Skip to content

Commit da524c2

Browse files
authored
fix(router): PPR gate honors a token-set per-request nonce (issue #656) (#657)
The PPR axis-1 safety gate only saw a nonce produced by the createRouter({ nonce }) provider (threaded as the `nonce` param). A per-request nonce set via the `nonce` ContextVar token in middleware (ctx.set(nonce, value)) left the threaded param undefined, so a ppr route sailed through the gate, entered capture, and baked the capture request's nonce into the SHARED shell; on a HIT that frozen nonce was served to every visitor and the browser's CSP rejected the nonced scripts for all but the capture request. The gate now reads the token off the post-middleware request variables at the commit point (nonce ?? contextGet(reqCtx._variables, nonceToken)) — sound because the commit point runs after the whole middleware chain. A declared-but- gated route logs a once-per-key warning (warnPprNonceActiveOnce, mirroring warnShellStoreMissingOnce) and serves pure axis 1 with no x-rango-shell header; non-ppr routes stay silent and zero-cost. Capture internals are untouched — the single gate guards both serve and capture scheduling. Tests: unit gate matrix (token-set blocks + no getShell/no schedule, provider blocks, warn-once per key naming the route, non-ppr+token = no warn); e2e test-app shell-cache + cloudflare-basic ppr-shell (dev+prod) — a new ppr route whose route-DSL middleware() sets crypto.randomUUID() via the token stays off HIT across repeated GETs with a DISTINCT nonce each. Docs: ppr SKILL, design scar-tissue note, feature-map/feature-file-map.
1 parent 26b6194 commit da524c2

14 files changed

Lines changed: 560 additions & 117 deletions

File tree

‎packages/rangojs-router/docs/design/ppr-shell-resume.md‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ request ──> global middleware chain (router.use(), onion)
8181
└─> route DSL middleware() (executeRender onion)
8282
└─> handleRscRenderingInner <-- THE COMMIT POINT
8383
ppr config off the classified route snapshot
84+
nonce check (provider OR token; warn-once + axis 1 if set)
8485
store family check (warn-once + axis 1 if absent)
8586
getSSRSetup (allReady => bypass, axis 1)
8687
getShell(key)
@@ -103,6 +104,24 @@ headers are committed at the flush — a failing hole cannot become a
103104
Suspense/error boundaries), and a near-unreachable redirecting match on a HIT
104105
degrades to a client-side `location.replace` script.
105106

107+
### The per-request nonce gate reads the token, not just the provider (scar tissue)
108+
109+
A per-request CSP nonce pins the route to axis 1: `useNonce()` renders it into
110+
every nonced script/style/meta, so a shell shared per host+URL cannot bake it
111+
without freezing one request's nonce for every visitor. The gate originally
112+
checked ONLY the `createRouter({ nonce })` provider value (threaded into
113+
`handleRscRendering` as the `nonce` param). But a nonce can also arrive via the
114+
`nonce` ContextVar TOKEN written in middleware (`ctx.set(nonce, value)`), and
115+
that path left the threaded param `undefined` — so a token-set nonce sailed
116+
through the gate, entered capture, and baked the capture request's nonce into
117+
the shared shell (issue #656). The fix reads the token off the post-middleware
118+
request variables AT the commit point: `nonce ?? contextGet(reqCtx._variables,
119+
nonceToken)`. This is only sound because the commit point runs after the whole
120+
middleware chain — the token write is already present. A declared-but-gated
121+
route logs a once-per-key warning (`warnPprNonceActiveOnce`, mirroring
122+
`warnShellStoreMissingOnce`) and serves pure axis 1 with no `x-rango-shell`
123+
header; an undeclared route stays silent.
124+
106125
### Theme fidelity on resume (scar tissue)
107126

108127
This started as a user-reported bug: PPR'd blog routes rendered LIGHT for a
@@ -499,8 +518,10 @@ once-per-key warning, since the declared intent cannot be honored).
499518
commit point: `resolvePprConfig` (normalizes the route's `ppr` option;
500519
`DEFAULT_PPR_TTL_SECONDS` = 300), `buildShellKey`
501520
(`${host}${pathname}${sortedSearch}:shell` — host-scoped so multi-tenant shells
502-
never collide), `isValidShellHit` (reactVersion gate), `hasShellFamily`, and
503-
the once-per-key missing-store-family warning. The route's ppr config is read
521+
never collide), `isValidShellHit` (reactVersion gate), `hasShellFamily`, the
522+
once-per-key missing-store-family warning, and `warnPprNonceActiveOnce` (the
523+
once-per-key active-per-request-nonce warning; see the nonce-gate scar tissue
524+
above). The route's ppr config is read
504525
off the CLASSIFIED route snapshot (`reqCtx._classifiedRoute.manifestEntry`),
505526
which the RSC handler stores before dispatching the render — available before
506527
`match()` runs, which is what makes the eager HIT flush possible.

‎packages/rangojs-router/docs/internal/feature-file-map.md‎

Lines changed: 41 additions & 41 deletions
Large diffs are not rendered by default.

‎packages/rangojs-router/docs/internal/feature-map.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ Route-local schema definitions (`search` option), typed route param types (`Rout
211211
- `"use cache"` directive runtime wrappers, response route cache layer
212212
- SWR background revalidation re-establishes the request-context ALS (so a cached body reading `getRequestContext()` resolves off the request's I/O context on workerd); profile opt-in `foregroundOnAction` re-executes a stale entry in the foreground during a server action's revalidation render (fresh action response) instead of serving stale + background-revalidating
213213
- Tag-based invalidation: `cacheTag()` (runtime) + `cache({ tags })` (static/dynamic); `updateTag()` (awaitable, read-your-own-writes) and `revalidateTag()` (background, non-blocking — both hard-purge; the only difference is awaitability) fan out to the store-level `invalidateTags()` (the whole tag batch in one call). Built-in stores index tags; the CF store keeps markers in its own KV (single-store, no companion tag store), and the tag-marker reads inherit the L1/L2 latency budgets and fail open. Explicit `cache({ store })` stores are registered for invalidation via a handler-owned, LRU-bounded registry. Document-cache entries are tagged with the request's tag union so they are tag-invalidatable too.
214-
- PPR shell caching (the `ppr` path option; `PartialPrerenderProps` exported from the root) — an opt-in second render axis, integral to the router (no middleware). It caches the rendered HTML shell (React `prerender`'s prelude bytes plus the `postponed` resume state, one coupled `ShellCacheEntry`) and, on a hit, commits the composed response after the WHOLE middleware chain: prelude bytes flush first, then fizz resumes only the holes; the browser sees one ordinary streamed document. Holes are render-defined — `loading()` subtrees (structural; loaders masked at capture), pending promises in handed-over data under the consumer's Suspense (physics), everything else shell (top-level pushed handle promises are awaited pre-SSR and baked; the capture gate holds for that await). The background capture is mixed-chain (cached segments replay, uncached handlers execute — the cookies()/headers() capture guard is load-bearing) and never re-runs middleware (the derived context inherits post-middleware state). Backed by the optional `getShell`/`putShell` store family (memory/CF/Vercel), reactVersion-gated and tag-invalidatable. Shell/payload PARITY on a HIT is guaranteed by the CAPTURE DATA SNAPSHOT (`cache/shell-snapshot.ts`, internal): a pre-render write barrier settles the foreground's deferred cache writes so the capture replays the foreground's cache generation (never clobbers it); the capture render records its cache-store read-hits + writes (`RecordingShellStore`, excluding the shell family; `captureAndStoreShell` fires the capture's isolated `onResponse` so the ring-3 segment write runs and is recorded), stores them on `ShellCacheEntry.snapshot` (carried through the CF/Vercel envelopes), and `serveShellHit`'s tail render replays them AS FRESH (`SeededShellStore`) so a shell-baked cached value that DRIFTED (shorter-ttl `cache()`, tag-invalidated item) still matches the frozen prelude — parity beats freshness inside the shell; freshness comes from holes, the shell ttl/swr, and `ppr.tags`. Actions, progressive enhancement, per-request nonce, and `streamMode: "allReady"` (the SEO/bot story) always take axis 1. See [PPR shell caching design](../design/ppr-shell-resume.md).
214+
- PPR shell caching (the `ppr` path option; `PartialPrerenderProps` exported from the root) — an opt-in second render axis, integral to the router (no middleware). It caches the rendered HTML shell (React `prerender`'s prelude bytes plus the `postponed` resume state, one coupled `ShellCacheEntry`) and, on a hit, commits the composed response after the WHOLE middleware chain: prelude bytes flush first, then fizz resumes only the holes; the browser sees one ordinary streamed document. Holes are render-defined — `loading()` subtrees (structural; loaders masked at capture), pending promises in handed-over data under the consumer's Suspense (physics), everything else shell (top-level pushed handle promises are awaited pre-SSR and baked; the capture gate holds for that await). The background capture is mixed-chain (cached segments replay, uncached handlers execute — the cookies()/headers() capture guard is load-bearing) and never re-runs middleware (the derived context inherits post-middleware state). Backed by the optional `getShell`/`putShell` store family (memory/CF/Vercel), reactVersion-gated and tag-invalidatable. Shell/payload PARITY on a HIT is guaranteed by the CAPTURE DATA SNAPSHOT (`cache/shell-snapshot.ts`, internal): a pre-render write barrier settles the foreground's deferred cache writes so the capture replays the foreground's cache generation (never clobbers it); the capture render records its cache-store read-hits + writes (`RecordingShellStore`, excluding the shell family; `captureAndStoreShell` fires the capture's isolated `onResponse` so the ring-3 segment write runs and is recorded), stores them on `ShellCacheEntry.snapshot` (carried through the CF/Vercel envelopes), and `serveShellHit`'s tail render replays them AS FRESH (`SeededShellStore`) so a shell-baked cached value that DRIFTED (shorter-ttl `cache()`, tag-invalidated item) still matches the frozen prelude — parity beats freshness inside the shell; freshness comes from holes, the shell ttl/swr, and `ppr.tags`. Actions, progressive enhancement, per-request nonce (BOTH the `createRouter({ nonce })` provider AND a `ctx.set(nonce, …)` token write in middleware — the gate reads the token off the post-middleware request variables at the commit point, warning once per key that a declared route cannot be honored), and `streamMode: "allReady"` (the SEO/bot story) always take axis 1. See [PPR shell caching design](../design/ppr-shell-resume.md).
215215

216216
### Error and Control Flow
217217

‎packages/rangojs-router/e2e/shell-cache.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -483,6 +483,61 @@ function runShellCacheSpec(f: Fixture): void {
483483
// caching, never the route. (The once-per-key capture warning is a worker-side
484484
// console.warn — not observable through this Playwright harness; it is pinned by
485485
// the unit test in src/rsc/__tests__/shell-capture.test.ts.)
486+
// --- Per-request nonce via the ContextVar token: ppr stays on axis 1 (#656) ---
487+
//
488+
// /shell-cache/nonce-token sets a fresh per-request nonce via the `nonce` token
489+
// in ROUTE middleware (ctx.set(nonce, crypto.randomUUID())). A shell is shared
490+
// per host+URL, so capturing it would freeze one request's nonce for every
491+
// visitor and break CSP. The commit-point gate reads the token AFTER the route
492+
// middleware runs, so a token nonce gates PPR exactly like a provider nonce:
493+
// pure axis 1, NO capture. Like the missing-store diagnostic, a nonce-gated ppr
494+
// route emits NO x-rango-shell header (it never participates in PPR) — so it can
495+
// never flip to HIT, and every GET carries a DISTINCT nonce. That also pins the
496+
// commit-point ordering: the DSL middleware's token write is visible to the
497+
// gate. Before the fix the gate only saw the provider-threaded nonce, so this
498+
// route entered capture (tagged MISS) and would have frozen one nonce for all.
499+
//
500+
// (The once-per-key worker warning is a server-side console.warn — not
501+
// observable through this Playwright harness; it is pinned by the unit test in
502+
// src/rsc/__tests__/rsc-rendering-shell-ppr.test.ts.)
503+
test("token nonce (route middleware) keeps a ppr route on axis 1: repeated GETs never HIT and carry a distinct nonce each", async ({
504+
request,
505+
}) => {
506+
const url = f.url("/shell-cache/nonce-token?probe=noncetoken");
507+
const seen = new Set<string>();
508+
509+
// Space GETs past the background-capture window so, if the gate wrongly
510+
// allowed capture, a later GET would flip to HIT and freeze one nonce.
511+
for (let i = 0; i < 4; i++) {
512+
const res = await request.get(url, { headers: HTML_HEADERS });
513+
expect(res.status()).toBe(200);
514+
// Nonce-gated: pure axis 1, no PPR participation — never a HIT, no header
515+
// (mirrors the missing-store diagnostic; the warn-once explains why).
516+
expect(
517+
res.headers()["x-rango-shell"],
518+
`request #${i} must never HIT (token nonce forces axis 1)`,
519+
).not.toBe("HIT");
520+
521+
const html = await res.text();
522+
const value = /data-nonce="([^"]+)"/.exec(html)?.[1];
523+
expect(
524+
value,
525+
"the per-request nonce is rendered into the shell",
526+
).toBeTruthy();
527+
expect(value).not.toBe("(none)");
528+
seen.add(value!);
529+
530+
// The live price hole still renders fresh under axis 1.
531+
expect(html).toContain("Live price:");
532+
533+
if (i < 3) await new Promise((r) => setTimeout(r, 350));
534+
}
535+
536+
// Per-request freshness: a distinct nonce every request. A frozen shared shell
537+
// (the bug) would have served ONE nonce across all four.
538+
expect(seen.size).toBe(4);
539+
});
540+
486541
test("no loading(): stays MISS across repeated GETs while the inner promise still streams", async ({
487542
request,
488543
}) => {

‎packages/rangojs-router/e2e/test-app/src/router.named-routes.gen.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,7 @@ export const NamedRoutes = {
324324
shellCacheActionPe: "/shell-cache-action/pe",
325325
shellCacheDrift: "/shell-cache/drift",
326326
shellCacheNoHole: "/shell-cache/no-hole",
327+
shellCacheNonceToken: "/shell-cache/nonce-token",
327328
shellCacheStream: "/shell-cache/stream",
328329
shellSecure: "/shell-secure",
329330
shellSecureDsl: "/shell-secure-dsl",

‎packages/rangojs-router/e2e/test-app/src/urls/shell-cache.tsx‎

Lines changed: 118 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { urls, Meta, Breadcrumbs } from "@rangojs/router";
1+
import { urls, Meta, Breadcrumbs, nonce } from "@rangojs/router";
22
import type { HandlerContext } from "@rangojs/router";
33
import { Link, Outlet } from "@rangojs/router/client";
44
import {
@@ -114,59 +114,123 @@ function ShellDriftPricePage() {
114114
return <ShellCachePrice loader={ShellPriceLoader} />;
115115
}
116116

117-
export const shellCachePatterns = urls(({ path, layout, loader, loading }) => [
118-
layout(ShellCacheLayout, () => [
119-
// ppr carries the WHOLE shell policy (ttl/swr/tags); no middleware exists.
120-
path(
121-
"/shell-cache",
122-
ShellCachePricePage,
123-
{ name: "shellCache", ppr: { ttl: 300, swr: 120 } },
124-
() => [
125-
loader(ShellPriceLoader),
126-
loading(<div data-testid="shell-price-fallback">Loading price...</div>),
127-
],
128-
),
129-
// Loader-carried promise WITH loading(): the loading() boundary is the hole.
130-
// On a HIT the resume streams three layers in one body — cached shell, then
131-
// the outer loader value + the inner Suspense fallback, then the
132-
// nested-promise inner value + $RC.
133-
path(
134-
"/shell-cache/stream",
135-
ShellCacheStreamPage,
136-
{ name: "shellCacheStream", ppr: { ttl: 300, swr: 120 } },
137-
() => [
138-
loader(ShellStreamLoader),
139-
loading(
140-
<div data-testid="shell-stream-fallback">Loading stream...</div>,
141-
),
142-
],
143-
),
144-
// Same loader/component, ppr DECLARED, but NO loading(): the loading-less
145-
// branch awaits loader data at tree-build, so capture's masked loader pins
146-
// the tree and the sanity gate refuses — x-rango-shell stays MISS forever
147-
// (plus the once-per-key warning). The nested inner promise still streams
148-
// under axis 1 (no loading() degrades only the caching, never the route).
149-
path(
150-
"/shell-cache/no-hole",
151-
ShellCacheStreamPage,
152-
{ name: "shellCacheNoHole", ppr: true },
153-
() => [loader(ShellStreamLoader)],
154-
),
155-
]),
156-
// Capture-data-snapshot DRIFT route: the shell bakes a value from a short-ttl
157-
// cache() (getDriftStamp, "drift" profile, ttl 1s); the shell's own ttl is 300.
158-
// After the inner ttl expires, a HIT must still show the CAPTURE-time stamp
159-
// (seeded from the snapshot) — byte parity with the frozen prelude — while the
160-
// price loader hole stays live. See docs/design/ppr-shell-resume.md.
161-
layout(ShellDriftLayout, () => [
162-
path(
163-
"/shell-cache/drift",
164-
ShellDriftPricePage,
165-
{ name: "shellCacheDrift", ppr: { ttl: 300, swr: 120 } },
117+
// Per-request CSP nonce set via the `nonce` ContextVar token in ROUTE middleware
118+
// (issue #656). A shell is shared per host+URL, so baking one request's nonce into
119+
// it would serve a frozen nonce to every visitor and break CSP for all but the
120+
// capture request. A ppr route with an active per-request nonce — from the
121+
// createRouter({ nonce }) provider OR a ctx.set(nonce, …) token write — must stay
122+
// on axis 1 (x-rango-shell: MISS) with a once-per-key worker warning.
123+
//
124+
// The layout reads ctx.get(nonce) and renders it into the SHELL region (above the
125+
// loading() hole), the exact material that would be frozen into a captured
126+
// prelude. With the gate reading the token at the commit point (which runs AFTER
127+
// the route middleware), capture never runs: every GET stays MISS and carries a
128+
// DISTINCT nonce. This also pins the commit-point ordering — the DSL middleware's
129+
// token write is visible to the gate.
130+
function ShellNonceLayout(ctx: HandlerContext) {
131+
const requestNonce = ctx.get(nonce);
132+
return (
133+
<main data-testid="shell-nonce-page">
134+
<h1 data-testid="shell-nonce-header">Shell Nonce Demo</h1>
135+
<span
136+
data-testid="shell-nonce-value"
137+
data-nonce={requestNonce ?? "(none)"}
138+
/>
139+
<Outlet />
140+
</main>
141+
);
142+
}
143+
144+
function ShellNoncePricePage() {
145+
return <ShellCachePrice loader={ShellPriceLoader} />;
146+
}
147+
148+
export const shellCachePatterns = urls(
149+
({ path, layout, loader, loading, middleware }) => [
150+
layout(ShellCacheLayout, () => [
151+
// ppr carries the WHOLE shell policy (ttl/swr/tags); no middleware exists.
152+
path(
153+
"/shell-cache",
154+
ShellCachePricePage,
155+
{ name: "shellCache", ppr: { ttl: 300, swr: 120 } },
156+
() => [
157+
loader(ShellPriceLoader),
158+
loading(
159+
<div data-testid="shell-price-fallback">Loading price...</div>,
160+
),
161+
],
162+
),
163+
// Loader-carried promise WITH loading(): the loading() boundary is the hole.
164+
// On a HIT the resume streams three layers in one body — cached shell, then
165+
// the outer loader value + the inner Suspense fallback, then the
166+
// nested-promise inner value + $RC.
167+
path(
168+
"/shell-cache/stream",
169+
ShellCacheStreamPage,
170+
{ name: "shellCacheStream", ppr: { ttl: 300, swr: 120 } },
171+
() => [
172+
loader(ShellStreamLoader),
173+
loading(
174+
<div data-testid="shell-stream-fallback">Loading stream...</div>,
175+
),
176+
],
177+
),
178+
// Same loader/component, ppr DECLARED, but NO loading(): the loading-less
179+
// branch awaits loader data at tree-build, so capture's masked loader pins
180+
// the tree and the sanity gate refuses — x-rango-shell stays MISS forever
181+
// (plus the once-per-key warning). The nested inner promise still streams
182+
// under axis 1 (no loading() degrades only the caching, never the route).
183+
path(
184+
"/shell-cache/no-hole",
185+
ShellCacheStreamPage,
186+
{ name: "shellCacheNoHole", ppr: true },
187+
() => [loader(ShellStreamLoader)],
188+
),
189+
]),
190+
// Capture-data-snapshot DRIFT route: the shell bakes a value from a short-ttl
191+
// cache() (getDriftStamp, "drift" profile, ttl 1s); the shell's own ttl is 300.
192+
// After the inner ttl expires, a HIT must still show the CAPTURE-time stamp
193+
// (seeded from the snapshot) — byte parity with the frozen prelude — while the
194+
// price loader hole stays live. See docs/design/ppr-shell-resume.md.
195+
layout(ShellDriftLayout, () => [
196+
path(
197+
"/shell-cache/drift",
198+
ShellDriftPricePage,
199+
{ name: "shellCacheDrift", ppr: { ttl: 300, swr: 120 } },
200+
() => [
201+
loader(ShellPriceLoader),
202+
loading(
203+
<div data-testid="drift-price-fallback">Loading price...</div>,
204+
),
205+
],
206+
),
207+
]),
208+
// Per-request nonce via the ContextVar TOKEN in route middleware (issue #656).
209+
// Scoped to THIS subtree (not global) so it gates only this ppr route and
210+
// leaves the rest of the shell-cache suite capturable — a global token nonce
211+
// would gate every other ppr fixture and kill their HIT coverage.
212+
middleware(
213+
async (ctx, next) => {
214+
ctx.set(nonce, crypto.randomUUID());
215+
return next();
216+
},
166217
() => [
167-
loader(ShellPriceLoader),
168-
loading(<div data-testid="drift-price-fallback">Loading price...</div>),
218+
layout(ShellNonceLayout, () => [
219+
path(
220+
"/shell-cache/nonce-token",
221+
ShellNoncePricePage,
222+
{ name: "shellCacheNonceToken", ppr: { ttl: 300, swr: 120 } },
223+
() => [
224+
loader(ShellPriceLoader),
225+
loading(
226+
<div data-testid="shell-nonce-price-fallback">
227+
Loading price...
228+
</div>,
229+
),
230+
],
231+
),
232+
]),
169233
],
170234
),
171-
]),
172-
]);
235+
],
236+
);

0 commit comments

Comments
 (0)