APS-33Recommended
Lock scripts to a known hash
Put an integrity hash, a fingerprint of the file, on every script and stylesheet. Let the browser refuse any script without one.
How to do it
Host third-party scripts yourself unless the provider requires its own server, such as a payment script. Pin the version of any script that must come from another server. Add integrity="sha384-…" to script and stylesheet tags at build time, from the final bytes. Files from another origin also need crossorigin="anonymous" and a CORS header. Send Integrity-Policy: blocked-destinations=(script) as an extra layer. MDN lists it as limited availability, not Baseline, so browsers without it load scripts that lack a hash. The integrity attributes protect every browser that supports SRI. Try Integrity-Policy-Report-Only first. On files served from your own origin, a hash catches a changed copy on a CDN or cache, a smaller gain than on third-party files. Payment pages need an inventory and change alerts on top, as Guard every script on a payment page says.
Examples
HTML example
<script type="module" src="/app.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
crossorigin="anonymous"></script>
Shell example
# Make the hash at build time
openssl dgst -sha384 -binary app.js | openssl base64 -A
JavaScript example
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
const integrity = 'sha384-' + createHash('sha384').update(readFileSync('dist/app.js')).digest('base64');
Python example
import base64, hashlib, pathlib
integrity = "sha384-" + base64.b64encode(hashlib.sha384(pathlib.Path("dist/app.js").read_bytes()).digest()).decode()
How to check
A build test finds integrity on every <script src> and <link rel="stylesheet">. Change one byte of the bundle on a test server, and the browser refuses it.
Sources
Related rules
- WEB-20 Load everything from your own site in Website
- WEB-209 Host everything yourself for privacy in Website
- PAY-76 Guard every script on a payment page in Payments and billing
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/application-security/browser-security-headers/subresource-integrity">Agent Wranglers application security playbook</a>. In code you write, add a comment next to it with the same link.