@tokenoftrust/storefront-runner 7.7.4 → 7.8.1

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 (64) 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/catalog/search/index.ts +3 -4
  14. package/apps/storefront/src/lib/catalog/shared/catalogIndex.ts +12 -7
  15. package/apps/storefront/src/lib/catalog/shared/catalogQueryView.ts +4 -2
  16. package/apps/storefront/src/lib/catalog/tot/query.ts +2 -1
  17. package/apps/storefront/src/lib/checkout/commerce/cartSession.ts +10 -11
  18. package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +81 -14
  19. package/apps/storefront/src/lib/compliance/browser/checkoutVerificationFlow.ts +35 -0
  20. package/apps/storefront/src/lib/content/seo/structuredData.ts +3 -2
  21. package/apps/storefront/src/lib/content/shared/jsonld.ts +3 -2
  22. package/apps/storefront/src/lib/customers/accounts/catalogAdmission.ts +75 -0
  23. package/apps/storefront/src/lib/customers/accounts/checkoutProof.ts +133 -0
  24. package/apps/storefront/src/lib/customers/accounts/orgKyb.ts +12 -0
  25. package/apps/storefront/src/lib/customers/accounts/pricing.ts +25 -0
  26. package/apps/storefront/src/lib/customers/accounts/purchaseAccess.ts +45 -0
  27. package/apps/storefront/src/lib/customers/accounts/scope.ts +60 -0
  28. package/apps/storefront/src/lib/customers/accounts/session.ts +173 -0
  29. package/apps/storefront/src/lib/customers/accounts/shopperPricingClient.ts +69 -0
  30. package/apps/storefront/src/lib/engagement/contact/submitToken.ts +2 -1
  31. package/apps/storefront/src/lib/inventory/allocations.ts +8 -5
  32. package/apps/storefront/src/lib/membership/eligibility.ts +2 -23
  33. package/apps/storefront/src/lib/publication/shared/cdnForward.ts +10 -3
  34. package/apps/storefront/src/lib/publication/shared/staticQuery.ts +10 -3
  35. package/apps/storefront/src/middleware/index.ts +80 -6
  36. package/apps/storefront/src/middleware/renderChain.ts +43 -26
  37. package/apps/storefront/src/middleware/routeBranch.ts +1 -0
  38. package/apps/storefront/src/middleware/staticBundle.ts +18 -3
  39. package/apps/storefront/src/pages/_sitemap.ts +14 -7
  40. package/apps/storefront/src/pages/api/cart-proposal/confirm.ts +2 -1
  41. package/apps/storefront/src/pages/api/cart-proposal/review.ts +5 -2
  42. package/apps/storefront/src/pages/api/commerce/cart-session.ts +3 -0
  43. package/apps/storefront/src/pages/api/commerce/checkout-sessions/[id].ts +2 -1
  44. package/apps/storefront/src/pages/api/commerce/checkout-sessions.ts +3 -1
  45. package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +43 -10
  46. package/apps/storefront/src/pages/api/compliance/preflight.ts +34 -5
  47. package/apps/storefront/src/pages/cart.ts +3 -0
  48. package/apps/storefront/src/pages/catalog-index.json.ts +3 -2
  49. package/apps/storefront/src/pages/collections/[handle]/page/[n].astro +2 -1
  50. package/apps/storefront/src/pages/collections/[handle].astro +2 -1
  51. package/apps/storefront/src/pages/collections/_CollectionView.astro +8 -4
  52. package/apps/storefront/src/pages/index.astro +5 -3
  53. package/apps/storefront/src/pages/llms.txt.ts +2 -1
  54. package/apps/storefront/src/pages/products/[handle].astro +52 -8
  55. package/apps/storefront/src/pages/saved.astro +2 -1
  56. package/package.json +1 -1
  57. package/packages/cli/src/declared-config.mjs +46 -1
  58. package/packages/public-runtime/src/checkout-orders.ts +9 -1
  59. package/packages/public-runtime/src/checkout.ts +1 -1
  60. package/packages/public-runtime/src/declared-tenant-config.d.mts +11 -1
  61. package/packages/public-runtime/src/declared-tenant-config.mjs +111 -1
  62. package/packages/public-runtime/src/publication-space.ts +1 -0
  63. package/packages/public-runtime/src/static-bundle.ts +28 -3
  64. package/packages/public-runtime/src/tenant.ts +15 -0
@@ -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,10 +64,22 @@ 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)) {
70
83
  const pinnedKey = cache && method === "GET"
71
84
  ? staticBundleCacheKey(tenant.tenant_id, "pinned", assetPath, "")
72
85
  : null;
@@ -138,7 +151,7 @@ export async function tryServeStaticBundle(
138
151
  !input.hasCandidatePin &&
139
152
  !input.hasDraftCookie &&
140
153
  !input.hasManagedInstalls &&
141
- !url.pathname.startsWith("/api/");
154
+ !/^\/(?:api|account)(?:\/|$)/i.test(url.pathname);
142
155
  if (!eligible) return null;
143
156
 
144
157
  const bundleBucket = await readR2("STATIC_BUNDLES");
@@ -162,8 +175,9 @@ export async function tryServeStaticBundle(
162
175
  return null;
163
176
  }
164
177
 
178
+ const cacheDigest = shopperDelivery ? `${digest}-shopper-${shopperDelivery.mode}-${shopperDelivery.pricesHidden}` : digest;
165
179
  const bundleCacheKey = cache && method === "GET"
166
- ? staticBundleCacheKey(tenant.tenant_id, digest, url.pathname, url.search)
180
+ ? staticBundleCacheKey(tenant.tenant_id, cacheDigest, url.pathname, url.search)
167
181
  : null;
168
182
  if (bundleCacheKey && cache) {
169
183
  const hit = await getCachedPage(cache, bundleCacheKey);
@@ -173,6 +187,7 @@ export async function tryServeStaticBundle(
173
187
  {
174
188
  bucket: bundleBucket as unknown as StaticBundleR2BucketLike,
175
189
  digest,
190
+ expectedShopperDelivery: shopperDelivery,
176
191
  onFailClosed: (detail) => {
177
192
  console.error(
178
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 }));
@@ -28,6 +28,11 @@ import { resolveStoreCurrency } from "@tot/public-runtime/declared-tenant-config
28
28
  import { createContentProvider } from "@/lib/content/storyblok/provider";
29
29
  import { createToTClient } from "@/lib/catalog/tot/ToTClient";
30
30
  import { refusalSentence } from "@/lib/commerce/refusalSentence";
31
+ import { requiresShopperPurchase } from "@/lib/customers/accounts/purchaseAccess";
32
+ import { bindCheckoutSnapshot, readShopperCheckoutWire, shopperCheckoutAuthorizationGuard, shopperCheckoutContextDigest, shopperVerificationRefMatches, verifyCheckoutProof, type ShopperCheckoutWire } from "@/lib/customers/accounts/checkoutProof";
33
+ import { shopperOrgKyb } from "@/lib/customers/accounts/orgKyb";
34
+ import { shopperVariantPrice } from "@/lib/customers/accounts/pricing";
35
+ import { resolveShopperAccessPolicy } from "@tot/public-runtime/declared-tenant-config";
31
36
  export const prerender = false;
32
37
  const HEX = /^[a-f0-9]{64}$/;
33
38
  /** The shopper's verification correlation handle, as the signed `verification` cart option carries it. */
@@ -77,7 +82,7 @@ async function digest(value: string): Promise<string> {
77
82
  * from a closed vocabulary; no other key. Optional: a snapshot without it is read as before.
78
83
  */
79
84
  export { EXCISE_REASONS, type ExciseCarrier, exciseLinesDigest, exciseReconcilesWithTotals, exciseRequiredForTenant, resolveTaxEvidence, checkoutStoreHasExciseProducer };
80
- type FinalCartWire = CommerceProviderCartSnapshot & { excise?: ExciseCarrier };
85
+ type FinalCartWire = CommerceProviderCartSnapshot & { excise?: ExciseCarrier; shopperCheckout?: ShopperCheckoutWire };
81
86
  export function readExcise(value: unknown): ExciseCarrier | null {
82
87
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
83
88
  const e = value as Record<string, unknown>;
@@ -93,10 +98,12 @@ function readSnapshot(value: unknown): FinalCartWire | null {
93
98
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
94
99
  const v = value as Record<string, unknown>;
95
100
  const allowed = ["provider", "providerCartId", "providerCartDigest", "tenantId", "stage", "currency", "lines", "totals", "destinationDigest", "destination"];
96
- const optional = ["expectedAuthorizationId", "verificationRef", "contentVersionId", "excise"];
101
+ const optional = ["expectedAuthorizationId", "verificationRef", "contentVersionId", "excise", "shopperCheckout", "checkoutContextDigest"];
97
102
  if (Object.keys(v).some(k => !allowed.includes(k) && !optional.includes(k)) || allowed.some(k => !(k in v))) return null;
98
103
  if ("excise" in v && !readExcise(v.excise)) return null;
99
104
  if ("contentVersionId" in v && (typeof v.contentVersionId !== "string" || !isContentVersionId(v.contentVersionId))) return null;
105
+ if (("shopperCheckout" in v) !== ("checkoutContextDigest" in v)) return null;
106
+ if ("shopperCheckout" in v && (!readShopperCheckoutWire(v.shopperCheckout) || typeof v.checkoutContextDigest !== "string" || !HEX.test(v.checkoutContextDigest))) return null;
100
107
  if ("expectedAuthorizationId" in v && (typeof v.expectedAuthorizationId !== "string" || !/^[a-z0-9][a-z0-9-]{0,80}$/.test(v.expectedAuthorizationId))) return null;
101
108
  if ("verificationRef" in v && (typeof v.verificationRef !== "string" || !VERIFICATION_REF.test(v.verificationRef))) return null;
102
109
  if (v.provider !== "foxycart" || typeof v.providerCartId !== "string" || !/^[a-zA-Z0-9._:-]{1,128}$/.test(v.providerCartId) ||
@@ -251,7 +258,8 @@ async function authorize(context: APIContext): Promise<Response> {
251
258
  let wire: FinalCartWire | null;
252
259
  try { wire = readSnapshot(JSON.parse(raw)); } catch { wire = null; }
253
260
  if (!wire || !await exciseBindsSnapshot(wire)) return deny("malformed-request");
254
- const snapshot = keyedLines(wire);
261
+ const { shopperCheckout, ...safeWire } = wire;
262
+ const snapshot = keyedLines(safeWire);
255
263
  const jwks = publicJwks(await readEnv("COMMERCE_CALLER_JWKS"));
256
264
  const issuers = list(await readEnv("COMMERCE_CALLER_ISSUERS"));
257
265
  const audience = await readEnv("COMMERCE_CALLER_AUDIENCE");
@@ -286,6 +294,18 @@ async function authorize(context: APIContext): Promise<Response> {
286
294
  if (err instanceof DeclaredTenantConfigUnreadError) return deny("config-unreadable", 503);
287
295
  throw err;
288
296
  }
297
+ const shopperRequired = requiresShopperPurchase(tenant);
298
+ if (shopperRequired && !shopperCheckout) return deny("shopper-checkout-proof-required");
299
+ if (shopperCheckout && await shopperCheckoutContextDigest(shopperCheckout) !== snapshot.checkoutContextDigest) return deny("shopper-checkout-context-mismatch");
300
+ const database = await readD1("STOREFRONT_APPS_DB");
301
+ if (!database) return deny("store-unconfigured", 503);
302
+ const queryable = fromD1(database);
303
+ const scopedProof = shopperCheckout ? await verifyCheckoutProof(queryable, snapshot, shopperCheckout) : null;
304
+ if (shopperCheckout && !scopedProof) return deny("shopper-checkout-proof-invalid");
305
+ if (scopedProof && snapshot.verificationRef && !await shopperVerificationRefMatches(scopedProof.shopper, snapshot.verificationRef)) {
306
+ return deny("shopper-verification-ref-invalid");
307
+ }
308
+ if (scopedProof?.shopper.checkoutLockMode === "require_step_up") return deny("shopper-step-up-required");
289
309
  const content = contentVersionId
290
310
  ? createContentProvider(tenant, undefined, { get: kvGet, versionId: contentVersionId })
291
311
  : createContentProvider(tenant, { get: kvGet, env: contentEnv });
@@ -321,7 +341,9 @@ async function authorize(context: APIContext): Promise<Response> {
321
341
  if (variants.length !== 1 || variants[0]!.id !== match.variant.id) return mismatch("variant-detail", index);
322
342
  const variant = variants[0]!;
323
343
  const digits = new Intl.NumberFormat("en", { style: "currency", currency: snapshot.currency }).resolvedOptions().maximumFractionDigits ?? 2;
324
- const scaled = variant.price * 10 ** digits;
344
+ const shopperPrice = scopedProof ? shopperVariantPrice(tenant, detail, variant, scopedProof.shopper.tierId) : null;
345
+ if (scopedProof && !shopperPrice) return mismatch("shopper-tier", index);
346
+ const scaled = (shopperPrice?.price ?? variant.price) * 10 ** digits;
325
347
  if (!variant.inventory.available) return mismatch("unavailable", index);
326
348
  if (variant.currency !== snapshot.currency) return mismatch("variant-currency", index);
327
349
  if (Math.abs(scaled - Math.round(scaled)) > 0.000001) return mismatch("price-precision", index);
@@ -337,11 +359,8 @@ async function authorize(context: APIContext): Promise<Response> {
337
359
  try { owed = shippingMinorFor(tenant.shipping, snapshot.currency, snapshot.totals.subtotalMinor); } catch { return deny("shipping-unavailable"); }
338
360
  if (snapshot.totals.shippingMinor !== owed) return deny("shipping-changed");
339
361
  }
340
- const database = await readD1("STOREFRONT_APPS_DB");
341
- if (!database) return deny("store-unconfigured", 503);
342
362
  if (tenant.inventory?.provider && tenant.inventory.provider !== "mirror") return deny("authority-unavailable");
343
363
  const now = new Date().toISOString();
344
- const queryable = fromD1(database);
345
364
  for (const line of snapshot.lines) {
346
365
  const reading = await readMirrorBalance(queryable, {
347
366
  tenantId: snapshot.tenantId, stage: snapshot.stage, sku: line.sku, locationId: "unspecified",
@@ -374,7 +393,13 @@ async function authorize(context: APIContext): Promise<Response> {
374
393
  }
375
394
  const stockExpiry = Math.min(...authorities.flatMap(authority => authority ? [Date.parse(authority.asOf) + 15 * 60_000] : []));
376
395
  const evidence: CommerceEvidence = { verification: "absent", tax: "absent", risk: "absent", stock: stockTracked ? "fresh" : "not-required" };
377
- const expiresAt = existing?.expiresAt ?? new Date(Math.min(Date.now() + 5 * 60_000, stockExpiry)).toISOString();
396
+ const orgKybRequired = resolveShopperAccessPolicy(tenant).b2bKybOrgVerification;
397
+ const orgKyb = orgKybRequired && scopedProof ? await shopperOrgKyb(queryable, scopedProof.shopper,
398
+ shopperCheckout?.licensedDestinationDigest, snapshot.totals.totalMinor, new Date(now)) : null;
399
+ if (orgKybRequired && !orgKyb) return deny("shopper-org-kyb-review-required");
400
+ if (existing && orgKyb && Date.parse(existing.expiresAt) > Date.parse(orgKyb.expiresAt)) return deny("admission-expired");
401
+ const expiresAt = existing?.expiresAt ?? new Date(Math.min(Date.now() + 5 * 60_000, stockExpiry,
402
+ scopedProof?.expiresAt ?? Infinity, orgKyb ? Date.parse(orgKyb.expiresAt) : Infinity)).toISOString();
378
403
  const provenance = {} as CommerceEvidenceProvenance;
379
404
  for (const field of ["verification", "tax", "risk"] as const) {
380
405
  if (policy[field] === "not-required") {
@@ -387,7 +412,7 @@ async function authorize(context: APIContext): Promise<Response> {
387
412
  : { requirement: "not-required", state: "not-required", source: "tenant-inventory-undeclared", policyRevision: "untracked-v1", expiresAt };
388
413
  const presented: FinalCartBinding = { tenantId: snapshot.tenantId, stage: snapshot.stage, currency: snapshot.currency, lines: snapshot.lines,
389
414
  destinationDigest: snapshot.destinationDigest, verificationExpiresAt: expiresAt, taxExpiresAt: expiresAt };
390
- const seamView = await seam(authorityContext, snapshot, selected, policy);
415
+ const seamView = await seam(authorityContext, snapshot, selected, orgKyb ? { ...policy, verification: "not-required" } : policy);
391
416
  let taxReason: ExciseEvidenceReason | undefined;
392
417
  if (policy.tax === "required") {
393
418
  const hasProducer = checkoutStoreHasExciseProducer(await resolveTenantCommerce(tenant));
@@ -404,7 +429,10 @@ async function authorize(context: APIContext): Promise<Response> {
404
429
  provenance.tax = taxResolution.provenance;
405
430
  taxReason = taxResolution.reason;
406
431
  }
407
- if (policy.verification === "required" && seamView.verified) {
432
+ if (orgKyb) {
433
+ evidence.verification = "fresh";
434
+ provenance.verification = { requirement: "required", state: "satisfied", source: "org-kyb", policyRevision: "org-kyb-v1", expiresAt };
435
+ } else if (policy.verification === "required" && seamView.verified) {
408
436
  evidence.verification = "fresh";
409
437
  provenance.verification = { requirement: "required", state: "satisfied", source: seamView.sandbox ? SHARED_STORE_SANDBOX_VERIFICATION_SOURCE : SHARED_STORE_VERIFICATION_SOURCE, policyRevision: SHARED_STORE_POLICY_REVISION, expiresAt };
410
438
  }
@@ -422,12 +450,17 @@ async function authorize(context: APIContext): Promise<Response> {
422
450
  return deny(decision.finding, 409, decision.owner, decision.exciseReason);
423
451
  }
424
452
  const authorizationId = existing?.authorizationId ?? `a${crypto.randomUUID()}`;
453
+ if (scopedProof && !await bindCheckoutSnapshot(queryable, scopedProof, snapshot.providerCartId, snapshot.providerCartDigest)) {
454
+ return deny("shopper-checkout-proof-unavailable");
455
+ }
425
456
  // Retries of the same verified provider cart share one reservation, including concurrent callbacks.
426
457
  const cartDigest = existing?.cartDigest ?? await digest(`commerce-provider-cart-v1\n${snapshot.providerCartId}\n${snapshot.providerCartDigest}`);
427
458
  const reserved = await reserveAllocation(d1CommerceRunner(database), { tenantId: decision.tenantId, stage: decision.stage, orderId: authorizationId,
428
459
  cartDigest, expiresAt: decision.expiresAt, now, currency: snapshot.currency, amountMinor: snapshot.totals.totalMinor,
429
460
  issuer: decision.issuer, jti: decision.jti, holds: decision.holds, stockUntracked: !stockTracked,
430
461
  providerCart: { provider: snapshot.provider, id: snapshot.providerCartId, digest: snapshot.providerCartDigest, expectedAuthorizationId: snapshot.expectedAuthorizationId },
462
+ ...(scopedProof ? { authorizationGuard: shopperCheckoutAuthorizationGuard(scopedProof, snapshot.providerCartId,
463
+ snapshot.providerCartDigest, orgKyb?.updatedAt) } : {}),
431
464
  admissionStatement: admissionSnapshotStatement({ ...snapshot, authorizationId, cartDigest, evidence, provenance, expiresAt: decision.expiresAt, now }),
432
465
  });
433
466
  if (!reserved.ok) return deny(reserved.finding);
@@ -14,6 +14,11 @@
14
14
  * never falls through to "clear".
15
15
  */
16
16
  import type { APIContext } from "astro";
17
+ import { shopperPurchaseAccess } from "@/lib/customers/accounts/purchaseAccess";
18
+ import { newShopperVerificationRef, shopperVerificationRefMatches } from "@/lib/customers/accounts/checkoutProof";
19
+ import { hasShopperOrgKyb } from "@/lib/customers/accounts/orgKyb";
20
+ import { shopperDb, type ScopedShopper } from "@/lib/customers/accounts/session";
21
+ import { resolveShopperAccessPolicy } from "@tot/public-runtime/declared-tenant-config";
17
22
  import {
18
23
  deriveProductProfile,
19
24
  evaluateCartCompliance,
@@ -195,6 +200,7 @@ interface LiveVerificationResolution {
195
200
  */
196
201
  async function resolveLiveVerification(
197
202
  body: PreflightBody,
203
+ shopper?: ScopedShopper,
198
204
  ): Promise<LiveVerificationResolution | null> {
199
205
  let client: TotVerificationClient | null;
200
206
  try {
@@ -211,6 +217,7 @@ async function resolveLiveVerification(
211
217
 
212
218
  try {
213
219
  if (ref) {
220
+ if (shopper && !await shopperVerificationRefMatches(shopper, ref)) return null;
214
221
  const read = await client.readVerification({ appTransactionId: ref });
215
222
  if (!read.ok) return null;
216
223
  if (read.status !== "not_started") {
@@ -230,7 +237,8 @@ async function resolveLiveVerification(
230
237
  };
231
238
  }
232
239
 
233
- const appTransactionId = ref ?? crypto.randomUUID();
240
+ const appTransactionId = ref ?? (shopper ? await newShopperVerificationRef(shopper) : crypto.randomUUID());
241
+ if (!appTransactionId) return null;
234
242
  const created = await client.createVerification({
235
243
  appTransactionId,
236
244
  person: {
@@ -273,11 +281,14 @@ function withProviderCleared(ruleset: ComplianceRuleset): ComplianceRuleset {
273
281
  }
274
282
 
275
283
  export async function POST(context: APIContext): Promise<Response> {
284
+ const access = await shopperPurchaseAccess(context);
285
+ if (!access.ok) return access.response;
276
286
  const regulated = isRegulatedTenant(context.locals.tenant);
277
287
 
278
288
  let body: PreflightBody;
279
289
  try {
280
290
  body = (await context.request.json()) as PreflightBody;
291
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("Invalid preflight body");
281
292
  } catch {
282
293
  // A regulated tenant must never proceed on an unreadable request.
283
294
  return regulated
@@ -290,8 +301,22 @@ export async function POST(context: APIContext): Promise<Response> {
290
301
  // product page's checkout gate, at click time, whether the store asks for the pre-cart dialog
291
302
  // at all, so a static page never carries a decision frozen at build time.
292
303
  const policy = await sharedStorePolicy(context.locals.tenant, context.locals.commerce, context.locals.customizationEnv);
293
- const gate = complianceGateRequiredFor(policy) ? "required" : "not-required";
294
- const result = await evaluatePreflight(context, body, policy ? { verification: policy.verification, rules: policy.rules } : {});
304
+ const shopper = access.shopper ?? undefined;
305
+ const orgKyb = shopper && resolveShopperAccessPolicy(context.locals.tenant).b2bKybOrgVerification;
306
+ if (orgKyb) {
307
+ try {
308
+ const db = await shopperDb();
309
+ if (!db || !await hasShopperOrgKyb(db, shopper)) {
310
+ return json({ decision: blockedDecision("Your business verification needs review before checkout."), gate: "required" });
311
+ }
312
+ } catch {
313
+ return json({ decision: blockedDecision("Business verification is unavailable."), gate: "required" }, 503);
314
+ }
315
+ }
316
+ const gate = !orgKyb && complianceGateRequiredFor(policy) ? "required" : "not-required";
317
+ const result = await evaluatePreflight(context, body, {
318
+ verification: orgKyb ? "not-required" : policy?.verification, rules: policy?.rules, shopper,
319
+ });
295
320
  logPreflightDecision(result.decision);
296
321
  return json({ ...result, gate });
297
322
  }
@@ -319,6 +344,7 @@ function logPreflightDecision(decision: CartComplianceDecision): void {
319
344
  }
320
345
 
321
346
  export interface PreflightOptions {
347
+ shopper?: ScopedShopper;
322
348
  /**
323
349
  * Server-owned verification requirement, from the shared test store's policy for this
324
350
  * tenant. "required" requires verification even where the ruleset would not; absent keeps
@@ -361,7 +387,7 @@ export async function evaluatePreflight(
361
387
  // never in SANDBOX_VERIFICATION_PROVIDERS. Any adapter failure clears the
362
388
  // provider so the engine blocks fail-closed, exactly as when none is wired.
363
389
  if (ruleset && ruleset.verification.required && isLiveTotVerificationProvider(ruleset.verification.provider)) {
364
- const resolved = await resolveLiveVerification(body);
390
+ const resolved = await resolveLiveVerification(body, options.shopper);
365
391
  if (!resolved) {
366
392
  ruleset = withProviderCleared(ruleset);
367
393
  verification = { outcome: "unknown" };
@@ -439,7 +465,10 @@ export async function evaluatePreflight(
439
465
  isSandboxVerificationProvider(ruleset.verification.provider)
440
466
  ) {
441
467
  const rawRef = typeof body.verificationRef === "string" ? body.verificationRef.trim() : "";
442
- const ref = SANDBOX_CLEARED_REF.test(rawRef) ? rawRef : `sandbox-cleared:${crypto.randomUUID()}`;
468
+ const ref = options.shopper
469
+ ? await newShopperVerificationRef(options.shopper, true)
470
+ : SANDBOX_CLEARED_REF.test(rawRef) ? rawRef : `sandbox-cleared:${crypto.randomUUID()}`;
471
+ if (!ref) return { decision: blockedDecision("Verification is unavailable.") };
443
472
  liveVerification = { ref, status: "conditions_met" };
444
473
  }
445
474
  return liveVerification ? { decision: applied, verification: liveVerification } : { decision: applied };
@@ -8,6 +8,7 @@ import {
8
8
  withCartSession,
9
9
  } from "@/lib/checkout/commerce/cartSession.js";
10
10
  import { managedCartHref } from "@/lib/content/chrome/managedCart.js";
11
+ import { shopperPurchaseAccess } from "@/lib/customers/accounts/purchaseAccess";
11
12
 
12
13
  export const prerender = false;
13
14
 
@@ -38,6 +39,8 @@ export const GET: APIRoute = async (context) => {
38
39
  headers: { location: `${cookiePath}cart`, "cache-control": NO_STORE },
39
40
  });
40
41
  }
42
+ const access = await shopperPurchaseAccess(context);
43
+ if (!access.ok) return access.response;
41
44
  const tenantId = context.locals.tenant ? commerceTenantId(context.locals.tenant) : "";
42
45
  const sessionId = tenantId ? await bindCartSession(context, context.locals.commerce, tenantId) : null;
43
46
  if (!sessionId) {
@@ -5,13 +5,14 @@
5
5
  * serves; commerce-only.
6
6
  */
7
7
  import type { APIContext } from "astro";
8
+ import { hidesPublicCatalogPrices } from "@tot/public-runtime/declared-tenant-config";
8
9
  import { buildCatalogIndex } from "@/lib/catalog/shared/catalogIndex.js";
9
10
 
10
11
  export async function GET(context: APIContext): Promise<Response> {
11
- const { tot, features } = context.locals;
12
+ const { tot, features, tenant } = context.locals;
12
13
  if (!features.catalog && !features.productSearch) return new Response(null, { status: 404 });
13
14
  const [products, collections] = await Promise.all([tot.getAllActiveProducts(), tot.listCollections()]);
14
- return new Response(JSON.stringify(buildCatalogIndex(products, collections)), {
15
+ return new Response(JSON.stringify(buildCatalogIndex(products, collections, hidesPublicCatalogPrices(tenant))), {
15
16
  headers: {
16
17
  "content-type": "application/json; charset=utf-8",
17
18
  "cache-control": "public, max-age=300, s-maxage=3600",
@@ -7,6 +7,7 @@
7
7
  import CollectionView from "../../_CollectionView.astro";
8
8
  import { collectionPageCount, loadCollectionListing } from "@/lib/catalog/shared/collectionPaging";
9
9
  import { effectiveCollectionQuery } from "@/lib/publication/shared/staticQuery";
10
+ import { hidesPublicCatalogPrices } from "@tot/public-runtime/declared-tenant-config";
10
11
  import { parsePagedRouteParam } from "@/lib/content/blog/pagination";
11
12
 
12
13
  // Same query contract as page 1: sort/facets/price/search are applied client-side
@@ -18,7 +19,7 @@ if (!Astro.locals.features.catalog) return new Response(null, { status: 404 });
18
19
  const pathPage = parsePagedRouteParam(Astro.params.n);
19
20
  if (!handle || pathPage === null) return new Response(null, { status: 404 });
20
21
 
21
- const query = effectiveCollectionQuery(Astro.url, pathPage);
22
+ const query = effectiveCollectionQuery(Astro.url, pathPage, hidesPublicCatalogPrices(Astro.locals.tenant));
22
23
  const listing = await loadCollectionListing(Astro.locals.tot, handle, query);
23
24
  if (!listing) return new Response(null, { status: 404 });
24
25
  // A page past the collection's end is a real 404, never a clamped copy of the last page.