@tokenoftrust/storefront-runner 7.9.8 → 7.9.10
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.
- package/apps/storefront/src/components/compliance/storefront/islands/CheckoutComplianceGate.tsx +8 -30
- package/apps/storefront/src/config/compliance/rulesets.ts +0 -2
- package/apps/storefront/src/lib/compliance/browser/checkoutVerificationFlow.ts +20 -0
- package/apps/storefront/src/pages/api/compliance/preflight.ts +27 -2
- package/package.json +1 -1
- package/packages/public-runtime/src/compliance/evaluate.ts +4 -2
- package/packages/public-runtime/src/compliance/profile.ts +63 -2
- package/packages/public-runtime/tests/fixtures/compliance-decisions.golden.json +326 -630
package/apps/storefront/src/components/compliance/storefront/islands/CheckoutComplianceGate.tsx
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* <CheckoutComplianceGate> — browser preflight for a regulated add-to-cart submit.
|
|
3
3
|
*
|
|
4
|
-
* The dialog collects the ship-to state
|
|
4
|
+
* The dialog collects the age affirmation (never a ship-to state: that is judged at checkout), then asks
|
|
5
5
|
* `/api/compliance/preflight` whether this browser may submit the form. Only a
|
|
6
6
|
* server `clear` releases that submit. A hard block (restricted destination,
|
|
7
7
|
* flavored ban, per-order limit, failed or unconfigured verification) stops it.
|
|
@@ -23,8 +23,9 @@
|
|
|
23
23
|
* never hydrates, or scripts are disabled, the form posts on its own.
|
|
24
24
|
*/
|
|
25
25
|
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
|
|
26
|
-
import {
|
|
26
|
+
import type { CartComplianceDecision } from "@tot/public-runtime";
|
|
27
27
|
import {
|
|
28
|
+
arrivalAgeAffirmed,
|
|
28
29
|
bypassesComplianceGate,
|
|
29
30
|
carryCheckoutVerification,
|
|
30
31
|
checkoutLineFromForm,
|
|
@@ -66,7 +67,6 @@ const STORE_NOT_PUBLIC_MESSAGE =
|
|
|
66
67
|
export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props) {
|
|
67
68
|
const [pending, setPending] = useState<PendingLine | null>(null);
|
|
68
69
|
const activeDialogLine = useRef<PendingLine | null>(null);
|
|
69
|
-
const [region, setRegion] = useState("");
|
|
70
70
|
const [affirmed, setAffirmed] = useState(false);
|
|
71
71
|
const [loading, setLoading] = useState(false);
|
|
72
72
|
const [decision, setDecision] = useState<CartComplianceDecision | null>(null);
|
|
@@ -125,7 +125,7 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
|
|
|
125
125
|
body: JSON.stringify({
|
|
126
126
|
lines: [{ handle: line.handle, sku: line.sku, variantId: line.variantId, quantity: line.quantity }],
|
|
127
127
|
destination: null,
|
|
128
|
-
ageAffirmed:
|
|
128
|
+
ageAffirmed: arrivalAgeAffirmed(typeof localStorage === "undefined" ? null : localStorage, minAge),
|
|
129
129
|
}),
|
|
130
130
|
});
|
|
131
131
|
if (!res.ok) return null;
|
|
@@ -162,7 +162,7 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
|
|
|
162
162
|
}
|
|
163
163
|
document.addEventListener("submit", onSubmit, true);
|
|
164
164
|
return () => document.removeEventListener("submit", onSubmit, true);
|
|
165
|
-
}, [preflightUrl, stopPolling]);
|
|
165
|
+
}, [preflightUrl, minAge, stopPolling]);
|
|
166
166
|
|
|
167
167
|
useEffect(() => {
|
|
168
168
|
if (phase !== "collect" || !pending || pending.shopperCart) return;
|
|
@@ -251,7 +251,7 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
|
|
|
251
251
|
quantity: line.quantity,
|
|
252
252
|
},
|
|
253
253
|
],
|
|
254
|
-
destination:
|
|
254
|
+
destination: null,
|
|
255
255
|
ageAffirmed: affirmed,
|
|
256
256
|
...(opts.ref ? { verificationRef: opts.ref } : {}),
|
|
257
257
|
...(opts.includeShopper && trimmedEmail
|
|
@@ -274,7 +274,7 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
|
|
|
274
274
|
return null;
|
|
275
275
|
}
|
|
276
276
|
},
|
|
277
|
-
[preflightUrl,
|
|
277
|
+
[preflightUrl, affirmed, email, givenName, familyName],
|
|
278
278
|
);
|
|
279
279
|
|
|
280
280
|
/**
|
|
@@ -457,32 +457,10 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
|
|
|
457
457
|
Confirm before checkout
|
|
458
458
|
</h2>
|
|
459
459
|
<p class="mt-2 text-sm text-[var(--color-muted)]">
|
|
460
|
-
This is an age-restricted order. We confirm your age
|
|
461
|
-
legally ship before sending you to secure checkout.
|
|
460
|
+
This is an age-restricted order. We confirm your age before sending you to secure checkout.
|
|
462
461
|
</p>
|
|
463
462
|
|
|
464
463
|
<div class="mt-5 flex flex-col gap-4">
|
|
465
|
-
<label class="flex flex-col gap-1.5">
|
|
466
|
-
<span class="font-mono text-xs uppercase tracking-[0.12em] text-[var(--color-muted)]">
|
|
467
|
-
Ship to state
|
|
468
|
-
</span>
|
|
469
|
-
<select
|
|
470
|
-
class="rounded-[var(--radius-md)] border border-[var(--color-border)] bg-[var(--color-bg)] px-3 py-2.5 text-[var(--color-text)]"
|
|
471
|
-
value={region}
|
|
472
|
-
onChange={(e) => {
|
|
473
|
-
setRegion((e.target as HTMLSelectElement).value);
|
|
474
|
-
setDecision(null);
|
|
475
|
-
}}
|
|
476
|
-
>
|
|
477
|
-
<option value="">Select a state…</option>
|
|
478
|
-
{US_REGIONS.map((r) => (
|
|
479
|
-
<option key={r.code} value={r.code}>
|
|
480
|
-
{r.name}
|
|
481
|
-
</option>
|
|
482
|
-
))}
|
|
483
|
-
</select>
|
|
484
|
-
</label>
|
|
485
|
-
|
|
486
464
|
<label class="flex items-start gap-2.5 text-sm text-[var(--color-text)]">
|
|
487
465
|
<input
|
|
488
466
|
type="checkbox"
|
|
@@ -51,8 +51,6 @@ function vapeRuleset(tenantId: string): ComplianceRuleset {
|
|
|
51
51
|
prohibitedCarriers: ["USPS"],
|
|
52
52
|
reportingRequired: true,
|
|
53
53
|
},
|
|
54
|
-
// A conservative federal-floor per-order cap; states below can tighten it.
|
|
55
|
-
defaultPerOrderUnitLimit: 10,
|
|
56
54
|
states: [
|
|
57
55
|
// --- Full DTC no-ship (state prohibits/does not license DTC vapor shipment) ---
|
|
58
56
|
{ region: "UT", banAll: true, note: "UT restricts DTC vapor shipment" },
|
|
@@ -134,6 +134,26 @@ export function bypassesComplianceGate(res: PreflightResponse | null): boolean {
|
|
|
134
134
|
return res !== null && res.gate === "not-required" && res.decision.status === "clear";
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
/**
|
|
138
|
+
* True when the shopper already affirmed the minimum age at the arrival age gate, which stores
|
|
139
|
+
* `tot:age-affirmed:<tenant>:<minAge>` = "yes" (the bare `tot:age-affirmed` key is the dialog's own).
|
|
140
|
+
*/
|
|
141
|
+
export function arrivalAgeAffirmed(storage: Pick<Storage, "getItem" | "key" | "length"> | null, minAge?: number): boolean {
|
|
142
|
+
if (!storage) return false;
|
|
143
|
+
try {
|
|
144
|
+
if (storage.getItem("tot:age-affirmed") === "yes") return true;
|
|
145
|
+
for (let i = 0; i < storage.length; i++) {
|
|
146
|
+
const key = storage.key(i);
|
|
147
|
+
if (!key || !key.startsWith("tot:age-affirmed:")) continue;
|
|
148
|
+
if (minAge !== undefined && !key.endsWith(`:${minAge}`)) continue;
|
|
149
|
+
if (storage.getItem(key) === "yes") return true;
|
|
150
|
+
}
|
|
151
|
+
} catch {
|
|
152
|
+
/* storage disabled */
|
|
153
|
+
}
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
|
|
137
157
|
function shopperAccountUrl(preflightUrl: string, endpoint: string): string {
|
|
138
158
|
return preflightUrl.replace(/\/api\/compliance\/preflight$/, `/api/account/${endpoint}`);
|
|
139
159
|
}
|
|
@@ -313,10 +313,14 @@ export async function POST(context: APIContext): Promise<Response> {
|
|
|
313
313
|
return json({ decision: blockedDecision("Business verification is unavailable."), gate: "required" }, 503);
|
|
314
314
|
}
|
|
315
315
|
}
|
|
316
|
-
const gate = !orgKyb && complianceGateRequiredFor(policy) ? "required" : "not-required";
|
|
317
316
|
const result = await evaluatePreflight(context, body, {
|
|
318
317
|
verification: orgKyb ? "not-required" : policy?.verification, rules: policy?.rules, shopper,
|
|
319
318
|
});
|
|
319
|
+
// A cleared, age-affirmed add-to-cart with no shipping address yet already carries its minted
|
|
320
|
+
// verification ref, so it needs no pre-cart dialog; the destination is judged at checkout.
|
|
321
|
+
const clearedBeforeAddress = body.ageAffirmed === true && !normalizeDestination(body.destination) &&
|
|
322
|
+
result.decision.status === "clear" && result.verification?.status === "conditions_met";
|
|
323
|
+
const gate = !orgKyb && complianceGateRequiredFor(policy) && !clearedBeforeAddress ? "required" : "not-required";
|
|
320
324
|
logPreflightDecision(result.decision);
|
|
321
325
|
return json({ ...result, gate });
|
|
322
326
|
}
|
|
@@ -456,7 +460,16 @@ export async function evaluatePreflight(
|
|
|
456
460
|
ageAffirmed: body.ageAffirmed === true,
|
|
457
461
|
});
|
|
458
462
|
|
|
459
|
-
|
|
463
|
+
// Add-to-cart happens before any shipping address exists. On the sandbox provider an
|
|
464
|
+
// affirmed 21+ shopper with no destination is not asked for a state: the missing destination
|
|
465
|
+
// is not a block here, and the destination rules run once checkout supplies the address.
|
|
466
|
+
const preAddress =
|
|
467
|
+
!destination &&
|
|
468
|
+
body.ageAffirmed === true &&
|
|
469
|
+
!!ruleset &&
|
|
470
|
+
isSandboxVerificationProvider(ruleset.verification.provider);
|
|
471
|
+
const base = preAddress ? withoutDestinationRequired(decision) : decision;
|
|
472
|
+
const applied = rulesOff ? verificationOnly(base) : base;
|
|
460
473
|
if (
|
|
461
474
|
!liveVerification &&
|
|
462
475
|
applied.status === "clear" &&
|
|
@@ -474,6 +487,18 @@ export async function evaluatePreflight(
|
|
|
474
487
|
return liveVerification ? { decision: applied, verification: liveVerification } : { decision: applied };
|
|
475
488
|
}
|
|
476
489
|
|
|
490
|
+
/** The decision without its `destination_required` block, status recomputed; every other block stays. */
|
|
491
|
+
function withoutDestinationRequired(decision: CartComplianceDecision): CartComplianceDecision {
|
|
492
|
+
const blocks = decision.blocks.filter((block) => block.code !== "destination_required");
|
|
493
|
+
if (blocks.length === decision.blocks.length) return decision;
|
|
494
|
+
return {
|
|
495
|
+
...decision,
|
|
496
|
+
blocks,
|
|
497
|
+
failedClosed: blocks.some((block) => block.failedClosed === true),
|
|
498
|
+
status: blocks.some((block) => block.code !== "verification_required") ? "blocked" : blocks.length ? "action_required" : "clear",
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
|
|
477
502
|
/** The decision with only its verification outcome: every rule block removed, status recomputed. */
|
|
478
503
|
function verificationOnly(decision: CartComplianceDecision): CartComplianceDecision {
|
|
479
504
|
const blocks = decision.blocks.filter((block) => block.code.startsWith("verification_"));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "7.9.
|
|
3
|
+
"version": "7.9.10",
|
|
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",
|
|
@@ -261,7 +261,7 @@ export function evaluateCartCompliance(
|
|
|
261
261
|
message:
|
|
262
262
|
allowed.length === 0
|
|
263
263
|
? `${name}: its allowed-states list names no valid state (safe default = BLOCK).`
|
|
264
|
-
: `${name}.`,
|
|
264
|
+
: `${name}: this product ships only to ${allowed.join(", ")} (seller restriction, compliance.allowed_states).`,
|
|
265
265
|
});
|
|
266
266
|
continue;
|
|
267
267
|
}
|
|
@@ -328,7 +328,9 @@ export function evaluateCartCompliance(
|
|
|
328
328
|
blocks.push({
|
|
329
329
|
code: "purchase_limit_exceeded",
|
|
330
330
|
region,
|
|
331
|
-
message: `This order (${units} units) exceeds the ${limit}-unit per-order limit for ${region}
|
|
331
|
+
message: `This order (${units} units) exceeds the ${limit}-unit per-order limit for ${region}${
|
|
332
|
+
stateRuleFor(ruleset, region)?.note ? ` (${stateRuleFor(ruleset, region)?.note})` : ""
|
|
333
|
+
}.`,
|
|
332
334
|
});
|
|
333
335
|
}
|
|
334
336
|
}
|
|
@@ -354,6 +354,8 @@ interface CatalogSignals {
|
|
|
354
354
|
characterizingLabel: string;
|
|
355
355
|
flavorClassified: boolean;
|
|
356
356
|
coolingAgent: boolean | null;
|
|
357
|
+
/** A catalog flavor classification of `menthol-cooling`: a cooling signal independent of any label. */
|
|
358
|
+
mentholCooling: boolean;
|
|
357
359
|
}
|
|
358
360
|
|
|
359
361
|
const factOf = (link: Pick<CatalogLink, "facts">, key: string): CatalogFact | undefined =>
|
|
@@ -381,6 +383,7 @@ function readCatalogSignals(links: ReadonlyArray<Pick<CatalogLink, "facts">>): C
|
|
|
381
383
|
const classes: Array<boolean | undefined> = [];
|
|
382
384
|
let characterizingLabel = "characterizing flavor";
|
|
383
385
|
let allClassified = true;
|
|
386
|
+
let mentholCooling = false;
|
|
384
387
|
const cooling: Array<boolean | undefined> = [];
|
|
385
388
|
for (const link of links) {
|
|
386
389
|
const category = factOf(link, "compliance_category");
|
|
@@ -393,7 +396,10 @@ function readCatalogSignals(links: ReadonlyArray<Pick<CatalogLink, "facts">>): C
|
|
|
393
396
|
let characterizes: boolean | undefined;
|
|
394
397
|
if (flavor?.state === "known" && typeof flavor.value === "string") {
|
|
395
398
|
characterizes = !CATALOG_PLAIN_FLAVOR.has(flavor.value);
|
|
396
|
-
if (flavor.value === "menthol-cooling")
|
|
399
|
+
if (flavor.value === "menthol-cooling") {
|
|
400
|
+
characterizingLabel = "menthol";
|
|
401
|
+
mentholCooling = true;
|
|
402
|
+
}
|
|
397
403
|
} else if (flavor?.state === "not_applicable") characterizes = false;
|
|
398
404
|
else if (flavor?.state === "conflict" || flavor?.state === "invalid") characterizes = true;
|
|
399
405
|
const flavorLabels = factOf(link, "flavor_labels");
|
|
@@ -413,6 +419,7 @@ function readCatalogSignals(links: ReadonlyArray<Pick<CatalogLink, "facts">>): C
|
|
|
413
419
|
characterizingLabel,
|
|
414
420
|
flavorClassified: allClassified,
|
|
415
421
|
coolingAgent: decided === undefined ? null : decided,
|
|
422
|
+
mentholCooling,
|
|
416
423
|
};
|
|
417
424
|
}
|
|
418
425
|
|
|
@@ -430,6 +437,50 @@ function tightenCooling(catalog: boolean | null, merchant: boolean | null): bool
|
|
|
430
437
|
return catalog ?? merchant;
|
|
431
438
|
}
|
|
432
439
|
|
|
440
|
+
/**
|
|
441
|
+
* Cooling signals matched per word token, by stem, so "iced", "frozen", "peppermint", "minty" and
|
|
442
|
+
* "koolada" read as cooling while "juice", "slice" and "spice" (whole tokens that merely end in
|
|
443
|
+
* "ice") do not. Over-matching only blocks, never clears.
|
|
444
|
+
*/
|
|
445
|
+
const COOLING_TOKEN =
|
|
446
|
+
/^(?:ice[dsy]?|icee|icey|freez\w*|froze\w*|frost\w*|chill\w*|cool\w*|kool\w*|menthol\w*|\w*mint\w*|wintergreen|arctic|polar|glacier)$/;
|
|
447
|
+
const COOLING_COMPOUND = /ws[\s-]?(?:23|3)(?![0-9])|winter\s+green/;
|
|
448
|
+
|
|
449
|
+
function hasCoolingSignal(text: string): boolean {
|
|
450
|
+
const t = text.toLowerCase();
|
|
451
|
+
return COOLING_COMPOUND.test(t) || t.split(/[^a-z0-9]+/).some((w) => COOLING_TOKEN.test(w));
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Cooling status when no metafield or catalog fact declares it. A classified product (category and
|
|
456
|
+
* flavor recorded) with no cooling signal in its flavor labels, title or tags has none (`false`);
|
|
457
|
+
* a signal reads `true`; an unclassified product stays `null` (fail closed).
|
|
458
|
+
*/
|
|
459
|
+
function inferCoolingAgent(input: {
|
|
460
|
+
classified: boolean;
|
|
461
|
+
flavorLabels: string[];
|
|
462
|
+
title: string;
|
|
463
|
+
tags: string[];
|
|
464
|
+
optionValues: string[];
|
|
465
|
+
}): boolean | null {
|
|
466
|
+
if (!input.classified) return null;
|
|
467
|
+
return [...input.flavorLabels, input.title, ...input.tags, ...input.optionValues].some(hasCoolingSignal);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** Variant option values (chosen variant, else every variant), minus the nicotine-strength axis. */
|
|
471
|
+
function optionValuesOf(
|
|
472
|
+
product: { variants?: ReadonlyArray<{ option_values?: Record<string, string> }> },
|
|
473
|
+
variant: { option_values?: Record<string, string> } | null | undefined,
|
|
474
|
+
): string[] {
|
|
475
|
+
const variants = variant ? [variant] : (product.variants ?? []);
|
|
476
|
+
return variants.flatMap((v) =>
|
|
477
|
+
Object.entries(v.option_values ?? {})
|
|
478
|
+
.filter(([name]) => name.trim().toLowerCase() !== "nicotine strength")
|
|
479
|
+
.map(([, value]) => value)
|
|
480
|
+
.filter(Boolean),
|
|
481
|
+
);
|
|
482
|
+
}
|
|
483
|
+
|
|
433
484
|
/** The accepted catalog links a profile reads: the chosen variant's, else every variant's. */
|
|
434
485
|
function catalogLinksOf(
|
|
435
486
|
product: { variants?: ReadonlyArray<{ catalog_link?: CatalogVariant["catalog_link"] }> },
|
|
@@ -552,7 +603,17 @@ export function deriveProductProfile(
|
|
|
552
603
|
const isFlavored = containsNicotine && (signals?.characterizing === true || characterizingFlavors.length > 0);
|
|
553
604
|
|
|
554
605
|
const merchantCooling = parseYesNo(readMetafield(product, "compliance", "cooling_agent"));
|
|
555
|
-
const
|
|
606
|
+
const declaredCooling = tightenCooling(signals?.coolingAgent ?? null, merchantCooling);
|
|
607
|
+
const coolingAgent =
|
|
608
|
+
declaredCooling !== null
|
|
609
|
+
? declaredCooling
|
|
610
|
+
: inferCoolingAgent({
|
|
611
|
+
classified: (categoryClassified || signals?.category !== undefined) && (flavorLabels.length > 0 || signals?.flavorClassified === true),
|
|
612
|
+
flavorLabels: signals?.mentholCooling ? [...flavorLabels, "menthol"] : flavorLabels,
|
|
613
|
+
title: product.title ?? "",
|
|
614
|
+
tags: product.tags ?? [],
|
|
615
|
+
optionValues: optionValuesOf(product, variant),
|
|
616
|
+
});
|
|
556
617
|
|
|
557
618
|
return {
|
|
558
619
|
containsNicotine,
|