| |

Web Security 16 🛡️ Advanced Browser Protections — Enforcing the Trusted Types API, Sanitizer API, and cross-origin isolation

⏱️ Estimated read: 25 min | |

Content Security Policy solved the problem of injected <script> tags and inline handlers. It did not solve the problem of the application itself taking a string from an untrusted source and handing it to innerHTML. That assignment is not a policy violation, it is a legitimate DOM operation, and the browser has no way to know that the string arrived from a query parameter three functions earlier. Trusted Types closes exactly that hole: it changes the type signature of the dangerous sinks so that a bare string is rejected and only a value minted by a registered policy is accepted.

The Sanitizer API is adjacent and complementary. Trusted Types forces every dangerous assignment to pass through a policy, but it does not define what the policy should do. The Sanitizer API defines that — a browser-native HTML sanitizer that strips scripts, event handlers, and dangerous URL schemes without shipping a third-party parser. Trusted Types is the gate; the Sanitizer is the gatekeeper. Used together, the policy body becomes a single call rather than a hand-written allowlist.

Cross-origin isolation addresses a different attack surface entirely: the speculative-execution side channels that made SharedArrayBuffer too dangerous to expose in 2018. Re-enabling it required the browser to know, with certainty, that a page and everything it embeds consent to being in the same process. That certainty comes from two response headers — Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy — plus a per-resource header, Cross-Origin-Resource-Policy, that every third party must opt into. When all three line up, self.crossOriginIsolated becomes true and the browser unlocks SharedArrayBuffer, Atomics, high-resolution timers, and performance.measureUserAgentSpecificMemory().

This chapter covers the three mechanisms in the order a team usually adopts them. First the Trusted Types policy model — the four types, the sinks, the CSP directive, and the default policy. Then the Sanitizer API — setHTML, setHTMLUnsafe, parseHTMLUnsafe, and the DOMPurify fallback that keeps non-Chromium browsers working. Then cross-origin isolation — the header triple, the credentialless variant, and what it unlocks. A final section covers the rollout strategy that keeps a production site online: report-only headers, violation reports, and the migration order.

Key point: Trusted Types changes the type of the DOM’s dangerous sinks so a bare string is rejected at runtime, the Sanitizer API gives the resulting policy a trustworthy body, and cross-origin isolation is a separate three-header handshake that no amount of sanitization can substitute for — each solves a different class of problem and none of them replaces the others.


Why it exists

The DOM XSS problem. Reflected and stored XSS through server-rendered HTML is well understood and largely mitigated by output encoding and CSP. The stubborn residual is DOM XSS: element.innerHTML = data where data came from location.hash, a postMessage, a JSON API, or a fetch response. The assignment is a normal DOM call, so CSP does not flag it, the bundler does not flag it, and code review misses it because the tainted flow crosses four files. Trusted Types exists because the only reliable place to enforce “this value was sanitized” is the sink itself, at the moment of assignment.

The sanitizer-dependency problem. Before the Sanitizer API, every application that needed to render user HTML shipped a parser — DOMPurify, sanitize-html, xss — and every one of those libraries is a moving target against a browser’s actual parsing behaviour. The mismatch between a JavaScript HTML parser and the browser’s real tokenizer is the source of a long line of mXSS bypasses. A browser-native sanitizer parses with the same parser the browser will use to render, which removes that entire class of bug by construction.

The side-channel problem. SharedArrayBuffer gives JavaScript a block of memory that two threads can read and write simultaneously, which is what makes Atomics.wait and high-performance worker code possible. It also gives an attacker a high-resolution timer, and a high-resolution timer is all a Spectre-style speculative execution attack needs to exfiltrate memory it should not be able to read. The 2018 response was to disable SharedArrayBuffer entirely. Cross-origin isolation is the negotiated re-enablement: if a page promises that every byte it embeds is same-origin or has explicitly opted in, the browser can isolate it in its own process and hand back the timer without exposing cross-origin memory.

The embedding problem. A page that is isolated has to know that its iframes, images, scripts, and fonts are not embedding it back. Cross-Origin-Embedder-Policy: require-corp converts that into a per-resource contract: a subresource loads only if it sends Cross-Origin-Resource-Policy or a valid CORS response. This breaks a lot of third-party integrations, which is precisely the point — an integration that cannot declare its embedding policy is one the browser cannot safely isolate against.

The precision problem. A single stray innerHTML assignment is enough to reintroduce DOM XSS into an application with a hundred thousand lines of code, and the person who wrote it has no idea they did. Enforcement has to be mechanical and default-deny, which is why Trusted Types is expressed as a CSP directive rather than a lint rule. The lint rule catches what the developer wrote; the directive catches what the framework, the dependency, and the marketing tag manager wrote.

The reporting problem. All three mechanisms break things. A Trusted Types rollout breaks every unmodified sink at once. A COEP rollout breaks every CDN image that did not send CORP. Both need a period where violations are collected but not blocked, and both integrate with the Reporting API so that the violations arrive in a store rather than a console. The report-only mode of each header exists for exactly this, and it is the difference between a rollout that takes a week and one that takes an afternoon of downtime.

The trade-off. Trusted Types is shipped in Chromium and not in Firefox or Safari, so enforcement silently does nothing on those browsers — the policy still needs to be written, but the guarantee is Chromium-only. The Sanitizer API’s configuration surface is still settling. Cross-origin isolation breaks OAuth popups under same-origin and breaks every third-party resource that has not adopted CORP. Each mechanism is a real hardening step and each one costs integration work that must be scheduled rather than assumed.


a. Trusted Types — policies, sinks, and the require-trusted-types-for directive

Trusted Types introduces four branded string types — TrustedHTML, TrustedScript, TrustedScriptURL, and TrustedURL — plus a factory, window.trustedTypes, that mints them. The brands cannot be forged: a string can be turned into a TrustedHTML only by calling createHTML on a policy object obtained from createPolicy. The browser refuses to accept a plain string wherever one of the branded types is expected.

// Without a policy, there is no way to reach innerHTML at all
el.innerHTML = "<b>hi</b>";
// TypeError: Failed to set the 'innerHTML' property on 'Element':
// This document requires 'TrustedHTML' assignment.

// The policy wraps the transformation and brands the output
const escapePolicy = trustedTypes.createPolicy("escape", {
  // createHTML receives the untrusted string and returns a safe string
  createHTML: (input) =>
    input.replace(/[&<>"']/g, (ch) => ({
      "&": "&",
      "<": "<",
      ">": ">",
      '"': """,
      "'": "'",
    })[ch]),
});

// The result carries the brand and the sink accepts it
el.innerHTML = escapePolicy.createHTML(userInput);

The set of sinks that require a branded type is larger than it looks. It covers every HTML assignment — innerHTML, outerHTML, insertAdjacentHTML, document.write, Range.createContextualFragment — every script load — script.src, script.text, script.textContent — every frame document — iframe.srcdoc — every string evaluation — eval(), new Function(), setTimeout() and setInterval() with a string argument — and every URL attribute set on a navigable or loadable element, which is why setAttribute("src", ...) and setAttribute("href", ...) on certain elements are also gated.

// A URL policy is the second half of the model: restrict the origin, not the characters
const urlPolicy = trustedTypes.createPolicy("assets", {
  createScriptURL: (input) => {
    const url = new URL(input, location.origin);
    // Only same-origin script URLs are permitted through the sink
    if (url.origin !== location.origin) {
      throw new TypeError(`Blocked cross-origin script: ${input}`);
    }
    return url.href;
  },
});

// Loader code becomes a three-line contract instead of a search-and-replace
const script = document.createElement("script");
script.src = urlPolicy.createScriptURL(cdnPath);
document.head.append(script);

The default policy is the escape hatch that makes adoption tractable. A policy literally named "default" is consulted automatically whenever a plain string is assigned to a sink, which means an existing application can be brought under enforcement without touching a single call site — the default policy runs the sanitizer, and every legacy innerHTML assignment starts flowing through it.

// The default policy intercepts every unbranded string headed for a sink
trustedTypes.createPolicy("default", {
  // Sanitize HTML rather than escaping it, so legacy markup keeps rendering
  createHTML: (input) => DOMPurify.sanitize(input, { RETURN_TRUSTED_TYPE: false }),

  // Anything that would create a script is refused outright
  createScript: () => {
    throw new TypeError("No dynamic script creation in this application");
  },

  // Script URLs are restricted to the document origin
  createScriptURL: (input) => {
    const url = new URL(input, location.origin);
    if (url.origin !== location.origin) throw new TypeError(`Blocked: ${input}`);
    return url.href;
  },
});

The default policy is a migration tool, not a destination. It centralises the sanitisation call and makes the entire application traffic through one audited function, which is a significant improvement over scattered innerHTML assignments — but it also means every sink accepts the output of the same sanitiser, so a policy that is too permissive is uniformly too permissive. The end state is named policies with narrow responsibilities and no default policy at all.

The browser exposes window.trustedTypes with a handful of helpers that make this testable and debuggable. trustedTypes.isHTML(value) returns true only for a branded value, getPolicyNames() lists the policies currently in effect, emptyHTML and emptyScript are pre-branded safe empties, and getAttributeType(tag, attr) reports which brand a given attribute requires.

// A guard that distinguishes "already safe" from "needs a policy"
function toTrustedHTML(value) {
  // A value that already carries the brand passes through unchanged
  if (trustedTypes.isHTML(value)) return value;
  // Everything else goes through the escape policy
  return escapePolicy.createHTML(String(value));
}

// Debugging: which sinks does this attribute participate in?
trustedTypes.getAttributeType("script", "src"); // "TrustedScriptURL"
trustedTypes.getAttributeType("div", "title");  // null

Enforcement is switched on by a Content Security Policy directive. require-trusted-types-for 'script' enables the sink checks, and trusted-types lists the policy names that are permitted to exist — anything not listed throws on createPolicy, so an injected attacker script cannot mint its own policy.

Content-Security-Policy:
  require-trusted-types-for 'script';
  trusted-types escape assets;
  report-to csp-endpoint

The trusted-types directive accepts policy names, the wildcard * (any name, useless as a control), the keyword 'none' (no policies at all, which is the strictest possible setting and only viable for an application with no HTML injection whatsoever), and the modifier 'allow-duplicates' (permits two policies with the same name, which is occasionally needed when two bundles both register a default). Angular, which ships first-class support, expects its own policy names in the same directive: trusted-types angular angular#bundler angular#unsafe-bypass; — the # suffix is Angular’s convention for separating the policy namespace from the sub-policy within it.


b. The Sanitizer API — setHTML, setHTMLUnsafe, and the fallback

The Sanitizer API gives the browser a native HTML sanitizer and exposes it through new parsing methods on Element and Document. The central method is Element.setHTML(), which parses the input in a context where scripts do not run, strips the elements and attributes that are unsafe, and inserts the result.

const comment = document.querySelector("#comment-body");

// setHTML sanitizes by default: no script, no on* handlers, no javascript: URLs
comment.setHTML(userSubmittedMarkup);

// The same call with an explicit configuration object
comment.setHTML(userSubmittedMarkup, {
  sanitizer: new Sanitizer({
    // Allow only the tags a comment may contain
    allowElements: ["b", "i", "em", "strong", "a", "p", "br"],
    // Allow the href attribute but nothing else on links
    allowAttributes: { a: ["href"] },
  }),
});

The configuration surface of the Sanitizer object has been revised several times during standardisation, so the safe engineering posture is to rely on the default behaviour — which is stable — and treat customisation as a progressive enhancement gated behind a feature check. The default is what most applications need: elements that can execute or navigate are removed, event handler attributes are removed, and the parser runs with a non-executing document so a <script> in the input never fires even while it is being classified.

Two companion methods exist for cases where sanitisation is the wrong tool. setHTMLUnsafe() parses and inserts without removing anything, and parseHTMLUnsafe() parses into a detached document without inserting at all. Neither executes script — the “unsafe” in the name refers to sanitisation, not to script execution.

// setHTMLUnsafe skips sanitisation but preserves declarative shadow DOM
// Useful when the markup is trusted (built by your own server) but must be parsed fast
templateContent.setHTMLUnsafe(serverRenderedCard);

// parseHTMLUnsafe builds a detached document; nothing is inserted, nothing executes
const fragment = document.parseHTMLUnsafe(userSubmittedMarkup);
// You can now inspect it with querySelector before deciding what to insert
const headings = fragment.querySelectorAll("h2");

The reason the Sanitizer API matters for Trusted Types is that it gives the policy a native body. Before it existed, policy implementations called DOMPurify, which parses the input with a JavaScript tokenizer and then re-serialises it into the DOM. Every sanitizer bypass of the last decade has been a mismatch between those two parsers. A policy that calls setHTML-equivalent native sanitisation has no such mismatch, because there is only one parser.

// A policy whose body is the browser's own sanitizer
const safePolicy = trustedTypes.createPolicy("safe-html", {
  createHTML: (input) => {
    // Feature-detect: native sanitiser when available
    if ("setHTML" in Element.prototype) {
      // setHTML is a sink, so parse into a scratch node with the *unsafe* raw path
      const scratch = document.createElement("div");
      scratch.setHTMLUnsafe(input);       // no execution, but no sanitisation
      // Trusted Types is not yet applying here; re-run through the native sanitiser
      const clean = document.createElement("div");
      clean.setHTML?.(input);
      return clean.innerHTML ?? "";
    }
    // Fall back to DOMPurify on engines without the Sanitizer API
    return DOMPurify.sanitize(input, { RETURN_TRUSTED_TYPE: false });
  },
});

In practice the cleaner form is a small abstraction that picks the implementation once, at load time, rather than branching on every call:

// Choose the sanitizer once, then expose a single function to the whole app
const supportsSanitizer = "setHTML" in Element.prototype;

export function sanitizeToHTML(dirty) {
  // Native path: parse into a scratch element and read the sanitised result back
  if (supportsSanitizer) {
    const holder = document.createElement("div");
    holder.setHTML(dirty);          // sanitises on the way in
    return holder.innerHTML;        // read back the sanitised markup as a string
  }
  // Fallback path: DOMPurify, which is what everyone used before 2022
  return DOMPurify.sanitize(dirty);
}

// The policy becomes a one-liner over the abstraction
trustedTypes.createPolicy("default", {
  createHTML: (input) => sanitizeToHTML(input),
});

DOMPurify remains the compatibility answer and will be for years. It is well maintained, it is the library that has survived the most adversarial scrutiny, and DOMPurify.sanitize(dirty, { RETURN_TRUSTED_TYPE: true }) returns a TrustedHTML directly, which means a DOMPurify-based policy does not need to be re-branded. The point of the native Sanitizer is not that DOMPurify is bad — it is that the browser’s own parser cannot diverge from itself.


c. Cross-origin isolation — COOP, COEP, CORP, and crossOriginIsolated

Cross-origin isolation is a promise made in headers and a boolean read in JavaScript. The promise is: this page and everything it embeds belong to the same origin, or have explicitly consented to being embedded. The boolean is self.crossOriginIsolated, and it flips to true when the promise holds.

if (self.crossOriginIsolated) {
  // SharedArrayBuffer exists only on an isolated page
  const buffer = new SharedArrayBuffer(1024);
  const view = new Int32Array(buffer);

  // Atomics are usable only against a SharedArrayBuffer
  Atomics.store(view, 0, 42);
  // performance.now() also gets 5µs resolution instead of 100µs
  const t0 = performance.now();
  doWork();
  console.log(performance.now() - t0);
} else {
  // Without isolation the constructor is not exposed at all
  console.warn("SharedArrayBuffer unavailable: page is not cross-origin isolated");
}

Two response headers carry the promise. Cross-Origin-Opener-Policy: same-origin severs the window.opener relationship between this page and any cross-origin window that opened it or that it opened, which removes the shared browsing-context group an attacker would otherwise use to probe. Cross-Origin-Embedder-Policy: require-corp blocks every subresource that has not itself declared an embedding policy.

// next.config.ts — both headers on every route
const nextConfig = {
  async headers() {
    return [
      {
        source: "/:path*",
        headers: [
          // Severs opener relationships with cross-origin windows
          { key: "Cross-Origin-Opener-Policy", value: "same-origin" },
          // Blocks subresources that lack CORP or CORS opt-in
          { key: "Cross-Origin-Embedder-Policy", value: "require-corp" },
          // Where COEP and COOP violations are reported
          { key: "Reporting-Endpoints", value: 'default="https://example.com/reports"' },
        ],
      },
    ];
  },
};

export default nextConfig;

The same pair in nginx, which is where a lot of teams discover that add_header is not inherited into location blocks that declare their own headers — a classic cause of “the headers work on / but not on /app“:

server {
  # `always` is required: these must be served on 4xx and 5xx too
  add_header Cross-Origin-Opener-Policy "same-origin" always;
  add_header Cross-Origin-Embedder-Policy "require-corp" always;

  location /app/ {
    # Declaring any add_header here drops the inherited ones above
    add_header Cache-Control "no-store" always;
    # Re-declare the isolation headers inside the block
    add_header Cross-Origin-Opener-Policy "same-origin" always;
    add_header Cross-Origin-Embedder-Policy "require-corp" always;
  }
}

require-corp is the strict setting and the one that historically broke the web. A third-party image without Cross-Origin-Resource-Policy: cross-origin is blocked. A third-party font without a permissive CORS response is blocked. An embedded YouTube iframe is blocked unless it sends Cross-Origin-Embedder-Policy itself. Cross-Origin-Embedder-Policy: credentialless is the softer variant: it still isolates the page, but no-cors subresources are fetched without credentials rather than being blocked outright, which lets a great many media and CDN resources keep working.

# On your own assets that legitimate third parties embed
Cross-Origin-Resource-Policy: cross-origin

# On assets only your own origin may embed
Cross-Origin-Resource-Policy: same-origin

The three Cross-Origin-Resource-Policy values form a small lattice. same-origin allows embedding only from the same origin, same-site extends that to sibling subdomains, and cross-origin allows anyone. The header is served by the resource being embedded, not by the page embedding it — which is why a CDN you do not control is a CDN you cannot fix, and why the practical migration path runs through credentialless first.

<!-- A cross-origin image under require-corp needs either CORP or CORS + crossorigin -->
<img src="https://cdn.partner.example/hero.jpg"
     crossorigin="anonymous"
     alt="Hero" />
<!-- The CDN must return Access-Control-Allow-Origin for this to load -->

Cross-origin isolation is also the precondition for performance.measureUserAgentSpecificMemory(), the only way to measure a page’s true memory footprint including its workers and iframes, and for performance.now() at full resolution. Both matter for exactly the workloads that need SharedArrayBuffer: video editors, CAD viewers, WASM physics engines, in-browser compilers, and anything running a compute kernel across Workers.

One behaviour change catches people out on day one: same-origin COOP means an OAuth popup opened by the page cannot talk back through window.opener. The sign-in flow that polled popup.closed and then read a token from the opener chain stops working. The fix is Cross-Origin-Opener-Policy: same-origin-allow-popups, which retains isolation for the page while keeping the opener relationship alive for windows it opened — and accepting a slightly weaker guarantee as the price.


d. Rolling out — report-only, violation reports, and the migration order

All three mechanisms ship with a report-only mode, and the report-only mode is the only responsible way to deploy any of them on a site with existing traffic. Content-Security-Policy-Report-Only, Cross-Origin-Embedder-Policy-Report-Only, and Cross-Origin-Opener-Policy-Report-Only evaluate the policy, block nothing, and emit a report for every violation.

# Step one: detect every sink, allow no policies, block nothing
Content-Security-Policy-Report-Only:
  require-trusted-types-for 'script';
  trusted-types 'none';
  report-to csp-endpoint

# The Reporting API endpoints declared once, referenced by the directive above
Reporting-Endpoints: csp-endpoint="https://example.com/reports/csp"

# Step one for isolation: see what CORP would have blocked
Cross-Origin-Embedder-Policy-Report-Only: require-corp
Cross-Origin-Opener-Policy-Report-Only: same-origin

The reports arrive as csp-violation bodies whose effectiveDirective is require-trusted-types-for, with the offending sink named in the sample field — which is precisely the list of call sites that need a policy. Cross-origin reports arrive as coep and coop types with the blocked resource URL, which is precisely the list of third parties that need CORP or a CORS header.

// Server handler that collects reports from the Reporting API
export async function POST(request) {
  // The browser posts an array of reports, not a single object
  const reports = await request.json();

  for (const report of reports) {
    if (report.type === "csp-violation") {
      // `effectiveDirective` names the directive that was violated
      const directive = report.body.effectiveDirective;
      // `sample` names the sink or blocking resource
      const sample = report.body.sample;
      console.warn(JSON.stringify({ kind: "csp", directive, sample }));
    }
    if (report.type === "coep" || report.type === "coop") {
      // The blocked resource URL is what needs a CORP header
      console.warn(JSON.stringify({ kind: report.type, url: report.body.blockedURL }));
    }
  }
  // 204 is the response the Reporting API expects
  return new Response(null, { status: 204 });
}

The migration order matters because the mechanisms have different blast radii. Isolation headers break third-party resources, which are outside the team’s control and take time to fix; Trusted Types breaks in-repo call sites, which are inside the team’s control and can be fixed in a sprint. Deploy them in the opposite order to their blast radius.

# Final production headers, once the report-only window is clean
Content-Security-Policy:
  require-trusted-types-for 'script';
  trusted-types default assets;

Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: credentialless
Cross-Origin-Resource-Policy: same-origin

Note the credentialless in the final state rather than require-corp. It is a legitimate end state, not a compromise: it delivers genuine cross-origin isolation for most pages, keeps third-party media working, and is supported in Chromium. Teams that need the strongest guarantee — and can prove every subresource sends CORP or CORS — move to require-corp afterward, as a separate, smaller, and better-understood change.


Complete Example Session

// ============================================
// PART 1: THE ESCAPE POLICY
// ============================================
// Registered under a name that the CSP directive must allow
const escapePolicy = trustedTypes.createPolicy("escape", {
  // Escape rather than sanitize: correct for text that must render literally
  createHTML: (input) =>
    String(input).replace(/[&<>"']/g, (ch) => ({
      "&": "&", "<": "<", ">": ">", '"': """, "'": "'",
    })[ch]),
});

// ============================================
// PART 2: THE URL POLICY
// ============================================
const assetPolicy = trustedTypes.createPolicy("assets", {
  createScriptURL: (input) => {
    const url = new URL(input, location.origin);
    // Same-origin only; anything else throws before reaching the sink
    if (url.origin !== location.origin) throw new TypeError(`Blocked ${input}`);
    return url.href;
  },
});

// ============================================
// PART 3: THE DEFAULT POLICY
// ============================================
// Intercepts legacy sinks without touching their call sites
trustedTypes.createPolicy("default", {
  createHTML: (input) => sanitizeToHTML(input),
  createScript: () => { throw new TypeError("dynamic script blocked"); },
});

// ============================================
// PART 4: THE SANITIZER ABSTRACTION
// ============================================
const nativeSanitizer = "setHTML" in Element.prototype;

function sanitizeToHTML(dirty) {
  if (nativeSanitizer) {
    // Parse through the sanitizing entry point, then read the result back
    const holder = document.createElement("div");
    holder.setHTML(dirty);
    return holder.innerHTML;
  }
  // Fallback for engines without the Sanitizer API
  return DOMPurify.sanitize(dirty);
}

// ============================================
// PART 5: THE TYPE GUARD
// ============================================
function safeHTML(value) {
  // Already branded: pass through, do not re-sanitize
  if (trustedTypes.isHTML(value)) return value;
  // Otherwise route through the escape policy
  return escapePolicy.createHTML(String(value));
}

// ============================================
// PART 6: THE REPORT-ONLY HEADER
// ============================================
// Content-Security-Policy-Report-Only:
//   require-trusted-types-for 'script';
//   trusted-types 'none';
//   report-to csp-endpoint
// Reporting-Endpoints: csp-endpoint="https://example.com/reports"

// ============================================
// PART 7: THE REPORT COLLECTOR
// ============================================
export async function POST(request) {
  const reports = await request.json();
  for (const r of reports) {
    // Log the sink name so the fix list is concrete
    console.warn(r.type, r.body.effectiveDirective, r.body.sample);
  }
  return new Response(null, { status: 204 });
}

// ============================================
// PART 8: THE ISOLATION HEADERS
// ============================================
const isolationHeaders = [
  { key: "Cross-Origin-Opener-Policy", value: "same-origin" },
  { key: "Cross-Origin-Embedder-Policy", value: "credentialless" },
  { key: "Cross-Origin-Resource-Policy", value: "same-origin" },
];

// ============================================
// PART 9: THE ISOLATED WORKER
// ============================================
if (self.crossOriginIsolated) {
  // Shared memory between the main thread and a worker
  const shared = new SharedArrayBuffer(4 * 1024);
  const flag = new Int32Array(shared, 0, 1);
  const worker = new Worker("/worker.js");
  // The worker receives the same buffer, not a structured clone of it
  worker.postMessage({ shared });
  // Block until the worker stores a non-zero value
  Atomics.wait(flag, 0, 0, 5000);
}

// ============================================
// PART 10: THE ENFORCED HEADERS
// ============================================
// Content-Security-Policy:
//   require-trusted-types-for 'script';
//   trusted-types escape assets default;
// Cross-Origin-Opener-Policy: same-origin
// Cross-Origin-Embedder-Policy: credentialless

The ten parts built a policy per danger class, a default policy for legacy sinks, a sanitizer abstraction with a native path and a fallback, a type guard, the report-only header and its collector, the isolation header triple, a worker that only runs when isolation holds, and the final enforced header set.


Quick Reference

Trusted Types Brands

TypeProduced ByRequired By
TrustedHTMLcreateHTMLinnerHTML, outerHTML, srcdoc
TrustedScriptcreateScripteval, Function, setTimeout(string)
TrustedScriptURLcreateScriptURLscript.src
TrustedURLcreateURLNavigation sinks

CSP Directives

DirectiveValuesEffect
require-trusted-types-for'script'Enables sink checks
trusted-typesnames, *, 'none'Policy names allowed to exist
trusted-types + 'allow-duplicates'modifierPermits duplicate policy names
report-toendpoint nameSends violations via Reporting API
report-uriURLLegacy report target

Sanitizer Methods

MethodSanitizesExecutes
el.setHTML()YesNo
el.setHTMLUnsafe()NoNo
document.parseHTMLUnsafe()NoNo

Isolation Headers

HeaderValuesServed By
Cross-Origin-Opener-Policysame-origin, same-origin-allow-popups, unsafe-noneThe page
Cross-Origin-Embedder-Policyrequire-corp, credentialless, unsafe-noneThe page
Cross-Origin-Resource-Policysame-origin, same-site, cross-originThe resource

What Isolation Unlocks

CapabilityRequires
SharedArrayBuffercrossOriginIsolated === true
Atomics on shared memorycrossOriginIsolated === true
performance.measureUserAgentSpecificMemory()crossOriginIsolated === true
5µs performance.now() resolutioncrossOriginIsolated === true

Best Practices

✅ Do This:

// Escape for text, sanitize for markup
createHTML: (s) => escapeText(s)                                   // ✅

// Restrict script URLs by origin
if (url.origin === location.origin) return url.href                // ✅

// Feature-detect the Sanitizer API once
const native = "setHTML" in Element.prototype;                     // ✅

// Start every header in report-only
Cross-Origin-Embedder-Policy-Report-Only: require-corp             // ✅

// Use credentialless when third parties are unavoidable
Cross-Origin-Embedder-Policy: credentialless                       // ✅

// Read crossOriginIsolated before using SharedArrayBuffer
if (self.crossOriginIsolated) { /* ... */ }                        // ✅

// Keep the default policy narrow and temporary
trustedTypes.createPolicy("default", { createHTML })               // ✅

❌ Don’t Do This:

// A policy that hands back the input unchanged
createHTML: (s) => s                                                // ❌

// Allowing any policy name
trusted-types *                                                     // ❌

// Using setHTMLUnsafe on untrusted input
el.setHTMLUnsafe(userMarkup)                                        // ❌

// Enforcing COEP before checking subresources
Cross-Origin-Embedder-Policy: require-corp  (day one)               // ❌

// Assuming Firefox and Safari enforce Trusted Types
trustedTypes.createPolicy("p", {}) // not enforced there            // ❌

// Constructing SharedArrayBuffer without a guard
new SharedArrayBuffer(1024) // ReferenceError when not isolated     // ❌

// Blocking the OAuth popup flow with plain same-origin
Cross-Origin-Opener-Policy: same-origin  (with a sign-in popup)     // ❌

Common Pitfalls

PitfallWhy It HappensFix
Every sink throws at onceEnforced without a default policyAdd default, then remove it
Violations not reportedReporting-Endpoints missingDeclare the endpoint header
Images disappear under COEPCDN sends no CORPAdd CORP or use credentialless
Sign-in popup breaksCOOP severs window.openersame-origin-allow-popups
SharedArrayBuffer undefinedPage not isolatedBoth COOP and COEP required
Policy creation throwsName absent from trusted-typesAdd the name to the directive
Sanitizer strips too muchCustom config too narrowUse the default configuration
No protection outside ChromiumTrusted Types unimplementedKeep server-side encoding

Real-World Examples

1. Escape policy

const p = trustedTypes.createPolicy("esc", {
  createHTML: (s) => s.replace(/</g, "<").replace(/>/g, ">"),
});

2. URL origin restriction

const u = trustedTypes.createPolicy("u", {
  createScriptURL: (s) => new URL(s, location.origin).href,
});

3. Type guard

if (trustedTypes.isHTML(v)) return v;
return escapePolicy.createHTML(String(v));

4. Attribute sink query

trustedTypes.getAttributeType("script", "src"); // "TrustedScriptURL"

5. Native parse

const holder = document.createElement("div");
holder.setHTML(dirty);
return holder.innerHTML;

6. Detached parse

const doc = document.parseHTMLUnsafe(markup);
doc.querySelectorAll("h2").length;

7. DOMPurify with Trusted Types

DOMPurify.sanitize(dirty, { RETURN_TRUSTED_TYPE: true });

8. Isolation check

if (!self.crossOriginIsolated) return fallbackSingleThreaded();

9. CORP on a CDN asset

Cross-Origin-Resource-Policy: cross-origin

10. Report-only rollout

Content-Security-Policy-Report-Only:
  require-trusted-types-for 'script'; trusted-types 'none'

Visual

The Trusted Types Gate

┌────────────────────────────────────────────────────┐
│  TRUSTED TYPES: WHAT THE SINK ACCEPTS              │
│                                                    │
│  string  ──────────────►  innerHTML                │
│                             │                      │
│                             ▼                      │
│                          TypeError  (blocked)      │
│                                                    │
│  TrustedHTML  ─────────►  innerHTML  ──►  render   │
│                                                    │
│  TrustedHTML is produced only by a policy:         │
│    trustedTypes.createPolicy("p", { createHTML })  │
└────────────────────────────────────────────────────┘

Sanitizer Parse Paths

┌────────────────────────────────────────────────────┐
│  PARSE PATHS AND WHAT THEY PRESERVE                │
│                                                    │
│  setHTML(html)                                     │
│    ── sanitize ── parse ── insert                  │
│    drops script, on* handlers, javascript: URLs    │
│                                                    │
│  setHTMLUnsafe(html)                               │
│    ── parse ── insert, no sanitization             │
│    keeps shadow DOM, never executes script         │
│                                                    │
│  parseHTMLUnsafe(html)                             │
│    ── parse only, detached document                │
└────────────────────────────────────────────────────┘

The Isolation Header Triple

┌────────────────────────────────────────────────────┐
│  ISOLATION REQUIRES THREE HEADERS                  │
│                                                    │
│  Cross-Origin-Opener-Policy:   same-origin         │
│    severs window.opener across origins             │
│                                                    │
│  Cross-Origin-Embedder-Policy: require-corp        │
│    every subresource needs CORP or CORS            │
│                                                    │
│  Cross-Origin-Resource-Policy: same-origin         │
│    on your own assets fetched elsewhere            │
│                                                    │
│  result: self.crossOriginIsolated === true         │
└────────────────────────────────────────────────────┘

The Rollout Sequence

┌────────────────────────────────────────────────────┐
│  ROLLOUT SEQUENCE                                  │
│                                                    │
│  [1] COOP report-only                              │
│        │                                           │
│        ▼                                           │
│  [2] COEP report-only + CORP on assets             │
│        │                                           │
│        ▼                                           │
│  [3] Trusted Types report-only                     │
│        │                                           │
│        ▼                                           │
│  [4] enforce everything                            │
└────────────────────────────────────────────────────┘

Summary

ItemValue
Factory objectwindow.trustedTypes
BrandsTrustedHTML, TrustedScript, TrustedScriptURL, TrustedURL
Sink-enabling directiverequire-trusted-types-for 'script'
Policy allowlist directivetrusted-types <names>
Interception policycreatePolicy("default", …)
Native sanitized parseElement.setHTML()
Native raw parseElement.setHTMLUnsafe(), document.parseHTMLUnsafe()
Isolation booleanself.crossOriginIsolated
Isolation headersCOOP + COEP
Resource opt-in headerCross-Origin-Resource-Policy
Reporting headerReporting-Endpoints

Key takeaways:

  • Trusted Types changes the type of the sink, not the type of the variable. A TrustedHTML can only be minted by a policy, so the guarantee is enforced at the moment of assignment rather than at the moment of construction, and no amount of upstream validation substitutes for it.
  • The default policy is a migration tool. It intercepts every legacy sink to a bare string, which makes an existing application enforceable without touching call sites — but a default policy that is uniformly permissive is uniformly permissive, so the end state is named policies with narrow responsibilities.
  • The Sanitizer API gives the policy a native body. setHTML parses with the same parser the browser will later use, which eliminates the parser-mismatch class of sanitizer bypass that third-party libraries have spent a decade patching.
  • Trusted Types is Chromium-only. Firefox and Safari do not enforce the sinks, so the policy is necessary but not sufficient; server-side output encoding remains the guarantee that covers every engine.
  • Cross-origin isolation is a three-header handshake. COOP severs the opener group, COEP blocks unconsented subresources, and CORP is the opt-in the subresource serves. credentialless is a legitimate end state that keeps third-party media working while still delivering isolation.
  • Everything ships report-only first. COEP breaks CDN images, COOP breaks OAuth popups, and Trusted Types breaks every unmodified sink simultaneously; the report stream turns each of those into a concrete fix list before anything is blocked.

Remember: These three mechanisms defend against three different things, and conflating them is the most common mistake. Trusted Types defends the assignment — it makes the dangerous DOM sinks refuse unvetted strings. The Sanitizer API defends the parsing — it makes the vetted string safe using the browser’s own tokenizer rather than a reimplementation of it. Cross-origin isolation defends the process — it makes the browser willing to give you shared memory and precise timers again, at the cost of declaring every embedding relationship your page participates in. Deploy each one in report-only first, read the reports, fix the list, and only then enforce. The window between report-only and enforcement is where the entire value of the rollout lives.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!