@tokenoftrust/storefront-runner 7.8.8 → 7.8.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.
@@ -80,7 +80,7 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
80
80
  const [familyName, setFamilyName] = useState("");
81
81
  const [guestShopper, setGuestShopper] = useState(false);
82
82
  const [saveForFastTrack, setSaveForFastTrack] = useState(true);
83
- const fastTrackSentRef = useRef(false);
83
+ const fastTrackSendRef = useRef<Promise<boolean> | null>(null);
84
84
  const [verificationRef, setVerificationRef] = useState<string | null>(null);
85
85
  const [continuationUrl, setContinuationUrl] = useState<string | null>(null);
86
86
  const [popupBlocked, setPopupBlocked] = useState(false);
@@ -146,7 +146,7 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
146
146
  setPopupBlocked(false);
147
147
  setGuestShopper(false);
148
148
  setSaveForFastTrack(true);
149
- fastTrackSentRef.current = false;
149
+ fastTrackSendRef.current = null;
150
150
  // A reload mid-trip must not lose the correlation: replay the stored ref so
151
151
  // the server re-reads THIS attempt's verification instead of starting over.
152
152
  setVerificationRef(line.shopperCart ? null :
@@ -185,7 +185,7 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
185
185
  document.documentElement.style.overflow = "";
186
186
  }, [stopPolling]);
187
187
 
188
- const proceed = useCallback((line: PendingLine, ref: string | null) => {
188
+ const submitClearedLine = useCallback((line: PendingLine, ref: string | null) => {
189
189
  stopPolling();
190
190
  if (line.shopperCart) {
191
191
  const current = checkoutLineFromForm(line.form);
@@ -212,6 +212,19 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
212
212
  else line.form.submit();
213
213
  if (line.shopperCart) delete line.form.dataset.complianceCleared;
214
214
  }, [close, preflightUrl, stopPolling]);
215
+
216
+ const proceed = useCallback((line: PendingLine, ref: string | null) => {
217
+ const fastTrackSend = activeDialogLine.current === line ? fastTrackSendRef.current : null;
218
+ if (!fastTrackSend) {
219
+ submitClearedLine(line, ref);
220
+ return;
221
+ }
222
+ // The native fallback can leave the page before the challenge is stored.
223
+ setLoading(true);
224
+ void fastTrackSend.then(() => {
225
+ if (activeDialogLine.current === line) submitClearedLine(line, ref);
226
+ });
227
+ }, [submitClearedLine]);
215
228
  proceedRef.current = proceed;
216
229
 
217
230
  /**
@@ -384,11 +397,12 @@ export default function CheckoutComplianceGate({ preflightUrl, minAge }: Props)
384
397
  setError(gateRefused.current ? STORE_NOT_PUBLIC_MESSAGE : FAIL_CLOSED_MESSAGE);
385
398
  return;
386
399
  }
387
- if (phase === "collect" && guestShopper && !fastTrackSentRef.current && saveForFastTrack && email.trim()) {
400
+ if (phase === "collect" && guestShopper && !fastTrackSendRef.current && saveForFastTrack && email.trim()) {
388
401
  const next = verificationPhase(res);
389
402
  if (next === "continue" || next === "waiting" || next === "cleared") {
390
- fastTrackSentRef.current = true;
391
- void requestFastTrackAccountSave({ preflightUrl, email, saveForFastTrack, shopperCart: pending.shopperCart });
403
+ fastTrackSendRef.current = requestFastTrackAccountSave({
404
+ preflightUrl, email, saveForFastTrack, shopperCart: pending.shopperCart,
405
+ });
392
406
  }
393
407
  }
394
408
  apply(pending, res);
@@ -63,6 +63,7 @@ export const AGENT_ALLOWED_ROUTES: ReadonlyArray<{ method: string; path: string
63
63
  */
64
64
  export const AGENT_ROLE_ROUTES: ReadonlyArray<{ method: string; path: string; role: AgentRoleId }> = [
65
65
  { method: "GET", path: "/api/admin/orders", role: ADMIN_READ_ROLE },
66
+ { method: "GET", path: "/api/admin/orders/manual", role: ADMIN_READ_ROLE },
66
67
  { method: "GET", path: "/api/admin/orders/:id", role: ADMIN_READ_ROLE },
67
68
  { method: "GET", path: "/api/admin/inventory/levels", role: ADMIN_READ_ROLE },
68
69
  { method: "GET", path: "/api/admin/inventory/history", role: ADMIN_READ_ROLE },
@@ -31,6 +31,11 @@ import {
31
31
  } from "@tot/public-runtime";
32
32
  import { readMirrorAuthority, VERIFICATION_PROVIDER_OWNER, type ReserveHold } from "@/lib/inventory/allocations.js";
33
33
 
34
+ /** Checkout authorization window for reservation and payment completion. */
35
+ export const CHECKOUT_ADMISSION_TTL_MS = 5 * 60_000;
36
+ /** Fulfillment evidence validity after accepting a checkout or approved invoice. */
37
+ export const FULFILLMENT_EVIDENCE_TTL_MS = 30 * 24 * 60 * 60_000;
38
+
34
39
  /**
35
40
  * Whether the signed excise carrier reconciles with the signed payment totals.
36
41
  * When `totals.exciseMinor` is present, the carrier must be `computed` with `amountMinor`
@@ -157,7 +162,7 @@ function seamRuleFinding(seam: SeamView | null): { finding: string } | null {
157
162
  return code ? { finding: `verification-refused:${code}` } : null;
158
163
  }
159
164
 
160
- function seamFinding(seam: SeamView | null): { finding: string; owner?: string } | null {
165
+ export function seamFinding(seam: SeamView | null): { finding: string; owner?: string } | null {
161
166
  if (!seam || seam.status === "absent") return { finding: "verification-seam-absent" };
162
167
  if (seam.status === "clear") return null;
163
168
  const codes = (seam.codes ?? []).filter((code) => /^[a-z0-9_-]+$/.test(code));
@@ -185,7 +190,7 @@ export function exciseUnavailableReason(
185
190
  return undefined;
186
191
  }
187
192
 
188
- function exciseFinding(
193
+ export function exciseFinding(
189
194
  exciseRequired: boolean | undefined,
190
195
  excise: ExciseCarrier | undefined,
191
196
  evidence: CommerceEvidence | null,
@@ -308,8 +313,32 @@ export async function evaluateFinalCart(input: FinalCartRequest): Promise<FinalC
308
313
  });
309
314
  if (!command.admit) return { ok: false, finding: commandFinding(command.reason) };
310
315
 
316
+ const stock = finalCartStockHolds(input.presented.lines, input.stockTracked, input.authorities, input.catalogAvailable);
317
+ if (!stock.ok) return stock;
318
+
319
+ if (input.token.scheme !== "asymmetric-jwks") return { ok: false, finding: "shared-secret" };
320
+ return {
321
+ ok: true,
322
+ digest,
323
+ expiresAt,
324
+ amountMinor,
325
+ holds: stock.holds,
326
+ issuer: input.token.issuer,
327
+ jti: input.token.jti,
328
+ tenantId: input.routedTenantId,
329
+ stage: input.presented.stage,
330
+ };
331
+ }
332
+
333
+ /** The allocation quantities and balance checks shared by both final-cart entry points. */
334
+ export function finalCartStockHolds(
335
+ lines: readonly { sku: string; quantity: number }[],
336
+ stockTracked: boolean,
337
+ authorities: readonly unknown[],
338
+ catalogAvailable: boolean,
339
+ ): { ok: true; holds: ReserveHold[] } | { ok: false; finding: string } {
311
340
  const quantities = new Map<string, number>();
312
- for (const line of input.presented.lines) {
341
+ for (const line of lines) {
313
342
  quantities.set(line.sku, (quantities.get(line.sku) ?? 0) + line.quantity);
314
343
  }
315
344
  const holds: ReserveHold[] = [];
@@ -320,31 +349,20 @@ export async function evaluateFinalCart(input: FinalCartRequest): Promise<FinalC
320
349
  continue;
321
350
  }
322
351
  const named =
323
- input.authorities.find((value) => {
352
+ authorities.find((value) => {
324
353
  if (!value || typeof value !== "object") return false;
325
354
  return (value as { sku?: unknown }).sku === sku;
326
- }) ?? (quantities.size === 1 ? (input.authorities[0] ?? null) : null);
355
+ }) ?? (quantities.size === 1 ? (authorities[0] ?? null) : null);
327
356
  if (named && typeof named === "object" && "provider" in named && (named as { provider: unknown }).provider !== "mirror") {
328
357
  return { ok: false, finding: "authority-unavailable" };
329
358
  }
330
359
  const mirror = readMirrorAuthority(named);
331
360
  if (!mirror || mirror.sku !== sku) {
332
- return { ok: false, finding: input.catalogAvailable && isCatalogShape(named) ? "catalog-not-authority" : "authority-unavailable" };
361
+ return { ok: false, finding: catalogAvailable && isCatalogShape(named) ? "catalog-not-authority" : "authority-unavailable" };
333
362
  }
334
363
  if (mirror.onHand < quantity) return { ok: false, finding: "stock-unavailable" };
335
364
  holds.push({ sku, locationId: mirror.locationId, quantity, onHand: mirror.onHand });
336
365
  }
337
366
 
338
- if (input.token.scheme !== "asymmetric-jwks") return { ok: false, finding: "shared-secret" };
339
- return {
340
- ok: true,
341
- digest,
342
- expiresAt,
343
- amountMinor,
344
- holds,
345
- issuer: input.token.issuer,
346
- jti: input.token.jti,
347
- tenantId: input.routedTenantId,
348
- stage: input.presented.stage,
349
- };
367
+ return { ok: true, holds };
350
368
  }
@@ -142,6 +142,17 @@ export function shopperAuthSendUrl(preflightUrl: string): string {
142
142
  return shopperAccountUrl(preflightUrl, "auth/send");
143
143
  }
144
144
 
145
+ export const SHOPPER_CHALLENGE_TTL_MS = 600_000;
146
+ const SHOPPER_CHALLENGE_REQUEST_TIMEOUT_MS = 5_000;
147
+
148
+ export function shopperChallengeKey(apiBase: string): string {
149
+ return `tot:shopper-challenge:${apiBase.replace(/\/+$/, "")}`;
150
+ }
151
+
152
+ function isShopperChallengeId(value: unknown): value is string {
153
+ return typeof value === "string" && /^[\w-]{43}$/.test(value);
154
+ }
155
+
145
156
  export async function isGuestShopper(preflightUrl: string): Promise<boolean> {
146
157
  const url = shopperAccountUrl(preflightUrl, "me");
147
158
  if (url === preflightUrl) return false;
@@ -173,10 +184,23 @@ export async function requestFastTrackAccountSave(opts: {
173
184
  headers: { "content-type": "application/json" },
174
185
  credentials: "same-origin",
175
186
  keepalive: true,
187
+ signal: AbortSignal.timeout(SHOPPER_CHALLENGE_REQUEST_TIMEOUT_MS),
176
188
  body: JSON.stringify({ identifier }),
177
189
  });
178
190
  if (!response.ok) return false;
179
- await response.json();
191
+ const body: unknown = await response.json();
192
+ if (body && typeof body === "object" && "ok" in body && body.ok === true &&
193
+ "challengeId" in body && isShopperChallengeId(body.challengeId)) {
194
+ const apiBase = opts.preflightUrl.slice(0, -"/api/compliance/preflight".length);
195
+ try {
196
+ sessionStorage.setItem(shopperChallengeKey(apiBase), JSON.stringify({
197
+ challengeId: body.challengeId,
198
+ expiresAt: Date.now() + SHOPPER_CHALLENGE_TTL_MS,
199
+ }));
200
+ } catch {
201
+ // Storage failure does not change the send result.
202
+ }
203
+ }
180
204
  return true;
181
205
  } catch {
182
206
  return false;
@@ -72,6 +72,8 @@ export interface ReadinessInput {
72
72
  shipTo?: OrderContactState;
73
73
  sourceHolds?: readonly SourceReadiness[];
74
74
  payment: PaymentState;
75
+ /** Set only from the current native invoice release receipt. */
76
+ approvedNetTerms?: boolean;
75
77
  stock: StockState;
76
78
  fulfillment: FulfillmentState;
77
79
  label: LabelState;
@@ -108,13 +110,14 @@ export function releaseHolds(input: ReadinessInput): ReleaseHold[] {
108
110
  if (input.cancelPending) add(holds, "cancel-pending");
109
111
  if (input.fulfillment === "cancelled") add(holds, "cancelled");
110
112
  if (input.fulfillment === "UNKNOWN") add(holds, "fulfillment-unknown");
111
- if (input.payment === "pending" || input.payment === "authorized") add(holds, "payment-pending");
113
+ const netTerms = input.payment === "authorized" && input.approvedNetTerms === true;
114
+ if (input.payment === "pending" || (input.payment === "authorized" && !netTerms)) add(holds, "payment-pending");
112
115
  else if (input.payment === "UNKNOWN" || input.payment === "capture_unknown") add(holds, "payment-unknown");
113
116
  else if (input.payment === "refund_requested") add(holds, "refund-pending");
114
117
  else if (input.payment === "refunded") add(holds, "refunded");
115
118
  else if (input.payment === "refund_unknown") add(holds, "refund-unknown");
116
119
  else if (input.payment === "voided") add(holds, "cancelled");
117
- else if (!paymentIsCaptured(input.payment)) add(holds, "payment-not-captured");
120
+ else if (!netTerms && !paymentIsCaptured(input.payment)) add(holds, "payment-not-captured");
118
121
  if (input.stock === "UNKNOWN") add(holds, "stock-unknown");
119
122
  else if (input.stock !== "confirmed") add(holds, "stock-unconfirmed");
120
123
  if (input.shipTo !== "present" && input.shipTo !== "restricted") {
@@ -133,7 +136,7 @@ export function handoffRefusal(input: ReadinessInput): ReleaseHold | "adult-sign
133
136
  if (holds.length > 0) return holds[0] ?? "fulfillment";
134
137
  const decision = decideCommerceCommand({
135
138
  command: "hand-off",
136
- payment: input.payment,
139
+ payment: input.payment === "authorized" && input.approvedNetTerms ? "captured" : input.payment,
137
140
  stock: input.stock,
138
141
  fulfillment: input.fulfillment,
139
142
  label: input.label,
@@ -95,6 +95,8 @@ export interface ReserveInput {
95
95
  * confirmation and release work unchanged, but no balance bounds it.
96
96
  */
97
97
  stockUntracked?: boolean;
98
+ /** A native invoice can renew only an expired reservation, under its scoped purchase guard. */
99
+ manualInvoice?: true;
98
100
  }
99
101
 
100
102
  export type ReserveResult =
@@ -262,10 +264,11 @@ function reserveShape(input: ReserveInput): ReserveResult | null {
262
264
  }
263
265
 
264
266
  function allocationInsert(input: ReserveInput, hold: ReserveHold, seenAt: string): SqlStatement {
267
+ const currentMirror = Boolean(input.admissionStatement || input.manualInvoice);
265
268
  const bound = input.stockUntracked ? "" : `(
266
269
  SELECT COALESCE(SUM(quantity), 0) FROM scrappy_allocations
267
270
  WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ? AND state IN ('reserved', 'confirmed')
268
- ) + ? <= ${input.admissionStatement
271
+ ) + ? <= ${currentMirror
269
272
  ? `(SELECT COALESCE(SUM(quantity_delta), 0) FROM commerce_inventory_movements
270
273
  WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?)`
271
274
  : "?"}
@@ -276,7 +279,7 @@ function allocationInsert(input: ReserveInput, hold: ReserveHold, seenAt: string
276
279
  hold.sku,
277
280
  hold.locationId,
278
281
  hold.quantity,
279
- ...(input.admissionStatement
282
+ ...(currentMirror
280
283
  ? [input.tenantId, input.stage, hold.sku, hold.locationId]
281
284
  : [hold.onHand]),
282
285
  ];
@@ -301,7 +304,9 @@ function allocationInsert(input: ReserveInput, hold: ReserveHold, seenAt: string
301
304
  WHERE tenant_id = ? AND stage = ? AND order_id = ?
302
305
  )
303
306
  ${input.providerCart ? `AND EXISTS (SELECT 1 FROM commerce_provider_carts WHERE tenant_id=? AND stage=? AND provider=? AND provider_cart_id=? AND authorization_id=? AND provider_cart_digest=?)` : ""}
304
- ON CONFLICT DO NOTHING
307
+ ${input.manualInvoice ? `ON CONFLICT(tenant_id,stage,order_id,sku,location_id)
308
+ DO UPDATE SET quantity=excluded.quantity,state='reserved' WHERE scrappy_allocations.state IN ('expired','released')`
309
+ : "ON CONFLICT DO NOTHING"}
305
310
  RETURNING order_id`,
306
311
  params: [
307
312
  input.tenantId,
@@ -337,7 +342,9 @@ export async function reserveAllocation(runner: StatementRunner, input: ReserveI
337
342
  const malformed = reserveShape(input);
338
343
  if (malformed) return malformed;
339
344
  const cart = input.providerCart;
340
- if (!!cart !== !!input.admissionStatement) return { ok: false, finding: "malformed-request" };
345
+ if (!!cart !== !!input.admissionStatement || (input.manualInvoice && (!input.authorizationGuard || cart))) {
346
+ return { ok: false, finding: "malformed-request" };
347
+ }
341
348
  if (cart && (!input.admissionStatement || cart.provider !== "foxycart" || !/^[a-zA-Z0-9._:-]{1,128}$/.test(cart.id) || !DIGEST_RE.test(cart.digest) ||
342
349
  (cart.expectedAuthorizationId !== undefined && !ID_RE.test(cart.expectedAuthorizationId)))) return { ok: false, finding: "malformed-request" };
343
350
  const seen = await runner.all(
@@ -392,7 +399,10 @@ export async function reserveAllocation(runner: StatementRunner, input: ReserveI
392
399
  SELECT 1 FROM scrappy_caller_replay
393
400
  WHERE tenant_id = ? AND stage = ? AND issuer = ? AND jti = ? AND seen_at = ?
394
401
  )
395
- ON CONFLICT DO NOTHING
402
+ ${input.manualInvoice ? `ON CONFLICT(tenant_id,stage,authorization_id)
403
+ DO UPDATE SET cart_digest=excluded.cart_digest,expires_at=excluded.expires_at,state='active'
404
+ WHERE scrappy_final_cart_authorizations.state='expired'`
405
+ : "ON CONFLICT DO NOTHING"}
396
406
  RETURNING authorization_id`,
397
407
  params: [
398
408
  input.tenantId,
@@ -780,13 +790,12 @@ function rowsScope(rows: readonly Record<string, unknown>[]): AvailabilityScope
780
790
  return itemScope(rows.map((row) => ({ sku: text(row, "sku"), locationId: text(row, "location_id") })));
781
791
  }
782
792
 
783
- /** Move reserved units to confirmed once. A second call decrements nothing. */
784
- export async function confirmHoldOnce(
785
- runner: StatementRunner,
786
- input: { tenantId: string; stage: CommerceStage; orderId: string },
787
- ): Promise<{ decremented: number; states: string[] }> {
793
+ type ConfirmHoldInput = { tenantId: string; stage: CommerceStage; orderId: string; requireUnexpired?: true };
794
+
795
+ /** The stock writes callers can compose into the transaction that authorizes payment. */
796
+ export function confirmHoldStatements(input: ConfirmHoldInput): SqlStatement[] {
788
797
  const scope = [input.tenantId, input.stage, input.orderId];
789
- const results = await runner.batch([
798
+ return [
790
799
  {
791
800
  sql: `UPDATE scrappy_allocations
792
801
  SET state = 'confirmed'
@@ -800,6 +809,7 @@ export async function confirmHoldOnce(
800
809
  AND EXISTS (
801
810
  SELECT 1 FROM scrappy_final_cart_authorizations
802
811
  WHERE tenant_id = ? AND stage = ? AND authorization_id = ? AND state = 'active'
812
+ ${input.requireUnexpired ? "AND julianday(expires_at) > julianday('now')" : ""}
803
813
  )
804
814
  RETURNING sku, location_id, quantity`,
805
815
  params: [...scope, ...scope, ...scope],
@@ -828,6 +838,18 @@ export async function confirmHoldOnce(
828
838
  RETURNING order_id`,
829
839
  params: [...scope, ...scope],
830
840
  },
841
+ ];
842
+ }
843
+
844
+ /** Move reserved units to confirmed once. A second call decrements nothing. */
845
+ export async function confirmHoldOnce(
846
+ runner: StatementRunner,
847
+ input: ConfirmHoldInput,
848
+ ): Promise<{ decremented: number; states: string[] }> {
849
+ const scope = [input.tenantId, input.stage, input.orderId];
850
+ const statements = confirmHoldStatements(input);
851
+ const results = await runner.batch([
852
+ ...statements,
831
853
  {
832
854
  sql: `SELECT state, sku, location_id FROM scrappy_allocations
833
855
  WHERE tenant_id = ? AND stage = ? AND order_id = ?`,
@@ -835,7 +857,7 @@ export async function confirmHoldOnce(
835
857
  },
836
858
  ]);
837
859
  const confirmedRows = results[0] ?? [];
838
- const allAllocations = results[3] ?? [];
860
+ const allAllocations = results[statements.length] ?? [];
839
861
  const confirmedTargets = new Map<string, { sku: string; locationId: string }>();
840
862
  for (const row of allAllocations) {
841
863
  if (text(row, "state") !== "confirmed") continue;
@@ -9,7 +9,7 @@ import {
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 { evaluateFinalCart, type RefusedLine, type SeamView } from "@/lib/checkout/commerce/finalCartAuthorization.js";
12
+ import { CHECKOUT_ADMISSION_TTL_MS, FULFILLMENT_EVIDENCE_TTL_MS, 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";
@@ -35,10 +35,6 @@ import { shopperVariantPrice } from "@/lib/customers/accounts/pricing";
35
35
  import { resolveShopperAccessPolicy } from "@tot/public-runtime/declared-tenant-config";
36
36
  export const prerender = false;
37
37
  const HEX = /^[a-f0-9]{64}$/;
38
- /** Checkout authorization window (reservation + payment completion). */
39
- const CHECKOUT_ADMISSION_TTL_MS = 5 * 60_000;
40
- /** Post-capture compliance evidence validity horizon for order fulfillment. */
41
- const FULFILLMENT_EVIDENCE_TTL_MS = 30 * 24 * 60 * 60_000;
42
38
  /** The shopper's verification correlation handle, as the signed `verification` cart option carries it. */
43
39
  const VERIFICATION_REF = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,199}$/;
44
40
  function json(body: unknown, status = 200): Response {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.8.8",
3
+ "version": "7.8.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",