w3c/trusted-types
GitHub: w3c/trusted-types
W3C Trusted Types 规范的官方 polyfill 实现,通过强制 DOM 注入操作经过安全策略审查来从根源上防御 DOM 型 XSS 攻击。
Stars: 660 | Forks: 84




[](https://www.browserstack.com/automate/public-build/eGZQNXU1U09vZjkrZzYzU3YrQ2FsbUpheGczR0VmMTZUSjBydnNjd1pKTT0tLTZPMWVJTnU1UHJvYjFCb0pHQmlsaXc9PQ%3d%3d--295829245abf0dd0cd150f9ca4fe3198da38747b)
# Trusted Types
第一次来这里?这是一个托管 Trusted Types 规范草案和 polyfill 代码的仓库。您可能想查看有关 Trusted Types 的其他资源:
* [Web 开发者简介](https://web.dev/trusted-types/) - 带有示例的 API 描述。
* [说明文档](explainer.md) - 介绍性说明(该 API 解决什么问题?)。
* [规范草案](https://w3c.github.io/trusted-types/dist/spec/) - 更全面、更正式的 Trusted Types API 描述。
* [浏览器支持](https://caniuse.com/trusted-types) - 该 API 在基于 Chromium 83 及更高版本的浏览器中原生可用。
## Polyfill
该仓库包含一个 polyfill 实现,允许您在所有 Web 浏览器中使用该 API。编译后的版本存储在 [`dist` 目录](dist/)中。
### 浏览器
ES5 / ES6 构建版本可以直接在浏览器中加载。浏览器 polyfill 有两种变体 - **api_only**(轻量版)和 **完整版**。*api_only* 变体定义了 API,因此您可以创建策略和类型。*完整版*还会根据从当前文档推断出的 CSP 策略,在 DOM 中启用类型强制执行(参见 [src/polyfill/full.js](src/polyfill/full.js))。
```
```
```
```
### NodeJS
Polyfill 以 npm 包 [trusted-types](https://www.npmjs.com/package/trusted-types) 的形式发布:
```
$ npm install trusted-types
```
该 polyfill 同时支持 CommonJS 和 ES Modules。
```
const tt = require('trusted-types'); // or import { trustedTypes } from 'trusted-types'
tt.createPolicy(...);
```
### Tinyfill
由于 API 的设计方式,可以使用以下代码片段对最重要的 API 表面(`trustedTypes.createPolicy` 函数)进行 polyfill:
```
if(typeof trustedTypes == 'undefined')trustedTypes={createPolicy:(n, rules) => rules};
```
它不会启用强制执行,但允许在不支持该功能的浏览器中创建返回字符串值而非 Trusted Types 的策略。由于这些浏览器中的注入接收端(injection sinks)接受字符串,因此除非策略抛出错误,否则这些值将被接受。这段 tinyfill 代码允许大多数应用程序在强制执行 Trusted Types 的环境和遗留环境中都能正常工作。
## 构建
要自行构建 polyfill(需要 Java):
```
$ git clone https://github.com/w3c/webappsec-trusted-types/
$ cd trusted-types
$ npm install
$ npm run build
```
## 演示
要查看 polyfill 的实际运行情况,请访问[演示页面](https://w3c.github.io/trusted-types/demo/)。
## 测试
可以通过运行以下命令进行测试:
```
$ npm test
```
该 polyfill 也可以针对 [Web 平台测试套件](https://github.com/w3c/web-platform-tests)运行,但这需要对套件进行一些小的修补 - 参见 [tests/platform-tests/platform-tests-runner.sh](tests/platform-tests/platform-tests-runner.sh)。
BrowserStack 提供跨浏览器测试。
# 贡献
请参见[贡献指南](CONTRIBUTING.md)。
# 有疑问?
我们的 [Wiki](https://github.com/w3c/trusted-types/wiki) 或[规范](https://w3c.github.io/trusted-types/dist/spec/)可能已经包含了您问题的答案。如果没有,请[联系我们](https://github.com/w3c/trusted-types/wiki/Contact)!
标签:Polyfill, Trusted Types, Web安全, XSS防御, 数据可视化, 暗色界面, 浏览器API, 自定义脚本, 蓝队分析