@tokenoftrust/storefront-runner 6.12.3 → 6.12.5

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.
@@ -84,6 +84,7 @@ import {
84
84
  appWritePredicate,
85
85
  idempotencyInsertStatement,
86
86
  labelOutcomeRecord,
87
+ labelVoidedRecord,
87
88
  parseStoredLabelFacts,
88
89
  replayedResponse,
89
90
  sameLabelFacts,
@@ -93,6 +94,7 @@ import {
93
94
  type AppWriteView,
94
95
  type HandoffEvidence,
95
96
  type LabelOutcomeEvidence,
97
+ type LabelVoidedEvidence,
96
98
  type StoredLabelFacts,
97
99
  } from "./appShipmentEvidence.js";
98
100
  import {
@@ -250,7 +252,12 @@ interface LoadedOrder {
250
252
  cancelPending: boolean;
251
253
  packingSlip: PackingSlip | null;
252
254
  shipment: { labelPurchaseState: string; handoffState: string } | null;
255
+ /** The open label_purchase operation (intent, accepted or unknown), or null when none is open. */
253
256
  provider: { purchaseId: string; outcome: ProviderOutcome } | null;
257
+ /** The latest settled label_purchase operation, read only by the desk's label outcome and view. */
258
+ settledProvider: { purchaseId: string; outcome: ProviderOutcome } | null;
259
+ /** The number of voided label_purchase operations: the purchase attempt the next id belongs to. */
260
+ labelGeneration: number;
254
261
  labelOutcome: StoredLabelFacts | null;
255
262
  carrierAccountId: string | null;
256
263
  prohibitedCarriers: string[];
@@ -395,11 +402,41 @@ async function digestHex(content: string): Promise<string> {
395
402
  return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
396
403
  }
397
404
 
398
- async function purchaseIdFor(tenantId: string, stage: CommerceStage, orderId: string): Promise<string> {
399
- const digest = await digestHex(`scrappy-label-intent-v1\n${tenantId}\n${stage}\n${orderId}`);
405
+ /**
406
+ * The platform purchase id of an order's label attempt. `generation` is the number of voided
407
+ * label_purchase operations for the order, so each attempt after a void has a distinct id and a
408
+ * message naming an earlier attempt cannot touch the current one. Generation 0 omits the suffix.
409
+ */
410
+ async function purchaseIdFor(tenantId: string, stage: CommerceStage, orderId: string, generation: number): Promise<string> {
411
+ const suffix = generation > 0 ? `\n${generation}` : "";
412
+ const digest = await digestHex(`scrappy-label-intent-v1\n${tenantId}\n${stage}\n${orderId}${suffix}`);
400
413
  return `label_${digest.slice(0, 32)}`;
401
414
  }
402
415
 
416
+ /** The purchase ids an app message is judged against: this attempt's, and the just-voided one's. */
417
+ interface PurchaseAttempt {
418
+ current: string;
419
+ previous: string | null;
420
+ }
421
+
422
+ /**
423
+ * Where a message's purchase id stands. `current` names this attempt (and the open operation, when
424
+ * one is open). `settled` names the just-voided attempt while no newer attempt is open. Anything
425
+ * else is `stale`.
426
+ */
427
+ function attemptStanding(state: LoadedOrder, attempt: PurchaseAttempt, purchaseId: string): "current" | "settled" | "stale" {
428
+ if (state.provider) return state.provider.purchaseId === attempt.current && purchaseId === attempt.current ? "current" : "stale";
429
+ if (purchaseId === attempt.current) return "current";
430
+ return attempt.previous !== null && purchaseId === attempt.previous ? "settled" : "stale";
431
+ }
432
+
433
+ async function purchaseAttempt(order: LoadedOrder["order"], generation: number): Promise<PurchaseAttempt> {
434
+ return {
435
+ current: await purchaseIdFor(order.tenantId, order.stage, order.orderId, generation),
436
+ previous: generation > 0 ? await purchaseIdFor(order.tenantId, order.stage, order.orderId, generation - 1) : null,
437
+ };
438
+ }
439
+
403
440
  function observedEvent(input: {
404
441
  eventVersion: number;
405
442
  orderId: string;
@@ -947,7 +984,8 @@ export class FulfillmentService {
947
984
  const mapped = labelOutcomeColumns(input.outcome);
948
985
  return this.commit(actor, orderId, input.expectedVersion, (state) => {
949
986
  if (state.assignment) return { type: "refuse", code: "processor-assigned" };
950
- if (!state.shipment || !state.provider) return { type: "refuse", code: "label" };
987
+ const operation = state.provider ?? state.settledProvider;
988
+ if (!state.shipment || !operation) return { type: "refuse", code: "label" };
951
989
  if (state.order.fulfillment === "handed_off") return { type: "refuse", code: "fulfillment" };
952
990
  if (state.shipment.labelPurchaseState === mapped.shipment && state.labelOutcome?.adultSignature === input.adultSignature) {
953
991
  return { type: "done", view: state.view };
@@ -1004,7 +1042,7 @@ export class FulfillmentService {
1004
1042
  state.order.tenantId,
1005
1043
  state.order.stage,
1006
1044
  state.order.orderId,
1007
- state.provider.purchaseId,
1045
+ operation.purchaseId,
1008
1046
  state.order.tenantId,
1009
1047
  state.order.stage,
1010
1048
  state.order.orderId,
@@ -1047,14 +1085,17 @@ export class FulfillmentService {
1047
1085
 
1048
1086
  /**
1049
1087
  * The processor's label outcome under its assignment, from `app:<installId>` only. The first
1050
- * outcome opens the whole-order shipment and its label operation under the platform purchase id.
1088
+ * outcome of an attempt opens its label operation under that attempt's platform purchase id (and
1089
+ * the whole-order shipment, on the first attempt). A purchase id of another attempt is a conflict;
1090
+ * the just-voided id is answered only while its terminal `voided` outcome still stands.
1051
1091
  */
1052
1092
  async appRecordLabelOutcome(request: AppEvidenceRequest<LabelOutcomeEvidence>): Promise<AppEvidenceResponse> {
1053
1093
  const evidence = request.evidence;
1054
- return this.appCommit(request, async (state, binding, purchaseId) => {
1055
- if (evidence.purchaseId !== purchaseId || (state.provider && state.provider.purchaseId !== purchaseId)) {
1056
- return { type: "refuse", code: "conflict" };
1057
- }
1094
+ return this.appCommit(request, async (state, binding, attempt) => {
1095
+ const standing = attemptStanding(state, attempt, evidence.purchaseId);
1096
+ const terminalVoid = standing === "settled" && state.shipment?.labelPurchaseState === "voided";
1097
+ if (standing === "stale" || (standing === "settled" && !terminalVoid)) return { type: "refuse", code: "conflict" };
1098
+ const purchaseId = evidence.purchaseId;
1058
1099
  const current = state.shipment?.labelPurchaseState ?? "none";
1059
1100
  const unchanged = { type: "done", view: appShipmentView(state, purchaseId) } as const;
1060
1101
  if (current === "purchased") {
@@ -1085,7 +1126,9 @@ export class FulfillmentService {
1085
1126
  params: [mapped.order, order.tenantId, order.stage, order.orderId, order.eventVersion, order.label, ...predicate.params],
1086
1127
  },
1087
1128
  ];
1088
- if (!state.shipment) statements.push(...(await this.intentStatements(state, actorId, version, nextStamp, { assigned: true })));
1129
+ if (!state.shipment || !state.provider) {
1130
+ statements.push(...(await this.intentStatements(state, actorId, version, nextStamp, { assigned: true })));
1131
+ }
1089
1132
  statements.push(
1090
1133
  {
1091
1134
  sql: `UPDATE scrappy_shipments
@@ -1123,10 +1166,11 @@ export class FulfillmentService {
1123
1166
  /** The processor's confirmed handoff under its assignment: every desk handoff gate, the label carrier, one order.fulfilled. */
1124
1167
  async appConfirmHandoff(request: AppEvidenceRequest<HandoffEvidence>): Promise<AppEvidenceResponse> {
1125
1168
  const evidence = request.evidence;
1126
- return this.appCommit(request, async (state, binding, purchaseId) => {
1127
- if (evidence.purchaseId !== purchaseId || (state.provider && state.provider.purchaseId !== purchaseId)) {
1128
- return { type: "refuse", code: "conflict" };
1129
- }
1169
+ return this.appCommit(request, async (state, binding, attempt) => {
1170
+ const standing = attemptStanding(state, attempt, evidence.purchaseId);
1171
+ const terminalVoid = standing === "settled" && state.shipment?.labelPurchaseState === "voided";
1172
+ if (standing === "stale" || (standing === "settled" && !terminalVoid)) return { type: "refuse", code: "conflict" };
1173
+ const purchaseId = evidence.purchaseId;
1130
1174
  const labelCarrier = state.labelOutcome?.carrier ?? null;
1131
1175
  if (state.shipment?.handoffState === "handed_off" || state.order.fulfillment === "handed_off") {
1132
1176
  return labelCarrier === evidence.carrier
@@ -1208,7 +1252,9 @@ export class FulfillmentService {
1208
1252
  const holds = releaseHolds(this.readiness(state));
1209
1253
  if (holds.length > 0) return { type: "refuse", code: holds[0]!, holds };
1210
1254
  if (state.order.fulfillment !== "ready") return { type: "refuse", code: "fulfillment" };
1211
- const labelInFlight = state.shipment !== null && state.shipment.labelPurchaseState !== "voided";
1255
+ // A label-voided reset leaves the whole-order shipment at `none`; only `voided` and `none` carry no label.
1256
+ const labelInFlight =
1257
+ state.shipment !== null && state.shipment.labelPurchaseState !== "voided" && state.shipment.labelPurchaseState !== "none";
1212
1258
  if (labelInFlight || !SPLIT_LABEL_STATES.includes(state.order.label)) return { type: "refuse", code: "whole-order-label" };
1213
1259
  if ((state.adultSignatureRequired || this.policy.adultSignatureRequired) && evidence.adultSignature !== "accepted") {
1214
1260
  return { type: "refuse", code: "adult-signature" };
@@ -1273,6 +1319,96 @@ export class FulfillmentService {
1273
1319
  });
1274
1320
  }
1275
1321
 
1322
+ /**
1323
+ * The processor voided the label of the current purchase attempt, before handoff. One batch:
1324
+ * the order CAS (install and assignment predicate, version, not handed off, shipment not handed
1325
+ * off, the open operation under this purchase id) resets the label to `none`; the shipment label
1326
+ * returns to `none`; the operation is marked voided and stays as history, which moves the order
1327
+ * to its next purchase attempt; a label-voided audit row records the voided purchase id. The
1328
+ * assignment stays active. The response names the next attempt's purchase id.
1329
+ */
1330
+ async appVoidLabel(request: AppEvidenceRequest<LabelVoidedEvidence>): Promise<AppEvidenceResponse> {
1331
+ const evidence = request.evidence;
1332
+ return this.appCommit(request, async (state, binding, attempt) => {
1333
+ const standing = attemptStanding(state, attempt, evidence.purchaseId);
1334
+ if (standing === "stale") return { type: "refuse", code: "conflict" };
1335
+ if (standing === "settled") return { type: "done", view: appShipmentView(state, attempt.current) };
1336
+ if ((state.shipment && state.shipment.handoffState !== "none") || state.order.fulfillment === "handed_off") {
1337
+ return { type: "refuse", code: "fulfillment" };
1338
+ }
1339
+ const open = state.provider;
1340
+ const recorded =
1341
+ open !== null &&
1342
+ (open.outcome === "accepted" || open.outcome === "unknown") &&
1343
+ (state.shipment?.labelPurchaseState === "purchased" || state.shipment?.labelPurchaseState === "unknown") &&
1344
+ (state.order.label === "purchased" || state.order.label === "printed" || state.order.label === "UNKNOWN");
1345
+ if (!recorded) return { type: "refuse", code: "label" };
1346
+ const { order } = state;
1347
+ const version = order.eventVersion + 1;
1348
+ const predicate = appWritePredicate(binding, order);
1349
+ const atVersion = {
1350
+ sql: `EXISTS (
1351
+ SELECT 1 FROM scrappy_commerce_orders
1352
+ WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
1353
+ )`,
1354
+ params: [order.tenantId, order.stage, order.orderId, version],
1355
+ };
1356
+ const next = await purchaseIdFor(order.tenantId, order.stage, order.orderId, state.labelGeneration + 1);
1357
+ return {
1358
+ type: "write",
1359
+ sourceAdvance: false,
1360
+ deliveries: [],
1361
+ statements: [
1362
+ {
1363
+ sql: `UPDATE scrappy_commerce_orders
1364
+ SET label_state = 'none', event_version = event_version + 1
1365
+ WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
1366
+ AND fulfillment_state != 'handed_off' AND label_state = ?
1367
+ AND EXISTS (
1368
+ SELECT 1 FROM scrappy_shipments AS s
1369
+ WHERE s.tenant_id = ? AND s.stage = ? AND s.order_id = ? AND s.handoff_state = 'none'
1370
+ )
1371
+ AND EXISTS (
1372
+ SELECT 1 FROM scrappy_provider_operations AS p
1373
+ WHERE p.tenant_id = ? AND p.stage = ? AND p.order_id = ? AND p.kind = 'label_purchase'
1374
+ AND p.purchase_id = ? AND p.outcome IN ('accepted', 'unknown')
1375
+ )
1376
+ AND ${predicate.sql}`,
1377
+ params: [
1378
+ order.tenantId, order.stage, order.orderId, order.eventVersion, order.label,
1379
+ order.tenantId, order.stage, order.orderId,
1380
+ order.tenantId, order.stage, order.orderId, evidence.purchaseId,
1381
+ ...predicate.params,
1382
+ ],
1383
+ },
1384
+ {
1385
+ sql: `UPDATE scrappy_shipments
1386
+ SET label_purchase_state = 'none', label_print_state = 'none'
1387
+ WHERE tenant_id = ? AND stage = ? AND order_id = ? AND handoff_state = 'none' AND ${atVersion.sql}`,
1388
+ params: [order.tenantId, order.stage, order.orderId, ...atVersion.params],
1389
+ },
1390
+ {
1391
+ sql: `UPDATE scrappy_provider_operations
1392
+ SET outcome = 'voided'
1393
+ WHERE tenant_id = ? AND stage = ? AND order_id = ? AND kind = 'label_purchase'
1394
+ AND purchase_id = ? AND outcome IN ('intent', 'accepted', 'unknown') AND ${atVersion.sql}`,
1395
+ params: [order.tenantId, order.stage, order.orderId, evidence.purchaseId, ...atVersion.params],
1396
+ },
1397
+ auditStatement(
1398
+ state,
1399
+ request.actor.actorId,
1400
+ "label-voided",
1401
+ order.label,
1402
+ jsonText(labelVoidedRecord(evidence.purchaseId)),
1403
+ version,
1404
+ stamp(this.now(), state.auditCount + 1),
1405
+ ),
1406
+ ],
1407
+ view: appShipmentView(state, next, { version, label: "none", facts: null }),
1408
+ };
1409
+ });
1410
+ }
1411
+
1276
1412
  /**
1277
1413
  * Lines of the processor's assignment it reports it cannot ship, for the operator desk. Every
1278
1414
  * release hold refuses, and each line's quantity is at most its remainder. Nothing is cancelled,
@@ -1356,7 +1492,7 @@ export class FulfillmentService {
1356
1492
  */
1357
1493
  private async appCommit(
1358
1494
  request: AppEvidenceRequest<{ assignmentId: string; expectedVersion?: number }>,
1359
- build: (state: LoadedOrder, binding: AppAssignmentBinding, purchaseId: string) => AppPlan | Promise<AppPlan>,
1495
+ build: (state: LoadedOrder, binding: AppAssignmentBinding, attempt: PurchaseAttempt) => AppPlan | Promise<AppPlan>,
1360
1496
  ): Promise<AppEvidenceResponse> {
1361
1497
  const binding = appBinding(request.actor, request.evidence.assignmentId);
1362
1498
  if (!binding) return appRefusal("denied");
@@ -1372,10 +1508,10 @@ export class FulfillmentService {
1372
1508
  if (assigned || !state) return appRefusal(assigned ?? "not-assigned");
1373
1509
  const expected = request.evidence.expectedVersion;
1374
1510
  if (expected !== undefined && state.order.eventVersion !== expected) return appRefusal("conflict");
1375
- const purchaseId = await purchaseIdFor(tenantId, stage, orderId);
1511
+ const attempt = await purchaseAttempt(state.order, state.labelGeneration);
1376
1512
  let plan: AppPlan;
1377
1513
  try {
1378
- plan = await build(state, binding, purchaseId);
1514
+ plan = await build(state, binding, attempt);
1379
1515
  } catch (error) {
1380
1516
  if (error instanceof CommercePayloadRefused) return appRefusal("malformed");
1381
1517
  throw error;
@@ -1634,7 +1770,8 @@ export class FulfillmentService {
1634
1770
  /** The assigned processor's first label outcome opens the shipment under its own assignment. */
1635
1771
  options: { assigned?: boolean } = {},
1636
1772
  ): Promise<SqlStatement[]> {
1637
- const purchaseId = state.provider?.purchaseId ?? (await purchaseIdFor(state.order.tenantId, state.order.stage, state.order.orderId));
1773
+ const purchaseId =
1774
+ state.provider?.purchaseId ?? (await purchaseIdFor(state.order.tenantId, state.order.stage, state.order.orderId, state.labelGeneration));
1638
1775
  const intent = {
1639
1776
  purchaseId,
1640
1777
  adultSignatureRequired: this.policy.adultSignatureRequired,
@@ -1752,7 +1889,14 @@ export class FulfillmentService {
1752
1889
  version,
1753
1890
  now: this.now(),
1754
1891
  }),
1755
- ...insertAssignmentLinesStatements({ assignmentId, version, lines: state.routing.lines }),
1892
+ ...insertAssignmentLinesStatements({
1893
+ assignmentId,
1894
+ tenantId: order.tenantId,
1895
+ stage: order.stage,
1896
+ orderId: order.orderId,
1897
+ version,
1898
+ lines: state.routing.lines,
1899
+ }),
1756
1900
  ],
1757
1901
  deliveries: [],
1758
1902
  };
@@ -1856,7 +2000,7 @@ export class FulfillmentService {
1856
2000
  stage: input.stage,
1857
2001
  eventVersion: state.order.eventVersion,
1858
2002
  assignedAt: row.assigned_at,
1859
- purchaseId: await purchaseIdFor(input.tenantId, input.stage, row.order_id),
2003
+ purchaseId: await purchaseIdFor(input.tenantId, input.stage, row.order_id, state.labelGeneration),
1860
2004
  lineItems: state.lines.map((line) => ({ sku: line.sku, quantity: line.quantity })),
1861
2005
  locationId: state.assignment.locationId,
1862
2006
  allowedCarriers: allowedCarriers(this.policy.prohibitedCarriers, state.prohibitedCarriers),
@@ -2209,6 +2353,7 @@ export class FulfillmentService {
2209
2353
  else if (audit.kind === "pending-cancel") cancelPending = audit.to_state === "open";
2210
2354
  else if (audit.kind === "packing-slip") packingSlip = parseSlip(parseJson(audit.to_state));
2211
2355
  else if (audit.kind === "label-outcome") labelOutcome = parseStoredLabelFacts(parseJson(audit.to_state));
2356
+ else if (audit.kind === "label-voided") labelOutcome = null;
2212
2357
  else if (audit.kind === "label-intent") {
2213
2358
  const intent = parseJson(audit.to_state);
2214
2359
  if (isRecord(intent)) {
@@ -2223,7 +2368,12 @@ export class FulfillmentService {
2223
2368
  if(evidenceExpiresAt && (!Number.isFinite(Date.parse(evidenceExpiresAt)) || Date.parse(evidenceExpiresAt)<=Date.parse(this.now()))) {
2224
2369
  evidence={verification:"stale",tax:"stale",risk:"stale",stock:"stale"};
2225
2370
  }
2226
- const provider = pickProvider(providers);
2371
+ const provider = openProvider(providers);
2372
+ const labelGeneration = providers.filter((row) => row.outcome === "voided").length;
2373
+ const lastVoided = labelGeneration > 0
2374
+ ? await purchaseIdFor(tenantId, stage, orderId, labelGeneration - 1)
2375
+ : null;
2376
+ const settledProvider = provider ? null : settledOperation(providers, lastVoided);
2227
2377
  const order = {
2228
2378
  tenantId,
2229
2379
  stage: row.stage,
@@ -2266,6 +2416,8 @@ export class FulfillmentService {
2266
2416
  ? { labelPurchaseState: shipment.label_purchase_state, handoffState: shipment.handoff_state }
2267
2417
  : null,
2268
2418
  provider,
2419
+ settledProvider,
2420
+ labelGeneration,
2269
2421
  labelOutcome,
2270
2422
  carrierAccountId: intentAccount,
2271
2423
  prohibitedCarriers: intentProhibited,
@@ -2305,7 +2457,7 @@ export class FulfillmentService {
2305
2457
  loaded.view.shipment = loaded.shipment
2306
2458
  ? {
2307
2459
  scope: "whole-order",
2308
- purchaseId: provider?.purchaseId ?? null,
2460
+ purchaseId: (provider ?? settledProvider)?.purchaseId ?? null,
2309
2461
  labelPurchaseState: loaded.shipment.labelPurchaseState,
2310
2462
  handoffState: loaded.shipment.handoffState,
2311
2463
  vendorSelected: false,
@@ -2365,7 +2517,7 @@ function assignmentOrderCas(
2365
2517
  ? `AND label_state IN (${SPLIT_LABEL_STATES.map(() => "?").join(", ")})
2366
2518
  AND NOT EXISTS (
2367
2519
  SELECT 1 FROM scrappy_shipments AS s
2368
- WHERE s.tenant_id = ? AND s.stage = ? AND s.order_id = ? AND s.label_purchase_state <> 'voided'
2520
+ WHERE s.tenant_id = ? AND s.stage = ? AND s.order_id = ? AND s.label_purchase_state NOT IN ('none', 'voided')
2369
2521
  )`
2370
2522
  : "";
2371
2523
  return {
@@ -2652,10 +2804,17 @@ function parseJson(value: string): unknown {
2652
2804
  }
2653
2805
  }
2654
2806
 
2655
- function pickProvider(rows: readonly { purchase_id: string; outcome: string }[]): LoadedOrder["provider"] {
2807
+ /** The open label_purchase operation; the unique index allows at most one. */
2808
+ function openProvider(rows: readonly { purchase_id: string; outcome: string }[]): LoadedOrder["provider"] {
2656
2809
  const open = rows.find((row) => row.outcome === "intent" || row.outcome === "accepted" || row.outcome === "unknown");
2657
- const chosen = open ?? rows[0];
2658
- if (!chosen || !oneOf(chosen.outcome, ["intent", "accepted", "unknown", "voided", "refunded"] as const)) return null;
2810
+ if (!open || !oneOf(open.outcome, ["intent", "accepted", "unknown"] as const)) return null;
2811
+ return { purchaseId: open.purchase_id, outcome: open.outcome };
2812
+ }
2813
+
2814
+ /** With none open, the operation of the latest voided attempt, else any settled one. */
2815
+ function settledOperation(rows: readonly { purchase_id: string; outcome: string }[], lastVoided: string | null): LoadedOrder["settledProvider"] {
2816
+ const chosen = rows.find((row) => row.purchase_id === lastVoided) ?? rows[0];
2817
+ if (!chosen || !oneOf(chosen.outcome, ["voided", "refunded"] as const)) return null;
2659
2818
  return { purchaseId: chosen.purchase_id, outcome: chosen.outcome };
2660
2819
  }
2661
2820
 
@@ -20,7 +20,14 @@ import {
20
20
  } from "@tot/public-runtime";
21
21
  import type { SourceReadiness } from "../orders/data/sourceAuthorityStore.js";
22
22
  import { COMPLIANCE_RULE_PROFILES } from "@/config/compliance/rulesets";
23
- import { canonicalCarrier, carrierProhibited, type CarrierCode } from "./carrierEvidence.js";
23
+ import {
24
+ CARRIER_CATALOG,
25
+ canonicalCarrier,
26
+ carrierCatalogEntry,
27
+ carrierProhibited,
28
+ type CarrierCatalogEntry,
29
+ type CarrierCode,
30
+ } from "./carrierEvidence.js";
24
31
 
25
32
  export const RELEASE_HOLDS = [
26
33
  "source-check-pending",
@@ -54,6 +61,8 @@ export type ReleaseHold = (typeof RELEASE_HOLDS)[number];
54
61
 
55
62
  export interface CarrierPolicy {
56
63
  adultSignatureRequired: boolean;
64
+ /** The tenant's compliance profile enables PACT: only statutorily eligible carriers may carry its parcels. */
65
+ pactEnabled: boolean;
57
66
  prohibitedCarriers: readonly string[];
58
67
  /** Null when the tenant has not configured an account. Absence is not a hold. */
59
68
  carrierAccountId: string | null;
@@ -153,34 +162,54 @@ export function carrierPolicyForTenant(tenant: {
153
162
  const enabled = ruleset?.pactAct.enabled === true;
154
163
  return {
155
164
  adultSignatureRequired: enabled && ruleset.pactAct.adultSignatureRequired === true,
165
+ pactEnabled: enabled,
156
166
  prohibitedCarriers: enabled ? [...ruleset.pactAct.prohibitedCarriers] : [],
157
167
  carrierAccountId,
158
168
  };
159
169
  }
160
170
 
161
- /** A supplied carrier is never a selection. USPS is refused when the policy prohibits it. */
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. */
162
190
  export function carrierSelectionRefusal(
163
191
  policy: CarrierPolicy,
164
192
  carrier: string | undefined,
193
+ catalog: readonly CarrierCatalogEntry[] = CARRIER_CATALOG,
165
194
  ): "carrier-prohibited" | "vendor-not-selected" | null {
166
195
  if (carrier === undefined) return null;
167
- const normalized = carrier.trim().toUpperCase();
168
- if (normalized === "") return "vendor-not-selected";
169
- if (policy.prohibitedCarriers.some((item) => item.toUpperCase() === normalized)) return "carrier-prohibited";
170
- return "vendor-not-selected";
196
+ if (canonicalCarrier(carrier) === "") return "vendor-not-selected";
197
+ return carrierPolicyRefusal(carrier, policy, catalog) ?? "vendor-not-selected";
171
198
  }
172
199
 
173
200
  /**
174
- * A processor's reported carrier. Prohibited when it is in the current policy's set or the order's
175
- * label-intent snapshot; a handoff carrier must equal the carrier its label was bought with.
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.
176
203
  */
177
204
  export function carrierEvidenceRefusal(input: {
178
205
  carrier: CarrierCode;
179
206
  policy: CarrierPolicy;
180
207
  snapshotProhibited: readonly string[];
181
208
  labelCarrier?: string | null;
209
+ catalog?: readonly CarrierCatalogEntry[];
182
210
  }): "carrier-prohibited" | "carrier-mismatch" | null {
183
- if (carrierProhibited(input.carrier, input.policy.prohibitedCarriers, input.snapshotProhibited)) return "carrier-prohibited";
211
+ if (carrierPolicyRefusal(input.carrier, input.policy, input.catalog)) return "carrier-prohibited";
212
+ if (carrierProhibited(input.carrier, input.snapshotProhibited)) return "carrier-prohibited";
184
213
  if (input.labelCarrier !== undefined && (input.labelCarrier === null || canonicalCarrier(input.labelCarrier) !== input.carrier)) {
185
214
  return "carrier-mismatch";
186
215
  }
@@ -15,7 +15,9 @@
15
15
  * `sha256Hex` carries no control-plane logic, so it lives in the
16
16
  * renderer-safe package instead (see `hash.ts` there). The plaintext secret
17
17
  * is returned exactly once, from `issue`/`rotate`, and never again;
18
- * `verifySecret` only ever compares hashes.
18
+ * `verifySecret` only ever compares hashes, and refuses a credential whose `auth_method` is
19
+ * `private_key_jwt` (that client authenticates only by RFC 7523 client assertion,
20
+ * `admin/clientAssertion.ts`).
19
21
  */
20
22
  import { sha256Hex } from "@tot/public-runtime";
21
23
  import type { CredentialPort, IssuedCredential } from "./registryService.js";
@@ -43,6 +45,59 @@ interface CredentialRow {
43
45
  secret_created_at: string;
44
46
  rotated_at: string | null;
45
47
  jwks_kid: string;
48
+ auth_method: CredentialAuthMethod;
49
+ }
50
+
51
+ /** How a credential's client authenticates at the token endpoint (`app_credentials.auth_method`). */
52
+ export type CredentialAuthMethod = "client_secret" | "private_key_jwt";
53
+
54
+ /**
55
+ * The stored secret hash of a key-bound (`private_key_jwt`) credential: the hash of random bytes
56
+ * that are discarded at once, so no secret for the client exists anywhere.
57
+ */
58
+ export async function discardedSecretHash(): Promise<string> {
59
+ return sha256Hex(randomSecret());
60
+ }
61
+
62
+ /**
63
+ * The statements that bind an install's client to `private_key_jwt`: the credential switches its
64
+ * method and replaces its secret hash with {@link discardedSecretHash}, and the install's key row
65
+ * is written or replaced. `WHERE` clauses bind both to the install on its tenant.
66
+ */
67
+ export async function bindClientKeysStatements(input: {
68
+ installId: string;
69
+ tenantId: string;
70
+ jwks: string | null;
71
+ jwksUri: string | null;
72
+ actor: string;
73
+ now: string;
74
+ }): Promise<{ sql: string; params: unknown[] }[]> {
75
+ return [
76
+ {
77
+ sql: `UPDATE app_credentials SET auth_method = 'private_key_jwt', secret_hash = ?, rotated_at = ?
78
+ WHERE install_id = ?
79
+ AND EXISTS (SELECT 1 FROM app_installs WHERE install_id = ? AND tenant_id = ?)`,
80
+ params: [await discardedSecretHash(), input.now, input.installId, input.installId, input.tenantId],
81
+ },
82
+ {
83
+ sql: `INSERT INTO app_client_keys (key_set_id, install_id, candidate_id, tenant_id, jwks, jwks_uri, updated_at, updated_by)
84
+ SELECT ?, ?, NULL, ?, ?, ?, ?, ?
85
+ WHERE EXISTS (SELECT 1 FROM app_credentials WHERE install_id = ? AND auth_method = 'private_key_jwt')
86
+ ON CONFLICT (install_id) DO UPDATE
87
+ SET jwks = excluded.jwks, jwks_uri = excluded.jwks_uri,
88
+ updated_at = excluded.updated_at, updated_by = excluded.updated_by`,
89
+ params: [
90
+ crypto.randomUUID(),
91
+ input.installId,
92
+ input.tenantId,
93
+ input.jwks,
94
+ input.jwksUri,
95
+ input.now,
96
+ input.actor,
97
+ input.installId,
98
+ ],
99
+ },
100
+ ];
46
101
  }
47
102
 
48
103
  /** High-entropy secret bytes (256 bits) before base64url encoding. */
@@ -138,6 +193,8 @@ export class D1CredentialStore implements CredentialPort {
138
193
  return null;
139
194
  }
140
195
  const presentedHash = await sha256Hex(presentedSecret);
196
+ // A key-bound client authenticates only by client assertion; no secret is ever accepted for it.
197
+ if (row.auth_method !== "client_secret") return null;
141
198
  if (!timingSafeEqualHex(presentedHash, row.secret_hash)) return null;
142
199
  return row.install_id;
143
200
  }