@decocms/tanstack 7.56.0 → 7.58.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.
- package/package.json +5 -4
- package/src/hooks/CdnSegmentMarker.tsx +35 -0
- package/src/hooks/DecoRootLayout.tsx +2 -0
- package/src/sdk/cdnSegment.test.ts +45 -33
- package/src/sdk/cdnSegment.ts +51 -54
- package/src/sdk/serverFnFetch.ts +32 -36
- package/src/sdk/startEntry.ts +31 -0
- package/src/sdk/workerEntry.test.ts +69 -18
- package/src/sdk/workerEntry.ts +60 -22
- package/src/vite/plugin.js +27 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@decocms/tanstack",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.58.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Deco framework binding for TanStack Start + Cloudflare Workers",
|
|
6
6
|
"repository": {
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
"./sdk/cookiePassthrough": "./src/sdk/cookiePassthrough.ts",
|
|
18
18
|
"./sdk/deferredSectionLoader": "./src/sdk/deferredSectionLoader.ts",
|
|
19
19
|
"./sdk/serverFnFetch": "./src/sdk/serverFnFetch.ts",
|
|
20
|
+
"./sdk/startEntry": "./src/sdk/startEntry.ts",
|
|
20
21
|
"./sdk/cdnSegment": "./src/sdk/cdnSegment.ts"
|
|
21
22
|
},
|
|
22
23
|
"scripts": {
|
|
@@ -26,9 +27,9 @@
|
|
|
26
27
|
"lint:unused": "knip"
|
|
27
28
|
},
|
|
28
29
|
"dependencies": {
|
|
29
|
-
"@decocms/blocks": "7.
|
|
30
|
-
"@decocms/blocks-admin": "7.
|
|
31
|
-
"@decocms/blocks-cli": "7.
|
|
30
|
+
"@decocms/blocks": "7.58.0",
|
|
31
|
+
"@decocms/blocks-admin": "7.58.0",
|
|
32
|
+
"@decocms/blocks-cli": "7.58.0",
|
|
32
33
|
"@deco-cx/warp-node": "^0.3.16",
|
|
33
34
|
"fast-json-patch": "^3.1.0",
|
|
34
35
|
"ws": "^8.18.0"
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Publishes the CDN segment token this server computed, so `decoServerFnFetch`
|
|
3
|
+
* can echo it back on `/_serverFn` URLs.
|
|
4
|
+
*
|
|
5
|
+
* Only the server can produce this value: the segment includes dimensions the
|
|
6
|
+
* browser cannot observe — region is resolved from `request.cf.regionCode`.
|
|
7
|
+
* A client that derives its own token therefore never matches on a
|
|
8
|
+
* regionalized store, which is exactly why this component exists.
|
|
9
|
+
*
|
|
10
|
+
* - **Server:** read the token from the RequestContext bag (filled by
|
|
11
|
+
* `createDecoWorkerEntry`) and emit a tiny inline `<script>`.
|
|
12
|
+
* - **Client:** the bag is a no-op stub, so the read yields undefined and this
|
|
13
|
+
* renders nothing — the global set during SSR is already on `window`.
|
|
14
|
+
*
|
|
15
|
+
* Safe in a cached response: the Worker's edge cache keys on the segment, so a
|
|
16
|
+
* stored entry carries the token of its own segment. And a stale token is
|
|
17
|
+
* harmless by construction — the Worker verifies by recomputing and falls back
|
|
18
|
+
* to `no-store` when it doesn't match.
|
|
19
|
+
*/
|
|
20
|
+
import { RequestContext } from "@decocms/blocks/sdk/requestContext";
|
|
21
|
+
import { CSEG_BAG_KEY, CSEG_GLOBAL } from "../sdk/cdnSegment";
|
|
22
|
+
|
|
23
|
+
export function CdnSegmentMarker() {
|
|
24
|
+
const token = RequestContext.getBag<string>(CSEG_BAG_KEY);
|
|
25
|
+
if (!token) return null;
|
|
26
|
+
return (
|
|
27
|
+
<script
|
|
28
|
+
// A hash this server computed, not user input. JSON.stringify keeps it
|
|
29
|
+
// inert regardless.
|
|
30
|
+
dangerouslySetInnerHTML={{
|
|
31
|
+
__html: `window.${CSEG_GLOBAL}=${JSON.stringify(token)}`,
|
|
32
|
+
}}
|
|
33
|
+
/>
|
|
34
|
+
);
|
|
35
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CdnSegmentMarker } from "./CdnSegmentMarker";
|
|
1
2
|
import { useEffect, type ReactNode } from "react";
|
|
2
3
|
import { HeadContent, Scripts, ScriptOnce, useRouterState } from "@tanstack/react-router";
|
|
3
4
|
import { LiveControls, Stats } from "@decocms/blocks/hooks";
|
|
@@ -141,6 +142,7 @@ export function DecoRootLayout({
|
|
|
141
142
|
<html lang={lang} data-theme={dataTheme} suppressHydrationWarning>
|
|
142
143
|
<head>
|
|
143
144
|
<HeadContent />
|
|
145
|
+
<CdnSegmentMarker />
|
|
144
146
|
{speculation && (
|
|
145
147
|
<script
|
|
146
148
|
type="speculationrules"
|
|
@@ -4,52 +4,64 @@ import { segmentToken } from "./cdnSegment";
|
|
|
4
4
|
const BUILD = "abc123";
|
|
5
5
|
|
|
6
6
|
describe("segmentToken", () => {
|
|
7
|
-
it("
|
|
8
|
-
expect(segmentToken(
|
|
9
|
-
expect(segmentToken({ device: "desktop" }, BUILD)).toBe("desktop.abc123");
|
|
10
|
-
// tablet is its own detectDevice value — it must not collapse into mobile
|
|
11
|
-
expect(segmentToken({ device: "tablet" }, BUILD)).toBe("tablet.abc123");
|
|
7
|
+
it("produces a token for an anonymous visitor", () => {
|
|
8
|
+
expect(segmentToken("desktop", false, BUILD)).toBeTruthy();
|
|
12
9
|
});
|
|
13
10
|
|
|
14
|
-
it("
|
|
15
|
-
|
|
16
|
-
|
|
11
|
+
it("gives different segments different tokens", () => {
|
|
12
|
+
// The whole point: the URL has to distinguish what the Worker's key
|
|
13
|
+
// distinguishes, or a cache in front serves one visitor another's response.
|
|
14
|
+
const tokens = ["desktop", "mobile", "desktop|r=RJ", "desktop|r=SP", "desktop|sc=3|r=RJ"].map(
|
|
15
|
+
(s) => segmentToken(s, false, BUILD),
|
|
17
16
|
);
|
|
17
|
+
expect(new Set(tokens).size).toBe(tokens.length);
|
|
18
18
|
});
|
|
19
19
|
|
|
20
|
-
it("
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
expect(segmentToken(
|
|
20
|
+
it("regionalized and non-regionalized visitors never share a token", () => {
|
|
21
|
+
// This is the case that made the first version inert on real stores: region
|
|
22
|
+
// is resolved server-side from cf.regionCode, so it MUST be in the token.
|
|
23
|
+
expect(segmentToken("desktop", false, BUILD)).not.toBe(
|
|
24
|
+
segmentToken("desktop|r=RJ", false, BUILD),
|
|
25
|
+
);
|
|
24
26
|
});
|
|
25
27
|
|
|
26
|
-
it("
|
|
27
|
-
//
|
|
28
|
-
//
|
|
29
|
-
expect(segmentToken(
|
|
30
|
-
|
|
28
|
+
it("is stable for the same segment and build", () => {
|
|
29
|
+
// The worker verifies by recomputing, so the same input must always give
|
|
30
|
+
// the same token — otherwise nothing would ever match.
|
|
31
|
+
expect(segmentToken("desktop|r=RJ", false, BUILD)).toBe(
|
|
32
|
+
segmentToken("desktop|r=RJ", false, BUILD),
|
|
33
|
+
);
|
|
31
34
|
});
|
|
32
35
|
|
|
33
|
-
it("
|
|
34
|
-
//
|
|
35
|
-
// is
|
|
36
|
-
expect(segmentToken(
|
|
37
|
-
expect(segmentToken({ device: "mobile", beta: false }, BUILD)).toBe("mobile.abc123");
|
|
38
|
-
expect(segmentToken({ device: "mobile", flags: [] }, BUILD)).toBe("mobile.abc123");
|
|
39
|
-
expect(segmentToken({ device: "mobile", loggedIn: undefined }, BUILD)).toBe("mobile.abc123");
|
|
36
|
+
it("refuses a logged-in visitor regardless of segment precision", () => {
|
|
37
|
+
// Personalized responses never belong in a shared entry, however exact the
|
|
38
|
+
// key is.
|
|
39
|
+
expect(segmentToken("desktop|auth|r=RJ", true, BUILD)).toBeNull();
|
|
40
40
|
});
|
|
41
41
|
|
|
42
|
-
it("missing or dev build hash
|
|
43
|
-
//
|
|
44
|
-
// would
|
|
45
|
-
expect(segmentToken(
|
|
46
|
-
expect(segmentToken(
|
|
47
|
-
expect(segmentToken(
|
|
42
|
+
it("refuses a missing or dev build hash", () => {
|
|
43
|
+
// Without a build hash there is no way to invalidate on deploy — the cache
|
|
44
|
+
// in front would keep serving stale code.
|
|
45
|
+
expect(segmentToken("desktop", false, undefined)).toBeNull();
|
|
46
|
+
expect(segmentToken("desktop", false, "")).toBeNull();
|
|
47
|
+
expect(segmentToken("desktop", false, "dev")).toBeNull();
|
|
48
48
|
});
|
|
49
49
|
|
|
50
|
-
it("
|
|
51
|
-
expect(segmentToken(
|
|
52
|
-
segmentToken(
|
|
50
|
+
it("changes with the build, so a deploy invalidates it", () => {
|
|
51
|
+
expect(segmentToken("desktop", false, "buildA")).not.toBe(
|
|
52
|
+
segmentToken("desktop", false, "buildB"),
|
|
53
53
|
);
|
|
54
54
|
});
|
|
55
|
+
|
|
56
|
+
it("refuses an empty segment descriptor", () => {
|
|
57
|
+
expect(segmentToken("", false, BUILD)).toBeNull();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("is URL-safe even when the segment carries a VTEX region id", () => {
|
|
61
|
+
// `v2.XXXX` contains the character an earlier format used as a separator;
|
|
62
|
+
// hashing sidesteps escaping entirely.
|
|
63
|
+
const t = segmentToken("desktop|r=v2.ABC-123|sc=3", false, BUILD);
|
|
64
|
+
expect(t).toMatch(/^[a-z0-9]+$/);
|
|
65
|
+
expect(encodeURIComponent(t as string)).toBe(t);
|
|
66
|
+
});
|
|
55
67
|
});
|
package/src/sdk/cdnSegment.ts
CHANGED
|
@@ -1,74 +1,71 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Segment marker on `/_serverFn` URLs, so
|
|
3
|
-
* response without invoking
|
|
2
|
+
* Segment marker on `/_serverFn` URLs, so a cache in front of the Worker can
|
|
3
|
+
* serve the response without invoking it.
|
|
4
4
|
*
|
|
5
|
-
* The problem:
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
5
|
+
* The problem: whatever sits in front (Workers Cache, a CDN rule) keys on the
|
|
6
|
+
* raw URL. The Worker keys on a SYNTHETIC Request carrying
|
|
7
|
+
* `__seg`/`__cf_device`/`__bot`/`__fetch`/`__abf` (`buildCacheKey` in
|
|
8
|
+
* `./workerEntry`) — params the URL never shows. That mismatch is why the
|
|
9
|
+
* framework stamps `CDN-Cache-Control: no-store` on public responses.
|
|
10
10
|
*
|
|
11
|
-
* The fix: put the segment in the URL itself
|
|
12
|
-
* equivalent
|
|
11
|
+
* The fix: put the segment in the URL itself, so the two keys become
|
|
12
|
+
* equivalent.
|
|
13
13
|
*
|
|
14
|
-
*
|
|
15
|
-
* the marker, the worker uses it to recompute and compare — same function on
|
|
16
|
-
* both sides, so they cannot drift.
|
|
14
|
+
* ## Why the SERVER issues the token
|
|
17
15
|
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* the
|
|
16
|
+
* The first version had the client derive the token from what it could see
|
|
17
|
+
* (`navigator.userAgent`). That only ever worked on sites whose segment
|
|
18
|
+
* reduces to device alone. A regionalized VTEX store — most of them — segments
|
|
19
|
+
* on region too, and region is resolved from `request.cf.regionCode`, which
|
|
20
|
+
* exists **only** on the server. The client cannot see it, so its token never
|
|
21
|
+
* matched and the feature stayed permanently inert.
|
|
22
|
+
*
|
|
23
|
+
* So the server computes the token from the segment it already built, publishes
|
|
24
|
+
* it to the page, and the client only echoes it back. The Worker still verifies
|
|
25
|
+
* by recomputing — the marker is never trusted, so a stale or forged one just
|
|
26
|
+
* keeps the `no-store`.
|
|
27
|
+
*
|
|
28
|
+
* The token is a hash rather than readable fields: `regionId` can contain the
|
|
29
|
+
* separator (`v2.XXXX`), values would need escaping, and there is no reason to
|
|
30
|
+
* publish a visitor's region in a URL that ends up in logs.
|
|
23
31
|
*/
|
|
24
32
|
|
|
25
|
-
import
|
|
33
|
+
import { djb2Hex } from "@decocms/blocks/sdk/djb2";
|
|
26
34
|
|
|
27
35
|
/** `__d` is reserved: `workerEntry` uses `?__d=` as an OTel debug flag. */
|
|
28
36
|
export const CSEG_PARAM = "__cseg";
|
|
29
37
|
|
|
30
|
-
/**
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
* pulls in the whole server graph.
|
|
36
|
-
*/
|
|
37
|
-
export interface CdnSegment {
|
|
38
|
-
device: Device;
|
|
39
|
-
loggedIn?: boolean;
|
|
40
|
-
salesChannel?: string;
|
|
41
|
-
regionId?: string;
|
|
42
|
-
[key: string]: unknown;
|
|
43
|
-
}
|
|
38
|
+
/** Global the SSR publishes the token on, read back by `decoServerFnFetch`. */
|
|
39
|
+
export const CSEG_GLOBAL = "__DECO_CSEG";
|
|
40
|
+
|
|
41
|
+
/** RequestContext bag key the worker entry fills before rendering. */
|
|
42
|
+
export const CSEG_BAG_KEY = "deco.cdn.segmentToken";
|
|
44
43
|
|
|
45
44
|
/**
|
|
46
|
-
*
|
|
45
|
+
* Build the token for a segment, or `null` when this request must not be
|
|
46
|
+
* cached in front of the Worker.
|
|
47
47
|
*
|
|
48
|
-
*
|
|
48
|
+
* `null` — i.e. keep `no-store` — when:
|
|
49
49
|
*
|
|
50
|
-
* -
|
|
51
|
-
*
|
|
52
|
-
* safe to expose in a URL; everything else has to keep resolving in the
|
|
53
|
-
* Worker. Unknown fields fail closed precisely because we can't know whether
|
|
54
|
-
* a site's custom dimension is personal.
|
|
50
|
+
* - the visitor is logged in. Personalized responses never belong in a shared
|
|
51
|
+
* entry, no matter how precise the key is.
|
|
55
52
|
* - there is no build hash, or it is `"dev"`. The build is part of the token
|
|
56
|
-
* because deploying does
|
|
57
|
-
*
|
|
53
|
+
* because deploying does not purge the cache in front, so the URL has to
|
|
54
|
+
* change on its own when the bundle does.
|
|
55
|
+
*
|
|
56
|
+
* Everything else in the segment — device, sales channel, region, a site's own
|
|
57
|
+
* custom dimensions — is folded INTO the token rather than rejected. That is
|
|
58
|
+
* the difference from the first version: those are what the key needs to
|
|
59
|
+
* distinguish, not reasons to give up on caching.
|
|
58
60
|
*/
|
|
59
|
-
export function segmentToken(
|
|
61
|
+
export function segmentToken(
|
|
62
|
+
segmentDescriptor: string,
|
|
63
|
+
loggedIn: boolean,
|
|
64
|
+
buildHash: string | undefined,
|
|
65
|
+
): string | null {
|
|
66
|
+
if (loggedIn) return null;
|
|
60
67
|
if (!buildHash || buildHash === "dev") return null;
|
|
61
|
-
if (!
|
|
62
|
-
if (seg.loggedIn || seg.salesChannel || seg.regionId) return null;
|
|
63
|
-
|
|
64
|
-
// Any dimension we don't recognize is assumed personal.
|
|
65
|
-
for (const [key, value] of Object.entries(seg)) {
|
|
66
|
-
if (key === "device") continue;
|
|
67
|
-
if (value === undefined || value === false) continue;
|
|
68
|
-
if (Array.isArray(value) && value.length === 0) continue;
|
|
69
|
-
if (value === "") continue;
|
|
70
|
-
return null;
|
|
71
|
-
}
|
|
68
|
+
if (!segmentDescriptor) return null;
|
|
72
69
|
|
|
73
|
-
return `${
|
|
70
|
+
return djb2Hex(`${segmentDescriptor}|${buildHash}`);
|
|
74
71
|
}
|
package/src/sdk/serverFnFetch.ts
CHANGED
|
@@ -1,63 +1,59 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Client-side `serverFns.fetch` hook that
|
|
2
|
+
* Client-side `serverFns.fetch` hook that echoes the CDN segment marker onto
|
|
3
3
|
* `/_serverFn` URLs.
|
|
4
4
|
*
|
|
5
5
|
* Pairs with `cdnCacheControl: "serverfn-segment"` on `createDecoWorkerEntry`.
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* why that is the whole problem.
|
|
6
|
+
* Putting the segment in the URL is what makes the key of whatever caches in
|
|
7
|
+
* front of the Worker equivalent to the Worker's own — see `./cdnSegment`.
|
|
9
8
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
9
|
+
* The client does not COMPUTE the token, it repeats one the server issued and
|
|
10
|
+
* published on the page. That is deliberate: the segment includes dimensions
|
|
11
|
+
* only the server can see (region comes from `request.cf`), so a client-derived
|
|
12
|
+
* token never matched on a regionalized store and the feature stayed inert
|
|
13
|
+
* there.
|
|
13
14
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* forged or stale-build marker just keeps today's `no-store` — it can never
|
|
18
|
-
* produce a wrong response.
|
|
15
|
+
* Only client-initiated requests carry it — SPA navigation and prefetch, which
|
|
16
|
+
* is the volume Speculation Rules generates. The initial HTML document is a
|
|
17
|
+
* browser navigation with no hook to attach anything to.
|
|
19
18
|
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
19
|
+
* SECURITY: the marker is a HINT. The worker recomputes the segment from the
|
|
20
|
+
* request itself and only relaxes `no-store` on an exact match
|
|
21
|
+
* (`cdnCacheableServerFn` in `./workerEntry`). A missing, stale, forged or
|
|
22
|
+
* mismatched marker just keeps today's `no-store` — it can never produce a
|
|
23
|
+
* wrong response.
|
|
24
|
+
*
|
|
25
|
+
* Wired automatically: `decoVitePlugin` supplies `sdk/startEntry` as the Start
|
|
26
|
+
* entry when a site has no `src/start.ts` of its own. A site that owns one
|
|
27
|
+
* composes this itself:
|
|
25
28
|
*
|
|
29
|
+
* ```ts
|
|
30
|
+
* import { decoServerFnFetch } from "@decocms/tanstack/sdk/serverFnFetch";
|
|
26
31
|
* export const startInstance = createStart(() => ({
|
|
27
32
|
* serverFns: { fetch: decoServerFnFetch },
|
|
28
33
|
* }));
|
|
29
34
|
* ```
|
|
30
35
|
*/
|
|
31
36
|
|
|
32
|
-
import {
|
|
33
|
-
import { CSEG_PARAM, segmentToken } from "./cdnSegment";
|
|
34
|
-
|
|
35
|
-
declare const __DECO_BUILD_HASH__: string | undefined;
|
|
36
|
-
|
|
37
|
-
function buildHash(): string | undefined {
|
|
38
|
-
return typeof __DECO_BUILD_HASH__ !== "undefined" ? __DECO_BUILD_HASH__ : undefined;
|
|
39
|
-
}
|
|
37
|
+
import { CSEG_GLOBAL, CSEG_PARAM } from "./cdnSegment";
|
|
40
38
|
|
|
41
|
-
function
|
|
42
|
-
if (typeof
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
// catches it during verification and keeps the no-store — the marker simply
|
|
46
|
-
// won't match.
|
|
47
|
-
return segmentToken({ device: detectDevice(navigator.userAgent) }, buildHash());
|
|
39
|
+
function publishedMarker(): string | null {
|
|
40
|
+
if (typeof window === "undefined") return null;
|
|
41
|
+
const v = (window as unknown as Record<string, unknown>)[CSEG_GLOBAL];
|
|
42
|
+
return typeof v === "string" && v.length > 0 ? v : null;
|
|
48
43
|
}
|
|
49
44
|
|
|
50
45
|
/**
|
|
51
|
-
* Drop-in `serverFns.fetch
|
|
52
|
-
*
|
|
46
|
+
* Drop-in `serverFns.fetch`. Falls back to a plain `fetch` whenever there is no
|
|
47
|
+
* marker to echo — no marker simply means the response stays uncached in front
|
|
48
|
+
* of the Worker, which is the previous behaviour.
|
|
53
49
|
*/
|
|
54
50
|
export const decoServerFnFetch: typeof fetch = (input, init) => {
|
|
55
51
|
// TanStack's serverFnFetcher always calls with the URL already built as a
|
|
56
52
|
// string (start-client-core/src/client-rpc/serverFnFetcher.ts). Anything else
|
|
57
53
|
// goes through untouched.
|
|
58
54
|
if (typeof input !== "string") return fetch(input, init);
|
|
59
|
-
const marker =
|
|
55
|
+
const marker = publishedMarker();
|
|
60
56
|
if (!marker) return fetch(input, init);
|
|
61
57
|
const sep = input.includes("?") ? "&" : "?";
|
|
62
|
-
return fetch(`${input}${sep}${CSEG_PARAM}=${marker}`, init);
|
|
58
|
+
return fetch(`${input}${sep}${CSEG_PARAM}=${encodeURIComponent(marker)}`, init);
|
|
63
59
|
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Default TanStack Start entry, supplied by the framework when a site doesn't
|
|
3
|
+
* have its own `src/start.ts`.
|
|
4
|
+
*
|
|
5
|
+
* It exists so that CDN caching of `/_serverFn` is something a site gets from a
|
|
6
|
+
* version bump instead of a per-site PR. The only thing it wires is
|
|
7
|
+
* `decoServerFnFetch`, which appends the cache segment to server-function URLs
|
|
8
|
+
* — see `./cdnSegment` for why that is what makes the CDN key match the
|
|
9
|
+
* Worker's.
|
|
10
|
+
*
|
|
11
|
+
* A site that declares its own `src/start.ts` keeps it: `decoVitePlugin` only
|
|
12
|
+
* aliases this module in when that file is absent. Such a site opts into the
|
|
13
|
+
* CDN behaviour by composing `decoServerFnFetch` itself:
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* import { decoServerFnFetch } from "@decocms/tanstack/sdk/serverFnFetch";
|
|
17
|
+
* export const startInstance = createStart(() => ({
|
|
18
|
+
* serverFns: { fetch: decoServerFnFetch },
|
|
19
|
+
* }));
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* The export name is load-bearing: `@tanstack/start-client-core`'s
|
|
23
|
+
* `hydrateStart` does `import { startInstance } from "#tanstack-start-entry"`.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { createStart } from "@tanstack/react-start";
|
|
27
|
+
import { decoServerFnFetch } from "./serverFnFetch";
|
|
28
|
+
|
|
29
|
+
export const startInstance = createStart(() => ({
|
|
30
|
+
serverFns: { fetch: decoServerFnFetch },
|
|
31
|
+
}));
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { setBlocks } from "@decocms/blocks/cms";
|
|
2
2
|
import { afterEach, describe, expect, it } from "vitest";
|
|
3
3
|
import { __resetKvHydrationStateForTests } from "./kvHydration";
|
|
4
|
+
import { segmentToken } from "./cdnSegment";
|
|
4
5
|
import {
|
|
5
6
|
buildGeoCacheParam,
|
|
6
7
|
createDecoWorkerEntry,
|
|
@@ -740,6 +741,9 @@ describe("draft preview (pull-based)", () => {
|
|
|
740
741
|
describe('cdnCacheControl: "serverfn-segment"', () => {
|
|
741
742
|
const BUILD = "abc123";
|
|
742
743
|
const ENV = { BUILD_HASH: BUILD };
|
|
744
|
+
// The token is a hash the server issues, so tests derive it the same way the
|
|
745
|
+
// worker does instead of hardcoding a shape.
|
|
746
|
+
const tok = (seg: string) => segmentToken(seg, false, BUILD) as string;
|
|
743
747
|
|
|
744
748
|
function worker(overrides: Record<string, unknown> = {}) {
|
|
745
749
|
return createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
|
|
@@ -764,7 +768,7 @@ describe('cdnCacheControl: "serverfn-segment"', () => {
|
|
|
764
768
|
}
|
|
765
769
|
|
|
766
770
|
it("releases the CDN when the marker matches the recomputed segment", async () => {
|
|
767
|
-
expect(await cdnHeader(sfnUrl(
|
|
771
|
+
expect(await cdnHeader(sfnUrl(tok("desktop")))).toMatch(/^public, max-age=\d+$/);
|
|
768
772
|
});
|
|
769
773
|
|
|
770
774
|
it("keeps no-store without a marker (bot, curl, old client)", async () => {
|
|
@@ -774,16 +778,16 @@ describe('cdnCacheControl: "serverfn-segment"', () => {
|
|
|
774
778
|
it("keeps no-store when the marker is for another device", async () => {
|
|
775
779
|
// The forged/diverging case: a desktop request claiming a mobile entry
|
|
776
780
|
// would let the CDN serve mobile HTML to desktop.
|
|
777
|
-
expect(await cdnHeader(sfnUrl(
|
|
781
|
+
expect(await cdnHeader(sfnUrl(tok("mobile")))).toBe("no-store");
|
|
778
782
|
});
|
|
779
783
|
|
|
780
784
|
it("keeps no-store when the marker is from an older build", async () => {
|
|
781
785
|
// Deploying does not purge the CDN, so a stale build token must not match.
|
|
782
|
-
expect(await cdnHeader(sfnUrl("desktop
|
|
786
|
+
expect(await cdnHeader(sfnUrl(segmentToken("desktop", false, "oldbuild") as string))).toBe("no-store");
|
|
783
787
|
});
|
|
784
788
|
|
|
785
789
|
it("keeps no-store when there is no build hash", async () => {
|
|
786
|
-
const res = await worker().fetch(new Request(sfnUrl(
|
|
790
|
+
const res = await worker().fetch(new Request(sfnUrl(tok("desktop"))), {}, MOCK_CTX);
|
|
787
791
|
expect(res.headers.get("CDN-Cache-Control")).toBe("no-store");
|
|
788
792
|
});
|
|
789
793
|
|
|
@@ -791,7 +795,7 @@ describe('cdnCacheControl: "serverfn-segment"', () => {
|
|
|
791
795
|
// Bots render every section eagerly (~10x payload). Sharing one CDN entry
|
|
792
796
|
// would serve that to humans, or the deferred one to crawlers.
|
|
793
797
|
expect(
|
|
794
|
-
await cdnHeader(sfnUrl(
|
|
798
|
+
await cdnHeader(sfnUrl(tok("desktop")), {
|
|
795
799
|
"user-agent": "Mozilla/5.0 (compatible; Googlebot/2.1)",
|
|
796
800
|
}),
|
|
797
801
|
).toBe("no-store");
|
|
@@ -799,41 +803,88 @@ describe('cdnCacheControl: "serverfn-segment"', () => {
|
|
|
799
803
|
|
|
800
804
|
it("keeps no-store for an A/B cohort cookie even with a valid marker", async () => {
|
|
801
805
|
expect(
|
|
802
|
-
await cdnHeader(sfnUrl(
|
|
806
|
+
await cdnHeader(sfnUrl(tok("desktop")), {
|
|
803
807
|
cookie: "deco_segment=eyJhY3RpdmUiOlsiYSJdfQ==",
|
|
804
808
|
}),
|
|
805
809
|
).toBe("no-store");
|
|
806
810
|
});
|
|
807
811
|
|
|
808
812
|
it("keeps no-store for a logged-in request", async () => {
|
|
809
|
-
expect(await cdnHeader(sfnUrl(
|
|
813
|
+
expect(await cdnHeader(sfnUrl(tok("desktop")), { cookie: "auth=1" })).toBe("no-store");
|
|
810
814
|
});
|
|
811
815
|
|
|
812
816
|
it("keeps no-store on HTML documents — they carry no marker", async () => {
|
|
813
817
|
expect(await cdnHeader("https://example.com/some-category")).toBe("no-store");
|
|
814
818
|
});
|
|
815
819
|
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
820
|
+
// NOTE: the end-to-end geo case is not exercised here. `injectGeoCookies`
|
|
821
|
+
// rebuilds the Request, and `new Request(req, init)` only carries `cf`
|
|
822
|
+
// through on workerd — under Node it is dropped, so a test would assert the
|
|
823
|
+
// absence of geo rather than its handling. The unit case below covers the
|
|
824
|
+
// property that matters, and the real path is verified against a built site.
|
|
825
|
+
it("never lets two regions share a token", () => {
|
|
826
|
+
// The leak this guards: RJ and SP resolving to the same colo must not
|
|
827
|
+
// share an entry, since their regionalized pricing and stock differ.
|
|
828
|
+
expect(tok("desktop|geo=BR|RJ")).not.toBe(tok("desktop|geo=BR|SP"));
|
|
829
|
+
});
|
|
830
|
+
|
|
831
|
+
it("keeps no-store without buildSegment, since the logged-in bypass is inert", async () => {
|
|
821
832
|
const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
|
|
822
833
|
observability: false,
|
|
823
834
|
cdnCacheControl: "serverfn-segment",
|
|
824
|
-
geoCacheKey: "region",
|
|
825
|
-
buildSegment: () => ({ device: "desktop" as const }),
|
|
826
835
|
});
|
|
827
|
-
const res = await w.fetch(new Request(sfnUrl(
|
|
836
|
+
const res = await w.fetch(new Request(sfnUrl(tok("desktop"))), ENV, MOCK_CTX);
|
|
828
837
|
expect(res.headers.get("CDN-Cache-Control")).toBe("no-store");
|
|
829
838
|
});
|
|
839
|
+
});
|
|
830
840
|
|
|
831
|
-
|
|
841
|
+
describe("cdnCacheControl default", () => {
|
|
842
|
+
const BUILD_D = "abc123";
|
|
843
|
+
const tokD = (seg: string) => segmentToken(seg, false, BUILD_D) as string;
|
|
844
|
+
|
|
845
|
+
// The default flipped from "no-store" to "serverfn-segment". That is only
|
|
846
|
+
// safe because it is inert until a verified marker arrives — these two tests
|
|
847
|
+
// are what make that claim checkable rather than asserted in a comment.
|
|
848
|
+
it("is inert for a client that never sends a marker", async () => {
|
|
832
849
|
const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
|
|
833
850
|
observability: false,
|
|
834
|
-
|
|
851
|
+
buildSegment: () => ({ device: "desktop" as const }),
|
|
835
852
|
});
|
|
836
|
-
const
|
|
853
|
+
const html = await w.fetch(new Request("https://example.com/"), { BUILD_HASH: BUILD_D }, MOCK_CTX);
|
|
854
|
+
expect(html.headers.get("CDN-Cache-Control")).toBe("no-store");
|
|
855
|
+
|
|
856
|
+
const sfn = await w.fetch(
|
|
857
|
+
new Request("https://example.com/_serverFn/loadCmsPage"),
|
|
858
|
+
{ BUILD_HASH: BUILD_D },
|
|
859
|
+
MOCK_CTX,
|
|
860
|
+
);
|
|
861
|
+
expect(sfn.headers.get("CDN-Cache-Control")).toBe("no-store");
|
|
862
|
+
});
|
|
863
|
+
|
|
864
|
+
it("engages once the client sends a valid marker, with no site config", async () => {
|
|
865
|
+
const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
|
|
866
|
+
observability: false,
|
|
867
|
+
buildSegment: () => ({ device: "desktop" as const }),
|
|
868
|
+
});
|
|
869
|
+
const res = await w.fetch(
|
|
870
|
+
new Request(`https://example.com/_serverFn/loadCmsPage?__cseg=${tokD("desktop")}`),
|
|
871
|
+
{ BUILD_HASH: BUILD_D },
|
|
872
|
+
MOCK_CTX,
|
|
873
|
+
);
|
|
874
|
+
expect(res.headers.get("CDN-Cache-Control")).toMatch(/^public, max-age=\d+$/);
|
|
875
|
+
});
|
|
876
|
+
|
|
877
|
+
it('still honours an explicit opt-out with "no-store"', async () => {
|
|
878
|
+
const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
|
|
879
|
+
observability: false,
|
|
880
|
+
cdnCacheControl: "no-store",
|
|
881
|
+
buildSegment: () => ({ device: "desktop" as const }),
|
|
882
|
+
});
|
|
883
|
+
const res = await w.fetch(
|
|
884
|
+
new Request(`https://example.com/_serverFn/loadCmsPage?__cseg=${tokD("desktop")}`),
|
|
885
|
+
{ BUILD_HASH: BUILD_D },
|
|
886
|
+
MOCK_CTX,
|
|
887
|
+
);
|
|
837
888
|
expect(res.headers.get("CDN-Cache-Control")).toBe("no-store");
|
|
838
889
|
});
|
|
839
890
|
});
|
package/src/sdk/workerEntry.ts
CHANGED
|
@@ -53,7 +53,7 @@ import {
|
|
|
53
53
|
} from "@decocms/blocks/sdk/cacheHeaders";
|
|
54
54
|
import { isDevMode } from "@decocms/blocks/sdk/env";
|
|
55
55
|
import { parseSegmentCookie, SEGMENT_COOKIE, segmentCacheToken } from "@decocms/blocks/sdk/flags";
|
|
56
|
-
import { CSEG_PARAM, segmentToken } from "./cdnSegment";
|
|
56
|
+
import { CSEG_BAG_KEY, CSEG_PARAM, segmentToken } from "./cdnSegment";
|
|
57
57
|
import {
|
|
58
58
|
getActiveSpan,
|
|
59
59
|
logRequest,
|
|
@@ -508,13 +508,18 @@ export interface DecoWorkerEntryOptions {
|
|
|
508
508
|
* desktop HTML to mobile, one region's to another, or a crawler's eager
|
|
509
509
|
* render to humans.
|
|
510
510
|
*
|
|
511
|
-
* - `"
|
|
512
|
-
*
|
|
513
|
-
*
|
|
514
|
-
*
|
|
515
|
-
*
|
|
516
|
-
*
|
|
517
|
-
*
|
|
511
|
+
* - `"serverfn-segment"` (default): allow CDN caching for `/_serverFn`
|
|
512
|
+
* requests whose URL carries a verified `__cseg` marker (see
|
|
513
|
+
* `./cdnSegment` and `decoServerFnFetch`). The marker makes the CDN's key
|
|
514
|
+
* equivalent to the Worker's. HTML documents keep `no-store` — the initial
|
|
515
|
+
* navigation is a browser request with no client hook to attach a marker.
|
|
516
|
+
*
|
|
517
|
+
* This is the default because it is inert until a marker actually arrives:
|
|
518
|
+
* a client that never sends `__cseg` keeps getting `no-store`, so enabling
|
|
519
|
+
* it cannot change behaviour on its own. That is what lets a site pick the
|
|
520
|
+
* feature up from a version bump rather than a per-site change.
|
|
521
|
+
* - `"no-store"`: the CDN never caches; every request invokes the Worker.
|
|
522
|
+
* Always correct, never fast. Set this to opt OUT.
|
|
518
523
|
* - `"match-profile"`: mirror the profile's `edge.fresh` as a CDN TTL. Sound
|
|
519
524
|
* ONLY when the cache key is the raw URL — no `buildSegment`,
|
|
520
525
|
* `deviceSpecificKeys: false`, `geoCacheKey: "off"`. Since
|
|
@@ -528,7 +533,7 @@ export interface DecoWorkerEntryOptions {
|
|
|
528
533
|
* whatever sits in front of the Worker has to reproduce the key above, and
|
|
529
534
|
* the initial navigation has no client hook to attach a marker to.
|
|
530
535
|
*
|
|
531
|
-
* @default "
|
|
536
|
+
* @default "serverfn-segment"
|
|
532
537
|
*/
|
|
533
538
|
cdnCacheControl?:
|
|
534
539
|
| "no-store"
|
|
@@ -995,7 +1000,7 @@ export function createDecoWorkerEntry(
|
|
|
995
1000
|
geoCacheKey: geoCacheKeyOpt = "auto",
|
|
996
1001
|
safeCookies: safeCookiesOpt = DEFAULT_SAFE_COOKIES,
|
|
997
1002
|
staticPaths: staticPathsOpt = DEFAULT_STATIC_PATHS,
|
|
998
|
-
cdnCacheControl: cdnCacheControlOpt = "
|
|
1003
|
+
cdnCacheControl: cdnCacheControlOpt = "serverfn-segment",
|
|
999
1004
|
observability: observabilityOpt,
|
|
1000
1005
|
outboundUserAgent: outboundUserAgentOpt,
|
|
1001
1006
|
speculationRules: speculationRulesOpt,
|
|
@@ -1270,21 +1275,40 @@ export function createDecoWorkerEntry(
|
|
|
1270
1275
|
return false;
|
|
1271
1276
|
}
|
|
1272
1277
|
|
|
1273
|
-
// `__cf_geo` in buildCacheKey
|
|
1274
|
-
//
|
|
1275
|
-
//
|
|
1276
|
-
//
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
if (effectiveGeoKey() !== "off") return false;
|
|
1283
|
-
|
|
1284
|
-
const expected = segmentToken(buildSegment(request), getBuildHash(env));
|
|
1278
|
+
// `__cf_geo` in buildCacheKey is a dimension the segment descriptor does not
|
|
1279
|
+
// carry: it comes from `buildGeoCacheParam` (country/region/city) rather
|
|
1280
|
+
// than from `buildSegment`. Fold it in so two visitors keyed differently by
|
|
1281
|
+
// the Worker can never share a URL.
|
|
1282
|
+
const expected = segmentToken(
|
|
1283
|
+
requestSegmentDescriptor(request),
|
|
1284
|
+
buildSegment(request).loggedIn === true,
|
|
1285
|
+
getBuildHash(env),
|
|
1286
|
+
);
|
|
1285
1287
|
return expected !== null && marker === expected;
|
|
1286
1288
|
}
|
|
1287
1289
|
|
|
1290
|
+
/**
|
|
1291
|
+
* The full set of dimensions the Worker keys this request on, as one string.
|
|
1292
|
+
*
|
|
1293
|
+
* MUST stay in step with `buildCacheKey` — it is the same question ("what
|
|
1294
|
+
* makes this response different from another visitor's?") asked in a form
|
|
1295
|
+
* that fits in a URL. A dimension present there and missing here is a
|
|
1296
|
+
* cross-visitor leak, which is why both read the same helpers rather than
|
|
1297
|
+
* re-deriving anything.
|
|
1298
|
+
*/
|
|
1299
|
+
function requestSegmentDescriptor(request: Request): string {
|
|
1300
|
+
if (!buildSegment) return "";
|
|
1301
|
+
const parts = [hashSegment(buildSegment(request))];
|
|
1302
|
+
|
|
1303
|
+
const geo = buildGeoCacheParam(
|
|
1304
|
+
(request as unknown as { cf?: Record<string, string> }).cf,
|
|
1305
|
+
effectiveGeoKey(),
|
|
1306
|
+
);
|
|
1307
|
+
if (geo) parts.push(`geo=${geo}`);
|
|
1308
|
+
|
|
1309
|
+
return parts.join("|");
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1288
1312
|
function buildCacheKey(
|
|
1289
1313
|
request: Request,
|
|
1290
1314
|
env: Record<string, unknown>,
|
|
@@ -1760,6 +1784,20 @@ export function createDecoWorkerEntry(
|
|
|
1760
1784
|
|
|
1761
1785
|
// Run app middleware (injects app state into RequestContext.bag,
|
|
1762
1786
|
// runs registered middleware like VTEX cookie forwarding).
|
|
1787
|
+
// Publish the segment token so the SSR can hand it to the browser
|
|
1788
|
+
// (see sdk/cdnSegment). Only the server can compute this: region
|
|
1789
|
+
// comes from `request.cf`, which the client never sees. Per-request
|
|
1790
|
+
// via the RequestContext bag — a module-level global here would be
|
|
1791
|
+
// the layout-cache race all over again.
|
|
1792
|
+
if (buildSegment && cdnCacheControlOpt === "serverfn-segment") {
|
|
1793
|
+
const token = segmentToken(
|
|
1794
|
+
requestSegmentDescriptor(request),
|
|
1795
|
+
buildSegment(request).loggedIn === true,
|
|
1796
|
+
getBuildHash(env),
|
|
1797
|
+
);
|
|
1798
|
+
if (token) RequestContext.setBag(CSEG_BAG_KEY, token);
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1763
1801
|
const appMw = getAppMiddleware();
|
|
1764
1802
|
const innerResponse = appMw
|
|
1765
1803
|
? await appMw(request, () => handleRequest(request, env, ctx))
|
package/src/vite/plugin.js
CHANGED
|
@@ -690,6 +690,33 @@ export function decoVitePlugin() {
|
|
|
690
690
|
/** @type {import("vite").UserConfig} */
|
|
691
691
|
const cfg = {};
|
|
692
692
|
|
|
693
|
+
// Supply a default TanStack Start entry when the site has none.
|
|
694
|
+
//
|
|
695
|
+
// `#tanstack-start-entry` is a subpath import of
|
|
696
|
+
// @tanstack/start-client-core; with no `src/start.ts` it resolves to a
|
|
697
|
+
// fake entry exporting `startInstance = undefined`, and the site gets no
|
|
698
|
+
// `serverFns.fetch` hook. That hook is what appends the cache segment to
|
|
699
|
+
// `/_serverFn` URLs (see sdk/cdnSegment), so without it CDN caching of
|
|
700
|
+
// SPA navigation can never engage.
|
|
701
|
+
//
|
|
702
|
+
// Aliasing it here means a site gets that from a version bump instead of
|
|
703
|
+
// a per-site PR. Strictly conditional on the file being absent: a site
|
|
704
|
+
// that owns its `src/start.ts` must keep it, since ours would otherwise
|
|
705
|
+
// silently replace whatever else it configures.
|
|
706
|
+
const siteStartEntry = ["ts", "tsx", "js", "jsx"]
|
|
707
|
+
.map((ext) => path.join(process.cwd(), "src", `start.${ext}`))
|
|
708
|
+
.find((f) => existsSync(f));
|
|
709
|
+
|
|
710
|
+
if (!siteStartEntry) {
|
|
711
|
+
cfg.resolve = {
|
|
712
|
+
...cfg.resolve,
|
|
713
|
+
alias: {
|
|
714
|
+
...cfg.resolve?.alias,
|
|
715
|
+
"#tanstack-start-entry": "@decocms/tanstack/sdk/startEntry",
|
|
716
|
+
},
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
|
|
693
720
|
// Allow tunnel domains through Vite's host check.
|
|
694
721
|
// .deco.studio is the new admin frontend; both real-world Deco sites
|
|
695
722
|
// (casaevideo-storefront, baggagio-tanstack) duplicated this list to
|