@tokenoftrust/storefront-runner 7.6.0 → 7.6.2

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.
@@ -73,6 +73,8 @@ export interface ParsedCart {
73
73
  lines: CartLine[];
74
74
  /** Messages the provider refused the request with. Empty when it accepted. */
75
75
  errors: string[];
76
+ /** Promotional coupon codes active on the cart. */
77
+ coupons?: string[];
76
78
  }
77
79
 
78
80
  export type CartAddedDetail =
@@ -84,6 +86,7 @@ export type CartAddedDetail =
84
86
  image: string | null;
85
87
  count: number;
86
88
  cartHref: string;
89
+ appliedCoupon?: string;
87
90
  }
88
91
  | { status: "error"; cartHref: string };
89
92
 
@@ -134,6 +137,37 @@ function wholeNumber(raw: unknown): number {
134
137
  return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
135
138
  }
136
139
 
140
+ /** Valid promotional coupon codes present on a FoxyCart JSONcart `coupons` payload. */
141
+ export function parseCartCoupons(body: unknown): string[] {
142
+ const cart = record(body);
143
+ if (!cart) return [];
144
+ const rawCoupons = cart.coupons;
145
+ const out: string[] = [];
146
+ const push = (candidate: unknown) => {
147
+ const valid = normalizePromoCoupon(candidate);
148
+ if (valid && !out.includes(valid)) out.push(valid);
149
+ };
150
+ if (Array.isArray(rawCoupons)) {
151
+ for (const entry of rawCoupons) {
152
+ if (typeof entry === "string") {
153
+ push(entry);
154
+ } else {
155
+ const obj = record(entry);
156
+ if (obj) push(obj.code);
157
+ }
158
+ }
159
+ } else {
160
+ const map = record(rawCoupons);
161
+ if (map) {
162
+ for (const [key, value] of Object.entries(map)) {
163
+ const obj = record(value);
164
+ push(obj?.code ?? key);
165
+ }
166
+ }
167
+ }
168
+ return out;
169
+ }
170
+
137
171
  /** The provider's cart JSON as a typed cart, or null when the body is not a cart. */
138
172
  export function parseCart(body: unknown): ParsedCart | null {
139
173
  const cart = record(body);
@@ -163,11 +197,13 @@ export function parseCart(body: unknown): ParsedCart | null {
163
197
  })
164
198
  : [];
165
199
  const session = cart.session_id;
200
+ const coupons = parseCartCoupons(cart);
166
201
  return {
167
202
  count,
168
203
  sessionId: typeof session === "string" && /^[a-z0-9]{10,64}$/.test(session) ? session : null,
169
204
  lines,
170
205
  errors,
206
+ ...(coupons.length > 0 ? { coupons } : {}),
171
207
  };
172
208
  }
173
209
 
@@ -469,8 +505,10 @@ export function describeAdded(
469
505
  cart: ParsedCart,
470
506
  form: { title: string; code: string; quantity: number },
471
507
  cartHref: string,
508
+ appliedCoupon?: string | null,
472
509
  ): CartAddedDetail {
473
510
  const line = addedLine(cart, form.code);
511
+ const coupon = normalizePromoCoupon(appliedCoupon ?? cart.coupons?.[0]);
474
512
  return {
475
513
  status: "added",
476
514
  title: form.title || line?.name || "Item",
@@ -479,6 +517,7 @@ export function describeAdded(
479
517
  image: line?.image ?? null,
480
518
  count: cart.count,
481
519
  cartHref,
520
+ ...(coupon ? { appliedCoupon: coupon } : {}),
482
521
  };
483
522
  }
484
523
 
@@ -539,19 +578,24 @@ export async function addFromForm(
539
578
  const key = storedCountKey(config.cookiePath);
540
579
  const quantity = wholeNumber(submittedField(data, "quantity")) || 1;
541
580
  try {
542
- const cart = parseCart(await loadCartJsonp(location, cartOrigin, env));
581
+ const rawBody = await loadCartJsonp(location, cartOrigin, env);
582
+ const cart = parseCart(rawBody);
543
583
  if (!cart || cart.errors.length > 0 || cart.count === 0) {
544
584
  announce(env, { status: "error", cartHref: config.cartUrl });
545
585
  return true;
546
586
  }
547
587
  writeStoredCount(env.storage, key, cart.count);
548
588
  renderCartCount(env.doc, cart.count);
589
+ const submittedCoupon = normalizePromoCoupon(data.get("coupon"));
590
+ const appliedCoupon =
591
+ parseCartCoupons(rawBody)[0] ?? pendingCoupon ?? submittedCoupon ?? undefined;
549
592
  announce(
550
593
  env,
551
594
  describeAdded(
552
595
  cart,
553
596
  { title: form.dataset.productTitle ?? "", code: submittedField(data, "code"), quantity },
554
597
  cartHrefFor(config, cart.sessionId),
598
+ appliedCoupon,
555
599
  ),
556
600
  );
557
601
  } catch {
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The ops stop control for assistant and agent order intake: one declared binding, read per request
3
+ * before any other work. While it reads `suspended`, new assistant proposals and agent checkout
4
+ * sessions are refused with a shopper message. The ordinary product page, cart and checkout path
5
+ * never read it.
6
+ */
7
+ import { readEnv } from "@/lib/publication/shared/runtimeEnv";
8
+
9
+ export const AGENT_INTAKE_SUSPENDED_MESSAGE = "This store is not accepting agent checkout requests right now.";
10
+ export const ASSISTANT_INTAKE_SUSPENDED_MESSAGE =
11
+ "This store is not accepting assistant order requests right now. You can still order from the store's product pages.";
12
+
13
+ /** True when the store has paused assistant and agent intake. A binding that cannot be read refuses. */
14
+ export async function agentIntakeSuspended(): Promise<boolean> {
15
+ try {
16
+ return (await readEnv("AGENT_CHECKOUT_INTAKE")) === "suspended";
17
+ } catch (error) {
18
+ console.warn("[storefront] intake-suspend binding unreadable; refusing intake", error instanceof Error ? error.name : "error");
19
+ return true;
20
+ }
21
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Carrier evidence a fulfillment processor reports, from one declarative carrier catalog.
3
+ *
4
+ * `trackingHosts` are carrier-owned tracking domains, used only as a fail-closed allowlist for
5
+ * app-supplied tracking URLs; the same allowlist validates an app's write and gates the merchant
6
+ * desk's tracking link. Tracking URLs are never fetched.
7
+ *
8
+ * `pactEligible` is statutory eligibility only: whether the carrier may carry ENDS parcels at all
9
+ * (the POSTAL Act's mailability ban rules out USPS). Carrier contract terms for regulated parcels
10
+ * belong to the tenant's carrier account, not to this catalog.
11
+ */
12
+ export type CarrierAdultSignature = "required" | "supported" | "unsupported";
13
+
14
+ export interface CarrierCatalogEntry {
15
+ readonly code: string;
16
+ readonly name: string;
17
+ readonly region: "US";
18
+ readonly pactEligible: boolean;
19
+ readonly adultSignature: CarrierAdultSignature;
20
+ readonly trackingHosts: readonly string[];
21
+ }
22
+
23
+ export const CARRIER_CATALOG = [
24
+ { code: "UPS", name: "UPS", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.ups.com"] },
25
+ { code: "FEDEX", name: "FedEx", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.fedex.com"] },
26
+ { code: "USPS", name: "USPS", region: "US", pactEligible: false, adultSignature: "supported", trackingHosts: ["tools.usps.com"] },
27
+ { code: "DHL", name: "DHL", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.dhl.com"] },
28
+ { code: "ONTRAC", name: "OnTrac", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.ontrac.com"] },
29
+ { code: "LSO", name: "Lone Star Overnight", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.lso.com"] },
30
+ { code: "BETTER_TRUCKS", name: "Better Trucks", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.bettertrucks.com"] },
31
+ { code: "GLS_US", name: "GLS US", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.gls-us.com"] },
32
+ { code: "SPEE_DEE", name: "Spee-Dee Delivery", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.speedeedelivery.com"] },
33
+ { code: "STAT_OVERNIGHT", name: "Stat Overnight", region: "US", pactEligible: true, adultSignature: "supported", trackingHosts: ["www.statovernight.com"] },
34
+ ] as const satisfies readonly CarrierCatalogEntry[];
35
+
36
+ export type CarrierCode = (typeof CARRIER_CATALOG)[number]["code"];
37
+
38
+ export const CARRIER_CODES: readonly CarrierCode[] = Object.freeze(CARRIER_CATALOG.map((entry) => entry.code));
39
+
40
+ export const CARRIER_TRACKING_HOSTS: Readonly<Record<CarrierCode, readonly string[]>> = Object.freeze(
41
+ Object.fromEntries(CARRIER_CATALOG.map((entry): [string, readonly string[]] => [entry.code, entry.trackingHosts])) as Record<
42
+ CarrierCode,
43
+ readonly string[]
44
+ >,
45
+ );
46
+
47
+ export const TRACKING_NUMBER = /^[A-Z0-9]{6,40}$/;
48
+ export const CARRIER_SERVICE = /^[A-Z0-9_]{1,40}$/;
49
+ export const TRACKING_URL_MAX = 2048;
50
+ export const TRACKING_PART_MAX = 512;
51
+
52
+ /** The canonical form every carrier comparison uses: trimmed and uppercased. */
53
+ export function canonicalCarrier(value: string): string {
54
+ return value.trim().toUpperCase();
55
+ }
56
+
57
+ /** A supplied carrier as its canonical code, or null when it is not in the closed set. */
58
+ export function parseCarrierCode(value: unknown): CarrierCode | null {
59
+ if (typeof value !== "string") return null;
60
+ const canonical = canonicalCarrier(value);
61
+ return (CARRIER_CODES as readonly string[]).includes(canonical) ? (canonical as CarrierCode) : null;
62
+ }
63
+
64
+ /** The tracking hosts allowed for `carrier`; none for a value outside the closed set. */
65
+ export function trackingHostsFor(carrier: unknown): readonly string[] {
66
+ const code = parseCarrierCode(carrier);
67
+ return code ? CARRIER_TRACKING_HOSTS[code] : [];
68
+ }
69
+
70
+ /**
71
+ * True when `url` is an https URL on one of `carrier`'s tracking hosts: at most 2048 characters,
72
+ * printable ASCII only, the authority exactly an allowed host (so no userinfo, port or IP literal),
73
+ * no fragment, and a path and query of at most 512 characters each.
74
+ */
75
+ export function trackingUrlAllowed(carrier: unknown, url: unknown): url is string {
76
+ if (typeof url !== "string" || url.length > TRACKING_URL_MAX) return false;
77
+ if (!/^[\x21-\x7e]+$/.test(url) || url.includes("#") || url.includes("\\")) return false;
78
+ if (!url.startsWith("https://")) return false;
79
+ const authority = url.slice("https://".length).split(/[/?]/, 1)[0] ?? "";
80
+ if (!trackingHostsFor(carrier).includes(authority)) return false;
81
+ let parsed: URL;
82
+ try {
83
+ parsed = new URL(url);
84
+ } catch {
85
+ return false;
86
+ }
87
+ if (parsed.protocol !== "https:" || parsed.username !== "" || parsed.password !== "" || parsed.port !== "") return false;
88
+ if (parsed.host !== authority || parsed.hash !== "") return false;
89
+ return parsed.pathname.length <= TRACKING_PART_MAX && parsed.search.replace(/^\?/, "").length <= TRACKING_PART_MAX;
90
+ }
91
+
92
+ /** The catalog entry for `carrier` in canonical form, or null when the catalog does not declare it. */
93
+ export function carrierCatalogEntry(
94
+ carrier: string,
95
+ catalog: readonly CarrierCatalogEntry[] = CARRIER_CATALOG,
96
+ ): CarrierCatalogEntry | null {
97
+ const canonical = canonicalCarrier(carrier);
98
+ return catalog.find((entry) => entry.code === canonical) ?? null;
99
+ }
100
+
101
+ /** True when `carrier` is in either prohibited set, both compared in canonical form. */
102
+ export function carrierProhibited(carrier: string, ...prohibited: ReadonlyArray<readonly string[]>): boolean {
103
+ const canonical = canonicalCarrier(carrier);
104
+ return prohibited.some((set) => set.some((item) => canonicalCarrier(item) === canonical));
105
+ }
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Release and hand-off gates for whole-order fulfillment.
3
+ *
4
+ * Evidence, payment, stock, refund, and cancel are rechecked from stored source
5
+ * truth. Compliance `fresh` is not evidence. A carrier account is tenant
6
+ * configuration: its absence is not a hold, and this module does not select a vendor.
7
+ */
8
+ import {
9
+ decideCommerceCommand,
10
+ paymentIsCaptured,
11
+ type CommerceEvidence,
12
+ type ComplianceRuleProfile,
13
+ type EvidenceState,
14
+ type FulfillmentState,
15
+ type LabelState,
16
+ type PaymentState,
17
+ type ProviderOutcome,
18
+ type StockState,
19
+ type OrderContactState,
20
+ } from "@tot/public-runtime";
21
+ import type { SourceReadiness } from "../orders/data/sourceAuthorityStore.js";
22
+ import { COMPLIANCE_RULE_PROFILES } from "@/config/compliance/rulesets";
23
+ import {
24
+ CARRIER_CATALOG,
25
+ canonicalCarrier,
26
+ carrierCatalogEntry,
27
+ carrierProhibited,
28
+ type CarrierCatalogEntry,
29
+ type CarrierCode,
30
+ } from "./carrierEvidence.js";
31
+
32
+ export const RELEASE_HOLDS = [
33
+ "source-check-pending",
34
+ "source-ledger-conflict",
35
+ "source-authority-unreadable",
36
+ "source-authority-unavailable",
37
+ "source-sync-pending",
38
+ "evidence-unknown",
39
+ "evidence-stale",
40
+ "evidence-unreadable",
41
+ "evidence-absent",
42
+ "operator-hold",
43
+ "payment-pending",
44
+ "payment-unknown",
45
+ "payment-not-captured",
46
+ "refund-pending",
47
+ "refunded",
48
+ "refund-unknown",
49
+ "cancel-pending",
50
+ "cancelled",
51
+ "stock-unknown",
52
+ "stock-unconfirmed",
53
+ "fulfillment-unknown",
54
+ "ship-to-absent",
55
+ "ship-to-expired",
56
+ "ship-to-erased",
57
+ "ship-to-unreadable",
58
+ ] as const;
59
+
60
+ export type ReleaseHold = (typeof RELEASE_HOLDS)[number];
61
+
62
+ export interface CarrierPolicy {
63
+ adultSignatureRequired: boolean;
64
+ /** The tenant's compliance profile enables PACT: only statutorily eligible carriers may carry its parcels. */
65
+ pactEnabled: boolean;
66
+ prohibitedCarriers: readonly string[];
67
+ /** Null when the tenant has not configured an account. Absence is not a hold. */
68
+ carrierAccountId: string | null;
69
+ }
70
+
71
+ export interface ReadinessInput {
72
+ shipTo?: OrderContactState;
73
+ sourceHolds?: readonly SourceReadiness[];
74
+ payment: PaymentState;
75
+ stock: StockState;
76
+ fulfillment: FulfillmentState;
77
+ label: LabelState;
78
+ evidence: CommerceEvidence;
79
+ operatorHold: boolean;
80
+ cancelPending: boolean;
81
+ providerOutcome: ProviderOutcome | null;
82
+ adultSignature: "accepted" | "refused" | "absent";
83
+ adultSignatureRequired: boolean;
84
+ }
85
+
86
+ const EVIDENCE_HOLDS: Record<EvidenceState, ReleaseHold | null> = {
87
+ fresh: null,
88
+ "not-required": null,
89
+ "not-computed": null,
90
+ UNKNOWN: "evidence-unknown",
91
+ stale: "evidence-stale",
92
+ unreadable: "evidence-unreadable",
93
+ absent: "evidence-absent",
94
+ };
95
+
96
+ function add(holds: ReleaseHold[], hold: ReleaseHold | null): void {
97
+ if (hold && !holds.includes(hold)) holds.push(hold);
98
+ }
99
+
100
+ /** Holds that forbid creating a shipment intent. Compliance is not an input. */
101
+ export function releaseHolds(input: ReadinessInput): ReleaseHold[] {
102
+ const holds: ReleaseHold[] = [...(input.sourceHolds ?? [])];
103
+ for (const field of ["verification", "tax", "risk", "stock"] as const) {
104
+ const value = input.evidence[field];
105
+ add(holds, value in EVIDENCE_HOLDS ? EVIDENCE_HOLDS[value as EvidenceState] : "evidence-unreadable");
106
+ }
107
+ if (input.operatorHold) add(holds, "operator-hold");
108
+ if (input.cancelPending) add(holds, "cancel-pending");
109
+ if (input.fulfillment === "cancelled") add(holds, "cancelled");
110
+ if (input.fulfillment === "UNKNOWN") add(holds, "fulfillment-unknown");
111
+ if (input.payment === "pending" || input.payment === "authorized") add(holds, "payment-pending");
112
+ else if (input.payment === "UNKNOWN" || input.payment === "capture_unknown") add(holds, "payment-unknown");
113
+ else if (input.payment === "refund_requested") add(holds, "refund-pending");
114
+ else if (input.payment === "refunded") add(holds, "refunded");
115
+ else if (input.payment === "refund_unknown") add(holds, "refund-unknown");
116
+ else if (input.payment === "voided") add(holds, "cancelled");
117
+ else if (!paymentIsCaptured(input.payment)) add(holds, "payment-not-captured");
118
+ if (input.stock === "UNKNOWN") add(holds, "stock-unknown");
119
+ else if (input.stock !== "confirmed") add(holds, "stock-unconfirmed");
120
+ if (input.shipTo !== "present" && input.shipTo !== "restricted") {
121
+ add(holds, input.shipTo === "absent" ? "ship-to-absent" : input.shipTo === "expired" ? "ship-to-expired" :
122
+ input.shipTo === "erased" ? "ship-to-erased" : "ship-to-unreadable");
123
+ }
124
+ return holds;
125
+ }
126
+
127
+ export function canRelease(input: ReadinessInput): boolean {
128
+ return input.fulfillment === "ready" && releaseHolds(input).length === 0;
129
+ }
130
+
131
+ export function handoffRefusal(input: ReadinessInput): ReleaseHold | "adult-signature" | "label" | "reconcile" | "fulfillment" | "evidence" | "payment" | "stock" | "reuse" | "ship-to" | null {
132
+ const holds = releaseHolds(input);
133
+ if (holds.length > 0) return holds[0] ?? "fulfillment";
134
+ const decision = decideCommerceCommand({
135
+ command: "hand-off",
136
+ payment: input.payment,
137
+ stock: input.stock,
138
+ fulfillment: input.fulfillment,
139
+ label: input.label,
140
+ evidence: input.evidence,
141
+ providerOutcome: input.providerOutcome,
142
+ shipTo: input.shipTo,
143
+ });
144
+ if (!decision.admit) return decision.reason === "admitted" ? "fulfillment" : decision.reason;
145
+ if (input.adultSignatureRequired && input.adultSignature !== "accepted") return "adult-signature";
146
+ return null;
147
+ }
148
+
149
+ export function carrierPolicyForTenant(tenant: {
150
+ tenant_id: string;
151
+ compliance?: { ruleProfile?: string };
152
+ carrierAccountId?: unknown;
153
+ }): CarrierPolicy {
154
+ const profile = tenant.compliance?.ruleProfile;
155
+ const build =
156
+ profile && Object.hasOwn(COMPLIANCE_RULE_PROFILES, profile)
157
+ ? COMPLIANCE_RULE_PROFILES[profile as ComplianceRuleProfile]
158
+ : undefined;
159
+ const ruleset = build ? build(tenant.tenant_id) : null;
160
+ const raw = tenant.carrierAccountId;
161
+ const carrierAccountId = typeof raw === "string" && raw.trim() !== "" ? raw.trim() : null;
162
+ const enabled = ruleset?.pactAct.enabled === true;
163
+ return {
164
+ adultSignatureRequired: enabled && ruleset.pactAct.adultSignatureRequired === true,
165
+ pactEnabled: enabled,
166
+ prohibitedCarriers: enabled ? [...ruleset.pactAct.prohibitedCarriers] : [],
167
+ carrierAccountId,
168
+ };
169
+ }
170
+
171
+ /**
172
+ * The tenant's compliance intersected with the carrier catalog. Prohibited when the carrier is in
173
+ * the policy's prohibited set, when PACT is enabled and the carrier is not statutorily eligible,
174
+ * or when adult signature is required and the carrier does not support it. A carrier the catalog
175
+ * does not declare has no eligibility and no adult-signature support, so it fails closed.
176
+ */
177
+ export function carrierPolicyRefusal(
178
+ carrier: string,
179
+ policy: CarrierPolicy,
180
+ catalog: readonly CarrierCatalogEntry[] = CARRIER_CATALOG,
181
+ ): "carrier-prohibited" | null {
182
+ if (carrierProhibited(carrier, policy.prohibitedCarriers)) return "carrier-prohibited";
183
+ const entry = carrierCatalogEntry(carrier, catalog);
184
+ if (policy.pactEnabled && !entry?.pactEligible) return "carrier-prohibited";
185
+ if (policy.adultSignatureRequired && (!entry || entry.adultSignature === "unsupported")) return "carrier-prohibited";
186
+ return null;
187
+ }
188
+
189
+ /** A supplied carrier is never a selection. A carrier the tenant's policy refuses answers carrier-prohibited. */
190
+ export function carrierSelectionRefusal(
191
+ policy: CarrierPolicy,
192
+ carrier: string | undefined,
193
+ catalog: readonly CarrierCatalogEntry[] = CARRIER_CATALOG,
194
+ ): "carrier-prohibited" | "vendor-not-selected" | null {
195
+ if (carrier === undefined) return null;
196
+ if (canonicalCarrier(carrier) === "") return "vendor-not-selected";
197
+ return carrierPolicyRefusal(carrier, policy, catalog) ?? "vendor-not-selected";
198
+ }
199
+
200
+ /**
201
+ * A processor's reported carrier. Prohibited when the current policy refuses it or the order's
202
+ * label-intent snapshot prohibits it; a handoff carrier must equal the carrier its label was bought with.
203
+ */
204
+ export function carrierEvidenceRefusal(input: {
205
+ carrier: CarrierCode;
206
+ policy: CarrierPolicy;
207
+ snapshotProhibited: readonly string[];
208
+ labelCarrier?: string | null;
209
+ catalog?: readonly CarrierCatalogEntry[];
210
+ }): "carrier-prohibited" | "carrier-mismatch" | null {
211
+ if (carrierPolicyRefusal(input.carrier, input.policy, input.catalog)) return "carrier-prohibited";
212
+ if (carrierProhibited(input.carrier, input.snapshotProhibited)) return "carrier-prohibited";
213
+ if (input.labelCarrier !== undefined && (input.labelCarrier === null || canonicalCarrier(input.labelCarrier) !== input.carrier)) {
214
+ return "carrier-mismatch";
215
+ }
216
+ return null;
217
+ }