-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
NEFARIOUSPLAN-CANONICAL-V1
{"body_md":"## The CSP request header is something Next.js's own middleware sets\n\nNext.js's documented pattern for nonce-based Content Security Policy lives in a `middleware.ts` at the project root. The middleware generates a random nonce per request, sets it as part of a `Content-Security-Policy` response header, and also writes that same header onto the inbound request via `NextResponse.next({ request: { headers } })`. The renderer downstream reads the request header back, extracts the nonce token, and stamps it onto every `` or its entity-decoded variants close the tag mid-payload. U+2028 and U+2029 are Unicode line separators that JSON tolerates as ordinary whitespace inside string literals but JavaScript treats as statement terminators, so an attacker who could embed one would terminate the JSON literal early as JS. Five characters. One destination. The function's name encoded what destination, JSON inside script-tag text. The regex encoded the threat model that destination required.\n\nThe CSP-nonce parser imported the regex and used it as the gate deciding whether the extracted nonce was safe. Safe for what destination? The destination, two files away, was this:\n\n```tsx\n``\n```\n\nZero encoding. The value that the parser returned is the value that lands inside the attribute. The validator decided.\n\nThree sites in three files. The validator filtered for JSON-in-script-text escape characters. The first emitter wrapped its input with JSON-string encoding. The second emitter wrapped its input with nothing at all. None of the three spoke the grammar of the destination.\n\n## The attribute breakout\n\nThe exploit lays all three layers bare with one request header. The literal byte between `\"` and `onerror` below is a TAB (0x09), not a space:\n\n```\nContent-Security-Policy: script-src 'nonce-\"\tonerror=\"alert(1)'\n```\n\nThe legacy parser does `directive.split(' ')` with a single literal space. The TAB is not a space, so the entire `'nonce-\"\\tonerror=\"alert(1)'` survives `split(' ')` as one element. The token starts with `'nonce-`. The token ends with `'`. Its length exceeds 8. The `.find()` predicate matches. The `?.slice(7, -1)` strips the wrapping `'nonce-` and `'`, returning the body: `\"\\tonerror=\"alert(1)`.\n\nThat body is tested against `ESCAPE_REGEX = /[&><\\u2028\\u2029]/g`. The body contains a `\"`, a TAB, an `=`, an `a`, an `l`, an `e`, an `r`, an `t`, a `(`, a `1`, a `)`. None of those are in `&><\\u2028\\u2029`. The regex does not match. The validator returns the value.\n\n`create-server-inserted-metadata.tsx` interpolates the value:\n\n```html\n\n```\n\nRead the bytes left to right as an HTML attribute parser does. `\"'` contains `<` and `>`, so on most runtimes the throw fired and the request handler returned a 500.\n\nThe throw was not fail-closed on every runtime. The patched test in `test/production/app-dir/subresource-integrity/subresource-integrity.test.ts` records the runtime split. Pre-patch:\n\n```ts\nit('throws when escape characters are included in nonce', async () => {\n const res = await fetchWithPolicy(\n `script-src 'nonce-\">\"'`\n )\n\n if (runtime === 'node' && process.env.__NEXT_CACHE_COMPONENTS) {\n expect(res.status).toBe(200)\n } else {\n expect(res.status).toBe(500)\n }\n})\n```\n\nRead what that test asserted. On the cacheComponents runtime, the response status is 200. The throw fires inside the parser, but by the time it fires the streaming renderer has already flushed leading bytes of the response to the client. The throw aborts further streaming. The bytes already on the wire carry the broken-out attribute. The server logs an internal error. The client receives a 200 with the reflected payload.\n\nThe post-patch test rewrites the assertion:\n\n```ts\nit('ignores malformed nonce values without failing the request', async () => {\n const policies = [\n `script-src 'nonce-\">\"'`,\n `script-src 'nonce-\" onerror=\"alert(1)'`,\n ]\n\n for (const policy of policies) {\n const $ = await renderWithPolicy(policy)\n expect($('script[nonce]').length).toBe(0)\n }\n})\n```\n\nThe patched gate silently drops a malformed nonce, returns `undefined`, and the emission sites omit the `nonce` attribute entirely. The throw that the cacheComponents runtime turned into a partial reflection is gone. The behaviour is silent-drop, on every runtime.\n\n## The patch admits both wrongs\n\nCommit `b4c6705c70`, authored by JJ Kasper on April 21 2026 with the commit message \"Ignore malformed CSP nonce headers,\" changes four source files plus tests. The shape of the four changes is the shape of the bug.\n\n`get-script-nonce-from-header.tsx`. The fragile `startsWith` / `endsWith` / `length > 8` predicate and the `ESCAPE_REGEX` post-filter are replaced with one strict regex applied per source token. The import of `ESCAPE_REGEX` is deleted:\n\n```diff\n-import { ESCAPE_REGEX } from '../htmlescape'\n+const CSP_NONCE_SOURCE_REGEX = /^'nonce-([A-Za-z0-9+/_-]+={0,2})'$/\n\n export function getScriptNonceFromHeader(\n cspHeaderValue: string\n ): string | undefined {\n // ... locate the script-src or default-src directive ...\n\n- const nonce = directive\n- .split(' ')\n- .slice(1)\n- .map((source) => source.trim())\n- .find(\n- (source) =>\n- source.startsWith(\"'nonce-\") &&\n- source.length > 8 &&\n- source.endsWith(\"'\")\n- )\n- ?.slice(7, -1)\n-\n- if (!nonce) return\n-\n- if (ESCAPE_REGEX.test(nonce)) {\n- throw new Error(\n- 'Nonce value from Content-Security-Policy contained HTML escape characters.'\n- )\n- }\n-\n- return nonce\n+ for (const source of directive.split(/\\s+/).slice(1)) {\n+ const match = source.trim().match(CSP_NONCE_SOURCE_REGEX)\n+ if (match) return match[1]\n+ }\n }\n```\n\nThe new regex `/^'nonce-([A-Za-z0-9+/_-]+={0,2})'$/` is the CSP spec's definition of a nonce source value: the literal `'nonce-`, then a base64 alphabet run, then optional `=` padding, then the closing `'`. Anything else is not a nonce source. The validator no longer asks the JSON-script-text regex about an HTML attribute. The validator no longer reaches into `htmlescape.ts` at all.\n\n`htmlescape.ts`. A second function and a second regex are added next to the first:\n\n```diff\n export const ESCAPE_REGEX = /[&><\\u2028\\u2029]/g\n\n+const ATTRIBUTE_ESCAPE_LOOKUP: { [match: string]: string } = {\n+ '&': '&',\n+ '\"': '"',\n+ \"'\": ''',\n+ '<': '<',\n+ '>': '>',\n+}\n+\n+const ATTRIBUTE_ESCAPE_REGEX = /[&\"'<>]/g\n+\n export function htmlEscapeJsonString(str: string): string {\n return str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match])\n }\n+\n+export function htmlEscapeAttributeString(str: string): string {\n+ return str.replace(\n+ ATTRIBUTE_ESCAPE_REGEX,\n+ (match) => ATTRIBUTE_ESCAPE_LOOKUP[match]\n+ )\n+}\n```\n\nThe two functions sit side by side. The name of each says which destination it speaks for. `htmlEscapeJsonString` covers `& > < U+2028 U+2029` because that is JSON-in-script-text. `htmlEscapeAttributeString` covers `& \" ' < >` because that is HTML attribute. Five characters each. Three of those characters overlap. The two characters that do not overlap are the two characters that distinguish the destinations: `\"` and `'` for the attribute, U+2028 and U+2029 for the script-tag body.\n\n`use-flight-response.tsx`. The wrap changes from `JSON.stringify` to `htmlEscapeAttributeString`:\n\n```diff\n-import { htmlEscapeJsonString } from '../htmlescape'\n+import { htmlEscapeAttributeString, htmlEscapeJsonString } from '../htmlescape'\n\n // ...\n\n const startScriptTag = nonce\n- ? ``\n+return ``\n```\n\nBoth emitters now speak HTML attribute. The validator no longer speaks JSON.\n\n## The Shell Was Not The Sink, applied to script tags\n\nThe defender-frame name for this is the-shell-was-not-the-sink, and the canonical exhibit is `cacti_escapeshellarg`, where Cacti's sanitiser was correct, complete behaviour for the POSIX shell and the value never reached a shell. Between Cacti's quote-wrap and rrdtool's read loop there is no shell. The wrap does not bind.\n\nNext.js stages the same shape one floor up the stack. Between Next.js's `getScriptNonceFromHeader` and the `