@tokenoftrust/storefront-runner 6.8.1 → 6.8.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,290 @@
1
+ /**
2
+ * The Private Apps inventory correction: an installed app with scope `inventory:write` reports a
3
+ * per-sku, per-location stock delta into the tenant's mirror ledger
4
+ * (`commerce_inventory_movements`, ADR 0033). It is a merchant-consented mirror correction: it
5
+ * never decrements for an order, never reserves, and is never an authoritative provider.
6
+ *
7
+ * One D1 transaction holds admission, movement, audit and receipt. The movement INSERT is the
8
+ * first statement and carries every check as a condition of the insert: the install is active on
9
+ * the host tenant, in the stage's install env, with `inventory:write` in its live scopes; the
10
+ * location is known; the balance stays in range. The audit row and the idempotency record (which
11
+ * holds the receipt) insert only when that movement inserted. Zero rows means refused: no
12
+ * movement, no audit, no receipt.
13
+ *
14
+ * Every movement field the caller could forge is derived here: `asOf` is the server receive time,
15
+ * `source` the app namespace of the install, `sourceEventId` a digest of the namespaced
16
+ * idempotency key, `actorId` the authenticated install.
17
+ */
18
+ import { isStoredSku, parseSku, skuKey } from "@tot/public-runtime/sku";
19
+ import type { CommerceStage } from "@tot/public-runtime";
20
+ import type { Queryable, QueryStatement } from "../../catalog/d1/catalog.js";
21
+ import {
22
+ guardedCorrectionStatement,
23
+ mirrorLocationKnown,
24
+ MIRROR_LOCATION_UNSPECIFIED,
25
+ type SqlCondition,
26
+ } from "../../inventory/mirrorStock.js";
27
+ import { checkIdempotency, computeBodyHash } from "./orders/idempotency.js";
28
+
29
+ export const INVENTORY_WRITE_SCOPE = "inventory:write";
30
+ export const INVENTORY_AUDIT_EVENT = "inventory.corrected";
31
+
32
+ const ID = /^[A-Za-z0-9._:-]{1,128}$/;
33
+ const IDEMPOTENCY_KEY = /^[\x21-\x7e]{8,128}$/;
34
+ const BODY_KEYS = new Set(["sku", "locationId", "quantityDelta"]);
35
+ /** Fields the platform derives; a body naming any of them is refused, never trusted or ignored. */
36
+ export const SERVER_DERIVED_FIELDS = ["asOf", "source", "sourceEventId", "actorId"] as const;
37
+
38
+ export type InventoryRefusalCode =
39
+ | "malformed"
40
+ | "server-derived-field"
41
+ | "invalid_token"
42
+ | "scope_denied"
43
+ | "denied"
44
+ | "unknown-sku"
45
+ | "unknown-location"
46
+ | "balance-out-of-range"
47
+ | "idempotency-conflict"
48
+ | "unavailable";
49
+
50
+ const STATUS: Record<InventoryRefusalCode, number> = {
51
+ malformed: 400,
52
+ "server-derived-field": 400,
53
+ invalid_token: 401,
54
+ scope_denied: 403,
55
+ denied: 403,
56
+ "unknown-sku": 422,
57
+ "unknown-location": 422,
58
+ "balance-out-of-range": 409,
59
+ "idempotency-conflict": 409,
60
+ unavailable: 503,
61
+ };
62
+
63
+ export interface InventoryReceipt {
64
+ receiptId: string;
65
+ sku: string;
66
+ locationId: string;
67
+ quantityDelta: number;
68
+ asOf: string;
69
+ balance: number;
70
+ }
71
+
72
+ export interface InventoryWriteResponse {
73
+ status: number;
74
+ body: InventoryReceipt | { code: InventoryRefusalCode; error: string };
75
+ }
76
+
77
+ export interface AppInventoryDelta {
78
+ sku: string;
79
+ locationId: string;
80
+ quantityDelta: number;
81
+ }
82
+
83
+ /** The authenticated install a write runs as. Built by the route from the verified token, never from the body. */
84
+ export interface InventoryWriteActor {
85
+ tenantId: string;
86
+ stage: CommerceStage;
87
+ installId: string;
88
+ appId: string;
89
+ }
90
+
91
+ export function inventoryRefusal(code: InventoryRefusalCode): InventoryWriteResponse {
92
+ if (code === "invalid_token") return { status: 401, body: { code, error: "Unauthorized" } };
93
+ return { status: STATUS[code], body: { code, error: code } };
94
+ }
95
+
96
+ function isRecord(value: unknown): value is Record<string, unknown> {
97
+ return typeof value === "object" && value !== null && !Array.isArray(value);
98
+ }
99
+
100
+ /** The body in the closed schema, or the refusal code. */
101
+ export function parseInventoryDelta(body: unknown): AppInventoryDelta | "malformed" | "server-derived-field" {
102
+ if (!isRecord(body)) return "malformed";
103
+ const keys = Object.keys(body);
104
+ if (keys.some((key) => (SERVER_DERIVED_FIELDS as readonly string[]).includes(key))) return "server-derived-field";
105
+ if (keys.some((key) => !BODY_KEYS.has(key))) return "malformed";
106
+ const sku = parseSku(body.sku);
107
+ if (!sku.ok) return "malformed";
108
+ const delta = body.quantityDelta;
109
+ if (typeof delta !== "number" || !Number.isSafeInteger(delta) || delta === 0) return "malformed";
110
+ const location = body.locationId ?? MIRROR_LOCATION_UNSPECIFIED;
111
+ if (typeof location !== "string" || !ID.test(location)) return "malformed";
112
+ return { sku: sku.sku, locationId: location, quantityDelta: delta };
113
+ }
114
+
115
+ /** The install env a stage admits: the same mapping widget rendering uses (`live` -> production, `test` -> test). */
116
+ export function installEnvForStage(stage: CommerceStage): "production" | "test" {
117
+ return stage === "publication" ? "production" : "test";
118
+ }
119
+
120
+ async function hex(text: string): Promise<string> {
121
+ const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
122
+ return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
123
+ }
124
+
125
+ /** The idempotency ledger key: tenant, stage, operation and caller key. The install is the ledger's other key column. */
126
+ export function namespacedKey(actor: InventoryWriteActor, key: string): string {
127
+ return ["inventory.write", actor.tenantId, actor.stage, key].join("\n");
128
+ }
129
+
130
+ /** The movement source: the app namespace of the install. */
131
+ export async function appSource(appId: string): Promise<string> {
132
+ const raw = `app:${appId}`;
133
+ return ID.test(raw) ? raw : `app:${(await hex(appId)).slice(0, 40)}`;
134
+ }
135
+
136
+ /** SQL condition (no leading AND): the install is active on the tenant, in the stage's env, with `inventory:write` live. */
137
+ export function installAdmissionCondition(actor: InventoryWriteActor): SqlCondition {
138
+ return {
139
+ sql: `EXISTS (
140
+ SELECT 1 FROM app_installs AS ai
141
+ WHERE ai.install_id = ? AND ai.tenant_id = ? AND ai.env = ? AND ai.status = 'active'
142
+ AND EXISTS (SELECT 1 FROM json_each(ai.scopes) WHERE json_each.value = '${INVENTORY_WRITE_SCOPE}')
143
+ )`,
144
+ params: [actor.installId, actor.tenantId, installEnvForStage(actor.stage)],
145
+ };
146
+ }
147
+
148
+ function lostRace(error: unknown): boolean {
149
+ for (let cause: unknown = error, depth = 0; cause instanceof Error && depth < 4; depth++, cause = cause.cause) {
150
+ if (cause.message.includes("UNIQUE constraint failed")) return true;
151
+ }
152
+ return false;
153
+ }
154
+
155
+ /** Runs the statements as one transaction and returns each one's changed-row count; a unique-key loss is all zeros. */
156
+ async function transact(db: Queryable, statements: readonly QueryStatement[]): Promise<number[]> {
157
+ if (!db.batchResults) throw new Error("transaction-results-required");
158
+ let results: readonly { results: readonly Record<string, unknown>[] }[];
159
+ try {
160
+ results = await db.batchResults(statements.flatMap((statement) => [statement, { sql: "SELECT changes() AS affected" }]));
161
+ } catch (error) {
162
+ if (lostRace(error)) return statements.map(() => 0);
163
+ throw error;
164
+ }
165
+ return statements.map((_, index) => Number(results[index * 2 + 1]?.results[0]?.affected ?? 0));
166
+ }
167
+
168
+ function receiptFrom(recorded: unknown): InventoryWriteResponse | null {
169
+ if (!isRecord(recorded) || !Number.isSafeInteger(recorded.status) || !isRecord(recorded.body)) return null;
170
+ return { status: Number(recorded.status), body: recorded.body as unknown as InventoryReceipt };
171
+ }
172
+
173
+ async function priorAnswer(db: Queryable, installId: string, key: string, bodyHash: string): Promise<InventoryWriteResponse | null> {
174
+ const check = await checkIdempotency(db, installId, key, bodyHash);
175
+ if (check.status === "proceed") return null;
176
+ if (check.status === "conflict") return inventoryRefusal("idempotency-conflict");
177
+ return receiptFrom(check.responseBody) ?? inventoryRefusal("idempotency-conflict");
178
+ }
179
+
180
+ export interface InventoryWriteRequest {
181
+ actor: InventoryWriteActor;
182
+ idempotencyKey: string;
183
+ delta: AppInventoryDelta;
184
+ /** The tenant catalog's stored form of `sku`, or null when the catalog has no such sku. */
185
+ resolveSku: (sku: string) => Promise<string | null>;
186
+ now: () => string;
187
+ }
188
+
189
+ /** Applies one app delta; every answer is a receipt or a coded refusal. */
190
+ export async function applyAppInventoryDelta(db: Queryable, request: InventoryWriteRequest): Promise<InventoryWriteResponse> {
191
+ const { actor, delta } = request;
192
+ if (!IDEMPOTENCY_KEY.test(request.idempotencyKey)) return inventoryRefusal("malformed");
193
+ if (!ID.test(actor.installId) || !actor.tenantId) return inventoryRefusal("invalid_token");
194
+ const key = namespacedKey(actor, request.idempotencyKey);
195
+ const bodyHash = await computeBodyHash({ operation: "inventory.write", ...delta });
196
+ const prior = await priorAnswer(db, actor.installId, key, bodyHash);
197
+ if (prior) return prior;
198
+
199
+ const sku = await request.resolveSku(delta.sku);
200
+ if (sku === null || !isStoredSku(sku)) return inventoryRefusal("unknown-sku");
201
+ const asOf = request.now();
202
+ const receiptId = `app.${(await hex(`${actor.installId}\n${key}`)).slice(0, 48)}`;
203
+ const actorId = `app:${actor.installId}`;
204
+ const movement = guardedCorrectionStatement(
205
+ {
206
+ tenantId: actor.tenantId,
207
+ stage: actor.stage,
208
+ source: await appSource(actor.appId),
209
+ sourceEventId: receiptId,
210
+ sku,
211
+ locationId: delta.locationId,
212
+ quantityDelta: delta.quantityDelta,
213
+ asOf,
214
+ actorId,
215
+ },
216
+ installAdmissionCondition(actor),
217
+ );
218
+ const detail = JSON.stringify({ receiptId, sku, locationId: delta.locationId, quantityDelta: delta.quantityDelta });
219
+ const changes = await transact(db, [
220
+ { sql: movement.sql, params: movement.params },
221
+ {
222
+ sql: `INSERT INTO app_audit_log (id, install_id, tenant_id, event, actor, trace_id, detail, at)
223
+ SELECT ?, ?, ?, '${INVENTORY_AUDIT_EVENT}', ?, NULL, ?, ? WHERE changes() = 1`,
224
+ params: [crypto.randomUUID(), actor.installId, actor.tenantId, actorId, detail, asOf],
225
+ },
226
+ {
227
+ sql: `INSERT INTO idempotency_keys (install_id, idempotency_key, body_hash, response_body, created_at)
228
+ SELECT ?, ?, ?, json_object('status', 201, 'body', json_object(
229
+ 'receiptId', ?, 'sku', ?, 'locationId', ?, 'quantityDelta', CAST(? AS INTEGER), 'asOf', ?,
230
+ 'balance', (SELECT SUM(quantity_delta) FROM commerce_inventory_movements
231
+ WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?))), ?
232
+ WHERE changes() = 1`,
233
+ params: [
234
+ actor.installId,
235
+ key,
236
+ bodyHash,
237
+ receiptId,
238
+ sku,
239
+ delta.locationId,
240
+ delta.quantityDelta,
241
+ asOf,
242
+ actor.tenantId,
243
+ actor.stage,
244
+ sku,
245
+ delta.locationId,
246
+ asOf,
247
+ ],
248
+ },
249
+ ]);
250
+ if ((changes[0] ?? 0) === 1 && (changes[2] ?? 0) === 1) {
251
+ return (await priorAnswer(db, actor.installId, key, bodyHash)) ?? inventoryRefusal("unavailable");
252
+ }
253
+ return classifyRefused(db, actor, delta, key, bodyHash);
254
+ }
255
+
256
+ /** Why a write did not commit, read after it: a same-key winner, the install, the location, else the bound. */
257
+ async function classifyRefused(
258
+ db: Queryable,
259
+ actor: InventoryWriteActor,
260
+ delta: AppInventoryDelta,
261
+ key: string,
262
+ bodyHash: string,
263
+ ): Promise<InventoryWriteResponse> {
264
+ const prior = await priorAnswer(db, actor.installId, key, bodyHash);
265
+ if (prior) return prior;
266
+ const install = await db.first<{ tenant_id: string; env: string; status: string; scopes: string }>(
267
+ `SELECT tenant_id, env, status, scopes FROM app_installs WHERE install_id = ?`,
268
+ actor.installId,
269
+ );
270
+ if (!install || install.tenant_id !== actor.tenantId || install.status !== "active") return inventoryRefusal("invalid_token");
271
+ if (install.env !== installEnvForStage(actor.stage)) return inventoryRefusal("denied");
272
+ let scopes: unknown = null;
273
+ try {
274
+ scopes = JSON.parse(install.scopes);
275
+ } catch {
276
+ scopes = null;
277
+ }
278
+ if (!Array.isArray(scopes) || !scopes.includes(INVENTORY_WRITE_SCOPE)) return inventoryRefusal("scope_denied");
279
+ if (!(await mirrorLocationKnown(db, { tenantId: actor.tenantId, stage: actor.stage, locationId: delta.locationId }))) {
280
+ return inventoryRefusal("unknown-location");
281
+ }
282
+ return inventoryRefusal("balance-out-of-range");
283
+ }
284
+
285
+ /** The stored catalog sku matching `sku` under the platform sku comparison, or null. */
286
+ export function matchCatalogSku(catalogSkus: Iterable<string>, sku: string): string | null {
287
+ const wanted = skuKey(sku);
288
+ for (const candidate of catalogSkus) if (skuKey(candidate) === wanted) return candidate;
289
+ return null;
290
+ }
@@ -2,7 +2,7 @@
2
2
  * Scope validation — the compliance-floor gate for Storefront Private Apps.
3
3
  * See `docs/private-apps/feature-brief.md` §"The
4
4
  * compliance floor" and the machine-readable contract:
5
- * - `docs/private-apps/contract/scopes.json` — the 10-scope V1 catalog.
5
+ * - `docs/private-apps/contract/scopes.json` — the V1 scope catalog.
6
6
  * - `docs/private-apps/contract/forbidden-scopes.json` — the 8 ids that map
7
7
  * to floor clauses (`checkout:mutate`, `tax:mutate`, …) and must NEVER be
8
8
  * grantable.
@@ -25,6 +25,7 @@ export const V1_SCOPES = [
25
25
  "orders:webhook",
26
26
  "customers:read:minimal",
27
27
  "inventory:read",
28
+ "inventory:write",
28
29
  "reports:read",
29
30
  "attribution:write",
30
31
  "widgets:launch",
@@ -178,18 +178,52 @@ export async function readMirrorBalances(
178
178
  return balances;
179
179
  }
180
180
 
181
+ /** SQL: the sum of every movement for one balance key except one event. Binds tenant, stage, sku, location, source, event. */
182
+ const OTHER_MOVEMENTS_SUM = `COALESCE((SELECT SUM(quantity_delta) FROM commerce_inventory_movements
183
+ WHERE tenant_id=? AND stage=? AND sku=? AND location_id=? AND NOT (source=? AND source_event_id=?)), 0)`;
184
+
181
185
  /**
182
186
  * One source on-hand observation. The stored delta is on-hand minus the sum of every other
183
- * movement, so a replay of this event does not add the snapshot twice.
187
+ * movement, computed inside the insert, so the balance after it is exactly on-hand: a movement
188
+ * committed before it (an app correction included) is absorbed, and one committed after it stays
189
+ * on top. Precedence is commit order; both rows remain. A replay of this event adds nothing, and
190
+ * a replay whose on-hand no longer reproduces the stored delta is a conflict.
184
191
  */
185
192
  export async function appendSourceOnHand(
186
193
  db: Queryable,
187
194
  input: Omit<MirrorMovement, "quantityDelta"> & { onHand: number },
188
195
  ): Promise<void> {
189
- if (!Number.isSafeInteger(input.onHand)) throw new InventoryMovementError("invalid-movement");
190
- const prior = await db.first<{ quantity_delta: number }>(
191
- `SELECT quantity_delta FROM commerce_inventory_movements
196
+ if (
197
+ !Number.isSafeInteger(input.onHand) ||
198
+ ![input.tenantId, input.source, input.sourceEventId, input.locationId, input.actorId].every((v) => ID.test(v)) ||
199
+ !isStoredSku(input.sku) ||
200
+ !Number.isFinite(Date.parse(input.asOf)) ||
201
+ !["preview", "publication"].includes(input.stage)
202
+ )
203
+ throw new InventoryMovementError("invalid-movement");
204
+ const others = [input.tenantId, input.stage, input.sku, input.locationId, input.source, input.sourceEventId];
205
+ await db.run(
206
+ `INSERT INTO commerce_inventory_movements
207
+ (tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id)
208
+ SELECT ?,?,?,?,?,?,CAST(? AS INTEGER) - ${OTHER_MOVEMENTS_SUM},?,? WHERE true
209
+ ON CONFLICT DO NOTHING`,
210
+ input.tenantId,
211
+ input.stage,
212
+ input.source,
213
+ input.sourceEventId,
214
+ input.sku,
215
+ input.locationId,
216
+ input.onHand,
217
+ ...others,
218
+ input.asOf,
219
+ input.actorId,
220
+ );
221
+ const actual = await db.first<{ quantity_delta: number; as_of: string; actor_id: string; expected: number }>(
222
+ `SELECT quantity_delta, as_of, actor_id, CAST(? AS INTEGER) - ${OTHER_MOVEMENTS_SUM} AS expected
223
+ FROM commerce_inventory_movements
192
224
  WHERE tenant_id=? AND stage=? AND source=? AND source_event_id=? AND sku=? AND location_id=?`,
225
+ input.onHand,
226
+ ...others,
193
227
  input.tenantId,
194
228
  input.stage,
195
229
  input.source,
@@ -197,11 +231,95 @@ export async function appendSourceOnHand(
197
231
  input.sku,
198
232
  input.locationId,
199
233
  );
200
- const reading = await readMirrorBalance(db, input);
201
- const currentSum = reading?.balance ?? 0;
202
- const existingDelta = prior ? Number(prior.quantity_delta) : 0;
203
- const { onHand, ...movement } = input;
204
- await appendMirrorMovement(db, { ...movement, quantityDelta: onHand - (currentSum - existingDelta) });
234
+ if (
235
+ !actual ||
236
+ Number(actual.quantity_delta) !== Number(actual.expected) ||
237
+ actual.as_of !== input.asOf ||
238
+ actual.actor_id !== input.actorId
239
+ )
240
+ throw new InventoryMovementError("conflict");
241
+ }
242
+
243
+ /** The largest balance a key may hold: the mirror ledger never stores or reports an unsafe integer. */
244
+ export const MIRROR_BALANCE_MAX = Number.MAX_SAFE_INTEGER;
245
+
246
+ export interface SqlCondition {
247
+ sql: string;
248
+ params: readonly unknown[];
249
+ }
250
+
251
+ /**
252
+ * A guarded correction: one INSERT that writes `movement` only when every check holds at write
253
+ * time, inside the statement. The balance after it stays within 0..MIRROR_BALANCE_MAX, except
254
+ * that a positive delta on a negative balance is admitted because it moves the balance toward
255
+ * zero; overflow is always refused, never clamped. The location is `unspecified` or one the
256
+ * tenant's movements for that stage already name. `guard` is an SQL condition (no leading AND)
257
+ * the caller's admission adds. Zero rows changed means refused.
258
+ */
259
+ export function guardedCorrectionStatement(movement: MirrorMovement, guard: SqlCondition): SqlCondition {
260
+ if (
261
+ ![movement.tenantId, movement.source, movement.sourceEventId, movement.locationId, movement.actorId].every((v) =>
262
+ ID.test(v),
263
+ ) ||
264
+ !isStoredSku(movement.sku) ||
265
+ !Number.isSafeInteger(movement.quantityDelta) ||
266
+ movement.quantityDelta === 0 ||
267
+ !Number.isFinite(Date.parse(movement.asOf)) ||
268
+ !["preview", "publication"].includes(movement.stage)
269
+ )
270
+ throw new InventoryMovementError("invalid-movement");
271
+ const delta = movement.quantityDelta;
272
+ return {
273
+ sql: `INSERT INTO commerce_inventory_movements
274
+ (tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id)
275
+ SELECT ?,?,?,?,?,?,CAST(? AS INTEGER),?,?
276
+ FROM (SELECT COALESCE(SUM(quantity_delta), 0) AS balance FROM commerce_inventory_movements
277
+ WHERE tenant_id=? AND stage=? AND sku=? AND location_id=?) AS current
278
+ WHERE current.balance + CAST(? AS INTEGER) <= ${MIRROR_BALANCE_MAX}
279
+ AND (current.balance + CAST(? AS INTEGER) >= 0 OR CAST(? AS INTEGER) > 0)
280
+ AND (? = '${MIRROR_LOCATION_UNSPECIFIED}' OR EXISTS (
281
+ SELECT 1 FROM commerce_inventory_movements WHERE tenant_id=? AND stage=? AND location_id=?
282
+ ))
283
+ AND (${guard.sql})`,
284
+ params: [
285
+ movement.tenantId,
286
+ movement.stage,
287
+ movement.source,
288
+ movement.sourceEventId,
289
+ movement.sku,
290
+ movement.locationId,
291
+ delta,
292
+ movement.asOf,
293
+ movement.actorId,
294
+ movement.tenantId,
295
+ movement.stage,
296
+ movement.sku,
297
+ movement.locationId,
298
+ delta,
299
+ delta,
300
+ delta,
301
+ movement.locationId,
302
+ movement.tenantId,
303
+ movement.stage,
304
+ movement.locationId,
305
+ ...guard.params,
306
+ ],
307
+ };
308
+ }
309
+
310
+ /** True when `locationId` is one a guarded correction may name for this tenant and stage. */
311
+ export async function mirrorLocationKnown(
312
+ db: Queryable,
313
+ input: { tenantId: string; stage: CommerceStage; locationId: string },
314
+ ): Promise<boolean> {
315
+ if (input.locationId === MIRROR_LOCATION_UNSPECIFIED) return true;
316
+ const row = await db.first<{ n: number }>(
317
+ `SELECT 1 AS n FROM commerce_inventory_movements WHERE tenant_id=? AND stage=? AND location_id=? LIMIT 1`,
318
+ input.tenantId,
319
+ input.stage,
320
+ input.locationId,
321
+ );
322
+ return row !== null;
205
323
  }
206
324
 
207
325
  export async function catalogImportEventId(runId: string, sku: string, onHand: number): Promise<string> {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.8.1",
3
+ "version": "6.8.2",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
6
6
  "packageManager": "pnpm@11.9.0",