require-trusted-types-for
require-trusted-types-for
require-trusted-types-for
This directive instructs user agents to control the data passed to DOM XSS sink functions, like Element.innerHTML setter.
Recommended Values
'script'
Enforces Trusted Types for script execution contexts
Enforces Trusted Types for script execution contexts
Explore detailed value definitions
Tips & Tricks
This directive helps mitigate DOM-based XSS attacks by ensuring that only trusted, typed values are used in sensitive DOM APIs.
This is an experimental technology. Check browser compatibility before using in production.
Examples
Requires Trusted Types for all script execution contexts and defines a policy named 'foo'
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types foo;
Allowed
const sanitizer = trustedTypes.createPolicy("foo", { createHTML: (input) => DOMPurify.sanitize(input), }); el.innerHTML = sanitizer.createHTML(attackerInput); // Puts the sanitized value into the DOM.
Blocked
el.innerHTML = attackerInput; // Rejects a string value; throws a TypeError.
Frequently Asked Questions
What is the require-trusted-types-for directive?
The require-trusted-types-for directive enforces the use of Trusted Types for DOM XSS injection sinks. When enabled with 'script', it requires all JavaScript string-to-code conversions (like innerHTML or eval) to use Trusted Types, helping prevent DOM-based cross-site scripting attacks.
Browser Support
Trusted Types are supported in Chrome 83+ and other Chromium-based browsers. Other browsers will ignore this directive.
How do I implement require-trusted-types-for?
To implement require-trusted-types-for, add it to your CSP header with the 'script' argument: 'require-trusted-types-for 'script''. You'll then need to create and use Trusted Type policies in your JavaScript code for any operations that could lead to DOM XSS.
What are the benefits of using require-trusted-types-for?
Using require-trusted-types-for provides strong protection against DOM-based XSS attacks by forcing developers to explicitly mark trusted content through Trusted Type policies. This makes it much harder to accidentally introduce XSS vulnerabilities through unsafe DOM manipulations.
Implementation Note
Before enabling this directive in production, ensure all your code and third-party scripts are compatible with Trusted Types to avoid breaking functionality.
Need to monitor CSP violations and maintain it easily?
Set up a reporting endpoint to monitor Content Security Policy violations in real-time to build and maintain your CSP easily.
Set up your endpoint now