Skip to the code

A Content Security Policy with a fresh nonce

Leaf and Kettle wants a strict Content Security Policy: the browser runs only the scripts the shop vouches for, so a <script> someone sneaks into a review never runs. The shop vouches for its inline scripts with a nonce, a random value that changes with every request: the policy names it, and only scripts carrying it run. Write proxy.ts to make one per request.

Make the nonce from 16 random bytes, crypto.getRandomValues(new Uint8Array(16)), written in base64 with btoa(String.fromCharCode(...bytes)). Every request gets a new one.

The policy has these eight directives, separated by ; : default-src 'self', script-src 'self' 'nonce-<nonce>' 'strict-dynamic', style-src 'self' 'nonce-<nonce>', img-src 'self' https://images.leafandkettle.example data:, object-src 'none', base-uri 'self', form-action 'self', and frame-ancestors 'none'. Send it to the browser in the response's Content-Security-Policy header.

Hand it to the app as well, as request headers through NextResponse.next({ request: { headers } }), starting from a copy of the request's headers: x-nonce with the nonce, which the home page reads with headers() for its inline theme script, and Content-Security-Policy with the policy, where Next.js itself looks for the nonce to put on its own scripts. Set both even when the request already has them, since anyone can send any header.

Next.js carries the request headers you give NextResponse.next() in its answer's x-middleware-request-<name> headers, listed in x-middleware-override-headers, so that's where the tests look for what the app will see.

Export a config.matcher that runs proxy.ts for pages, and not for /api/..., /_next/static/..., /_next/image, /favicon.ico, or the requests Next.js's router sends to prefetch a page, which carry a next-router-prefetch header: none of them is an HTML page, so a policy on them does nothing.

GET /teas
→ Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-q3Zt0f1x8kVb2m9LwPa4cg==' 'strict-dynamic'; ...
→ the app's request headers:  x-nonce: q3Zt0f1x8kVb2m9LwPa4cg==, content-security-policy: (the same policy)
→ app/page.tsx renders <script nonce="q3Zt0f1x8kVb2m9LwPa4cg==">…</script>

The app's other files

app/page.tsx, read-only. Import it as @/app/page.

import { headers } from "next/headers";
 
/** Sets the saved theme before the page paints, so a dark-mode visitor never sees a white flash. */
const THEME_SCRIPT = 'document.documentElement.dataset.theme = localStorage.getItem("theme") === "dark" ? "dark" : "light";';
 
export default async function HomePage() {
  // proxy.ts made this request's nonce. Without it, the policy stops this inline script.
  const nonce = (await headers()).get("x-nonce") ?? undefined;
 
  return (
    <main>
      <script nonce={nonce} dangerouslySetInnerHTML={{ __html: THEME_SCRIPT }} />
      <h1>Leaf and Kettle</h1>
    </main>
  );
}

What the tests check

  1. sends a policy whose scripts need the nonce
    /** The policy's directives, by name: { "script-src": ["'self'", ...], ... }. */
    const directives = (policy) => {
      const found = {};
      for (const part of String(policy).split(";")) {
        const [name, ...sources] = part.trim().split(/\s+/);
        if (name) found[name.toLowerCase()] = sources;
      }
      return found;
    };
    const policyOf = (response) => response.headers.get("content-security-policy");
    const nonceIn = (policy) => {
      const sources = directives(policy)["script-src"] || [];
      const found = sources.map((source) => /^'nonce-(.+)'$/.exec(source)).find(Boolean);
      return found ? found[1] : null;
    };
    /** The request headers proxy.ts handed the app: NextResponse.next() carries them as x-middleware-request-<name>. */
    const forwarded = (response) => {
      const names = (response.headers.get("x-middleware-override-headers") || "").split(",").filter(Boolean);
      return Object.fromEntries(names.map((name) => [name, response.headers.get("x-middleware-request-" + name)]));
    };
    const policy = policyOf(await proxy(request("/teas")));
    const scripts = directives(policy)["script-src"];
    expect(scripts).toContain("'self'");
    expect(scripts).toContain("'strict-dynamic'");
    expect(scripts.filter((source) => source.startsWith("'nonce-")).length).toBe(1);
    expect(nonceIn(policy)).not.toBeNull();
    expect(policy).not.toMatch(/unsafe-inline|unsafe-eval/);
    
  2. makes a fresh, random nonce for every request
    /** The policy's directives, by name: { "script-src": ["'self'", ...], ... }. */
    const directives = (policy) => {
      const found = {};
      for (const part of String(policy).split(";")) {
        const [name, ...sources] = part.trim().split(/\s+/);
        if (name) found[name.toLowerCase()] = sources;
      }
      return found;
    };
    const policyOf = (response) => response.headers.get("content-security-policy");
    const nonceIn = (policy) => {
      const sources = directives(policy)["script-src"] || [];
      const found = sources.map((source) => /^'nonce-(.+)'$/.exec(source)).find(Boolean);
      return found ? found[1] : null;
    };
    /** The request headers proxy.ts handed the app: NextResponse.next() carries them as x-middleware-request-<name>. */
    const forwarded = (response) => {
      const names = (response.headers.get("x-middleware-override-headers") || "").split(",").filter(Boolean);
      return Object.fromEntries(names.map((name) => [name, response.headers.get("x-middleware-request-" + name)]));
    };
    const nonces = [];
    for (let n = 0; n < 5; n++) nonces.push(nonceIn(policyOf(await proxy(request("/teas")))));
    expect(new Set(nonces).size).toBe(5);
    for (const nonce of nonces) {
      expect(nonce).toMatch(/^[A-Za-z0-9+/]+={0,2}$/);
      expect(atob(nonce).length).toBeGreaterThanOrEqual(16);
    }
    
  3. lists the shop's sources for everything else
    /** The policy's directives, by name: { "script-src": ["'self'", ...], ... }. */
    const directives = (policy) => {
      const found = {};
      for (const part of String(policy).split(";")) {
        const [name, ...sources] = part.trim().split(/\s+/);
        if (name) found[name.toLowerCase()] = sources;
      }
      return found;
    };
    const policyOf = (response) => response.headers.get("content-security-policy");
    const nonceIn = (policy) => {
      const sources = directives(policy)["script-src"] || [];
      const found = sources.map((source) => /^'nonce-(.+)'$/.exec(source)).find(Boolean);
      return found ? found[1] : null;
    };
    /** The request headers proxy.ts handed the app: NextResponse.next() carries them as x-middleware-request-<name>. */
    const forwarded = (response) => {
      const names = (response.headers.get("x-middleware-override-headers") || "").split(",").filter(Boolean);
      return Object.fromEntries(names.map((name) => [name, response.headers.get("x-middleware-request-" + name)]));
    };
    const policy = policyOf(await proxy(request("/")));
    const found = directives(policy);
    const nonce = nonceIn(policy);
    const sorted = (sources) => [...(sources || [])].sort();
    expect(Object.keys(found).sort()).toEqual(["base-uri", "default-src", "form-action", "frame-ancestors", "img-src", "object-src", "script-src", "style-src"]);
    expect(found["default-src"]).toEqual(["'self'"]);
    expect(sorted(found["style-src"])).toEqual(sorted(["'self'", "'nonce-" + nonce + "'"]));
    expect(sorted(found["img-src"])).toEqual(sorted(["'self'", "https://images.leafandkettle.example", "data:"]));
    expect(found["object-src"]).toEqual(["'none'"]);
    expect(found["base-uri"]).toEqual(["'self'"]);
    expect(found["form-action"]).toEqual(["'self'"]);
    expect(found["frame-ancestors"]).toEqual(["'none'"]);
    
  4. hands the app the nonce and the policy, not ones the request brought
    /** The policy's directives, by name: { "script-src": ["'self'", ...], ... }. */
    const directives = (policy) => {
      const found = {};
      for (const part of String(policy).split(";")) {
        const [name, ...sources] = part.trim().split(/\s+/);
        if (name) found[name.toLowerCase()] = sources;
      }
      return found;
    };
    const policyOf = (response) => response.headers.get("content-security-policy");
    const nonceIn = (policy) => {
      const sources = directives(policy)["script-src"] || [];
      const found = sources.map((source) => /^'nonce-(.+)'$/.exec(source)).find(Boolean);
      return found ? found[1] : null;
    };
    /** The request headers proxy.ts handed the app: NextResponse.next() carries them as x-middleware-request-<name>. */
    const forwarded = (response) => {
      const names = (response.headers.get("x-middleware-override-headers") || "").split(",").filter(Boolean);
      return Object.fromEntries(names.map((name) => [name, response.headers.get("x-middleware-request-" + name)]));
    };
    const response = await proxy(request("/account", { headers: { cookie: "session=token-ana", "x-nonce": "attacker", "content-security-policy": "script-src *" } }));
    const policy = policyOf(response);
    const app = forwarded(response);
    expect(policy).toMatch(/'nonce-/);
    expect(response.headers.get("x-middleware-next")).toBe("1");
    expect(Object.keys(app)).toContain("x-nonce");
    expect(app["x-nonce"]).toBe(nonceIn(policy));
    expect(app["content-security-policy"]).toBe(policy);
    expect(app.cookie).toBe("session=token-ana");
    
  5. the home page's inline script carries the nonce
    /** The policy's directives, by name: { "script-src": ["'self'", ...], ... }. */
    const directives = (policy) => {
      const found = {};
      for (const part of String(policy).split(";")) {
        const [name, ...sources] = part.trim().split(/\s+/);
        if (name) found[name.toLowerCase()] = sources;
      }
      return found;
    };
    const policyOf = (response) => response.headers.get("content-security-policy");
    const nonceIn = (policy) => {
      const sources = directives(policy)["script-src"] || [];
      const found = sources.map((source) => /^'nonce-(.+)'$/.exec(source)).find(Boolean);
      return found ? found[1] : null;
    };
    /** The request headers proxy.ts handed the app: NextResponse.next() carries them as x-middleware-request-<name>. */
    const forwarded = (response) => {
      const names = (response.headers.get("x-middleware-override-headers") || "").split(",").filter(Boolean);
      return Object.fromEntries(names.map((name) => [name, response.headers.get("x-middleware-request-" + name)]));
    };
    const response = await proxy(request("/"));
    expect(policyOf(response)).toMatch(/'nonce-/);
    const nonce = nonceIn(policyOf(response));
    const tree = await withRequest({ headers: forwarded(response) }, () => Page());
    const scripts = [];
    const visit = (node) => {
      if (Array.isArray(node)) node.forEach(visit);
      else if (React.isValidElement(node)) {
        if (node.type === "script") scripts.push(node);
        visit(node.props.children);
      }
    };
    visit(tree);
    expect(scripts.length).toBe(1);
    expect(scripts[0].props.nonce).toBe(nonce);
    
  6. runs for pages, not for the API, Next.js's files, or prefetches
    for (const path of ["/", "/teas", "/teas/mint", "/account/orders"]) expect(proxyRuns(path)).toBe(true);
    for (const path of ["/api/teas", "/_next/static/chunks/main.js", "/_next/image", "/favicon.ico"]) expect(proxyRuns(path)).toBe(false);
    expect(proxyRuns("/teas", { headers: { "next-router-prefetch": "1" } })).toBe(false);
    

Learn more

proxy.tsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).