Subresource Integrity (SRI): securing third-party scripts
In short: Subresource Integrity lets the browser check that an externally loaded file (script or stylesheet) is still exactly the one you expect. If it was changed, the browser doesn’t load it.
The problem
Anyone embedding a script from a foreign server (CDN) trusts that server blindly. If it is hacked or suddenly serves different code, the malicious code runs on your page with all rights; see XSS and software supply chain and SBOM.
How SRI works
The tag contains a fingerprint of the file, a hash such as SHA-256 or SHA-384:
<script src="https://cdn.example/lib.js"
integrity="sha384-BASE64HASH"
crossorigin="anonymous"></script>The browser loads the file, computes the hash and compares. If it doesn’t match, the file is blocked.
Important
crossorigin="anonymous"is needed so the browser may check the file.- If the provider legitimately changes the file (new version at the same address), the page breaks. So embed fixed versions, not “latest” addresses.
- SRI doesn’t replace trusting the provider the first time: the hash is taken from the reviewed version.
Even better: self-host
The safest solution is to serve libraries yourself. Then there is no third party who could change anything, and no visitor IP is sent to them when loading. Emzett does this too (wiki libraries, Pyodide, sql.js). Additionally, a content security policy limits where scripts may be loaded from at all.