@decocms/tanstack 7.55.2 → 7.57.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.55.2",
3
+ "version": "7.57.0",
4
4
  "type": "module",
5
5
  "description": "Deco framework binding for TanStack Start + Cloudflare Workers",
6
6
  "repository": {
@@ -15,7 +15,10 @@
15
15
  "./daemon": "./src/daemon/index.ts",
16
16
  "./sdk/createInvoke": "./src/sdk/createInvoke.ts",
17
17
  "./sdk/cookiePassthrough": "./src/sdk/cookiePassthrough.ts",
18
- "./sdk/deferredSectionLoader": "./src/sdk/deferredSectionLoader.ts"
18
+ "./sdk/deferredSectionLoader": "./src/sdk/deferredSectionLoader.ts",
19
+ "./sdk/serverFnFetch": "./src/sdk/serverFnFetch.ts",
20
+ "./sdk/startEntry": "./src/sdk/startEntry.ts",
21
+ "./sdk/cdnSegment": "./src/sdk/cdnSegment.ts"
19
22
  },
20
23
  "scripts": {
21
24
  "build": "tsc",
@@ -24,9 +27,9 @@
24
27
  "lint:unused": "knip"
25
28
  },
26
29
  "dependencies": {
27
- "@decocms/blocks": "7.55.2",
28
- "@decocms/blocks-admin": "7.55.2",
29
- "@decocms/blocks-cli": "7.55.2",
30
+ "@decocms/blocks": "7.57.0",
31
+ "@decocms/blocks-admin": "7.57.0",
32
+ "@decocms/blocks-cli": "7.57.0",
30
33
  "@deco-cx/warp-node": "^0.3.16",
31
34
  "fast-json-patch": "^3.1.0",
32
35
  "ws": "^8.18.0"
package/src/index.ts CHANGED
@@ -52,3 +52,8 @@ export type {
52
52
  // parses (never imports) to emit real top-level createServerFn declarations
53
53
  // into each site's own src/server/invoke.gen.ts. Import it from the
54
54
  // dedicated "@decocms/tanstack/sdk/createInvoke" subpath instead.
55
+ // decoServerFnFetch is intentionally NOT re-exported from this root barrel
56
+ // either. A site wires it in `src/start.ts`, which is part of the CLIENT
57
+ // bundle; importing it from here would drag `createDecoWorkerEntry` (and the
58
+ // whole server graph behind it) into that bundle. Import it from the dedicated
59
+ // "@decocms/tanstack/sdk/serverFnFetch" subpath instead.
@@ -0,0 +1,55 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { segmentToken } from "./cdnSegment";
3
+
4
+ const BUILD = "abc123";
5
+
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");
12
+ });
13
+
14
+ it("mobile and desktop never share a token", () => {
15
+ expect(segmentToken({ device: "mobile" }, BUILD)).not.toBe(
16
+ segmentToken({ device: "desktop" }, BUILD),
17
+ );
18
+ });
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();
24
+ });
25
+
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();
31
+ });
32
+
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");
40
+ });
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();
48
+ });
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"),
53
+ );
54
+ });
55
+ });
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Segment marker on `/_serverFn` URLs, so Cloudflare's CDN can serve the
3
+ * response without invoking the Worker.
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`.
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.
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.
17
+ *
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`.
23
+ */
24
+
25
+ import type { Device } from "@decocms/blocks/sdk/detectDevice";
26
+
27
+ /** `__d` is reserved: `workerEntry` uses `?__d=` as an OTel debug flag. */
28
+ export const CSEG_PARAM = "__cseg";
29
+
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
+ }
44
+
45
+ /**
46
+ * The segment token, or `null` when this request must not be CDN-cached.
47
+ *
48
+ * Returns `null` — keeping today's `no-store` — when:
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.
55
+ * - 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.
58
+ */
59
+ export function segmentToken(seg: CdnSegment, buildHash: string | undefined): string | null {
60
+ 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
+ }
72
+
73
+ return `${seg.device}.${buildHash}`;
74
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Client-side `serverFns.fetch` hook that attaches the CDN segment marker to
3
+ * `/_serverFn` URLs.
4
+ *
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.
9
+ *
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.
13
+ *
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.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * // src/start.ts
23
+ * import { createStart } from "@tanstack/react-start";
24
+ * import { decoServerFnFetch } from "@decocms/tanstack";
25
+ *
26
+ * export const startInstance = createStart(() => ({
27
+ * serverFns: { fetch: decoServerFnFetch },
28
+ * }));
29
+ * ```
30
+ */
31
+
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
+ }
40
+
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());
48
+ }
49
+
50
+ /**
51
+ * Drop-in `serverFns.fetch` implementation. Falls back to a plain `fetch` when
52
+ * there is no marker to add.
53
+ */
54
+ export const decoServerFnFetch: typeof fetch = (input, init) => {
55
+ // TanStack's serverFnFetcher always calls with the URL already built as a
56
+ // string (start-client-core/src/client-rpc/serverFnFetcher.ts). Anything else
57
+ // goes through untouched.
58
+ if (typeof input !== "string") return fetch(input, init);
59
+ const marker = segmentMarker();
60
+ if (!marker) return fetch(input, init);
61
+ const sep = input.includes("?") ? "&" : "?";
62
+ return fetch(`${input}${sep}${CSEG_PARAM}=${marker}`, init);
63
+ };
@@ -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
+ }));
@@ -736,3 +736,205 @@ describe("draft preview (pull-based)", () => {
736
736
  expect(res.headers.get("X-Robots-Tag")).toBeNull();
737
737
  });
738
738
  });
739
+
740
+ describe('cdnCacheControl: "serverfn-segment"', () => {
741
+ const BUILD = "abc123";
742
+ const ENV = { BUILD_HASH: BUILD };
743
+
744
+ function worker(overrides: Record<string, unknown> = {}) {
745
+ return createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
746
+ observability: false,
747
+ cdnCacheControl: "serverfn-segment",
748
+ buildSegment: (req: Request) => ({
749
+ device: req.headers.get("user-agent")?.includes("iPhone")
750
+ ? ("mobile" as const)
751
+ : ("desktop" as const),
752
+ ...(req.headers.get("cookie")?.includes("auth=1") ? { loggedIn: true } : {}),
753
+ }),
754
+ ...overrides,
755
+ });
756
+ }
757
+
758
+ const sfnUrl = (marker?: string) =>
759
+ `https://example.com/_serverFn/loadCmsPage${marker ? `?__cseg=${marker}` : ""}`;
760
+
761
+ async function cdnHeader(url: string, headers: Record<string, string> = {}) {
762
+ const res = await worker().fetch(new Request(url, { headers }), ENV, MOCK_CTX);
763
+ return res.headers.get("CDN-Cache-Control");
764
+ }
765
+
766
+ it("releases the CDN when the marker matches the recomputed segment", async () => {
767
+ expect(await cdnHeader(sfnUrl(`desktop.${BUILD}`))).toMatch(/^public, max-age=\d+$/);
768
+ });
769
+
770
+ it("keeps no-store without a marker (bot, curl, old client)", async () => {
771
+ expect(await cdnHeader(sfnUrl())).toBe("no-store");
772
+ });
773
+
774
+ it("keeps no-store when the marker is for another device", async () => {
775
+ // The forged/diverging case: a desktop request claiming a mobile entry
776
+ // would let the CDN serve mobile HTML to desktop.
777
+ expect(await cdnHeader(sfnUrl(`mobile.${BUILD}`))).toBe("no-store");
778
+ });
779
+
780
+ it("keeps no-store when the marker is from an older build", async () => {
781
+ // Deploying does not purge the CDN, so a stale build token must not match.
782
+ expect(await cdnHeader(sfnUrl("desktop.oldbuild"))).toBe("no-store");
783
+ });
784
+
785
+ it("keeps no-store when there is no build hash", async () => {
786
+ const res = await worker().fetch(new Request(sfnUrl(`desktop.${BUILD}`)), {}, MOCK_CTX);
787
+ expect(res.headers.get("CDN-Cache-Control")).toBe("no-store");
788
+ });
789
+
790
+ it("keeps no-store for a bot UA even with a valid marker", async () => {
791
+ // Bots render every section eagerly (~10x payload). Sharing one CDN entry
792
+ // would serve that to humans, or the deferred one to crawlers.
793
+ expect(
794
+ await cdnHeader(sfnUrl(`desktop.${BUILD}`), {
795
+ "user-agent": "Mozilla/5.0 (compatible; Googlebot/2.1)",
796
+ }),
797
+ ).toBe("no-store");
798
+ });
799
+
800
+ it("keeps no-store for an A/B cohort cookie even with a valid marker", async () => {
801
+ expect(
802
+ await cdnHeader(sfnUrl(`desktop.${BUILD}`), {
803
+ cookie: "deco_segment=eyJhY3RpdmUiOlsiYSJdfQ==",
804
+ }),
805
+ ).toBe("no-store");
806
+ });
807
+
808
+ it("keeps no-store for a logged-in request", async () => {
809
+ expect(await cdnHeader(sfnUrl(`desktop.${BUILD}`), { cookie: "auth=1" })).toBe("no-store");
810
+ });
811
+
812
+ it("keeps no-store on HTML documents — they carry no marker", async () => {
813
+ expect(await cdnHeader("https://example.com/some-category")).toBe("no-store");
814
+ });
815
+
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");
829
+ });
830
+
831
+ it("keeps no-store without buildSegment, since the logged-in bypass is inert", async () => {
832
+ const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
833
+ observability: false,
834
+ cdnCacheControl: "serverfn-segment",
835
+ });
836
+ const res = await w.fetch(new Request(sfnUrl(`desktop.${BUILD}`)), ENV, MOCK_CTX);
837
+ expect(res.headers.get("CDN-Cache-Control")).toBe("no-store");
838
+ });
839
+ });
840
+
841
+ describe("cdnCacheControl default", () => {
842
+ const BUILD_D = "abc123";
843
+
844
+ // The default flipped from "no-store" to "serverfn-segment". That is only
845
+ // safe because it is inert until a verified marker arrives — these two tests
846
+ // are what make that claim checkable rather than asserted in a comment.
847
+ it("is inert for a client that never sends a marker", async () => {
848
+ const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
849
+ observability: false,
850
+ buildSegment: () => ({ device: "desktop" as const }),
851
+ });
852
+ const html = await w.fetch(new Request("https://example.com/"), { BUILD_HASH: BUILD_D }, MOCK_CTX);
853
+ expect(html.headers.get("CDN-Cache-Control")).toBe("no-store");
854
+
855
+ const sfn = await w.fetch(
856
+ new Request("https://example.com/_serverFn/loadCmsPage"),
857
+ { BUILD_HASH: BUILD_D },
858
+ MOCK_CTX,
859
+ );
860
+ expect(sfn.headers.get("CDN-Cache-Control")).toBe("no-store");
861
+ });
862
+
863
+ it("engages once the client sends a valid marker, with no site config", async () => {
864
+ const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
865
+ observability: false,
866
+ buildSegment: () => ({ device: "desktop" as const }),
867
+ });
868
+ const res = await w.fetch(
869
+ new Request(`https://example.com/_serverFn/loadCmsPage?__cseg=desktop.${BUILD_D}`),
870
+ { BUILD_HASH: BUILD_D },
871
+ MOCK_CTX,
872
+ );
873
+ expect(res.headers.get("CDN-Cache-Control")).toMatch(/^public, max-age=\d+$/);
874
+ });
875
+
876
+ it('still honours an explicit opt-out with "no-store"', async () => {
877
+ const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
878
+ observability: false,
879
+ cdnCacheControl: "no-store",
880
+ buildSegment: () => ({ device: "desktop" as const }),
881
+ });
882
+ const res = await w.fetch(
883
+ new Request(`https://example.com/_serverFn/loadCmsPage?__cseg=desktop.${BUILD_D}`),
884
+ { BUILD_HASH: BUILD_D },
885
+ MOCK_CTX,
886
+ );
887
+ expect(res.headers.get("CDN-Cache-Control")).toBe("no-store");
888
+ });
889
+ });
890
+
891
+ describe("CDN-Cache-Control at the single response exit", () => {
892
+ it("defaults to no-store on early returns that never reach dressResponse", async () => {
893
+ // `?asJson` returns the fully resolved page — loaders run with the caller's
894
+ // cookies — and returns before dressResponse, so it expresses no opinion on
895
+ // CDN caching. Without a default here it would inherit whatever the CDN
896
+ // decides for a 200 with no cache directives.
897
+ const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, { observability: false });
898
+ const res = await w.fetch(
899
+ new Request("https://example.com/some-category?asJson"),
900
+ EMPTY_ENV,
901
+ MOCK_CTX,
902
+ );
903
+ expect(res.headers.get("CDN-Cache-Control")).toBe("no-store");
904
+ });
905
+
906
+ it("leaves a value dressResponse already decided", async () => {
907
+ // The cacheable path is the one branch that reasoned about whether the CDN
908
+ // key matches the worker key — the default must not stomp it.
909
+ const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
910
+ observability: false,
911
+ cdnCacheControl: "match-profile",
912
+ deviceSpecificKeys: false,
913
+ geoCacheKey: "off",
914
+ });
915
+ const res = await w.fetch(new Request("https://example.com/some-category"), EMPTY_ENV, MOCK_CTX);
916
+ expect(res.headers.get("CDN-Cache-Control")).toMatch(/^public, max-age=\d+$/);
917
+ });
918
+ });
919
+
920
+ describe('cdnCacheControl: "match-profile" guard', () => {
921
+ it("is ignored while the cache key is segmented (deviceSpecificKeys defaults to true)", async () => {
922
+ const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
923
+ observability: false,
924
+ cdnCacheControl: "match-profile",
925
+ });
926
+ const res = await w.fetch(new Request("https://example.com/some-category"), {}, MOCK_CTX);
927
+ expect(res.headers.get("CDN-Cache-Control")).toBe("no-store");
928
+ });
929
+
930
+ it("is honored only when the key really is the raw URL", async () => {
931
+ const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
932
+ observability: false,
933
+ cdnCacheControl: "match-profile",
934
+ deviceSpecificKeys: false,
935
+ geoCacheKey: "off",
936
+ });
937
+ const res = await w.fetch(new Request("https://example.com/some-category"), {}, MOCK_CTX);
938
+ expect(res.headers.get("CDN-Cache-Control")).toMatch(/^public, max-age=\d+$/);
939
+ });
940
+ });
@@ -53,6 +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
57
  import {
57
58
  getActiveSpan,
58
59
  logRequest,
@@ -307,7 +308,6 @@ export interface DecoWorkerEntryOptions {
307
308
  * @default "PURGE_TOKEN"
308
309
  */
309
310
  purgeTokenEnv?: string | false;
310
-
311
311
  /**
312
312
  * Paths that should always bypass the edge cache, even if the
313
313
  * profile detector would otherwise cache them.
@@ -498,18 +498,48 @@ export interface DecoWorkerEntryOptions {
498
498
  staticPaths?: string[];
499
499
 
500
500
  /**
501
- * CDN-Cache-Control header strategy.
501
+ * CDN-Cache-Control header strategy — i.e. what Cloudflare's own CDN layer is
502
+ * allowed to do, as distinct from the Cache API this Worker manages directly.
503
+ *
504
+ * The default is `"no-store"` because the Worker's cache key is a SYNTHETIC
505
+ * Request carrying `__seg`/`__cf_device`/`__cf_geo`/`__bot`/`__fetch`/`__abf`
506
+ * (see `buildCacheKey`), while the CDN keys on the raw URL and ignores `Vary`
507
+ * beyond `Accept-Encoding`. Letting the CDN cache by URL alone would serve
508
+ * desktop HTML to mobile, one region's to another, or a crawler's eager
509
+ * render to humans.
510
+ *
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.
502
516
  *
503
- * - `"no-store"` (default): CDN never caches; every request invokes the Worker.
504
- * Correct when segment-based cache keys differ from the original URL.
505
- * - `"match-profile"`: Set CDN-Cache-Control to a short TTL matching the
506
- * profile's edge.fresh value. Only safe when you are NOT using segment-based
507
- * cache keys (i.e., no `buildSegment` and `deviceSpecificKeys: false`).
508
- * - A function: Return a CDN-Cache-Control value per profile, or `null` for no-store.
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.
523
+ * - `"match-profile"`: mirror the profile's `edge.fresh` as a CDN TTL. Sound
524
+ * ONLY when the cache key is the raw URL — no `buildSegment`,
525
+ * `deviceSpecificKeys: false`, `geoCacheKey: "off"`. Since
526
+ * `deviceSpecificKeys` defaults to **true**, this is almost never the case;
527
+ * when it isn't, the option is ignored with a warning rather than silently
528
+ * cross-serving segments.
529
+ * - A function: return a CDN-Cache-Control value per profile, or `null` for
530
+ * no-store. You own the correctness of the key/TTL pairing.
509
531
  *
510
- * @default "no-store"
532
+ * Caching HTML is deliberately not covered here. It is not a header change:
533
+ * whatever sits in front of the Worker has to reproduce the key above, and
534
+ * the initial navigation has no client hook to attach a marker to.
535
+ *
536
+ * @default "serverfn-segment"
511
537
  */
512
- cdnCacheControl?: "no-store" | "match-profile" | ((profile: CacheProfileName) => string | null);
538
+ cdnCacheControl?:
539
+ | "no-store"
540
+ | "serverfn-segment"
541
+ | "match-profile"
542
+ | ((profile: CacheProfileName) => string | null);
513
543
  /**
514
544
  * Auto-instrumentation via `instrumentWorker` is enabled by default. The
515
545
  * framework wraps the returned handler so that, when OTel env vars
@@ -777,11 +807,17 @@ function parseCookieNames(response: Response): string[] {
777
807
  /**
778
808
  * Check if ALL cookies in a response are in the safe list.
779
809
  * Returns true if the response has no cookies or only safe cookies.
810
+ *
811
+ * Fail-closed: a response that HAS a `set-cookie` we couldn't parse into names
812
+ * is treated as unsafe. The parser's fallback path (comma-splitting the
813
+ * combined header) is documented as unreliable, and the cost of the two
814
+ * outcomes is not symmetric — guessing "safe" here caches a personalized
815
+ * response into the shared edge entry.
780
816
  */
781
817
  function hasOnlySafeCookies(response: Response, safeCookieSet: Set<string>): boolean {
782
818
  if (!response.headers.has("set-cookie")) return true;
783
819
  const names = parseCookieNames(response);
784
- if (names.length === 0) return true;
820
+ if (names.length === 0) return false;
785
821
  return names.every((name) => safeCookieSet.has(name));
786
822
  }
787
823
 
@@ -964,7 +1000,7 @@ export function createDecoWorkerEntry(
964
1000
  geoCacheKey: geoCacheKeyOpt = "auto",
965
1001
  safeCookies: safeCookiesOpt = DEFAULT_SAFE_COOKIES,
966
1002
  staticPaths: staticPathsOpt = DEFAULT_STATIC_PATHS,
967
- cdnCacheControl: cdnCacheControlOpt = "no-store",
1003
+ cdnCacheControl: cdnCacheControlOpt = "serverfn-segment",
968
1004
  observability: observabilityOpt,
969
1005
  outboundUserAgent: outboundUserAgentOpt,
970
1006
  speculationRules: speculationRulesOpt,
@@ -1028,6 +1064,10 @@ export function createDecoWorkerEntry(
1028
1064
 
1029
1065
  const safeCookieSet = new Set(safeCookiesOpt);
1030
1066
 
1067
+ // One warning per worker instance, not per request — same pattern as
1068
+ // `warnedLongMaxAge` in @decocms/blocks/sdk/cachedLoader.
1069
+ let warnedMatchProfile = false;
1070
+
1031
1071
  // Build the final security headers map (merged defaults + custom + CSP)
1032
1072
  const secHeaders: Record<string, string> | null = (() => {
1033
1073
  if (securityHeadersOpt === false) return null;
@@ -1058,7 +1098,24 @@ export function createDecoWorkerEntry(
1058
1098
  return out;
1059
1099
  }
1060
1100
 
1061
- const allBypassPaths = [...(bypassPaths ?? DEFAULT_BYPASS_PATHS), ...extraBypassPaths];
1101
+ // DEFAULT_BYPASS_PATHS is always included, even when a site passes its own
1102
+ // `bypassPaths`. It used to be replaced, so a site adding one path silently
1103
+ // lost `/deco/`, `/live/` and `/.decofile` — framework routes that must never
1104
+ // be cached. Cache configuration from a site can tighten, never loosen.
1105
+ const allBypassPaths = [
1106
+ ...new Set([...DEFAULT_BYPASS_PATHS, ...(bypassPaths ?? []), ...extraBypassPaths]),
1107
+ ];
1108
+
1109
+ // The logged-in bypass below reads `segment.loggedIn`, which only ever exists
1110
+ // when the site supplies `buildSegment`. Without it, authenticated and
1111
+ // anonymous visitors share one edge entry.
1112
+ if (!rawBuildSegment) {
1113
+ console.warn(
1114
+ "[deco] createDecoWorkerEntry: no `buildSegment` configured — logged-in " +
1115
+ "visitors share the anonymous edge cache entry. Required before enabling " +
1116
+ "CDN caching.",
1117
+ );
1118
+ }
1062
1119
 
1063
1120
  // -- Helpers ----------------------------------------------------------------
1064
1121
 
@@ -1172,6 +1229,67 @@ export function createDecoWorkerEntry(
1172
1229
  return undefined;
1173
1230
  }
1174
1231
 
1232
+ function isServerFnPathname(pathname: string): boolean {
1233
+ return pathname.startsWith("/_serverFn/") || pathname.startsWith("/_server/");
1234
+ }
1235
+
1236
+ /**
1237
+ * Whether this `/_serverFn` request may be cached by Cloudflare's CDN.
1238
+ *
1239
+ * True only when the URL carries a `__cseg` marker (put there by
1240
+ * `decoServerFnFetch` on the client) AND recomputing the segment from this
1241
+ * request produces the same token. When it matches, the CDN's key — the raw
1242
+ * URL — is equivalent to the Worker's synthetic key, so serving from the CDN
1243
+ * cannot cross segments.
1244
+ *
1245
+ * Fail-closed on every axis: no marker (bot, curl, old client), diverging
1246
+ * marker, forged marker, stale build, logged-in / region / sales channel, a
1247
+ * custom segment dimension, a bot UA, or an A/B cohort cookie all keep
1248
+ * today's `no-store`. The worst case is not caching — never a wrong response.
1249
+ *
1250
+ * `isBot` and the A/B cookie are checked HERE rather than inside
1251
+ * `segmentToken` because they are request-only: the client cannot observe
1252
+ * them, and they are exactly the two dimensions the original site-level
1253
+ * version missed. They must use the same `isBot` / `segmentCacheToken` that
1254
+ * `buildCacheKey` uses — keying and releasing off different predicates is how
1255
+ * the two silently diverge.
1256
+ */
1257
+ function cdnCacheableServerFn(request: Request, url: URL, env: Record<string, unknown>): boolean {
1258
+ if (!isServerFnPathname(url.pathname)) return false;
1259
+
1260
+ const marker = url.searchParams.get(CSEG_PARAM);
1261
+ if (!marker) return false;
1262
+
1263
+ // Without buildSegment the logged-in bypass is inert (see the boot warning),
1264
+ // so there is nothing reliable to verify the marker against.
1265
+ if (!buildSegment) return false;
1266
+
1267
+ // `__bot=1` in buildCacheKey: bots render every section eagerly (~10x
1268
+ // payload). Letting the CDN share one entry would serve that to humans, or
1269
+ // the deferred one to crawlers.
1270
+ if (isBot(request.headers.get("user-agent") ?? undefined)) return false;
1271
+
1272
+ // `__abf` in buildCacheKey: an A/B visitor must not get another cohort's
1273
+ // cached variant.
1274
+ if (segmentCacheToken(parseSegmentCookie(readRequestCookie(request, SEGMENT_COOKIE)))) {
1275
+ return false;
1276
+ }
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));
1290
+ return expected !== null && marker === expected;
1291
+ }
1292
+
1175
1293
  function buildCacheKey(
1176
1294
  request: Request,
1177
1295
  env: Record<string, unknown>,
@@ -1678,6 +1796,27 @@ export function createDecoWorkerEntry(
1678
1796
  // invoke handlers, etc.) may independently append the same cookie.
1679
1797
  deduplicateSetCookies(response);
1680
1798
 
1799
+ // `CDN-Cache-Control` is decided here, at the single response exit, so no
1800
+ // branch can forget it. Two cases:
1801
+ //
1802
+ // - `X-Cache: BYPASS` — the worker deliberately declined to cache, so
1803
+ // the CDN must not either. A dozen call sites set this; some deleted
1804
+ // the header, some didn't, and several still emitted the profile's
1805
+ // public `Cache-Control` (`public, s-maxage=900`) on the way out.
1806
+ // - header absent — a branch that returned before `dressResponse` and
1807
+ // expressed no opinion. `?asJson`, `?renderJson`, proxied responses and
1808
+ // the redirect paths all land here. Defaulting these to `no-store` is
1809
+ // what makes the invariant hold: an early return can only ever be
1810
+ // MORE restrictive than the cache layer, never accidentally public.
1811
+ //
1812
+ // A value already set by `dressResponse` (the cacheable path) is left
1813
+ // alone — that is the one branch that has actually reasoned about whether
1814
+ // the CDN key matches the worker key.
1815
+ const bypassed = response.headers.get("X-Cache") === "BYPASS";
1816
+ if (bypassed || !response.headers.has("CDN-Cache-Control")) {
1817
+ response.headers.set("CDN-Cache-Control", "no-store");
1818
+ }
1819
+
1681
1820
  let finalResponse = applySecurityHeaders(response);
1682
1821
 
1683
1822
  // Echo request.id + trace.id back to the client / tail worker.
@@ -2383,17 +2522,45 @@ export function createDecoWorkerEntry(
2383
2522
 
2384
2523
  // CDN-Cache-Control: controls Cloudflare's automatic CDN layer
2385
2524
  // (separate from Cache API which the worker manages directly).
2386
- if (cdnCacheControlOpt === "no-store") {
2387
- out.headers.set("CDN-Cache-Control", "no-store");
2525
+ const cdnPublic = `public, max-age=${edgeConfig.fresh}`;
2526
+ const cdnCacheable = edgeConfig.isPublic && edgeConfig.fresh > 0;
2527
+
2528
+ if (cdnCacheControlOpt === "serverfn-segment") {
2529
+ // Only `/_serverFn` requests whose URL carries a verified segment
2530
+ // marker. Everything else — including every HTML document, which has no
2531
+ // client hook to attach a marker on the initial navigation — keeps
2532
+ // `no-store`.
2533
+ out.headers.set(
2534
+ "CDN-Cache-Control",
2535
+ cdnCacheable && cdnCacheableServerFn(request, url, env) ? cdnPublic : "no-store",
2536
+ );
2388
2537
  } else if (cdnCacheControlOpt === "match-profile") {
2389
- if (edgeConfig.isPublic && edgeConfig.fresh > 0) {
2390
- out.headers.set("CDN-Cache-Control", `public, max-age=${edgeConfig.fresh}`);
2391
- } else {
2538
+ // `match-profile` is only sound when the Worker's cache key is the raw
2539
+ // URL. It almost never is: `deviceSpecificKeys` defaults to true, so
2540
+ // every site keys on `__cf_device` even without a `buildSegment`, and a
2541
+ // location matcher adds `__cf_geo`. Honoring the option under those
2542
+ // conditions would serve desktop HTML to mobile, or one region's to
2543
+ // another — silently. Refuse, and say why once.
2544
+ const keyed =
2545
+ buildSegment !== undefined || deviceSpecificKeys || effectiveGeoKey() !== "off";
2546
+ if (keyed) {
2547
+ if (!warnedMatchProfile) {
2548
+ warnedMatchProfile = true;
2549
+ console.warn(
2550
+ '[deco] cdnCacheControl: "match-profile" ignored — the edge cache key is ' +
2551
+ "segmented (buildSegment / deviceSpecificKeys / geoCacheKey), which the CDN " +
2552
+ "cannot reproduce from the URL alone. Keeping CDN-Cache-Control: no-store.",
2553
+ );
2554
+ }
2392
2555
  out.headers.set("CDN-Cache-Control", "no-store");
2556
+ } else {
2557
+ out.headers.set("CDN-Cache-Control", cdnCacheable ? cdnPublic : "no-store");
2393
2558
  }
2394
2559
  } else if (typeof cdnCacheControlOpt === "function") {
2395
2560
  const val = cdnCacheControlOpt(profile);
2396
2561
  out.headers.set("CDN-Cache-Control", val ?? "no-store");
2562
+ } else {
2563
+ out.headers.set("CDN-Cache-Control", "no-store");
2397
2564
  }
2398
2565
 
2399
2566
  out.headers.set("X-Cache", xCache);
@@ -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