@tokenoftrust/storefront-runner 7.6.1 → 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.
@@ -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
+ }
@@ -0,0 +1,380 @@
1
+ /** Strict signed source authority controls. Business event bytes remain independent. */
2
+ import {
3
+ canonicalJson,
4
+ sha256Hex,
5
+ type CommerceStage,
6
+ } from "@tot/public-runtime";
7
+ export const SOURCE_SCHEMA = "commerce-source-authority/v1";
8
+ export const SOURCE_LIMIT = 64;
9
+ export const SOURCE_LEASE_MS = 120_000;
10
+ export const FAULT_KINDS = [
11
+ "fork",
12
+ "committed-payload-missing",
13
+ "committed-payload-corrupt",
14
+ "source-resource-invalid",
15
+ "census-incomplete",
16
+ "census-changing",
17
+ "source-unavailable",
18
+ "authority-budget",
19
+ ] as const;
20
+ export type FaultKind = (typeof FAULT_KINDS)[number];
21
+ export interface SourceKey {
22
+ tenantId: string;
23
+ stage: CommerceStage;
24
+ source: "foxycart";
25
+ providerStoreId: string;
26
+ sourceOrderId: string;
27
+ }
28
+ export interface ManifestCore {
29
+ v: 2;
30
+ store: string;
31
+ order: string;
32
+ revision: number;
33
+ parent: string | null;
34
+ parts: number;
35
+ bytes: number;
36
+ sha256: string;
37
+ }
38
+ export interface BusinessPair {
39
+ sourceEventId: string;
40
+ originalEventDigest: string;
41
+ }
42
+ export interface FaultProof {
43
+ faultKind: FaultKind;
44
+ conditionDigest: string;
45
+ completeValidatedManifestSetOrNull: ManifestCore[] | null;
46
+ divergenceParentOrNull: string | null;
47
+ conflictingValidatedGenerationsOrNull: string[] | null;
48
+ }
49
+ export interface SourceBegin {
50
+ kind: "source-check-begin";
51
+ schema: typeof SOURCE_SCHEMA;
52
+ source: "foxycart";
53
+ providerStoreId: string;
54
+ sourceOrderId: string;
55
+ requestId: string;
56
+ }
57
+ interface ResultCommon {
58
+ kind: "source-check-result";
59
+ schema: typeof SOURCE_SCHEMA;
60
+ source: "foxycart";
61
+ providerStoreId: string;
62
+ sourceOrderId: string;
63
+ checkId: string;
64
+ observationId: string;
65
+ expectedCheckRevision: number;
66
+ expectedSourceStateVersion: number;
67
+ }
68
+ export type SourceResult = ResultCommon &
69
+ (
70
+ | ({ outcome: "fault" } & FaultProof)
71
+ | {
72
+ outcome: "healthy";
73
+ actualObservedAt: string;
74
+ tipGeneration: string;
75
+ validatedManifestCores: ManifestCore[];
76
+ recognizedResourceSetDigest: string;
77
+ businessEventDigestPairs: BusinessPair[];
78
+ businessEventSetDigest: string;
79
+ resolvesHoldIds: string[];
80
+ }
81
+ );
82
+ export interface Provenance {
83
+ acceptedLedgerGeneration: string;
84
+ businessEventSetDigest: string;
85
+ exactOriginalEventDigest: string;
86
+ }
87
+ export interface SourceOrderWrapper {
88
+ kind: "source-order-event";
89
+ schema: typeof SOURCE_SCHEMA;
90
+ event: Record<string, unknown>;
91
+ provenance: Provenance;
92
+ }
93
+ export interface SourceHold {
94
+ holdId: string;
95
+ conditionDigest: string;
96
+ faultKind: FaultKind;
97
+ openingObservationId: string;
98
+ openingProof: FaultProof;
99
+ }
100
+ export interface BeginAck {
101
+ ok: true;
102
+ duplicate: boolean;
103
+ checkId: string;
104
+ checkRevision: number;
105
+ sourceStateVersion: number;
106
+ acceptedLedgerGeneration: string | null;
107
+ acceptedBusinessEventSetDigest: string | null;
108
+ unresolvedHolds: SourceHold[];
109
+ }
110
+ export interface ResultAck {
111
+ ok: true;
112
+ duplicate: boolean;
113
+ checkId: string;
114
+ observationId: string;
115
+ sourceStateVersion: number;
116
+ acceptedLedgerGeneration: string | null;
117
+ acceptedBusinessEventSetDigest: string | null;
118
+ sourceProofExpiresAt: string | null;
119
+ pendingCheck: boolean;
120
+ unresolvedHoldIdsDigest: string;
121
+ sourceSyncPending: boolean;
122
+ }
123
+ export type AuthorityCode =
124
+ | "malformed"
125
+ | "signature"
126
+ | "tenant"
127
+ | "stage"
128
+ | "source-state-changed"
129
+ | "source-authority-unavailable"
130
+ | "source-sync-pending"
131
+ | "authority-budget"
132
+ | "control-identity-conflict"
133
+ | "use";
134
+ export class SourceAuthorityError extends Error {
135
+ constructor(readonly code: AuthorityCode) {
136
+ super(code);
137
+ }
138
+ }
139
+ export const isRecord = (v: unknown): v is Record<string, unknown> =>
140
+ v !== null && typeof v === "object" && !Array.isArray(v);
141
+ export const isHash = (v: unknown): v is string =>
142
+ typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
143
+ export const isSourceId = (v: unknown): v is string =>
144
+ typeof v === "string" && /^[1-9][0-9]{0,30}$/.test(v);
145
+ const opaque = (v: unknown): v is string =>
146
+ typeof v === "string" && /^[A-Za-z0-9:_-]{1,128}$/.test(v);
147
+ const integer = (v: unknown, min = 0, max = Number.MAX_SAFE_INTEGER) =>
148
+ Number.isSafeInteger(v) && Number(v) >= min && Number(v) <= max;
149
+ export function exactKeys(
150
+ v: unknown,
151
+ keys: readonly string[],
152
+ ): v is Record<string, unknown> {
153
+ return (
154
+ isRecord(v) &&
155
+ Object.keys(v).length === keys.length &&
156
+ keys.every((k) => Object.hasOwn(v, k))
157
+ );
158
+ }
159
+ export function canonicalInstant(v: unknown): v is string {
160
+ if (typeof v !== "string") return false;
161
+ const n = Date.parse(v);
162
+ return Number.isFinite(n) && new Date(n).toISOString() === v;
163
+ }
164
+ const BASE = ["kind", "schema", "source", "providerStoreId", "sourceOrderId"];
165
+ const COMMON = [
166
+ ...BASE,
167
+ "checkId",
168
+ "observationId",
169
+ "expectedCheckRevision",
170
+ "expectedSourceStateVersion",
171
+ "outcome",
172
+ ];
173
+ const FAULT = [
174
+ "faultKind",
175
+ "conditionDigest",
176
+ "completeValidatedManifestSetOrNull",
177
+ "divergenceParentOrNull",
178
+ "conflictingValidatedGenerationsOrNull",
179
+ ];
180
+ function core(v: unknown): v is ManifestCore {
181
+ return (
182
+ exactKeys(v, [
183
+ "v",
184
+ "store",
185
+ "order",
186
+ "revision",
187
+ "parent",
188
+ "parts",
189
+ "bytes",
190
+ "sha256",
191
+ ]) &&
192
+ v.v === 2 &&
193
+ typeof v.store === "string" &&
194
+ typeof v.order === "string" &&
195
+ integer(v.revision, 1) &&
196
+ (v.parent === null || isHash(v.parent)) &&
197
+ integer(v.parts, 1, 350) &&
198
+ integer(v.bytes, 1, 262144) &&
199
+ isHash(v.sha256)
200
+ );
201
+ }
202
+ function cores(v: unknown): v is ManifestCore[] {
203
+ return (
204
+ Array.isArray(v) &&
205
+ v.length > 0 &&
206
+ v.length <= SOURCE_LIMIT &&
207
+ v.every(core)
208
+ );
209
+ }
210
+ export function faultProof(v: SourceResult & { outcome: "fault" }): FaultProof {
211
+ return {
212
+ faultKind: v.faultKind,
213
+ conditionDigest: v.conditionDigest,
214
+ completeValidatedManifestSetOrNull: v.completeValidatedManifestSetOrNull,
215
+ divergenceParentOrNull: v.divergenceParentOrNull,
216
+ conflictingValidatedGenerationsOrNull:
217
+ v.conflictingValidatedGenerationsOrNull,
218
+ };
219
+ }
220
+ export function parseSourceWire(
221
+ v: unknown,
222
+ ): SourceBegin | SourceResult | SourceOrderWrapper | null {
223
+ if (!isRecord(v) || v.schema !== SOURCE_SCHEMA) return null;
224
+ if (v.kind === "source-order-event") {
225
+ if (
226
+ !exactKeys(v, ["kind", "schema", "event", "provenance"]) ||
227
+ !isRecord(v.event) ||
228
+ !exactKeys(v.provenance, [
229
+ "acceptedLedgerGeneration",
230
+ "businessEventSetDigest",
231
+ "exactOriginalEventDigest",
232
+ ]) ||
233
+ !Object.values(v.provenance).every(isHash)
234
+ )
235
+ return null;
236
+ return v as unknown as SourceOrderWrapper;
237
+ }
238
+ if (
239
+ v.source !== "foxycart" ||
240
+ !isSourceId(v.providerStoreId) ||
241
+ !isSourceId(v.sourceOrderId)
242
+ )
243
+ return null;
244
+ if (v.kind === "source-check-begin")
245
+ return exactKeys(v, [...BASE, "requestId"]) && opaque(v.requestId)
246
+ ? (v as unknown as SourceBegin)
247
+ : null;
248
+ if (
249
+ v.kind !== "source-check-result" ||
250
+ !opaque(v.checkId) ||
251
+ !isHash(v.observationId) ||
252
+ !integer(v.expectedCheckRevision) ||
253
+ !integer(v.expectedSourceStateVersion)
254
+ )
255
+ return null;
256
+ if (v.outcome === "fault") {
257
+ if (
258
+ !exactKeys(v, [...COMMON, ...FAULT]) ||
259
+ !FAULT_KINDS.includes(v.faultKind as FaultKind) ||
260
+ !isHash(v.conditionDigest)
261
+ )
262
+ return null;
263
+ if (
264
+ v.completeValidatedManifestSetOrNull !== null &&
265
+ !cores(v.completeValidatedManifestSetOrNull)
266
+ )
267
+ return null;
268
+ if (v.divergenceParentOrNull !== null && !isHash(v.divergenceParentOrNull))
269
+ return null;
270
+ const ids = v.conflictingValidatedGenerationsOrNull;
271
+ if (
272
+ ids !== null &&
273
+ (!Array.isArray(ids) ||
274
+ ids.length < 2 ||
275
+ ids.length > SOURCE_LIMIT ||
276
+ !ids.every(isHash) ||
277
+ new Set(ids).size !== ids.length)
278
+ )
279
+ return null;
280
+ return v as unknown as SourceResult;
281
+ }
282
+ if (
283
+ v.outcome !== "healthy" ||
284
+ !exactKeys(v, [
285
+ ...COMMON,
286
+ "actualObservedAt",
287
+ "tipGeneration",
288
+ "validatedManifestCores",
289
+ "recognizedResourceSetDigest",
290
+ "businessEventDigestPairs",
291
+ "businessEventSetDigest",
292
+ "resolvesHoldIds",
293
+ ])
294
+ )
295
+ return null;
296
+ if (
297
+ !canonicalInstant(v.actualObservedAt) ||
298
+ !isHash(v.tipGeneration) ||
299
+ !cores(v.validatedManifestCores) ||
300
+ !isHash(v.recognizedResourceSetDigest) ||
301
+ !isHash(v.businessEventSetDigest)
302
+ )
303
+ return null;
304
+ if (
305
+ !Array.isArray(v.resolvesHoldIds) ||
306
+ v.resolvesHoldIds.length > SOURCE_LIMIT ||
307
+ !v.resolvesHoldIds.every(opaque) ||
308
+ new Set(v.resolvesHoldIds).size !== v.resolvesHoldIds.length
309
+ )
310
+ return null;
311
+ const pairs = v.businessEventDigestPairs;
312
+ if (!Array.isArray(pairs) || pairs.length > SOURCE_LIMIT) return null;
313
+ for (let i = 0; i < pairs.length; i++) {
314
+ const p = pairs[i];
315
+ if (
316
+ !exactKeys(p, ["sourceEventId", "originalEventDigest"]) ||
317
+ typeof p.sourceEventId !== "string" ||
318
+ !/^[-A-Za-z0-9._:]{1,128}$/.test(p.sourceEventId) ||
319
+ !isHash(p.originalEventDigest) ||
320
+ (i > 0 && pairs[i - 1].sourceEventId >= p.sourceEventId)
321
+ )
322
+ return null;
323
+ }
324
+ return v as unknown as SourceResult;
325
+ }
326
+ export const digestJson = (v: unknown): Promise<string> =>
327
+ sha256Hex(canonicalJson(v));
328
+ export function conditionDigest(
329
+ key: SourceKey,
330
+ proof: Omit<FaultProof, "conditionDigest">,
331
+ ): Promise<string> {
332
+ return digestJson({ v: 1, key, ...proof });
333
+ }
334
+ export function observationId(
335
+ key: SourceKey,
336
+ result: Omit<SourceResult, "observationId"> | Record<string, unknown>,
337
+ ): Promise<string> {
338
+ const r = { ...result };
339
+ delete (r as Record<string, unknown>).observationId;
340
+ return digestJson({
341
+ domain: "commerce-source-observation/v1",
342
+ key,
343
+ result: r,
344
+ });
345
+ }
346
+ export async function validateManifestSet(
347
+ key: SourceKey,
348
+ items: readonly ManifestCore[],
349
+ ): Promise<Map<string, ManifestCore>> {
350
+ const map = new Map<string, ManifestCore>();
351
+ for (const item of items) {
352
+ if (
353
+ item.store !== `https://api.foxycart.com/stores/${key.providerStoreId}` ||
354
+ item.order !==
355
+ `https://api.foxycart.com/transactions/${key.sourceOrderId}`
356
+ )
357
+ throw new SourceAuthorityError("malformed");
358
+ const id = await digestJson(item);
359
+ if (map.has(id)) throw new SourceAuthorityError("malformed");
360
+ map.set(id, item);
361
+ }
362
+ return map;
363
+ }
364
+ export function uniqueLineage(
365
+ map: Map<string, ManifestCore>,
366
+ tip: string,
367
+ ): boolean {
368
+ let id: string | null = tip;
369
+ let child: ManifestCore | null = null;
370
+ const seen = new Set<string>();
371
+ while (id !== null) {
372
+ const c = map.get(id);
373
+ if (!c || seen.has(id) || (child && child.revision !== c.revision + 1))
374
+ return false;
375
+ seen.add(id);
376
+ child = c;
377
+ id = c.parent;
378
+ }
379
+ return child?.revision === 1 && seen.size === map.size;
380
+ }