You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Add setCSPTrustedTypesCallback for CSP trusted types.
[CSP trusted types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/trusted-types) is an API that allows a website to reduce the possibility of XSS by controlling what kind of content can be placed in a "sink" like `.innerHTML`. This commit introduces a flexible callback that allows the calling code to provide its own validation or rejection of an server response for an `<include-fragment-element>`. For example, the site may want to allow the server to send a header to assert that certain HTML is sanitized and safe to use as-is, or the site may want to run the response through a sanitizer. Here is a snippet that looks for such a header and falls back to the `dompurify` library for extremely basic sanitization.
```ts
import { setCSPTrustedTypesCallback } from "include-fragment-element";
import { default as DOMPurify } from "dompurify";
const policy = trustedTypes.createPolicy("server-sanitized", {
createHTML: (s) => s
});
setCSPTrustedTypesCallback(async (r: Response) => {
if (r.headers.get("X-Response-Trusted-Types")?.split(",").includes("server-sanitized=true")) {
return policy.createHTML(r.text());
}
return DOMPurify.sanitize(await r.text(), { RETURN_TRUSTED_TYPE: true });
});
```
0 commit comments