Skip to content

Commit 7ef0e37

Browse files
authored
fix(caching/ppr): audit remediation — redirect guard, host key, base64 bound, SSR capture hardening, +docs/diagnostics (#685)
* fix(ppr): guard the shell-HIT redirect degradation against open redirects The shell-HIT tail's degradation branch emitted <script>location.replace(raw match.redirect)</script> into an already-committed 200 body, bypassing the 3xx guardOutgoingRedirect chokepoint. Route the target through the shared resolveSameOriginRedirect (extracted as resolveShellHitRedirectTarget) so a cross-origin/unsafe target neutralizes to the basename root, matching every other redirect exit. * docs(caching): document render-callable cacheTag() in skills and design docs cacheTag() shipped a second, render-callable form (#648): called during a request render outside a "use cache" function it records onto the document/ shell artifact. Four skills and two canonical design docs still taught it as "use cache"-only; the ppr-shell-resume out-of-scope bullet contradicted the shipped auto-collection. Correct all six, plus notes on the no-TTL marker cost and that action invalidation does not evict the server shell. * fix(cache): host-namespace the default document-cache key VercelCacheStore and MemorySegmentCacheStore key the response cache by the raw string with no host prefix (only CFCacheStore adds host internally), so on one function serving multiple domains the default document-cache key bled tenant A's full response to tenant B. Prefix url.host on the default-key branch, mirroring cache-scope.getCacheKeyBase; the keyGenerator branch is left to the consumer with a JSDoc warning. * fix(cache): bound Vercel store base64 chunk via the shared cf-base64 helpers The Vercel store spread up to 32768 bytes into String.fromCharCode, 4x closer to the JS argument-count ceiling than the CF encoder's deliberate 8192-.apply; a large body could throw RangeError inside putResponse/putShell and degrade silently to no-cache. Delegate both encode and decode to the import-pure cf-base64.ts (byte-identical output, no cache cold-start). * feat(cache): warn once per namespace on CF tag invalidation with no marker expiry With tagInvalidationTtl unset (the default) every invalidated tag writes a permanent KV marker; high-cardinality tags accumulate KV keys unboundedly with no reaper. Emit a one-time-per-namespace warning at the invalidateTags batch entry point pointing at the sizing rule, mirroring the existing floor-warning idiom. No default-behavior change. * test(e2e): add production-mode coverage for navigation loading states navigation-loading.test.ts ran both describes dev-only, and check:e2e-parity is warn-only so the gap never failed CI. Extract each body into a spec function and add a (production) mode:"build" sibling, mirroring shell-cache.test.ts. The 10 production tests pass locally. * feat(ppr): diagnostics for untagged shell bake and the silent action-refetch drop Two silent PPR/action edges now emit signal without changing behavior. (A) When a bake-lane loader freezes data into the shell but the capture recorded zero tags, that data is un-invalidatable except by TTL (an action refresh touches the client only); warn once per shell key in dev. (B) The action-mode missing- segments branch in partial-update was a bare return with no diagnostic; log the intentional drop. * fix(ppr): SSR capture stops masking real errors, bounds bootstrap, closes reader leak captureShellHTML swallowed any AbortError-named throw into a null no-shell degrade because it aborts before awaiting, so signal.aborted was always true; discriminate the deliberate abort by identity (error === abortReason), verified against real react-dom/static.edge. Also arm the maxWaitMs deadline before the bootstrap load so a hung load degrades bounded, and add try/finally reader cleanup on the mid-read error path.
1 parent 2346b42 commit 7ef0e37

20 files changed

Lines changed: 949 additions & 181 deletions

‎docs/design/cache-tags-flow.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,13 @@ The three verbs a consumer touches:
3434
| `updateTag(...tags)` | server actions | **read-your-own-writes** — awaitable, immediate |
3535
| `revalidateTag(...tags)` | route handlers / webhooks | background (non-blocking) — hard-purge, next read re-renders fresh |
3636

37+
`cacheTag(...tags)` has a second, render-callable form: called during a request
38+
render **outside** any `"use cache"` function, it records onto the request's
39+
`_requestTags` instead of throwing. PPR shell capture and the document cache union
40+
that set onto their entry, so a plain server component can tag the shell/full-page
41+
artifact it renders into — `revalidateTag` then evicts it. On a route that is
42+
neither PPR nor document-cached the tag records where nothing reads it (a no-op).
43+
3744
---
3845

3946
## ① WRITE — caching a tagged entry

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -990,8 +990,11 @@ are not revived.
990990
with the same storage contract.
991991
- CF Cache-API L1 tier for shell entries (KV only in v1).
992992
- Vercel BOA `chain` / streaming-lambda serving.
993-
- Segment-tag union auto-collection for shell entries (v1: TTL/SWR + explicit
994-
tags option + reactVersion gate).
993+
- Render-recorded shell-tag union for shell entries: SHIPPED in #648 (originally
994+
scoped out of v1, which had only TTL/SWR + the explicit `ppr.tags` option +
995+
reactVersion gate). The render-callable `cacheTag()` unions render-recorded tags
996+
onto the shell entry — see "Shell invalidation is DERIVATIVE (render-recorded
997+
tags, #648)" above.
995998
- Flight-byte splicing for the cached portion of the payload (the full Flight
996999
render still runs per request; hydration needs it anyway).
9971000
- Warm-pass two-phase capture: a second capture render that lets non-loader

‎packages/rangojs-router/e2e/navigation-loading.test.ts‎

Lines changed: 36 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,13 @@
11
import { expect, test } from "@playwright/test";
2-
import { useFixture } from "./fixture";
2+
import { useFixture, type Fixture } from "./fixture";
33
import {
44
waitForHydration,
55
expectNoPageError,
66
goBack,
77
getHistoryState,
88
} from "./helper";
99

10-
test.describe("navigation-state", () => {
11-
const f = useFixture({
12-
root: "./e2e/test-app",
13-
mode: "dev",
14-
});
15-
10+
function runNavigationStateSpec(f: Fixture) {
1611
test("should pass state to loading skeleton via Link state prop", async ({
1712
page,
1813
}) => {
@@ -117,14 +112,9 @@ test.describe("navigation-state", () => {
117112
expect(locationState?.productName).toBe("Slow Product A");
118113
expect(locationState?.productPrice).toBe(99);
119114
});
120-
});
121-
122-
test.describe("intercept-loading-states", () => {
123-
const f = useFixture({
124-
root: "./e2e/test-app",
125-
mode: "dev",
126-
});
115+
}
127116

117+
function runInterceptLoadingSpec(f: Fixture) {
128118
test("should show loading skeleton in modal while slow loader resolves", async ({
129119
page,
130120
}) => {
@@ -407,4 +397,36 @@ test.describe("intercept-loading-states", () => {
407397
page.locator('[data-testid="slow-modal-product-name"]'),
408398
).toBeVisible();
409399
});
400+
}
401+
402+
test.describe("navigation-state (dev)", () => {
403+
const f = useFixture({
404+
root: "./e2e/test-app",
405+
mode: "dev",
406+
});
407+
runNavigationStateSpec(f);
408+
});
409+
410+
test.describe("navigation-state (production)", () => {
411+
const f = useFixture({
412+
root: "./e2e/test-app",
413+
mode: "build",
414+
});
415+
runNavigationStateSpec(f);
416+
});
417+
418+
test.describe("intercept-loading-states (dev)", () => {
419+
const f = useFixture({
420+
root: "./e2e/test-app",
421+
mode: "dev",
422+
});
423+
runInterceptLoadingSpec(f);
424+
});
425+
426+
test.describe("intercept-loading-states (production)", () => {
427+
const f = useFixture({
428+
root: "./e2e/test-app",
429+
mode: "build",
430+
});
431+
runInterceptLoadingSpec(f);
410432
});

‎packages/rangojs-router/skills/cache-guide/SKILL.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@ caching:
2020
1. **Stored-value freshness** — _is a cached value still good?_
2121
→ `"use cache"` (fn/component), `cache()` (segment), loader `cache()` (loader data).
2222
Entries expire by **TTL/SWR** and can be tagged (`cache({ tags })` or runtime
23-
`cacheTag(...tags)`). Built-in stores (`MemorySegmentCacheStore`, `CFCacheStore`)
23+
`cacheTag(...tags)` — inside `"use cache"` it tags that entry; called during a
24+
request render outside `"use cache"` it tags the document/shell artifact).
25+
Built-in stores (`MemorySegmentCacheStore`, `CFCacheStore`)
2426
index by tag; invalidate on demand with `updateTag(...tags)` (awaitable,
2527
read-your-own-writes) or `revalidateTag(...tags)` (background, non-blocking).
2628
Both hard-purge; the difference is awaitability, not stale-serving.

‎packages/rangojs-router/skills/caching/SKILL.md‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ Caching") over caching the rendered segment.
111111

112112
## Tag-Based Invalidation
113113

114-
Tag cached entries, then invalidate them on demand. Tags can be attached three ways:
114+
Tag cached entries, then invalidate them on demand. Tags can be attached four ways:
115115

116116
```typescript
117117
// 1. Static tags in the cache() DSL
@@ -129,8 +129,22 @@ async function getProduct(id: string) {
129129
cacheTag(`product:${id}`, "products"); // variadic, additive
130130
return db.getProduct(id);
131131
}
132+
133+
// 4. Render-callable — a plain server component (no "use cache" in its tree)
134+
// records onto the request's document/shell artifact.
135+
function CampaignBanner() {
136+
cacheTag("campaign:spring"); // rides ctx._requestTags → shell/document entry
137+
return <aside>Spring sale</aside>;
138+
}
132139
```
133140

141+
Form 4 is how you make a PPR shell or a `/document-cache` page tag-invalidatable
142+
without wrapping anything in `"use cache"`: the tag rides the request's
143+
`_requestTags` onto the shell/document entry, and `revalidateTag` then evicts it.
144+
On a route that is neither PPR nor document-cached the tag records where nothing
145+
reads it — a silent no-op, so don't expect a bare `cacheTag()` to tag an ordinary
146+
uncached page.
147+
134148
Invalidate with one of two server-only verbs (both variadic, imported from
135149
`@rangojs/router`):
136150

@@ -171,7 +185,8 @@ converge within `tagCacheTtl` (the **maximum extra cross-colo invalidation
171185
latency** when no purge is wired). Keep it small (e.g. 30–60), or wire a purge
172186
(below) and set it large. (Contrast `tagInvalidationTtl`, which must be _large_
173187
— it bounds how long the KV marker itself lives and must exceed your max entry
174-
TTL+SWR.)
188+
TTL+SWR. Left unset there is no expiry: KV markers accumulate unbounded under
189+
high-cardinality tags, so set it above your largest entry TTL+SWR to bound them.)
175190

176191
To make other colos prompt without a short `tagCacheTtl`, pass `onRevalidateTag`:
177192
each cached marker carries a namespaced Cloudflare `Cache-Tag`, and the hook is

‎packages/rangojs-router/skills/ppr/SKILL.md‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -516,17 +516,24 @@ multi-tenant shells never collide).
516516
HTML; `revalidate()` is a DATA lever that never touches it.
517517

518518
A captured shell auto-carries the UNION of the non-loader tags recorded during
519-
the capture render — every `cacheTag(...)` from a `"use cache"` function or
520-
`cache()` segment that ran as shell material. Loader tags never attach (the
521-
holes are already live). `ppr.tags` adds operational tags the render cannot
522-
know (a tenant id, a deploy marker).
519+
the capture render — every `cacheTag(...)` that ran as shell material, whether
520+
from a `"use cache"` function, a `cache()` segment, or a render-callable
521+
`cacheTag()` in a plain server component (no `"use cache"`/`cache()` in its
522+
tree). Loader tags never attach (the holes are already live). `ppr.tags` adds
523+
operational tags the render cannot know (a tenant id, a deploy marker).
523524

524525
| Lever | Reaches the frozen shell? | Reaches the holes? |
525526
| --------------------------------------------- | ------------------------------------------------------------- | --------------------------------------------------- |
526527
| `updateTag` / `revalidateTag` on a SHELL tag | YES — drops the shell → MISS → recapture | n/a (holes are already live) |
527528
| `updateTag` / `revalidateTag` on a LOADER tag | no — loader tags never attach to a shell | drops that loader's cached value (if it `cache()`s) |
528529
| `revalidate()` (named revalidation contract) | **no** — re-runs segments/loaders for the PAYLOAD, never HTML | yes — the hole re-renders with fresh data |
529530

531+
A server action's automatic invalidation refreshes the CLIENT only — it re-runs
532+
the holes and streams a fresh payload, but does NOT evict the server shell.
533+
Shell-baked data stays stale until the shell's TTL unless you tag-invalidate it
534+
(`updateTag` on a shell tag). Data baked into the shell WITHOUT a tag cannot be
535+
evicted by tag at all — move always-fresh data under a `loading()` hole.
536+
530537
## Pitfalls
531538

532539
- **A bake-lane loader that reads `cookies()`/`headers()`**: the capture is
@@ -574,8 +581,11 @@ cache"` value baked into the shell is PINNED at capture (the capture data
574581
tag-invalidated. This is deliberate — parity beats freshness inside the shell.
575582
If a shell region needs to be fresh, put it under a hole — `loading()` for
576583
loader data, or an un-awaited promise under the consumer's `<Suspense>`
577-
(holes are never pinned) — or make the SHELL itself invalidatable by adding
578-
the tag to `ppr.tags`. Ring-1/ring-3 tag invalidation does NOT drop the shell.
584+
(holes are never pinned) — or make the SHELL itself invalidatable by tagging
585+
it: call `cacheTag(...)` from the shell-material render code (the render-time
586+
lever), or add the tag to `ppr.tags` (operational tags the render cannot know —
587+
a tenant id, a deploy marker). Ring-1/ring-3 tag invalidation does NOT drop the
588+
shell.
579589
- **Uncached nondeterminism in the shell is a hydration hazard**: a raw
580590
`Date.now()` / `Math.random()` / uncached `fetch` rendered directly in shell
581591
material (outside any cache ring) drifts between capture and hit and the

‎packages/rangojs-router/skills/use-cache/SKILL.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -353,8 +353,11 @@ export async function getProducts() {
353353
Writes to the same `SegmentCacheStore` as `cache()` DSL, `Static()`, and `Prerender()`.
354354
One store, one configuration.
355355

356-
Cache entries (and `cacheProfiles`) can be tagged via `cache({ tags })` or, inside
357-
a `"use cache"` function, runtime `cacheTag(...tags)`. The built-in
356+
Cache entries (and `cacheProfiles`) can be tagged via `cache({ tags })` or runtime
357+
`cacheTag(...tags)`. `cacheTag` has two forms: inside a `"use cache"` function it
358+
tags that entry; called during a request render outside `"use cache"` it tags the
359+
request's document/shell artifact (rides `_requestTags`) instead of throwing. The
360+
built-in
358361
`MemorySegmentCacheStore` and `CFCacheStore` index by tag. Invalidate on demand
359362
with `updateTag(...tags)` (awaitable, read-your-own-writes; for server actions) or
360363
`revalidateTag(...tags)` (background, non-blocking; for route handlers/webhooks).

‎packages/rangojs-router/src/browser/partial-update.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,13 @@ export function createPartialUpdater(
395395
return;
396396
}
397397
if (mode.type === "action") {
398+
// An action refetch that lands on missing segments (navigated away /
399+
// consolidation / HMR) drops rather than refetch-all: the action flow
400+
// is storeOnly / skipLoadingState, so a full refetch here would fight
401+
// it. Keep the stale-but-consistent tree; log so the drop is visible.
402+
debugLog(
403+
`[Browser] Action refetch: ${missingCount} segments missing; dropping (stale-but-consistent tree kept).`,
404+
);
398405
return;
399406
}
400407
console.warn(

0 commit comments

Comments
 (0)