Every script or stylesheet your page loads from a CDN or another origin runs with the full authority of your page, and if that host is compromised the browser will execute whatever it now serves. Subresource Integrity (SRI) is the browser feature that closes that gap for static files: you publish a cryptographic hash of the exact file you expect, and the browser refuses to use anything that does not match. This guide covers how SRI works at the specification level, the CORS rules that trip most teams up, which resources SRI can and cannot protect, how to generate and maintain hashes in a build pipeline, how to enforce coverage with the newer Integrity-Policy header, and how SRI evidence supports PCI DSS v4.0.1 requirements 6.4.3 and 11.6.1. It is written for front-end engineers, application security teams and assessors who need more than a one-line "add SRI" recommendation.
Key takeaways
- SRI pins content, not a location. The
integrityattribute carries one or more base64 hashes (sha256, sha384 or sha512); if the fetched bytes do not match, the browser returns a network error and the script never runs. - Cross-origin SRI needs CORS. Without
crossorigin="anonymous"and anAccess-Control-Allow-Originheader from the host, an integrity-protected request fails by design. - SRI only fits static, versioned files. "Latest" URLs, per-browser bundles, tag manager loaders and vendor scripts that change without notice cannot be hashed in advance; those need self-hosting, isolation or monitoring instead.
- Coverage can now be enforced.
Integrity-Policy-Report-Onlyand thenIntegrity-Policylet a page report, then block, any script or stylesheet that loads without integrity metadata. - SRI is evidence, not a full answer, for PCI DSS 6.4.3. It is a strong method to assure integrity of each payment page script, but you still need the authorisation and inventory elements, plus change and tamper detection under 11.6.1.
How SRI works
The W3C Subresource Integrity specification (currently a Level 2 Editor's Draft maintained by the Web Application Security Working Group) defines a single mechanism: integrity metadata attached to a request, checked by the browser against the response body before the resource is executed or applied.
- Supported elements:
<script>, and<link>whererelisstylesheet,preloadormodulepreload. The specification notes that support for other elements (images, iframes, media) may come in a future revision; today they are not covered. - Syntax: the value is a whitespace-separated list of
<algorithm>-<base64 digest>expressions, for exampleintegrity="sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO". A?optionsuffix is reserved in the grammar, but no options are defined and browsers must ignore unknown ones. - Algorithms: only
sha256,sha384andsha512are valid. The specification orders them from weakest to strongest and states that SHA-384 is a good baseline; MD5 and SHA-1 are explicitly not recommended and are not accepted. - Strongest wins: if you list hashes from more than one algorithm, the browser discards all but the strongest algorithm present and checks only those. If you list several hashes of the same algorithm, a match on any one passes, which is how you allow two known-good versions during a transition.
- Failure behaviour: a mismatch produces a network error and fires an
errorevent on the element. You can catch that event to load a fallback copy from your own origin, but a fallback that silently loads an unhashed copy defeats the control. - Preload headers: integrity can also be expressed on an HTTP
Linkheader, for exampleLink: </style.css>; rel=preload; as=style; crossorigin="anonymous"; integrity="sha256-...". - ES modules: import maps accept an
integritykey that maps module URLs to integrity metadata, so dynamically and statically imported modules can be checked even when no<script>tag carries the attribute.
SRI and CORS: the rule that breaks most rollouts
The specification states plainly that SRI requires CORS and that using it without CORS is a logical error. The reason is privacy: if a page could attach a guessed hash to any cross-origin URL and watch for load failures, it could learn the contents of resources it is not allowed to read, such as whether a user is logged in to another site. Browsers therefore refuse to apply integrity checks to no-cors requests, and a request with an integrity attribute but no crossorigin attribute always fails.
| Markup and server response | Result | Notes |
|---|---|---|
integrity set, no crossorigin, cross-origin host | Blocked | Request goes in no-cors mode; integrity cannot be applied, so the load fails. |
crossorigin="anonymous", host sends Access-Control-Allow-Origin: * | Loads if hash matches | The normal public CDN case; no cookies are sent. |
crossorigin="anonymous", host sends no CORS header | Blocked | Common with self-managed buckets and older vendor hosts. Fix the host, or self-host the file. |
crossorigin="use-credentials" | Loads only if host allows your exact origin with credentials | Rarely needed for scripts; a wildcard origin is not accepted with credentials. |
Same-origin file with integrity | Loads if hash matches | No CORS headers needed; still useful when files come from a separate deployment or storage layer. |
Two further rules from the specification matter in production. Intermediaries that rewrite responses (minifying proxies, some CDN optimisation features, injected analytics) will break the hash, so the host should send Cache-Control: no-transform and you should disable automatic optimisation for hashed paths. And integrity metadata served on a plain HTTP page protects nothing against a network attacker, who can simply strip the attribute; SRI belongs only on HTTPS pages. See the CORS Misconfiguration Guide for setting CORS headers safely on your own hosts.
What SRI can and cannot protect
SRI works by pinning exact bytes, so it suits resources whose content you decide, and fails for resources whose content the vendor decides. Classify every external resource before you start hashing.
| Resource type | SRI fit | Better control if SRI does not fit |
|---|---|---|
Versioned open source library on a public CDN (for example [email protected]/dist/x.min.js) | Strong | SRI plus exact version pin; or self-host from your build. |
Same library loaded as @latest or an unversioned path | None (hash breaks on every release) | Pin the version first, then hash. |
| Web fonts and CSS frameworks from a CDN | Strong for <link rel="stylesheet">; font files fetched by CSS are not covered | Self-host fonts if their integrity matters. |
| Vendor SDK that the vendor updates in place (analytics, chat, A/B testing) | Poor: breaks without warning | Ask for versioned URLs with published hashes; otherwise isolate, restrict with CSP and monitor. |
| Bundles generated per browser or per request | None | Self-host a fixed build or drop the dependency. |
| Tag manager container and the scripts it injects | Loader only, at best; injected tags are uncontrolled | Tag governance and script monitoring. See the Third-Party JavaScript Management Guide. |
| Payment fields from a payment service provider | Usually not applicable | PSP-hosted iframe or redirect, which moves the field out of your page. |
| Scripts created at runtime by your own code | Possible: set script.integrity and script.crossOrigin before inserting | Generate the hash at build time and ship it with the loader. |
The polyfill.io case in June 2024 shows the limit clearly. According to Sansec, after the domain changed owner, malicious code was served to more than 100,000 sites. That service generated a different bundle depending on the visiting browser, so there was no single file to hash: the only effective defences were removing the dependency or self-hosting a fixed build.
Generating and maintaining hashes in the build
Hand-pasting hashes from a website works for a demo and fails at scale. Treat integrity values as build artefacts derived from the same lockfile that pins your dependency versions.
- Compute from the file you will serve:
openssl dgst -sha384 -binary file.js | openssl base64 -Agives the digest; prefix it withsha384-. Hash the minified, compressed-as-served bytes after decompression, which is what the browser checks. - Bundlers: build plugins such as webpack-subresource-integrity add
integrityto the chunks and tags they emit, including lazily loaded chunks. Most frameworks have an equivalent option; turn it on rather than writing your own. - External CDN files: download the pinned version once in CI, hash it, and fail the build if the CDN copy ever differs from the hash recorded in the repository. That check also detects a CDN serving tampered content between releases.
- Algorithm choice: use
sha384by default;sha512is fine. Do not mix insha256for the same file thinking it adds safety: the browser will ignore it in favour of the stronger set. - Updates: when a dependency update bot raises a version bump, the same pull request must regenerate the hash. A bump that changes the URL but not the hash breaks the page; a hash regenerated from an unreviewed file simply launders the change. See the Dependency Update Automation Guide.
- Two-version transition: list two hashes of the same algorithm when you need a staged rollout across caches, then remove the old one.
Enforcing coverage: Integrity-Policy and CSP
SRI on its own is opt-in per tag, so one new tag without an attribute silently reopens the risk. Two browser mechanisms turn it into a policy.
Integrity-Policy headers
The SRI specification now defines Integrity-Policy and Integrity-Policy-Report-Only response headers. Their value is a structured field dictionary with blocked-destinations (allowed values script and style), optional sources (only inline, the default) and optional endpoints naming reporting endpoints declared in Reporting-Endpoints. With the enforcing header, the browser blocks any listed destination requested without integrity metadata, and blocks no-cors requests outright. Violations generate reports of type integrity-violation containing the document URL, blocked URL, destination and whether the policy was report-only, which you can also observe in page with a ReportingObserver.
A practical pair of headers for a payment page:
Reporting-Endpoints: integrity="https://reports.example.com/integrity"Integrity-Policy-Report-Only: blocked-destinations=(script style), endpoints=(integrity)
Browser support for these headers is newer and uneven; check current compatibility data before relying on blocking, and keep CSP as the baseline control.
Content Security Policy
CSP Level 3 lets a script-src hash source match a request's integrity metadata, so an external script whose integrity hash appears in the policy can be allowed without allowlisting its host. In practice most teams combine a nonce or hash based script-src for first-party code with SRI on the remaining static third-party files. OWASP ASVS 5.0 requirement V3.4.3 sets the CSP baseline (object-src 'none', base-uri 'none', and an allowlist, nonces or hashes). See the Content Security Policy Guide.
Choosing between SRI, self-hosting and isolation
| Option | Protects against | Cost and trade-offs | Choose when |
|---|---|---|---|
| SRI on CDN-hosted file | Tampering at the CDN or origin host | Hash maintenance; CORS dependency; breaks if host changes the file | Static, versioned public libraries where CDN delivery matters |
| Self-host from your build | Third-party host compromise entirely | You own patching and caching; your own pipeline becomes the trust point | Most libraries; any file you would otherwise hash |
| Self-host plus SRI | Tampering in your own storage or CDN layer | Low extra cost once the build emits hashes | Payment pages and high-value pages served from separate asset storage |
| Sandboxed iframe on another origin | Third-party code reading or changing your page | Layout and messaging work (postMessage) | Widgets and vendor code that must stay dynamic |
| Script monitoring or tamper detection | Detects changes after they happen | Does not prevent the first execution | Dynamic vendor scripts that cannot be hashed; PCI DSS 11.6.1 |
Small versus large organisations: a small site gets most of the benefit by self-hosting libraries, turning on the bundler SRI option and adding a report-only integrity policy. A large estate with many teams and vendors needs a central script inventory, CI checks that fail builds missing integrity, collected integrity and CSP reports, and an exception register for every unhashed script with an owner and justification.
Implementation plan
- Inventory: crawl the pages in scope (start with login, checkout and account pages) and list every external script and stylesheet with host, URL, version and owner. Browser developer tools and CSP report-only data both help.
- Classify: sort each item into the categories in the table above: hashable, needs pinning first, self-host, isolate, or monitor only.
- Pin and fix CORS: replace floating URLs with exact versions and confirm each host returns
Access-Control-Allow-Origin. Move files from hosts that cannot do CORS to your own origin. - Add hashes in the build: enable the bundler integrity option, add a CI step that recomputes external hashes and fails on drift, and add
crossorigin="anonymous"to every hashed cross-origin tag. - Test in a pilot: deploy to a staging environment and one low-risk page first; watch the browser console and error tracking for integrity failures. Test a deliberately wrong hash to confirm the page fails safely.
- Report-only policy: ship
Integrity-Policy-Report-Onlyfor scripts and styles and collect reports until unexpected entries stop. - Enforce: switch to
Integrity-Policyon pages where every remaining script is hashed or isolated. Rollback is a header change: revert to report-only if a release breaks a page, rather than removing hashes. - Maintain: require hash regeneration in dependency update pull requests and review the exception register quarterly.
Detection and measurement
- Integrity violation reports: collect
integrity-violationreports and CSP violation reports centrally; a new blocked URL on a payment page is a security event until proven otherwise. - Client-side load errors: forward script
errorevents with the failing URL to your error tracking so a real integrity failure is not dismissed as a flaky CDN. - CI drift checks: alert when a pinned CDN file no longer matches its recorded hash; that indicates either an upstream change or tampering.
- Change review: log every change to integrity values in source control with the reviewer, so an assessor can see who approved each script version.
Metrics that show SRI is working:
- Percentage of external scripts and stylesheets on in-scope pages that are hashed, self-hosted or isolated (target 100 percent on payment pages).
- Number of open exceptions (unhashed scripts) with an owner and justification, and their age.
- Integrity violations per week after tuning, and median time to triage each one.
- Percentage of dependency update pull requests that regenerated hashes in the same change.
- Pages with an enforcing Integrity-Policy or nonce-based CSP, out of pages in scope.
PCI DSS and framework mapping
PCI DSS v4.0.1 requirement 6.4.3 requires that every payment page script executed in the consumer's browser is authorised, has its integrity assured and is listed in an inventory with a written justification; requirement 11.6.1 requires a change and tamper detection mechanism for security-impacting HTTP headers and script contents of payment pages as received by the browser. Both became mandatory on 31 March 2025. In January 2025 the PCI Security Standards Council removed 6.4.3 and 11.6.1 from SAQ A, replacing them with an eligibility criterion that the merchant confirms its site is not susceptible to attacks from scripts that could affect its e-commerce systems; the Council stressed this does not weaken the underlying requirements. See the PCI DSS for E-commerce Payment Page Scripts Guide.
| Framework | Reference | How SRI contributes |
|---|---|---|
| PCI DSS v4.0.1 | 6.4.3 | Integrity element for static scripts; hash list in source control supports authorisation evidence |
| PCI DSS v4.0.1 | 11.6.1 | Integrity policy reports and CI drift checks feed tamper detection; not sufficient alone for dynamic scripts or headers |
| OWASP ASVS 5.0 | V3.6.1 (Level 3) | External assets only if static, versioned and protected by SRI, otherwise a documented decision per resource |
| NIST SP 800-53 Rev. 5 | SI-7, SI-7(15), SR-11, SA-9 | Integrity verification and code authentication of externally provided components |
| NIST CSF 2.0 | ID.AM-02, PR.PS-01, GV.SC-07 | Script inventory, configuration management of page content, supplier risk |
| MITRE ATT&CK | T1195.002 Compromise Software Supply Chain; T1189 Drive-by Compromise | Blocks tampered third-party code from executing in visitors' browsers |
Common failure patterns
- Missing
crossorigin: teams add the hash, the script fails in every browser, and the attribute is removed under pressure. Add both together and test before release. - Hashing a floating URL: a hash on
@latestbreaks at the next upstream release, which teaches developers to distrust SRI. The Lottie Player npm compromise reached websites precisely because many loaded the player from public CDNs using the latest tag, so malicious versions published with a stolen npm token were served without any change on those sites. - Trusting your own asset storage: SRI is often applied only to public CDNs. In the Twilio TaskRouter SDK compromise, a vendor SDK served from a world-writable S3 bucket was modified for about nine hours; customers loading a pinned, hashed copy would have blocked it.
- Fallback that bypasses the check: an
onerrorhandler that loads the same file from another host without integrity converts a blocked attack into a successful one. - CDN optimisation rewriting files: automatic minification or script injection features change the bytes and break hashes; disable them for hashed paths and send
no-transform. - Assuming SRI covers tag managers: hashing the container loader does nothing for the tags it injects later.
Where identity fits
The files SRI protects are published by someone holding a credential: an npm publishing token, a CDN or bucket write key, a CI deploy role. SRI limits the blast radius when those credentials are stolen, but the root fix is scoping and shortening them. Treat CDN and package publishing credentials as privileged non-human identities. See the npm Tokens Security Guide and the CDN Security Guide.
Practitioner checklist
- Inventory every external script and stylesheet on login, checkout and account pages, with owner and justification.
- Pin every third-party file to an exact version before hashing it; remove
@latestand unversioned URLs. - Use
sha384integrity values withcrossorigin="anonymous"and confirm each host returns CORS headers. - Generate hashes in the build and fail CI when an external file drifts from its recorded hash.
- Self-host files where you can; isolate dynamic vendor code in sandboxed iframes.
- Deploy
Integrity-Policy-Report-Onlywith a reporting endpoint, then enforce on pages with full coverage. - Never write error fallbacks that load unhashed copies.
- Require hash regeneration and review in every dependency update pull request.
- Keep SRI evidence (hash history, reports, exceptions) for PCI DSS 6.4.3 and 11.6.1 assessments.
Standards and references
- W3C: Subresource Integrity (Editor's Draft, Level 2)
- W3C: Content Security Policy Level 3
- MDN Web Docs: Subresource Integrity
- MDN Web Docs: Integrity-Policy header
- OWASP: Application Security Verification Standard 5.0
- PCI Security Standards Council: Important Updates Announced for Merchants Validating to SAQ A
- NIST: SP 800-53 Rev. 5
- MITRE ATT&CK: Compromise Software Supply Chain
Related NHI Mgmt Group resources: Client-Side Security Guide · OWASP Top 10 A08 Guide · Content Security Policy Guide · PCI DSS for E-commerce Payment Page Scripts Guide · Software Supply Chain Security Guide