@tokenoftrust/storefront-runner 8.0.0 → 8.0.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.
|
@@ -149,7 +149,7 @@ function evidenceFinding(evidence: CommerceEvidence | null, stockTracked: boolea
|
|
|
149
149
|
return null;
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
-
const RULE_BLOCK_CODES: ReadonlySet<string> = new Set([
|
|
152
|
+
export const RULE_BLOCK_CODES: ReadonlySet<string> = new Set([
|
|
153
153
|
"invalid_ruleset",
|
|
154
154
|
"postal_code_required",
|
|
155
155
|
"flavored_prohibited",
|
|
@@ -162,15 +162,15 @@ const RULE_BLOCK_CODES: ReadonlySet<string> = new Set([
|
|
|
162
162
|
"purchase_limit_exceeded",
|
|
163
163
|
]);
|
|
164
164
|
|
|
165
|
-
function seamRuleFinding(seam: SeamView | null): { finding: string } | null {
|
|
166
|
-
if (!seam || seam.status !== "blocked") return null;
|
|
165
|
+
export function seamRuleFinding(seam: SeamView | null): { finding: string } | null {
|
|
166
|
+
if (!seam || (seam.status !== "blocked" && seam.failedClosed !== true)) return null;
|
|
167
167
|
const code = (seam.codes ?? []).find((c) => RULE_BLOCK_CODES.has(c));
|
|
168
168
|
return code ? { finding: `verification-refused:${code}` } : null;
|
|
169
169
|
}
|
|
170
170
|
|
|
171
171
|
export function seamFinding(seam: SeamView | null): { finding: string; owner?: string } | null {
|
|
172
172
|
if (!seam || seam.status === "absent") return { finding: "verification-seam-absent" };
|
|
173
|
-
if (seam.status === "clear") return null;
|
|
173
|
+
if (seam.status === "clear" && seam.failedClosed !== true) return null;
|
|
174
174
|
const codes = (seam.codes ?? []).filter((code) => /^[a-z0-9_-]+$/.test(code));
|
|
175
175
|
if (seam.failedClosed && codes.some((code) => code === "verification_unconfigured" || code === "ruleset_unavailable")) {
|
|
176
176
|
return { finding: "verification-provider-unconfigured", owner: VERIFICATION_PROVIDER_OWNER };
|
|
@@ -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
|
|
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
|
-
|
|
192
|
-
|
|
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
|
|
220
|
+
destination,
|
|
204
221
|
...(policy.verification === "required" && snapshot.verificationRef ? { verificationRef: snapshot.verificationRef } : {}),
|
|
205
222
|
...(sandbox ? { ageAffirmed: true } : {}),
|
|
206
|
-
}, { verification: policy.verification, 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
|
-
|
|
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 (
|
|
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
|
|
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
|
|
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(
|
|
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
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
if (
|
|
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
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
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
|
-
|
|
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 &&
|
|
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 =
|
|
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
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "8.0.
|
|
3
|
+
"version": "8.0.1",
|
|
4
4
|
"license": "SEE LICENSE IN LICENSE",
|
|
5
5
|
"description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
|
|
6
6
|
"packageManager": "pnpm@11.9.0",
|