Skip to content

Commit 38606cb

Browse files
authored
chore(router): #684 follow-ups — DRY consolidations + docs-api guard over caching/PPR skills (#686)
* chore(router): #684 follow-ups — shared blocked-redirect landing, shared cache key base, CFCacheStore warn-once, docs-api guard over caching/PPR skills Issue #684 groups A (DRY consolidations) and D (tooling): - safeSameOriginLanding() in redirect-origin.ts: the one answer to "where does a blocked redirect go"; redirect-guard.ts and resolveShellHitRedirectTarget (rsc-rendering.ts) now share it. - cacheKeyBase() in cache-key-utils.ts: the one host-namespaced ${host}${pathname}[:params][?search] composition; cache-scope.ts (segment tier) and document-cache.ts (document tier) both ride it. Output byte-identical to both prior inline shapes. - CFCacheStore.warnOncePerNamespace(): collapses the three open-coded once-per-namespace warn dances (no-KV read invalidation, TTL floor, no-TTL marker growth). - check:docs-api now also guards the 8 caching/PPR skills (cache-guide, caching, defer-hydration, document-cache, ppr, prerender, shell-manifest, use-cache) — the cacheTag() render-callable drift class (plan 003). Shakedown found and fixed a guard false-negative: class declarations (e.g. errors.ts Skip) matched no definition-ish position; createHydrationGate allowlisted as a userland recipe name. * ci: trigger run
1 parent 7ef0e37 commit 38606cb

10 files changed

Lines changed: 166 additions & 111 deletions

File tree

‎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: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -223,9 +223,11 @@ Route-local schema definitions (`search` option), typed route param types (`Rout
223223
single redirect off-host but only to an `http(s)` target (a `javascript:`/`data:`
224224
target is neutralized). The opt-in is an out-of-band brand on the Response
225225
object (`WeakSet`, not a wire header) so a proxied upstream's forged header
226-
cannot forge it. Two shared rules (`redirect-origin.ts`:
227-
`resolveSameOriginRedirect`, `resolveExternalRedirect`) back both the client
228-
validators and the server guard. See `docs/internal/security-checklist.md`.
226+
cannot forge it. Three shared rules (`redirect-origin.ts`:
227+
`resolveSameOriginRedirect`, `resolveExternalRedirect`,
228+
`safeSameOriginLanding` — the one blocked-redirect landing) back both the
229+
client validators and the server guard. See
230+
`docs/internal/security-checklist.md`.
229231
- Typed error model: `RouteNotFoundError`, `DataNotFoundError`, etc.
230232
- Not-found and error boundary propagation across the route tree
231233

‎packages/rangojs-router/src/cache/cache-key-utils.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,32 @@ export function sortedRouteParams(
5858
if (!params) return "";
5959
return encodeKV(Object.entries(params), { sort: true });
6060
}
61+
62+
/**
63+
* Host-namespaced cache key base: `${host}${pathname}[:params][?search]`.
64+
*
65+
* The ONE composition of the host-namespacing rule, shared by the segment tier
66+
* (cache-scope.ts) and the document tier (document-cache.ts) so the rule cannot
67+
* drift between them. Host prefixing matters because VercelCacheStore /
68+
* MemorySegmentCacheStore key by the raw string (only CFCacheStore adds host
69+
* internally) -- on a single function serving multiple domains an
70+
* un-namespaced key bleeds tenant A's cached response to tenant B.
71+
*
72+
* Output is BYTE-STABLE by contract: changing the composition silently
73+
* invalidates every persisted cache entry on upgrade. Callers append their own
74+
* tier-specific suffixes (`:rsc`/`:html`, segment hash) after this base.
75+
*/
76+
export function cacheKeyBase(
77+
host: string,
78+
pathname: string,
79+
searchParams?: URLSearchParams,
80+
params?: Record<string, string>,
81+
): string {
82+
const paramStr = sortedRouteParams(params);
83+
const searchStr = searchParams ? sortedSearchString(searchParams) : "";
84+
85+
let key = `${host}${pathname}`;
86+
if (paramStr) key += `:${paramStr}`;
87+
if (searchStr) key += `?${searchStr}`;
88+
return key;
89+
}

‎packages/rangojs-router/src/cache/cache-scope.ts‎

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ import {
3131
encodeHandles,
3232
decodeHandles,
3333
} from "./handle-snapshot.js";
34-
import { sortedSearchString, sortedRouteParams } from "./cache-key-utils.js";
34+
import { cacheKeyBase } from "./cache-key-utils.js";
3535
import {
3636
DEFAULT_ROUTE_TTL,
3737
isFiniteNonNegativeSeconds,
@@ -85,21 +85,6 @@ function validatedSwr(value: number | undefined): number | undefined {
8585
return isValidCacheSeconds(value, "swr") ? value : undefined;
8686
}
8787

88-
function getCacheKeyBase(
89-
host: string,
90-
pathname: string,
91-
params?: Record<string, string>,
92-
searchParams?: URLSearchParams,
93-
): string {
94-
const paramStr = sortedRouteParams(params);
95-
const searchStr = searchParams ? sortedSearchString(searchParams) : "";
96-
97-
let key = `${host}${pathname}`;
98-
if (paramStr) key += `:${paramStr}`;
99-
if (searchStr) key += `?${searchStr}`;
100-
return key;
101-
}
102-
10388
function getDefaultRouteCacheKey(
10489
pathname: string,
10590
params?: Record<string, string>,
@@ -113,7 +98,7 @@ function getDefaultRouteCacheKey(
11398
// Intercept navigations get their own cache namespace
11499
const prefix = isIntercept ? "intercept" : isPartial ? "partial" : "doc";
115100

116-
return `${prefix}:${getCacheKeyBase(host, pathname, params, searchParams)}`;
101+
return `${prefix}:${cacheKeyBase(host, pathname, searchParams, params)}`;
117102
}
118103

119104
// ============================================================================

‎packages/rangojs-router/src/cache/cf/cf-cache-store.ts‎

Lines changed: 36 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -350,19 +350,30 @@ export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
350350
// kv - yet every tagged read still serves stale data with no other signal.
351351
// Surface that misconfiguration.
352352
if (!this.kv && (this.tagCacheTtl > 0 || this.onRevalidateTag)) {
353-
const id = this.namespace ?? "default";
354-
if (!warnedNoKvReadInvalidation.has(id)) {
355-
warnedNoKvReadInvalidation.add(id);
356-
console.warn(
357-
`[CFCacheStore] tagCacheTtl/onRevalidateTag is configured without a KV ` +
358-
`namespace, so tag invalidation has NO read-side effect: tagged reads ` +
359-
`are never treated as invalidated and serve stale data. Configure ` +
360-
`{ kv } for distributed tag invalidation.`,
361-
);
362-
}
353+
this.warnOncePerNamespace(
354+
warnedNoKvReadInvalidation,
355+
`[CFCacheStore] tagCacheTtl/onRevalidateTag is configured without a KV ` +
356+
`namespace, so tag invalidation has NO read-side effect: tagged reads ` +
357+
`are never treated as invalidated and serve stale data. Configure ` +
358+
`{ kv } for distributed tag invalidation.`,
359+
);
363360
}
364361
}
365362

363+
/**
364+
* Warn about a namespace-scoped misconfiguration once per namespace per
365+
* isolate. `seen` is the module-level Set for that message family -- Sets
366+
* are module-level (not instance fields) so re-constructed stores in the
367+
* same isolate don't re-warn.
368+
* @internal
369+
*/
370+
private warnOncePerNamespace(seen: Set<string>, message: string): void {
371+
const id = this.namespace ?? "default";
372+
if (seen.has(id)) return;
373+
seen.add(id);
374+
console.warn(message);
375+
}
376+
366377
/**
367378
* Validate a consumer-supplied tagInvalidationTtl against CF KV's expirationTtl
368379
* floor. A finite value below KV_MIN_EXPIRATION_TTL is raised to it (with a
@@ -378,16 +389,13 @@ export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
378389
if (value == null) return undefined;
379390
if (!Number.isFinite(value) || value <= 0) return undefined;
380391
if (value < KV_MIN_EXPIRATION_TTL) {
381-
const id = this.namespace ?? "default";
382-
if (!warnedTagInvalidationTtlFloor.has(id)) {
383-
warnedTagInvalidationTtlFloor.add(id);
384-
console.warn(
385-
`[CFCacheStore] tagInvalidationTtl ${value} is below Cloudflare KV's ` +
386-
`${KV_MIN_EXPIRATION_TTL}s expirationTtl floor; raising to ` +
387-
`${KV_MIN_EXPIRATION_TTL}. It must still exceed your largest entry ` +
388-
`TTL+SWR or invalidated entries can resurrect when the marker expires.`,
389-
);
390-
}
392+
this.warnOncePerNamespace(
393+
warnedTagInvalidationTtlFloor,
394+
`[CFCacheStore] tagInvalidationTtl ${value} is below Cloudflare KV's ` +
395+
`${KV_MIN_EXPIRATION_TTL}s expirationTtl floor; raising to ` +
396+
`${KV_MIN_EXPIRATION_TTL}. It must still exceed your largest entry ` +
397+
`TTL+SWR or invalidated entries can resurrect when the marker expires.`,
398+
);
391399
return KV_MIN_EXPIRATION_TTL;
392400
}
393401
return value;
@@ -2271,17 +2279,14 @@ export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
22712279
// that path only fires for a positive below-floor value, never the unset
22722280
// default sanitizeTagInvalidationTtl passes through as undefined.
22732281
if (!this.tagInvalidationTtl) {
2274-
const id = this.namespace ?? "default";
2275-
if (!warnedNoTagInvalidationTtl.has(id)) {
2276-
warnedNoTagInvalidationTtl.add(id);
2277-
console.warn(
2278-
`[CFCacheStore] invalidateTags is writing KV markers with no expiry ` +
2279-
`(tagInvalidationTtl is unset): high-cardinality tags accumulate KV ` +
2280-
`keys unboundedly (storage + list-scan cost) with no reaper. Set ` +
2281-
`tagInvalidationTtl above your largest entry TTL+SWR to bound marker ` +
2282-
`growth; setting it too small resurrects invalidated entries.`,
2283-
);
2284-
}
2282+
this.warnOncePerNamespace(
2283+
warnedNoTagInvalidationTtl,
2284+
`[CFCacheStore] invalidateTags is writing KV markers with no expiry ` +
2285+
`(tagInvalidationTtl is unset): high-cardinality tags accumulate KV ` +
2286+
`keys unboundedly (storage + list-scan cost) with no reaper. Set ` +
2287+
`tagInvalidationTtl above your largest entry TTL+SWR to bound marker ` +
2288+
`growth; setting it too small resurrects invalidated entries.`,
2289+
);
22852290
}
22862291
await Promise.all(
22872292
tags.map(async (tag) => {

‎packages/rangojs-router/src/cache/document-cache.ts‎

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import {
1919
type RequestContext,
2020
} from "../server/request-context.js";
2121
import { mayNeedSSR } from "../rsc/ssr-setup.js";
22-
import { sortedSearchString } from "./cache-key-utils.js";
22+
import { cacheKeyBase } from "./cache-key-utils.js";
2323
import { runBackground } from "./background-task.js";
2424
import { reportCacheError } from "./cache-error.js";
2525

@@ -317,25 +317,17 @@ export function createDocumentCacheMiddleware<TEnv = any>(
317317
isPartial && clientSegments ? `:${hashSegmentIds(clientSegments)}` : "";
318318
const typeSuffix = isRscRequest ? ":rsc" : ":html";
319319

320-
let searchSuffix = "";
321-
if (!keyGenerator) {
322-
const sorted = sortedSearchString(url.searchParams);
323-
if (sorted) {
324-
searchSuffix = `?${sorted}`;
325-
}
326-
}
327-
328-
// Host-namespace the default key. VercelCacheStore/MemorySegmentCacheStore
329-
// key by the raw string with no host prefix (only CFCacheStore adds host
330-
// internally), so on a single function serving multiple domains an
331-
// un-namespaced key bleeds tenant A's full response to tenant B. Mirrors
332-
// the segment path's cache-scope.ts getCacheKeyBase (`${host}${pathname}`).
320+
// Default key rides the shared host-namespaced base (cacheKeyBase) so the
321+
// segment tier (cache-scope.ts) and this document tier cannot drift on the
322+
// host-namespacing rule -- see the contract on cacheKeyBase.
333323
// The keyGenerator branch is left untouched: a consumer-supplied generator
334324
// owns its own namespacing (auto-prefixing host would silently change their
335325
// existing keys and double any host they already include).
336326
const cacheKey = keyGenerator
337327
? keyGenerator(url) + segmentHash + typeSuffix
338-
: `${url.host}${url.pathname}${searchSuffix}${segmentHash}${typeSuffix}`;
328+
: cacheKeyBase(url.host, url.pathname, url.searchParams) +
329+
segmentHash +
330+
typeSuffix;
339331
// 1. Check cache
340332
const cached = await store.getResponse(cacheKey);
341333

‎packages/rangojs-router/src/redirect-origin.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,20 @@ export function resolveExternalRedirect(
6060
}
6161
}
6262

63+
/**
64+
* The safe same-origin landing for a blocked redirect.
65+
*
66+
* Every guard that neutralizes a cross-origin/unsafe redirect target sends the
67+
* browser here instead: the app's basename root, or `"/"` when unset. Kept
68+
* beside the resolvers so the "where does a blocked redirect go" answer lives
69+
* in ONE place -- the server 3xx guard (`rsc/redirect-guard.ts`) and the
70+
* shell-HIT degradation path (`rsc/rsc-rendering.ts`) must agree, or a blocked
71+
* redirect lands differently depending on which exit it took.
72+
*/
73+
export function safeSameOriginLanding(basename: string | undefined): string {
74+
return basename && basename !== "/" ? basename : "/";
75+
}
76+
6377
/**
6478
* Out-of-band brand for `redirect(url, { external: true })`.
6579
*

‎packages/rangojs-router/src/rsc/redirect-guard.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import {
3838
resolveSameOriginRedirect,
3939
resolveExternalRedirect,
4040
isExternalRedirect,
41+
safeSameOriginLanding,
4142
EXTERNAL_REDIRECT_MARKER,
4243
} from "../redirect-origin.js";
4344
import { carryOverRedirectHeaders } from "./helpers.js";
@@ -79,7 +80,7 @@ export function guardOutgoingRedirect(
7980

8081
// Cross-origin (or unsafe-scheme external): neutralize to a safe same-origin
8182
// landing.
82-
const safeTarget = basename && basename !== "/" ? basename : "/";
83+
const safeTarget = safeSameOriginLanding(basename);
8384
if (process.env.NODE_ENV !== "production") {
8485
console.error(
8586
`[rango] Blocked cross-origin redirect to "${location}"; sent to ` +

‎packages/rangojs-router/src/rsc/rsc-rendering.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,10 @@ import {
4444
warnPprNonceActiveOnce,
4545
} from "./shell-serve.js";
4646
import { contextGet } from "../context-var.js";
47-
import { resolveSameOriginRedirect } from "../redirect-origin.js";
47+
import {
48+
resolveSameOriginRedirect,
49+
safeSameOriginLanding,
50+
} from "../redirect-origin.js";
4851
import { nonce as nonceToken } from "./nonce.js";
4952
import { reportCacheError } from "../cache/cache-error.js";
5053
import { INTERNAL_RANGO_DEBUG } from "../internal-debug.js";
@@ -433,7 +436,7 @@ export function resolveShellHitRedirectTarget(
433436
): string {
434437
return (
435438
resolveSameOriginRedirect(rawTarget, requestOrigin) ??
436-
(basename && basename !== "/" ? basename : "/")
439+
safeSameOriginLanding(basename)
437440
);
438441
}
439442

‎tools/check-docs-api.mjs‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,20 @@ const REPO_ROOT = path.resolve(
3535
const DOCS = [
3636
"packages/rangojs-router/README.md",
3737
"packages/rangojs-router/docs/why-rango.md",
38+
// The caching/PPR skill family teaches API surface the same way the
39+
// positioning docs do, and has drifted the same way: skills taught a
40+
// "use cache"-only cacheTag() after src shipped the render-callable form
41+
// (issue #684, plan 003). Guard them with the same identifier check.
42+
...[
43+
"cache-guide",
44+
"caching",
45+
"defer-hydration",
46+
"document-cache",
47+
"ppr",
48+
"prerender",
49+
"shell-manifest",
50+
"use-cache",
51+
].map((skill) => `packages/rangojs-router/skills/${skill}/SKILL.md`),
3852
];
3953

4054
const SRC_ROOT = path.join(REPO_ROOT, "packages/rangojs-router/src");
@@ -46,6 +60,10 @@ const ALLOWLIST = new Set([
4660
// ("config extracts into factories you can share").
4761
"withCaching",
4862
"withAuth",
63+
// Suggested userland factory name in the defer-hydration recipe ("factor the
64+
// module into a createHydrationGate() if you go there") -- deliberately not a
65+
// shipped API; the recipe has zero API commitment.
66+
"createHydrationGate",
4967
]);
5068

5169
// --- extraction ------------------------------------------------------------
@@ -123,7 +141,13 @@ const corpus = collectSrcCorpus(SRC_ROOT, []).join("\n");
123141

124142
function existsInSrc(name) {
125143
const escaped = name.replace(/\$/g, "\\$");
126-
return new RegExp(`\\b${escaped}\\s*(?:\\(|:|=[^=]|\\?:|<)`).test(corpus);
144+
// Second alternation: class declarations (`export class Skip extends Error`)
145+
// sit in none of the value-ish positions the first pattern matches -- found
146+
// when the skills joined the doc list and `Skip` false-negatived.
147+
return (
148+
new RegExp(`\\b${escaped}\\s*(?:\\(|:|=[^=]|\\?:|<)`).test(corpus) ||
149+
new RegExp(`\\bclass\\s+${escaped}\\b`).test(corpus)
150+
);
127151
}
128152

129153
// --- run ---------------------------------------------------------------------

0 commit comments

Comments
 (0)