slop audit
Blog post 70 / Security and launch readiness

Subresource integrity: generate hashes and test CDN assets

Add subresource integrity to scripts and stylesheets, generate SHA-384 hashes, debug CDN and CORS failures, and test blocked assets before your website launches.

By Slop Audit · 8 min read

Subresource integrity (SRI) lets a browser compare a downloaded script or stylesheet with a hash you approved. If the bytes change, the browser can reject the resource before using it. This is useful when a portfolio, documentation site, or student project loads a versioned dependency from a CDN.

The launch risk is practical: an incorrect hash can block your own application. This guide shows how to generate the value from a reviewed artifact, configure cross-origin delivery, diagnose failures, and keep a small browser test for both accepted and rejected content.

Subresource integrity launch checklist

  1. Inventory externally loaded scripts and stylesheets on the routes you plan to ship.
  2. Choose an exact dependency version and review the artifact you intend to trust.
  3. Generate a digest from that file after all build transformations finish.
  4. Put the matching URL, hash, and cross-origin setting in the HTML together.
  5. Test the real CDN response and the user task that depends on it.
  6. In a controlled fixture, verify that changed bytes are rejected.
  7. Keep the previous HTML and asset pair available for rollback.

Start with one dependency that has a clear owner and release process. Record its URL, version, local artifact path, digest, and dependent task in the release review. Do not add hashes copied from an unrelated version just to complete a checklist.

What the script integrity attribute protects

An integrity value combines an algorithm name with a base64 digest. Supported algorithms include SHA-256, SHA-384, and SHA-512. On a mismatch, a supporting browser refuses to execute the script or apply the stylesheet. MDN's integrity attribute reference describes the supported elements and algorithms.

SRI binds a resource to expected content. It does not establish that the approved content is safe. Review the dependency and its provenance before accepting a new hash. If someone can replace both your HTML and its hash, that altered document can approve altered code. The W3C SRI Recommendation describes this threat model and the integrity comparison.

Use it alongside your Content Security Policy tests. A source allowlist decides which origins may supply resources; SRI checks expected bytes for a resource carrying integrity metadata. Keep both decisions in the release review. Neither removes the need to test the feature that uses the dependency.

A single entry script's hash also does not automatically pin every later request it makes. Inventory imported code, runtime-injected scripts, and other dependent assets separately. For integrations that intentionally change their script at a stable URL, ask the provider about a versioned distribution or consider bundling a reviewed dependency yourself.

Generate a SHA-384 SRI hash from the release artifact

This Node.js command hashes a local file. Replace the path with the exact final script or stylesheet you approved:

node --input-type=module - ./dist/vendor/widget-1.2.3.min.js <<'JS'
import { readFileSync } from "node:fs";
import { createHash } from "node:crypto";
const bytes = readFileSync(process.argv[2]);
const digest = createHash("sha384").update(bytes).digest("base64");
console.log(`sha384-${digest}`);
JS

Run this after minification, banners, and other content changes. Hash the file contents, not the filename, URL, or a text rendering of the hexadecimal digest. Keep the generated value beside the corresponding artifact in the review evidence. Node's crypto hash documentation explains update and the base64 output encoding.

For an external dependency, compare your approved file with the bytes served by the exact CDN URL. A successful download alone does not establish trust: an unexpected response needs investigation before you generate a replacement hash. Avoid mutable version aliases such as latest in a pinned release contract.

Use the output in markup like this. The uppercase tokens are placeholders, not working hashes:

<script defer
  src="https://cdn.example.com/widget/1.2.3/widget.min.js"
  integrity="REPLACE_WITH_GENERATED_SHA384_VALUE"
  crossorigin="anonymous"></script>

<link rel="stylesheet"
  href="https://cdn.example.com/widget/1.2.3/widget.min.css"
  integrity="REPLACE_WITH_CSS_SHA384_VALUE"
  crossorigin="anonymous">

Generate a separate digest for each file. A JavaScript hash cannot stand in for the stylesheet's hash. MDN's SRI implementation guide provides script and stylesheet markup examples.

For a bundler-generated site, use a build integration that emits integrity metadata for the final output and HTML together. Inspect the generated document rather than assuming development mode matches production. Publish the assets before switching the HTML, and retain old versioned files while older documents may still reference them.

Configure subresource integrity CORS delivery

For a cross-origin resource using SRI, the server must permit the CORS request. crossorigin="anonymous" selects the appropriate request mode without cross-origin credentials. A public, credential-free CDN resource can respond with:

Access-Control-Allow-Origin: *

Use a specific permitted page origin when that matches the delivery policy. The HTML attribute cannot add permission to the remote server. MDN's SRI security guide explains why integrity validation requires cross-origin access.

Inspect the final resource response in DevTools Network. Check its URL, response headers, content type, and body. Redirects, access challenges, and fallback HTML can produce a different resource from the file you reviewed. Use the CORS troubleshooting guide for origin-policy failures and the JavaScript MIME type guide when a script URL returns HTML.

Test from the actual page origin. Opening the CDN URL in a browser tab does not reproduce the page's cross-origin request. Also test the real deployed delivery path: a local file comparison cannot prove that edge transformations or routing leave the production response unchanged.

Debug an integrity mismatch without removing protection

When a feature stops working after adding SRI, keep Console and Network open through a fresh page load. Follow a short evidence trail:

  • Digest mismatch: compare the final served bytes with the approved artifact. Look for a different version, changed line endings, injected comments, or CDN transformations.
  • CORS rejection: confirm the element has the intended cross-origin mode and the final response permits the page origin.
  • CSP rejection: inspect the enforcing directive before changing either the hash or policy.
  • Wrong content: inspect the response body for an HTML error page, authentication screen, or single-page-app fallback.
  • Works only after refresh: compare the HTML release and asset version across browser caches and the edge.

A 200 response in Network is insufficient evidence that a script executed. Check the dependent user task and the browser's failure message. Do not silently remove integrity, broaden the CSP, or approve newly fetched bytes until you understand the difference.

If the update was intentional, review it, generate its new hash, and release the new HTML and asset contract together. If the response changed unexpectedly, restore the reviewed pair or remove the integration while investigating. Keep the failure evidence in the release ticket.

Add focused SRI testing to Playwright

This self-contained fixture uses a synthetic CDN response so the test does not depend on a live vendor. Save it in an existing Playwright Test project. It verifies that approved bytes execute and changed bytes do not, using the same declared digest in both cases:

import { createHash } from "node:crypto";
import { test, expect } from "@playwright/test";

const approved = 'document.querySelector("#result").textContent = "Loaded";';
const integrity = "sha384-" + createHash("sha384")
  .update(approved).digest("base64");

test.use({ serviceWorkers: "block" });

for (const changed of [false, true]) {
  test(`SRI ${changed ? "rejects changed" : "accepts approved"} bytes`,
    async ({ page }) => {
      await page.route("https://cdn.example.test/widget.js", (route) =>
        route.fulfill({
          status: 200,
          contentType: "text/javascript",
          headers: { "access-control-allow-origin": "*" },
          body: changed ? approved + "\n// unexpected change" : approved,
        })
      );
      await page.route("https://app.example.test/", (route) =>
        route.fulfill({
          contentType: "text/html",
          body: `<!doctype html><html lang="en"><title>SRI fixture</title>
            <p id="result">Not loaded</p>
            <script src="https://cdn.example.test/widget.js"
              integrity="${integrity}" crossorigin="anonymous"></script>`,
        })
      );
      await page.goto("https://app.example.test/", { waitUntil: "load" });
      await expect(page.locator("#result")).toHaveText(
        changed ? "Not loaded" : "Loaded"
      );
    }
  );
}

The fixture's parser-blocking script finishes loading or failing before the page load event, so the negative assertion has a defined observation point. The positive case prevents a permanently broken fixture from looking like successful rejection. Playwright's network mocking guide describes fulfilling intercepted requests.

This proves the fixture behavior in the browser you run. It does not validate your CDN, production hashes, dependency safety, or stylesheet rendering. Add a separate unmocked test for your deployed route: check the expected integrity attribute and complete the real dependency-backed task. Run relevant supported browsers, retain traces, and include the case in your website regression testing routine.

Check the surrounding public release with Slop Audit

After the focused SRI and user-task tests pass, audit the deployed public page with Slop Audit. Review its observed security-header presence checks and available same-site runtime error and failed-request evidence. Assign actionable findings, fix them, and rescan the same URL to compare the result.

Slop Audit does not generate or verify SRI hashes, test CDN tampering, or guarantee detection of third-party asset failures. Its browser run is bounded and does not exercise every dependency-backed interaction. Keep your dedicated SRI tests and dependency review with the report; a passing launch audit does not certify supply-chain security.

For sign-off, save the reviewed artifact version, digest, public page URL, tested browser, dependent task result, and rollback pair. That gives the next release a concrete contract to recheck.