@tokenoftrust/storefront-runner 7.7.3 → 7.8.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.
Files changed (65) hide show
  1. package/apps/storefront/dev-plugins/dev-auth-outbox.mjs +5 -3
  2. package/apps/storefront/src/components/catalog/storefront/ProductCard.astro +13 -9
  3. package/apps/storefront/src/components/catalog/storefront/islands/SearchTypeahead.tsx +2 -2
  4. package/apps/storefront/src/components/catalog/storefront/islands/VariantSelector.tsx +6 -4
  5. package/apps/storefront/src/components/catalog/storefront/plp/FacetSidebar.astro +4 -3
  6. package/apps/storefront/src/components/catalog/storefront/plp/SortSelect.astro +3 -2
  7. package/apps/storefront/src/components/compliance/storefront/islands/CheckoutComplianceGate.tsx +39 -45
  8. package/apps/storefront/src/components/publication/storefront/islands/CatalogQueryView.tsx +7 -4
  9. package/apps/storefront/src/layouts/Layout.astro +11 -7
  10. package/apps/storefront/src/lib/access/auth/agentSessionGate.ts +1 -0
  11. package/apps/storefront/src/lib/access/auth/loginGate.ts +14 -0
  12. package/apps/storefront/src/lib/access/shared/tenantRouting.ts +3 -1
  13. package/apps/storefront/src/lib/assets/captured-original-serve.ts +61 -1
  14. package/apps/storefront/src/lib/catalog/search/index.ts +3 -4
  15. package/apps/storefront/src/lib/catalog/shared/catalogIndex.ts +12 -7
  16. package/apps/storefront/src/lib/catalog/shared/catalogQueryView.ts +4 -2
  17. package/apps/storefront/src/lib/catalog/tot/query.ts +2 -1
  18. package/apps/storefront/src/lib/checkout/commerce/cartSession.ts +10 -11
  19. package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +81 -14
  20. package/apps/storefront/src/lib/compliance/browser/checkoutVerificationFlow.ts +35 -0
  21. package/apps/storefront/src/lib/content/seo/structuredData.ts +3 -2
  22. package/apps/storefront/src/lib/content/shared/jsonld.ts +3 -2
  23. package/apps/storefront/src/lib/customers/accounts/catalogAdmission.ts +75 -0
  24. package/apps/storefront/src/lib/customers/accounts/checkoutProof.ts +133 -0
  25. package/apps/storefront/src/lib/customers/accounts/orgKyb.ts +12 -0
  26. package/apps/storefront/src/lib/customers/accounts/pricing.ts +25 -0
  27. package/apps/storefront/src/lib/customers/accounts/purchaseAccess.ts +45 -0
  28. package/apps/storefront/src/lib/customers/accounts/scope.ts +55 -0
  29. package/apps/storefront/src/lib/customers/accounts/session.ts +173 -0
  30. package/apps/storefront/src/lib/customers/accounts/shopperPricingClient.ts +69 -0
  31. package/apps/storefront/src/lib/engagement/contact/submitToken.ts +2 -1
  32. package/apps/storefront/src/lib/inventory/allocations.ts +8 -5
  33. package/apps/storefront/src/lib/membership/eligibility.ts +2 -23
  34. package/apps/storefront/src/lib/publication/shared/cdnForward.ts +10 -3
  35. package/apps/storefront/src/lib/publication/shared/staticQuery.ts +10 -3
  36. package/apps/storefront/src/middleware/index.ts +80 -6
  37. package/apps/storefront/src/middleware/renderChain.ts +43 -26
  38. package/apps/storefront/src/middleware/routeBranch.ts +1 -0
  39. package/apps/storefront/src/middleware/staticBundle.ts +43 -13
  40. package/apps/storefront/src/pages/_sitemap.ts +14 -7
  41. package/apps/storefront/src/pages/api/cart-proposal/confirm.ts +2 -1
  42. package/apps/storefront/src/pages/api/cart-proposal/review.ts +5 -2
  43. package/apps/storefront/src/pages/api/commerce/cart-session.ts +3 -0
  44. package/apps/storefront/src/pages/api/commerce/checkout-sessions/[id].ts +2 -1
  45. package/apps/storefront/src/pages/api/commerce/checkout-sessions.ts +3 -1
  46. package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +43 -10
  47. package/apps/storefront/src/pages/api/compliance/preflight.ts +34 -5
  48. package/apps/storefront/src/pages/cart.ts +3 -0
  49. package/apps/storefront/src/pages/catalog-index.json.ts +3 -2
  50. package/apps/storefront/src/pages/collections/[handle]/page/[n].astro +2 -1
  51. package/apps/storefront/src/pages/collections/[handle].astro +2 -1
  52. package/apps/storefront/src/pages/collections/_CollectionView.astro +8 -4
  53. package/apps/storefront/src/pages/index.astro +5 -3
  54. package/apps/storefront/src/pages/llms.txt.ts +2 -1
  55. package/apps/storefront/src/pages/products/[handle].astro +52 -15
  56. package/apps/storefront/src/pages/saved.astro +2 -1
  57. package/package.json +1 -1
  58. package/packages/cli/src/declared-config.mjs +46 -1
  59. package/packages/public-runtime/src/checkout-orders.ts +9 -1
  60. package/packages/public-runtime/src/checkout.ts +1 -1
  61. package/packages/public-runtime/src/declared-tenant-config.d.mts +11 -1
  62. package/packages/public-runtime/src/declared-tenant-config.mjs +111 -1
  63. package/packages/public-runtime/src/publication-space.ts +1 -0
  64. package/packages/public-runtime/src/static-bundle.ts +28 -3
  65. package/packages/public-runtime/src/tenant.ts +15 -0
@@ -14,8 +14,14 @@ import { isPathPageable, withPathPage } from "../../catalog/shared/collectionPag
14
14
  import { buildQueryString, parseQuery } from "./url.js";
15
15
 
16
16
  /** The listing query a collection view at `url` applies (page from the path when the query names none). */
17
- export function effectiveCollectionQuery(url: URL, pathPage?: number): ListProductsQuery {
18
- return withPathPage(parseQuery(url), pathPage);
17
+ export function effectiveCollectionQuery(url: URL, pathPage?: number, pricesHidden = false): ListProductsQuery {
18
+ return withoutPrivatePriceQuery(withPathPage(parseQuery(url), pathPage), pricesHidden);
19
+ }
20
+
21
+ export function withoutPrivatePriceQuery(query: ListProductsQuery, pricesHidden: boolean): ListProductsQuery {
22
+ if (!pricesHidden) return query;
23
+ const { priceMin: _min, priceMax: _max, sort, ...filters } = query;
24
+ return sort && !sort.startsWith("price-") ? { ...filters, sort } : filters;
19
25
  }
20
26
 
21
27
  /** A stable key for the query a listing view applied. */
@@ -46,8 +52,9 @@ export function planCollectionQuery(opts: {
46
52
  /** Tenant-prefixed collection path, unformed (`/collections/<h>`). */
47
53
  pageBase: string;
48
54
  trailingSlash: boolean;
55
+ pricesHidden?: boolean;
49
56
  }): CollectionQueryPlan {
50
- const query = effectiveCollectionQuery(opts.url, opts.pathPage);
57
+ const query = effectiveCollectionQuery(opts.url, opts.pathPage, opts.pricesHidden);
51
58
  if (opts.appliedKey !== null && listQueryKey(query) === opts.appliedKey) return { kind: "rendered" };
52
59
  if (isPathPageable(query)) {
53
60
  const page = query.page ?? 1;
@@ -61,6 +61,9 @@ import { serveControlPlane } from "./controlPlane.js";
61
61
  import { KvSessionStore, readSession, SESSION_COOKIE } from "@/lib/access/auth/session";
62
62
  import { agentMayReach, agentSessionGateRefusal, holdReadMixedCredentialsRefusal } from "@/lib/access/auth/agentSessionGate";
63
63
  import { mintOpaqueBrokerAssertion } from "@/lib/access/auth/brokerAssertion";
64
+ import { withDeclaredTenantConfig } from "@/config/declaredTenantConfig";
65
+ import { closedCatalogPath, resolveShopperAccessPolicy } from "@tot/public-runtime/declared-tenant-config";
66
+ import { SHOPPER_CATALOG_COOKIE, verifyShopperCatalogAdmission } from "@/lib/customers/accounts/catalogAdmission";
64
67
  import {
65
68
  applyInternalContentResponsePolicy,
66
69
  authorizeInternalContentRequest,
@@ -91,7 +94,7 @@ export const onRequest = defineMiddleware(async (context, next) => {
91
94
  const outer = !context.locals.serverTiming;
92
95
  const timing = context.locals.serverTiming ?? new ServerTiming();
93
96
  context.locals.serverTiming = timing;
94
- const seen: { cdnForwarded: boolean; assetBasePath?: string } = { cdnForwarded: false };
97
+ const seen: RequestDelivery = { cdnForwarded: false };
95
98
  const served = await serveRequest(context, next, seen, timing);
96
99
  // Registered responsive renditions on a rendered page, by the same addresses and markup the static
97
100
  // bundle carries. The materialize render is left to the bundle build, which owns its renditions.
@@ -108,9 +111,26 @@ export const onRequest = defineMiddleware(async (context, next) => {
108
111
  scoped,
109
112
  visitorRegionFor(context.request, { cdnForwarded: seen.cdnForwarded, dev: import.meta.env.DEV }),
110
113
  );
114
+ if (seen.privateCatalog) {
115
+ finished.headers.set("cache-control", "private, no-store");
116
+ finished.headers.set("x-robots-tag", "noindex, nofollow");
117
+ }
111
118
  return outer ? withServerTiming(finished, timing) : finished;
112
119
  });
113
120
 
121
+ interface RequestDelivery {
122
+ cdnForwarded: boolean;
123
+ assetBasePath?: string;
124
+ privateCatalog?: boolean;
125
+ }
126
+
127
+ function privateCatalogResponse(status: number, location?: string): Response {
128
+ const headers = new Headers({ "cache-control": "private, no-store", "x-robots-tag": "noindex, nofollow" });
129
+ if (location) headers.set("location", location);
130
+ applySecurityHeaders(headers);
131
+ return new Response(null, { status, headers });
132
+ }
133
+
114
134
  /**
115
135
  * The sponsored-agent gate: null to proceed, or the 403 to answer. A request with no
116
136
  * session cookie, or a public/platform request an agent may make anyway, never pays
@@ -146,7 +166,7 @@ async function agentGate(
146
166
  async function serveRequest(
147
167
  context: APIContext,
148
168
  next: MiddlewareNext,
149
- seen: { cdnForwarded: boolean; assetBasePath?: string },
169
+ seen: RequestDelivery,
150
170
  timing: ServerTiming,
151
171
  ): Promise<Response> {
152
172
  const { request, locals } = context;
@@ -232,7 +252,7 @@ async function serveRequest(
232
252
  // Host first; if the host owns no tenant, a leading /<domain>/ path segment
233
253
  // selects one (DNS-free tenant selection on localhost/preview). The resolver
234
254
  // is KV-backed in prod (many-tenant) and static in plain dev.
235
- const { tenant, basePath, renderPath, imageBasePath } = await timing.time("tenant", async () => {
255
+ const { tenant, basePath, renderPath, imageBasePath, routedByFallback } = await timing.time("tenant", async () => {
236
256
  const resolver = await getTenantResolver();
237
257
  return cdn
238
258
  ? await resolveCdnForwardRouting(cdn, url.pathname, resolver)
@@ -274,6 +294,61 @@ async function serveRequest(
274
294
  return agentRefusal;
275
295
  }
276
296
 
297
+ const kv = await readKv("TENANT_CACHE");
298
+ const routeTarget = publication.action === "redirect-308" ? publication.locationPath
299
+ : publication.action === "render" ? publication.renderPath : renderPath;
300
+ const directCatalogPath = closedCatalogPath(renderPath);
301
+ const targetCatalogPath = closedCatalogPath(routeTarget);
302
+ let deliveryTenant = tenant;
303
+ const shopperRoute = /^\/(?:account|api\/account)(?:\/|$)/i.test(renderPath);
304
+ if (shopperRoute || directCatalogPath !== "allow" || targetCatalogPath !== "allow") {
305
+ const previewSecret = await readEnv("CUSTOMIZATION_PREVIEW_SECRET");
306
+ const now = Math.floor(Date.now() / 1000);
307
+ const preview = await resolveRequestPreviewContext({
308
+ url, request, cookies: context.cookies, renderPath, tenantId: tenant.tenant_id,
309
+ secret: previewSecret, nowSeconds: now,
310
+ });
311
+ const candidate = await resolveCandidateContentPin(url, tenant.tenant_id);
312
+ const materialize = await readEnv(MATERIALIZE_MODE_BINDING) === "1";
313
+ const localDev = import.meta.env.DEV && /^(?:localhost|127\.0\.0\.1)(?::\d+)?$/.test(host);
314
+ if (shopperRoute && routedByFallback && !localDev && !materialize &&
315
+ (!basePath || preview.context.status !== "valid")) return privateCatalogResponse(404);
316
+ const customization = await resolveCustomizationEnv({
317
+ isPreviewHost: host.toLowerCase().startsWith("preview.") && !candidate,
318
+ tenantId: tenant.tenant_id,
319
+ token: preview.context.status === "valid" ? preview.context.token : null,
320
+ secret: previewSecret,
321
+ nowSeconds: now,
322
+ pathname: url.pathname,
323
+ });
324
+ const env = candidate ? "test" : customization.env;
325
+ try {
326
+ const effective = await withDeclaredTenantConfig(tenant, key => kv?.get(key) ?? Promise.resolve(null), {
327
+ env, ...(candidate ? { pinnedVersionId: candidate.versionId } : {}),
328
+ });
329
+ deliveryTenant = effective;
330
+ if (resolveShopperAccessPolicy(effective).mode === "closed_store") {
331
+ seen.privateCatalog = true;
332
+ if (!shopperRoute) {
333
+ if (routedByFallback && !localDev && !materialize && !candidate &&
334
+ (!basePath || preview.context.status !== "valid")) return privateCatalogResponse(404);
335
+ if (directCatalogPath === "deny" || targetCatalogPath === "deny") return privateCatalogResponse(404);
336
+ if (preview.context.status === "refused" || customization.reject) return privateCatalogResponse(401);
337
+ const token = context.cookies.get(SHOPPER_CATALOG_COOKIE)?.value;
338
+ const scope = { tenantId: commerceTenantId(effective), stage: env === "live" ? "publication" : "preview" } as const;
339
+ if (!materialize &&
340
+ (!token || !await verifyShopperCatalogAdmission(token, scope, host, now))) {
341
+ const destination = new URL(`${basePath}/account/sign-in`, origin);
342
+ destination.searchParams.set("next", `${basePath}${renderPath}`);
343
+ return privateCatalogResponse(303, destination.href);
344
+ }
345
+ }
346
+ }
347
+ } catch {
348
+ return privateCatalogResponse(503);
349
+ }
350
+ }
351
+
277
352
  // The availability document (ADR 0043): stored bytes by key, one R2 read, no D1 and no render.
278
353
  // On a login-gated host it is served by the control plane, after the gate.
279
354
  const availabilityStage = publicAvailabilityStageOf(renderPath);
@@ -380,10 +455,9 @@ async function serveRequest(
380
455
  // Workers Cache API: backs the full-page edge cache in the render chain, and
381
456
  // the bundle read below. Undefined in `astro dev` (Node) — a no-op there.
382
457
  const cache =
383
- typeof caches !== "undefined" && "default" in caches
458
+ !seen.privateCatalog && typeof caches !== "undefined" && "default" in caches
384
459
  ? (caches as unknown as { default: Cache }).default
385
460
  : undefined;
386
- const kv = await readKv("TENANT_CACHE");
387
461
  const publicationBucket = publication.action === "render"
388
462
  ? await readR2("TENANT_ASSETS") as unknown as PublicationArtifactBucketV1 | undefined
389
463
  : undefined;
@@ -433,7 +507,7 @@ async function serveRequest(
433
507
  const bundled = await timing.time("bundle", () => tryServeStaticBundle({
434
508
  request,
435
509
  url,
436
- tenant,
510
+ tenant: deliveryTenant,
437
511
  basePath,
438
512
  cache,
439
513
  kv,
@@ -146,6 +146,7 @@ import { timed } from "@/lib/observability/shared/serverTiming";
146
146
  import { middlewareRewriteTargetV1 } from "./routeBranch.js";
147
147
  import { declaredTenantOrigins } from "@/lib/access/shared/tenantOrigins";
148
148
  import { DeclaredTenantConfigUnreadError, withDeclaredTenantConfig } from "@/config/declaredTenantConfig";
149
+ import { closedCatalogPath, shopperDeliveryPolicy } from "@tot/public-runtime/declared-tenant-config";
149
150
  import {
150
151
  applyInternalContentResponsePolicy,
151
152
  internalContentGrantMatchesPlan,
@@ -335,6 +336,32 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
335
336
  if (isInternalPublication) applyInternalContentResponsePolicy(response.headers);
336
337
  return response;
337
338
  }
339
+ // The tenant as it renders in THIS environment: its record with the declared
340
+ // `.tot/config.json` fields applied (compliance, siteType, capabilities,
341
+ // features). Everything below — static bundle, notices, gates, features,
342
+ // capabilities — reads this, never the bare record. A candidate-pinned render
343
+ // takes the candidate version's declaration, so a reviewer sees the notices the
344
+ // change under review declares. A declaration that cannot be read refuses the
345
+ // render: the store's compliance is unknown, and its gates and notices with it.
346
+ let tenant: TenantConfig;
347
+ try {
348
+ tenant = await timed(timing, "config", () => withDeclaredTenantConfig(
349
+ tenantRecord,
350
+ kv ? (key: string) => kv.get(key) : async () => null,
351
+ { env: customization.env, ...(candidatePin ? { pinnedVersionId: candidatePin.versionId } : {}) },
352
+ ));
353
+ } catch (err) {
354
+ if (!(err instanceof DeclaredTenantConfigUnreadError)) throw err;
355
+ console.error(err.message);
356
+ const response = new Response("Service Unavailable", {
357
+ status: 503,
358
+ headers: { "Cache-Control": "private, no-store", "Retry-After": "30" },
359
+ });
360
+ applySecurityHeaders(response.headers);
361
+ if (isInternalPublication) applyInternalContentResponsePolicy(response.headers);
362
+ return response;
363
+ }
364
+ const shopperDelivery = shopperDeliveryPolicy(tenant);
338
365
  // The owning space's content-declared redirects: a same-origin target keeps the path-routing
339
366
  // prefix and goes through the shared return-path sanitizer, so no request query (a preview
340
367
  // capability, a pin token) reaches the Location; an off-site target (the root space only) is sent
@@ -344,6 +371,16 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
344
371
  // nothing renders there (the static planes drop such an entry when the release is composed).
345
372
  const declaredRedirect = (location: string): Response => {
346
373
  const prefix = candidatePin ? candidatePin.basePath : basePath;
374
+ if (shopperDelivery?.mode === "closed_store" && location.startsWith("/")) {
375
+ const target = closedCatalogPath(location);
376
+ const headers = new Headers({ "cache-control": "private, no-store", "x-robots-tag": "noindex, nofollow" });
377
+ applySecurityHeaders(headers);
378
+ if (target === "deny") return new Response(null, { status: 404, headers });
379
+ if (target === "admit" && closedCatalogPath(renderPath) === "allow") {
380
+ headers.set("location", `${prefix}/account/sign-in?next=${encodeURIComponent(prefix + location)}`);
381
+ return new Response(null, { status: 303, headers });
382
+ }
383
+ }
347
384
  const response = new Response(null, {
348
385
  status: 308,
349
386
  headers: {
@@ -361,31 +398,6 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
361
398
  redirectUnlessRendered = match?.location ?? null;
362
399
  }
363
400
 
364
- // The tenant as it renders in THIS environment: its record with the declared
365
- // `.tot/config.json` fields applied (compliance, siteType, capabilities,
366
- // features). Everything below — static bundle, notices, gates, features,
367
- // capabilities — reads this, never the bare record. A candidate-pinned render
368
- // takes the candidate version's declaration, so a reviewer sees the notices the
369
- // change under review declares. A declaration that cannot be read refuses the
370
- // render: the store's compliance is unknown, and its gates and notices with it.
371
- let tenant: TenantConfig;
372
- try {
373
- tenant = await timed(timing, "config", () => withDeclaredTenantConfig(
374
- tenantRecord,
375
- kv ? (key: string) => kv.get(key) : async () => null,
376
- { env: customization.env, ...(candidatePin ? { pinnedVersionId: candidatePin.versionId } : {}) },
377
- ));
378
- } catch (err) {
379
- if (!(err instanceof DeclaredTenantConfigUnreadError)) throw err;
380
- console.error(err.message);
381
- const response = new Response("Service Unavailable", {
382
- status: 503,
383
- headers: { "Cache-Control": "private, no-store", "Retry-After": "30" },
384
- });
385
- applySecurityHeaders(response.headers);
386
- if (isInternalPublication) applyInternalContentResponsePolicy(response.headers);
387
- return response;
388
- }
389
401
  // Request-scoped read memo: every content read resolves the same pointer and
390
402
  // version manifest, and a catalog render reads one artifact per catalog file.
391
403
  const kvReads = new Map<string, Promise<string | null>>();
@@ -624,7 +636,9 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
624
636
  url.pathname,
625
637
  url.search,
626
638
  version,
627
- locals.integrationCsp?.planRevision,
639
+ shopperDelivery
640
+ ? `${locals.integrationCsp?.planRevision ?? ""}:shopper:${shopperDelivery.mode}:${shopperDelivery.pricesHidden}`
641
+ : locals.integrationCsp?.planRevision,
628
642
  publicationSource.status === "selected" ? publicationSource.cacheScope : undefined,
629
643
  );
630
644
  const key = pageKey;
@@ -1067,6 +1081,9 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
1067
1081
  // absolute), and the publish scan classifies such references by path instead of as
1068
1082
  // third-party hotlinks.
1069
1083
  response.headers.set(TENANT_ORIGINS_CAPTURE_HEADER, declaredTenantOrigins(tenant).join(","));
1084
+ if (await readEnv(MATERIALIZE_MODE_BINDING) === "1") {
1085
+ response.headers.set("x-tot-shopper-delivery", JSON.stringify(shopperDelivery));
1086
+ }
1070
1087
  }
1071
1088
  if (isInternalPublication) applyInternalContentResponsePolicy(response.headers);
1072
1089
  // Stamp a fresh per-response nonce into this cold response's body + CSP header
@@ -83,6 +83,7 @@ export const PLATFORM_PUBLIC_DISCOVERY_PATHS = [
83
83
  * Dynamic Astro pages, not bytes, so `public-render` — never passthrough.
84
84
  */
85
85
  export const PLATFORM_PUBLIC_APP_ROUTE_PREFIXES = [
86
+ "/catalog-index.json",
86
87
  "/collections",
87
88
  "/products",
88
89
  "/saved",
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import { readR2 } from "@/lib/publication/shared/runtimeEnv";
11
11
  import { getCachedPage, putCachedPage, staticBundleCacheKey } from "@/lib/publication/shared/edgeCache";
12
+ import { closedCatalogPath, shopperDeliveryPolicy } from "@tot/public-runtime/declared-tenant-config";
12
13
  import {
13
14
  resolveChannelDigest,
14
15
  serveStaticBundle,
@@ -63,26 +64,47 @@ export async function tryServeStaticBundle(
63
64
  const assetPath = input.basePath && url.pathname.startsWith(`${input.basePath}/_a/`)
64
65
  ? url.pathname.slice(input.basePath.length) : url.pathname;
65
66
 
67
+ const shopperDelivery = shopperDeliveryPolicy(tenant);
68
+ const privateAsset = shopperDelivery?.mode === "closed_store" &&
69
+ assetPath.startsWith("/_a/") && closedCatalogPath(assetPath) === "admit";
70
+ if (privateAsset && input.capturedOriginal?.revisionId &&
71
+ (input.isPreviewHost || input.hasPreviewToken || input.hasCandidatePin || input.basePath !== "")) {
72
+ const { tryServeCapturedOriginal } = await import("@/lib/assets/captured-original-serve");
73
+ return tryServeCapturedOriginal({
74
+ bucket: input.capturedOriginal.bucket, tenantId: tenant.tenant_id, revisionId: input.capturedOriginal.revisionId,
75
+ pathname: assetPath, method,
76
+ });
77
+ }
78
+
66
79
  // Version-independent assets (`/_a/<sha256>`, `/_astro/<name>`) are exact addresses: the same
67
80
  // bytes for every viewer, preview or not, whatever the live pointer says. A page from an
68
81
  // older version — or a preview of one — keeps resolving its own sub-resources.
69
- if ((method === "GET" || method === "HEAD") && versionIndependentAssetKey(assetPath)) {
82
+ if (!privateAsset && (method === "GET" || method === "HEAD") && versionIndependentAssetKey(assetPath)) {
83
+ const pinnedKey = cache && method === "GET"
84
+ ? staticBundleCacheKey(tenant.tenant_id, "pinned", assetPath, "")
85
+ : null;
86
+ if (pinnedKey && cache) {
87
+ const hit = await getCachedPage(cache, pinnedKey);
88
+ if (hit) return hit;
89
+ }
90
+ const cacheImmutableAsset = async (response: Response) => {
91
+ if (!pinnedKey || !cache || response.status !== 200) return;
92
+ if (!(response.headers.get("cache-control") ?? "").includes("immutable")) return;
93
+ if (response.headers.has("set-cookie")) return;
94
+ const cloned = response.clone();
95
+ const toStore = new Response(cloned.body, cloned);
96
+ toStore.headers.set("X-ToT-Cache", "stored");
97
+ await cache.put(pinnedKey, toStore).catch(() => void 0);
98
+ };
70
99
  const bucket = await readR2("STATIC_BUNDLES");
71
100
  if (bucket) {
72
- const pinnedKey = cache && method === "GET"
73
- ? staticBundleCacheKey(tenant.tenant_id, "pinned", assetPath, "")
74
- : null;
75
- if (pinnedKey && cache) {
76
- const hit = await getCachedPage(cache, pinnedKey);
77
- if (hit) return hit;
78
- }
79
101
  const pinned = await serveVersionIndependentAsset(
80
102
  bucket as unknown as StaticBundleR2BucketLike,
81
103
  assetPath,
82
104
  method,
83
105
  );
84
106
  if (pinned && pinned.ok) {
85
- if (pinnedKey && cache) await putCachedPage(cache, pinnedKey, pinned);
107
+ await cacheImmutableAsset(pinned);
86
108
  return pinned;
87
109
  }
88
110
  // `/_a/` miss: try revision-bound captured originals before the pinned 404.
@@ -96,7 +118,10 @@ export async function tryServeStaticBundle(
96
118
  method,
97
119
  ...(kv ? { durable: { kv, provider: tenant.serving?.provider } } : {}),
98
120
  });
99
- if (captured) return captured;
121
+ if (captured) {
122
+ await cacheImmutableAsset(captured);
123
+ return captured;
124
+ }
100
125
  }
101
126
  if (pinned) return pinned;
102
127
  } else if (input.capturedOriginal && assetPath.startsWith("/_a/")) {
@@ -109,7 +134,10 @@ export async function tryServeStaticBundle(
109
134
  method,
110
135
  ...(kv ? { durable: { kv, provider: tenant.serving?.provider } } : {}),
111
136
  });
112
- if (captured) return captured;
137
+ if (captured) {
138
+ await cacheImmutableAsset(captured);
139
+ return captured;
140
+ }
113
141
  }
114
142
  }
115
143
 
@@ -123,7 +151,7 @@ export async function tryServeStaticBundle(
123
151
  !input.hasCandidatePin &&
124
152
  !input.hasDraftCookie &&
125
153
  !input.hasManagedInstalls &&
126
- !url.pathname.startsWith("/api/");
154
+ !/^\/(?:api|account)(?:\/|$)/i.test(url.pathname);
127
155
  if (!eligible) return null;
128
156
 
129
157
  const bundleBucket = await readR2("STATIC_BUNDLES");
@@ -147,8 +175,9 @@ export async function tryServeStaticBundle(
147
175
  return null;
148
176
  }
149
177
 
178
+ const cacheDigest = shopperDelivery ? `${digest}-shopper-${shopperDelivery.mode}-${shopperDelivery.pricesHidden}` : digest;
150
179
  const bundleCacheKey = cache && method === "GET"
151
- ? staticBundleCacheKey(tenant.tenant_id, digest, url.pathname, url.search)
180
+ ? staticBundleCacheKey(tenant.tenant_id, cacheDigest, url.pathname, url.search)
152
181
  : null;
153
182
  if (bundleCacheKey && cache) {
154
183
  const hit = await getCachedPage(cache, bundleCacheKey);
@@ -158,6 +187,7 @@ export async function tryServeStaticBundle(
158
187
  {
159
188
  bucket: bundleBucket as unknown as StaticBundleR2BucketLike,
160
189
  digest,
190
+ expectedShopperDelivery: shopperDelivery,
161
191
  onFailClosed: (detail) => {
162
192
  console.error(
163
193
  `[static-bundle] fail-closed for ${tenant.tenant_id} ${url.pathname}: ${detail}`,
@@ -16,6 +16,9 @@
16
16
  * planes, not just the SSR Worker.
17
17
  */
18
18
  import type { APIContext } from "astro";
19
+ import { MATERIALIZE_MODE_BINDING } from "@tot/public-runtime";
20
+ import { resolveShopperAccessPolicy } from "@tot/public-runtime/declared-tenant-config";
21
+ import { readEnv, readKv } from "@/lib/publication/shared/runtimeEnv";
19
22
  import {
20
23
  chunkSitemapGroupsV1,
21
24
  parseSitemapChildPathV1,
@@ -34,7 +37,6 @@ import { getTheBuildSettings, listBuildPosts } from "@/lib/content/the-build/pro
34
37
  import { resolveTheBuildIndexCopy } from "@/lib/content/the-build/pagination.js";
35
38
  import { isIndexableHtml, rawPageCanonicalUrl } from "@/lib/content/shared/rawMarketingHtml.js";
36
39
  import { compileRouteTierIndexV1 } from "@tot/public-runtime";
37
- import { readKv } from "@/lib/publication/shared/runtimeEnv.js";
38
40
  import {
39
41
  declaresMountedSpacesV1,
40
42
  mountedDiscoveryUrlV1,
@@ -52,7 +54,7 @@ const XML_HEADERS = {
52
54
  } as const;
53
55
 
54
56
  /** Every indexable URL the tenant serves, sorted into the sitemap groups. */
55
- async function collectSitemapGroups(locals: APIContext["locals"]): Promise<SitemapGroups> {
57
+ async function collectSitemapGroups(locals: APIContext["locals"], includeClosedCatalog: boolean): Promise<SitemapGroups> {
56
58
  const { tot, tenant, canonicalBase, content, features, publicationTimestamp } = locals;
57
59
  const base = canonicalBase.replace(/\/$/, "");
58
60
  const blogSettings = await getBlogSettings(tenant.tenant_id, content);
@@ -64,7 +66,7 @@ async function collectSitemapGroups(locals: APIContext["locals"]): Promise<Sitem
64
66
 
65
67
  // Commerce URLs only for tenants with a catalog sitemap. Marketing tenants
66
68
  // emit homepage + content pages, keeping product/collection routes out.
67
- if (features.commerceSitemap) {
69
+ if (features.commerceSitemap && (includeClosedCatalog || resolveShopperAccessPolicy(tenant).mode !== "closed_store")) {
68
70
  const [products, allCollections] = await Promise.all([
69
71
  tot.getAllActiveProducts(),
70
72
  tot.listCollections(),
@@ -158,14 +160,14 @@ async function collectSitemapGroups(locals: APIContext["locals"]): Promise<Sitem
158
160
  }
159
161
 
160
162
  /** The tenant's child sitemaps, in index order; empty groups have none. */
161
- export async function tenantSitemapChildren(locals: APIContext["locals"]): Promise<SitemapChildV1[]> {
162
- const groups = await collectSitemapGroups(locals);
163
+ export async function tenantSitemapChildren(locals: APIContext["locals"], includeClosedCatalog = false): Promise<SitemapChildV1[]> {
164
+ const groups = await collectSitemapGroups(locals, includeClosedCatalog);
163
165
  return chunkSitemapGroupsV1((Object.keys(groups) as SitemapGroupV1[]).map((group) => ({ group, urls: groups[group] })));
164
166
  }
165
167
 
166
168
  /** `/sitemap.xml`: the index of every child sitemap. */
167
169
  export async function sitemapIndexResponse(context: APIContext): Promise<Response> {
168
- const children = await tenantSitemapChildren(context.locals);
170
+ const children = await tenantSitemapChildren(context.locals, await isCatalogMaterializeProbe(context));
169
171
  return new Response(renderSitemapIndexV1(context.locals.canonicalBase, children), { headers: XML_HEADERS });
170
172
  }
171
173
 
@@ -182,8 +184,13 @@ export function sitemapChildPathOf(context: APIContext): string {
182
184
  export async function sitemapChildResponse(context: APIContext): Promise<Response> {
183
185
  const named = parseSitemapChildPathV1(sitemapChildPathOf(context));
184
186
  if (!named) return new Response("Not found", { status: 404, headers: { "content-type": "text/plain; charset=utf-8" } });
185
- const children = await tenantSitemapChildren(context.locals);
187
+ const children = await tenantSitemapChildren(context.locals, await isCatalogMaterializeProbe(context));
186
188
  const child = children.find((c) => c.group === named.group && c.page === named.page);
187
189
  if (!child) return new Response("Not found", { status: 404, headers: { "content-type": "text/plain; charset=utf-8" } });
188
190
  return new Response(renderSitemapUrlsetV1(child.urls), { headers: XML_HEADERS });
189
191
  }
192
+
193
+ async function isCatalogMaterializeProbe(context: APIContext): Promise<boolean> {
194
+ return context.url.searchParams.get("__tot_catalog_bake") === "1" &&
195
+ await readEnv(MATERIALIZE_MODE_BINDING) === "1";
196
+ }
@@ -4,6 +4,7 @@ import { cartProposalConfirm } from "@/lib/checkout/proposal/proposalRoutes";
4
4
  import { pageUrlForm } from "@/lib/content/seo/urlForm";
5
5
  import { carrierPolicyForTenant } from "@/lib/fulfillment/readiness";
6
6
  import { withBase } from "@/lib/publication/shared/basePath";
7
+ import { withShopperPurchase } from "@/lib/customers/accounts/purchaseAccess";
7
8
 
8
9
  export const prerender = false;
9
10
 
@@ -14,4 +15,4 @@ const adultSignatureRequired = (context: APIContext): boolean =>
14
15
  carrierPolicyForTenant(context.locals.tenant).adultSignatureRequired;
15
16
 
16
17
  export const POST = (context: APIContext): Promise<Response> =>
17
- cartProposalConfirm(context, { productPagePath, adultSignatureRequired });
18
+ withShopperPurchase(context, () => cartProposalConfirm(context, { productPagePath, adultSignatureRequired }));
@@ -4,6 +4,7 @@ import type { CartProposalLine } from "@tot/public-runtime";
4
4
  import { cartProposalOpen, cartProposalReview, type ProposalCompliance } from "@/lib/checkout/proposal/proposalRoutes";
5
5
  import { sharedStorePolicy } from "@/lib/checkout/commerce/sharedStoreAdmission";
6
6
  import { evaluatePreflight } from "../compliance/preflight.js";
7
+ import { withShopperPurchase } from "@/lib/customers/accounts/purchaseAccess";
7
8
 
8
9
  export const prerender = false;
9
10
 
@@ -22,5 +23,7 @@ export async function proposalPreflight(context: APIContext, lines: readonly Car
22
23
  };
23
24
  }
24
25
 
25
- export const GET = (context: APIContext): Promise<Response> => cartProposalOpen(context, { preflight: proposalPreflight });
26
- export const POST = (context: APIContext): Promise<Response> => cartProposalReview(context, { preflight: proposalPreflight });
26
+ export const GET = (context: APIContext): Promise<Response> =>
27
+ withShopperPurchase(context, () => cartProposalOpen(context, { preflight: proposalPreflight }));
28
+ export const POST = (context: APIContext): Promise<Response> =>
29
+ withShopperPurchase(context, () => cartProposalReview(context, { preflight: proposalPreflight }));
@@ -2,6 +2,7 @@
2
2
  import type { APIRoute } from "astro";
3
3
  import { commerceTenantId } from "@tot/public-runtime";
4
4
  import { bindCartSession } from "@/lib/checkout/commerce/cartSession";
5
+ import { shopperPurchaseAccess } from "@/lib/customers/accounts/purchaseAccess";
5
6
 
6
7
  export const prerender = false;
7
8
 
@@ -16,6 +17,8 @@ function json(body: unknown, status: number): Response {
16
17
  }
17
18
 
18
19
  export const GET: APIRoute = async (context) => {
20
+ const access = await shopperPurchaseAccess(context);
21
+ if (!access.ok) return access.response;
19
22
  const { commerce, tenant } = context.locals;
20
23
  if (!commerce) return json({ error: "no-store" }, 409);
21
24
  const tenantId = tenant ? commerceTenantId(tenant) : "";
@@ -2,6 +2,7 @@
2
2
  import type { APIContext } from "astro";
3
3
  import { getCheckoutSession } from "@/lib/checkout/agent/checkoutSession";
4
4
  import { proposalPreflight } from "../../cart-proposal/review.js";
5
+ import { withShopperPurchase } from "@/lib/customers/accounts/purchaseAccess";
5
6
 
6
7
  export const prerender = false;
7
8
 
@@ -17,4 +18,4 @@ function resolveCheckoutSessionId(context: APIContext): string {
17
18
  }
18
19
 
19
20
  export const GET = (context: APIContext): Promise<Response> =>
20
- getCheckoutSession(context, resolveCheckoutSessionId(context), { preflight: proposalPreflight });
21
+ withShopperPurchase(context, () => getCheckoutSession(context, resolveCheckoutSessionId(context), { preflight: proposalPreflight }));
@@ -2,7 +2,9 @@
2
2
  import type { APIContext } from "astro";
3
3
  import { createCheckoutSession } from "@/lib/checkout/agent/checkoutSession";
4
4
  import { proposalPreflight } from "../cart-proposal/review.js";
5
+ import { withShopperPurchase } from "@/lib/customers/accounts/purchaseAccess";
5
6
 
6
7
  export const prerender = false;
7
8
 
8
- export const POST = (context: APIContext): Promise<Response> => createCheckoutSession(context, { preflight: proposalPreflight });
9
+ export const POST = (context: APIContext): Promise<Response> =>
10
+ withShopperPurchase(context, () => createCheckoutSession(context, { preflight: proposalPreflight }));