Trusted Types Policy Stub
Scaffold a Trusted Types policy and the CSP directive that enforces it.
Overview
The Trusted Types Policy Stub generates a starter Trusted Types policy and the matching Content-Security-Policy: require-trusted-types-for 'script'; trusted-types <policy-name>; directive. Output includes a JavaScript policy creation snippet plus the CSP header that activates enforcement.
Useful for security engineers and developers learning how to enforce Trusted Types for DOM-based XSS protection or how to create a default Trusted Types policy. Reach for it locking down a high-value app against DOM XSS, or migrating a codebase to inject-safe APIs.
How it works
Trusted Types is a browser security feature that requires innerHTML, script.src, and other DOM sinks to receive a "typed" object rather than a raw string. The application creates one or more policies (via trustedTypes.createPolicy) that vet input and return typed objects. The CSP directive require-trusted-types-for 'script' causes the browser to throw when an untyped string reaches a DOM sink.
The trusted-types CSP directive lists which policy names are allowed; the special name 'default' enables a fallback used when no policy is specified. The stub generates a starter policy (escaping HTML, validating URLs) plus the activating CSP fragment.
Examples
- A default policy that sanitises input →
trustedTypes.createPolicy('default', { createHTML: s => DOMPurify.sanitize(s) }). - Activating CSP fragment →
require-trusted-types-for 'script'; trusted-types 'default';. - Report-only mode for safe rollout →
Content-Security-Policy-Report-Onlywith the directives. - A named policy for a templating engine →
trustedTypes.createPolicy('templating', { createHTML: render }).
FAQ
Browser support?
Chromium-based browsers. Firefox does not implement Trusted Types as of 2025. Use as defence-in-depth, not as the only XSS protection.
Report-only or enforce?
Roll out in report-only first — Trusted Types violations break apps that use innerHTML widely. Fix the violations, then switch to enforce.
Does Trusted Types replace input validation?
No. It's complementary. Trusted Types ensures every DOM sink goes through a vetting policy; input validation ensures the vetting is correct.
Can I migrate incrementally?
Yes. Add the report-only CSP, watch for violations in your reporting endpoint, refactor the worst sinks to use a policy, then promote to enforce.