@tokenoftrust/storefront-runner 6.12.1 → 6.12.3
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.
- package/apps/storefront/migrations-apps/0030_assignment_split_shipments.sql +103 -0
- package/apps/storefront/src/lib/access/auth/loginGate.ts +2 -0
- package/apps/storefront/src/lib/customers/contactVault/dataKeys.ts +28 -1
- package/apps/storefront/src/lib/fulfillment/admin/commerceDesk.ts +13 -0
- package/apps/storefront/src/lib/fulfillment/appShipmentEvidence.ts +6 -2
- package/apps/storefront/src/lib/fulfillment/assignmentStore.ts +136 -30
- package/apps/storefront/src/lib/fulfillment/fulfillmentService.ts +323 -9
- package/apps/storefront/src/lib/fulfillment/splitShipments.ts +388 -0
- package/apps/storefront/src/lib/fulfillment/syntheticPreviewOrders.ts +5 -65
- package/apps/storefront/src/lib/integrations/webhooks/commercePayloads.ts +9 -5
- package/apps/storefront/src/lib/integrations/webhooks/deliveryStore.ts +1 -0
- package/apps/storefront/src/lib/integrations/webhooks/events.ts +1 -0
- package/apps/storefront/src/lib/orders/vault/orderContactVault.ts +74 -27
- package/package.json +1 -1
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Assignment-keyed shipments and exceptions: the closed request schemas a processor posts against
|
|
3
|
+
* one assignment, the per-line quantity ledger (assigned, shipped, cancelled), and the statements a
|
|
4
|
+
* shipment or exception writes. Every statement here is gated on the order having committed at the
|
|
5
|
+
* new event version in the same batch, so the order's compare-and-set serializes every write to
|
|
6
|
+
* the assignment and its lines.
|
|
7
|
+
*/
|
|
8
|
+
import type { CommerceStage } from "@tot/public-runtime";
|
|
9
|
+
import type { FulfillmentDatabase, SqlStatement } from "./store.js";
|
|
10
|
+
import {
|
|
11
|
+
CARRIER_CODES,
|
|
12
|
+
CARRIER_SERVICE,
|
|
13
|
+
TRACKING_NUMBER,
|
|
14
|
+
carrierProhibited,
|
|
15
|
+
parseCarrierCode,
|
|
16
|
+
trackingUrlAllowed,
|
|
17
|
+
type CarrierCode,
|
|
18
|
+
} from "./carrierEvidence.js";
|
|
19
|
+
|
|
20
|
+
export const EXCEPTION_CODES = [
|
|
21
|
+
"vendor_rejected",
|
|
22
|
+
"backordered",
|
|
23
|
+
"out_of_stock",
|
|
24
|
+
"damaged",
|
|
25
|
+
"address_undeliverable",
|
|
26
|
+
"carrier_refused",
|
|
27
|
+
"other",
|
|
28
|
+
] as const;
|
|
29
|
+
export type ExceptionCode = (typeof EXCEPTION_CODES)[number];
|
|
30
|
+
|
|
31
|
+
export interface ShipmentLine {
|
|
32
|
+
sku: string;
|
|
33
|
+
quantity: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface AssignmentShipmentEvidence {
|
|
37
|
+
kind: "shipment";
|
|
38
|
+
assignmentId: string;
|
|
39
|
+
lines: ShipmentLine[];
|
|
40
|
+
/** The carrier code as posted; plan time refuses one outside the allowed set. */
|
|
41
|
+
carrier: string;
|
|
42
|
+
service?: string;
|
|
43
|
+
trackingNumber: string;
|
|
44
|
+
trackingUrl?: string;
|
|
45
|
+
adultSignature: "accepted" | "refused" | "absent";
|
|
46
|
+
expectedVersion?: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface AssignmentExceptionEvidence {
|
|
50
|
+
kind: "exception";
|
|
51
|
+
assignmentId: string;
|
|
52
|
+
lines: ShipmentLine[];
|
|
53
|
+
code: ExceptionCode;
|
|
54
|
+
note?: string;
|
|
55
|
+
expectedVersion?: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface AssignmentShipmentView {
|
|
59
|
+
assignmentId: string;
|
|
60
|
+
shipmentId: string;
|
|
61
|
+
fulfilledLines: ShipmentLine[];
|
|
62
|
+
complete: boolean;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface AssignmentExceptionView {
|
|
66
|
+
assignmentId: string;
|
|
67
|
+
exceptionId: string;
|
|
68
|
+
code: ExceptionCode;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** One assignment line as stored. */
|
|
72
|
+
export interface AssignmentLineState {
|
|
73
|
+
lineId: string;
|
|
74
|
+
sku: string;
|
|
75
|
+
locationId: string;
|
|
76
|
+
assigned: number;
|
|
77
|
+
shipped: number;
|
|
78
|
+
cancelled: number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** An open exception as the operator desk reads it. */
|
|
82
|
+
export interface AssignmentExceptionRecord {
|
|
83
|
+
exceptionId: string;
|
|
84
|
+
assignmentId: string;
|
|
85
|
+
code: ExceptionCode;
|
|
86
|
+
lines: ShipmentLine[];
|
|
87
|
+
note: string | null;
|
|
88
|
+
createdAt: string;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const SHIPMENT_KEYS = new Set(["lines", "carrier", "service", "trackingNumber", "trackingUrl", "adultSignature"]);
|
|
92
|
+
const EXCEPTION_KEYS = new Set(["lines", "code", "note"]);
|
|
93
|
+
const LINE_KEYS = new Set(["sku", "quantity"]);
|
|
94
|
+
const CARRIER_PATTERN = /^[A-Z0-9_]{2,40}$/;
|
|
95
|
+
const SKU_MAX = 256;
|
|
96
|
+
const LINES_MAX = 500;
|
|
97
|
+
const NOTE_MAX = 500;
|
|
98
|
+
/** A note is free text, never contact data: no address sign and no run of seven or more digits. */
|
|
99
|
+
const NOTE_CONTACT = /@|\d[\d\s().-]{5,}\d/;
|
|
100
|
+
|
|
101
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
102
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The request lines: one entry per sku, each quantity a positive safe integer. Null when malformed. */
|
|
106
|
+
function parseLines(value: unknown): ShipmentLine[] | null {
|
|
107
|
+
if (!Array.isArray(value) || value.length === 0 || value.length > LINES_MAX) return null;
|
|
108
|
+
const seen = new Set<string>();
|
|
109
|
+
const lines: ShipmentLine[] = [];
|
|
110
|
+
for (const item of value) {
|
|
111
|
+
if (!isRecord(item) || Object.keys(item).some((key) => !LINE_KEYS.has(key))) return null;
|
|
112
|
+
const { sku, quantity } = item;
|
|
113
|
+
if (typeof sku !== "string" || sku.length === 0 || sku.length > SKU_MAX || sku.trim() !== sku) return null;
|
|
114
|
+
if (!Number.isSafeInteger(quantity) || Number(quantity) < 1) return null;
|
|
115
|
+
if (seen.has(sku)) return null;
|
|
116
|
+
seen.add(sku);
|
|
117
|
+
lines.push({ sku, quantity: Number(quantity) });
|
|
118
|
+
}
|
|
119
|
+
return lines;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function closedKeys(body: Record<string, unknown>, allowed: ReadonlySet<string>): boolean {
|
|
123
|
+
return Object.keys(body).every((key) => allowed.has(key)) && Object.values(body).every((value) => value !== null);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** `AssignmentShipmentWrite` in its closed schema, or null (400 malformed). */
|
|
127
|
+
export function parseAssignmentShipment(assignmentId: string, body: unknown): AssignmentShipmentEvidence | null {
|
|
128
|
+
if (!isRecord(body) || !closedKeys(body, SHIPMENT_KEYS)) return null;
|
|
129
|
+
const lines = parseLines(body.lines);
|
|
130
|
+
if (!lines) return null;
|
|
131
|
+
if (typeof body.carrier !== "string" || !CARRIER_PATTERN.test(body.carrier)) return null;
|
|
132
|
+
if (typeof body.trackingNumber !== "string" || !TRACKING_NUMBER.test(body.trackingNumber)) return null;
|
|
133
|
+
if (body.service !== undefined && (typeof body.service !== "string" || !CARRIER_SERVICE.test(body.service))) return null;
|
|
134
|
+
const known = parseCarrierCode(body.carrier);
|
|
135
|
+
if (body.trackingUrl !== undefined && (known === null || !trackingUrlAllowed(known, body.trackingUrl))) return null;
|
|
136
|
+
const adult = body.adultSignature ?? "absent";
|
|
137
|
+
if (adult !== "accepted" && adult !== "refused" && adult !== "absent") return null;
|
|
138
|
+
return {
|
|
139
|
+
kind: "shipment",
|
|
140
|
+
assignmentId,
|
|
141
|
+
lines,
|
|
142
|
+
carrier: body.carrier,
|
|
143
|
+
trackingNumber: body.trackingNumber,
|
|
144
|
+
adultSignature: adult,
|
|
145
|
+
...(typeof body.service === "string" ? { service: body.service } : {}),
|
|
146
|
+
...(typeof body.trackingUrl === "string" ? { trackingUrl: body.trackingUrl } : {}),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** `AssignmentExceptionWrite` in its closed schema, or null (400 malformed). */
|
|
151
|
+
export function parseAssignmentException(assignmentId: string, body: unknown): AssignmentExceptionEvidence | null {
|
|
152
|
+
if (!isRecord(body) || !closedKeys(body, EXCEPTION_KEYS)) return null;
|
|
153
|
+
const lines = parseLines(body.lines);
|
|
154
|
+
if (!lines) return null;
|
|
155
|
+
if (typeof body.code !== "string" || !(EXCEPTION_CODES as readonly string[]).includes(body.code)) return null;
|
|
156
|
+
if (body.note !== undefined) {
|
|
157
|
+
if (typeof body.note !== "string" || body.note.length === 0 || body.note.length > NOTE_MAX) return null;
|
|
158
|
+
if (NOTE_CONTACT.test(body.note) || /[\u0000-\u001f\u007f]/.test(body.note)) return null;
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
kind: "exception",
|
|
162
|
+
assignmentId,
|
|
163
|
+
lines,
|
|
164
|
+
code: body.code as ExceptionCode,
|
|
165
|
+
...(typeof body.note === "string" ? { note: body.note } : {}),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The carriers an order may ship with: the closed set minus the policy's and the order's prohibited carriers. */
|
|
170
|
+
export function allowedCarriers(policyProhibited: readonly string[], snapshotProhibited: readonly string[]): CarrierCode[] {
|
|
171
|
+
return CARRIER_CODES.filter((code) => !carrierProhibited(code, policyProhibited, snapshotProhibited));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Why `carrier` may not carry this order, or null. */
|
|
175
|
+
export function shipmentCarrierRefusal(
|
|
176
|
+
carrier: string,
|
|
177
|
+
policyProhibited: readonly string[],
|
|
178
|
+
snapshotProhibited: readonly string[],
|
|
179
|
+
): "carrier-prohibited" | "carrier-unsupported" | null {
|
|
180
|
+
if (carrierProhibited(carrier, policyProhibited, snapshotProhibited)) return "carrier-prohibited";
|
|
181
|
+
return parseCarrierCode(carrier) === null ? "carrier-unsupported" : null;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function remainingQuantity(line: AssignmentLineState): number {
|
|
185
|
+
return line.assigned - line.shipped - line.cancelled;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Why `requested` cannot be taken from `lines`, or null: an unknown sku, or more than a line's remainder. */
|
|
189
|
+
export function lineRefusal(
|
|
190
|
+
lines: readonly AssignmentLineState[],
|
|
191
|
+
requested: readonly ShipmentLine[],
|
|
192
|
+
): "line-unknown" | "quantity-exceeded" | null {
|
|
193
|
+
for (const want of requested) {
|
|
194
|
+
const line = lines.find((item) => item.sku === want.sku);
|
|
195
|
+
if (!line) return "line-unknown";
|
|
196
|
+
if (want.quantity > remainingQuantity(line)) return "quantity-exceeded";
|
|
197
|
+
}
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** True when shipping `requested` leaves every line with nothing remaining. */
|
|
202
|
+
export function completesLines(lines: readonly AssignmentLineState[], requested: readonly ShipmentLine[]): boolean {
|
|
203
|
+
return lines.every((line) => remainingQuantity(line) - (requested.find((item) => item.sku === line.sku)?.quantity ?? 0) === 0);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Each line's whole remainder, the shipment a whole-order handoff records. Lines with none are omitted. */
|
|
207
|
+
export function remainingLines(lines: readonly AssignmentLineState[]): ShipmentLine[] {
|
|
208
|
+
return lines.filter((line) => remainingQuantity(line) > 0).map((line) => ({ sku: line.sku, quantity: remainingQuantity(line) }));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** The assignment's stored lines in line order. */
|
|
212
|
+
export async function readAssignmentLines(db: Pick<FulfillmentDatabase, "all">, assignmentId: string): Promise<AssignmentLineState[]> {
|
|
213
|
+
const rows = await db.all<{
|
|
214
|
+
line_id: string;
|
|
215
|
+
sku: string;
|
|
216
|
+
location_id: string;
|
|
217
|
+
quantity_assigned: number;
|
|
218
|
+
quantity_shipped: number;
|
|
219
|
+
quantity_cancelled: number;
|
|
220
|
+
}>(
|
|
221
|
+
`SELECT line_id, sku, location_id, quantity_assigned, quantity_shipped, quantity_cancelled
|
|
222
|
+
FROM fulfillment_assignment_lines WHERE assignment_id = ?
|
|
223
|
+
ORDER BY CAST(line_id AS INTEGER) ASC, line_id ASC`,
|
|
224
|
+
[assignmentId],
|
|
225
|
+
);
|
|
226
|
+
return rows.map((row) => ({
|
|
227
|
+
lineId: row.line_id,
|
|
228
|
+
sku: row.sku,
|
|
229
|
+
locationId: row.location_id,
|
|
230
|
+
assigned: Number(row.quantity_assigned),
|
|
231
|
+
shipped: Number(row.quantity_shipped),
|
|
232
|
+
cancelled: Number(row.quantity_cancelled),
|
|
233
|
+
}));
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** SQL condition: the order committed at `version` in this batch. */
|
|
237
|
+
export function orderCommittedAt(scope: { tenantId: string; stage: CommerceStage; orderId: string }, version: number): SqlStatement {
|
|
238
|
+
return {
|
|
239
|
+
sql: `EXISTS (
|
|
240
|
+
SELECT 1 FROM scrappy_commerce_orders
|
|
241
|
+
WHERE tenant_id = ? AND stage = ? AND order_id = ? AND event_version = ?
|
|
242
|
+
)`,
|
|
243
|
+
params: [scope.tenantId, scope.stage, scope.orderId, version],
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Adds `requested` to each line's shipped quantity, from the quantity read at the planned version.
|
|
249
|
+
* The table's CHECK aborts the batch if shipped plus cancelled would exceed assigned.
|
|
250
|
+
*/
|
|
251
|
+
export function consumeLinesStatements(
|
|
252
|
+
assignmentId: string,
|
|
253
|
+
lines: readonly AssignmentLineState[],
|
|
254
|
+
requested: readonly ShipmentLine[],
|
|
255
|
+
gate: SqlStatement,
|
|
256
|
+
): SqlStatement[] {
|
|
257
|
+
return requested.map((want) => {
|
|
258
|
+
const line = lines.find((item) => item.sku === want.sku)!;
|
|
259
|
+
return {
|
|
260
|
+
sql: `UPDATE fulfillment_assignment_lines SET quantity_shipped = quantity_shipped + ?
|
|
261
|
+
WHERE assignment_id = ? AND line_id = ? AND quantity_shipped = ? AND quantity_cancelled = ? AND ${gate.sql}`,
|
|
262
|
+
params: [want.quantity, assignmentId, line.lineId, line.shipped, line.cancelled, ...gate.params],
|
|
263
|
+
};
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export function insertShipmentStatement(
|
|
268
|
+
input: {
|
|
269
|
+
shipmentId: string;
|
|
270
|
+
assignmentId: string;
|
|
271
|
+
tenantId: string;
|
|
272
|
+
stage: CommerceStage;
|
|
273
|
+
orderId: string;
|
|
274
|
+
installId: string;
|
|
275
|
+
carrier: string;
|
|
276
|
+
service: string | null;
|
|
277
|
+
trackingNumber: string;
|
|
278
|
+
trackingUrl: string | null;
|
|
279
|
+
adultSignature: "accepted" | "refused" | "absent";
|
|
280
|
+
lines: readonly ShipmentLine[];
|
|
281
|
+
now: string;
|
|
282
|
+
},
|
|
283
|
+
gate: SqlStatement,
|
|
284
|
+
): SqlStatement {
|
|
285
|
+
return {
|
|
286
|
+
sql: `INSERT INTO fulfillment_shipments (
|
|
287
|
+
shipment_id, assignment_id, tenant_id, stage, order_id, install_id, carrier, service,
|
|
288
|
+
tracking_number, tracking_url, adult_signature, shipped_items, created_at
|
|
289
|
+
) SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE ${gate.sql}`,
|
|
290
|
+
params: [
|
|
291
|
+
input.shipmentId,
|
|
292
|
+
input.assignmentId,
|
|
293
|
+
input.tenantId,
|
|
294
|
+
input.stage,
|
|
295
|
+
input.orderId,
|
|
296
|
+
input.installId,
|
|
297
|
+
input.carrier,
|
|
298
|
+
input.service,
|
|
299
|
+
input.trackingNumber,
|
|
300
|
+
input.trackingUrl,
|
|
301
|
+
input.adultSignature,
|
|
302
|
+
JSON.stringify(input.lines.map((line) => ({ sku: line.sku, quantity: line.quantity }))),
|
|
303
|
+
input.now,
|
|
304
|
+
...gate.params,
|
|
305
|
+
],
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Event gate: the shipment row exists — the shipment it reports committed. */
|
|
310
|
+
export function shipmentCommittedGate(shipmentId: string): SqlStatement {
|
|
311
|
+
return { sql: `EXISTS (SELECT 1 FROM fulfillment_shipments WHERE shipment_id = ?)`, params: [shipmentId] };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export function insertExceptionStatement(
|
|
315
|
+
input: {
|
|
316
|
+
exceptionId: string;
|
|
317
|
+
assignmentId: string;
|
|
318
|
+
tenantId: string;
|
|
319
|
+
stage: CommerceStage;
|
|
320
|
+
orderId: string;
|
|
321
|
+
installId: string;
|
|
322
|
+
code: ExceptionCode;
|
|
323
|
+
lines: readonly ShipmentLine[];
|
|
324
|
+
note: string | null;
|
|
325
|
+
now: string;
|
|
326
|
+
},
|
|
327
|
+
gate: SqlStatement,
|
|
328
|
+
): SqlStatement {
|
|
329
|
+
return {
|
|
330
|
+
sql: `INSERT INTO fulfillment_assignment_exceptions (
|
|
331
|
+
exception_id, assignment_id, tenant_id, stage, order_id, install_id, code, lines, note, state, created_at
|
|
332
|
+
) SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ? WHERE ${gate.sql}`,
|
|
333
|
+
params: [
|
|
334
|
+
input.exceptionId,
|
|
335
|
+
input.assignmentId,
|
|
336
|
+
input.tenantId,
|
|
337
|
+
input.stage,
|
|
338
|
+
input.orderId,
|
|
339
|
+
input.installId,
|
|
340
|
+
input.code,
|
|
341
|
+
JSON.stringify(input.lines.map((line) => ({ sku: line.sku, quantity: line.quantity }))),
|
|
342
|
+
input.note,
|
|
343
|
+
input.now,
|
|
344
|
+
...gate.params,
|
|
345
|
+
],
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** The order's open exceptions, oldest first. Rows whose stored shape fails validation are skipped. */
|
|
350
|
+
export async function readOpenExceptions(
|
|
351
|
+
db: Pick<FulfillmentDatabase, "all">,
|
|
352
|
+
scope: { tenantId: string; stage: CommerceStage; orderId: string },
|
|
353
|
+
): Promise<AssignmentExceptionRecord[]> {
|
|
354
|
+
const rows = await db.all<{
|
|
355
|
+
exception_id: string;
|
|
356
|
+
assignment_id: string;
|
|
357
|
+
code: string;
|
|
358
|
+
lines: string;
|
|
359
|
+
note: string | null;
|
|
360
|
+
created_at: string;
|
|
361
|
+
}>(
|
|
362
|
+
`SELECT exception_id, assignment_id, code, lines, note, created_at FROM fulfillment_assignment_exceptions
|
|
363
|
+
WHERE tenant_id = ? AND stage = ? AND order_id = ? AND state = 'open'
|
|
364
|
+
ORDER BY created_at ASC, exception_id ASC`,
|
|
365
|
+
[scope.tenantId, scope.stage, scope.orderId],
|
|
366
|
+
);
|
|
367
|
+
const records: AssignmentExceptionRecord[] = [];
|
|
368
|
+
for (const row of rows) {
|
|
369
|
+
if (!(EXCEPTION_CODES as readonly string[]).includes(row.code)) continue;
|
|
370
|
+
let parsed: unknown;
|
|
371
|
+
try {
|
|
372
|
+
parsed = JSON.parse(row.lines);
|
|
373
|
+
} catch {
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
const lines = parseLines(parsed);
|
|
377
|
+
if (!lines) continue;
|
|
378
|
+
records.push({
|
|
379
|
+
exceptionId: row.exception_id,
|
|
380
|
+
assignmentId: row.assignment_id,
|
|
381
|
+
code: row.code as ExceptionCode,
|
|
382
|
+
lines,
|
|
383
|
+
note: typeof row.note === "string" ? row.note : null,
|
|
384
|
+
createdAt: row.created_at,
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
return records;
|
|
388
|
+
}
|
|
@@ -29,52 +29,6 @@ const SYNTHETIC_DIGEST = "0".repeat(64);
|
|
|
29
29
|
const CONSENT_DAYS = 30;
|
|
30
30
|
|
|
31
31
|
type VaultKms = Parameters<typeof sealOrderContact>[1];
|
|
32
|
-
type GeneratedKey = Awaited<ReturnType<VaultKms["generateDataKey"]>>;
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* A KMS client that answers every repeat of a request from its first answer: a repeated data-key
|
|
36
|
-
* generation for the same context, or a decrypt of a blob it generated or already decrypted, makes no
|
|
37
|
-
* further KMS call. Key bytes are handed out as fresh copies because the vault zeroes what it imports;
|
|
38
|
-
* `clear` zeroes the copies it holds.
|
|
39
|
-
*/
|
|
40
|
-
function replayingKms(kms: VaultKms): { client: VaultKms; clear(): void } {
|
|
41
|
-
const generated = new Map<string, GeneratedKey>();
|
|
42
|
-
const decrypted = new Map<string, Uint8Array>();
|
|
43
|
-
const keep = (bytes: Uint8Array): Uint8Array => {
|
|
44
|
-
const copy = new Uint8Array(bytes);
|
|
45
|
-
bytes.fill(0);
|
|
46
|
-
return copy;
|
|
47
|
-
};
|
|
48
|
-
const client: VaultKms = {
|
|
49
|
-
async generateDataKey(ctx) {
|
|
50
|
-
const id = JSON.stringify(ctx);
|
|
51
|
-
let first = generated.get(id);
|
|
52
|
-
if (!first) {
|
|
53
|
-
const answer = await kms.generateDataKey(ctx);
|
|
54
|
-
first = { ...answer, plaintext: keep(answer.plaintext) };
|
|
55
|
-
generated.set(id, first);
|
|
56
|
-
decrypted.set(answer.ciphertextBlob, first.plaintext);
|
|
57
|
-
}
|
|
58
|
-
return { ...first, plaintext: new Uint8Array(first.plaintext) };
|
|
59
|
-
},
|
|
60
|
-
async decrypt(blob, ctx, keyArn) {
|
|
61
|
-
let first = decrypted.get(blob);
|
|
62
|
-
if (!first) {
|
|
63
|
-
first = keep(await kms.decrypt(blob, ctx, keyArn));
|
|
64
|
-
decrypted.set(blob, first);
|
|
65
|
-
}
|
|
66
|
-
return new Uint8Array(first);
|
|
67
|
-
},
|
|
68
|
-
};
|
|
69
|
-
return {
|
|
70
|
-
client,
|
|
71
|
-
clear() {
|
|
72
|
-
for (const bytes of decrypted.values()) bytes.fill(0);
|
|
73
|
-
generated.clear();
|
|
74
|
-
decrypted.clear();
|
|
75
|
-
},
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
32
|
|
|
79
33
|
export interface SyntheticOrderDeps {
|
|
80
34
|
/** Vault, consent and install reads. */
|
|
@@ -195,9 +149,8 @@ export async function bindTestProcessor(
|
|
|
195
149
|
|
|
196
150
|
/**
|
|
197
151
|
* Write one synthetic preview order, its source authority, and its sealed RFC-reserved recipient.
|
|
198
|
-
* The vault keys are
|
|
199
|
-
*
|
|
200
|
-
* the order exists.
|
|
152
|
+
* The vault keys are opened and stored before the order is written and the seal uses that key
|
|
153
|
+
* material, so a KMS failure refuses with nothing written and cannot arrive after the order exists.
|
|
201
154
|
*/
|
|
202
155
|
export async function createSyntheticOrder(
|
|
203
156
|
deps: SyntheticOrderDeps,
|
|
@@ -209,23 +162,9 @@ export async function createSyntheticOrder(
|
|
|
209
162
|
} catch {
|
|
210
163
|
return { ok: false, code: "vault-key-unavailable" };
|
|
211
164
|
}
|
|
212
|
-
const replaying = replayingKms(kms);
|
|
213
|
-
try {
|
|
214
|
-
return await createWithKeys(deps, scope, replaying.client);
|
|
215
|
-
} finally {
|
|
216
|
-
replaying.clear();
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
async function createWithKeys(
|
|
221
|
-
deps: SyntheticOrderDeps,
|
|
222
|
-
scope: SyntheticScope,
|
|
223
|
-
kms: VaultKms,
|
|
224
|
-
): Promise<SyntheticResult<{ orderId: string; stage: typeof SYNTHETIC_STAGE }>> {
|
|
225
165
|
const now = nowOf(deps);
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
}
|
|
166
|
+
const keys = await prepareOrderContactKeys(deps.db, kms, scope.tenantId, SYNTHETIC_STAGE, now);
|
|
167
|
+
if (!keys) return { ok: false, code: "vault-key-unavailable" };
|
|
229
168
|
const nowIso = now.toISOString();
|
|
230
169
|
const sourceOrderId = `${now.getTime()}${Math.floor(Math.random() * 1_000_000)}`;
|
|
231
170
|
const orderId = `synthetic-${sourceOrderId}`;
|
|
@@ -260,6 +199,7 @@ async function createWithKeys(
|
|
|
260
199
|
jti: `synthetic-seal-${orderId}`,
|
|
261
200
|
regulated: false,
|
|
262
201
|
now,
|
|
202
|
+
keys,
|
|
263
203
|
});
|
|
264
204
|
if (!sealed.ok) {
|
|
265
205
|
return { ok: false, code: sealed.reason === "vault-key-unavailable" ? "vault-key-unavailable" : "contact-refused" };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Payload admission for the commerce topics the single commerce emitter writes:
|
|
3
|
-
* `fulfillment.assignment.created`, `fulfillment.assignment.updated`, `order.fulfilled
|
|
4
|
-
* and `inventory.changed`.
|
|
3
|
+
* `fulfillment.assignment.created`, `fulfillment.assignment.updated`, `order.fulfilled`,
|
|
4
|
+
* `order.partially_fulfilled` and `inventory.changed`.
|
|
5
5
|
*
|
|
6
6
|
* Each topic has a closed key set (`asyncapi.yaml` `FulfillmentAssignmentData`, `OrderData`
|
|
7
7
|
* and `InventoryChangedData`) and every payload also passes the private-identity check. Both
|
|
@@ -13,12 +13,14 @@ export type CommerceTopic =
|
|
|
13
13
|
| "fulfillment.assignment.created"
|
|
14
14
|
| "fulfillment.assignment.updated"
|
|
15
15
|
| "order.fulfilled"
|
|
16
|
+
| "order.partially_fulfilled"
|
|
16
17
|
| "inventory.changed";
|
|
17
18
|
|
|
18
19
|
export const COMMERCE_TOPICS: readonly CommerceTopic[] = [
|
|
19
20
|
"fulfillment.assignment.created",
|
|
20
21
|
"fulfillment.assignment.updated",
|
|
21
22
|
"order.fulfilled",
|
|
23
|
+
"order.partially_fulfilled",
|
|
22
24
|
"inventory.changed",
|
|
23
25
|
];
|
|
24
26
|
|
|
@@ -82,9 +84,10 @@ function assignmentAdmissible(topic: CommerceTopic, payload: Record<string, unkn
|
|
|
82
84
|
return typeof payload.occurredAt === "string" && Number.isFinite(Date.parse(payload.occurredAt));
|
|
83
85
|
}
|
|
84
86
|
|
|
85
|
-
|
|
87
|
+
/** `OrderData` with `status` exactly `status`: `fulfilled` for order.fulfilled, `created` while lines remain unshipped. */
|
|
88
|
+
function orderDataAdmissible(payload: Record<string, unknown>, status: "fulfilled" | "created"): boolean {
|
|
86
89
|
if (Object.keys(payload).some((key) => !ORDER_DATA_KEYS.has(key))) return false;
|
|
87
|
-
if (!nonEmptyString(payload.id) || payload.status !==
|
|
90
|
+
if (!nonEmptyString(payload.id) || payload.status !== status || !nonEmptyString(payload.currency)) return false;
|
|
88
91
|
if (payload.customerHash !== undefined && typeof payload.customerHash !== "string") return false;
|
|
89
92
|
for (const key of ["subtotal", "total"] as const) {
|
|
90
93
|
if (payload[key] !== undefined && (typeof payload[key] !== "number" || !Number.isFinite(payload[key]))) return false;
|
|
@@ -117,7 +120,8 @@ export function inventoryChangedAdmissible(payload: unknown): boolean {
|
|
|
117
120
|
/** True when `payload` is exactly the closed shape `topic` allows and carries no private identity. */
|
|
118
121
|
export function commercePayloadAdmissible(topic: CommerceTopic, payload: unknown): boolean {
|
|
119
122
|
if (!isRecord(payload) || commercePayloadHasPrivateIdentity(payload)) return false;
|
|
120
|
-
if (topic === "order.fulfilled") return
|
|
123
|
+
if (topic === "order.fulfilled") return orderDataAdmissible(payload, "fulfilled");
|
|
124
|
+
if (topic === "order.partially_fulfilled") return orderDataAdmissible(payload, "created");
|
|
121
125
|
if (topic === "inventory.changed") return inventoryChangedAdmissible(payload);
|
|
122
126
|
return assignmentAdmissible(topic, payload);
|
|
123
127
|
}
|
|
@@ -27,6 +27,7 @@ export const TOPIC_REQUIRED_SCOPE: Record<WebhookTopic, string | null> = {
|
|
|
27
27
|
"inventory.changed": "inventory:read",
|
|
28
28
|
"order.created": "orders:webhook",
|
|
29
29
|
"order.fulfilled": "orders:webhook",
|
|
30
|
+
"order.partially_fulfilled": "orders:webhook",
|
|
30
31
|
"customer.marketing_consent.updated": "customers:read:minimal",
|
|
31
32
|
"attribution.finalized": "attribution:write",
|
|
32
33
|
"fulfillment.assignment.created": "fulfillment:process",
|