Trusted Types

A CSP-enforced browser API making a raw-string assignment to a DOM-XSS-sensitive sink a structural TypeError, unless it passes through a reviewed policy.

                trustedTypes.createPolicy(name, { createHTML: fn })
              

Purpose

Trusted Types, enabled via a Content-Security-Policy directive, makes assigning a raw string to a DOM-XSS-sensitive sink (innerHTML, document.write, and others) a structural TypeError — unless the value was produced through an explicitly defined, reviewed policy.

Syntax

// With Trusted Types enforced via CSP:
element.innerHTML = userInput; // TypeError — raw string rejected outright

const policy = trustedTypes.createPolicy('sanitizer', {
  createHTML: (input) => sanitizeHtml(input),
});
element.innerHTML = policy.createHTML(userInput); // works — went through the policy

Behavior notes

  • This shifts DOM XSS defense from “every developer must remember to sanitize every time” to a platform-enforced boundary — an unsafe assignment fails structurally, regardless of whether the specific string happened to be dangerous.
  • A policy’s createHTML/createScript/createScriptURL functions are the single reviewed places where raw strings become “trusted” — concentrating the actual sanitization logic that matters into a small, auditable surface.
  • Requires require-trusted-types-for 'script' in the page’s CSP to actually enforce; without it, the API is available but not mandatory.

Common mistakes

  • Creating an overly permissive default policy (one that trusts everything) purely to stop the TypeErrors, defeating the entire point of the enforcement.
  • Assuming Trusted Types alone is sufficient XSS defense — it enforces sink safety, but output still needs correct escaping/sanitization logic inside the policy itself.

Runtime notes

Supported in Chromium-based browsers; not yet universal across all browser engines — check current support before depending on it as a sole defense.

Taught in these lessons

Related reference