@decocms/tanstack 7.64.2 → 7.65.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.
@@ -25,14 +25,6 @@
25
25
  * ```
26
26
  */
27
27
 
28
- import {
29
- bindCacheStorage,
30
- type CacheStorage,
31
- createWebCacheStorage,
32
- getCacheStorageContext,
33
- } from "@decocms/blocks/sdk/cacheStorage";
34
- import { createResponseCache } from "@decocms/blocks/sdk/responseCache";
35
-
36
28
  import {
37
29
  getRevision,
38
30
  getSectionOptions,
@@ -58,9 +50,16 @@ import {
58
50
  getCacheProfile,
59
51
  serverFnPagePath,
60
52
  } from "@decocms/blocks/sdk/cacheHeaders";
53
+ import {
54
+ bindCacheStorage,
55
+ type CacheStorage,
56
+ createWebCacheStorage,
57
+ getCacheStorageContext,
58
+ } from "@decocms/blocks/sdk/cacheStorage";
61
59
  import { djb2Hex } from "@decocms/blocks/sdk/djb2";
62
60
  import { isDevMode } from "@decocms/blocks/sdk/env";
63
61
  import { parseSegmentCookie, SEGMENT_COOKIE, segmentCacheToken } from "@decocms/blocks/sdk/flags";
62
+ import { generateNonce, NONCE_BAG_KEY } from "@decocms/blocks/sdk/nonce";
64
63
  import {
65
64
  getActiveSpan,
66
65
  logRequest,
@@ -79,6 +78,7 @@ import { setRuntimeEnv } from "@decocms/blocks/sdk/otelAdapters";
79
78
  import { parseTraceparent } from "@decocms/blocks/sdk/otelHttpTracer";
80
79
  import { loadRedirects, matchRedirect, type RedirectMap } from "@decocms/blocks/sdk/redirects";
81
80
  import { RequestContext } from "@decocms/blocks/sdk/requestContext";
81
+ import { createResponseCache } from "@decocms/blocks/sdk/responseCache";
82
82
  import { cleanPathForCacheKey } from "@decocms/blocks/sdk/urlUtils";
83
83
  import { type Device, isMobileUA } from "@decocms/blocks/sdk/useDevice";
84
84
  import { getRenderShellConfig } from "@decocms/blocks-admin/admin/setup";
@@ -434,6 +434,24 @@ export interface DecoWorkerEntryOptions {
434
434
  */
435
435
  csp?: string[] | false;
436
436
 
437
+ /**
438
+ * How the `csp` directives are delivered.
439
+ *
440
+ * - `"report-only"` (default): emitted as `Content-Security-Policy-Report-Only`.
441
+ * Browsers report violations but never block — backward-compatible, zero risk.
442
+ * - `"enforce"`: emitted as an enforced `Content-Security-Policy`, but ONLY on
443
+ * non-cacheable (`CDN-Cache-Control: no-store`) HTML responses. A fresh nonce
444
+ * is generated per request, threaded into every SSR inline `<script>` (via
445
+ * `router.options.ssr.nonce` + the deco layout components) and into the
446
+ * header's `script-src` (which also drops `'unsafe-inline'`). Cacheable
447
+ * responses stay report-only, because a per-request nonce would desync from a
448
+ * cached body and block every script. `'unsafe-eval'`, if present in the
449
+ * site's `script-src`, is left untouched — remove it explicitly in your `csp`.
450
+ *
451
+ * @default "report-only"
452
+ */
453
+ cspMode?: "report-only" | "enforce";
454
+
437
455
  /**
438
456
  * Automatically inject Cloudflare geo data (country, region, city)
439
457
  * as internal cookies on every request so location matchers can read
@@ -771,6 +789,53 @@ export const DECO_ADMIN_FRAME_ANCESTORS: string[] = [
771
789
  */
772
790
  export const DEFAULT_FRAME_ANCESTORS_CSP = `frame-ancestors ${DECO_ADMIN_FRAME_ANCESTORS.join(" ")}`;
773
791
 
792
+ /**
793
+ * Rewrite a `script-src` directive for nonce enforcement: drop `'unsafe-inline'`
794
+ * (a nonce makes it dead weight — and CSP ignores it once a nonce is present)
795
+ * and add `'nonce-<nonce>'` plus `'inline-speculation-rules'` (so the layout's
796
+ * `<script type="speculationrules">` still runs). `'unsafe-eval'` is left as-is.
797
+ */
798
+ function hardenScriptSrc(directive: string, nonce: string): string {
799
+ const tokens = directive.trim().split(/\s+/).slice(1);
800
+ const kept = tokens.filter((t) => t.toLowerCase() !== "'unsafe-inline'");
801
+ for (const extra of [`'nonce-${nonce}'`, "'inline-speculation-rules'"]) {
802
+ if (!kept.includes(extra)) kept.push(extra);
803
+ }
804
+ return `script-src ${kept.join(" ")}`;
805
+ }
806
+
807
+ /**
808
+ * Build the enforced `Content-Security-Policy` value from the site's `csp`
809
+ * directives + the enforced `frame-ancestors`. The `script-src` directive is
810
+ * hardened with the request nonce (added if the site declared none). Any
811
+ * `frame-ancestors` the site put in `csp` is dropped in favour of the canonical
812
+ * enforced one.
813
+ */
814
+ export function buildEnforcedCsp(
815
+ directives: string[],
816
+ frameAncestorsCsp: string,
817
+ nonce: string,
818
+ ): string {
819
+ const out: string[] = [];
820
+ let sawScriptSrc = false;
821
+ for (const directive of directives) {
822
+ const name = directive.trim().split(/\s+/)[0]?.toLowerCase();
823
+ if (name === "script-src") {
824
+ sawScriptSrc = true;
825
+ out.push(hardenScriptSrc(directive, nonce));
826
+ } else if (name === "frame-ancestors") {
827
+ // replaced by the canonical enforced frame-ancestors appended below
828
+ } else {
829
+ out.push(directive.trim());
830
+ }
831
+ }
832
+ if (!sawScriptSrc) {
833
+ out.push(`script-src 'self' 'nonce-${nonce}' 'inline-speculation-rules'`);
834
+ }
835
+ out.push(frameAncestorsCsp.trim());
836
+ return out.join("; ");
837
+ }
838
+
774
839
  const DEFAULT_BYPASS_PATHS = ["/_build", "/deco/", "/live/", "/.decofile"];
775
840
 
776
841
  /**
@@ -1009,6 +1074,7 @@ export function createDecoWorkerEntry(
1009
1074
  cacheVersionEnv = "BUILD_HASH",
1010
1075
  securityHeaders: securityHeadersOpt,
1011
1076
  csp: cspOpt,
1077
+ cspMode = "report-only",
1012
1078
  autoInjectGeoCookies: geoOpt = true,
1013
1079
  geoCacheKey: geoCacheKeyOpt = "auto",
1014
1080
  safeCookies: safeCookiesOpt = DEFAULT_SAFE_COOKIES,
@@ -1100,7 +1166,12 @@ export function createDecoWorkerEntry(
1100
1166
  return base;
1101
1167
  })();
1102
1168
 
1103
- function applySecurityHeaders(resp: Response): Response {
1169
+ // The enforced frame-ancestors value that ends up on `Content-Security-Policy`
1170
+ // (site override wins, else the deco default). Reused when we build the
1171
+ // enforced nonce CSP so framing protection is preserved.
1172
+ const frameAncestorsCsp = secHeaders?.["Content-Security-Policy"] ?? DEFAULT_FRAME_ANCESTORS_CSP;
1173
+
1174
+ function applySecurityHeaders(resp: Response, nonce?: string): Response {
1104
1175
  if (!secHeaders) return resp;
1105
1176
  const ct = resp.headers.get("content-type") ?? "";
1106
1177
  if (!ct.includes("text/html")) return resp;
@@ -1108,6 +1179,24 @@ export function createDecoWorkerEntry(
1108
1179
  for (const [k, v] of Object.entries(secHeaders)) {
1109
1180
  if (!out.headers.has(k)) out.headers.set(k, v);
1110
1181
  }
1182
+ // Enforced nonce CSP: enforce mode + a real nonce + a non-cacheable
1183
+ // response only. On a cacheable response a per-request nonce baked into the
1184
+ // (cached) body would desync from the header on the next HIT and block every
1185
+ // script, so those stay report-only. `CDN-Cache-Control` is decided at the
1186
+ // single response exit just before this call, so `no-store` is reliable here.
1187
+ if (
1188
+ cspMode === "enforce" &&
1189
+ nonce &&
1190
+ cspOpt &&
1191
+ cspOpt.length > 0 &&
1192
+ (out.headers.get("CDN-Cache-Control") ?? "").includes("no-store")
1193
+ ) {
1194
+ out.headers.delete("Content-Security-Policy-Report-Only");
1195
+ out.headers.set(
1196
+ "Content-Security-Policy",
1197
+ buildEnforcedCsp(cspOpt, frameAncestorsCsp, nonce),
1198
+ );
1199
+ }
1111
1200
  return out;
1112
1201
  }
1113
1202
 
@@ -1761,6 +1850,12 @@ export function createDecoWorkerEntry(
1761
1850
  // the final response. Inert on non-preview builds/hosts.
1762
1851
  let draftDecision: DraftDecision = { previewing: false, setCookie: null, clearCookie: false };
1763
1852
 
1853
+ // Per-request CSP nonce (enforce mode only). Generated inside the
1854
+ // RequestContext.run below — before the render — so SSR components and the
1855
+ // router can read it from the bag, then lifted here so the enforced CSP
1856
+ // header built after the render carries the same value.
1857
+ let cspNonce: string | undefined;
1858
+
1764
1859
  // Wrap the entire request in a RequestContext so that all code
1765
1860
  // in the call stack (loaders, invoke handlers, vtexFetchWithCookies)
1766
1861
  // can access the request and write response headers.
@@ -1770,6 +1865,24 @@ export function createDecoWorkerEntry(
1770
1865
  // via getRuntimeEnv() in sdk/otelAdapters.ts.
1771
1866
  setRuntimeEnv(env);
1772
1867
 
1868
+ // Fast-deploy: hydrate the in-memory decofile from KV on the first
1869
+ // request per isolate (awaited, ~10-30ms once), then opportunistically
1870
+ // poll for content changes (non-blocking, via ctx.waitUntil). No-op
1871
+ // unless the DECO_KV binding + DECO_FAST_DEPLOY are present —
1872
+ // non-migrated sites are unaffected.
1873
+ //
1874
+ // MUST come before reconfigureAppsOnce() and bindRequestDraft() below.
1875
+ // Both read the decofile, and both are one-shot/latching:
1876
+ // - reconfigureAppsOnce() configures apps from the blocks it sees and
1877
+ // latches `reinitPromise` forever. Running it first means a
1878
+ // fastDeploy build (whose bundled decofile is `{}`) configures ZERO
1879
+ // apps, and the only recovery is setBlocks()'s onChange listener,
1880
+ // whose promise setBlocks drops unawaited — so the request would
1881
+ // proceed with no app loaders registered.
1882
+ // - bindRequestDraft() composes draft overrides into loadBlocks().
1883
+ await ensureBlocksHydrated(env, ctx);
1884
+ maybePollRevision(env, ctx);
1885
+
1773
1886
  // First-request re-configuration of apps. autoconfigApps() runs at
1774
1887
  // module init (setup.ts), before `env` — and thus DECO_CRYPTO_KEY —
1775
1888
  // is available, so encrypted app credentials (VTEX appKey/appToken,
@@ -1841,6 +1954,15 @@ export function createDecoWorkerEntry(
1841
1954
  if (token) RequestContext.setBag(CSEG_BAG_KEY, token);
1842
1955
  }
1843
1956
 
1957
+ // CSP nonce (enforce mode only): produce it before the render and
1958
+ // publish it in the bag so `createDecoRouter` (router.options.ssr.nonce)
1959
+ // and the deco layout components pick it up while rendering. Lifted to
1960
+ // `cspNonce` so applySecurityHeaders below stamps the matching header.
1961
+ if (cspMode === "enforce") {
1962
+ cspNonce = generateNonce();
1963
+ RequestContext.setBag(NONCE_BAG_KEY, cspNonce);
1964
+ }
1965
+
1844
1966
  const appMw = getAppMiddleware();
1845
1967
  const innerResponse = appMw
1846
1968
  ? await appMw(request, () => handleRequest(request, env, ctx))
@@ -1893,7 +2015,7 @@ export function createDecoWorkerEntry(
1893
2015
  response.headers.set("CDN-Cache-Control", "no-store");
1894
2016
  }
1895
2017
 
1896
- let finalResponse = applySecurityHeaders(response);
2018
+ let finalResponse = applySecurityHeaders(response, cspNonce);
1897
2019
 
1898
2020
  // Echo request.id + trace.id back to the client / tail worker.
1899
2021
  // The CF tail worker reads these headers off the response to
@@ -2000,13 +2122,9 @@ export function createDecoWorkerEntry(
2000
2122
  ): Promise<Response> {
2001
2123
  const url = new URL(request.url);
2002
2124
 
2003
- // Fast-deploy: hydrate the in-memory decofile from KV on the first request
2004
- // per isolate (awaited, ~10-30ms once), then opportunistically poll for
2005
- // content changes (non-blocking, via ctx.waitUntil). No-op unless the
2006
- // DECO_KV binding is present — non-migrated sites are unaffected. Runs
2007
- // before admin routes so /.decofile reads reflect KV too.
2008
- await ensureBlocksHydrated(env, ctx);
2009
- maybePollRevision(env, ctx);
2125
+ // NOTE: fast-deploy hydration does NOT run here. It must happen before
2126
+ // `reconfigureAppsOnce()` and `bindRequestDraft()`, both of which run in
2127
+ // the outer fetch above — see the `ensureBlocksHydrated` call there.
2010
2128
 
2011
2129
  {
2012
2130
  const segment = buildSegment?.(request);
@@ -162,7 +162,7 @@ const STUB_SOURCE = {
162
162
  * Resolvable). This matters because meta.gen.json is committed and Studio reads
163
163
  * it as-is (no composeMeta at read time) — an uncomposed rewrite would silently
164
164
  * break the admin editors, e.g. the date matcher powering variant rules
165
- * disappearing (casaevideo-tanstack #633). Mirrors `npm run generate`'s schema
165
+ * disappearing (a production storefront regression). Mirrors `npm run generate`'s schema
166
166
  * step. Both invocation sites in configureServer derive their args here so they
167
167
  * can never drift apart.
168
168
  *
@@ -194,6 +194,13 @@ export function generateSchemaArgs(siteName) {
194
194
  * @returns {import("vite").PluginOption}
195
195
  */
196
196
  export function decoVitePlugin({ fastDeploy = false } = {}) {
197
+ // Set from the `config` hook (which Vite always runs before `load`). The
198
+ // fastDeploy stub must apply to production builds ONLY: `vite dev` has no KV
199
+ // to hydrate from, and the dev bootstrap below deliberately relies on reading
200
+ // the `.json` sibling that the stub bypasses — stubbing there blanks the
201
+ // local site.
202
+ let isBuild = false;
203
+
197
204
  /** @type {import("vite").Plugin} */
198
205
  const plugin = {
199
206
  name: "deco-server-only-stubs",
@@ -231,7 +238,8 @@ export function decoVitePlugin({ fastDeploy = false } = {}) {
231
238
  // second, permanently-reachable copy in isolate memory (the site's
232
239
  // `import { blocks }` binding keeps the bundled graph alive for the
233
240
  // isolate's whole life, even after `setBlocks()` swaps in the KV one).
234
- if (fastDeploy) {
241
+ // Build only — see `isBuild` above.
242
+ if (fastDeploy && isBuild) {
235
243
  return "export const blocks = {};";
236
244
  }
237
245
 
@@ -715,6 +723,9 @@ export function decoVitePlugin({ fastDeploy = false } = {}) {
715
723
  },
716
724
 
717
725
  config(_cfg, { command }) {
726
+ // Gate the fastDeploy SSR stub in `load()` to production builds.
727
+ isBuild = command === "build";
728
+
718
729
  /** @type {import("vite").UserConfig} */
719
730
  const cfg = {};
720
731
 
@@ -746,9 +757,9 @@ export function decoVitePlugin({ fastDeploy = false } = {}) {
746
757
  }
747
758
 
748
759
  // Allow tunnel domains through Vite's host check.
749
- // .deco.studio is the new admin frontend; both real-world Deco sites
750
- // (casaevideo-storefront, baggagio-tanstack) duplicated this list to
751
- // include it — bundling it here removes that boilerplate.
760
+ // .deco.studio is the new admin frontend; multiple real-world Deco sites
761
+ // duplicated this list to include it — bundling it here removes that
762
+ // boilerplate.
752
763
  if (process.env.DECO_SITE_NAME) {
753
764
  cfg.server = {
754
765
  allowedHosts: [".deco.host", ".decocdn.com", ".deco.studio"],
@@ -767,6 +778,14 @@ export function decoVitePlugin({ fastDeploy = false } = {}) {
767
778
  cfg.define = {
768
779
  ...cfg.define,
769
780
  __DECO_BUILD_HASH__: JSON.stringify(buildHash),
781
+ // Tells the runtime whether this bundle actually ships a decofile.
782
+ // `ensureBlocksHydrated` needs a build-time answer: with no bundled
783
+ // snapshot, its "warn and serve bundled" recovery would serve an EMPTY
784
+ // site with 200s. Inferring it from an empty in-memory map at runtime
785
+ // is not equivalent — draft-preview overrides can make a stubbed bundle
786
+ // look populated, and a legitimately-empty decofile (new site) would
787
+ // look stubbed.
788
+ __DECO_BLOCKS_STUBBED__: JSON.stringify(fastDeploy && command === "build"),
770
789
  };
771
790
 
772
791
  // Only split chunks for production builds — dev uses unbundled ESM.
@@ -58,7 +58,7 @@ describe("generateSchemaArgs (regression: meta.gen.json must be composed)", () =
58
58
  // start) derive their args from this helper. generate-schema always composes
59
59
  // before writing, so the manifest carries every framework website/* block
60
60
  // (matchers/Page/Resolvable) that Studio — which reads meta.gen.json as-is —
61
- // needs, e.g. the variant date matcher. See casaevideo-tanstack #633.
61
+ // needs, e.g. the variant date matcher. See a production storefront regression.
62
62
  it("targets the given site", () => {
63
63
  expect(generateSchemaArgs("my-site")).toEqual(["--site", "my-site"]);
64
64
  });
@@ -52,45 +52,61 @@ describe("decoVitePlugin — loaders.gen client stub", () => {
52
52
  });
53
53
 
54
54
  /**
55
- * `fastDeploy: true` must stub blocks.gen out of the SERVER bundle too.
55
+ * `fastDeploy: true` must stub blocks.gen out of the SERVER bundle — but only
56
+ * for production builds.
56
57
  *
57
- * Otherwise a fast-deploy site holds the decofile twice: the bundled
58
+ * Without the stub, a fast-deploy site holds the decofile twice: the bundled
58
59
  * JSON.parse(...) graph stays reachable via the site's `import { blocks }`
59
- * binding for the isolate's whole life, and ensureBlocksHydrated adds a
60
- * second graph. Tens of MB of avoidable memory for a 10MB decofile.
60
+ * binding for the isolate's whole life, and ensureBlocksHydrated adds a second
61
+ * graph. Measured at 13.6 MB + 13.4 MB for a 9.2 MB decofile.
62
+ *
63
+ * In `vite dev` there is no KV to hydrate from, and the dev bootstrap relies on
64
+ * reading the `.json` sibling the stub bypasses — so stubbing there would blank
65
+ * the local site.
61
66
  */
62
67
  describe("decoVitePlugin — fastDeploy server stub", () => {
63
68
  const id = "/repo/.deco/blocks.gen.ts";
64
69
  const STUB = "export const blocks = {};";
65
70
 
66
- it("stubs blocks.gen on SSR when fastDeploy is on", () => {
67
- const plugin = decoVitePlugin({ fastDeploy: true }) as {
68
- load: (id: string, options?: { ssr?: boolean }) => string | undefined;
69
- };
70
- expect(plugin.load(id, { ssr: true })).toBe(STUB);
71
+ /** @param {{fastDeploy?: boolean}} opts @param {"build"|"serve"} command */
72
+ const make = (opts, command) => {
73
+ const p = /** @type {any} */ (decoVitePlugin(opts));
74
+ p.config({}, { command }); // Vite always runs config() before load()
75
+ return p;
76
+ };
77
+
78
+ it("stubs blocks.gen on SSR for a production build", () => {
79
+ expect(make({ fastDeploy: true }, "build").load(id, { ssr: true })).toBe(STUB);
80
+ });
81
+
82
+ it("does NOT stub on SSR in dev, where there is no KV to hydrate from", () => {
83
+ expect(make({ fastDeploy: true }, "serve").load(id, { ssr: true })).not.toBe(STUB);
71
84
  });
72
85
 
73
- it("keeps stubbing the client bundle when fastDeploy is on", () => {
74
- const plugin = decoVitePlugin({ fastDeploy: true }) as {
75
- load: (id: string, options?: { ssr?: boolean }) => string | undefined;
76
- };
77
- expect(plugin.load(id, { ssr: false })).toBe(STUB);
86
+ it("keeps stubbing the client bundle regardless", () => {
87
+ expect(make({ fastDeploy: true }, "build").load(id, { ssr: false })).toBe(STUB);
88
+ expect(make({ fastDeploy: true }, "serve").load(id, { ssr: false })).toBe(STUB);
78
89
  });
79
90
 
80
91
  it("does NOT stub blocks.gen on SSR by default (bundled fallback preserved)", () => {
81
- const plugin = decoVitePlugin() as {
82
- load: (id: string, options?: { ssr?: boolean }) => string | undefined;
83
- };
84
92
  // No .json sibling on disk for this synthetic path, so the hook falls
85
- // through to Vite (undefined) rather than returning a stub. The point is
86
- // that it never returns the empty stub for SSR.
87
- expect(plugin.load(id, { ssr: true })).not.toBe(STUB);
93
+ // through to Vite (undefined). The point is it never returns the stub.
94
+ expect(make({}, "build").load(id, { ssr: true })).not.toBe(STUB);
95
+ });
96
+
97
+ it("leaves unrelated modules alone", () => {
98
+ expect(make({ fastDeploy: true }, "build").load("/repo/src/x.tsx", { ssr: true })).toBeUndefined();
88
99
  });
89
100
 
90
- it("leaves unrelated modules alone with fastDeploy on", () => {
91
- const plugin = decoVitePlugin({ fastDeploy: true }) as {
92
- load: (id: string, options?: { ssr?: boolean }) => string | undefined;
93
- };
94
- expect(plugin.load("/repo/src/sections/Hero.tsx", { ssr: true })).toBeUndefined();
101
+ it("defines __DECO_BLOCKS_STUBBED__ so the runtime knows whether it has a fallback", () => {
102
+ const build = /** @type {any} */ (decoVitePlugin({ fastDeploy: true })).config({}, { command: "build" });
103
+ expect(build.define.__DECO_BLOCKS_STUBBED__).toBe("true");
104
+
105
+ // Dev and the default must both report "no, you still have a decofile",
106
+ // otherwise ensureBlocksHydrated would start failing requests.
107
+ const dev = /** @type {any} */ (decoVitePlugin({ fastDeploy: true })).config({}, { command: "serve" });
108
+ expect(dev.define.__DECO_BLOCKS_STUBBED__).toBe("false");
109
+ const def = /** @type {any} */ (decoVitePlugin()).config({}, { command: "build" });
110
+ expect(def.define.__DECO_BLOCKS_STUBBED__).toBe("false");
95
111
  });
96
112
  });