@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
@@ -15,7 +15,7 @@ import { sha256Hex } from "@tot/public-runtime";
15
15
  import { IMAGE_LIMITS_CEILING } from "@tot/public-runtime/image-limits";
16
16
  import {
17
17
  PINNED_ASSET_EXTENSION_BY_MEDIA_TYPE, PINNED_ASSET_MEDIA_TYPE_BY_EXTENSION,
18
- sealedOriginalEntryAllowed, validSvgSanitizeReceipt, type SvgSanitizeReceipt,
18
+ UPLOADABLE_MEDIA_TYPES, sealedOriginalEntryAllowed, validSvgSanitizeReceipt, type SvgSanitizeReceipt,
19
19
  } from "@tot/public-runtime/hosted-image-media-types";
20
20
  import { durableAssetsStatusKey, durableCaptureRevisionId, durableRequiredStores, parseDurableAssetsStatus } from "@tot/public-runtime/durable-assets";
21
21
  import { POOL_ASSET_SECURITY_HEADERS } from "@tot/public-runtime/pool-asset-headers";
@@ -57,6 +57,61 @@ function objectKey(tenantId: string, address: string): string {
57
57
  return `original-images/${tenantId}/objects/${address}`;
58
58
  }
59
59
 
60
+ const ACTOR_ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
61
+
62
+ function uploadRecordKey(tenantId: string, address: string): string {
63
+ return `original-images/${tenantId}/uploads/${address}.json`;
64
+ }
65
+
66
+ async function readUploadedOriginalEntry(
67
+ bucket: CapturedOriginalBucket,
68
+ tenantId: string,
69
+ address: string,
70
+ ): Promise<ManifestEntry | null> {
71
+ const maxEntryBytes = IMAGE_LIMITS_CEILING.maxEncodedBytes;
72
+ if (!isSafeTenantId(tenantId) || !ADDRESS_RE.test(address)) return null;
73
+ const object = await bucket.get(uploadRecordKey(tenantId, address));
74
+ if (!object || typeof object !== "object") return null;
75
+ const body = object as { arrayBuffer?: () => Promise<ArrayBuffer> };
76
+ if (typeof body.arrayBuffer !== "function") return null;
77
+ const bytes = await body.arrayBuffer();
78
+ let parsed: {
79
+ version?: unknown;
80
+ address?: unknown;
81
+ byteLength?: unknown;
82
+ mediaType?: unknown;
83
+ provenance?: { kind?: unknown };
84
+ uploaderActorId?: unknown;
85
+ at?: unknown;
86
+ } | null = null;
87
+ try {
88
+ parsed = JSON.parse(new TextDecoder().decode(new Uint8Array(bytes)));
89
+ } catch { /* Malformed upload record fails closed. */ }
90
+ if (
91
+ !parsed ||
92
+ typeof parsed !== "object" ||
93
+ parsed.version !== 1 ||
94
+ parsed.address !== address ||
95
+ parsed.provenance?.kind !== "upload" ||
96
+ !Number.isSafeInteger(parsed.byteLength) ||
97
+ (parsed.byteLength as number) < 1 ||
98
+ (parsed.byteLength as number) > maxEntryBytes ||
99
+ typeof parsed.mediaType !== "string" ||
100
+ !(UPLOADABLE_MEDIA_TYPES as readonly string[]).includes(parsed.mediaType) ||
101
+ typeof parsed.uploaderActorId !== "string" ||
102
+ !ACTOR_ID_RE.test(parsed.uploaderActorId) ||
103
+ typeof parsed.at !== "string"
104
+ ) {
105
+ return null;
106
+ }
107
+ return {
108
+ address,
109
+ byteLength: parsed.byteLength as number,
110
+ mediaType: parsed.mediaType,
111
+ provenance: { kind: "upload", locator: `/_a/${address}${PINNED_ASSET_EXTENSION_BY_MEDIA_TYPE[parsed.mediaType]}` },
112
+ };
113
+ }
114
+
60
115
  /** Parse `/_a/<sha256>[.ext]` — null when the path is not a pinned asset URL. */
61
116
  export function parsePinnedImagePath(pathname: string): { address: string; ext: string } | null {
62
117
  const match = pathname.match(/^\/_a\/([0-9a-f]{64})(\.[A-Za-z0-9]+)?$/);
@@ -183,6 +238,11 @@ export async function tryServeCapturedOriginal(input: {
183
238
  durable = !!entry;
184
239
  } catch { /* Unreadable durable authority fails closed. */ }
185
240
  }
241
+ if (!entry) {
242
+ try {
243
+ entry = await readUploadedOriginalEntry(input.bucket, input.tenantId, parsed.address) ?? undefined;
244
+ } catch { /* Unreadable upload authority fails closed. */ }
245
+ }
186
246
  if (entry && parsed.ext && EXT_TYPE[parsed.ext.toLowerCase()] !== entry.mediaType) entry = undefined;
187
247
  if (!entry) {
188
248
  return new Response("Not found", { status: 404, headers: { "cache-control": "no-store" } });
@@ -52,8 +52,8 @@ export interface TypeaheadDoc {
52
52
  title: string;
53
53
  vendor?: string;
54
54
  type?: string;
55
- price: number;
56
- currency: string;
55
+ price?: number;
56
+ currency?: string;
57
57
  image?: string;
58
58
  tags: string[];
59
59
  }
@@ -62,8 +62,7 @@ export function toTypeaheadDoc(p: CatalogProduct): TypeaheadDoc {
62
62
  const doc: TypeaheadDoc = {
63
63
  handle: p.handle,
64
64
  title: p.title,
65
- price: p.price_range.min,
66
- currency: p.price_range.currency,
65
+ ...(p.price_range ? { price: p.price_range.min, currency: p.price_range.currency } : {}),
67
66
  tags: p.tags,
68
67
  };
69
68
  if (p.vendor) doc.vendor = p.vendor;
@@ -15,7 +15,7 @@ export const CATALOG_INDEX_VERSION = 1;
15
15
  const DESCRIPTION_CHARS = 280;
16
16
 
17
17
  export interface CatalogIndexVariant {
18
- price: number;
18
+ price?: number;
19
19
  compare_at_price?: number;
20
20
  option_values: Record<string, string>;
21
21
  inventory: { available: boolean };
@@ -32,7 +32,7 @@ export interface CatalogIndexProduct {
32
32
  status: CatalogProduct["status"];
33
33
  options: { name: string }[];
34
34
  variants: CatalogIndexVariant[];
35
- price_range: CatalogProduct["price_range"];
35
+ price_range?: CatalogProduct["price_range"];
36
36
  collections: string[];
37
37
  created_at: string;
38
38
  image?: { url: string; alt?: string; rehosted?: boolean; id?: string };
@@ -47,9 +47,10 @@ export interface CatalogIndex {
47
47
  version: number;
48
48
  products: CatalogIndexProduct[];
49
49
  collections: CatalogIndexCollection[];
50
+ pricesHidden?: true;
50
51
  }
51
52
 
52
- export function toCatalogIndexProduct(p: CatalogProduct): CatalogIndexProduct {
53
+ export function toCatalogIndexProduct(p: CatalogProduct, pricesHidden = false): CatalogIndexProduct {
53
54
  const doc: CatalogIndexProduct = {
54
55
  id: p.id,
55
56
  handle: p.handle,
@@ -59,12 +60,14 @@ export function toCatalogIndexProduct(p: CatalogProduct): CatalogIndexProduct {
59
60
  status: p.status,
60
61
  options: p.options.map((o) => ({ name: o.name })),
61
62
  variants: p.variants.map((v) => ({
62
- price: v.price,
63
- ...(v.compare_at_price != null ? { compare_at_price: v.compare_at_price } : {}),
63
+ ...(!pricesHidden ? {
64
+ price: v.price,
65
+ ...(v.compare_at_price != null ? { compare_at_price: v.compare_at_price } : {}),
66
+ } : {}),
64
67
  option_values: v.option_values,
65
68
  inventory: { available: v.inventory.available },
66
69
  })),
67
- price_range: p.price_range,
70
+ ...(!pricesHidden ? { price_range: p.price_range } : {}),
68
71
  collections: p.collections,
69
72
  created_at: p.created_at,
70
73
  };
@@ -84,11 +87,13 @@ export function toCatalogIndexProduct(p: CatalogProduct): CatalogIndexProduct {
84
87
  export function buildCatalogIndex(
85
88
  activeProducts: CatalogProduct[],
86
89
  collections: CatalogCollection[],
90
+ pricesHidden = false,
87
91
  ): CatalogIndex {
88
92
  return {
89
93
  version: CATALOG_INDEX_VERSION,
90
- products: activeProducts.map(toCatalogIndexProduct),
94
+ products: activeProducts.map(product => toCatalogIndexProduct(product, pricesHidden)),
91
95
  collections: collections.map((c) => ({ handle: c.handle, product_handles: c.product_handles })),
96
+ ...(pricesHidden ? { pricesHidden: true } : {}),
92
97
  };
93
98
  }
94
99
 
@@ -7,6 +7,7 @@
7
7
  import type { ListProductsQuery, ListProductsResponse } from "@tot/public-runtime";
8
8
  import { applyQuery, buildFacets, collectionProducts, paginate } from "../tot/query.js";
9
9
  import { buildSearchIndex } from "../search/index.js";
10
+ import { withoutPrivatePriceQuery } from "../../publication/shared/staticQuery.js";
10
11
  import {
11
12
  asCatalogCollection,
12
13
  asCatalogProduct,
@@ -29,8 +30,9 @@ export function collectionViewFromIndex(
29
30
  const active = index.products.map(asCatalogProduct);
30
31
  const collection = index.collections.find((c) => c.handle === handle);
31
32
  const pool = collection ? collectionProducts(active, asCatalogCollection(collection)) : [];
32
- const facets = buildFacets(pool, query);
33
- const { items, page, pageSize, total } = paginate(applyQuery(pool, query, true), query);
33
+ const browse = withoutPrivatePriceQuery(query, index.pricesHidden === true);
34
+ const facets = buildFacets(pool, browse, !index.pricesHidden);
35
+ const { items, page, pageSize, total } = paginate(applyQuery(pool, browse, true), browse);
34
36
  return { products: items, page, pageSize, total, facets };
35
37
  }
36
38
 
@@ -53,6 +53,7 @@ export function isNew(p: CatalogProduct, days = 60): boolean {
53
53
  export function buildFacets(
54
54
  pool: CatalogProduct[],
55
55
  query: ListProductsQuery = {},
56
+ includePrices = true,
56
57
  ): Facet[] {
57
58
  const optionValues = new Map<string, Set<string>>();
58
59
  const tagNames = new Set<string>();
@@ -76,7 +77,7 @@ export function buildFacets(
76
77
  facets.push(buildTagFacet(tagNames, applyFilters(pool, query, "tags")));
77
78
  }
78
79
  facets.push(buildAvailabilityFacet(applyFilters(pool, query, "availability")));
79
- facets.push(buildPriceFacet(applyFilters(pool, query, "price")));
80
+ if (includePrices) facets.push(buildPriceFacet(applyFilters(pool, query, "price")));
80
81
  return facets;
81
82
  }
82
83
 
@@ -147,12 +147,15 @@ async function readCart(
147
147
  } catch (error) {
148
148
  return { status: "unreadable", reason: error instanceof Error ? error.name : "Error" };
149
149
  }
150
- for (const field of fields) url.searchParams.append(field.name, field.value);
150
+ const protectedFields = fields.some(field => /^(?:\d+:)?shopper_checkout\|\|/.test(field.name));
151
+ const form = protectedFields ? new URLSearchParams() : url.searchParams;
152
+ for (const field of fields) form.append(field.name, field.value);
151
153
  url.searchParams.set("output", "json");
152
154
  if (fcsid) url.searchParams.set("fcsid", fcsid);
153
155
  try {
154
156
  const response = await fetchImpl(url.toString(), {
155
- method: "GET",
157
+ method: protectedFields ? "POST" : "GET",
158
+ ...(protectedFields ? { body: form } : {}),
156
159
  redirect: "manual",
157
160
  credentials: "omit",
158
161
  headers: { accept: "application/json" },
@@ -377,17 +380,13 @@ export async function addLinesToTenantCart(input: {
377
380
  }
378
381
  const mergedCoupons = [...existingCoupons, ...newCoupons];
379
382
  const addVerification = adds.flat().find((field) => field.name.split("||")[0] === "verification")?.value;
383
+ const checkoutProof = adds.flat().find((field) => field.name.split("||")[0] === "shopper_checkout")?.value;
380
384
  const itemFields: CartLineField[] = [];
381
385
  for (const [index, line] of carried.entries()) {
382
- const toSign = addVerification
383
- ? {
384
- ...line,
385
- fields: [
386
- ...line.fields.filter((f) => f.name !== "verification"),
387
- { name: "verification", value: addVerification },
388
- ],
389
- }
390
- : line;
386
+ const fields = line.fields.filter(field => !(addVerification && field.name === "verification") && field.name !== "shopper_checkout");
387
+ if (addVerification) fields.push({ name: "verification", value: addVerification });
388
+ if (checkoutProof) fields.push({ name: "shopper_checkout", value: checkoutProof });
389
+ const toSign = { ...line, fields };
391
390
  for (const field of await input.sign(toSign)) itemFields.push({ name: `${index + 1}:${field.name}`, value: field.value });
392
391
  }
393
392
  const numbered = carried.length + adds.length > 1;
@@ -56,6 +56,8 @@ import { effectiveExcise } from "@/lib/checkout/commerce/checkoutExcise";
56
56
  import { fromD1 } from "@/lib/catalog/d1/catalog";
57
57
  import { readD1 } from "@/lib/publication/shared/env";
58
58
  import { handoffStockFinding, MIRROR_LOCATION_UNSPECIFIED, readMirrorBalance } from "@/lib/inventory/mirrorStock";
59
+ import { shopperCatalogProduct, shopperVariantPrice } from "@/lib/customers/accounts/pricing";
60
+ import { requiresShopperPurchase, shopperJson } from "@/lib/customers/accounts/purchaseAccess";
59
61
 
60
62
  export type SampleProductReader = (tenant: TenantConfig, handle: string, commerce: ResolvedManagedCheckout) => Promise<CatalogProduct | null>;
61
63
 
@@ -153,10 +155,9 @@ function takePromoCoupon(
153
155
  }
154
156
 
155
157
  /**
156
- * Add the enforced line to this tenant's Foxy cart from the server, and return the cart view of
157
- * the session that holds it. The location carries no cart fields, so following it adds nothing.
158
+ * Add the enforced line to this tenant's Foxy cart from the server.
158
159
  */
159
- async function sessionedCartLocation(
160
+ async function addEnforcedLine(
160
161
  context: APIContext,
161
162
  commerce: ResolvedManagedCheckout,
162
163
  tenant: TenantConfig,
@@ -164,7 +165,7 @@ async function sessionedCartLocation(
164
165
  secret: string | undefined,
165
166
  coupon: string | null = null,
166
167
  ): Promise<string | null> {
167
- const fcsid = await addToBoundCart(
168
+ return addToBoundCart(
168
169
  context,
169
170
  commerce,
170
171
  commerceTenantId(tenant),
@@ -173,7 +174,6 @@ async function sessionedCartLocation(
173
174
  undefined,
174
175
  coupon,
175
176
  );
176
- return fcsid ? withCartSession(commerce.cartUrl, fcsid) : null;
177
177
  }
178
178
 
179
179
  export function ledgerStage(env: string | undefined): "preview" | "publication" | null {
@@ -280,7 +280,32 @@ export async function completeCartFields(
280
280
  }
281
281
 
282
282
  /** Native cart POST. Browser preflight is not consulted. Payment is never authorized. */
283
- async function cartFormPost(context: APIContext): Promise<Response> {
283
+ export interface GatedHandoff {
284
+ tierId: string | null;
285
+ providerOrigin: string;
286
+ validateVerificationRef: (ref: string) => Promise<boolean>;
287
+ prepareProof: () => Promise<{ proof: string; buyerConfirmation: string; bind: (selector: string) => Promise<boolean> } | null>;
288
+ }
289
+
290
+ function buyerHandoff(providerOrigin: string, selector: string, proof: string, confirmation: string): Response {
291
+ const action = new URL("/api/commerce/shopper-checkout-handoff", providerOrigin);
292
+ const fields = { fcsid: selector, shopper_checkout: proof, buyer_confirmation: confirmation };
293
+ const inputs = Object.entries(fields).map(([name, value]) =>
294
+ `<input type="hidden" name="${name}" value="${escapeHtml(value)}">`).join("");
295
+ const html = '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">' +
296
+ `<title>Continue to checkout</title><main><h1>Continue to checkout</h1><form method="post" action="${escapeHtml(action.href)}">` +
297
+ `${inputs}<button type="submit">Continue to checkout</button></form></main></html>`;
298
+ return new Response(html, { headers: {
299
+ "content-type": "text/html; charset=utf-8",
300
+ "cache-control": "private, no-store",
301
+ "content-security-policy": `default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action ${action.origin}`,
302
+ "referrer-policy": "no-referrer",
303
+ "x-robots-tag": "noindex, nofollow",
304
+ "x-tot-payment-authorized": "false",
305
+ } });
306
+ }
307
+
308
+ async function cartFormPost(context: APIContext, shopper?: GatedHandoff): Promise<Response> {
284
309
  const { tenant, commerce } = context.locals;
285
310
  if (!commerce) {
286
311
  return cartDenial(
@@ -297,12 +322,43 @@ async function cartFormPost(context: APIContext): Promise<Response> {
297
322
  503,
298
323
  );
299
324
  }
300
- const form = await context.request.formData();
325
+ let form: FormData;
326
+ try { form = await context.request.formData(); }
327
+ catch { return cartDenial("signature", "Invalid cart.", 422); }
301
328
  const submitted: Array<[string, string]> = [];
302
329
  for (const [name, value] of form.entries()) {
303
330
  if (typeof value !== "string") return cartDenial("signature", "Invalid cart.", 422);
304
331
  submitted.push([name, value]);
305
332
  }
333
+ if (shopper) {
334
+ const { entries: purchase, ref } = takeVerificationRef(submitted);
335
+ const handle = form.get("productHandle");
336
+ const variantId = form.get("variantId");
337
+ const quantity = form.get("quantity");
338
+ if (purchase.length !== 3 || submitted.length !== 3 + Number(ref !== null) ||
339
+ typeof handle !== "string" || typeof variantId !== "string" ||
340
+ typeof quantity !== "string" || !/^[1-9]\d{0,2}$/.test(quantity) || Number(quantity) > MAX_CART_QUANTITY ||
341
+ handle.length < 1 || handle.length > 160 || variantId.length < 1 || variantId.length > 256) {
342
+ return cartDenial("signature", "Invalid cart.", 422);
343
+ }
344
+ if (ref && !await shopper.validateVerificationRef(ref)) return cartDenial("signature", "Verification is unavailable for this session.", 422);
345
+ const product = await context.locals.tot.getProductByHandle(handle);
346
+ if (!shopperCatalogProduct(tenant, product)) return cartDenial("signature", "This product is unavailable.", 422);
347
+ const variant = product.variants.find(item => item.id === variantId && item.inventory.available);
348
+ const price = variant && shopperVariantPrice(tenant, product, variant, shopper.tierId);
349
+ if (!price || !variant) return cartDenial("signature", "This product is unavailable.", 422);
350
+ const payload = await buildVariantCartPayload(product, variant, {
351
+ mode: commerce.mode, secret: signing.secret, signedPrice: price.price, tenantId: commerceTenantId(tenant),
352
+ currency: tenant.currency, publicOrigin: tenantPublicOrigin(tenant, {
353
+ requestOrigin: context.locals.requestOrigin,
354
+ basePath: context.locals.imageBasePath || context.locals.apiBasePath || context.locals.basePath,
355
+ }),
356
+ });
357
+ submitted.length = 0;
358
+ for (const field of payload.hidden) submitted.push([field.name, field.value]);
359
+ submitted.push([payload.quantityName, quantity]);
360
+ if (ref) submitted.push(["verification", ref]);
361
+ }
306
362
  // The compliance gate adds the shopper's verification ref; it rides to the cart signed.
307
363
  const { entries: withoutVerification, ref } = takeVerificationRef(submitted);
308
364
  const { entries, coupon } = takePromoCoupon(withoutVerification, context.request.url);
@@ -323,8 +379,18 @@ async function cartFormPost(context: APIContext): Promise<Response> {
323
379
  ref, returnUrl: submittedFromUrl(context.request, tenant),
324
380
  });
325
381
  if (!imaged) return cartDenial("shipping", SHIPPING_UNAVAILABLE_CART_MESSAGE, 409);
326
- const location = await sessionedCartLocation(context, commerce, tenant, imaged, signing.secret, coupon);
327
- if (!location) return cartDenial("signing-unavailable", CART_UNAVAILABLE_MESSAGE, 503);
382
+ let proof: Awaited<ReturnType<GatedHandoff["prepareProof"]>> = null;
383
+ if (shopper) {
384
+ if (commerce.mode !== "signed" || !signing.secret) return cartDenial("signing-unavailable", CART_UNAVAILABLE_MESSAGE, 503);
385
+ const code = submittedCode(imaged);
386
+ proof = code ? await shopper.prepareProof() : null;
387
+ if (!proof || !code) return cartDenial("signing-unavailable", CART_UNAVAILABLE_MESSAGE, 503);
388
+ imaged.push(...await signCartLine([{ name: "shopper_checkout", value: proof.proof }], { mode: commerce.mode, secret: signing.secret, code }));
389
+ }
390
+ const selector = await addEnforcedLine(context, commerce, tenant, imaged, signing.secret, coupon);
391
+ if (!selector || (proof && !await proof.bind(selector))) return cartDenial("signing-unavailable", CART_UNAVAILABLE_MESSAGE, 503);
392
+ if (proof && shopper) return buyerHandoff(shopper.providerOrigin, selector, proof.proof, proof.buyerConfirmation);
393
+ const location = withCartSession(commerce.cartUrl, selector);
328
394
  // The page reads the cart that now holds the line (cartState.ts) and asks for its URL as data.
329
395
  if ((context.request.headers.get("accept") ?? "").includes("application/json")) {
330
396
  return new Response(JSON.stringify({ location }), {
@@ -348,8 +414,9 @@ async function cartFormPost(context: APIContext): Promise<Response> {
348
414
  });
349
415
  }
350
416
 
351
- export async function checkoutHandoffPost(context: APIContext): Promise<Response> {
352
- if (isCartForm(context.request)) return cartFormPost(context);
417
+ export async function checkoutHandoffPost(context: APIContext, shopper?: GatedHandoff): Promise<Response> {
418
+ if (!shopper && requiresShopperPurchase(context.locals.tenant)) return shopperJson({ ok: false, error: "shopper_sign_in_required" }, 401);
419
+ if (isCartForm(context.request)) return cartFormPost(context, shopper);
353
420
  const { tenant, browserEnvironment, commerce } = context.locals;
354
421
 
355
422
  // No managed checkout on this tenant → nothing to attribute.
@@ -450,9 +517,9 @@ export async function sampleCartGet(
450
517
  if (!result.ok) return invalid();
451
518
  const shipped = await boundShippingPolicy(result.fields, tenant, "signed", signing.secret);
452
519
  if (!shipped) return sampleResponse('{"error":"shipping_unavailable"}', 409);
453
- const location = await sessionedCartLocation(context, commerce, tenant, shipped, signing.secret);
454
- if (!location) return sampleResponse('{"error":"cart_unavailable"}', 503);
455
- return sampleResponse(null, 303, location);
520
+ const selector = await addEnforcedLine(context, commerce, tenant, shipped, signing.secret);
521
+ if (!selector) return sampleResponse('{"error":"cart_unavailable"}', 503);
522
+ return sampleResponse(null, 303, withCartSession(commerce.cartUrl, selector));
456
523
  } catch { return sampleResponse('{"error":"sample_unavailable"}', 503); }
457
524
  }
458
525
 
@@ -134,6 +134,41 @@ export function bypassesComplianceGate(res: PreflightResponse | null): boolean {
134
134
  return res !== null && res.gate === "not-required" && res.decision.status === "clear";
135
135
  }
136
136
 
137
+ export interface PendingLine {
138
+ form: HTMLFormElement;
139
+ shopperCart: boolean;
140
+ handle: string;
141
+ sku?: string;
142
+ variantId?: string;
143
+ quantity: number;
144
+ title: string;
145
+ }
146
+
147
+ export function checkoutLineFromForm(form: HTMLFormElement): PendingLine | null {
148
+ const shopperCart = form.hasAttribute("data-shopper-cart");
149
+ if (!shopperCart && !form.hasAttribute("data-managed-cart")) return null;
150
+ const quantityInput = form.querySelector<HTMLInputElement>('input[name$="quantity" i]');
151
+ return {
152
+ form,
153
+ shopperCart,
154
+ handle: shopperCart ? form.querySelector<HTMLInputElement>('input[name="productHandle"]')?.value ?? "" : form.dataset.productHandle ?? "",
155
+ variantId: (shopperCart ? form.querySelector<HTMLSelectElement>('select[name="variantId"]')?.value : form.dataset.variantId) || undefined,
156
+ sku: shopperCart ? undefined : form.dataset.variantSku || undefined,
157
+ quantity: Math.max(1, parseInt(quantityInput?.value ?? "1", 10) || 1),
158
+ title: form.dataset.productTitle ?? "this item",
159
+ };
160
+ }
161
+
162
+ export function carryCheckoutVerification(form: HTMLFormElement, ref: string | null): void {
163
+ form.querySelectorAll('input[name="verification"]').forEach(input => input.remove());
164
+ if (!ref) return;
165
+ const input = form.ownerDocument.createElement("input");
166
+ input.type = "hidden";
167
+ input.name = "verification";
168
+ input.value = ref;
169
+ form.appendChild(input);
170
+ }
171
+
137
172
  /** True when the decision carries the provider's real "did not pass" block. */
138
173
  function hasVerificationFailure(decision: CartComplianceDecision): boolean {
139
174
  return decision.blocks.some(
@@ -17,6 +17,7 @@ import type {
17
17
  TenantConfig,
18
18
  } from "@tot/public-runtime";
19
19
  import { productLd } from "../shared/jsonld.js";
20
+ import { hidesPublicCatalogPrices } from "@tot/public-runtime/declared-tenant-config";
20
21
  import { pageUrlForm } from "./urlForm.js";
21
22
 
22
23
  type Node = Record<string, unknown>;
@@ -256,7 +257,7 @@ export function composeStructuredData(input: ComposeInput): Node | null {
256
257
  name: nameOf("Product", p.title, "title"),
257
258
  url: canonical,
258
259
  ...(pageToken ? { mainEntityOfPage: { "@id": pageId } } : {}),
259
- ...(single ? { offers: offer(single) } : {}),
260
+ ...(single && !hidesPublicCatalogPrices(tenant) ? { offers: offer(single) } : {}),
260
261
  ...(profile.reviews ? page.reviews ?? {} : {}),
261
262
  };
262
263
  }
@@ -277,7 +278,7 @@ export function composeStructuredData(input: ComposeInput): Node | null {
277
278
  "@type": "Product",
278
279
  name: `${p.title} - ${v.title}`,
279
280
  ...(v.sku ? { sku: v.sku } : {}),
280
- offers: offer(v),
281
+ ...(!hidesPublicCatalogPrices(tenant) ? { offers: offer(v) } : {}),
281
282
  })),
282
283
  ...(profile.reviews ? page.reviews ?? {} : {}),
283
284
  };
@@ -3,6 +3,7 @@
3
3
  * BreadcrumbList, Organization. Kept pure so pages compose them and pass to <Seo>.
4
4
  */
5
5
  import type { CatalogProduct, Review, TenantConfig } from "@tot/public-runtime";
6
+ import { hidesPublicCatalogPrices } from "@tot/public-runtime/declared-tenant-config";
6
7
  import { pageUrlForm } from "../seo/urlForm.js";
7
8
  import { isAvailable } from "../../catalog/tot/query.js";
8
9
 
@@ -235,7 +236,7 @@ export function productLd(
235
236
  ...(images.length ? { image: images } : {}),
236
237
  ...(p.vendor ? { brand: { "@type": "Brand", name: p.vendor } } : {}),
237
238
  ...(p.product_type ? { category: p.product_type } : {}),
238
- offers: {
239
+ ...(!hidesPublicCatalogPrices(tenant) && { offers: {
239
240
  "@type": "AggregateOffer",
240
241
  priceCurrency: p.price_range.currency,
241
242
  lowPrice: p.price_range.min.toFixed(2),
@@ -245,7 +246,7 @@ export function productLd(
245
246
  ? "https://schema.org/InStock"
246
247
  : "https://schema.org/OutOfStock",
247
248
  offers,
248
- },
249
+ } }),
249
250
  };
250
251
  }
251
252
 
@@ -0,0 +1,75 @@
1
+ import type { APIContext } from "astro";
2
+ import {
3
+ catalogAdmissionMessage,
4
+ catalogAdmissionWindow,
5
+ resolveShopperAccessPolicy,
6
+ } from "@tot/public-runtime/declared-tenant-config";
7
+ import { readEnv } from "@/lib/publication/shared/env";
8
+ import { getScopedShopper, isApprovedShopper, type ScopedShopper } from "./session";
9
+ import { resolveShopperScope, shopperCookiePath, type ShopperScope } from "./scope";
10
+
11
+ export const SHOPPER_CATALOG_COOKIE = "tot_shopper_catalog";
12
+ const ADMISSION_SECONDS = 120;
13
+ const encoder = new TextEncoder();
14
+
15
+ async function catalogKey(scope: ShopperScope): Promise<CryptoKey | null> {
16
+ const raw = await readEnv("SHOPPER_CATALOG_ADMISSION_KEYS");
17
+ if (!raw) return null;
18
+ let keys: unknown;
19
+ try {
20
+ keys = JSON.parse(raw);
21
+ } catch (error) {
22
+ if (error instanceof SyntaxError) return null;
23
+ throw error;
24
+ }
25
+ const name = `${scope.tenantId}:${scope.stage}`;
26
+ if (!keys || typeof keys !== "object" || !Object.hasOwn(keys, name)) return null;
27
+ const key = (keys as Record<string, unknown>)[name];
28
+ if (typeof key !== "string" || !/^[a-f0-9]{64}$/.test(key)) return null;
29
+ return crypto.subtle.importKey("raw", encoder.encode(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
30
+ }
31
+
32
+ export async function hasShopperCatalogAdmissionKey(scope: ShopperScope): Promise<boolean> {
33
+ return (await catalogKey(scope)) !== null;
34
+ }
35
+
36
+ export async function verifyShopperCatalogAdmission(
37
+ token: string, scope: ShopperScope, host: string, now = Math.floor(Date.now() / 1000),
38
+ ): Promise<boolean> {
39
+ const window = catalogAdmissionWindow(token, now);
40
+ if (!window?.mac) return false;
41
+ const key = await catalogKey(scope);
42
+ if (!key) return false;
43
+ const bytes = Uint8Array.from(window.mac.match(/../g) ?? [], octet => Number.parseInt(octet, 16));
44
+ const message = catalogAdmissionMessage(scope.tenantId, scope.stage, host, window.issued, window.expires);
45
+ return await crypto.subtle.verify("HMAC", key, bytes, encoder.encode(message));
46
+ }
47
+
48
+ /** The supplied shopper is the just-authenticated, freshly read result of session issuance. */
49
+ export async function setShopperCatalogAdmission(context: APIContext, shopper?: ScopedShopper): Promise<boolean> {
50
+ const scope = resolveShopperScope(context.locals);
51
+ if (!scope || !context.locals.requestOrigin || resolveShopperAccessPolicy(context.locals.tenant).mode !== "closed_store") return false;
52
+ const approved = shopper ?? await getScopedShopper(context);
53
+ if (!isApprovedShopper(approved) || approved.scope.tenantId !== scope.tenantId || approved.scope.stage !== scope.stage) return false;
54
+ const key = await catalogKey(scope);
55
+ if (!key) return false;
56
+ const issued = Math.floor(Date.now() / 1000);
57
+ const expires = Math.min(issued + ADMISSION_SECONDS, Math.floor(approved.expiresAt / 1000));
58
+ if (expires <= issued) return false;
59
+ const host = new URL(context.locals.requestOrigin).host;
60
+ const message = catalogAdmissionMessage(scope.tenantId, scope.stage, host, issued, expires);
61
+ const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(message));
62
+ const hex = Array.from(new Uint8Array(sig), byte => byte.toString(16).padStart(2, "0")).join("");
63
+ context.cookies.set(SHOPPER_CATALOG_COOKIE, `v1.${issued}.${expires}.${hex}`, {
64
+ path: shopperCookiePath(context.locals),
65
+ httpOnly: true,
66
+ secure: true,
67
+ sameSite: "lax",
68
+ maxAge: expires - issued,
69
+ });
70
+ return true;
71
+ }
72
+
73
+ export function clearShopperCatalogAdmission(context: APIContext): void {
74
+ context.cookies.delete(SHOPPER_CATALOG_COOKIE, { path: shopperCookiePath(context.locals), secure: true, httpOnly: true, sameSite: "lax" });
75
+ }