@tokenoftrust/storefront-runner 8.0.0 → 8.1.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 (22) hide show
  1. package/apps/storefront/src/components/catalog/storefront/ProductCard.astro +15 -7
  2. package/apps/storefront/src/components/publication/storefront/islands/CatalogQueryView.tsx +6 -1
  3. package/apps/storefront/src/layouts/Layout.astro +39 -1
  4. package/apps/storefront/src/lib/checkout/commerce/finalCartAuthorization.ts +4 -4
  5. package/apps/storefront/src/lib/compliance/shopper/statePickerClient.ts +622 -67
  6. package/apps/storefront/src/lib/compliance/shopper/staticEligibilityArtifact.ts +182 -0
  7. package/apps/storefront/src/lib/compliance/shopper/staticEligibilityPointerGate.ts +13 -0
  8. package/apps/storefront/src/middleware/routeBranch.ts +1 -0
  9. package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +45 -28
  10. package/apps/storefront/src/pages/api/compliance/preflight.ts +162 -66
  11. package/apps/storefront/src/pages/eligibility.json.ts +23 -0
  12. package/package.json +1 -1
  13. package/packages/cli/src/publication-spaces.mjs +1 -1
  14. package/packages/public-runtime/package.json +1 -0
  15. package/packages/public-runtime/schemas/publication-space/v1/manifest.schema.json +1 -1
  16. package/packages/public-runtime/schemas/publication-space/v1/normalized-mount.schema.json +1 -1
  17. package/packages/public-runtime/src/compliance/evaluate.ts +13 -0
  18. package/packages/public-runtime/src/compliance/state-directory.ts +16 -2
  19. package/packages/public-runtime/src/compliance/static-eligibility.d.mts +92 -0
  20. package/packages/public-runtime/src/compliance/static-eligibility.mjs +394 -0
  21. package/packages/public-runtime/src/declared-tenant-config.mjs +1 -1
  22. package/packages/public-runtime/src/publication-space.ts +1 -0
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Worker-side producer of the static shopper-eligibility artifact
3
+ * (`@tot/public-runtime/compliance/static-eligibility`, ADR 0013 + ADR 0047).
4
+ *
5
+ * Projects the tenant's declarative rule pack (merged stricter-only with the tenant's overlays) and
6
+ * its catalog's product facts into the public-only artifact a published page filters on in the
7
+ * browser. The projection reads the rule pack's own data (regions, ZIP prefixes, registry
8
+ * predicates) and the engine's own subject matcher, so the static layer cannot drift from the
9
+ * authoritative checkout evaluation (`POST /api/compliance/preflight`), which stays the enforcement
10
+ * seam.
11
+ *
12
+ * Fail-closed projection: a declared-but-empty or malformed licensed footprint restricts every
13
+ * state, exactly as `evaluateCartCompliance` does; an allow-list that names no valid US state is
14
+ * encoded `[]` (ships nowhere), never dropped to "no restriction".
15
+ */
16
+ import type { CatalogProduct, ComplianceRule, ComplianceRuleset, TenantConfig } from "@tot/public-runtime";
17
+ import {
18
+ deriveProductProfile,
19
+ mergeTenantOverrides,
20
+ normalizeRegionCode,
21
+ ruleSubjectOutcome,
22
+ unconditionalProhibitedRegions,
23
+ } from "@tot/public-runtime";
24
+ import {
25
+ extractDirectoryStatesFromTags,
26
+ normalizeUsStateCode,
27
+ US_STATE_OPTIONS,
28
+ } from "@tot/public-runtime/compliance/state-directory";
29
+ import {
30
+ buildStaticEligibilityArtifact,
31
+ staticEligibilityRevisionSource,
32
+ type StaticEligibilityArtifact,
33
+ type StaticEligibilityZipScope,
34
+ } from "@tot/public-runtime/compliance/static-eligibility";
35
+ import { COMPLIANCE_RULE_PROFILES } from "@/config/compliance/rulesets";
36
+ import { resolveTenantRuleset } from "@/lib/compliance/enforcement";
37
+
38
+ type EligibilityTenant = Pick<TenantConfig, "tenant_id" | "compliance">;
39
+
40
+ /** Ruleset version used when a tenant declares state eligibility without a rule profile. */
41
+ export const DECLARED_ELIGIBILITY_RULESET_VERSION = "declared-state-eligibility:1";
42
+
43
+ /**
44
+ * The provenance `rulesetVersion` for a tenant, or `null` when the tenant has no eligibility
45
+ * surface at all (no rule profile and no declared state eligibility). Synchronous so the layout can
46
+ * decide whether to emit the page pointer without resolving the ruleset.
47
+ */
48
+ export function staticEligibilityRulesetVersion(tenant: EligibilityTenant): string | null {
49
+ const profile = tenant.compliance?.ruleProfile;
50
+ if (profile) {
51
+ const build = COMPLIANCE_RULE_PROFILES[profile];
52
+ if (!build) return null;
53
+ const pack = build(tenant.tenant_id).rulePack;
54
+ return `${pack.packId}:${pack.version}`;
55
+ }
56
+ return tenant.compliance?.stateEligibility ? DECLARED_ELIGIBILITY_RULESET_VERSION : null;
57
+ }
58
+
59
+ interface RegistryPredicateRule {
60
+ rule: ComplianceRule;
61
+ regions: string[];
62
+ jurisdiction: string;
63
+ zipPrefixes: string[];
64
+ }
65
+
66
+ /** The rules whose effect is a registry-listing requirement, with their destination and jurisdiction. */
67
+ function registryRules(rules: readonly ComplianceRule[]): RegistryPredicateRule[] {
68
+ const out: RegistryPredicateRule[] = [];
69
+ for (const rule of rules) {
70
+ const effect = rule.effect;
71
+ if (effect.kind !== "require_predicate") continue;
72
+ const predicate = effect.predicate as { field?: unknown; op?: unknown; value?: unknown };
73
+ if (predicate.field !== "catalog.registryListings" || predicate.op !== "registry_listed" ||
74
+ typeof predicate.value !== "string") continue;
75
+ const destination = rule.when?.destination;
76
+ const regions = (destination?.regions ?? []).map((r) => normalizeRegionCode(r)).filter(Boolean);
77
+ if (regions.length === 0) continue;
78
+ out.push({
79
+ rule,
80
+ regions,
81
+ jurisdiction: predicate.value,
82
+ zipPrefixes: [...(destination?.zipPrefixes ?? [])],
83
+ });
84
+ }
85
+ return out;
86
+ }
87
+
88
+ const ALL_STATE_CODES = US_STATE_OPTIONS.map((state) => state.code);
89
+
90
+ /**
91
+ * Build the artifact for `tenant` over its active `products`, or `null` when the tenant has no
92
+ * eligibility surface. `catalogRevision` is the content hash of the eligibility inputs.
93
+ */
94
+ export async function buildTenantStaticEligibility(
95
+ tenant: EligibilityTenant,
96
+ products: readonly CatalogProduct[],
97
+ ): Promise<StaticEligibilityArtifact | null> {
98
+ const rulesetVersion = staticEligibilityRulesetVersion(tenant);
99
+ if (!rulesetVersion) return null;
100
+
101
+ const declared = tenant.compliance?.stateEligibility;
102
+ const ruleset: ComplianceRuleset | null = tenant.compliance?.ruleProfile
103
+ ? await resolveTenantRuleset(tenant)
104
+ : null;
105
+ const merged = ruleset ? mergeTenantOverrides(ruleset.rulePack, ruleset.tenantOverrides) : null;
106
+ const rules = merged?.rules ?? [];
107
+
108
+ const restricted = new Set<string>();
109
+ for (const code of declared?.restrictedStates ?? []) {
110
+ const normalized = normalizeUsStateCode(code);
111
+ if (normalized) restricted.add(normalized);
112
+ }
113
+ if (ruleset) {
114
+ for (const code of unconditionalProhibitedRegions(ruleset)) {
115
+ const normalized = normalizeUsStateCode(code);
116
+ if (normalized) restricted.add(normalized);
117
+ }
118
+ }
119
+
120
+ // A footprint the engine fails closed on (declared but empty, or with a malformed entry) refuses
121
+ // every destination here too.
122
+ const footprintDeclared = merged ? merged.licensedStates !== null : Array.isArray(declared?.eligibleStates);
123
+ const licensed = merged?.licensedStates ?? declared?.eligibleStates ?? [];
124
+ const eligibleStates = licensed.map((code) => normalizeUsStateCode(code)).filter((code): code is string => code !== null);
125
+ if (footprintDeclared && (eligibleStates.length === 0 || merged?.licensedStatesInvalid)) {
126
+ for (const code of ALL_STATE_CODES) restricted.add(code);
127
+ }
128
+
129
+ const registry = registryRules(rules);
130
+ const zipScopes: StaticEligibilityZipScope[] = registry
131
+ .filter((entry) => entry.zipPrefixes.length > 0)
132
+ .flatMap((entry) => entry.regions.map((region) => ({
133
+ region,
134
+ jurisdiction: entry.jurisdiction,
135
+ zipPrefixes: entry.zipPrefixes,
136
+ })));
137
+ const stateRegistry = registry.filter((entry) => entry.zipPrefixes.length === 0);
138
+
139
+ const entries = products.map((product) => {
140
+ const profile = deriveProductProfile(product);
141
+ const reading = profile.catalogFacts.registryListings;
142
+ const registryStates = new Set<string>();
143
+ for (const entry of [...stateRegistry, ...registry.filter((e) => e.zipPrefixes.length > 0)]) {
144
+ // `indeterminate` (an unread fact) is held to the registry: fail closed.
145
+ if (ruleSubjectOutcome(entry.rule, profile) === "false") continue;
146
+ for (const region of entry.regions) {
147
+ const code = normalizeUsStateCode(region);
148
+ if (code) registryStates.add(code);
149
+ }
150
+ }
151
+ const allowed = profile.allowedRegions === null
152
+ ? null
153
+ : profile.allowedRegions.map((code) => normalizeUsStateCode(code)).filter((code): code is string => code !== null);
154
+ return {
155
+ handle: product.handle,
156
+ allowedStates: allowed,
157
+ restrictedStates: profile.restrictedRegions.map((code) => normalizeUsStateCode(code)).filter((code): code is string => code !== null),
158
+ directoryStates: extractDirectoryStatesFromTags(product.tags),
159
+ registryStates: [...registryStates],
160
+ registryListings: reading.state === "known" ? { ...reading.value } as Record<string, string> : null,
161
+ };
162
+ });
163
+
164
+ const body = buildStaticEligibilityArtifact({
165
+ provenance: { tenant: tenant.tenant_id, catalogRevision: "pending", rulesetVersion },
166
+ rules: {
167
+ directoryStates: declared?.directoryStates ?? [],
168
+ restrictedStates: [...restricted],
169
+ eligibleStates,
170
+ zipScopes,
171
+ },
172
+ products: entries,
173
+ });
174
+ const revision = (await sha256Hex(staticEligibilityRevisionSource(body))).slice(0, 32);
175
+ return { ...body, provenance: { ...body.provenance, catalogRevision: revision } };
176
+ }
177
+
178
+ /** sha256 hex over UTF-8 text with WebCrypto (the Worker and the browser both have it). */
179
+ async function sha256Hex(text: string): Promise<string> {
180
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
181
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
182
+ }
@@ -0,0 +1,13 @@
1
+ import { closedCatalogPath } from "@tot/public-runtime/declared-tenant-config";
2
+
3
+ /**
4
+ * Whether a page may carry the static-eligibility pointer, status shell and boot script.
5
+ *
6
+ * A closed store serves the artifact only to an admitted shopper (`closedCatalogPath` "admit"):
7
+ * an unadmitted visitor is redirected to sign-in. So its public "allow" routes (home, content
8
+ * pages) must not fetch it, or they would show the fail-closed unavailable banner. Every other
9
+ * store carries the pointer on every page.
10
+ */
11
+ export function staticEligibilityPointerAllowed(accessMode: string, path: string): boolean {
12
+ return accessMode !== "closed_store" || closedCatalogPath(path) === "admit";
13
+ }
@@ -84,6 +84,7 @@ export const PLATFORM_PUBLIC_DISCOVERY_PATHS = [
84
84
  */
85
85
  export const PLATFORM_PUBLIC_APP_ROUTE_PREFIXES = [
86
86
  "/catalog-index.json",
87
+ "/eligibility.json",
87
88
  "/collections",
88
89
  "/products",
89
90
  "/saved",
@@ -2,14 +2,14 @@
2
2
  import type { APIContext } from "astro";
3
3
  import { createLocalJWKSet, decodeProtectedHeader, jwtVerify, type JSONWebKeySet } from "jose";
4
4
  import {
5
- commerceTenantId, isRegulated, totalsMatch, shippingMinorFor, isContentVersionId, catalogPinDigestFinding, cartLineKey,
5
+ commerceTenantId, deriveProductProfile, isRegulated, isRegulatedProfile, normalizeRegionCode, totalsMatch, shippingMinorFor, isContentVersionId, catalogPinDigestFinding, cartLineKey,
6
6
  EXCISE_REASONS, type CallerToken, type CatalogProduct, type CatalogVariant, type CommerceEvidence, type CommerceEvidenceProvenance,
7
7
  type CommerceProviderCartSnapshot, type ExciseCarrier, type ExciseEvidenceReason, type FinalCartBinding, type TenantConfig,
8
8
  } from "@tot/public-runtime";
9
9
  import { skuFromToken } from "@tot/public-runtime/sku";
10
10
  import { fromD1 } from "@/lib/catalog/d1/catalog.js";
11
11
  import { readD1, readEnv, readKv } from "@/lib/publication/shared/env";
12
- import { CHECKOUT_ADMISSION_TTL_MS, FULFILLMENT_EVIDENCE_TTL_MS, evaluateFinalCart, type RefusedLine, type SeamView } from "@/lib/checkout/commerce/finalCartAuthorization.js";
12
+ import { CHECKOUT_ADMISSION_TTL_MS, FULFILLMENT_EVIDENCE_TTL_MS, RULE_BLOCK_CODES, evaluateFinalCart, type RefusedLine, type SeamView } from "@/lib/checkout/commerce/finalCartAuthorization.js";
13
13
  import { d1CommerceRunner, reserveAllocation } from "@/lib/inventory/allocations.js";
14
14
  import { readMirrorBalance, readMirrorStock, writeAvailabilityProjection } from "@/lib/inventory/mirrorStock.js";
15
15
  import { publicAvailabilityPublisher } from "@/lib/inventory/publicAvailabilityRuntime";
@@ -148,7 +148,7 @@ function readSnapshot(value: unknown): FinalCartWire | null {
148
148
  if (!d || Object.keys(d).length !== 2 || typeof d.country !== "string" || !/^[A-Z]{2}$/.test(d.country) || typeof d.region !== "string" || !/^[A-Z0-9-]{1,8}$/.test(d.region)) return null;
149
149
  if ("shipTo" in v) {
150
150
  const shipTo = readShipTo(v.shipTo);
151
- if (!shipTo || shipTo.country !== d.country || shipTo.region.toUpperCase() !== d.region) return null;
151
+ if (!shipTo || shipTo.country !== d.country || normalizeRegionCode(shipTo.region) !== normalizeRegionCode(d.region)) return null;
152
152
  v.shipTo = shipTo;
153
153
  }
154
154
  const snapshot = v as unknown as FinalCartWire;
@@ -171,9 +171,9 @@ function keyedLines(wire: CommerceProviderCartSnapshot): CommerceProviderCartSna
171
171
  * cart's verification ref goes to preflight, whose live provider re-reads its real status
172
172
  * server-side; `verified` is true only when that read satisfied the requirement.
173
173
  */
174
- async function seam(context: APIContext, snapshot: CommerceProviderCartSnapshot, selected: ReadonlyMap<string, CatalogProduct>, policy: SharedStoreEvidencePolicy): Promise<SeamView & { verified: boolean; sandbox: boolean }> {
174
+ async function seam(context: APIContext, snapshot: CommerceProviderCartSnapshot, selected: ReadonlyMap<string, CatalogProduct>, policy: SharedStoreEvidencePolicy, rawPostalCode?: string): Promise<SeamView & { verified: boolean; sandbox: boolean }> {
175
175
  const sandbox = await sandboxVerificationApplies(context.locals.tenant, snapshot);
176
- const view = await evaluateSeam(context, snapshot, selected, policy, sandbox);
176
+ const view = await evaluateSeam(context, snapshot, selected, policy, sandbox, rawPostalCode);
177
177
  return { ...view, sandbox: sandbox && view.verified };
178
178
  }
179
179
  /**
@@ -188,9 +188,26 @@ async function sandboxVerificationApplies(_tenant: TenantConfig, snapshot: Comme
188
188
  && (await readEnv("COMMERCE_DEMO_CHECKOUT_TIER")) === "test"
189
189
  && SANDBOX_CLEARED_REF.test(snapshot.verificationRef ?? "");
190
190
  }
191
- async function evaluateSeam(context: APIContext, snapshot: CommerceProviderCartSnapshot, selected: ReadonlyMap<string, CatalogProduct>, policy: SharedStoreEvidencePolicy, sandbox: boolean): Promise<SeamView & { verified: boolean }> {
192
- if (policy.rules === "off" && policy.verification === "not-required") return { status: "clear", verified: false };
191
+ function hasRegulatedCartLines(snapshot: CommerceProviderCartSnapshot, products: readonly CatalogProduct[]): boolean {
192
+ return snapshot.lines.some((line) => {
193
+ for (const product of products) {
194
+ const variant = product.variants.find((v) => cartLineKey(v) === line.sku);
195
+ if (variant) return isRegulatedProfile(deriveProductProfile(product, variant));
196
+ }
197
+ return false;
198
+ });
199
+ }
200
+ async function evaluateSeam(context: APIContext, snapshot: CommerceProviderCartSnapshot, selected: ReadonlyMap<string, CatalogProduct>, policy: SharedStoreEvidencePolicy, sandbox: boolean, rawPostalCode?: string): Promise<SeamView & { verified: boolean }> {
193
201
  const products = [...selected.values()];
202
+ const regulatedLines = hasRegulatedCartLines(snapshot, products);
203
+ const effectiveRules: "enforce" | "off" = regulatedLines ? "enforce" : policy.rules;
204
+ if (effectiveRules === "off" && policy.verification === "not-required") return { status: "clear", verified: false };
205
+ const postalCode = rawPostalCode?.trim();
206
+ const destination = {
207
+ country: snapshot.destination.country,
208
+ region: normalizeRegionCode(snapshot.destination.region),
209
+ ...(postalCode ? { postalCode } : {}),
210
+ };
194
211
  try {
195
212
  const { decision } = await evaluatePreflight({ locals: { tenant: context.locals.tenant, tot: {
196
213
  getProductByHandle: async (handle: string) => selected.get(handle) ?? null,
@@ -200,45 +217,35 @@ async function evaluateSeam(context: APIContext, snapshot: CommerceProviderCartS
200
217
  const variant = product.variants.find(v => cartLineKey(v) === line.sku)!;
201
218
  return { handle: product.handle, variantId: variant.id, sku: line.sku, quantity: line.quantity };
202
219
  }),
203
- destination: snapshot.destination,
220
+ destination,
204
221
  ...(policy.verification === "required" && snapshot.verificationRef ? { verificationRef: snapshot.verificationRef } : {}),
205
222
  ...(sandbox ? { ageAffirmed: true } : {}),
206
- }, { verification: policy.verification, rules: policy.rules });
223
+ }, { verification: policy.verification, rules: effectiveRules });
207
224
  const verified = policy.verification === "required" && decision.requirements.ageVerification === "satisfied";
208
225
  const blocks = decision.blocks;
209
226
  if (blocks.length === 0) return { status: "clear", verified };
227
+ const failedClosed = blocks.some(block => block.failedClosed === true);
210
228
  const flavors = [...new Set(blocks.flatMap(block => block.code === "flavored_prohibited" ? block.flavors ?? [] : []))];
211
- const hasRuleBlock = blocks.some(
212
- block =>
213
- block.code === "invalid_ruleset" ||
214
- block.code === "postal_code_required" ||
215
- block.code === "flavored_prohibited" ||
216
- block.code === "cooling_agent_prohibited" ||
217
- block.code === "region_prohibited" ||
218
- block.code === "registry_prohibited" ||
219
- block.code === "fact_prohibited" ||
220
- block.code === "pact_requirement_failed" ||
221
- block.code === "sku_limit_exceeded" ||
222
- block.code === "purchase_limit_exceeded",
223
- );
224
- const titleOf = (sku: string) => products.find(p => p.variants.some(v => v.sku === sku))?.title;
229
+ const hasRuleBlock = blocks.some(block => RULE_BLOCK_CODES.has(block.code));
230
+ const titleOf = (sku: string) => products.find(p => p.variants.some(v => cartLineKey(v) === sku))?.title;
225
231
  const seen = new Set<string>();
226
232
  const lines: RefusedLine[] = [];
227
233
  for (const block of blocks) {
228
- if (block.failedClosed === true || typeof block.message !== "string" || !block.message) continue;
234
+ if (typeof block.message !== "string" || !block.message) continue;
229
235
  if (hasRuleBlock && block.code.startsWith("verification_")) continue;
236
+ if (block.failedClosed === true && (block.code === "verification_unconfigured" || block.code === "ruleset_unavailable")) continue;
230
237
  const key = `${block.code}\n${block.sku ?? ""}\n${block.message}`;
231
238
  if (seen.has(key)) continue;
232
239
  seen.add(key);
233
240
  const title = block.sku ? titleOf(block.sku) : undefined;
234
241
  lines.push({ code: block.code, message: block.message, ...(block.sku ? { sku: block.sku } : {}), ...(title ? { title } : {}) });
235
242
  }
236
- return { status: "blocked", verified, failedClosed: blocks.some(block => block.failedClosed === true), codes: blocks.map(block => block.code),
243
+ return { status: "blocked", verified, failedClosed, codes: blocks.map(block => block.code),
237
244
  ...(flavors.length ? { flavors } : {}), ...(lines.length ? { lines } : {}) };
238
245
  } catch { return { status: "absent", verified: false }; }
239
246
  }
240
247
  function fullCartProduct(value: unknown, handle: string, scope: string): value is CatalogProduct {
241
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
248
+ if (!value || typeof value !== "object" || Array.isArray(value) || typeof scope !== "string" || scope.length === 0) return false;
242
249
  const product = value as CatalogProduct;
243
250
  return product.handle === handle && product.tenant_id === scope && typeof product.id === "string" && !!product.id &&
244
251
  product.status === "active" && (product.visibility === undefined || product.visibility === "public") &&
@@ -416,7 +423,11 @@ async function authorize(context: APIContext): Promise<Response> {
416
423
  if (existing && !admissionMatches(existing, snapshot)) return deny("provider-cart-changed");
417
424
  const requirements = await readCheckoutRequirements(tenant.tenant_id, contentEnv);
418
425
  if (!requirements) return deny("checkout-requirements-unreadable", 503);
419
- const policy = testStoreEvidencePolicy(requirements, isRegulated({ compliance: tenant.compliance }));
426
+ const regulatedLines = hasRegulatedCartLines(snapshot, products);
427
+ const policy = testStoreEvidencePolicy(
428
+ requirements,
429
+ isRegulated({ compliance: tenant.compliance }) || regulatedLines,
430
+ );
420
431
  // A declared mirror provider is admitted only against a fresh positive balance. An undeclared
421
432
  // tenant with no movements records stock as `not-required`. A non-positive balance already refused.
422
433
  const stockTracked = tenant.inventory?.provider === "mirror";
@@ -450,7 +461,13 @@ async function authorize(context: APIContext): Promise<Response> {
450
461
  : { requirement: "not-required", state: "not-required", source: "tenant-inventory-undeclared", policyRevision: "untracked-v1", expiresAt: evidenceExpiresAt };
451
462
  const presented: FinalCartBinding = { tenantId: snapshot.tenantId, stage: snapshot.stage, currency: snapshot.currency, lines: snapshot.lines,
452
463
  destinationDigest: snapshot.destinationDigest, verificationExpiresAt: expiresAt, taxExpiresAt: expiresAt };
453
- const seamView = await seam(authorityContext, snapshot, selected, orgKyb ? { ...policy, verification: "not-required" } : policy);
464
+ const seamView = await seam(
465
+ authorityContext,
466
+ snapshot,
467
+ selected,
468
+ orgKyb ? { ...policy, verification: "not-required" } : policy,
469
+ shipTo?.postalCode,
470
+ );
454
471
  let taxReason: ExciseEvidenceReason | undefined;
455
472
  if (policy.tax === "required") {
456
473
  const hasProducer = checkoutStoreHasExciseProducer(await resolveTenantCommerce(tenant));
@@ -20,8 +20,11 @@ import { hasShopperOrgKyb } from "@/lib/customers/accounts/orgKyb";
20
20
  import { shopperDb, type ScopedShopper } from "@/lib/customers/accounts/session";
21
21
  import { resolveShopperAccessPolicy } from "@tot/public-runtime/declared-tenant-config";
22
22
  import {
23
+ cartLineKey,
23
24
  deriveProductProfile,
24
25
  evaluateCartCompliance,
26
+ isRegulatedProfile,
27
+ normalizeRegionCode,
25
28
  type CartComplianceLine,
26
29
  type ShipDestination,
27
30
  type VerificationState,
@@ -134,18 +137,35 @@ function normalizeVerification(
134
137
  };
135
138
  }
136
139
 
137
- function normalizeDestination(
138
- d: PreflightBody["destination"],
139
- ): ShipDestination | null {
140
- if (!d || typeof d !== "object") return null;
141
- const region = String(d.region ?? "").trim();
142
- const country = String(d.country ?? "US").trim() || "US";
143
- if (!region) return null;
140
+ type DestinationParseResult =
141
+ | { ok: true; destination: ShipDestination | null }
142
+ | { ok: false };
143
+
144
+ function parseDestination(d: PreflightBody["destination"]): DestinationParseResult {
145
+ if (d === undefined || d === null) return { ok: true, destination: null };
146
+ if (typeof d !== "object" || Array.isArray(d)) return { ok: false };
147
+ if (d.country !== undefined && typeof d.country !== "string") return { ok: false };
148
+ if (d.region !== undefined && typeof d.region !== "string") return { ok: false };
149
+ if (d.postalCode !== undefined && typeof d.postalCode !== "string") return { ok: false };
150
+ const country = (typeof d.country === "string" ? d.country.trim().toUpperCase() : "") || "US";
151
+ const region = typeof d.region === "string" ? normalizeRegionCode(d.region) : "";
152
+ if (!/^[A-Z]{2}$/.test(country)) return { ok: false };
153
+ const regionPattern = country === "US" ? /^[A-Z]{2}$/ : /^[A-Z0-9-]{1,8}$/;
154
+ if (!region || !regionPattern.test(region)) return { ok: false };
155
+ let postalCode: string | undefined;
156
+ if (typeof d.postalCode === "string") {
157
+ if (/[\p{C}]/u.test(d.postalCode)) return { ok: false };
158
+ const trimmed = d.postalCode.trim();
159
+ if (trimmed.length > 20) return { ok: false };
160
+ if (trimmed.length > 0) postalCode = trimmed;
161
+ }
144
162
  return {
145
- region,
146
- country,
147
- postalCode:
148
- typeof d.postalCode === "string" ? d.postalCode.trim() : undefined,
163
+ ok: true,
164
+ destination: {
165
+ region,
166
+ country,
167
+ ...(postalCode ? { postalCode } : {}),
168
+ },
149
169
  };
150
170
  }
151
171
 
@@ -283,17 +303,13 @@ function withProviderCleared(ruleset: ComplianceRuleset): ComplianceRuleset {
283
303
  export async function POST(context: APIContext): Promise<Response> {
284
304
  const access = await shopperPurchaseAccess(context);
285
305
  if (!access.ok) return access.response;
286
- const regulated = isRegulatedTenant(context.locals.tenant);
287
306
 
288
307
  let body: PreflightBody;
289
308
  try {
290
309
  body = (await context.request.json()) as PreflightBody;
291
310
  if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("Invalid preflight body");
292
311
  } catch {
293
- // A regulated tenant must never proceed on an unreadable request.
294
- return regulated
295
- ? json({ decision: blockedDecision("Malformed preflight request.") }, 400)
296
- : json({ decision: evaluateEmpty() });
312
+ return json({ decision: blockedDecision("Malformed preflight request."), gate: "required" }, 400);
297
313
  }
298
314
 
299
315
  // The shared test store applies the store's own saved requirements, computed here from the
@@ -318,9 +334,13 @@ export async function POST(context: APIContext): Promise<Response> {
318
334
  });
319
335
  // A cleared, age-affirmed add-to-cart with no shipping address yet already carries its minted
320
336
  // verification ref, so it needs no pre-cart dialog; the destination is judged at checkout.
321
- const clearedBeforeAddress = body.ageAffirmed === true && !normalizeDestination(body.destination) &&
337
+ const clearedBeforeAddress = body.ageAffirmed === true && (body.destination === undefined || body.destination === null) &&
322
338
  result.decision.status === "clear" && result.verification?.status === "conditions_met";
323
- const gate = !orgKyb && complianceGateRequiredFor(policy) && !clearedBeforeAddress ? "required" : "not-required";
339
+ const gate =
340
+ result.decision.status !== "clear" ||
341
+ (!orgKyb && complianceGateRequiredFor(policy) && !clearedBeforeAddress)
342
+ ? "required"
343
+ : "not-required";
324
344
  logPreflightDecision(result.decision);
325
345
  return json({ ...result, gate });
326
346
  }
@@ -367,6 +387,34 @@ export interface PreflightResult {
367
387
  verification?: LiveVerificationMeta;
368
388
  }
369
389
 
390
+ function matchesTenantScope(
391
+ scope: string | undefined,
392
+ product: { tenant_id?: unknown },
393
+ variant: { tenant_id?: unknown },
394
+ ): boolean {
395
+ if (scope !== undefined) {
396
+ if (typeof scope !== "string" || scope.trim().length === 0) return false;
397
+ if (product.tenant_id !== scope) return false;
398
+ return variant.tenant_id === undefined || variant.tenant_id === scope;
399
+ }
400
+ return product.tenant_id === undefined && variant.tenant_id === undefined;
401
+ }
402
+
403
+ function resolveProductVariant<T extends { id: string; sku?: string; tenant_id?: unknown }>(
404
+ variants: readonly T[] | undefined,
405
+ variantId: string | undefined,
406
+ sku: string | undefined,
407
+ ): T | null {
408
+ if (!Array.isArray(variants) || variants.length === 0) return null;
409
+ const matches = variants.filter((variant) => {
410
+ const idOk = variantId ? variant.id === variantId : true;
411
+ const skuOk = sku ? (variant.sku === sku || cartLineKey(variant) === sku) : true;
412
+ return idOk && skuOk;
413
+ });
414
+ if (!variantId && !sku) return variants.length === 1 ? variants[0]! : null;
415
+ return matches.length === 1 ? matches[0]! : null;
416
+ }
417
+
370
418
  /** The preflight decision for `body`, evaluated server-side against the tenant's ruleset. */
371
419
  export async function evaluatePreflight(
372
420
  context: APIContext,
@@ -376,15 +424,108 @@ export async function evaluatePreflight(
376
424
  const { tenant, tot } = context.locals;
377
425
  const regulated = isRegulatedTenant(tenant);
378
426
 
427
+ if (body.lines !== undefined && !Array.isArray(body.lines)) {
428
+ return {
429
+ decision: blockedDecision("Preflight line items must be provided as an array."),
430
+ };
431
+ }
432
+
433
+ const destParsed = parseDestination(body.destination);
434
+ if (!destParsed.ok) {
435
+ return {
436
+ decision: blockedDecision("Shipping destination is invalid or incomplete for compliance evaluation."),
437
+ };
438
+ }
439
+ const destination = destParsed.destination;
440
+
379
441
  let ruleset = await resolveTenantRuleset(tenant);
380
442
  if (ruleset && options.verification) {
381
443
  ruleset = { ...ruleset, verification: { ...ruleset.verification, required: options.verification === "required" } };
382
444
  }
383
- const rulesOff = options.rules === "off";
384
445
  let verification = normalizeVerification(body.verification);
385
- const destination = normalizeDestination(body.destination);
386
446
  let liveVerification: LiveVerificationMeta | undefined;
387
447
 
448
+ // Resolve each line's compliance profile SERVER-SIDE from the catalog before enforcing
449
+ // runtime rules so regulated-profile lines always trigger rule evaluation.
450
+ const lines: CartComplianceLine[] = [];
451
+ for (const raw of body.lines ?? []) {
452
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || typeof raw.handle !== "string") {
453
+ return {
454
+ decision: blockedDecision("Each line item must specify a valid product handle."),
455
+ };
456
+ }
457
+ const handle = raw.handle.trim();
458
+ if (!handle) {
459
+ return {
460
+ decision: blockedDecision("Each line item must specify a valid product handle."),
461
+ };
462
+ }
463
+ if (
464
+ (raw.variantId !== undefined && typeof raw.variantId !== "string") ||
465
+ (raw.sku !== undefined && typeof raw.sku !== "string")
466
+ ) {
467
+ return {
468
+ decision: blockedDecision("Product variant identifier is invalid for compliance evaluation."),
469
+ };
470
+ }
471
+ if (
472
+ raw.quantity !== undefined &&
473
+ (typeof raw.quantity !== "number" || !Number.isFinite(raw.quantity) || !Number.isSafeInteger(raw.quantity) || raw.quantity < 1)
474
+ ) {
475
+ return {
476
+ decision: blockedDecision("Line item quantity must be a positive integer."),
477
+ };
478
+ }
479
+ const quantity = raw.quantity ?? 1;
480
+
481
+ let product: Awaited<ReturnType<typeof tot.getProductByHandle>> | null;
482
+ try {
483
+ product = await tot.getProductByHandle(handle);
484
+ } catch {
485
+ return {
486
+ decision: blockedDecision("Product could not be resolved for compliance evaluation."),
487
+ };
488
+ }
489
+ if (
490
+ !product ||
491
+ typeof product.handle !== "string" ||
492
+ !product.handle ||
493
+ (product.status !== undefined && product.status !== "active") ||
494
+ (product.visibility !== undefined && product.visibility !== "public")
495
+ ) {
496
+ return {
497
+ decision: blockedDecision("Product could not be resolved for compliance evaluation."),
498
+ };
499
+ }
500
+
501
+ const variantId = typeof raw.variantId === "string" && raw.variantId.trim() ? raw.variantId.trim() : undefined;
502
+ const rawSku = typeof raw.sku === "string" && raw.sku.trim() ? raw.sku.trim() : undefined;
503
+ const variant = resolveProductVariant(product.variants, variantId, rawSku);
504
+ if (!variant) {
505
+ return {
506
+ decision: blockedDecision("Product variant could not be resolved for compliance evaluation."),
507
+ };
508
+ }
509
+ if (!matchesTenantScope(tenant.tot_data_scope, product, variant)) {
510
+ return {
511
+ decision: blockedDecision("Product is outside the store catalog scope."),
512
+ };
513
+ }
514
+
515
+ const profile = deriveProductProfile(product, variant);
516
+ const resolvedSku = cartLineKey(variant) || product.handle;
517
+ lines.push({
518
+ sku: resolvedSku,
519
+ quantity,
520
+ profile,
521
+ title: product.title,
522
+ });
523
+ }
524
+
525
+ const regulatedLines = lines.some((line) => isRegulatedProfile(line.profile));
526
+ const effectiveRegulated = regulated || regulatedLines;
527
+ const rulesOff = options.rules === "off" && !effectiveRegulated;
528
+
388
529
  // LIVE provider: the decision is made here, from a real server-side API call.
389
530
  // The client-supplied `verification` field is DISCARDED (it is a shopper input,
390
531
  // not evidence) and the affirmation shortcut below is unreachable — "tot" is
@@ -417,43 +558,9 @@ export async function evaluatePreflight(
417
558
  verification = { outcome: "verified", verifiedAge: ruleset.verification.minAge };
418
559
  }
419
560
 
420
- // Resolve each line's compliance profile SERVER-SIDE from the catalog.
421
- const lines: CartComplianceLine[] = [];
422
- for (const raw of body.lines ?? []) {
423
- if (!raw || typeof raw.handle !== "string" || !raw.handle) continue;
424
- const quantity =
425
- typeof raw.quantity === "number" && raw.quantity > 0
426
- ? Math.floor(raw.quantity)
427
- : 1;
428
- const product = await tot.getProductByHandle(raw.handle);
429
- if (!product) {
430
- // A line we can't resolve on a regulated tenant is a fail-closed block:
431
- // we can't prove it's shippable, so we don't let it through.
432
- if (regulated && !rulesOff) {
433
- return {
434
- decision: blockedDecision(
435
- `Product "${raw.handle}" could not be resolved for compliance evaluation.`,
436
- ),
437
- };
438
- }
439
- continue;
440
- }
441
- const variant =
442
- product.variants.find(
443
- (v) => v.id === raw.variantId || (raw.sku && v.sku === raw.sku),
444
- ) ?? null;
445
- const profile = deriveProductProfile(product, variant);
446
- lines.push({
447
- sku: variant?.sku ?? raw.sku ?? product.handle,
448
- quantity,
449
- profile,
450
- title: product.title,
451
- });
452
- }
453
-
454
561
  const decision = evaluateCartCompliance({
455
562
  ruleset,
456
- regulated,
563
+ regulated: effectiveRegulated,
457
564
  lines,
458
565
  destination,
459
566
  verification,
@@ -524,17 +631,6 @@ function verificationOnly(decision: CartComplianceDecision): CartComplianceDecis
524
631
  };
525
632
  }
526
633
 
527
- /** The trivial "nothing to enforce" decision for an unregulated empty request. */
528
- function evaluateEmpty(): CartComplianceDecision {
529
- return evaluateCartCompliance({
530
- ruleset: null,
531
- regulated: false,
532
- lines: [],
533
- destination: null,
534
- verification: null,
535
- });
536
- }
537
-
538
634
  export async function GET(): Promise<Response> {
539
635
  return json({ error: "method_not_allowed" }, 405);
540
636
  }