DOM lib: Add support for Trusted Types API
See original GitHub issueSearch Terms
Trusted Types, DOM
Suggestion
Trusted Types (spec, introductory article) is a new experimental DOM API implemented within the WICG , with a working Chrome implementation.
The API creates a few new objects available on the global object in the browser, like most other web APIs (impl in TS and in Closure compiler).
Under certain conditions, controlled by a HTTP header (analogous to Content-Security-Policy behavior), the API can enable the enforcement - then it changes the signature of several DOM API functions and property setters, such that they accept specific object types, and reject strings. Colloquially, DOM API becomes strongly typed.
For example, with Trusted Types Element.innerHTML
property setter accepts a TrustedHTML
object.
Trusted Type objects stringify to their inner value. This API shape is a deliberate choice that enables existing web applications and libraries to gradually migrate from strings to Trusted Types without breaking functionality. In our example, it makes it possible to write the following:
const policy = TrustedTypes.createPolicy('foo', {
createHTML: (s) => { /* some validation*/; return s}
});
const trustedHTML = policy.createHTML('bar');
anElement.innerHTML = trustedHTML
anElement.innerHTML === 'bar'
The above code works regardless if the Trusted Types enforcement is enabled or not.
Reading from the DOM is unaffected, so Element.innerHTML
getter returns a string. That’s for practical reasons – web applications read from DOM more often than they write to it, and only writing exposes the application to DOM XSS risks. Typing only the setters allows us to secure web applications with minimal code changes.
It’s difficult to map that API using TS types (due to #2521). The only way is to change the DOM sink functions to have the any
type, which is obviously suboptimal.
Use Cases
Writing a TS application that uses the Trusted Types API.
Checklist
My suggestion meets these guidelines:
- This wouldn’t be a breaking change in existing TypeScript/JavaScript code
- This wouldn’t change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn’t a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript’s Design Goals.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:28
- Comments:12 (5 by maintainers)
Top GitHub Comments
Trusted Types are now available in Chrome canary.
microsoft/TypeScript-DOM-lib-generator#1246 is backward-incompatible and will break a bunch of existing code. The fix is to only widen the type on writing, while leaving the read type the same: