Autopsy #11: Anatomy of a Supply-Chain DOM XSS & How Trusted Types Stop It
Compromised third-party widget injects an inline script via an innerHTML sink and exfiltrates session tokens.
The Incident & The False Culprit
A marketing PR added a one-line <script> embed for a third-party support chat widget to the authenticated dashboard layout. Local smoke tests showed the chat bubble rendering cleanly with zero console errors.
- T+00:00Deployed the widget embed to production. An upstream CDN compromise injected a payload into the widget's `postMessage` stream.
- T+06:00The widget assigned an attacker-controlled string directly to `widgetRoot.innerHTML`, executing `<img src=x onerror=fetch(...)>` inside the host origin.
- T+14:00WAF anomaly alerts flagged `POST /collect` beacons exfiltrating session tokens and CSRF nonces from 3.8% of active customer sessions.
- T+22:00Audit logs confirmed zero server-side breach; all exfiltration originated from authenticated browsers executing injected DOM handlers.
The Red Herring — Why the First Reflex Failed
In #sec-incident, the team shipped an emergency regex stripper (html.replace(/<script/gi, '')) while keeping script-src 'self' 'unsafe-inline' in CSP. It blocked <script>alert(1)</script> in staging.
In production, the exfiltration continued unabated:
- Event-handler attributes bypassed
<script>regexes:<img onerror=...>and<svg onload=...>executed without a<script>tag. 'unsafe-inline'permitted injected handlers: CSP allowed inline event attributes to run inside the host document.- Unvalidated JSON polluted
Object.prototype: A__proto__payload flippedconfig.allowRawHtmltotrueacross every widget instance.
Causal Chain Traversed
Step-by-step propagation across atomic concepts. Hover or click any step to inspect the underlying mechanism.
- 01Security & AccessibilityDOM XSS Prevention with Trusted Types
Enforces TrustedHTML objects on innerHTML sinks so raw attacker strings throw a TypeError.
- 02Security & AccessibilityContent Security Policy Nonces and strict-dynamic
Blocks injected inline scripts and restricts execution to nonce-authenticated bundles.
- 03JS RuntimePrototype Chain Lookup and Delegation
Prevents prototype pollution gadgets on Object.prototype from forging sanitization bypass flags.
- 04Security & AccessibilityCross-Origin Isolation with COOP and COEP
Isolates browsing context groups and restricts cross-origin resource loading via CORP/COEP.
- 05State & ArchitectureRuntime Boundary Validation (Parse, Don't Validate)
Validates third-party postMessage and JSON payloads with strict schemas before state or DOM updates.
Five browser security boundaries fail together during a supply-chain DOM XSS takeover:
- Unchecked
innerHTMLsink: Blink's HTML parser turns raw strings into executable DOM nodes. - Permissive CSP (
'unsafe-inline'): Inline event attributes execute unhindered inside the host origin. - Prototype chain gadget:
__proto__keys inJSON.parseforge truthy flags onObject.prototype. - Shared context & unparsed
postMessage: Missing COOP/COEP and unvalidatedev.datafeed untrusted inputs directly into DOM sinks.
Failure Reproduction Lab
Toggle between the unguarded third-party widget sink and the Trusted Types + Nonce CSP + Schema Gate boundary in the comparator below.
Supply-Chain Widget: Raw innerHTML Sink vs Trusted Types + CSP Nonce
Compare an unguarded third-party widget writing raw HTML and reading unvalidated postMessage payloads against a TrustedHTML-enforced boundary.
// CSP: script-src 'self' 'unsafe-inline' https://cdn.widget.example
window.addEventListener('message', (ev) => {
const { html, config } = JSON.parse(ev.data);
if (config?.isAdmin) enableDebugTokens();
widgetRoot.innerHTML = html; // Executes <img src=x onerror=fetch(...)>
});A compromised CDN script injects an inline event handler into innerHTML and pollutes Object.prototype.isAdmin to exfiltrate session tokens.
// CSP: require-trusted-types-for 'script'; script-src 'nonce-9f3a' 'strict-dynamic'
const policy = trustedTypes.createPolicy('widget-sanitize', {
createHTML: (dirty) => DOMPurify.sanitize(dirty, { RETURN_TRUSTED_TYPE: false }),
});
window.addEventListener('message', (ev) => {
if (ev.origin !== 'https://app.widget.example') return;
const parsed = WidgetPayloadSchema.parse(JSON.parse(ev.data));
if (Object.hasOwn(parsed, 'html')) widgetRoot.innerHTML = policy.createHTML(parsed.html);
});Raw string assignments to innerHTML throw TypeError, inline scripts fail nonce verification, and Object.hasOwn blocks prototype gadgets.
Layer-by-Layer Dissection
Sink Type-Locking Eliminates Raw Strings Before Script Execution
Assigning raw strings to innerHTML is blocked at the DOM boundary by DOM XSS Prevention with Trusted Types. Enforcing Content-Security-Policy: require-trusted-types-for 'script' changes DOM sink behavior:
- Raw string assignment: Blink throws a
TypeErrorbefore parsing any HTML nodes. TrustedHTMLassignment: Only values returned by a registeredTrustedTypePolicyenter the DOM parser.
Even if a legacy iframe or dependency exposes an unguarded sink, Content Security Policy Nonces and strict-dynamic removes 'unsafe-inline' and restricts script execution to elements carrying a per-response cryptographic nonce.
CSP Enforcement Exposes Prototype Chain Gadgets
CSP nonces block unauthorized <script> elements, yet authorized scripts still read properties through JavaScript Prototype Chain Lookup and Delegation. When a widget merges untrusted JSON into a configuration object, __proto__ keys mutate Object.prototype and make config.allowRawHtml evaluate to true via prototype delegation.
Reading feature flags with Object.hasOwn(config, 'allowRawHtml') or storing lookups in Object.create(null) dictionaries blocks prototype-chain bypasses.
Prototype Hardening Requires Cross-Origin Context Isolation
Hardening JS objects still leaves cross-origin resource and window-opener vectors open when third-party widgets spawn popups or load external frames. Enforcing Cross-Origin Isolation with COOP and COEP (same-origin plus require-corp) isolates the browsing context:
- COOP
same-origin: Severswindow.openerreferences from cross-origin popups. - COEP
require-corp: Blocks subresources lacking explicitCross-Origin-Resource-Policyheaders.
Context Isolation Connects to Runtime Boundary Parsing
Before any postMessage payload reaches a Trusted Types policy or state store, Runtime Boundary Validation (Parse, Don't Validate) checks ev.origin and parses ev.data through a strict Zod schema. Unexpected shapes are rejected at the boundary before touching the DOM.
Architectural Fix & Invariants
// Enforce: CSP "require-trusted-types-for 'script'; script-src 'nonce-...' 'strict-dynamic'"
const htmlPolicy = trustedTypes.createPolicy('widget-html', {
createHTML: (dirty: string) => DOMPurify.sanitize(dirty, { RETURN_TRUSTED_TYPE: false }),
});
window.addEventListener('message', (ev: MessageEvent) => {
if (ev.origin !== 'https://widget.trusted-partner.example') return;
const parsed = WidgetEventSchema.safeParse(JSON.parse(String(ev.data)));
if (!parsed.success) return;
const container = document.getElementById('widget-root');
if (container && Object.hasOwn(parsed.data, 'html')) {
container.innerHTML = htmlPolicy.createHTML(parsed.data.html);
}
});Architectural Invariants
- Zero raw string DOM sinks:
require-trusted-types-for 'script'is enforced in HTTP headers; everyinnerHTMLwrite requires a namedTrustedTypePolicy. - Nonce-only script execution: CSP omits
'unsafe-inline'and'unsafe-eval', authorizing scripts exclusively via per-request cryptographic nonces. - Own-property flag checks: Untrusted JSON never merges into
Object.prototype; feature flags are read withObject.hasOwn. - Strict origin and schema gate: Every
postMessagelistener verifiesev.originand parsesev.datawith a strict schema before DOM mutation.
Golden Rule: Regex sanitizers cannot outsmart an HTML parser; lock DOM sinks with Trusted Types, drop 'unsafe-inline', and parse every cross-origin message at the boundary.
Primary Sources
Last verified: 2026-11-16