Experimental: This feature is experimental and subject to change. It may not be supported by all browsers and could have compatibility issues.
require-trusted-types-for
Therequire-trusted-types-for
directive instructs user agents to control the data passed to DOM XSS sink functions, like Element.innerHTML
setter.
Recommended Values
'script' Prohibits the use of string values with DOM XSS sink functions and requires that corresponding types be created by Trusted Type policies
Recommended require-trusted-types-for configuration
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types foo;
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.
Possible Values
'script'
: Prohibits the use of string values with DOM XSS sink functions and requires that corresponding types be created by Trusted Type policies
Example Configurations
Basic Policy Definition
Basic trusted types configuration
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types foo;
Allowed
const sanitizer = trustedtypes.createPolicy("foo", {
createHTML: (input) => DOMPurify.sanitize(input),
});
// Using sanitized value through trusted type policy
el.innerHTML = sanitizer.createHTML(attackerInput);
Blocked
// Direct assignment without trusted type policy
el.innerHTML = attackerInput; // Throws TypeError
// Using undefined policy
const invalidPolicy = trustedtypes.createPolicy("bar", {
createHTML: (input) => input,
}); // Throws Error if 'bar' is not in trusted-types directive
Additional Information
- Trusted Types provide a way to prevent DOM-based XSS attacks at the type system level
- The policy must be explicitly defined in both the CSP header and the JavaScript code
- All DOM XSS sink operations must use values created through trusted type policies
- Combining with other CSP directives provides comprehensive security coverage
Best Practices
- Always define explicit policies for handling untrusted input
- Use appropriate sanitization methods within your trusted type policies
- Test thoroughly in your target browsers due to the experimental nature of this feature
- Combine with other CSP directives for comprehensive security