@tokenoftrust/storefront-runner 6.12.4 → 6.12.6

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.
@@ -0,0 +1,133 @@
1
+ -- How an install's client authenticates at the token endpoint. A private_key_jwt credential keeps a
2
+ -- secret_hash of discarded random bytes, and the secret path refuses it.
3
+ ALTER TABLE `app_credentials` ADD `auth_method` text DEFAULT 'client_secret' NOT NULL
4
+ CHECK (`auth_method` IN ('client_secret', 'private_key_jwt'));
5
+ --> statement-breakpoint
6
+ -- Public client keys for private_key_jwt: a validated public JWKS or a jwks_uri, bound to exactly one
7
+ -- install or one production candidate. Opaque actor ids only. Never deleted; a candidate's key set
8
+ -- is part of its immutable snapshot.
9
+ CREATE TABLE `app_client_keys` (
10
+ `key_set_id` text PRIMARY KEY NOT NULL,
11
+ `install_id` text,
12
+ `candidate_id` text,
13
+ `tenant_id` text NOT NULL,
14
+ `jwks` text,
15
+ `jwks_uri` text,
16
+ `updated_at` text NOT NULL,
17
+ `updated_by` text NOT NULL,
18
+ CHECK ((`install_id` IS NULL) <> (`candidate_id` IS NULL)),
19
+ CHECK ((`jwks` IS NULL) <> (`jwks_uri` IS NULL))
20
+ );
21
+ --> statement-breakpoint
22
+ CREATE UNIQUE INDEX `app_client_keys_install` ON `app_client_keys` (`install_id`);
23
+ --> statement-breakpoint
24
+ CREATE UNIQUE INDEX `app_client_keys_candidate` ON `app_client_keys` (`candidate_id`);
25
+ --> statement-breakpoint
26
+ CREATE TRIGGER `app_client_keys_no_delete`
27
+ BEFORE DELETE ON `app_client_keys`
28
+ BEGIN
29
+ SELECT RAISE(ABORT, 'append-only');
30
+ END;
31
+ --> statement-breakpoint
32
+ CREATE TRIGGER `app_client_keys_binding_fixed`
33
+ BEFORE UPDATE ON `app_client_keys`
34
+ WHEN OLD.`candidate_id` IS NOT NULL
35
+ OR NEW.`key_set_id` IS NOT OLD.`key_set_id`
36
+ OR NEW.`install_id` IS NOT OLD.`install_id`
37
+ OR NEW.`candidate_id` IS NOT OLD.`candidate_id`
38
+ OR NEW.`tenant_id` IS NOT OLD.`tenant_id`
39
+ BEGIN
40
+ SELECT RAISE(ABORT, 'binding-fixed');
41
+ END;
42
+ --> statement-breakpoint
43
+ -- Single-use client assertion ids. Rows past exp_at (epoch seconds) plus the clock tolerance are
44
+ -- pruned on insert; nothing else deletes or updates them.
45
+ CREATE TABLE `app_client_assertion_jti` (
46
+ `client_id` text NOT NULL,
47
+ `jti` text NOT NULL,
48
+ `exp_at` integer NOT NULL,
49
+ PRIMARY KEY (`client_id`, `jti`)
50
+ );
51
+ --> statement-breakpoint
52
+ CREATE INDEX `idx_app_client_assertion_jti_exp` ON `app_client_assertion_jti` (`exp_at`);
53
+ --> statement-breakpoint
54
+ CREATE TRIGGER `app_client_assertion_jti_no_update`
55
+ BEFORE UPDATE ON `app_client_assertion_jti`
56
+ BEGIN
57
+ SELECT RAISE(ABORT, 'append-only');
58
+ END;
59
+ --> statement-breakpoint
60
+ -- A staged production install awaiting a human owner. The snapshot columns are immutable; the only
61
+ -- update is the single pending_approval -> approved|rejected transition. Rows are never deleted.
62
+ CREATE TABLE `app_install_candidates` (
63
+ `candidate_id` text PRIMARY KEY NOT NULL,
64
+ `tenant_id` text NOT NULL,
65
+ `app_id` text NOT NULL,
66
+ `app_version` text NOT NULL,
67
+ `env` text DEFAULT 'production' NOT NULL CHECK (`env` = 'production'),
68
+ `scopes` text NOT NULL,
69
+ `manifest` text NOT NULL,
70
+ `webhook_endpoint` text,
71
+ `widget_placements` text DEFAULT '[]' NOT NULL,
72
+ `client_id` text NOT NULL,
73
+ `request_consent` integer DEFAULT 0 NOT NULL CHECK (`request_consent` IN (0, 1)),
74
+ `snapshot_digest` text NOT NULL CHECK (length(`snapshot_digest`) = 64 AND `snapshot_digest` NOT GLOB '*[^0-9a-f]*'),
75
+ `status` text DEFAULT 'pending_approval' NOT NULL
76
+ CHECK (`status` IN ('pending_approval', 'approved', 'rejected')),
77
+ `staged_by` text NOT NULL,
78
+ `staged_at` text NOT NULL,
79
+ `decided_by` text,
80
+ `decided_at` text,
81
+ `decision_id` text,
82
+ `install_id` text,
83
+ CHECK (
84
+ (`status` = 'pending_approval' AND `decided_by` IS NULL AND `decided_at` IS NULL
85
+ AND `decision_id` IS NULL AND `install_id` IS NULL)
86
+ OR (`status` = 'approved' AND `decided_by` IS NOT NULL AND `decided_at` IS NOT NULL
87
+ AND `decision_id` IS NOT NULL AND `install_id` IS NOT NULL)
88
+ OR (`status` = 'rejected' AND `decided_by` IS NOT NULL AND `decided_at` IS NOT NULL
89
+ AND `decision_id` IS NOT NULL AND `install_id` IS NULL)
90
+ )
91
+ );
92
+ --> statement-breakpoint
93
+ CREATE UNIQUE INDEX `app_install_candidates_client_id` ON `app_install_candidates` (`client_id`);
94
+ --> statement-breakpoint
95
+ CREATE UNIQUE INDEX `app_install_candidates_one_pending`
96
+ ON `app_install_candidates` (`tenant_id`, `app_id`)
97
+ WHERE `status` = 'pending_approval';
98
+ --> statement-breakpoint
99
+ CREATE INDEX `idx_app_install_candidates_tenant` ON `app_install_candidates` (`tenant_id`, `staged_at`);
100
+ --> statement-breakpoint
101
+ CREATE TRIGGER `app_install_candidates_no_delete`
102
+ BEFORE DELETE ON `app_install_candidates`
103
+ BEGIN
104
+ SELECT RAISE(ABORT, 'append-only');
105
+ END;
106
+ --> statement-breakpoint
107
+ CREATE TRIGGER `app_install_candidates_decide_once`
108
+ BEFORE UPDATE ON `app_install_candidates`
109
+ WHEN OLD.`status` <> 'pending_approval'
110
+ BEGIN
111
+ SELECT RAISE(ABORT, 'decide-once');
112
+ END;
113
+ --> statement-breakpoint
114
+ CREATE TRIGGER `app_install_candidates_snapshot_immutable`
115
+ BEFORE UPDATE ON `app_install_candidates`
116
+ WHEN NEW.`status` = 'pending_approval'
117
+ OR NEW.`candidate_id` IS NOT OLD.`candidate_id`
118
+ OR NEW.`tenant_id` IS NOT OLD.`tenant_id`
119
+ OR NEW.`app_id` IS NOT OLD.`app_id`
120
+ OR NEW.`app_version` IS NOT OLD.`app_version`
121
+ OR NEW.`env` IS NOT OLD.`env`
122
+ OR NEW.`scopes` IS NOT OLD.`scopes`
123
+ OR NEW.`manifest` IS NOT OLD.`manifest`
124
+ OR NEW.`webhook_endpoint` IS NOT OLD.`webhook_endpoint`
125
+ OR NEW.`widget_placements` IS NOT OLD.`widget_placements`
126
+ OR NEW.`client_id` IS NOT OLD.`client_id`
127
+ OR NEW.`request_consent` IS NOT OLD.`request_consent`
128
+ OR NEW.`snapshot_digest` IS NOT OLD.`snapshot_digest`
129
+ OR NEW.`staged_by` IS NOT OLD.`staged_by`
130
+ OR NEW.`staged_at` IS NOT OLD.`staged_at`
131
+ BEGIN
132
+ SELECT RAISE(ABORT, 'snapshot-immutable');
133
+ END;
@@ -0,0 +1,38 @@
1
+ -- Declared stock locations, WMS movement reasons, and the projected availability per sku.
2
+ CREATE TABLE commerce_inventory_locations (
3
+ tenant_id TEXT NOT NULL, stage TEXT NOT NULL CHECK(stage IN ('preview','publication')),
4
+ location_id TEXT NOT NULL, name TEXT NOT NULL,
5
+ kind TEXT NOT NULL CHECK(kind IN ('warehouse','3pl','dropship_vendor','retail')),
6
+ is_fulfillable INTEGER NOT NULL DEFAULT 1 CHECK(is_fulfillable IN (0,1)),
7
+ status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active','archived')),
8
+ updated_at TEXT NOT NULL,
9
+ PRIMARY KEY(tenant_id,stage,location_id),
10
+ CHECK(location_id != 'unspecified' OR status = 'active')
11
+ );
12
+ ALTER TABLE commerce_inventory_movements ADD COLUMN reason TEXT
13
+ CHECK(reason IS NULL OR reason IN ('received','picked','restock','cycle_count','damaged','transfer','adjustment','reconcile'));
14
+ CREATE INDEX commerce_inventory_location_scope ON commerce_inventory_movements(tenant_id,stage,location_id,sku);
15
+ CREATE INDEX scrappy_allocations_sku_scope ON scrappy_allocations(tenant_id,stage,sku,location_id,state);
16
+ -- Last projected availability per sku: the change detector for inventory.changed and the source of the KV projection.
17
+ CREATE TABLE commerce_inventory_availability (
18
+ tenant_id TEXT NOT NULL, stage TEXT NOT NULL CHECK(stage IN ('preview','publication')),
19
+ sku TEXT NOT NULL, available INTEGER NOT NULL, version INTEGER NOT NULL DEFAULT 0, as_of TEXT NOT NULL,
20
+ PRIMARY KEY(tenant_id,stage,sku)
21
+ );
22
+ -- Never holds a row: a batch inserts 1 here to abort its whole transaction when any item is refused.
23
+ CREATE TABLE commerce_inventory_batch_guard (
24
+ refused INTEGER NOT NULL, CONSTRAINT inventory_batch_refused CHECK(refused = 0)
25
+ );
26
+ INSERT OR IGNORE INTO commerce_inventory_locations (tenant_id,stage,location_id,name,kind,is_fulfillable,status,updated_at)
27
+ SELECT tenant_id, stage, 'unspecified', 'Unspecified', 'warehouse', 1, 'active', strftime('%Y-%m-%dT%H:%M:%fZ','now')
28
+ FROM (SELECT tenant_id, stage FROM commerce_inventory_movements UNION SELECT tenant_id, stage FROM scrappy_allocations);
29
+ INSERT OR IGNORE INTO commerce_inventory_locations (tenant_id,stage,location_id,name,kind,is_fulfillable,status,updated_at)
30
+ SELECT tenant_id, stage, location_id, location_id, 'warehouse', 1, 'active', strftime('%Y-%m-%dT%H:%M:%fZ','now')
31
+ FROM (SELECT tenant_id, stage, location_id FROM commerce_inventory_movements
32
+ UNION SELECT tenant_id, stage, location_id FROM scrappy_allocations);
33
+ INSERT OR IGNORE INTO commerce_inventory_availability (tenant_id,stage,sku,available,version,as_of)
34
+ SELECT m.tenant_id, m.stage, m.sku,
35
+ SUM(m.quantity_delta) - COALESCE((SELECT SUM(a.quantity) FROM scrappy_allocations AS a
36
+ WHERE a.tenant_id = m.tenant_id AND a.stage = m.stage AND a.sku = m.sku AND a.state IN ('reserved','confirmed')), 0),
37
+ 0, MAX(m.as_of)
38
+ FROM commerce_inventory_movements AS m GROUP BY m.tenant_id, m.stage, m.sku;
@@ -38,7 +38,15 @@ export interface HandoffEvidence {
38
38
  expectedVersion?: number;
39
39
  }
40
40
 
41
- export type ShipmentEvidence = LabelOutcomeEvidence | HandoffEvidence;
41
+ /** The processor voided the label it bought under `purchaseId`, before handoff. */
42
+ export interface LabelVoidedEvidence {
43
+ kind: "label-voided";
44
+ assignmentId: string;
45
+ purchaseId: string;
46
+ expectedVersion?: number;
47
+ }
48
+
49
+ export type ShipmentEvidence = LabelOutcomeEvidence | HandoffEvidence | LabelVoidedEvidence;
42
50
 
43
51
  export interface AppShipmentView {
44
52
  orderId: string;
@@ -89,6 +97,12 @@ const LABEL_KEYS = new Set([
89
97
  "expectedVersion",
90
98
  ]);
91
99
  const HANDOFF_KEYS = new Set(["kind", "assignmentId", "purchaseId", "carrier", "expectedVersion"]);
100
+ const VOIDED_KEYS = new Set(["kind", "assignmentId", "purchaseId", "expectedVersion"]);
101
+ const KEYS_BY_KIND: Readonly<Record<string, ReadonlySet<string>>> = {
102
+ "label-outcome": LABEL_KEYS,
103
+ handoff: HANDOFF_KEYS,
104
+ "label-voided": VOIDED_KEYS,
105
+ };
92
106
  const PURCHASED_REQUIRES = ["carrier", "service", "trackingNumber", "trackingUrl", "adultSignature"] as const;
93
107
 
94
108
  function opaque(value: unknown): value is string {
@@ -102,12 +116,15 @@ function isRecord(value: unknown): value is Record<string, unknown> {
102
116
  /** The body in the closed schema, or null (400 malformed): unknown keys, a null value, unknown carrier, unsafe URL. */
103
117
  export function parseShipmentEvidence(body: unknown): ShipmentEvidence | null {
104
118
  if (!isRecord(body)) return null;
105
- const keys = body.kind === "label-outcome" ? LABEL_KEYS : body.kind === "handoff" ? HANDOFF_KEYS : null;
119
+ const keys = typeof body.kind === "string" && Object.hasOwn(KEYS_BY_KIND, body.kind) ? KEYS_BY_KIND[body.kind] : undefined;
106
120
  if (!keys || Object.keys(body).some((key) => !keys.has(key))) return null;
107
121
  if (Object.values(body).some((value) => value === null)) return null;
108
122
  if (!opaque(body.assignmentId) || !opaque(body.purchaseId)) return null;
109
123
  if (body.expectedVersion !== undefined && (!Number.isSafeInteger(body.expectedVersion) || Number(body.expectedVersion) < 0)) return null;
110
124
  const expected = body.expectedVersion === undefined ? {} : { expectedVersion: Number(body.expectedVersion) };
125
+ if (body.kind === "label-voided") {
126
+ return { kind: "label-voided", assignmentId: body.assignmentId, purchaseId: body.purchaseId, ...expected };
127
+ }
111
128
  if (body.kind === "handoff") {
112
129
  const carrier = parseCarrierCode(body.carrier);
113
130
  if (!carrier) return null;
@@ -148,6 +165,11 @@ export function labelOutcomeRecord(evidence: LabelOutcomeEvidence): Record<strin
148
165
  };
149
166
  }
150
167
 
168
+ /** The label-voided audit `to_state`: the label state it leaves and the purchase id it voided. */
169
+ export function labelVoidedRecord(purchaseId: string): Record<string, string> {
170
+ return { label: "none", purchaseId };
171
+ }
172
+
151
173
  /** A stored label-outcome audit `to_state`, re-validated on read. Facts that fail their shape read as absent. */
152
174
  export function parseStoredLabelFacts(value: unknown): StoredLabelFacts | null {
153
175
  if (!isRecord(value)) return null;
@@ -1,17 +1,48 @@
1
1
  /**
2
- * Carrier evidence a fulfillment processor reports: a closed set of canonical carrier codes and,
3
- * per carrier, the tracking hosts a tracking URL may name. The same allowlist validates an app's
4
- * write and gates the merchant desk's tracking link. Tracking URLs are never fetched.
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.
5
11
  */
6
- export const CARRIER_CODES = ["UPS", "FEDEX", "USPS", "DHL"] as const;
7
- export type CarrierCode = (typeof CARRIER_CODES)[number];
12
+ export type CarrierAdultSignature = "required" | "supported" | "unsupported";
8
13
 
9
- export const CARRIER_TRACKING_HOSTS: Readonly<Record<CarrierCode, readonly string[]>> = {
10
- UPS: ["www.ups.com"],
11
- FEDEX: ["www.fedex.com"],
12
- USPS: ["tools.usps.com"],
13
- DHL: ["www.dhl.com"],
14
- };
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
+ );
15
46
 
16
47
  export const TRACKING_NUMBER = /^[A-Z0-9]{6,40}$/;
17
48
  export const CARRIER_SERVICE = /^[A-Z0-9_]{1,40}$/;
@@ -58,6 +89,15 @@ export function trackingUrlAllowed(carrier: unknown, url: unknown): url is strin
58
89
  return parsed.pathname.length <= TRACKING_PART_MAX && parsed.search.replace(/^\?/, "").length <= TRACKING_PART_MAX;
59
90
  }
60
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
+
61
101
  /** True when `carrier` is in either prohibited set, both compared in canonical form. */
62
102
  export function carrierProhibited(carrier: string, ...prohibited: ReadonlyArray<readonly string[]>): boolean {
63
103
  const canonical = canonicalCarrier(carrier);
@@ -127,7 +127,7 @@ export async function projectCommerceOrder(
127
127
  }
128
128
  const evidence = trusted && admission ? admission.evidence : UNKNOWN;
129
129
  const service = new FulfillmentService(fulfillmentDbFromQueryable(db), {
130
- policy: { adultSignatureRequired: false, prohibitedCarriers: [], carrierAccountId: null },
130
+ policy: { adultSignatureRequired: false, pactEnabled: false, prohibitedCarriers: [], carrierAccountId: null },
131
131
  now: () => input.now,
132
132
  notify: dispatchCommerceDeliveries,
133
133
  });