@decocms/tanstack 7.64.3 → 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.
@@ -1,9 +1,13 @@
1
1
  import { computeRevision, revisionKey, setBlocks, snapshotKey } from "@decocms/blocks/cms";
2
- import { __resetAutoconfigStateForTests, autoconfigApps } from "@decocms/blocks-admin/apps/autoconfig";
2
+ import {
3
+ __resetAutoconfigStateForTests,
4
+ autoconfigApps,
5
+ } from "@decocms/blocks-admin/apps/autoconfig";
3
6
  import { afterEach, beforeEach, describe, expect, it } from "vitest";
4
- import { __resetKvHydrationStateForTests } from "./kvHydration";
5
7
  import { segmentToken } from "./cdnSegment";
8
+ import { __resetKvHydrationStateForTests } from "./kvHydration";
6
9
  import {
10
+ buildEnforcedCsp,
7
11
  buildGeoCacheParam,
8
12
  createDecoWorkerEntry,
9
13
  DECO_ADMIN_FRAME_ANCESTORS,
@@ -61,10 +65,7 @@ describe("injectGeoCookies", () => {
61
65
  });
62
66
 
63
67
  it("strips cf-ipcity from the outgoing Request headers while preserving the value in __cf_geo_city cookie", () => {
64
- const req = makeRequest(
65
- { city: "Brasília", country: "BR" },
66
- { "cf-ipcity": "Brasília" },
67
- );
68
+ const req = makeRequest({ city: "Brasília", country: "BR" }, { "cf-ipcity": "Brasília" });
68
69
 
69
70
  const out = injectGeoCookies(req);
70
71
 
@@ -93,10 +94,7 @@ describe("injectGeoCookies", () => {
93
94
  });
94
95
 
95
96
  it("preserves a pre-existing cookie header", () => {
96
- const req = makeRequest(
97
- { region: "São Paulo" },
98
- { cookie: "vtex_segment=abc; another=xyz" },
99
- );
97
+ const req = makeRequest({ region: "São Paulo" }, { cookie: "vtex_segment=abc; another=xyz" });
100
98
 
101
99
  const out = injectGeoCookies(req);
102
100
 
@@ -151,9 +149,7 @@ describe("buildGeoCacheParam", () => {
151
149
 
152
150
  it("omits missing fields gracefully", () => {
153
151
  expect(buildGeoCacheParam({ country: "BR" }, "city")).toBe("BR");
154
- expect(buildGeoCacheParam({ country: "BR", region: "MG" }, "city")).toBe(
155
- "BR|MG",
156
- );
152
+ expect(buildGeoCacheParam({ country: "BR", region: "MG" }, "city")).toBe("BR|MG");
157
153
  });
158
154
 
159
155
  it("returns undefined when cf has none of country/region/city", () => {
@@ -227,11 +223,7 @@ describe("CMS redirects", () => {
227
223
  const worker = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
228
224
  observability: false,
229
225
  });
230
- const res = await worker.fetch(
231
- new Request("https://example.com/old"),
232
- EMPTY_ENV,
233
- MOCK_CTX,
234
- );
226
+ const res = await worker.fetch(new Request("https://example.com/old"), EMPTY_ENV, MOCK_CTX);
235
227
  expect(res.status).toBe(301);
236
228
  expect(res.headers.get("Location")).toBe("/new");
237
229
  });
@@ -265,11 +257,7 @@ describe("CMS redirects", () => {
265
257
  const worker = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
266
258
  observability: false,
267
259
  });
268
- const res = await worker.fetch(
269
- new Request("https://example.com/promo"),
270
- EMPTY_ENV,
271
- MOCK_CTX,
272
- );
260
+ const res = await worker.fetch(new Request("https://example.com/promo"), EMPTY_ENV, MOCK_CTX);
273
261
  expect(res.status).toBe(302);
274
262
  expect(res.headers.get("Location")).toBe("/promo%C3%A7%C3%A3o");
275
263
  });
@@ -284,11 +272,7 @@ describe("CMS redirects", () => {
284
272
  const worker = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
285
273
  observability: false,
286
274
  });
287
- const res = await worker.fetch(
288
- new Request("https://example.com/promo"),
289
- EMPTY_ENV,
290
- MOCK_CTX,
291
- );
275
+ const res = await worker.fetch(new Request("https://example.com/promo"), EMPTY_ENV, MOCK_CTX);
292
276
  expect(res.status).toBe(302);
293
277
  expect(res.headers.get("Location")).toBe("/sale");
294
278
  });
@@ -303,11 +287,7 @@ describe("CMS redirects", () => {
303
287
  const worker = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
304
288
  observability: false,
305
289
  });
306
- const res = await worker.fetch(
307
- new Request("https://example.com/other"),
308
- EMPTY_ENV,
309
- MOCK_CTX,
310
- );
290
+ const res = await worker.fetch(new Request("https://example.com/other"), EMPTY_ENV, MOCK_CTX);
311
291
  expect(res.status).toBe(200);
312
292
  });
313
293
 
@@ -318,11 +298,7 @@ describe("CMS redirects", () => {
318
298
  });
319
299
 
320
300
  // First request with no redirects — falls through
321
- const res1 = await worker.fetch(
322
- new Request("https://example.com/v1"),
323
- EMPTY_ENV,
324
- MOCK_CTX,
325
- );
301
+ const res1 = await worker.fetch(new Request("https://example.com/v1"), EMPTY_ENV, MOCK_CTX);
326
302
  expect(res1.status).toBe(200);
327
303
 
328
304
  // Hot-reload: add a redirect
@@ -334,11 +310,7 @@ describe("CMS redirects", () => {
334
310
  });
335
311
 
336
312
  // Same path should now redirect
337
- const res2 = await worker.fetch(
338
- new Request("https://example.com/v1"),
339
- EMPTY_ENV,
340
- MOCK_CTX,
341
- );
313
+ const res2 = await worker.fetch(new Request("https://example.com/v1"), EMPTY_ENV, MOCK_CTX);
342
314
  expect(res2.status).toBe(301);
343
315
  expect(res2.headers.get("Location")).toBe("/v2");
344
316
  });
@@ -415,14 +387,8 @@ describe("security headers — frame-ancestors default", () => {
415
387
 
416
388
  it("applies the default frame-ancestors CSP on HTML responses and drops X-Frame-Options", async () => {
417
389
  const worker = createDecoWorkerEntry(HTML_SERVER_ENTRY);
418
- const res = await worker.fetch(
419
- new Request("https://example.com/"),
420
- EMPTY_ENV,
421
- MOCK_CTX,
422
- );
423
- expect(res.headers.get("Content-Security-Policy")).toBe(
424
- DEFAULT_FRAME_ANCESTORS_CSP,
425
- );
390
+ const res = await worker.fetch(new Request("https://example.com/"), EMPTY_ENV, MOCK_CTX);
391
+ expect(res.headers.get("Content-Security-Policy")).toBe(DEFAULT_FRAME_ANCESTORS_CSP);
426
392
  expect(res.headers.get("X-Frame-Options")).toBeNull();
427
393
  // Other defaults are still present.
428
394
  expect(res.headers.get("X-Content-Type-Options")).toBe("nosniff");
@@ -432,28 +398,16 @@ describe("security headers — frame-ancestors default", () => {
432
398
  const worker = createDecoWorkerEntry(HTML_SERVER_ENTRY, {
433
399
  securityHeaders: { "Content-Security-Policy": "frame-ancestors 'none'" },
434
400
  });
435
- const res = await worker.fetch(
436
- new Request("https://example.com/"),
437
- EMPTY_ENV,
438
- MOCK_CTX,
439
- );
440
- expect(res.headers.get("Content-Security-Policy")).toBe(
441
- "frame-ancestors 'none'",
442
- );
401
+ const res = await worker.fetch(new Request("https://example.com/"), EMPTY_ENV, MOCK_CTX);
402
+ expect(res.headers.get("Content-Security-Policy")).toBe("frame-ancestors 'none'");
443
403
  });
444
404
 
445
405
  it("emits the full site CSP report-only alongside the enforced frame-ancestors", async () => {
446
406
  const worker = createDecoWorkerEntry(HTML_SERVER_ENTRY, {
447
407
  csp: ["default-src 'self'", "img-src 'self' https:"],
448
408
  });
449
- const res = await worker.fetch(
450
- new Request("https://example.com/"),
451
- EMPTY_ENV,
452
- MOCK_CTX,
453
- );
454
- expect(res.headers.get("Content-Security-Policy")).toBe(
455
- DEFAULT_FRAME_ANCESTORS_CSP,
456
- );
409
+ const res = await worker.fetch(new Request("https://example.com/"), EMPTY_ENV, MOCK_CTX);
410
+ expect(res.headers.get("Content-Security-Policy")).toBe(DEFAULT_FRAME_ANCESTORS_CSP);
457
411
  expect(res.headers.get("Content-Security-Policy-Report-Only")).toBe(
458
412
  "default-src 'self'; img-src 'self' https:",
459
413
  );
@@ -463,14 +417,83 @@ describe("security headers — frame-ancestors default", () => {
463
417
  const worker = createDecoWorkerEntry(HTML_SERVER_ENTRY, {
464
418
  securityHeaders: false,
465
419
  });
466
- const res = await worker.fetch(
467
- new Request("https://example.com/"),
468
- EMPTY_ENV,
469
- MOCK_CTX,
470
- );
420
+ const res = await worker.fetch(new Request("https://example.com/"), EMPTY_ENV, MOCK_CTX);
471
421
  expect(res.headers.get("Content-Security-Policy")).toBeNull();
472
422
  expect(res.headers.get("X-Content-Type-Options")).toBeNull();
473
423
  });
424
+
425
+ it("keeps report-only by default even when a site passes csp (cspMode unset)", async () => {
426
+ const worker = createDecoWorkerEntry(HTML_SERVER_ENTRY, {
427
+ csp: ["default-src 'self'"],
428
+ });
429
+ const res = await worker.fetch(new Request("https://example.com/"), EMPTY_ENV, MOCK_CTX);
430
+ expect(res.headers.get("Content-Security-Policy")).toBe(DEFAULT_FRAME_ANCESTORS_CSP);
431
+ expect(res.headers.get("Content-Security-Policy-Report-Only")).toBe("default-src 'self'");
432
+ });
433
+
434
+ it("enforce mode emits a nonce CSP (no report-only, no unsafe-inline) on a no-store HTML response", async () => {
435
+ const worker = createDecoWorkerEntry(HTML_SERVER_ENTRY, {
436
+ csp: ["default-src 'self'", "script-src 'self' 'unsafe-inline' https://gtm.example"],
437
+ cspMode: "enforce",
438
+ });
439
+ const res = await worker.fetch(new Request("https://example.com/"), EMPTY_ENV, MOCK_CTX);
440
+ const csp = res.headers.get("Content-Security-Policy") ?? "";
441
+ // Promoted to enforced — report-only is gone.
442
+ expect(res.headers.get("Content-Security-Policy-Report-Only")).toBeNull();
443
+ expect(csp).toContain("default-src 'self'");
444
+ // script-src hardened: unsafe-inline dropped, per-request nonce +
445
+ // inline-speculation-rules added, the host allowlist kept.
446
+ expect(csp).toMatch(/script-src[^;]*'nonce-[A-Za-z0-9+/=]+'/);
447
+ expect(csp).toContain("'inline-speculation-rules'");
448
+ expect(csp).toContain("https://gtm.example");
449
+ expect(csp).not.toContain("'unsafe-inline'");
450
+ // Framing protection preserved.
451
+ expect(csp).toContain("frame-ancestors");
452
+ });
453
+
454
+ it("enforce mode leaves 'unsafe-eval' in place (opt-out is explicit)", async () => {
455
+ const worker = createDecoWorkerEntry(HTML_SERVER_ENTRY, {
456
+ csp: ["script-src 'self' 'unsafe-inline' 'unsafe-eval'"],
457
+ cspMode: "enforce",
458
+ });
459
+ const res = await worker.fetch(new Request("https://example.com/"), EMPTY_ENV, MOCK_CTX);
460
+ const csp = res.headers.get("Content-Security-Policy") ?? "";
461
+ expect(csp).toContain("'unsafe-eval'");
462
+ expect(csp).not.toContain("'unsafe-inline'");
463
+ });
464
+ });
465
+
466
+ describe("buildEnforcedCsp", () => {
467
+ const FA = "frame-ancestors 'self' https://studio.decocms.com";
468
+
469
+ it("hardens script-src: drops unsafe-inline, adds nonce + inline-speculation-rules, keeps hosts + unsafe-eval", () => {
470
+ const csp = buildEnforcedCsp(
471
+ ["script-src 'self' 'unsafe-inline' 'unsafe-eval' https://gtm.example"],
472
+ FA,
473
+ "abc123",
474
+ );
475
+ expect(csp).toContain("script-src");
476
+ expect(csp).toContain("'self'");
477
+ expect(csp).toContain("https://gtm.example");
478
+ expect(csp).toContain("'unsafe-eval'");
479
+ expect(csp).toContain("'nonce-abc123'");
480
+ expect(csp).toContain("'inline-speculation-rules'");
481
+ expect(csp).not.toContain("'unsafe-inline'");
482
+ expect(csp).toContain(FA);
483
+ });
484
+
485
+ it("adds a script-src when the site declared none", () => {
486
+ const csp = buildEnforcedCsp(["default-src 'self'"], FA, "n0nce");
487
+ expect(csp).toContain("default-src 'self'");
488
+ expect(csp).toContain("script-src 'self' 'nonce-n0nce' 'inline-speculation-rules'");
489
+ expect(csp).toContain(FA);
490
+ });
491
+
492
+ it("drops any frame-ancestors from the site csp in favour of the canonical one", () => {
493
+ const csp = buildEnforcedCsp(["frame-ancestors 'none'", "default-src 'self'"], FA, "x");
494
+ expect(csp).not.toContain("frame-ancestors 'none'");
495
+ expect(csp).toContain(FA);
496
+ });
474
497
  });
475
498
 
476
499
  describe("POST /_cache/purge-loaders", () => {
@@ -479,10 +502,7 @@ describe("POST /_cache/purge-loaders", () => {
479
502
  setBlocks({});
480
503
  });
481
504
 
482
- const purge = (
483
- env: Record<string, unknown>,
484
- headers: Record<string, string> = {},
485
- ) => {
505
+ const purge = (env: Record<string, unknown>, headers: Record<string, string> = {}) => {
486
506
  const worker = createDecoWorkerEntry(MOCK_SERVER_ENTRY, {
487
507
  observability: false,
488
508
  });
@@ -502,18 +522,12 @@ describe("POST /_cache/purge-loaders", () => {
502
522
  });
503
523
 
504
524
  it("401s with the wrong token", async () => {
505
- const res = await purge(
506
- { PURGE_TOKEN: "secret" },
507
- { Authorization: "Bearer nope" },
508
- );
525
+ const res = await purge({ PURGE_TOKEN: "secret" }, { Authorization: "Bearer nope" });
509
526
  expect(res.status).toBe(401);
510
527
  });
511
528
 
512
529
  it("clears the loader cache with a valid token", async () => {
513
- const res = await purge(
514
- { PURGE_TOKEN: "secret" },
515
- { Authorization: "Bearer secret" },
516
- );
530
+ const res = await purge({ PURGE_TOKEN: "secret" }, { Authorization: "Bearer secret" });
517
531
  expect(res.status).toBe(200);
518
532
  expect(await res.json()).toEqual({ cleared: true, scope: "isolate" });
519
533
  });
@@ -557,14 +571,8 @@ describe("X-Cache-Segment — custom SegmentKey fields (#284)", () => {
557
571
  delivery: "store-42",
558
572
  }),
559
573
  });
560
- const res = await worker.fetch(
561
- new Request("https://example.com/"),
562
- EMPTY_ENV,
563
- MOCK_CTX,
564
- );
565
- expect(res.headers.get("X-Cache-Segment")).toBe(
566
- "desktop|r=RJ|delivery=store-42",
567
- );
574
+ const res = await worker.fetch(new Request("https://example.com/"), EMPTY_ENV, MOCK_CTX);
575
+ expect(res.headers.get("X-Cache-Segment")).toBe("desktop|r=RJ|delivery=store-42");
568
576
  });
569
577
 
570
578
  it("produces different X-Cache-Segment hashes for requests that only differ by a custom field", async () => {
@@ -574,19 +582,11 @@ describe("X-Cache-Segment — custom SegmentKey fields (#284)", () => {
574
582
  buildSegment: () => ({ device: "desktop", delivery }),
575
583
  });
576
584
 
577
- const first = await worker.fetch(
578
- new Request("https://example.com/"),
579
- EMPTY_ENV,
580
- MOCK_CTX,
581
- );
585
+ const first = await worker.fetch(new Request("https://example.com/"), EMPTY_ENV, MOCK_CTX);
582
586
  const firstSegment = first.headers.get("X-Cache-Segment");
583
587
 
584
588
  delivery = "store-2";
585
- const second = await worker.fetch(
586
- new Request("https://example.com/"),
587
- EMPTY_ENV,
588
- MOCK_CTX,
589
- );
589
+ const second = await worker.fetch(new Request("https://example.com/"), EMPTY_ENV, MOCK_CTX);
590
590
  const secondSegment = second.headers.get("X-Cache-Segment");
591
591
 
592
592
  expect(firstSegment).not.toBe(secondSegment);
@@ -601,11 +601,7 @@ describe("X-Cache-Segment — custom SegmentKey fields (#284)", () => {
601
601
  flags: ["b", "a"],
602
602
  }),
603
603
  });
604
- const res = await worker.fetch(
605
- new Request("https://example.com/"),
606
- EMPTY_ENV,
607
- MOCK_CTX,
608
- );
604
+ const res = await worker.fetch(new Request("https://example.com/"), EMPTY_ENV, MOCK_CTX);
609
605
  expect(res.headers.get("X-Cache-Segment")).toBe("desktop|sc=1|f=a,b");
610
606
  });
611
607
  });
@@ -622,8 +618,7 @@ describe("draft preview (pull-based)", () => {
622
618
  const REFLECT_ENTRY = {
623
619
  fetch: async () => {
624
620
  const { loadBlocks } = await import("@decocms/blocks/cms");
625
- const home =
626
- (loadBlocks()["pages-home"] as { title?: string } | undefined) ?? {};
621
+ const home = (loadBlocks()["pages-home"] as { title?: string } | undefined) ?? {};
627
622
  return new Response(home.title ?? "PUBLISHED", { status: 200 });
628
623
  },
629
624
  };
@@ -631,9 +626,7 @@ describe("draft preview (pull-based)", () => {
631
626
  let realFetch: typeof fetch;
632
627
  afterEach(async () => {
633
628
  globalThis.fetch = realFetch;
634
- const { setDraftPreviewHosts, clearDraftCache } = await import(
635
- "@decocms/blocks/cms"
636
- );
629
+ const { setDraftPreviewHosts, clearDraftCache } = await import("@decocms/blocks/cms");
637
630
  setDraftPreviewHosts([]);
638
631
  clearDraftCache();
639
632
  __resetKvHydrationStateForTests();
@@ -641,9 +634,7 @@ describe("draft preview (pull-based)", () => {
641
634
  });
642
635
 
643
636
  async function enable() {
644
- const { setDraftPreviewHosts, clearDraftCache } = await import(
645
- "@decocms/blocks/cms"
646
- );
637
+ const { setDraftPreviewHosts, clearDraftCache } = await import("@decocms/blocks/cms");
647
638
  setBlocks({
648
639
  "pages-home": { name: "home", path: "/", title: "PUBLISHED" },
649
640
  });
@@ -784,7 +775,9 @@ describe('cdnCacheControl: "serverfn-segment"', () => {
784
775
 
785
776
  it("keeps no-store when the marker is from an older build", async () => {
786
777
  // Deploying does not purge the CDN, so a stale build token must not match.
787
- expect(await cdnHeader(sfnUrl(segmentToken("desktop", false, "oldbuild") as string))).toBe("no-store");
778
+ expect(await cdnHeader(sfnUrl(segmentToken("desktop", false, "oldbuild") as string))).toBe(
779
+ "no-store",
780
+ );
788
781
  });
789
782
 
790
783
  it("keeps no-store when there is no build hash", async () => {
@@ -851,7 +844,11 @@ describe("cdnCacheControl default", () => {
851
844
  observability: false,
852
845
  buildSegment: () => ({ device: "desktop" as const }),
853
846
  });
854
- const html = await w.fetch(new Request("https://example.com/"), { BUILD_HASH: BUILD_D }, MOCK_CTX);
847
+ const html = await w.fetch(
848
+ new Request("https://example.com/"),
849
+ { BUILD_HASH: BUILD_D },
850
+ MOCK_CTX,
851
+ );
855
852
  expect(html.headers.get("CDN-Cache-Control")).toBe("no-store");
856
853
 
857
854
  const sfn = await w.fetch(
@@ -914,7 +911,11 @@ describe("CDN-Cache-Control at the single response exit", () => {
914
911
  deviceSpecificKeys: false,
915
912
  geoCacheKey: "off",
916
913
  });
917
- const res = await w.fetch(new Request("https://example.com/some-category"), EMPTY_ENV, MOCK_CTX);
914
+ const res = await w.fetch(
915
+ new Request("https://example.com/some-category"),
916
+ EMPTY_ENV,
917
+ MOCK_CTX,
918
+ );
918
919
  expect(res.headers.get("CDN-Cache-Control")).toMatch(/^public, max-age=\d+$/);
919
920
  });
920
921
  });
@@ -1000,19 +1001,19 @@ describe("fast-deploy hydration ordering", () => {
1000
1001
  await autoconfigApps({}, registry as never);
1001
1002
  expect(seen).toEqual([]); // nothing to configure yet — this is the trap
1002
1003
 
1003
- const store = new Map<string, string>([
1004
- [snapshotKey(ID), JSON.stringify(KV_BLOCKS)],
1005
- [revisionKey(ID), computeRevision(KV_BLOCKS)],
1006
- ]);
1007
- const env = {
1008
- DECO_KV: {
1009
- get: (k: string) => Promise.resolve(store.get(k) ?? null),
1010
- put: () => Promise.resolve(),
1011
- delete: () => Promise.resolve(),
1012
- },
1013
- DECO_FAST_DEPLOY: "1",
1014
- DECO_DEPLOYMENT_ID: ID,
1015
- };
1004
+ const store = new Map<string, string>([
1005
+ [snapshotKey(ID), JSON.stringify(KV_BLOCKS)],
1006
+ [revisionKey(ID), computeRevision(KV_BLOCKS)],
1007
+ ]);
1008
+ const env = {
1009
+ DECO_KV: {
1010
+ get: (k: string) => Promise.resolve(store.get(k) ?? null),
1011
+ put: () => Promise.resolve(),
1012
+ delete: () => Promise.resolve(),
1013
+ },
1014
+ DECO_FAST_DEPLOY: "1",
1015
+ DECO_DEPLOYMENT_ID: ID,
1016
+ };
1016
1017
 
1017
1018
  const worker = createDecoWorkerEntry(MOCK_SERVER_ENTRY, { observability: false });
1018
1019
  await worker.fetch(new Request("https://example.com/"), env, MOCK_CTX);
@@ -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.
@@ -1859,6 +1954,15 @@ export function createDecoWorkerEntry(
1859
1954
  if (token) RequestContext.setBag(CSEG_BAG_KEY, token);
1860
1955
  }
1861
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
+
1862
1966
  const appMw = getAppMiddleware();
1863
1967
  const innerResponse = appMw
1864
1968
  ? await appMw(request, () => handleRequest(request, env, ctx))
@@ -1911,7 +2015,7 @@ export function createDecoWorkerEntry(
1911
2015
  response.headers.set("CDN-Cache-Control", "no-store");
1912
2016
  }
1913
2017
 
1914
- let finalResponse = applySecurityHeaders(response);
2018
+ let finalResponse = applySecurityHeaders(response, cspNonce);
1915
2019
 
1916
2020
  // Echo request.id + trace.id back to the client / tail worker.
1917
2021
  // The CF tail worker reads these headers off the response to
@@ -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
  *
@@ -757,9 +757,9 @@ export function decoVitePlugin({ fastDeploy = false } = {}) {
757
757
  }
758
758
 
759
759
  // Allow tunnel domains through Vite's host check.
760
- // .deco.studio is the new admin frontend; both real-world Deco sites
761
- // (casaevideo-storefront, baggagio-tanstack) duplicated this list to
762
- // 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.
763
763
  if (process.env.DECO_SITE_NAME) {
764
764
  cfg.server = {
765
765
  allowedHosts: [".deco.host", ".decocdn.com", ".deco.studio"],