Architecture Autopsies
Case #11Silent Data Corruption7 min read

Autopsy #11: Anatomy of a Supply-Chain DOM XSS & How Trusted Types Stop It

Production Symptom

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.

  1. T+00:00Deployed the widget embed to production. An upstream CDN compromise injected a payload into the widget's `postMessage` stream.
  2. T+06:00The widget assigned an attacker-controlled string directly to `widgetRoot.innerHTML`, executing `<img src=x onerror=fetch(...)>` inside the host origin.
  3. T+14:00WAF anomaly alerts flagged `POST /collect` beacons exfiltrating session tokens and CSRF nonces from 3.8% of active customer sessions.
  4. T+22:00Audit logs confirmed zero server-side breach; all exfiltration originated from authenticated browsers executing injected DOM handlers.
REJECTED PATCH

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 flipped config.allowRawHtml to true across every widget instance.

Causal Chain Traversed

Step-by-step propagation across atomic concepts. Hover or click any step to inspect the underlying mechanism.

  1. 01Security & Accessibility
    DOM XSS Prevention with Trusted Types

    Enforces TrustedHTML objects on innerHTML sinks so raw attacker strings throw a TypeError.

  2. 02Security & Accessibility
    Content Security Policy Nonces and strict-dynamic

    Blocks injected inline scripts and restricts execution to nonce-authenticated bundles.

  3. 03JS Runtime
    Prototype Chain Lookup and Delegation

    Prevents prototype pollution gadgets on Object.prototype from forging sanitization bypass flags.

  4. 04Security & Accessibility
    Cross-Origin Isolation with COOP and COEP

    Isolates browsing context groups and restricts cross-origin resource loading via CORP/COEP.

  5. 05State & Architecture
    Runtime 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 innerHTML sink: 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 in JSON.parse forge truthy flags on Object.prototype.
  • Shared context & unparsed postMessage: Missing COOP/COEP and unvalidated ev.data feed 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.

Interactive Simulator

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.

Lines of Code
Before
6
After
9
Reflows / Browser Cost
Before
DOM XSS + Prototype Gadget
After
TypeError on Raw Strings
BeforeUnguarded Widget Sink + Unsafe CSP
// 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(...)>
});
Lines: 6Reflows: DOM XSS + Prototype GadgetDependencies: 0 kB

A compromised CDN script injects an inline event handler into innerHTML and pollutes Object.prototype.isAdmin to exfiltrate session tokens.

After (Native)Trusted Types + Nonce CSP + Schema Gate
// 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);
});
Lines: 9Reflows: TypeError on Raw StringsDependencies: DOMPurify + Zod

Raw string assignments to innerHTML throw TypeError, inline scripts fail nonce verification, and Object.hasOwn blocks prototype gadgets.

Layer-by-Layer Dissection

01 → 02

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 TypeError before parsing any HTML nodes.
  • TrustedHTML assignment: Only values returned by a registered TrustedTypePolicy enter 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.

02 → 03

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.

03 → 04

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: Severs window.opener references from cross-origin popups.
  • COEP require-corp: Blocks subresources lacking explicit Cross-Origin-Resource-Policy headers.
04 → 05

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

TS
// 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; every innerHTML write requires a named TrustedTypePolicy.
  • 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 with Object.hasOwn.
  • Strict origin and schema gate: Every postMessage listener verifies ev.origin and parses ev.data with 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