@decocms/tanstack 7.57.0 → 7.59.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/tanstack",
3
- "version": "7.57.0",
3
+ "version": "7.59.0",
4
4
  "type": "module",
5
5
  "description": "Deco framework binding for TanStack Start + Cloudflare Workers",
6
6
  "repository": {
@@ -27,9 +27,9 @@
27
27
  "lint:unused": "knip"
28
28
  },
29
29
  "dependencies": {
30
- "@decocms/blocks": "7.57.0",
31
- "@decocms/blocks-admin": "7.57.0",
32
- "@decocms/blocks-cli": "7.57.0",
30
+ "@decocms/blocks": "7.59.0",
31
+ "@decocms/blocks-admin": "7.59.0",
32
+ "@decocms/blocks-cli": "7.59.0",
33
33
  "@deco-cx/warp-node": "^0.3.16",
34
34
  "fast-json-patch": "^3.1.0",
35
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("anonymous: token is device.build", () => {
8
- expect(segmentToken({ device: "mobile" }, BUILD)).toBe("mobile.abc123");
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("mobile and desktop never share a token", () => {
15
- expect(segmentToken({ device: "mobile" }, BUILD)).not.toBe(
16
- segmentToken({ device: "desktop" }, BUILD),
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("personalization disables CDN caching", () => {
21
- expect(segmentToken({ device: "mobile", loggedIn: true }, BUILD)).toBeNull();
22
- expect(segmentToken({ device: "mobile", regionId: "v2.XYZ" }, BUILD)).toBeNull();
23
- expect(segmentToken({ device: "mobile", salesChannel: "3" }, BUILD)).toBeNull();
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("an unknown custom dimension fails closed", () => {
27
- // A site adding its own SegmentKey field must not silently share entries
28
- // across that dimension.
29
- expect(segmentToken({ device: "mobile", storeId: "sp-01" }, BUILD)).toBeNull();
30
- expect(segmentToken({ device: "mobile", flags: ["promo"] }, BUILD)).toBeNull();
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("empty-ish custom values do not disable caching", () => {
34
- // These carry no dimension — hashSegment skips them too, so the Worker key
35
- // is identical with or without them.
36
- expect(segmentToken({ device: "mobile", storeId: "" }, BUILD)).toBe("mobile.abc123");
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 disables CDN caching", () => {
43
- // without a build hash there is no way to invalidate on deploy — the CDN
44
- // would serve stale code
45
- expect(segmentToken({ device: "mobile" }, undefined)).toBeNull();
46
- expect(segmentToken({ device: "mobile" }, "")).toBeNull();
47
- expect(segmentToken({ device: "mobile" }, "dev")).toBeNull();
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("a different build yields a different token (invalidates on deploy)", () => {
51
- expect(segmentToken({ device: "mobile" }, "buildA")).not.toBe(
52
- segmentToken({ device: "mobile" }, "buildB"),
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
  });
@@ -1,74 +1,71 @@
1
1
  /**
2
- * Segment marker on `/_serverFn` URLs, so Cloudflare's CDN can serve the
3
- * response without invoking the Worker.
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: the CDN keys on the raw URL. The Worker keys on a SYNTHETIC
6
- * Request carrying `__seg`/`__v`/`__bot`/`__fetch`/`__abf` (`buildCacheKey` in
7
- * `./workerEntry`) — params the CDN never sees. That mismatch is why the
8
- * framework stamps `CDN-Cache-Control: no-store` on every public response, and
9
- * why 100% of traffic comes back `cf-cache-status: BYPASS`.
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. The CDN's key then becomes
12
- * equivalent to the Worker's, and relaxing the `no-store` is safe.
11
+ * The fix: put the segment in the URL itself, so the two keys become
12
+ * equivalent.
13
13
  *
14
- * This is the ONLY definition of the token format. The client uses it to build
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
- * Note the split of responsibilities: this module covers what is observable on
19
- * BOTH sides (device + build). Request-only dimensions — bot UA, the A/B
20
- * cookie — are checked by the worker alone, in `cdnServerFnToken`. A client
21
- * that can't see them just emits a marker that fails verification, which keeps
22
- * the existing `no-store`.
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 type { Device } from "@decocms/blocks/sdk/detectDevice";
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
- * The subset of `SegmentKey` this token can express.
32
- *
33
- * Deliberately structural rather than importing `SegmentKey` from
34
- * `./workerEntry`: this module is bundled into the CLIENT, and workerEntry
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
- * The segment token, or `null` when this request must not be CDN-cached.
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
- * Returns `null` — keeping today's `no-store` — when:
48
+ * `null` — i.e. keep `no-store` — when:
49
49
  *
50
- * - there is any personalization beyond device (`loggedIn`, `salesChannel`,
51
- * `regionId`, or any custom `SegmentKey` field a site added). Only device is
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 NOT purge the CDN (the framework's purge clears
57
- * `caches.default`), so the URL has to change on its own when the bundle does.
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(seg: CdnSegment, buildHash: string | undefined): string | null {
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 (!seg.device) return null;
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 `${seg.device}.${buildHash}`;
70
+ return djb2Hex(`${segmentDescriptor}|${buildHash}`);
74
71
  }
@@ -1,63 +1,59 @@
1
1
  /**
2
- * Client-side `serverFns.fetch` hook that attaches the CDN segment marker to
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
- * Attaching the segment to the URL makes Cloudflare's CDN key (the raw URL)
7
- * equivalent to the key the Worker builds internally — see `./cdnSegment` for
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
- * Only the client can do this: the initial HTML document is a browser
11
- * navigation with no JS hook. This covers SPA data requests and prefetches,
12
- * which is the volume Speculation Rules creates.
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
- * SECURITY: the marker is a HINT, not a source of truth. The worker recomputes
15
- * the segment from the request itself and only releases the CDN when it matches
16
- * exactly (`cdnCacheableServerFn` in `./workerEntry`). A missing, diverging,
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
- * @example
21
- * ```ts
22
- * // src/start.ts
23
- * import { createStart } from "@tanstack/react-start";
24
- * import { decoServerFnFetch } from "@decocms/tanstack";
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 { detectDevice } from "@decocms/blocks/sdk/detectDevice";
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 segmentMarker(): string | null {
42
- if (typeof navigator === "undefined") return null;
43
- // Device is the only dimension observable on the client. If this request is
44
- // in fact from a logged-in user, or in a region, or an A/B cohort, the worker
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` implementation. Falls back to a plain `fetch` when
52
- * there is no marker to add.
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 = segmentMarker();
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
  };
@@ -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(`desktop.${BUILD}`))).toMatch(/^public, max-age=\d+$/);
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(`mobile.${BUILD}`))).toBe("no-store");
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.oldbuild"))).toBe("no-store");
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(`desktop.${BUILD}`)), {}, MOCK_CTX);
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(`desktop.${BUILD}`), {
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,33 +803,29 @@ 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(`desktop.${BUILD}`), {
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(`desktop.${BUILD}`), { cookie: "auth=1" })).toBe("no-store");
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
- it("keeps no-store when the cache key varies by geo", async () => {
817
- // `__cf_geo` is in the Worker key but cannot be expressed in the marker nor
818
- // reproduced by the CDN, so a site with geo keying must not release it —
819
- // otherwise one region's regionalized data (pricing, stock, store) is
820
- // served to another from the same colo.
821
- const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
822
- observability: false,
823
- cdnCacheControl: "serverfn-segment",
824
- geoCacheKey: "region",
825
- buildSegment: () => ({ device: "desktop" as const }),
826
- });
827
- const res = await w.fetch(new Request(sfnUrl(`desktop.${BUILD}`)), ENV, MOCK_CTX);
828
- expect(res.headers.get("CDN-Cache-Control")).toBe("no-store");
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
829
  });
830
830
 
831
831
  it("keeps no-store without buildSegment, since the logged-in bypass is inert", async () => {
@@ -833,13 +833,14 @@ describe('cdnCacheControl: "serverfn-segment"', () => {
833
833
  observability: false,
834
834
  cdnCacheControl: "serverfn-segment",
835
835
  });
836
- const res = await w.fetch(new Request(sfnUrl(`desktop.${BUILD}`)), ENV, MOCK_CTX);
836
+ const res = await w.fetch(new Request(sfnUrl(tok("desktop"))), ENV, MOCK_CTX);
837
837
  expect(res.headers.get("CDN-Cache-Control")).toBe("no-store");
838
838
  });
839
839
  });
840
840
 
841
841
  describe("cdnCacheControl default", () => {
842
842
  const BUILD_D = "abc123";
843
+ const tokD = (seg: string) => segmentToken(seg, false, BUILD_D) as string;
843
844
 
844
845
  // The default flipped from "no-store" to "serverfn-segment". That is only
845
846
  // safe because it is inert until a verified marker arrives — these two tests
@@ -866,7 +867,7 @@ describe("cdnCacheControl default", () => {
866
867
  buildSegment: () => ({ device: "desktop" as const }),
867
868
  });
868
869
  const res = await w.fetch(
869
- new Request(`https://example.com/_serverFn/loadCmsPage?__cseg=desktop.${BUILD_D}`),
870
+ new Request(`https://example.com/_serverFn/loadCmsPage?__cseg=${tokD("desktop")}`),
870
871
  { BUILD_HASH: BUILD_D },
871
872
  MOCK_CTX,
872
873
  );
@@ -880,7 +881,7 @@ describe("cdnCacheControl default", () => {
880
881
  buildSegment: () => ({ device: "desktop" as const }),
881
882
  });
882
883
  const res = await w.fetch(
883
- new Request(`https://example.com/_serverFn/loadCmsPage?__cseg=desktop.${BUILD_D}`),
884
+ new Request(`https://example.com/_serverFn/loadCmsPage?__cseg=${tokD("desktop")}`),
884
885
  { BUILD_HASH: BUILD_D },
885
886
  MOCK_CTX,
886
887
  );
@@ -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,
@@ -1275,21 +1275,40 @@ export function createDecoWorkerEntry(
1275
1275
  return false;
1276
1276
  }
1277
1277
 
1278
- // `__cf_geo` in buildCacheKey, which the marker cannot express and the CDN
1279
- // cannot reproduce. Mostly moot — with geo on, the `buildSegment` wrapper
1280
- // back-fills `regionId`, and any `regionId` already makes `segmentToken`
1281
- // return null. But the back-fill reads only `cf.regionCode` while
1282
- // `buildGeoCacheParam` keys on country/region/city, so a request with a
1283
- // country but no region code (Tor exits, some carriers, countries without
1284
- // first-level subdivisions) slips through with a releasable token while the
1285
- // Worker key still varies by geo. Refuse outright, the same way the
1286
- // `match-profile` branch below does.
1287
- if (effectiveGeoKey() !== "off") return false;
1288
-
1289
- 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
+ );
1290
1287
  return expected !== null && marker === expected;
1291
1288
  }
1292
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
+
1293
1312
  function buildCacheKey(
1294
1313
  request: Request,
1295
1314
  env: Record<string, unknown>,
@@ -1765,6 +1784,20 @@ export function createDecoWorkerEntry(
1765
1784
 
1766
1785
  // Run app middleware (injects app state into RequestContext.bag,
1767
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
+
1768
1801
  const appMw = getAppMiddleware();
1769
1802
  const innerResponse = appMw
1770
1803
  ? await appMw(request, () => handleRequest(request, env, ctx))