@rsc-kit/core 0.30.53 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"headers.js","sourceRoot":"","sources":["../src/headers.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAC3D,EAAE;AACF,0EAA0E;AAC1E,sEAAsE;AACtE,wEAAwE;AACxE,2EAA2E;AAC3E,gCAAgC;AAChC,EAAE;AACF,gFAAgF;AAEhF,MAAM,CAAC,MAAM,MAAM,GAAG;IACpB;;;OAGG;IACH,GAAG,EAAE,OAAO;IAEZ,iFAAiF;IACjF,QAAQ,EAAE,gBAAgB;IAE1B,kEAAkE;IAClE,YAAY,EAAE,qBAAqB;IAEnC,wCAAwC;IACxC,OAAO,EAAE,eAAe;IAExB;;;;OAIG;IACH,QAAQ,EAAE,iBAAiB;IAE3B,gFAAgF;IAChF,OAAO,EAAE,eAAe;IAExB,uDAAuD;IACvD,SAAS,EAAE,iBAAiB;IAE5B,gDAAgD;IAChD,OAAO,EAAE,eAAe;IAExB,uEAAuE;IACvE,UAAU,EAAE,kBAAkB;IAE9B,0CAA0C;IAC1C,MAAM,EAAE,cAAc;IAEtB;;;;;;;OAOG;IACH,QAAQ,EAAE,gBAAgB;IAE1B;;;;;;OAMG;IACH,WAAW,EAAE,oBAAoB;IAEjC;;;;;OAKG;IACH,UAAU,EAAE,cAAc;IAC1B;;;;;;;;;OASG;IACH;;;;;;;OAOG;IACH,KAAK,EAAE,aAAa;IAEpB,SAAS,EAAE,aAAa;IACxB;;;;OAIG;IACH,SAAS,EAAE,eAAe;IAC1B,+EAA+E;IAC/E,WAAW,EAAE,eAAe;IAC5B,8FAA8F;IAC9F,UAAU,EAAE,cAAc;CAClB,CAAA;AAEV,sBAAsB;AACtB,MAAM,CAAC,MAAM,WAAW,GAAG,iCAAiC,CAAA;AAE5D,2BAA2B;AAC3B,MAAM,CAAC,MAAM,SAAS,GAAG,0BAA0B,CAAA;AAEnD;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,MAAM,CAAC,GAAG;IACV,MAAM,CAAC,QAAQ;IACf,MAAM,CAAC,UAAU;IACjB,MAAM,CAAC,SAAS;IAChB,MAAM,CAAC,OAAO;CACf,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AAEZ;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,mBAAmB,CAAA;AAE7C;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,oCAAoC,CAAA;AAE9D;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,qCAAqC,CAAA;AAEhE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG;IAClB,MAAM,EAAE,SAAS;IACjB,QAAQ,EAAE,aAAa;IACvB,UAAU,EAAE,eAAe;IAC3B,QAAQ,EAAE,YAAY;IACtB,KAAK,EAAE,YAAY;IACnB,KAAK,EAAE,YAAY;IACnB,uEAAuE;IACvE,YAAY,EAAE,YAAY;CAClB,CAAA;AAEV;;;;;GAKG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,kBAAkB;IAClB,MAAM;IACN,eAAe;IACf,cAAc;IACd,yBAAyB;IACzB,oBAAoB;IACpB,iBAAiB;IACjB,2BAA2B;IAC3B,iBAAiB;IACjB,wBAAwB;IACxB,4BAA4B;IAC5B,8BAA8B;IAC9B,8BAA8B;IAC9B,wBAAwB;CAChB,CAAA","sourcesContent":["// The wire protocol, as names rather than string literals.\n//\n// A host writing these out by hand is how they drift. Two of them are not\n// negotiable at all — the client sends them or asks for them at fixed\n// addresses, and a host that spells one differently fails silently: the\n// request falls through, the decoder never runs, and a button does nothing\n// with no error on either side.\n//\n// PROTOCOL.md describes what each one means. This is the same list, importable.\n\nexport const HEADER = {\n /**\n * Present on a request for a Flight payload rather than the document. One\n * url serves both, which is why every answer must Vary on it.\n */\n rsc: 'X-RSC',\n\n /** The layout chain the client has mounted, outermost first, comma-separated. */\n segments: 'X-RSC-Segments',\n\n /** The boundary the answer replaces. 0 means a whole document. */\n segmentDepth: 'X-RSC-Segment-Depth',\n\n /** The chain to send back next time. */\n layouts: 'X-RSC-Layouts',\n\n /**\n * On a payload request: this url's page said it does not exist, after the\n * shell went out, and the client is asking for the not-found page to put\n * where it was. RedirectBoundary sends it.\n */\n notFound: 'X-RSC-Not-Found',\n\n /** Identifies the build, so a client can notice it is talking to an old one. */\n version: 'X-RSC-Version',\n\n /** The slot an intercepted navigation is targeting. */\n intercept: 'X-RSC-Intercept',\n\n /** Where the navigation or action came from. */\n referer: 'X-RSC-Referer',\n\n /** One named region of the current page to render and return alone. */\n revalidate: 'X-RSC-Revalidate',\n\n /** The server reference being invoked. */\n action: 'X-RSC-Action',\n\n /**\n * Go here instead.\n *\n * Used for a redirect the client has to perform itself: a failed action, and\n * a navigation whose render redirected. Never a 3xx for those — `fetch`\n * follows one transparently, so the client would get the destination's HTML\n * where it expected a Flight payload and decode it as one.\n */\n redirect: 'X-RSC-Redirect',\n\n /**\n * The body's real type.\n *\n * The body itself goes out as application/octet-stream so a host that parses\n * multipart cannot consume it before the action does — reading Content-Type\n * instead leaves an upload undecodable.\n */\n contentType: 'X-RSC-Content-Type',\n\n /**\n * Where the browser posts server actions.\n *\n * Not a convention this can choose: the client runtime posts here\n * unconditionally.\n */\n actionPath: '/_rsc/action',\n /**\n * Where the browser reads queries.\n *\n * A GET, and that is the whole point of it being a separate address: a POST\n * is cacheable by nothing, so a read routed through the action endpoint can\n * never be kept by an HTTP cache, a CDN or a service worker. Only functions\n * declared with `query()` are reachable here — the endpoint checks the mark\n * before invoking anything, because otherwise this address would run any\n * registered action over GET.\n */\n /**\n * Sent on every read, and required by the query endpoint.\n *\n * A GET with no unusual header is a simple request, so any page could\n * trigger one with an <img> and the visitor's cookies would ride along.\n * This header is not CORS-safelisted, so the browser preflights it — the\n * same thing that makes a POST carrying X-RSC-Action safe.\n */\n query: 'X-RSC-Query',\n\n queryPath: '/_rsc/query',\n /**\n * On a refresh a change triggered: which names moved, to which versions\n * (`stock@5,orders@2`). A shared section renders once per such change, and\n * every tab asking with the same one gets that render.\n */\n changedBy: 'X-RSC-Changed',\n /** The stream a tab hears on when a name its page refreshes on has changed. */\n changesPath: '/_rsc/changes',\n /** Whether this renderer can serve: up, and its backend answering. GET only, never cached. */\n healthPath: '/_rsc/health',\n} as const\n\n/** Flight payload. */\nexport const FLIGHT_TYPE = 'text/x-component; charset=utf-8'\n\n/** A rendered document. */\nexport const HTML_TYPE = 'text/html; charset=utf-8'\n\n/**\n * Every request header that changes what a response body contains.\n *\n * One url answers with a whole document, a partial payload, a named region or\n * an interceptor depending on these — so a cache keyed on the url alone, or on\n * `X-RSC` alone, will hand one client another's answer. They are materially\n * different bodies, not variations in presentation.\n */\nexport const VARY_ON_RSC = [\n HEADER.rsc,\n HEADER.segments,\n HEADER.revalidate,\n HEADER.intercept,\n HEADER.referer,\n].join(', ')\n\n/**\n * What a response says about being stored, when it must not be.\n *\n * `Vary` alone is not enough on the platform this targets. Cloudflare ignores\n * `Vary` for everything except `Accept-Encoding`, and this package ships a\n * Workers story as a headline feature — so one url answering with a document,\n * a Flight payload, a segment and an interceptor, keyed only on the url, hands\n * one visitor another's body. Anything narrowed by a request header, and\n * anything behind a guard, says outright that it is not to be stored.\n */\nexport const PER_CLIENT = 'private, no-store'\n\n/**\n * And what a frozen, unguarded page says.\n *\n * Explicit rather than absent: with no directive at all, whether an\n * intermediary stores it comes down to that intermediary's heuristics, which\n * is not a decision this package should be leaving to chance in either\n * direction.\n */\nexport const REVALIDATE = 'public, max-age=0, must-revalidate'\n\n/**\n * And what a page rendered for one request says.\n *\n * It may have read the visitor's cookies, and nothing in the headers - which\n * leave before the render has finished - can know whether it did. So a shared\n * cache may not keep it; the visitor's own browser may, and must ask again.\n */\nexport const PER_REQUEST = 'private, max-age=0, must-revalidate'\n\n/**\n * The edge contract: one marker, one page endpoint, one resume, for any edge\n * and any framework that implements it. Vendor-neutral names on purpose: an\n * edge speaks the contract, and there is no second way in that is rsc-kit's\n * own. docs/reference/edge-contract.mdx is the specification.\n */\nexport const EDGE = {\n prefix: '/_edge/',\n pagePath: '/_edge/page',\n resumePath: '/_edge/resume',\n tokenEnv: 'EDGE_TOKEN',\n token: 'Edge-Token',\n build: 'Edge-Build',\n /** The marker's copy beside the stored pages, which the host reads. */\n storedMarker: '_edge.json',\n} as const\n\n/**\n * The response headers an edge may send with a page it serves from its cache\n * (the contract's `headers`), and so the only ones rscKit({ headers }) sets:\n * one outside this list could not leave with a cached page, and the page would\n * go out without it.\n */\nexport const EDGE_HEADERS = [\n 'Content-Language',\n 'Link',\n 'Cache-Control',\n 'X-Robots-Tag',\n 'Content-Security-Policy',\n 'Permissions-Policy',\n 'Referrer-Policy',\n 'Strict-Transport-Security',\n 'X-Frame-Options',\n 'X-Content-Type-Options',\n 'Cross-Origin-Opener-Policy',\n 'Cross-Origin-Embedder-Policy',\n 'Cross-Origin-Resource-Policy',\n 'X-DNS-Prefetch-Control',\n] as const\n"]}
1
+ {"version":3,"file":"headers.js","sourceRoot":"","sources":["../src/headers.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAC3D,EAAE;AACF,0EAA0E;AAC1E,sEAAsE;AACtE,wEAAwE;AACxE,2EAA2E;AAC3E,gCAAgC;AAChC,EAAE;AACF,gFAAgF;AAEhF,MAAM,CAAC,MAAM,MAAM,GAAG;IACpB;;;OAGG;IACH,GAAG,EAAE,OAAO;IAEZ,iFAAiF;IACjF,QAAQ,EAAE,gBAAgB;IAE1B,kEAAkE;IAClE,YAAY,EAAE,qBAAqB;IAEnC,wCAAwC;IACxC,OAAO,EAAE,eAAe;IAExB;;;;OAIG;IACH,QAAQ,EAAE,iBAAiB;IAE3B,gFAAgF;IAChF,OAAO,EAAE,eAAe;IAExB,uDAAuD;IACvD,SAAS,EAAE,iBAAiB;IAE5B,gDAAgD;IAChD,OAAO,EAAE,eAAe;IAExB,uEAAuE;IACvE,UAAU,EAAE,kBAAkB;IAE9B,0CAA0C;IAC1C,MAAM,EAAE,cAAc;IAEtB;;;;;;;OAOG;IACH,QAAQ,EAAE,gBAAgB;IAE1B;;;;;;OAMG;IACH,WAAW,EAAE,oBAAoB;IAEjC;;;;;OAKG;IACH,UAAU,EAAE,cAAc;IAC1B;;;;;;;;;OASG;IACH;;;;;;;OAOG;IACH,KAAK,EAAE,aAAa;IAEpB,SAAS,EAAE,aAAa;IACxB;;;;OAIG;IACH,SAAS,EAAE,eAAe;IAC1B,+EAA+E;IAC/E,WAAW,EAAE,eAAe;IAC5B,8FAA8F;IAC9F,UAAU,EAAE,cAAc;CAClB,CAAA;AAEV,sBAAsB;AACtB,MAAM,CAAC,MAAM,WAAW,GAAG,iCAAiC,CAAA;AAE5D,2BAA2B;AAC3B,MAAM,CAAC,MAAM,SAAS,GAAG,0BAA0B,CAAA;AAEnD;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,MAAM,CAAC,GAAG;IACV,MAAM,CAAC,QAAQ;IACf,MAAM,CAAC,UAAU;IACjB,MAAM,CAAC,SAAS;IAChB,MAAM,CAAC,OAAO;CACf,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AAEZ;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,mBAAmB,CAAA;AAE7C;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,oCAAoC,CAAA;AAE9D;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,qCAAqC,CAAA;AAEhE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG;IAClB,MAAM,EAAE,SAAS;IACjB,QAAQ,EAAE,aAAa;IACvB,UAAU,EAAE,eAAe;IAC3B,QAAQ,EAAE,YAAY;IACtB,KAAK,EAAE,YAAY;IACnB,KAAK,EAAE,YAAY;IACnB;;;;OAIG;IACH,MAAM,EAAE,aAAa;IACrB,iFAAiF;IACjF,KAAK,EAAE,YAAY;IACnB,iFAAiF;IACjF,gBAAgB,EAAE,cAAc;IAChC,uEAAuE;IACvE,YAAY,EAAE,YAAY;CAClB,CAAA;AAEV;;;;;GAKG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,kBAAkB;IAClB,MAAM;IACN,eAAe;IACf,cAAc;IACd,yBAAyB;IACzB,qCAAqC;IACrC,oBAAoB;IACpB,iBAAiB;IACjB,2BAA2B;IAC3B,iBAAiB;IACjB,wBAAwB;IACxB,4BAA4B;IAC5B,8BAA8B;IAC9B,8BAA8B;IAC9B,wBAAwB;CAChB,CAAA","sourcesContent":["// The wire protocol, as names rather than string literals.\n//\n// A host writing these out by hand is how they drift. Two of them are not\n// negotiable at all — the client sends them or asks for them at fixed\n// addresses, and a host that spells one differently fails silently: the\n// request falls through, the decoder never runs, and a button does nothing\n// with no error on either side.\n//\n// PROTOCOL.md describes what each one means. This is the same list, importable.\n\nexport const HEADER = {\n /**\n * Present on a request for a Flight payload rather than the document. One\n * url serves both, which is why every answer must Vary on it.\n */\n rsc: 'X-RSC',\n\n /** The layout chain the client has mounted, outermost first, comma-separated. */\n segments: 'X-RSC-Segments',\n\n /** The boundary the answer replaces. 0 means a whole document. */\n segmentDepth: 'X-RSC-Segment-Depth',\n\n /** The chain to send back next time. */\n layouts: 'X-RSC-Layouts',\n\n /**\n * On a payload request: this url's page said it does not exist, after the\n * shell went out, and the client is asking for the not-found page to put\n * where it was. RedirectBoundary sends it.\n */\n notFound: 'X-RSC-Not-Found',\n\n /** Identifies the build, so a client can notice it is talking to an old one. */\n version: 'X-RSC-Version',\n\n /** The slot an intercepted navigation is targeting. */\n intercept: 'X-RSC-Intercept',\n\n /** Where the navigation or action came from. */\n referer: 'X-RSC-Referer',\n\n /** One named region of the current page to render and return alone. */\n revalidate: 'X-RSC-Revalidate',\n\n /** The server reference being invoked. */\n action: 'X-RSC-Action',\n\n /**\n * Go here instead.\n *\n * Used for a redirect the client has to perform itself: a failed action, and\n * a navigation whose render redirected. Never a 3xx for those — `fetch`\n * follows one transparently, so the client would get the destination's HTML\n * where it expected a Flight payload and decode it as one.\n */\n redirect: 'X-RSC-Redirect',\n\n /**\n * The body's real type.\n *\n * The body itself goes out as application/octet-stream so a host that parses\n * multipart cannot consume it before the action does — reading Content-Type\n * instead leaves an upload undecodable.\n */\n contentType: 'X-RSC-Content-Type',\n\n /**\n * Where the browser posts server actions.\n *\n * Not a convention this can choose: the client runtime posts here\n * unconditionally.\n */\n actionPath: '/_rsc/action',\n /**\n * Where the browser reads queries.\n *\n * A GET, and that is the whole point of it being a separate address: a POST\n * is cacheable by nothing, so a read routed through the action endpoint can\n * never be kept by an HTTP cache, a CDN or a service worker. Only functions\n * declared with `query()` are reachable here — the endpoint checks the mark\n * before invoking anything, because otherwise this address would run any\n * registered action over GET.\n */\n /**\n * Sent on every read, and required by the query endpoint.\n *\n * A GET with no unusual header is a simple request, so any page could\n * trigger one with an <img> and the visitor's cookies would ride along.\n * This header is not CORS-safelisted, so the browser preflights it — the\n * same thing that makes a POST carrying X-RSC-Action safe.\n */\n query: 'X-RSC-Query',\n\n queryPath: '/_rsc/query',\n /**\n * On a refresh a change triggered: which names moved, to which versions\n * (`stock@5,orders@2`). A shared section renders once per such change, and\n * every tab asking with the same one gets that render.\n */\n changedBy: 'X-RSC-Changed',\n /** The stream a tab hears on when a name its page refreshes on has changed. */\n changesPath: '/_rsc/changes',\n /** Whether this renderer can serve: up, and its backend answering. GET only, never cached. */\n healthPath: '/_rsc/health',\n} as const\n\n/** Flight payload. */\nexport const FLIGHT_TYPE = 'text/x-component; charset=utf-8'\n\n/** A rendered document. */\nexport const HTML_TYPE = 'text/html; charset=utf-8'\n\n/**\n * Every request header that changes what a response body contains.\n *\n * One url answers with a whole document, a partial payload, a named region or\n * an interceptor depending on these — so a cache keyed on the url alone, or on\n * `X-RSC` alone, will hand one client another's answer. They are materially\n * different bodies, not variations in presentation.\n */\nexport const VARY_ON_RSC = [\n HEADER.rsc,\n HEADER.segments,\n HEADER.revalidate,\n HEADER.intercept,\n HEADER.referer,\n].join(', ')\n\n/**\n * What a response says about being stored, when it must not be.\n *\n * `Vary` alone is not enough on the platform this targets. Cloudflare ignores\n * `Vary` for everything except `Accept-Encoding`, and this package ships a\n * Workers story as a headline feature — so one url answering with a document,\n * a Flight payload, a segment and an interceptor, keyed only on the url, hands\n * one visitor another's body. Anything narrowed by a request header, and\n * anything behind a guard, says outright that it is not to be stored.\n */\nexport const PER_CLIENT = 'private, no-store'\n\n/**\n * And what a frozen, unguarded page says.\n *\n * Explicit rather than absent: with no directive at all, whether an\n * intermediary stores it comes down to that intermediary's heuristics, which\n * is not a decision this package should be leaving to chance in either\n * direction.\n */\nexport const REVALIDATE = 'public, max-age=0, must-revalidate'\n\n/**\n * And what a page rendered for one request says.\n *\n * It may have read the visitor's cookies, and nothing in the headers - which\n * leave before the render has finished - can know whether it did. So a shared\n * cache may not keep it; the visitor's own browser may, and must ask again.\n */\nexport const PER_REQUEST = 'private, max-age=0, must-revalidate'\n\n/**\n * The edge contract: one marker, one page endpoint, one resume, for any edge\n * and any framework that implements it. Vendor-neutral names on purpose: an\n * edge speaks the contract, and there is no second way in that is rsc-kit's\n * own. docs/reference/edge-contract.mdx is the specification.\n */\nexport const EDGE = {\n prefix: '/_edge/',\n pagePath: '/_edge/page',\n resumePath: '/_edge/resume',\n tokenEnv: 'EDGE_TOKEN',\n token: 'Edge-Token',\n build: 'Edge-Build',\n /**\n * On a page request, `nonce` says the edge mints a nonce per response: a\n * shell under a Content-Security-Policy is then answered, its policy naming\n * `nonce` (the placeholder below) where the edge puts its own.\n */\n accept: 'Edge-Accept',\n /** On a resume, the nonce the edge put in the policy, for the holes' scripts. */\n nonce: 'Edge-Nonce',\n /** What the edge replaces, in every header value of the page, with its nonce. */\n noncePlaceholder: '{edge-nonce}',\n /** The marker's copy beside the stored pages, which the host reads. */\n storedMarker: '_edge.json',\n} as const\n\n/**\n * The response headers an edge may send with a page it serves from its cache\n * (the contract's `headers`), and so the only ones rscKit({ headers }) sets:\n * one outside this list could not leave with a cached page, and the page would\n * go out without it.\n */\nexport const EDGE_HEADERS = [\n 'Content-Language',\n 'Link',\n 'Cache-Control',\n 'X-Robots-Tag',\n 'Content-Security-Policy',\n 'Content-Security-Policy-Report-Only',\n 'Permissions-Policy',\n 'Referrer-Policy',\n 'Strict-Transport-Security',\n 'X-Frame-Options',\n 'X-Content-Type-Options',\n 'Cross-Origin-Opener-Policy',\n 'Cross-Origin-Embedder-Policy',\n 'Cross-Origin-Resource-Policy',\n 'X-DNS-Prefetch-Control',\n] as const\n"]}
package/dist/host.js CHANGED
@@ -19,7 +19,8 @@ import { apiKey } from "./apiPrerender.js";
19
19
  import { hostPath, hostSegment, routableHost } from "./hostRouting.js";
20
20
  import { withRevalidation } from "./revalidate.js";
21
21
  import { withoutPayloadKey } from "./js/payloadKey.js";
22
- import { cachingFor, createPageCache, finishCacheable, noteReadsSoFar, pageMemoryStore } from "./pageCache.js";
22
+ import { cachingFor, createPageCache, finishCacheable, keptBodyOf, noteReadsSoFar, pageMemoryStore } from "./pageCache.js";
23
+ import { inlineHashes, newNonce, policyHeaderName, policyValue } from "./csp.js";
23
24
  /**
24
25
  * @internal For a host adapter that embeds the engine. An app imports this
25
26
  * from `@rsc-kit/core/revalidate`.
@@ -183,8 +184,18 @@ function redirectResponse(to, isPayloadRequest, revalidated = []) {
183
184
  * runs the page reads it; a crawler that does not run it is answered with
184
185
  * the whole document and a real 404 - see `forCrawler`.
185
186
  */
186
- const LATE_NOINDEX = '<meta name="robots" content="noindex">' +
187
- "<script>document.head.appendChild(document.currentScript.previousSibling)</script>";
187
+ function lateNoindex(nonce) {
188
+ return ('<meta name="robots" content="noindex">' +
189
+ `<script${nonceAttribute(nonce)}>document.head.appendChild(document.currentScript.previousSibling)</script>`);
190
+ }
191
+ /**
192
+ * The nonce a script the host writes into a streamed document carries, so a
193
+ * Content-Security-Policy that allows React's own allows it too. Base64 only,
194
+ * so nothing to escape.
195
+ */
196
+ function nonceAttribute(nonce) {
197
+ return nonce ? ` nonce="${nonce}"` : "";
198
+ }
188
199
  /**
189
200
  * What a browser fetches as part of a page, by the request's own
190
201
  * Sec-Fetch-Dest. A page can never be the answer to one. Not `empty` (a
@@ -211,7 +222,7 @@ function forSubresource(request) {
211
222
  * Read on flush, because that is when the render has finished and a redirect
212
223
  * from inside a Suspense boundary is finally known.
213
224
  */
214
- function appendLateRedirect(stream, taken, missing = () => false) {
225
+ function appendLateRedirect(stream, taken, missing = () => false, nonce) {
215
226
  // An engine that answered with a finished body rather than a stream has no
216
227
  // late window at all: the render was over before this was called, so the
217
228
  // caller's own check already saw everything there was to see.
@@ -233,10 +244,10 @@ function appendLateRedirect(stream, taken, missing = () => false) {
233
244
  const to = taken();
234
245
  // replace, so Back does not return to a url that redirected.
235
246
  if (to) {
236
- controller.enqueue(encoder.encode(`<script>location.replace(${inScript(to.location)})</script>`));
247
+ controller.enqueue(encoder.encode(`<script${nonceAttribute(nonce)}>location.replace(${inScript(to.location)})</script>`));
237
248
  }
238
249
  else if (missing()) {
239
- controller.enqueue(encoder.encode(LATE_NOINDEX));
250
+ controller.enqueue(encoder.encode(lateNoindex(nonce)));
240
251
  }
241
252
  controller.close();
242
253
  },
@@ -588,7 +599,26 @@ export function createRscHandler(options) {
588
599
  const identify = Boolean(manifest.build?.identify);
589
600
  // rscKit({ headers }): every response, and every page an edge serves.
590
601
  const pageHeaders = manifest.build?.headers ?? {};
591
- const hasPageHeaders = Object.keys(pageHeaders).length > 0;
602
+ // rscKit({ contentSecurityPolicy }): the author's policy, plus what each
603
+ // document's own inline code needs - see csp.ts.
604
+ const policy = manifest.build?.contentSecurityPolicy;
605
+ const policyName = policy ? policyHeaderName(policy) : "";
606
+ /** The nonce a request's render puts on its scripts: only one rendered for it, never one a cache keeps. */
607
+ const nonces = new WeakMap();
608
+ /** Answers that are a page's document, the only ones the policy is written for. */
609
+ const documents = new WeakSet();
610
+ /** What a stored document or shell's inline code hashes to, known before it is sent. */
611
+ const hashedAs = new WeakMap();
612
+ const hashesByFile = new Map();
613
+ /** A stored file's hashes, worked out once: the file is the same until the next build. */
614
+ async function hashesOfFile(name, html) {
615
+ let found = hashesByFile.get(name);
616
+ if (!found) {
617
+ found = await inlineHashes(html);
618
+ hashesByFile.set(name, found);
619
+ }
620
+ return found;
621
+ }
592
622
  /** How a response was answered, for X-RSC-Kit: a file the build wrote, or a shell of one. */
593
623
  const servedFrom = new WeakMap();
594
624
  /** What a stored document's head names, read once per file, for the Link header. */
@@ -789,6 +819,10 @@ export function createRscHandler(options) {
789
819
  withResponseDraft(async ({ taken, seal }) => {
790
820
  if (caching)
791
821
  renderAsNobody();
822
+ // A render a cache may keep goes out the same for everyone, so it
823
+ // gets no nonce: its scripts are hashed once its body is whole.
824
+ if (policy && !(caching && !caching.refused))
825
+ nonces.set(request, newNonce());
792
826
  const rendered = await route(request);
793
827
  seal();
794
828
  if (!rendered) {
@@ -800,6 +834,7 @@ export function createRscHandler(options) {
800
834
  }
801
835
  let response = rendered;
802
836
  const collected = taken();
837
+ const isDocument = documents.has(rendered);
803
838
  // Under whatever the answer already has, and before the middleware's,
804
839
  // so a page or a middleware that asked for its own value keeps it.
805
840
  for (const [name, value] of Object.entries(pageHeaders)) {
@@ -828,6 +863,22 @@ export function createRscHandler(options) {
828
863
  if (hints)
829
864
  hinted.set(response, hints);
830
865
  }
866
+ // The policy, with this document's own inline code allowed: by hash
867
+ // when its body was whole before it left - a stored page, a shell, a
868
+ // page a cache keeps, read in full by finishCacheable - and by the
869
+ // nonce its render used when it streams. Before pages.keep, which
870
+ // keeps the headers with the page. A middleware's own policy is left
871
+ // as it is.
872
+ if (policy && isDocument && !response.headers.has(policyName)) {
873
+ const from = servedFrom.get(response);
874
+ const nonce = from === "stored" ? undefined : nonces.get(request);
875
+ let hashes = hashedAs.get(response) ?? null;
876
+ if (!hashes && !nonce) {
877
+ const kept = keptBodyOf(response);
878
+ hashes = await inlineHashes(kept ? new TextDecoder().decode(kept) : await response.clone().text());
879
+ }
880
+ response.headers.set(policyName, policyValue(policy, { hashes, nonce }));
881
+ }
831
882
  // How this answer was served - the header a developer reads in the
832
883
  // Network tab, the way X-Nextjs-Cache is. Always: it names no
833
884
  // product, and a CDN rule or a check can key on it.
@@ -1114,8 +1165,8 @@ export function createRscHandler(options) {
1114
1165
  const letGo = () => void rscPayload?.cancel().catch(() => { });
1115
1166
  try {
1116
1167
  ({ htmlStream, rscPayload } = formPost
1117
- ? await engine.handleRscFormPost(match.route.component, props, layouts, match.route.loadings, match.route.slots, {}, undefined, url.pathname, true, formPost)
1118
- : await engine.handleRscHtmlStream(match.route.component, props, layouts, match.route.loadings, match.route.slots, {}, undefined, url.pathname,
1168
+ ? await engine.handleRscFormPost(match.route.component, props, layouts, match.route.loadings, match.route.slots, {}, nonces.get(request), url.pathname, true, formPost)
1169
+ : await engine.handleRscHtmlStream(match.route.component, props, layouts, match.route.loadings, match.route.slots, {}, nonces.get(request), url.pathname,
1119
1170
  // A route that ships no runtime gets no bootstrap and no segment
1120
1171
  // boundary — the boundary is itself a client component, so leaving
1121
1172
  // it in means no page could ever be JS-free.
@@ -1170,7 +1221,7 @@ export function createRscHandler(options) {
1170
1221
  const body = rscPayload
1171
1222
  ? inlineFlight(htmlStream, rscPayload, inlineFlightStart(chain.join(",")))
1172
1223
  : htmlStream;
1173
- return new Response(appendLateRedirect(body, taken, missing), {
1224
+ const answered = new Response(appendLateRedirect(body, taken, missing, nonces.get(request)), {
1174
1225
  headers: withVersion({
1175
1226
  "Content-Type": HTML_TYPE,
1176
1227
  [HEADER.layouts]: chain.join(","),
@@ -1186,6 +1237,8 @@ export function createRscHandler(options) {
1186
1237
  : PER_REQUEST,
1187
1238
  }),
1188
1239
  });
1240
+ documents.add(answered);
1241
+ return answered;
1189
1242
  });
1190
1243
  }
1191
1244
  const from = sharedDepth(request.headers.get(HEADER.segments), chain);
@@ -1304,21 +1357,31 @@ export function createRscHandler(options) {
1304
1357
  headers: { "content-type": "application/json", "cache-control": "no-store" },
1305
1358
  });
1306
1359
  }
1307
- /** Whether a health probe sent this deployment's host-call secret, compared in constant time. */
1360
+ /**
1361
+ * Whether a health probe sent this deployment's host-call secret, compared in
1362
+ * constant time - or the one it replaced, while RSC_HOST_CALL_SECRET_PREVIOUS
1363
+ * still names it, so a rotation fails no probe.
1364
+ */
1308
1365
  function probeHoldsSecret(request) {
1309
- return holdsSecret(request, "x-rsc-host-secret", "RSC_HOST_CALL_SECRET");
1366
+ return holdsSecret(request, "x-rsc-host-secret", "RSC_HOST_CALL_SECRET", "RSC_HOST_CALL_SECRET_PREVIOUS");
1310
1367
  }
1311
- /** Whether the request's header holds the secret in the environment's variable, compared in constant time. */
1312
- function holdsSecret(request, header, variable) {
1313
- const expected = (typeof process === "undefined" ? undefined : process.env[variable]) ?? "";
1368
+ /** Whether the request's header holds the secret in one of the environment's variables, compared in constant time. */
1369
+ function holdsSecret(request, header, ...variables) {
1314
1370
  const given = request.headers.get(header) ?? "";
1315
- // An unset secret matches nothing, the empty string included.
1316
- if (expected === "" || given.length !== expected.length)
1317
- return false;
1318
- let differ = 0;
1319
- for (let i = 0; i < expected.length; i++)
1320
- differ |= expected.charCodeAt(i) ^ given.charCodeAt(i);
1321
- return differ === 0;
1371
+ let held = false;
1372
+ // Every variable is compared, not the first match returned: how long the
1373
+ // check takes says nothing about which one held.
1374
+ for (const variable of variables) {
1375
+ const expected = (typeof process === "undefined" ? undefined : process.env[variable]) ?? "";
1376
+ // An unset secret matches nothing, the empty string included.
1377
+ if (expected === "" || given.length !== expected.length)
1378
+ continue;
1379
+ let differ = 0;
1380
+ for (let i = 0; i < expected.length; i++)
1381
+ differ |= expected.charCodeAt(i) ^ given.charCodeAt(i);
1382
+ held = held || differ === 0;
1383
+ }
1384
+ return held;
1322
1385
  }
1323
1386
  async function frozenApi(request, url, api) {
1324
1387
  if (isGuarded(api))
@@ -1409,16 +1472,6 @@ export function createRscHandler(options) {
1409
1472
  // component reading the search params would otherwise find `?url=…`.
1410
1473
  // Absolute, as the request's own url is: searchParams() parses it whole.
1411
1474
  return await withUrl(target.href, async () => {
1412
- // The same refusal the document would get, before a byte of the holes
1413
- // is rendered. Nothing below runs for a caller this turns away.
1414
- const refusal = await refuseUnlessAllowed(request, route);
1415
- if (refusal === RENDER_NOT_FOUND)
1416
- return new Response("Not found", { status: 404 });
1417
- if (refusal)
1418
- return refusal;
1419
- if (!engine.handleRscResume) {
1420
- return new Response("This engine cannot resume", { status: 500 });
1421
- }
1422
1475
  const key = storedKeyFor(pathname, route);
1423
1476
  if (key === null)
1424
1477
  return new Response("No such page", { status: 404 });
@@ -1433,7 +1486,29 @@ export function createRscHandler(options) {
1433
1486
  const state = shellKey === null ? null : await read(`${shellKey}.postponed.json`);
1434
1487
  if (state === null)
1435
1488
  return new Response("Nothing to resume", { status: 404 });
1436
- const { htmlStream } = await engine.handleRscResume(route.route.component, route.params, route.route.layouts.map((component) => ({ component, props: {} })), route.route.loadings, route.route.slots, {}, JSON.parse(state), undefined, shellKey === key ? pathname : "", pathname);
1489
+ // Under a policy the holes' scripts run only by the nonce the edge put
1490
+ // in the page's policy. Without one they would be refused in the
1491
+ // browser, so they are refused here, where the edge can see it.
1492
+ const nonce = policy ? edgeNonceOf(request) : undefined;
1493
+ // Checked before the route's middleware runs, and only once the path is
1494
+ // a shell: a resume for any other path is a 404 with or without a
1495
+ // nonce, so a 400 always means an edge that failed to send one.
1496
+ if (policy && !nonce) {
1497
+ return new Response(`A resume under a Content-Security-Policy needs the ${EDGE.nonce} the page's policy names`, {
1498
+ status: 400,
1499
+ });
1500
+ }
1501
+ // The same refusal the document would get, before a byte of the holes
1502
+ // is rendered. Nothing below runs for a caller this turns away.
1503
+ const refusal = await refuseUnlessAllowed(request, route);
1504
+ if (refusal === RENDER_NOT_FOUND)
1505
+ return new Response("Not found", { status: 404 });
1506
+ if (refusal)
1507
+ return refusal;
1508
+ if (!engine.handleRscResume) {
1509
+ return new Response("This engine cannot resume", { status: 500 });
1510
+ }
1511
+ const { htmlStream } = await engine.handleRscResume(route.route.component, route.params, route.route.layouts.map((component) => ({ component, props: {} })), route.route.loadings, route.route.slots, {}, JSON.parse(state), nonce, shellKey === key ? pathname : "", pathname);
1437
1512
  // Carries the build version so a caller holding a cached shell can tell
1438
1513
  // that it no longer belongs to this origin. A shell from an older build
1439
1514
  // does not make the resume fail — it replays against slots that have
@@ -1475,6 +1550,22 @@ export function createRscHandler(options) {
1475
1550
  });
1476
1551
  }
1477
1552
  }
1553
+ /** Whether the edge mints a nonce per response: `Edge-Accept: nonce`. */
1554
+ function acceptsNonce(request) {
1555
+ return (request.headers.get(EDGE.accept) ?? "")
1556
+ .split(",")
1557
+ .some((token) => token.trim().toLowerCase() === "nonce");
1558
+ }
1559
+ /**
1560
+ * The nonce the edge minted, when it is one: base64 or base64url of at
1561
+ * least 128 bits, bounded at 128 characters, as the shared contract pins it
1562
+ * (an edge sends 16 bytes, padded: 24). Anything else is no nonce, never a
1563
+ * guess.
1564
+ */
1565
+ function edgeNonceOf(request) {
1566
+ const nonce = request.headers.get(EDGE.nonce)?.trim() ?? "";
1567
+ return /^[A-Za-z0-9+/_-]{22,128}={0,2}$/.test(nonce) ? nonce : undefined;
1568
+ }
1478
1569
  async function edgeContractAnswer(request, url) {
1479
1570
  const missing = new Response("Not found", { status: 404 });
1480
1571
  const read = options.prerendered;
@@ -1492,9 +1583,26 @@ export function createRscHandler(options) {
1492
1583
  // Whole only for a path the marker names, and only from the document
1493
1584
  // the build stored for it; anything else is a shell or nothing.
1494
1585
  const complete = marker.static.has(asked);
1586
+ // A shell under a policy needs a nonce for its holes, which only an
1587
+ // edge that mints one per response can give it. Any other edge would
1588
+ // send the placeholder as it is, and the holes would be refused.
1589
+ const edgeNonce = !complete && policy !== undefined;
1590
+ if (edgeNonce && !acceptsNonce(request))
1591
+ return missing;
1495
1592
  const html = complete ? await pageAt(pathname, read) : await shellAt(pathname, read);
1496
1593
  if (html instanceof Response)
1497
1594
  return html;
1595
+ // The page's policy with its own hashes, as the app sends it - and for
1596
+ // a shell, the placeholder where the edge puts the nonce it mints.
1597
+ const headers = policy
1598
+ ? {
1599
+ ...pageHeaders,
1600
+ [policyName]: policyValue(policy, {
1601
+ hashes: await hashesOfFile(`edge|${asked}`, html),
1602
+ nonce: edgeNonce ? EDGE.noncePlaceholder : null,
1603
+ }),
1604
+ }
1605
+ : pageHeaders;
1498
1606
  return new Response(request.method === "HEAD"
1499
1607
  ? null
1500
1608
  : JSON.stringify({
@@ -1503,8 +1611,9 @@ export function createRscHandler(options) {
1503
1611
  html,
1504
1612
  state: "",
1505
1613
  ...(complete ? { complete: true } : {}),
1614
+ ...(edgeNonce ? { nonce: EDGE.noncePlaceholder } : {}),
1506
1615
  // What the page itself goes out with, so the edge's copy does too.
1507
- ...(hasPageHeaders ? { headers: pageHeaders } : {}),
1616
+ ...(Object.keys(headers).length ? { headers } : {}),
1508
1617
  }), {
1509
1618
  headers: {
1510
1619
  "Content-Type": "application/json",
@@ -1610,6 +1719,9 @@ export function createRscHandler(options) {
1610
1719
  }
1611
1720
  hinted.set(response, found);
1612
1721
  storedAs.set(response, `${key}.html`);
1722
+ documents.add(response);
1723
+ if (policy)
1724
+ hashedAs.set(response, await hashesOfFile(`${key}.html`, whole));
1613
1725
  return response;
1614
1726
  }
1615
1727
  // Then a shell, under this url or under the route's pattern. Which of the
@@ -1680,7 +1792,7 @@ export function createRscHandler(options) {
1680
1792
  ? route.params
1681
1793
  : Object.fromEntries(Object.keys(route.params).map((name) => [name, PARAM_PLACEHOLDER]));
1682
1794
  // In a render scope, so a notFound() in a hole is recorded for the
1683
- // stream's end - see LATE_NOINDEX.
1795
+ // stream's end - see lateNoindex.
1684
1796
  let missing = () => false;
1685
1797
  const resume = engine.handleRscResume;
1686
1798
  const { htmlStream, replayed, rscPayload } = await withRedirect((_, said) => {
@@ -1691,7 +1803,10 @@ export function createRscHandler(options) {
1691
1803
  // key — so an argument that differs from the frozen render at all is a
1692
1804
  // tree that "doesn't match", and every boundary falls back to the
1693
1805
  // client instead of being filled here.
1694
- route.route.layouts.map((component) => ({ component, props: {} })), route.route.loadings, route.route.slots, {}, JSON.parse(state), undefined,
1806
+ route.route.layouts.map((component) => ({ component, props: {} })), route.route.loadings, route.route.slots, {}, JSON.parse(state),
1807
+ // React's scripts that move each hole into place are written now,
1808
+ // for this request, so they carry its nonce.
1809
+ nonces.get(request),
1695
1810
  // A shell found under the route's pattern was frozen for no particular
1696
1811
  // url, so it was rendered with no page key. Handing one over now would
1697
1812
  // key the tree differently from the one being resumed.
@@ -1729,7 +1844,7 @@ export function createRscHandler(options) {
1729
1844
  controller.enqueue(value);
1730
1845
  }
1731
1846
  if (missing())
1732
- controller.enqueue(new TextEncoder().encode(LATE_NOINDEX));
1847
+ controller.enqueue(new TextEncoder().encode(lateNoindex(nonces.get(request))));
1733
1848
  }
1734
1849
  finally {
1735
1850
  controller.close();
@@ -1757,6 +1872,10 @@ export function createRscHandler(options) {
1757
1872
  }),
1758
1873
  });
1759
1874
  servedFrom.set(withHoles, "shell");
1875
+ documents.add(withHoles);
1876
+ // The shell's own scripts by hash, the holes' by the nonce.
1877
+ if (policy)
1878
+ hashedAs.set(withHoles, await hashesOfFile(`${shellKey}.ppr.html`, shell));
1760
1879
  // The shell's head is the document's head; its fonts are known too.
1761
1880
  let found = hintsByKey.get(shellKey);
1762
1881
  if (!found) {