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
📌 Key Takeaways
- Enforce Trusted Types using
Content-Security-Policy: require-trusted-types-for 'script'. - When active, any attempt to assign a raw string to
innerHTMLordocument.writethrows aTypeErrorin the browser. - --
❓ Knowledge Check
1. Which of the following is correct?
2. Which of the following is correct?