完整性检查
【Integrity checks】
策略文件必须使用与浏览器兼容的子资源完整性字符串进行完整性检查,这些字符串与关联绝对 URL 的 integrity 属性 相对应。
【Policy files must use integrity checks with Subresource Integrity strings compatible with the browser integrity attribute associated with absolute URLs.】
使用 require() 或 import 时,如果指定了策略清单,加载所涉及的所有资源都会进行完整性检查。如果资源与清单中列出的完整性不匹配,将会抛出错误。
【When using require() or import all resources involved in loading are checked
for integrity if a policy manifest has been specified. If a resource does not
match the integrity listed in the manifest, an error will be thrown.】
一个示例策略文件,它允许加载文件 checked.js:
【An example policy file that would allow loading a file checked.js:】
{
"resources": {
"./app/checked.js": {
"integrity": "sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0"
}
}
} 策略清单中列出的每个资源可以采用以下格式之一来确定其位置:
【Each resource listed in the policy manifest can be of one the following formats to determine its location:】
- 从清单中的资源引用 相对 URL 字符串,例如
./resource.js、../resource.js或/resource.js。 - 指向资源的完整 URL 字符串,例如
file:///resource.js。
在加载资源时,整个 URL 必须完全匹配,包括查询参数和哈希片段。尝试加载 ./a.js 时不会使用 ./a.js?b,反之亦然。
【When loading resources the entire URL must match including search parameters
and hash fragment. ./a.js?b will not be used when attempting to load
./a.js and vice versa.】
要生成完整性字符串,可以使用如下脚本:
node -e 'process.stdout.write("sha256-");process.stdin.pipe(crypto.createHash("sha256").setEncoding("base64")).pipe(process.stdout)' < FILE
【To generate integrity strings, a script such as
node -e 'process.stdout.write("sha256-");process.stdin.pipe(crypto.createHash("sha256").setEncoding("base64")).pipe(process.stdout)' < FILE
can be used.】
完整性可以指定为布尔值 true,以接受资源的任何内容,这在本地开发中可能很有用。但在生产环境中不推荐使用,因为这会允许对资源的意外更改被视为有效。
【Integrity can be specified as the boolean value true to accept any
body for the resource which can be useful for local development. It is not
recommended in production since it would allow unexpected alteration of
resources to be considered valid.】