@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
@@ -0,0 +1,45 @@
1
+ import type { APIContext } from "astro";
2
+ import type { TenantConfig } from "@tot/public-runtime";
3
+ import { resolveShopperAccessPolicy } from "@tot/public-runtime/declared-tenant-config";
4
+ import { getScopedShopper } from "./session";
5
+ import { isShopperOrigin } from "./scope";
6
+
7
+ export function requiresShopperPurchase(tenant: TenantConfig): boolean {
8
+ const policy = resolveShopperAccessPolicy(tenant);
9
+ return policy.mode !== "open" || policy.hidePricesForGuests || policy.b2bKybOrgVerification;
10
+ }
11
+
12
+ export function shopperJson(body: unknown, status = 200): Response {
13
+ return Response.json(body, { status, headers: {
14
+ "cache-control": "private, no-store",
15
+ "x-robots-tag": "noindex, nofollow",
16
+ } });
17
+ }
18
+
19
+ export type ShopperPurchaseAccess =
20
+ | { ok: true; shopper: Awaited<ReturnType<typeof getScopedShopper>> }
21
+ | { ok: false; response: Response };
22
+
23
+ export async function shopperPurchaseAccess(
24
+ context: APIContext, declaration?: "shopper-session" | "shopper-approved",
25
+ ): Promise<ShopperPurchaseAccess> {
26
+ const deny = (error: string, status: number): ShopperPurchaseAccess => ({
27
+ ok: false, response: shopperJson({ ok: false, error }, status),
28
+ });
29
+ try {
30
+ if (!context.locals.tenant) return deny("store_unavailable", 503);
31
+ if (!declaration && !requiresShopperPurchase(context.locals.tenant)) return { ok: true, shopper: null };
32
+ if (context.request.method === "POST" && !isShopperOrigin(context)) return deny("origin_denied", 403);
33
+ const shopper = await getScopedShopper(context);
34
+ if (!shopper) return deny("shopper_sign_in_required", 401);
35
+ if (declaration !== "shopper-session" && shopper.approvalStatus !== "approved") return deny("shopper_approval_required", 403);
36
+ return { ok: true, shopper };
37
+ } catch {
38
+ return deny("shopper_authority_unavailable", 503);
39
+ }
40
+ }
41
+
42
+ export async function withShopperPurchase(context: APIContext, run: () => Promise<Response>): Promise<Response> {
43
+ const access = await shopperPurchaseAccess(context);
44
+ return access.ok ? run() : access.response;
45
+ }
@@ -0,0 +1,60 @@
1
+ import type { APIContext } from "astro";
2
+ import { commerceTenantId } from "@tot/public-runtime";
3
+ import { safeNext } from "@/lib/access/auth/safeNext";
4
+
5
+ /** Shopper routes use tenant-stage and shopper or interactive-owner authority. */
6
+ export const SHOPPER_ADMISSION_CLASSES = [
7
+ "shopper-public", "shopper-origin", "shopper-session", "shopper-approved",
8
+ "shopper-owner-read", "shopper-owner-mutation",
9
+ "shopper-portal-read", "shopper-portal-approved-read", "shopper-portal-mutation", "shopper-portal-approved-mutation",
10
+ ] as const;
11
+ export type ShopperAdmissionClass = (typeof SHOPPER_ADMISSION_CLASSES)[number];
12
+ /** Account portal routes: the signed-in shopper's own records; mutations are same-origin POST or DELETE. */
13
+ export type ShopperPortalAdmission = Extract<ShopperAdmissionClass, `shopper-portal-${string}`>;
14
+ type PortalMutation = Extract<ShopperPortalAdmission, `${string}-mutation`>;
15
+ export type ShopperRouteAdmission = {
16
+ GET?: Exclude<ShopperAdmissionClass, "shopper-origin" | "shopper-owner-mutation" | PortalMutation>;
17
+ POST?: Extract<ShopperAdmissionClass, "shopper-origin" | "shopper-owner-mutation" | PortalMutation>;
18
+ DELETE?: PortalMutation;
19
+ };
20
+
21
+ export interface ShopperScope {
22
+ tenantId: string;
23
+ stage: "preview" | "publication";
24
+ }
25
+
26
+ export function resolveShopperScope(
27
+ locals: Pick<App.Locals, "tenant" | "customizationEnv">,
28
+ ): ShopperScope | null {
29
+ const tenantId = locals.tenant ? commerceTenantId(locals.tenant) : "";
30
+ const stage = locals.customizationEnv === "test"
31
+ ? "preview"
32
+ : locals.customizationEnv === "live" ? "publication" : null;
33
+ return tenantId && stage ? { tenantId, stage } : null;
34
+ }
35
+
36
+ export function isShopperOrigin(context: Pick<APIContext, "request" | "locals">): boolean {
37
+ const origin = context.locals.requestOrigin;
38
+ return !!origin && origin === context.request.headers.get("origin");
39
+ }
40
+
41
+ export function admitShopperScope(
42
+ context: Pick<APIContext, "request" | "locals">,
43
+ declaration: "shopper-public" | "shopper-origin",
44
+ ): ShopperScope | null {
45
+ if (declaration === "shopper-public" && context.request.method === "GET") return resolveShopperScope(context.locals);
46
+ if (declaration === "shopper-origin" && context.request.method === "POST" && isShopperOrigin(context)) {
47
+ return resolveShopperScope(context.locals);
48
+ }
49
+ return null;
50
+ }
51
+
52
+ export function shopperCookiePath(locals: Pick<App.Locals, "apiBasePath">): string {
53
+ return locals.apiBasePath || "/";
54
+ }
55
+
56
+ export function shopperReturnPath(value: string | null, base: string): string {
57
+ const normalized = new URL(safeNext(value), "https://shopper.invalid");
58
+ const path = safeNext(normalized.pathname + normalized.search);
59
+ return !base || path === base || path.startsWith(`${base}/`) || path.startsWith(`${base}?`) ? path : base + path;
60
+ }
@@ -0,0 +1,173 @@
1
+ import type { APIContext } from "astro";
2
+ import { sha256Hex } from "@tot/public-runtime";
3
+ import { fromD1, type Queryable } from "@/lib/catalog/d1/catalog";
4
+ import { CART_SESSION_COOKIE, PROPOSAL_MARKER_COOKIE, cartSessionCookiePath } from "@/lib/checkout/commerce/cartSession";
5
+ import { readD1, readKv } from "@/lib/publication/shared/env";
6
+ import { resolveShopperScope, shopperCookiePath, type ShopperScope } from "./scope";
7
+
8
+ export const SHOPPER_SESSION_COOKIE = "tot_shopper_session";
9
+ const SESSION_PREFIX = "shopper_sess:";
10
+ export const SHOPPER_SESSION_TTL_SECONDS = 7 * 24 * 3600;
11
+ export type ShopperApproval = "pending" | "approved" | "rejected" | "suspended";
12
+
13
+ export interface ScopedShopper {
14
+ scope: ShopperScope;
15
+ sessionId: string;
16
+ shopperId: string;
17
+ expiresAt: number;
18
+ approvalStatus: ShopperApproval;
19
+ orgId: string | null;
20
+ orgRole: "owner" | "buyer" | null;
21
+ orgApprovalStatus: ShopperApproval | null;
22
+ tierId: string | null;
23
+ checkoutLockMode: "standard" | "require_step_up";
24
+ }
25
+
26
+ interface SessionHint extends ShopperScope {
27
+ expiresAt: number;
28
+ }
29
+
30
+ type SessionContext = Pick<APIContext, "locals" | "cookies">;
31
+
32
+ export function randomShopperToken(bytes = 32): string {
33
+ const octets = crypto.getRandomValues(new Uint8Array(bytes));
34
+ return btoa(String.fromCharCode(...octets)).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
35
+ }
36
+
37
+ export function isShopperToken(value: unknown): value is string {
38
+ return typeof value === "string" && /^[\w-]{43}$/.test(value);
39
+ }
40
+
41
+ export async function shopperDb(): Promise<Queryable | null> {
42
+ const db = await readD1("STOREFRONT_APPS_DB");
43
+ return db ? fromD1(db) : null;
44
+ }
45
+
46
+ export function isApprovedShopper(shopper: ScopedShopper | null): shopper is ScopedShopper & { approvalStatus: "approved" } {
47
+ return shopper?.approvalStatus === "approved" && (!shopper.orgId || shopper.orgApprovalStatus === "approved");
48
+ }
49
+
50
+ function refuseSessionRead(reason: "database-unavailable" | "hint-unavailable" | "hint-invalid"): null {
51
+ console.warn("shopper-session-read-refused", { reason });
52
+ return null;
53
+ }
54
+
55
+ function parseSessionHint(raw: string): SessionHint | null {
56
+ try {
57
+ const hint = JSON.parse(raw) as SessionHint | null;
58
+ if (!hint || typeof hint.tenantId !== "string" || (hint.stage !== "preview" && hint.stage !== "publication") ||
59
+ !Number.isSafeInteger(hint.expiresAt)) return refuseSessionRead("hint-invalid");
60
+ return hint;
61
+ } catch (error) {
62
+ if (error instanceof SyntaxError) return refuseSessionRead("hint-invalid");
63
+ throw error;
64
+ }
65
+ }
66
+
67
+ /** For a provider call only after its signature and shopper proof have been verified. */
68
+ export async function readShopperBySessionRef(
69
+ scope: ShopperScope, sessionId: string, now = Date.now(), database?: Queryable,
70
+ ): Promise<ScopedShopper | null> {
71
+ if (!/^[a-f0-9]{64}$/.test(sessionId) || !Number.isFinite(now)) return null;
72
+ try {
73
+ const db = database ?? await shopperDb();
74
+ if (!db) return refuseSessionRead("database-unavailable");
75
+ const row = await db.first<Omit<ScopedShopper, "scope" | "sessionId">>(
76
+ `SELECT a.id AS shopperId, s.expires_at AS expiresAt,
77
+ CASE WHEN a.approval_status = 'approved' AND a.org_id IS NOT NULL
78
+ THEN COALESCE(o.approval_status, 'suspended') ELSE a.approval_status END AS approvalStatus,
79
+ a.org_id AS orgId, a.org_role AS orgRole, o.approval_status AS orgApprovalStatus,
80
+ COALESCE(a.tier_id, o.tier_id) AS tierId, a.checkout_lock_mode AS checkoutLockMode
81
+ FROM shopper_sessions s
82
+ JOIN shopper_accounts a ON a.tenant_id = s.tenant_id AND a.stage = s.stage AND a.id = s.shopper_id
83
+ LEFT JOIN buyer_orgs o ON o.tenant_id = a.tenant_id AND o.stage = a.stage AND o.id = a.org_id
84
+ WHERE s.tenant_id = ? AND s.stage = ? AND s.id = ? AND s.revoked_at IS NULL AND s.expires_at > ?`,
85
+ scope.tenantId, scope.stage, sessionId, now,
86
+ );
87
+ return row ? { ...row, scope, sessionId } : null;
88
+ } catch {
89
+ return refuseSessionRead("database-unavailable");
90
+ }
91
+ }
92
+
93
+ export async function readScopedShopper(
94
+ scope: ShopperScope, token: string, now = Date.now(),
95
+ deps: { db?: Queryable; kv?: KVNamespace } = {},
96
+ ): Promise<ScopedShopper | null> {
97
+ if (!isShopperToken(token) || !Number.isFinite(now)) return null;
98
+ try {
99
+ const kv = deps.kv ?? await readKv("SESSION");
100
+ if (!kv) return refuseSessionRead("hint-unavailable");
101
+ const raw = await kv.get(SESSION_PREFIX + token);
102
+ if (!raw) return null;
103
+ const hint = parseSessionHint(raw);
104
+ if (!hint || hint.tenantId !== scope.tenantId || hint.stage !== scope.stage || hint.expiresAt <= now) return null;
105
+ return readShopperBySessionRef(scope, await sha256Hex(token), now, deps.db);
106
+ } catch {
107
+ return refuseSessionRead("hint-unavailable");
108
+ }
109
+ }
110
+
111
+ export async function getScopedShopper(context: SessionContext): Promise<ScopedShopper | null> {
112
+ const scope = resolveShopperScope(context.locals);
113
+ const id = context.cookies.get(SHOPPER_SESSION_COOKIE)?.value;
114
+ return scope && id ? readScopedShopper(scope, id) : null;
115
+ }
116
+
117
+ export async function newShopperSession(scope: ShopperScope, now: number) {
118
+ const token = randomShopperToken();
119
+ return { scope, token, id: await sha256Hex(token), expiresAt: now + SHOPPER_SESSION_TTL_SECONDS * 1000 };
120
+ }
121
+
122
+ type NewShopperSession = Awaited<ReturnType<typeof newShopperSession>>;
123
+
124
+ /** The hint alone grants nothing. The D1 session is created in the same batch as proof consumption. */
125
+ export async function writeShopperSessionHint(session: NewShopperSession, kv: KVNamespace): Promise<void> {
126
+ await kv.put(SESSION_PREFIX + session.token, JSON.stringify({ ...session.scope, expiresAt: session.expiresAt }), {
127
+ expirationTtl: SHOPPER_SESSION_TTL_SECONDS,
128
+ });
129
+ }
130
+
131
+ export function setShopperSessionCookie(context: SessionContext, id: string): void {
132
+ clearShopperCheckoutCookies(context);
133
+ context.cookies.set(SHOPPER_SESSION_COOKIE, id, {
134
+ path: shopperCookiePath(context.locals), httpOnly: true, secure: true, sameSite: "lax",
135
+ maxAge: SHOPPER_SESSION_TTL_SECONDS,
136
+ });
137
+ }
138
+
139
+ function clearShopperCheckoutCookies(context: SessionContext): void {
140
+ const path = cartSessionCookiePath(context.locals.apiBasePath ?? context.locals.basePath ?? "");
141
+ const options = { path, httpOnly: true, secure: true, sameSite: "lax" as const };
142
+ context.cookies.delete(CART_SESSION_COOKIE, options);
143
+ context.cookies.delete(PROPOSAL_MARKER_COOKIE, options);
144
+ }
145
+
146
+ export async function revokeScopedShopper(context: SessionContext, now = Date.now()): Promise<boolean> {
147
+ const scope = resolveShopperScope(context.locals);
148
+ const id = context.cookies.get(SHOPPER_SESSION_COOKIE)?.value;
149
+ context.cookies.delete(SHOPPER_SESSION_COOKIE, { path: shopperCookiePath(context.locals) });
150
+ clearShopperCheckoutCookies(context);
151
+ if (!isShopperToken(id)) return true;
152
+ if (!scope) return false;
153
+ try {
154
+ const db = await shopperDb();
155
+ if (!db) return false;
156
+ const revoked = await db.first(
157
+ `UPDATE shopper_sessions SET revoked_at = ?
158
+ WHERE tenant_id = ? AND stage = ? AND id = ? AND revoked_at IS NULL RETURNING id`,
159
+ now, scope.tenantId, scope.stage, await sha256Hex(id),
160
+ );
161
+ if (revoked) {
162
+ try {
163
+ const kv = await readKv("SESSION");
164
+ await kv?.delete(SESSION_PREFIX + id);
165
+ } catch {
166
+ // The durable revocation remains authoritative.
167
+ }
168
+ }
169
+ return true;
170
+ } catch {
171
+ return false;
172
+ }
173
+ }
@@ -0,0 +1,69 @@
1
+ import type { shopperVariantPrice } from "./pricing.js";
2
+
3
+ type PricedVariant = NonNullable<ReturnType<typeof shopperVariantPrice>>;
4
+
5
+ function isPricedVariant(input: unknown): input is PricedVariant {
6
+ if (typeof input !== "object" || input === null) return false;
7
+ return "id" in input && typeof input.id === "string" &&
8
+ "title" in input && typeof input.title === "string" &&
9
+ "available" in input && typeof input.available === "boolean" &&
10
+ "currency" in input && typeof input.currency === "string" &&
11
+ "price" in input && typeof input.price === "number" && Number.isFinite(input.price) &&
12
+ "compareAtPrice" in input &&
13
+ (input.compareAtPrice === null || (typeof input.compareAtPrice === "number" && Number.isFinite(input.compareAtPrice)));
14
+ }
15
+
16
+ async function readPricing(url: URL): Promise<PricedVariant[]> {
17
+ const response = await fetch(url, { credentials: "same-origin", headers: { Accept: "application/json" } });
18
+ if (!response.ok) return [];
19
+ const reply: unknown = await response.json();
20
+ if (typeof reply !== "object" || reply === null || !("ok" in reply) || reply.ok !== true ||
21
+ !("variants" in reply) || !Array.isArray(reply.variants) || !reply.variants.every(isPricedVariant)) return [];
22
+ return reply.variants;
23
+ }
24
+
25
+ export async function mountShopperPricing(region: HTMLElement): Promise<void> {
26
+ const { pricingUrl, purchaseUrl, shopperProduct, locale } = region.dataset;
27
+ const cta = region.querySelector("[data-shopper-pricing-cta]");
28
+ const template = region.querySelector<HTMLTemplateElement>("template");
29
+ const form = template?.content.querySelector("form")?.cloneNode(true) as HTMLFormElement | undefined;
30
+ const select = form?.querySelector<HTMLSelectElement>("select[name=variantId]");
31
+ const buy = form?.querySelector<HTMLButtonElement>("button[type=submit]");
32
+ const product = form?.querySelector<HTMLInputElement>("input[name=productHandle]");
33
+ const priceText = form?.querySelector<HTMLElement>("[data-shopper-price]");
34
+ if (!pricingUrl || !purchaseUrl || !shopperProduct || !cta || !form || !select || !buy || !product || !priceText) return;
35
+
36
+ try {
37
+ const url = new URL(pricingUrl, location.origin);
38
+ url.searchParams.set("handle", shopperProduct);
39
+ const variants = await readPricing(url);
40
+ if (variants.length === 0) return;
41
+ form.setAttribute("action", purchaseUrl);
42
+ product.value = shopperProduct;
43
+ if (form.dataset.shopperCompliance === "required") {
44
+ form.addEventListener("submit", event => {
45
+ if (form.dataset.complianceCleared === "1") return;
46
+ event.preventDefault();
47
+ const status = form.querySelector("[data-shopper-preflight-status]");
48
+ if (status) status.textContent = "Checkout verification is loading. Try again in a moment.";
49
+ });
50
+ }
51
+ for (const variant of variants) select.add(new Option(variant.title, variant.id));
52
+ const showSelection = () => {
53
+ const item = variants[select.selectedIndex];
54
+ if (!item) return;
55
+ const formatter = new Intl.NumberFormat(locale, { style: "currency", currency: item.currency });
56
+ const price = formatter.format(item.price);
57
+ const original = item.compareAtPrice !== null && item.compareAtPrice > item.price
58
+ ? `${formatter.format(item.compareAtPrice)} · ` : "";
59
+ priceText.textContent = `${original}${price}`;
60
+ buy.disabled = !item.available;
61
+ };
62
+ showSelection();
63
+ select.addEventListener("change", showSelection);
64
+ cta.replaceWith(form);
65
+ region.parentElement?.querySelector("[data-guest-variant-selector]")?.setAttribute("hidden", "");
66
+ } catch {
67
+ // The sign-in action stays available when live pricing cannot be loaded.
68
+ }
69
+ }
@@ -16,11 +16,12 @@ const VERSION = "v1";
16
16
  const encoder = new TextEncoder();
17
17
 
18
18
  /** The public forms a submit token can be issued for. */
19
- export type ContactFormKind = "contact" | "bulk-quote";
19
+ export type ContactFormKind = "contact" | "bulk-quote" | "wholesale-application";
20
20
 
21
21
  const MAC_PREFIX: Record<ContactFormKind, string> = {
22
22
  contact: "contact-form",
23
23
  "bulk-quote": "bulk-quote-form",
24
+ "wholesale-application": "wholesale-application-form",
24
25
  };
25
26
 
26
27
  export function isContactFormKind(value: unknown): value is ContactFormKind {
@@ -86,6 +86,8 @@ export interface ReserveInput {
86
86
  holds: readonly ReserveHold[];
87
87
  /** Trusted server snapshot committed in the same transaction as the stock holds. */
88
88
  admissionStatement?: SqlStatement;
89
+ /** Scoped server-side authority that must still hold when the reservation begins. */
90
+ authorizationGuard?: SqlStatement;
89
91
  /** Immutable provider identity, claimed atomically with its receipt and holds. */
90
92
  providerCart?: { provider: "foxycart"; id: string; digest: string; expectedAuthorizationId?: string };
91
93
  /**
@@ -97,7 +99,7 @@ export interface ReserveInput {
97
99
 
98
100
  export type ReserveResult =
99
101
  | { ok: true; authorizationId: string; repeated: boolean; expiresAt: string }
100
- | { ok: false; finding: "caller-replay" | "stock-unavailable" | "malformed-request" | "provider-cart-conflict" | "admission-consumed" | "admission-expired" };
102
+ | { ok: false; finding: "caller-replay" | "stock-unavailable" | "malformed-request" | "provider-cart-conflict" | "admission-consumed" | "admission-expired" | "shopper-checkout-proof-unavailable" };
101
103
 
102
104
  export interface PolicyResult {
103
105
  released: number;
@@ -347,20 +349,21 @@ export async function reserveAllocation(runner: StatementRunner, input: ReserveI
347
349
  const seenAt = `${input.now}|${crypto.randomUUID()}`;
348
350
  const holds = [...input.holds].sort((left, right) => left.sku.localeCompare(right.sku) || left.locationId.localeCompare(right.locationId));
349
351
  const sync = allocationSync({ tenantId: input.tenantId, stage: input.stage, now: input.now, scope: itemScope(holds) });
352
+ const guard = input.authorizationGuard;
350
353
  const statements: SqlStatement[] = [
351
354
  {
352
355
  sql: `INSERT INTO scrappy_caller_replay (tenant_id, stage, issuer, jti, seen_at)
353
- VALUES (?, ?, ?, ?, ?)
356
+ SELECT ?, ?, ?, ?, ? WHERE ${guard ? `EXISTS (${guard.sql})` : "1"}
354
357
  ON CONFLICT DO NOTHING
355
358
  RETURNING jti`,
356
- params: [input.tenantId, input.stage, input.issuer, input.jti, seenAt],
359
+ params: [input.tenantId, input.stage, input.issuer, input.jti, seenAt, ...(guard?.params ?? [])],
357
360
  },
358
361
  {
359
362
  sql: `INSERT INTO scrappy_commerce_orders (
360
363
  tenant_id, stage, order_id, source, source_order_id, currency, placed_at,
361
364
  payment_state, compliance_state, stock_state, fulfillment_state, label_state,
362
365
  amount_minor, event_version
363
- ) VALUES (?, ?, ?, 'scrappy', ?, ?, ?, 'pending', 'UNKNOWN', 'unallocated', 'held', 'none', ?, 1)
366
+ ) SELECT ?, ?, ?, 'scrappy', ?, ?, ?, 'pending', 'UNKNOWN', 'unallocated', 'held', 'none', ?, 1 WHERE ${guard ? "changes() = 1" : "1"}
364
367
  ON CONFLICT DO NOTHING
365
368
  RETURNING order_id`,
366
369
  params: [input.tenantId, input.stage, input.orderId, input.orderId, input.currency, input.now, input.amountMinor],
@@ -472,7 +475,7 @@ export async function reserveAllocation(runner: StatementRunner, input: ReserveI
472
475
  if (authRows.length > 0) {
473
476
  return { ok: true, authorizationId: input.orderId, repeated: false, expiresAt: input.expiresAt };
474
477
  }
475
- if (replayRows.length === 0) return { ok: false, finding: "caller-replay" };
478
+ if (replayRows.length === 0) return { ok: false, finding: guard ? "shopper-checkout-proof-unavailable" : "caller-replay" };
476
479
  const existing = selected[0];
477
480
  if (existing) {
478
481
  return {
@@ -1,34 +1,13 @@
1
- /**
2
- * Shopper membership eligibility — the request-scoped seam that resolves whether
3
- * the current shopper is a member, and which tier.
4
- *
5
- * Phase 1 storefronts have NO shopper-login/account source (member accounts are
6
- * a Phase-2 managed-checkout capability), so this resolves anonymous
7
- * (`{ isMember: false }`) by default. The pricing engine in
8
- * `@tot/public-runtime` is real and unit-tested regardless; member pricing only
9
- * RENDERS once a real eligibility signal flows through here.
10
- *
11
- * Production wires the signal from the resolved account claim (e.g. a
12
- * member-tier cookie/JWT set by the Phase-2 login), so the whole storefront gets
13
- * member pricing by threading one function — no per-page auth logic.
14
- */
1
+ /** Resolve membership pricing from a server-verified shopper tier. */
15
2
  import type { MemberContext } from "@tot/public-runtime";
16
3
  import { ANONYMOUS_MEMBER } from "@tot/public-runtime";
17
4
 
18
- /**
19
- * The minimal membership signal a request carries. Phase 1 never populates it;
20
- * production derives it from the shopper's resolved account (a member-tier
21
- * claim). Kept tiny + framework-free so it is trivially testable.
22
- */
5
+ /** The tier read from the shopper's live, approved account. */
23
6
  export interface MembershipSignal {
24
7
  /** The shopper's membership tier id, if they are a signed-in member. */
25
8
  memberTierId?: string | null;
26
9
  }
27
10
 
28
- /**
29
- * Resolve the shopper's {@link MemberContext} from an optional membership signal.
30
- * No signal (Phase 1, or an anonymous shopper) → non-member.
31
- */
32
11
  export function resolveMemberContext(signal?: MembershipSignal | null): MemberContext {
33
12
  if (signal?.memberTierId) {
34
13
  return { isMember: true, tierId: signal.memberTierId };
@@ -74,12 +74,19 @@ export async function verifyCdnForward(
74
74
  * CloudFront edge, shared by every visitor behind it. Otherwise — a Cloudflare-served
75
75
  * request, or a viewer-IP header with no valid forward proof — it is `cf-connecting-ip`,
76
76
  * which Cloudflare sets and a client cannot. The first `x-forwarded-for` hop is the
77
- * local dev fallback. Never throws.
77
+ * local dev fallback. With a trusted source selected by routing, only that source
78
+ * is accepted and a missing or malformed address returns `unknown`.
78
79
  */
79
- export async function requestClientIp(headers: Headers, cdnOriginSecret: string | undefined): Promise<string> {
80
- const forward = await verifyCdnForward(headers, cdnOriginSecret);
80
+ export async function requestClientIp(
81
+ headers: Headers,
82
+ cdnOriginSecret: string | undefined,
83
+ trustedSource?: "cloudfront" | "cloudflare",
84
+ ): Promise<string> {
85
+ const forward = trustedSource === "cloudflare" ? null : await verifyCdnForward(headers, cdnOriginSecret);
81
86
  if (forward?.viewerIp) return forward.viewerIp;
87
+ if (trustedSource === "cloudfront") return "unknown";
82
88
  const cf = headers.get("cf-connecting-ip");
89
+ if (trustedSource === "cloudflare") return cf && IP_SHAPE.test(cf) ? cf : "unknown";
83
90
  if (cf) return cf;
84
91
  const xff = headers.get("x-forwarded-for");
85
92
  if (xff) return xff.split(",")[0]!.trim();
@@ -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,