Trusted Types API
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Note: This feature is available inWeb Workers.
TheTrusted Types API gives web developers a way to ensure that input has been passed through a user-specified transformation function before being passed to an API that might execute that input. This can help to protect against client-sidecross-site scripting (XSS) attacks. Most commonly the transformation functionsanitizes the input.
In this article
Concepts and usage
Client-side, or DOM-based, XSS attacks happen when data crafted by an attacker is passed to a browser API that executes that data as code. These APIs are known asinjection sinks.
The Trusted Types API distinguishes three sorts of injection sinks:
- HTML sinks: APIs that interpret their input as HTML, such as
Element.innerHTMLordocument.write(). These APIs could execute JavaScript if it is embedded in the HTML, for example in<script>tags or event handler attributes. - JavaScript sinks: APIs that interpret their input as JavaScript, such as
eval()orHTMLScriptElement.text. - JavaScript URL sinks: APIs that interpret their input as the URL of a script, such as
HTMLScriptElement.src.
One of the main defenses against DOM-based XSS attacks is to ensure that input is made safe before being passed to an injection sink.
In the Trusted Types API, a developer defines apolicy object, which contains methods that transform input bound for an injection sink so as to make it safe. The policy can define different methods for the different types of sink:
- For HTML sinks, the transformation function typicallysanitizes the input, for example by using a library likeDOMPurify.
- For JavaScript and JavaScript URL sinks, the policy may turn off the sinks entirely or allow certain predefined inputs (for example, specific URLs).
The Trusted Types API will then ensure that input is passed through the appropriate transformation function before being passed into the sink.
That is, the API enables you to define your policy in one place and then be assured that any data passed to an injection sink has been passed through the policy.
Note:
The Trusted Types API doesnot itself supply a policy or any transformation functions: the developer defines their own policy, which contains the transformations that they wish to apply.
The API has two main parts:
- A JavaScript API enables a developer to sanitize data before passing it to an injection sink.
- TwoCSP directives enforce and control the usage of the JavaScript API.
The Trusted Types JavaScript API
In the Trusted Types API:
- The
trustedTypesglobal property, available in bothWindowandWorkercontexts, is used to createTrustedTypePolicyobjects. - A
TrustedTypePolicyobject is used to create trusted type objects: it will do this by passing the data through a transformation function. - Trusted type objects represent data that has been through the policy, and can therefore be safely passed to an injection sink. There are three sorts of trusted type, corresponding to the different sort of injection sink:
TrustedHTMLis for passing to a sink that will render the data as HTML.TrustedScriptis for passing to a sink that will execute the data as JavaScript.TrustedScriptURLis for passing to a sink that will parse the data as a URL to a script.
With this API, instead of passing a string to an injection sink likeinnerHTML, you use aTrustedTypePolicy to create aTrustedHTML object from the string, then pass that into the sink, and can be sure that the string has been passed through a transformation function.
For example, this code creates aTrustedTypePolicy that can createTrustedHTML objects by sanitizing the input strings with theDOMPurify library:
const policy = trustedTypes.createPolicy("my-policy", { createHTML: (input) => DOMPurify.sanitize(input),});Next, you can use thispolicy object to create aTrustedHTML object, and pass that object into the injection sink:
const userInput = "<p>I might be XSS</p>";const element = document.querySelector("#container");const trustedHTML = policy.createHTML(userInput);element.innerHTML = trustedHTML;Using a CSP to enforce trusted types
The API described above enables you to sanitize data, but it doesn't ensure that your code never passes input directly to an injection sink: that is, it doesn't stop you passing a string intoinnerHTML.
In order to enforce that a trusted type must always be passed, you include therequire-trusted-types-for directive in yourCSP.With this directive set, passing strings into injection sinks will result in aTypeError exception:
const userInput = "<p>I might be XSS</p>";const element = document.querySelector("#container");element.innerHTML = userInput; // Throws a TypeErrorAdditionally, thetrusted-types CSP directive can be used to control which policies your code is allowed to create. When you create a policy usingtrustedTypes.createPolicy(), you pass a name for the policy. Thetrusted-types CSP directive lists acceptable policy names, socreatePolicy() will throw an exception if it is passed a name which was not listed intrusted-types. This prevents some code in your web application from creating a policy that you were not expecting.
The default policy
In the Trusted Types API, you can define adefault policy. This helps you find any places in your code where you're still passing strings into injection sinks, so you can rewrite the code to create and pass trusted types instead.
If you create a policy named"default", and your CSP enforces the use of trusted types, then any string argument passed into injection sinks will be automatically passed to this policy. For example, suppose we create a policy like this:
trustedTypes.createPolicy("default", { createHTML(value) { console.log("Please refactor this code"); return sanitize(value); },});With this policy, if your code assigns a string toinnerHTML, the browser will call the policy'screateHTML() method and assign its result to the sink:
const userInput = "<p>I might be XSS</p>";const element = document.querySelector("#container");element.innerHTML = userInput;// Logs "Please refactor this code"// Assigns the result of sanitize(userInput)If the default policy returnednull orundefined, then the browser will throw aTypeError when assigning the result to the sink:
trustedTypes.createPolicy("default", { createHTML(value) { console.log("Please refactor this code"); return null; },});const userInput = "<p>I might be XSS</p>";const element = document.querySelector("#container");element.innerHTML = userInput;// Logs "Please refactor this code"// Throws a TypeErrorNote:It's recommended that you use the default policy only while you are transitioning from legacy code that passes input directly to injection sinks, to code that uses trusted types explicitly.
Injection sink interfaces
This section provides a list of "direct" injection sink interfaces.
Note that there are cases where untrusted strings may be "indirectly injected", such as when an untrusted string is added as the child node of a script element, and then the element is added to the document.These cases are evaluated the untrusted script is added to the document.
TrustedHTML
Document.execCommand()with acommandNameof"insertHTML"Document.parseHTMLUnsafe()Document.write()Document.writeln()DOMParser.parseFromString()Element.innerHTMLElement.insertAdjacentHTMLElement.outerHTMLElement.setHTMLUnsafe()HTMLIFrameElement.srcdocRange.createContextualFragment()ShadowRoot.innerHTMLShadowRoot.setHTMLUnsafe()
TrustedScript
eval()Element.setAttribute()(valueargument)Element.setAttributeNS()(valueargument)Function()constructorHTMLScriptElement.innerTextHTMLScriptElement.textContentHTMLScriptElement.textwindow.setTimeout()andWorkerGlobalScope.setTimeout()(codeargument)window.setInterval()andWorkerGlobalScope.setInterval()(codeargument)
TrustedScriptURL
Cross-browser support for trusted types
The Trusted Types API is not yet available in all modern browsers, but it is usable everywhere today thanks tocompatibility aids created by the W3C.
- Thefull polyfill defines the JavaScript API, attempts to infer the CSP from the current document, and enforces the use of trusted types based on the inferred CSP.
- TheAPI only polyfill defines only the JavaScript API, and does not include the ability to enforce the use of trusted types using a CSP.
As well as these two polyfills, the W3C provides what it calls atinyfill, which we'll explain in more detail below.
Note that as long as you have tested your code on a supporting browser with CSP enforcement enabled, then you don't need to use thefull polyfill above on other browsers — you can get the same benefits using theAPI only polyfill or thetinyfill.
This is because the enforcement forces you to refactor your code to ensure that all data is passed through the Trusted Types API (and therefore has been through a sanitization function) before being passed to an injection sink.If you then run the refactored code in a different browser without enforcement, it will still go through the same code paths, and give you the same protection.
Trusted Types tinyfill
In this section we'll look at how the trusted types tinyfill can protect a website, even though it doesn't add support for trusted types at all.
The trusted types tinyfill is just this:
if (typeof trustedTypes === "undefined") trustedTypes = { createPolicy: (n, rules) => rules };It provides an implementation oftrustedTypes.createPolicy() which just returns thepolicyOptions object it was passed. ThepolicyOptions object defines sanitization functions for data, and these functions are expected to return strings.
With this tinyfill in place, suppose we create a policy:
const policy = trustedTypes.createPolicy("my-policy", { createHTML: (input) => DOMPurify.sanitize(input),});In browsers that support trusted types, this will return aTrustedTypePolicy which will create aTrustedHTML object when we callpolicy.createHTML(). TheTrustedHTML object can then be passed to an injection sink, and we can enforce that the sink received a trusted type, rather than a string.
In browsers that don't support trusted types, this code will return an object with acreateHTML() function that sanitizes its input and returns it as a string. The sanitized string can then be passed to an injection sink.
const userInput = "I might be XSS";const element = document.querySelector("#container");const trustedHTML = policy.createHTML(userInput);// In supporting browsers, trustedHTML is a TrustedHTML object.// In non-supporting browsers, trustedHTML is a string.element.innerHTML = trustedHTML;// In supporting browsers, this will throw if trustedHTML// is not a TrustedHTML object.Either way, the injection sink gets sanitized data, and because we could enforce the use of the policy in the supporting browser, we know that this code path goes through the sanitization function in the non-supporting browser, too.
Interfaces
TrustedHTMLRepresents a string to insert into an injection sink that will render it as HTML.
TrustedScriptRepresents a string to insert into an injection sink that could lead to the script being executed.
TrustedScriptURLRepresents a string to insert into an injection sink that will parse it as a URL of an external script resource.
TrustedTypePolicyDefines the functions used to create the above Trusted Type objects.
TrustedTypePolicyFactoryCreates policies and verifies that Trusted Type object instances were created via one of the policies.
Extensions to other interfaces
Window.trustedTypesReturns the
TrustedTypePolicyFactoryobject associated with the global object in the main thread.This is the entry point for using the API in the Window thread.WorkerGlobalScope.trustedTypes.Returns the
TrustedTypePolicyFactoryobject associated with the global object in a worker.
Extensions to HTTP
Content-Security-Policy directives
require-trusted-types-forEnforces that Trusted Types are passed to DOM XSSinjection sinks.
trusted-typesUsed to specify an allowlist of Trusted Types policy names.
Content-Security-Policy keywords
trusted-types-evalAllows
eval()and similar functions to be used but only when Trusted Types are supported and enforced.
Examples
In the below example we create a policy that will createTrustedHTML objects usingTrustedTypePolicyFactory.createPolicy(). We can then useTrustedTypePolicy.createHTML() to create a sanitized HTML string to be inserted into the document.
The sanitized value can then be used withElement.innerHTML to ensure that no new HTML elements can be injected.
<div></div>const escapeHTMLPolicy = trustedTypes.createPolicy("myEscapePolicy", { createHTML: (string) => string .replace(/&/g, "&") .replace(/</g, "<") .replace(/"/g, """) .replace(/'/g, "'"),});let el = document.getElementById("myDiv");const escaped = escapeHTMLPolicy.createHTML("<img src=x onerror=alert(1)>");console.log(escaped instanceof TrustedHTML); // trueel.innerHTML = escaped;Read more about this example, and discover other ways to sanitize input in the articlePrevent DOM-based cross-site scripting vulnerabilities with Trusted Types.
Specifications
| Specification |
|---|
| Trusted Types> |