@decocms/tanstack 7.55.1 → 7.56.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.1",
3
+ "version": "7.56.0",
4
4
  "type": "module",
5
5
  "description": "Deco framework binding for TanStack Start + Cloudflare Workers",
6
6
  "repository": {
@@ -15,7 +15,9 @@
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/cdnSegment": "./src/sdk/cdnSegment.ts"
19
21
  },
20
22
  "scripts": {
21
23
  "build": "tsc",
@@ -24,9 +26,9 @@
24
26
  "lint:unused": "knip"
25
27
  },
26
28
  "dependencies": {
27
- "@decocms/blocks": "7.55.1",
28
- "@decocms/blocks-admin": "7.55.1",
29
- "@decocms/blocks-cli": "7.55.1",
29
+ "@decocms/blocks": "7.56.0",
30
+ "@decocms/blocks-admin": "7.56.0",
31
+ "@decocms/blocks-cli": "7.56.0",
30
32
  "@deco-cx/warp-node": "^0.3.16",
31
33
  "fast-json-patch": "^3.1.0",
32
34
  "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
+ };
@@ -736,3 +736,155 @@ 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("CDN-Cache-Control at the single response exit", () => {
842
+ it("defaults to no-store on early returns that never reach dressResponse", async () => {
843
+ // `?asJson` returns the fully resolved page — loaders run with the caller's
844
+ // cookies — and returns before dressResponse, so it expresses no opinion on
845
+ // CDN caching. Without a default here it would inherit whatever the CDN
846
+ // decides for a 200 with no cache directives.
847
+ const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, { observability: false });
848
+ const res = await w.fetch(
849
+ new Request("https://example.com/some-category?asJson"),
850
+ EMPTY_ENV,
851
+ MOCK_CTX,
852
+ );
853
+ expect(res.headers.get("CDN-Cache-Control")).toBe("no-store");
854
+ });
855
+
856
+ it("leaves a value dressResponse already decided", async () => {
857
+ // The cacheable path is the one branch that reasoned about whether the CDN
858
+ // key matches the worker key — the default must not stomp it.
859
+ const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
860
+ observability: false,
861
+ cdnCacheControl: "match-profile",
862
+ deviceSpecificKeys: false,
863
+ geoCacheKey: "off",
864
+ });
865
+ const res = await w.fetch(new Request("https://example.com/some-category"), EMPTY_ENV, MOCK_CTX);
866
+ expect(res.headers.get("CDN-Cache-Control")).toMatch(/^public, max-age=\d+$/);
867
+ });
868
+ });
869
+
870
+ describe('cdnCacheControl: "match-profile" guard', () => {
871
+ it("is ignored while the cache key is segmented (deviceSpecificKeys defaults to true)", async () => {
872
+ const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
873
+ observability: false,
874
+ cdnCacheControl: "match-profile",
875
+ });
876
+ const res = await w.fetch(new Request("https://example.com/some-category"), {}, MOCK_CTX);
877
+ expect(res.headers.get("CDN-Cache-Control")).toBe("no-store");
878
+ });
879
+
880
+ it("is honored only when the key really is the raw URL", async () => {
881
+ const w = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
882
+ observability: false,
883
+ cdnCacheControl: "match-profile",
884
+ deviceSpecificKeys: false,
885
+ geoCacheKey: "off",
886
+ });
887
+ const res = await w.fetch(new Request("https://example.com/some-category"), {}, MOCK_CTX);
888
+ expect(res.headers.get("CDN-Cache-Control")).toMatch(/^public, max-age=\d+$/);
889
+ });
890
+ });
@@ -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,43 @@ 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
+ * - `"no-store"` (default): the CDN never caches; every request invokes the
512
+ * Worker. Always correct, never fast.
513
+ * - `"serverfn-segment"`: opt in to CDN caching for `/_serverFn` requests
514
+ * whose URL carries a verified `__cseg` marker (see `./cdnSegment` and
515
+ * `decoServerFnFetch`). The marker makes the CDN's key equivalent to the
516
+ * Worker's. HTML documents keep `no-store` — the initial navigation is a
517
+ * browser request with no client hook to attach a marker.
518
+ * - `"match-profile"`: mirror the profile's `edge.fresh` as a CDN TTL. Sound
519
+ * ONLY when the cache key is the raw URL — no `buildSegment`,
520
+ * `deviceSpecificKeys: false`, `geoCacheKey: "off"`. Since
521
+ * `deviceSpecificKeys` defaults to **true**, this is almost never the case;
522
+ * when it isn't, the option is ignored with a warning rather than silently
523
+ * cross-serving segments.
524
+ * - A function: return a CDN-Cache-Control value per profile, or `null` for
525
+ * no-store. You own the correctness of the key/TTL pairing.
502
526
  *
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.
527
+ * Caching HTML is deliberately not covered here. It is not a header change:
528
+ * whatever sits in front of the Worker has to reproduce the key above, and
529
+ * the initial navigation has no client hook to attach a marker to.
509
530
  *
510
531
  * @default "no-store"
511
532
  */
512
- cdnCacheControl?: "no-store" | "match-profile" | ((profile: CacheProfileName) => string | null);
533
+ cdnCacheControl?:
534
+ | "no-store"
535
+ | "serverfn-segment"
536
+ | "match-profile"
537
+ | ((profile: CacheProfileName) => string | null);
513
538
  /**
514
539
  * Auto-instrumentation via `instrumentWorker` is enabled by default. The
515
540
  * framework wraps the returned handler so that, when OTel env vars
@@ -777,11 +802,17 @@ function parseCookieNames(response: Response): string[] {
777
802
  /**
778
803
  * Check if ALL cookies in a response are in the safe list.
779
804
  * Returns true if the response has no cookies or only safe cookies.
805
+ *
806
+ * Fail-closed: a response that HAS a `set-cookie` we couldn't parse into names
807
+ * is treated as unsafe. The parser's fallback path (comma-splitting the
808
+ * combined header) is documented as unreliable, and the cost of the two
809
+ * outcomes is not symmetric — guessing "safe" here caches a personalized
810
+ * response into the shared edge entry.
780
811
  */
781
812
  function hasOnlySafeCookies(response: Response, safeCookieSet: Set<string>): boolean {
782
813
  if (!response.headers.has("set-cookie")) return true;
783
814
  const names = parseCookieNames(response);
784
- if (names.length === 0) return true;
815
+ if (names.length === 0) return false;
785
816
  return names.every((name) => safeCookieSet.has(name));
786
817
  }
787
818
 
@@ -1028,6 +1059,10 @@ export function createDecoWorkerEntry(
1028
1059
 
1029
1060
  const safeCookieSet = new Set(safeCookiesOpt);
1030
1061
 
1062
+ // One warning per worker instance, not per request — same pattern as
1063
+ // `warnedLongMaxAge` in @decocms/blocks/sdk/cachedLoader.
1064
+ let warnedMatchProfile = false;
1065
+
1031
1066
  // Build the final security headers map (merged defaults + custom + CSP)
1032
1067
  const secHeaders: Record<string, string> | null = (() => {
1033
1068
  if (securityHeadersOpt === false) return null;
@@ -1058,7 +1093,24 @@ export function createDecoWorkerEntry(
1058
1093
  return out;
1059
1094
  }
1060
1095
 
1061
- const allBypassPaths = [...(bypassPaths ?? DEFAULT_BYPASS_PATHS), ...extraBypassPaths];
1096
+ // DEFAULT_BYPASS_PATHS is always included, even when a site passes its own
1097
+ // `bypassPaths`. It used to be replaced, so a site adding one path silently
1098
+ // lost `/deco/`, `/live/` and `/.decofile` — framework routes that must never
1099
+ // be cached. Cache configuration from a site can tighten, never loosen.
1100
+ const allBypassPaths = [
1101
+ ...new Set([...DEFAULT_BYPASS_PATHS, ...(bypassPaths ?? []), ...extraBypassPaths]),
1102
+ ];
1103
+
1104
+ // The logged-in bypass below reads `segment.loggedIn`, which only ever exists
1105
+ // when the site supplies `buildSegment`. Without it, authenticated and
1106
+ // anonymous visitors share one edge entry.
1107
+ if (!rawBuildSegment) {
1108
+ console.warn(
1109
+ "[deco] createDecoWorkerEntry: no `buildSegment` configured — logged-in " +
1110
+ "visitors share the anonymous edge cache entry. Required before enabling " +
1111
+ "CDN caching.",
1112
+ );
1113
+ }
1062
1114
 
1063
1115
  // -- Helpers ----------------------------------------------------------------
1064
1116
 
@@ -1172,6 +1224,67 @@ export function createDecoWorkerEntry(
1172
1224
  return undefined;
1173
1225
  }
1174
1226
 
1227
+ function isServerFnPathname(pathname: string): boolean {
1228
+ return pathname.startsWith("/_serverFn/") || pathname.startsWith("/_server/");
1229
+ }
1230
+
1231
+ /**
1232
+ * Whether this `/_serverFn` request may be cached by Cloudflare's CDN.
1233
+ *
1234
+ * True only when the URL carries a `__cseg` marker (put there by
1235
+ * `decoServerFnFetch` on the client) AND recomputing the segment from this
1236
+ * request produces the same token. When it matches, the CDN's key — the raw
1237
+ * URL — is equivalent to the Worker's synthetic key, so serving from the CDN
1238
+ * cannot cross segments.
1239
+ *
1240
+ * Fail-closed on every axis: no marker (bot, curl, old client), diverging
1241
+ * marker, forged marker, stale build, logged-in / region / sales channel, a
1242
+ * custom segment dimension, a bot UA, or an A/B cohort cookie all keep
1243
+ * today's `no-store`. The worst case is not caching — never a wrong response.
1244
+ *
1245
+ * `isBot` and the A/B cookie are checked HERE rather than inside
1246
+ * `segmentToken` because they are request-only: the client cannot observe
1247
+ * them, and they are exactly the two dimensions the original site-level
1248
+ * version missed. They must use the same `isBot` / `segmentCacheToken` that
1249
+ * `buildCacheKey` uses — keying and releasing off different predicates is how
1250
+ * the two silently diverge.
1251
+ */
1252
+ function cdnCacheableServerFn(request: Request, url: URL, env: Record<string, unknown>): boolean {
1253
+ if (!isServerFnPathname(url.pathname)) return false;
1254
+
1255
+ const marker = url.searchParams.get(CSEG_PARAM);
1256
+ if (!marker) return false;
1257
+
1258
+ // Without buildSegment the logged-in bypass is inert (see the boot warning),
1259
+ // so there is nothing reliable to verify the marker against.
1260
+ if (!buildSegment) return false;
1261
+
1262
+ // `__bot=1` in buildCacheKey: bots render every section eagerly (~10x
1263
+ // payload). Letting the CDN share one entry would serve that to humans, or
1264
+ // the deferred one to crawlers.
1265
+ if (isBot(request.headers.get("user-agent") ?? undefined)) return false;
1266
+
1267
+ // `__abf` in buildCacheKey: an A/B visitor must not get another cohort's
1268
+ // cached variant.
1269
+ if (segmentCacheToken(parseSegmentCookie(readRequestCookie(request, SEGMENT_COOKIE)))) {
1270
+ return false;
1271
+ }
1272
+
1273
+ // `__cf_geo` in buildCacheKey, which the marker cannot express and the CDN
1274
+ // cannot reproduce. Mostly moot — with geo on, the `buildSegment` wrapper
1275
+ // back-fills `regionId`, and any `regionId` already makes `segmentToken`
1276
+ // return null. But the back-fill reads only `cf.regionCode` while
1277
+ // `buildGeoCacheParam` keys on country/region/city, so a request with a
1278
+ // country but no region code (Tor exits, some carriers, countries without
1279
+ // first-level subdivisions) slips through with a releasable token while the
1280
+ // Worker key still varies by geo. Refuse outright, the same way the
1281
+ // `match-profile` branch below does.
1282
+ if (effectiveGeoKey() !== "off") return false;
1283
+
1284
+ const expected = segmentToken(buildSegment(request), getBuildHash(env));
1285
+ return expected !== null && marker === expected;
1286
+ }
1287
+
1175
1288
  function buildCacheKey(
1176
1289
  request: Request,
1177
1290
  env: Record<string, unknown>,
@@ -1678,6 +1791,27 @@ export function createDecoWorkerEntry(
1678
1791
  // invoke handlers, etc.) may independently append the same cookie.
1679
1792
  deduplicateSetCookies(response);
1680
1793
 
1794
+ // `CDN-Cache-Control` is decided here, at the single response exit, so no
1795
+ // branch can forget it. Two cases:
1796
+ //
1797
+ // - `X-Cache: BYPASS` — the worker deliberately declined to cache, so
1798
+ // the CDN must not either. A dozen call sites set this; some deleted
1799
+ // the header, some didn't, and several still emitted the profile's
1800
+ // public `Cache-Control` (`public, s-maxage=900`) on the way out.
1801
+ // - header absent — a branch that returned before `dressResponse` and
1802
+ // expressed no opinion. `?asJson`, `?renderJson`, proxied responses and
1803
+ // the redirect paths all land here. Defaulting these to `no-store` is
1804
+ // what makes the invariant hold: an early return can only ever be
1805
+ // MORE restrictive than the cache layer, never accidentally public.
1806
+ //
1807
+ // A value already set by `dressResponse` (the cacheable path) is left
1808
+ // alone — that is the one branch that has actually reasoned about whether
1809
+ // the CDN key matches the worker key.
1810
+ const bypassed = response.headers.get("X-Cache") === "BYPASS";
1811
+ if (bypassed || !response.headers.has("CDN-Cache-Control")) {
1812
+ response.headers.set("CDN-Cache-Control", "no-store");
1813
+ }
1814
+
1681
1815
  let finalResponse = applySecurityHeaders(response);
1682
1816
 
1683
1817
  // Echo request.id + trace.id back to the client / tail worker.
@@ -2383,17 +2517,45 @@ export function createDecoWorkerEntry(
2383
2517
 
2384
2518
  // CDN-Cache-Control: controls Cloudflare's automatic CDN layer
2385
2519
  // (separate from Cache API which the worker manages directly).
2386
- if (cdnCacheControlOpt === "no-store") {
2387
- out.headers.set("CDN-Cache-Control", "no-store");
2520
+ const cdnPublic = `public, max-age=${edgeConfig.fresh}`;
2521
+ const cdnCacheable = edgeConfig.isPublic && edgeConfig.fresh > 0;
2522
+
2523
+ if (cdnCacheControlOpt === "serverfn-segment") {
2524
+ // Only `/_serverFn` requests whose URL carries a verified segment
2525
+ // marker. Everything else — including every HTML document, which has no
2526
+ // client hook to attach a marker on the initial navigation — keeps
2527
+ // `no-store`.
2528
+ out.headers.set(
2529
+ "CDN-Cache-Control",
2530
+ cdnCacheable && cdnCacheableServerFn(request, url, env) ? cdnPublic : "no-store",
2531
+ );
2388
2532
  } 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 {
2533
+ // `match-profile` is only sound when the Worker's cache key is the raw
2534
+ // URL. It almost never is: `deviceSpecificKeys` defaults to true, so
2535
+ // every site keys on `__cf_device` even without a `buildSegment`, and a
2536
+ // location matcher adds `__cf_geo`. Honoring the option under those
2537
+ // conditions would serve desktop HTML to mobile, or one region's to
2538
+ // another — silently. Refuse, and say why once.
2539
+ const keyed =
2540
+ buildSegment !== undefined || deviceSpecificKeys || effectiveGeoKey() !== "off";
2541
+ if (keyed) {
2542
+ if (!warnedMatchProfile) {
2543
+ warnedMatchProfile = true;
2544
+ console.warn(
2545
+ '[deco] cdnCacheControl: "match-profile" ignored — the edge cache key is ' +
2546
+ "segmented (buildSegment / deviceSpecificKeys / geoCacheKey), which the CDN " +
2547
+ "cannot reproduce from the URL alone. Keeping CDN-Cache-Control: no-store.",
2548
+ );
2549
+ }
2392
2550
  out.headers.set("CDN-Cache-Control", "no-store");
2551
+ } else {
2552
+ out.headers.set("CDN-Cache-Control", cdnCacheable ? cdnPublic : "no-store");
2393
2553
  }
2394
2554
  } else if (typeof cdnCacheControlOpt === "function") {
2395
2555
  const val = cdnCacheControlOpt(profile);
2396
2556
  out.headers.set("CDN-Cache-Control", val ?? "no-store");
2557
+ } else {
2558
+ out.headers.set("CDN-Cache-Control", "no-store");
2397
2559
  }
2398
2560
 
2399
2561
  out.headers.set("X-Cache", xCache);