Chapter 68: Preventing XSS & Clickjacking

W3C Trusted Types API for DOM XSS Prevention

**Part 14: Security & Best Practices** — Chapter 68: Preventing XSS & Clickjacking in HTML

LEARNING OBJECTIVES
  • Understand how the W3C Trusted Types API locks down dangerous DOM injection sinks (element.innerHTML, location.href, script.src).
  • Enforce Trusted Types via the CSP header: Content-Security-Policy: require-trusted-types-for 'script'.
  • Create type-safe sanitization policies with trustedTypes.createPolicy().
  • Eliminate DOM XSS vulnerabilities at the browser engine compiler level.
🎬 INTERACTIVE VISUAL PIPELINE Core Architecture Simulation
🌐
1. Input
Directives & Tags
⚙️
2. Parse
Tokenizer & AST
🌳
3. Layout
Box Model & Flow
🎨
4. Render
GPU Paint & Composite
PHASE 1: INPUT & DIRECTIVES
Browser receives declarative markup stream, parsing tag tokens and initializing component state.

📖 The Mental Model & Story

In standard JavaScript, passing a string to element.innerHTML = userInput is like handing cash directly to an unvetted third-party without a receipt. If the string contains <img src=x onerror=stealCookies()>, the browser executes it immediately.

Trusted Types locks the bank vault. The browser refuses to accept raw strings into dangerous sinks. Instead, you must run data through an audited, certified TrustedHTML Policy that stamps the payload with a cryptographic type wrapper.

Raw Untrusted String ===> trustedTypes.createPolicy('my-policy', { createHTML: sanitize }) ===> TrustedHTML Object ===> element.innerHTML ✅ (Allowed!)
Raw Untrusted String =========================================================================================> element.innerHTML ❌ (BLOCKED by Browser!)

💻 Interactive Code Playground


SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
HTML STARSHIP CODE TERMINAL playground.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45°C
INSPECTING DOM: VALID
TAGS: SCANNING...

📌 Key Takeaways

  • Enforce Trusted Types using Content-Security-Policy: require-trusted-types-for 'script'.
  • When active, any attempt to assign a raw string to innerHTML or document.write throws a TypeError in the browser.
  • --

❓ Knowledge Check

1. Which of the following is correct?

2. Which of the following is correct?