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

- **Canonical URL:** https://frontend.rocks/autopsies/third-party-script-xss-takeover/
- **Case:** #11
- **Failure Mode:** Silent Data Corruption
- **Production Symptom:** Compromised third-party widget injects an inline script via an innerHTML sink and exfiltrates session tokens.
- **Last Verified:** 2026-11-16

## Causal Chain
1. [DOM XSS Prevention with Trusted Types](https://frontend.rocks/concepts/dom-xss-trusted-types.md): Enforces TrustedHTML objects on innerHTML sinks so raw attacker strings throw a TypeError.
2. [Content Security Policy Nonces and strict-dynamic](https://frontend.rocks/concepts/csp-nonces-strict-dynamic.md): Blocks injected inline scripts and restricts execution to nonce-authenticated bundles.
3. [Prototype Chain Lookup and Delegation](https://frontend.rocks/concepts/prototype-chain-lookup.md): Prevents prototype pollution gadgets on Object.prototype from forging sanitization bypass flags.
4. [Cross-Origin Isolation with COOP and COEP](https://frontend.rocks/concepts/cross-origin-isolation-coop-coep.md): Isolates browsing context groups and restricts cross-origin resource loading via CORP/COEP.
5. [Runtime Boundary Validation (Parse, Don't Validate)](https://frontend.rocks/concepts/runtime-boundary-validation.md): Validates third-party postMessage and JSON payloads with strict schemas before state or DOM updates.

## Primary Sources
- https://w3c.github.io/trusted-types/dist/spec/
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy

---
## Incident Report

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

## The Red Herring

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

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 Simulator

Toggle between the unguarded third-party widget sink and the Trusted Types + Nonce CSP + Schema Gate boundary in the comparator below.

## 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](/concepts/dom-xss-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](/concepts/csp-nonces-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](/concepts/prototype-chain-lookup). 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](/concepts/cross-origin-isolation-coop-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)](/concepts/runtime-boundary-validation) 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.
