@tokenoftrust/storefront-runner 6.11.11 → 6.12.0

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.
@@ -1532,6 +1532,7 @@ export class FulfillmentService {
1532
1532
  };
1533
1533
  this.appendCommerceEvent(plan, {
1534
1534
  tenantId: order.tenantId,
1535
+ stage: order.stage,
1535
1536
  topic: "fulfillment.assignment.created",
1536
1537
  payload: assignmentPayload(state, assignmentId, "active", version, this.now()),
1537
1538
  gate: assignmentAtGate(assignmentId, "active", version),
@@ -1558,12 +1559,13 @@ export class FulfillmentService {
1558
1559
  params: [order.tenantId, order.stage, order.orderId, version],
1559
1560
  }),
1560
1561
  );
1561
- const targets = commerceTargetsQuery(order.tenantId, "order.fulfilled");
1562
+ const targets = commerceTargetsQuery(order.tenantId, "order.fulfilled", order.stage);
1562
1563
  const installs = await this.db.all<{ install_id: string }>(targets.sql, targets.params);
1563
1564
  const payload: Record<string, unknown> = { id: order.sourceOrderId, status: "fulfilled", currency: order.currency };
1564
1565
  if (state.lines.length > 0) payload.lineItems = state.lines.map((line) => ({ sku: line.sku, quantity: line.quantity }));
1565
1566
  this.appendCommerceEvent(plan, {
1566
1567
  tenantId: order.tenantId,
1568
+ stage: order.stage,
1567
1569
  topic: "order.fulfilled",
1568
1570
  payload,
1569
1571
  gate: claimedByEventGate(key, eventId),
@@ -1633,6 +1635,7 @@ export class FulfillmentService {
1633
1635
  plan: PlanStatements,
1634
1636
  input: {
1635
1637
  tenantId: string;
1638
+ stage: CommerceStage;
1636
1639
  topic: CommerceTopic;
1637
1640
  payload: Record<string, unknown>;
1638
1641
  gate: SqlStatement;
@@ -1644,6 +1647,7 @@ export class FulfillmentService {
1644
1647
  const built = commerceEventStatements({
1645
1648
  eventId: input.eventId ?? crypto.randomUUID(),
1646
1649
  tenantId: input.tenantId,
1650
+ stage: input.stage,
1647
1651
  topic: input.topic,
1648
1652
  payload: input.payload,
1649
1653
  gate: { sql: input.gate.sql, params: [...input.gate.params] },
@@ -1682,6 +1686,7 @@ export class FulfillmentService {
1682
1686
  );
1683
1687
  this.appendCommerceEvent(plan, {
1684
1688
  tenantId: state.order.tenantId,
1689
+ stage: state.order.stage,
1685
1690
  topic: "fulfillment.assignment.updated",
1686
1691
  payload: assignmentPayload(state, assignment.assignmentId, to, version, this.now()),
1687
1692
  gate: assignmentAtGate(assignment.assignmentId, to, version),
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Synthetic preview orders for exercising a `test` Private App install end to end.
3
+ *
4
+ * Everything here writes only the `preview` stage partition and only orders whose source is
5
+ * {@link SYNTHETIC_SOURCE}; a live (`publication`) record is never read or written, and a preview
6
+ * order from any other source is never released. Contact data is RFC-reserved: example.com /
7
+ * example.net mail domains (RFC 2606), a NANP fictional 555-01xx number, and a placeholder street.
8
+ *
9
+ * - `bindTestProcessor` binds the caller's own `test` install as the preview fulfillment processor
10
+ * (the processor-binding seam, stage `preview`) and grants it preview recipient consent.
11
+ * - `createSyntheticOrder` writes one captured, stock-confirmed, ready order to the preview ledger,
12
+ * its synthetic source authority, and its sealed synthetic recipient.
13
+ * - `releaseSyntheticOrder` claims and releases one synthetic order; with a notifiable processor
14
+ * bound, the release assigns it and queues the processor's assignment webhook.
15
+ */
16
+ import type { Queryable } from "../catalog/d1/catalog.js";
17
+ import { orderContactKeysAvailable, sealOrderContact } from "../orders/vault/orderContactVault.js";
18
+ import { readOrderContactCommand, type OrderContactCommand } from "../orders/vault/orderContact.js";
19
+ import { grantConsent, grantedByHash } from "../integrations/apps/appContactConsents.js";
20
+ import { readProcessor, setProcessor } from "./assignmentStore.js";
21
+ import { FulfillmentService, type FulfillmentActor, type SourceOrderSnapshot } from "./fulfillmentService.js";
22
+ import { carrierPolicyForTenant, type CarrierPolicy } from "./readiness.js";
23
+ import type { FulfillmentDatabase } from "./store.js";
24
+
25
+ export const SYNTHETIC_SOURCE = "tot-synthetic";
26
+ export const SYNTHETIC_STAGE = "preview" as const;
27
+ const SYNTHETIC_PROVIDER_STORE = "1";
28
+ const SYNTHETIC_DIGEST = "0".repeat(64);
29
+ const CONSENT_DAYS = 30;
30
+
31
+ type VaultKms = Parameters<typeof sealOrderContact>[1];
32
+
33
+ export interface SyntheticOrderDeps {
34
+ /** Vault, consent and install reads. */
35
+ db: Queryable;
36
+ /** The same database as the fulfillment core's transactional port. */
37
+ fulfillment: FulfillmentDatabase;
38
+ /** Loaded only when a recipient is sealed. */
39
+ kms: () => Promise<VaultKms>;
40
+ policy: CarrierPolicy;
41
+ now?: () => Date;
42
+ }
43
+
44
+ /** The carrier policy for the routed tenant locals, as the fulfillment routes derive it. */
45
+ export function syntheticOrderPolicy(tenant: unknown, host: string): CarrierPolicy {
46
+ const t = (tenant ?? {}) as { tenant_id?: string; compliance?: { ruleProfile?: string }; carrierAccountId?: unknown };
47
+ return carrierPolicyForTenant({ tenant_id: t.tenant_id || host, compliance: t.compliance, carrierAccountId: t.carrierAccountId });
48
+ }
49
+
50
+ export interface SyntheticScope {
51
+ tenantId: string;
52
+ actorId: string;
53
+ }
54
+
55
+ export type SyntheticRefusal =
56
+ | "install-not-found"
57
+ | "install-not-test"
58
+ | "conflict"
59
+ | "order-not-found"
60
+ | "vault-key-unavailable"
61
+ | "contact-refused"
62
+ | (string & {});
63
+
64
+ export type SyntheticResult<T> = { ok: true; value: T } | { ok: false; code: SyntheticRefusal; holds?: readonly string[] };
65
+
66
+ /** The RFC-reserved recipient sealed for every synthetic order. Index picks the 555-01xx line. */
67
+ export function syntheticRecipient(orderId: string, index = 0): OrderContactCommand {
68
+ const line = String(100 + (Math.abs(index) % 100)).padStart(4, "0");
69
+ const command = readOrderContactCommand({
70
+ kind: "order-contact",
71
+ v: 1,
72
+ orderId,
73
+ customer: { name: "Example Recipient", email: "recipient@example.com", phone: `+1 202 555 ${line}` },
74
+ shipTo: { name: "Example Recipient", line1: "100 Example Street", city: "Anytown", postalCode: "00000", country: "US" },
75
+ billTo: { name: "Example Billing", line1: "100 Example Street", city: "Anytown", postalCode: "00000", country: "US" },
76
+ });
77
+ if (!command) throw new Error("synthetic recipient did not parse");
78
+ return command;
79
+ }
80
+
81
+ function nowOf(deps: SyntheticOrderDeps): Date {
82
+ return deps.now ? deps.now() : new Date();
83
+ }
84
+
85
+ function service(deps: SyntheticOrderDeps): FulfillmentService {
86
+ return new FulfillmentService(deps.fulfillment, {
87
+ policy: deps.policy,
88
+ now: () => nowOf(deps).toISOString(),
89
+ });
90
+ }
91
+
92
+ function actor(scope: SyntheticScope): FulfillmentActor {
93
+ return { role: "owner", tenantId: scope.tenantId, stage: SYNTHETIC_STAGE, actorId: scope.actorId };
94
+ }
95
+
96
+ /**
97
+ * Bind `installId` as the tenant's preview processor and grant it preview recipient consent. The
98
+ * install must belong to the tenant, be unmanaged, and have env `test`.
99
+ */
100
+ export async function bindTestProcessor(
101
+ deps: SyntheticOrderDeps,
102
+ scope: SyntheticScope & { installId: string },
103
+ ): Promise<SyntheticResult<{ installId: string; notifiable: boolean; consentGranted: boolean }>> {
104
+ const install = await deps.db.first<{ env: string }>(
105
+ `SELECT env FROM app_installs WHERE install_id = ? AND tenant_id = ? AND managed_kind IS NULL`,
106
+ scope.installId,
107
+ scope.tenantId,
108
+ );
109
+ if (!install) return { ok: false, code: "install-not-found" };
110
+ if (install.env !== "test") return { ok: false, code: "install-not-test" };
111
+
112
+ const now = nowOf(deps);
113
+ const db = deps.fulfillment;
114
+ const bound = await setProcessor(db, {
115
+ tenantId: scope.tenantId,
116
+ stage: SYNTHETIC_STAGE,
117
+ installId: scope.installId,
118
+ actorId: scope.actorId,
119
+ now: now.toISOString(),
120
+ });
121
+ if (!bound.ok) return { ok: false, code: bound.code };
122
+
123
+ const live = await deps.db.first(
124
+ `SELECT 1 AS live FROM app_contact_consents
125
+ WHERE install_id = ? AND tenant_id = ? AND stage = ? AND revoked_at IS NULL AND expires_at > ?`,
126
+ scope.installId,
127
+ scope.tenantId,
128
+ SYNTHETIC_STAGE,
129
+ now.toISOString(),
130
+ );
131
+ let consentGranted = live !== null;
132
+ if (!consentGranted) {
133
+ const granted = await grantConsent(deps.db, {
134
+ tenantId: scope.tenantId,
135
+ stage: SYNTHETIC_STAGE,
136
+ installId: scope.installId,
137
+ expiresAt: new Date(now.getTime() + CONSENT_DAYS * 86_400_000).toISOString(),
138
+ grantedBy: await grantedByHash(scope.actorId),
139
+ now,
140
+ });
141
+ consentGranted = granted.ok;
142
+ }
143
+ const processor = await readProcessor(db, scope.tenantId, SYNTHETIC_STAGE);
144
+ return {
145
+ ok: true,
146
+ value: { installId: scope.installId, notifiable: processor?.notifiable === true, consentGranted },
147
+ };
148
+ }
149
+
150
+ /** Write one synthetic preview order, its source authority, and its sealed RFC-reserved recipient. */
151
+ export async function createSyntheticOrder(
152
+ deps: SyntheticOrderDeps,
153
+ scope: SyntheticScope,
154
+ ): Promise<SyntheticResult<{ orderId: string; stage: typeof SYNTHETIC_STAGE }>> {
155
+ let kms: VaultKms;
156
+ try {
157
+ kms = await deps.kms();
158
+ } catch {
159
+ return { ok: false, code: "vault-key-unavailable" };
160
+ }
161
+ const now = nowOf(deps);
162
+ // Prove the vault can seal before writing anything: an unconfigured or unreachable KMS refuses here.
163
+ if (!(await orderContactKeysAvailable(deps.db, kms, scope.tenantId, SYNTHETIC_STAGE, now))) {
164
+ return { ok: false, code: "vault-key-unavailable" };
165
+ }
166
+ const nowIso = now.toISOString();
167
+ const sourceOrderId = `${now.getTime()}${Math.floor(Math.random() * 1_000_000)}`;
168
+ const orderId = `synthetic-${sourceOrderId}`;
169
+ const snapshot: SourceOrderSnapshot = {
170
+ tenantId: scope.tenantId,
171
+ stage: SYNTHETIC_STAGE,
172
+ orderId,
173
+ source: SYNTHETIC_SOURCE,
174
+ sourceOrderId,
175
+ currency: "USD",
176
+ placedAt: nowIso,
177
+ payment: "captured",
178
+ compliance: "fresh",
179
+ stock: "confirmed",
180
+ fulfillment: "ready",
181
+ label: "none",
182
+ amountMinor: 1000,
183
+ totals: { subtotalMinor: 1000, shippingMinor: 0, taxMinor: 0, totalMinor: 1000 },
184
+ evidence: { verification: "fresh", tax: "fresh", risk: "fresh", stock: "fresh" },
185
+ lines: [{ sku: "synthetic-sku", quantity: 1 }],
186
+ };
187
+ const applied = await service(deps).applySourceSnapshot(actor(scope), snapshot);
188
+ if (!applied.ok) return { ok: false, code: applied.code, ...(applied.holds ? { holds: applied.holds } : {}) };
189
+
190
+ await insertSyntheticAuthority(deps.db, scope.tenantId, orderId, sourceOrderId);
191
+
192
+ const sealed = await sealOrderContact(deps.db, kms, {
193
+ tenantId: scope.tenantId,
194
+ stage: SYNTHETIC_STAGE,
195
+ command: syntheticRecipient(orderId, Number(sourceOrderId.slice(-2))),
196
+ issuer: SYNTHETIC_SOURCE,
197
+ jti: `synthetic-seal-${orderId}`,
198
+ regulated: false,
199
+ now,
200
+ });
201
+ if (!sealed.ok) {
202
+ return { ok: false, code: sealed.reason === "vault-key-unavailable" ? "vault-key-unavailable" : "contact-refused" };
203
+ }
204
+ return { ok: true, value: { orderId, stage: SYNTHETIC_STAGE } };
205
+ }
206
+
207
+ /** Claim and release one synthetic preview order. Orders from any other source are not found. */
208
+ export async function releaseSyntheticOrder(
209
+ deps: SyntheticOrderDeps,
210
+ scope: SyntheticScope & { orderId: string },
211
+ ): Promise<SyntheticResult<{ orderId: string; fulfillment: string; assignedInstallId: string | null }>> {
212
+ const order = await deps.db.first<{ order_id: string }>(
213
+ `SELECT order_id FROM scrappy_commerce_orders WHERE tenant_id = ? AND stage = ? AND order_id = ? AND source = ?`,
214
+ scope.tenantId,
215
+ SYNTHETIC_STAGE,
216
+ scope.orderId,
217
+ SYNTHETIC_SOURCE,
218
+ );
219
+ if (!order) return { ok: false, code: "order-not-found" };
220
+
221
+ const core = service(deps);
222
+ const claimed = await core.claim(actor(scope), [scope.orderId]);
223
+ if (!claimed.ok) return { ok: false, code: claimed.code, ...(claimed.holds ? { holds: claimed.holds } : {}) };
224
+ const released = await core.release(actor(scope), scope.orderId);
225
+ if (!released.ok) return { ok: false, code: released.code, ...(released.holds ? { holds: released.holds } : {}) };
226
+
227
+ const assignment = await deps.db.first<{ install_id: string }>(
228
+ `SELECT install_id FROM fulfillment_assignments
229
+ WHERE tenant_id = ? AND stage = ? AND order_id = ? AND state = 'active'`,
230
+ scope.tenantId,
231
+ SYNTHETIC_STAGE,
232
+ scope.orderId,
233
+ );
234
+ return {
235
+ ok: true,
236
+ value: {
237
+ orderId: scope.orderId,
238
+ fulfillment: released.value.fulfillment,
239
+ assignedInstallId: assignment?.install_id ?? null,
240
+ },
241
+ };
242
+ }
243
+
244
+ /**
245
+ * A healthy source-authority row for a synthetic preview order: the synthetic source is its own
246
+ * authority, so there is no upstream check to wait on. Scoped by the table's
247
+ * (tenant, stage, source, order) keys to `preview` and {@link SYNTHETIC_SOURCE} only.
248
+ */
249
+ async function insertSyntheticAuthority(db: Queryable, tenantId: string, orderId: string, sourceOrderId: string) {
250
+ const expires = "9999-12-31T23:59:59.999Z";
251
+ const state = {
252
+ version: 1,
253
+ revision: 1,
254
+ active: null,
255
+ pending: false,
256
+ accepted: SYNTHETIC_DIGEST,
257
+ businessDigest: SYNTHETIC_DIGEST,
258
+ pairs: [],
259
+ expires,
260
+ sync: false,
261
+ holds: [],
262
+ budget: false,
263
+ orderId,
264
+ };
265
+ await db.run(
266
+ `INSERT INTO commerce_source_authority
267
+ (tenant_id, stage, source, provider_store_id, source_order_id, order_id, source_state_version, check_revision,
268
+ active_check_id, pending_check, accepted_ledger_generation, accepted_business_event_set_digest,
269
+ source_proof_expires_at, source_sync_pending, unresolved_count, authority_budget, binding_digest, state_json,
270
+ mutation_id)
271
+ VALUES (?, ?, ?, ?, ?, ?, 1, 1, NULL, 0, ?, ?, ?, 0, 0, 0, ?, ?, ?)`,
272
+ tenantId,
273
+ SYNTHETIC_STAGE,
274
+ SYNTHETIC_SOURCE,
275
+ SYNTHETIC_PROVIDER_STORE,
276
+ sourceOrderId,
277
+ orderId,
278
+ SYNTHETIC_DIGEST,
279
+ SYNTHETIC_DIGEST,
280
+ expires,
281
+ SYNTHETIC_DIGEST,
282
+ JSON.stringify(state),
283
+ `synthetic-${orderId}`,
284
+ );
285
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The canonical host-stage → install-env wall for the Private Apps gateway.
3
+ *
4
+ * A storefront host serves exactly one commerce stage, read from the routed
5
+ * customization env (`context.locals.customizationEnv`): `test` routes the
6
+ * `preview` stage and `live` routes `publication`. Each stage admits exactly one
7
+ * install env: `preview` → `test`, `publication` → `production`. Token minting,
8
+ * scoped-API authorization, order reads and webhook targeting all derive the
9
+ * expected install env here, so a test install can never read live orders or
10
+ * receive live webhooks, and a production install never acts on preview data.
11
+ */
12
+ import type { CommerceStage } from "@tot/public-runtime";
13
+
14
+ export { appInstallEnvForStage, type AppInstallEnv } from "@tot/public-runtime";
15
+
16
+ /** The commerce stage a routed customization env serves, or `null` when the host routes no stage. */
17
+ export function commerceStageForCustomizationEnv(env: string | undefined): CommerceStage | null {
18
+ if (env === "live") return "publication";
19
+ if (env === "test") return "preview";
20
+ return null;
21
+ }
22
+
23
+ /** The commerce stage an install env belongs to, or `null` for an env outside the wall. */
24
+ export function commerceStageForInstallEnv(env: string): CommerceStage | null {
25
+ if (env === "production") return "publication";
26
+ if (env === "test") return "preview";
27
+ return null;
28
+ }
@@ -26,6 +26,7 @@ import {
26
26
  } from "../../inventory/mirrorStock.js";
27
27
  import { checkIdempotency, computeBodyHash } from "./orders/idempotency.js";
28
28
  import { emitInventoryChanged } from "../webhooks/emit.js";
29
+ import { appInstallEnvForStage } from "./appInstallEnv.js";
29
30
 
30
31
  export const INVENTORY_WRITE_SCOPE = "inventory:write";
31
32
  export const INVENTORY_AUDIT_EVENT = "inventory.corrected";
@@ -113,11 +114,6 @@ export function parseInventoryDelta(body: unknown): AppInventoryDelta | "malform
113
114
  return { sku: sku.sku, locationId: location, quantityDelta: delta };
114
115
  }
115
116
 
116
- /** The install env a stage admits: the same mapping widget rendering uses (`live` -> production, `test` -> test). */
117
- export function installEnvForStage(stage: CommerceStage): "production" | "test" {
118
- return stage === "publication" ? "production" : "test";
119
- }
120
-
121
117
  async function hex(text: string): Promise<string> {
122
118
  const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
123
119
  return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
@@ -142,7 +138,7 @@ export function installAdmissionCondition(actor: InventoryWriteActor): SqlCondit
142
138
  WHERE ai.install_id = ? AND ai.tenant_id = ? AND ai.env = ? AND ai.status = 'active'
143
139
  AND EXISTS (SELECT 1 FROM json_each(ai.scopes) WHERE json_each.value = '${INVENTORY_WRITE_SCOPE}')
144
140
  )`,
145
- params: [actor.installId, actor.tenantId, installEnvForStage(actor.stage)],
141
+ params: [actor.installId, actor.tenantId, appInstallEnvForStage(actor.stage)],
146
142
  };
147
143
  }
148
144
 
@@ -299,7 +295,7 @@ async function classifyRefused(
299
295
  actor.installId,
300
296
  );
301
297
  if (!install || install.tenant_id !== actor.tenantId || install.status !== "active") return inventoryRefusal("invalid_token");
302
- if (install.env !== installEnvForStage(actor.stage)) return inventoryRefusal("denied");
298
+ if (install.env !== appInstallEnvForStage(actor.stage)) return inventoryRefusal("denied");
303
299
  let scopes: unknown = null;
304
300
  try {
305
301
  scopes = JSON.parse(install.scopes);
@@ -42,6 +42,8 @@
42
42
  import type { Queryable } from "../../catalog/d1/catalog.js";
43
43
  import { TOPIC_REQUIRED_SCOPE } from "./events.js";
44
44
  import { COMMERCE_TOPICS, commercePayloadAdmissible, type CommerceTopic } from "./commercePayloads.js";
45
+ import { appInstallEnvForStage } from "../apps/appInstallEnv.js";
46
+ import type { CommerceStage } from "@tot/public-runtime";
45
47
 
46
48
  /** Mirrors the `Delivery.topic` / CloudEvents channel enum in the D1/D2 contract. */
47
49
  export type WebhookTopic =
@@ -689,30 +691,36 @@ export interface CommerceEventStatement {
689
691
  params: unknown[];
690
692
  }
691
693
 
692
- /** SQL condition an eligible install row `i` satisfies; binds the tenant id, then the topic's required scope. */
693
- const ELIGIBLE_INSTALL_CONDITION = `i.tenant_id = ? AND i.status = 'active' AND i.managed_kind IS NULL
694
+ /**
695
+ * SQL condition an eligible install row `i` satisfies; binds the tenant id, the install env the
696
+ * event's stage admits (`appInstallEnvForStage`), then the topic's required scope. A `test` install
697
+ * never receives a `publication` event and a `production` install never a `preview` one.
698
+ */
699
+ const ELIGIBLE_INSTALL_CONDITION = `i.tenant_id = ? AND i.env = ? AND i.status = 'active' AND i.managed_kind IS NULL
694
700
  AND COALESCE(i.webhook_endpoint, '') != ''
695
701
  AND EXISTS (SELECT 1 FROM json_each(i.scopes) WHERE json_each.value = ?)`;
696
702
 
697
- /** Installs on `tenantId` that would receive `topic` now, oldest first. Statements re-check this at write. */
698
- export function commerceTargetsQuery(tenantId: string, topic: CommerceTopic): CommerceEventStatement {
703
+ /** Installs on `tenantId` in `stage`'s install env that would receive `topic` now, oldest first. Statements re-check this at write. */
704
+ export function commerceTargetsQuery(tenantId: string, topic: CommerceTopic, stage: CommerceStage): CommerceEventStatement {
699
705
  return {
700
706
  sql: `SELECT i.install_id AS install_id FROM app_installs AS i
701
707
  WHERE ${ELIGIBLE_INSTALL_CONDITION}
702
708
  ORDER BY i.created_at ASC, i.install_id ASC`,
703
- params: [tenantId, TOPIC_REQUIRED_SCOPE[topic]],
709
+ params: [tenantId, appInstallEnvForStage(stage), TOPIC_REQUIRED_SCOPE[topic]],
704
710
  };
705
711
  }
706
712
 
707
713
  /**
708
714
  * The single commerce emitter: one `webhook_events` row written only when `gate` holds, and one
709
715
  * pending `webhook_deliveries` row per target written only when that event row exists and the
710
- * target install is still eligible. Ids are minted by the caller so the statements run inside the
711
- * batch of the change they report; the delivery id is the CloudEvents `id`.
716
+ * target install is still eligible — including belonging to the install env `stage` admits. Ids are
717
+ * minted by the caller so the statements run inside the batch of the change they report; the
718
+ * delivery id is the CloudEvents `id`.
712
719
  */
713
720
  export function commerceEventStatements(input: {
714
721
  eventId: string;
715
722
  tenantId: string;
723
+ stage: CommerceStage;
716
724
  topic: CommerceTopic;
717
725
  payload: unknown;
718
726
  gate: CommerceEventStatement;
@@ -752,6 +760,7 @@ export function commerceEventStatements(input: {
752
760
  input.now,
753
761
  target.installId,
754
762
  input.tenantId,
763
+ appInstallEnvForStage(input.stage),
755
764
  TOPIC_REQUIRED_SCOPE[input.topic],
756
765
  input.eventId,
757
766
  input.tenantId,
@@ -24,6 +24,13 @@
24
24
  * install — correct for data topics (`order.created`, etc.), where
25
25
  * multiple installed apps legitimately subscribe to the same data.
26
26
  *
27
+ * Stage wall: every data topic names the commerce stage it happened in
28
+ * (`opts.stage`, required — a data topic without a valid stage is refused,
29
+ * logged, `null`). Only installs whose `env` is the one that stage admits
30
+ * (`appInstallEnvForStage`) are targeted, so a `test` install never receives
31
+ * a `publication` event and a `production` install never a `preview` one.
32
+ * Lifecycle topics are about one subject install and stay env-agnostic.
33
+ *
27
34
  * Mirrors `adminService.ts`'s `getRegistryService()` composition-root shape —
28
35
  * reuses it outright for the registry, and builds its own
29
36
  * `WebhookDeliveryStore` over the same `STOREFRONT_APPS_DB` binding (the D1
@@ -64,22 +71,38 @@ import { fromD1, type Queryable } from "../../catalog/d1/catalog.js";
64
71
  import { setInventoryChangedNotify } from "../../inventory/mirrorStock.js";
65
72
  import { getWorkerEnv, readD1, readEnv } from "../../publication/shared/env.js";
66
73
  import type { CommerceStage } from "@tot/public-runtime";
74
+ import { appInstallEnvForStage } from "../apps/appInstallEnv.js";
67
75
 
68
76
  /** Contract-scoped payload schema version — `asyncapi.yaml`'s `dataschemaversion` is `const: "1"` for V1. */
69
77
  const DATASCHEMA_VERSION = "1";
70
78
  const WEBHOOK_SIGNING_PRIVATE_KEY_ENV = "WEBHOOK_SIGNING_PRIVATE_KEY_B64";
71
79
 
72
- export interface EmitWebhookEventOptions {
73
- /**
74
- * Restrict delivery to exactly this one install — the event's subject.
75
- * REQUIRED for `app.installed`/`app.uninstalled` (see
76
- * {@link LIFECYCLE_TOPICS}); omit for a tenant-wide data-topic fan-out.
77
- */
78
- installId?: string;
80
+ /** Topics about one subject install, env-agnostic. */
81
+ export type LifecycleWebhookTopic = "app.installed" | "app.uninstalled";
82
+ /** Topics carrying data from one commerce stage. */
83
+ export type DataWebhookTopic = Exclude<WebhookTopic, LifecycleWebhookTopic>;
84
+
85
+ interface EmitOptionsBase {
79
86
  /** Override for a future contract version bump. Defaults to {@link DATASCHEMA_VERSION}. */
80
87
  dataschemaVersion?: string;
81
88
  }
82
89
 
90
+ export interface LifecycleEmitOptions extends EmitOptionsBase {
91
+ /** The event's subject install — delivery is restricted to exactly this one install. */
92
+ installId: string;
93
+ }
94
+
95
+ export interface DataEmitOptions extends EmitOptionsBase {
96
+ /** The commerce stage the data belongs to; only installs in the env it admits are targeted. */
97
+ stage: CommerceStage;
98
+ /** Restrict delivery to this one install; omit for a tenant-wide fan-out. */
99
+ installId?: string;
100
+ }
101
+
102
+ export type EmitWebhookEventOptions<T extends WebhookTopic = WebhookTopic> = T extends LifecycleWebhookTopic
103
+ ? LifecycleEmitOptions
104
+ : DataEmitOptions;
105
+
83
106
  /** `null` when no install on the tenant was eligible — not an error; no event/delivery rows are written in that case. */
84
107
  export type EmitWebhookEventResult = { eventId: string; deliveryCount: number } | null;
85
108
 
@@ -123,16 +146,24 @@ function logDiag(fields: Record<string, unknown>): void {
123
146
  * `opts.installId` (a caller bug — logged, never silently broadened to a
124
147
  * tenant-wide broadcast).
125
148
  */
126
- export async function emitWebhookEvent(
127
- topic: WebhookTopic,
149
+ export async function emitWebhookEvent<T extends WebhookTopic>(
150
+ topic: T,
128
151
  tenantId: string,
129
152
  data: unknown,
130
- opts: EmitWebhookEventOptions = {},
153
+ opts: EmitWebhookEventOptions<T>,
131
154
  ): Promise<EmitWebhookEventResult> {
132
- if (LIFECYCLE_TOPICS.has(topic) && !opts.installId) {
155
+ const options: { installId?: string; stage?: unknown; dataschemaVersion?: string } = opts;
156
+ const lifecycle = LIFECYCLE_TOPICS.has(topic);
157
+ if (lifecycle && !options.installId) {
133
158
  logDiag({ topic, tenantId, reason: "lifecycle_topic_requires_installId" });
134
159
  return null;
135
160
  }
161
+ const stage = options.stage;
162
+ if (!lifecycle && stage !== "preview" && stage !== "publication") {
163
+ logDiag({ topic, tenantId, reason: "data_topic_requires_stage" });
164
+ return null;
165
+ }
166
+ const expectedEnv = lifecycle ? null : appInstallEnvForStage(stage as CommerceStage);
136
167
  if (isCommerceTopic(topic) && !commercePayloadAdmissible(topic, data)) {
137
168
  throw new CommercePayloadRefused(topic);
138
169
  }
@@ -157,12 +188,14 @@ export async function emitWebhookEvent(
157
188
  // `candidates`, so a cross-tenant `installId` yields zero eligible targets
158
189
  // rather than leaking across tenants.
159
190
  const candidates = await registry.listByTenant(tenantId);
160
- const scoped = opts.installId ? candidates.filter((install) => install.installId === opts.installId) : candidates;
161
- const eligible = scoped.filter((install) => isEligibleTarget(install, topic));
191
+ const scoped = options.installId ? candidates.filter((install) => install.installId === options.installId) : candidates;
192
+ const eligible = scoped.filter(
193
+ (install) => isEligibleTarget(install, topic) && (expectedEnv === null || install.env === expectedEnv),
194
+ );
162
195
  if (eligible.length === 0) return null;
163
196
 
164
197
  const { event, deliveries } = await store.createEvent(
165
- { tenantId, topic, dataschemaVersion: opts.dataschemaVersion ?? DATASCHEMA_VERSION, payload: data },
198
+ { tenantId, topic, dataschemaVersion: options.dataschemaVersion ?? DATASCHEMA_VERSION, payload: data },
166
199
  eligible.map((install) => ({ installId: install.installId })),
167
200
  );
168
201
 
@@ -247,7 +280,7 @@ export async function dispatchInventoryDeliveries(
247
280
  /**
248
281
  * Emit `inventory.changed` once for a committed inventory movement on `db`. Writes the
249
282
  * `webhook_events` row and one `pending` `webhook_deliveries` row per active `inventory:read`
250
- * install on `input.tenantId`, gated on `input.gate` (defaulting to the movement row's presence in
283
+ * install on `input.tenantId` in the install env `input.stage` admits, gated on `input.gate` (defaulting to the movement row's presence in
251
284
  * `commerce_inventory_movements`) and the absence of the deterministic `eventId`.
252
285
  */
253
286
  export async function emitInventoryChanged(
@@ -265,7 +298,7 @@ export async function emitInventoryChanged(
265
298
  balance: input.balance,
266
299
  asOf: input.asOf,
267
300
  };
268
- const targetsQuery = commerceTargetsQuery(input.tenantId, "inventory.changed");
301
+ const targetsQuery = commerceTargetsQuery(input.tenantId, "inventory.changed", input.stage);
269
302
  const installs = await db.all<{ install_id: string }>(targetsQuery.sql, ...targetsQuery.params);
270
303
  const targets = await Promise.all(
271
304
  installs.map(async (row) => ({
@@ -300,6 +333,7 @@ export async function emitInventoryChanged(
300
333
  const statements = commerceEventStatements({
301
334
  eventId,
302
335
  tenantId: input.tenantId,
336
+ stage: input.stage,
303
337
  topic: "inventory.changed",
304
338
  payload,
305
339
  gate,
@@ -1,6 +1,6 @@
1
1
  /** Tenant-scoped inventory authority. Catalog availability never supplies a balance. */
2
2
  import type { Queryable } from "../catalog/d1/catalog.js";
3
- import type { CommerceStage } from "@tot/public-runtime";
3
+ import { appInstallEnvForStage, type CommerceStage } from "@tot/public-runtime";
4
4
  import { isStoredSku } from "@tot/public-runtime/sku";
5
5
  import type { MirrorStockAuthority } from "./allocations.js";
6
6
 
@@ -8,7 +8,8 @@ const ID = /^[A-Za-z0-9._:-]{1,128}$/;
8
8
  const INVENTORY_CHANGED_TOPIC = "inventory.changed";
9
9
  const INVENTORY_READ_SCOPE = "inventory:read";
10
10
  const INVENTORY_DATASCHEMA_VERSION = "1";
11
- const ELIGIBLE_INVENTORY_INSTALL_SQL = `i.tenant_id = ? AND i.status = 'active' AND i.managed_kind IS NULL
11
+ /** Binds tenant, then the install env the event's stage admits (appInstallEnvForStage). */
12
+ const ELIGIBLE_INVENTORY_INSTALL_SQL = `i.tenant_id = ? AND i.env = ? AND i.status = 'active' AND i.managed_kind IS NULL
12
13
  AND COALESCE(i.webhook_endpoint, '') != ''
13
14
  AND EXISTS (SELECT 1 FROM json_each(i.scopes) WHERE json_each.value = '${INVENTORY_READ_SCOPE}')`;
14
15
 
@@ -64,6 +65,7 @@ export async function recordMirrorInventoryChanged(
64
65
  },
65
66
  ): Promise<{ eventId: string; deliveryIds: string[] } | null> {
66
67
  const eventId = await mirrorMovementEventId(input);
68
+ const installEnv = appInstallEnvForStage(input.stage);
67
69
  const payload = JSON.stringify({
68
70
  sku: input.sku,
69
71
  locationId: input.locationId,
@@ -75,6 +77,7 @@ export async function recordMirrorInventoryChanged(
75
77
  WHERE ${ELIGIBLE_INVENTORY_INSTALL_SQL}
76
78
  ORDER BY i.created_at ASC, i.install_id ASC`,
77
79
  input.tenantId,
80
+ installEnv,
78
81
  );
79
82
  const targets = await Promise.all(
80
83
  installs.map(async (row) => ({
@@ -124,6 +127,7 @@ export async function recordMirrorInventoryChanged(
124
127
  input.asOf,
125
128
  target.installId,
126
129
  input.tenantId,
130
+ installEnv,
127
131
  eventId,
128
132
  input.tenantId,
129
133
  eventId,
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The commerce order ledger (`ScrappyOrderLedger`) read as the Private Apps
3
+ * contract's minimized `Order` shape (`docs/private-apps/contract/openapi.yaml`).
4
+ *
5
+ * This is how a `test` app install reads orders: the scoped order routes on a
6
+ * `preview` host read that stage's ledger partition through here and never the
7
+ * live order provider. Only paid orders are returned; a `scrappy` final-cart
8
+ * reservation is not an order. The ledger holds no customer identifier (contact
9
+ * lives in the encrypted vault), so the opaque `customerHash` is derived from the
10
+ * order id by the caller's per-install hasher. Money is the ledger's integer
11
+ * minor units of a two-decimal currency, reported in major units like the live
12
+ * provider's orders.
13
+ */
14
+ import type { CommerceStage } from "@tot/public-runtime";
15
+ import { foldCommerceEvents, type ContractOrder, type ContractOrderStatus } from "./orderMapper.js";
16
+ import type { CommerceOrderBookEntry, ScrappyOrderLedger } from "./ordersStore.js";
17
+
18
+ /** Opaque per-(tenant, install) customer hash of one subject. */
19
+ export type ContractCustomerHasher = (subject: string) => Promise<string>;
20
+
21
+ export interface LedgerContractScope {
22
+ tenantId: string;
23
+ stage: CommerceStage;
24
+ }
25
+
26
+ function toMajor(minor: number): number {
27
+ return minor / 100;
28
+ }
29
+
30
+ function isoInstant(value: string): string {
31
+ const parsed = new Date(value);
32
+ return Number.isNaN(parsed.getTime()) ? value : parsed.toISOString();
33
+ }
34
+
35
+ function contractStatus(entry: CommerceOrderBookEntry): ContractOrderStatus {
36
+ if (entry.fulfillment === "cancelled") return "cancelled";
37
+ if (
38
+ entry.payment === "voided" ||
39
+ entry.payment === "refunded" ||
40
+ entry.payment === "refund_requested" ||
41
+ entry.payment === "refund_unknown"
42
+ ) {
43
+ return "cancelled";
44
+ }
45
+ if (entry.fulfillment === "handed_off") return "fulfilled";
46
+ return "created";
47
+ }
48
+
49
+ /** Map one paid ledger order to the contract `Order`. */
50
+ export async function ledgerEntryToContractOrder(
51
+ entry: CommerceOrderBookEntry,
52
+ hashCustomer: ContractCustomerHasher,
53
+ ): Promise<ContractOrder> {
54
+ const totals =
55
+ entry.events.length > 0
56
+ ? foldCommerceEvents(entry.events).totals
57
+ : { subtotalMinor: entry.amountMinor, shippingMinor: 0, taxMinor: 0, totalMinor: entry.amountMinor };
58
+ const lines =
59
+ [...entry.events].sort((a, b) => b.eventVersion - a.eventVersion).find((event) => event.lines?.length)?.lines ?? [];
60
+ return {
61
+ id: entry.orderId,
62
+ status: contractStatus(entry),
63
+ currency: entry.currency,
64
+ customerHash: await hashCustomer(entry.orderId),
65
+ subtotal: toMajor(totals.subtotalMinor),
66
+ total: toMajor(totals.totalMinor),
67
+ lineItems: lines.map((line) => ({
68
+ sku: line.sku,
69
+ quantity: line.quantity,
70
+ lineTotal: toMajor(line.unitMinor * line.quantity),
71
+ })),
72
+ createdAt: isoInstant(entry.placedAt),
73
+ };
74
+ }
75
+
76
+ function paidOrders(book: readonly CommerceOrderBookEntry[]): CommerceOrderBookEntry[] {
77
+ return book.filter((entry) => entry.source !== "scrappy");
78
+ }
79
+
80
+ /** Every paid order in one tenant's stage partition, newest first. */
81
+ export async function readLedgerContractOrders(
82
+ ledger: Pick<ScrappyOrderLedger, "readOrderBook">,
83
+ scope: LedgerContractScope,
84
+ hashCustomer: ContractCustomerHasher,
85
+ ): Promise<ContractOrder[]> {
86
+ const book = paidOrders(await ledger.readOrderBook(scope.tenantId, scope.stage));
87
+ const orders = await Promise.all(book.map((entry) => ledgerEntryToContractOrder(entry, hashCustomer)));
88
+ return orders.sort((a, b) =>
89
+ a.createdAt === b.createdAt ? (a.id < b.id ? -1 : a.id > b.id ? 1 : 0) : a.createdAt < b.createdAt ? 1 : -1,
90
+ );
91
+ }
92
+
93
+ /** One paid order in one tenant's stage partition, or `null` when that partition has no such order. */
94
+ export async function readLedgerContractOrder(
95
+ ledger: Pick<ScrappyOrderLedger, "readOrderBook">,
96
+ scope: LedgerContractScope,
97
+ orderId: string,
98
+ hashCustomer: ContractCustomerHasher,
99
+ ): Promise<ContractOrder | null> {
100
+ const entry = paidOrders(await ledger.readOrderBook(scope.tenantId, scope.stage)).find(
101
+ (candidate) => candidate.orderId === orderId,
102
+ );
103
+ return entry ? ledgerEntryToContractOrder(entry, hashCustomer) : null;
104
+ }
@@ -158,7 +158,9 @@ export async function receiveForwardedOrder(
158
158
  if (await emitClaimedOrderFulfilled(db, input, order, options.notify)) emitted.push(topic);
159
159
  continue;
160
160
  }
161
- await emitWebhookEvent(topic, input.tenantId, toOrderData(order), {});
161
+ const stage = forwardStage(input.env);
162
+ if (!stage) continue;
163
+ await emitWebhookEvent(topic, input.tenantId, toOrderData(order), { stage });
162
164
  emitted.push(topic);
163
165
  }
164
166
 
@@ -183,7 +185,7 @@ async function emitClaimedOrderFulfilled(
183
185
  };
184
186
  const eventId = crypto.randomUUID();
185
187
  const now = new Date().toISOString();
186
- const targets = commerceTargetsQuery(input.tenantId, "order.fulfilled");
188
+ const targets = commerceTargetsQuery(input.tenantId, "order.fulfilled", stage);
187
189
  const installs = await db.all<{ install_id: string }>(targets.sql, ...targets.params);
188
190
  const deliveries = installs.map((row) => ({ installId: row.install_id, deliveryId: crypto.randomUUID() }));
189
191
  await db.batch([
@@ -191,6 +193,7 @@ async function emitClaimedOrderFulfilled(
191
193
  ...commerceEventStatements({
192
194
  eventId,
193
195
  tenantId: input.tenantId,
196
+ stage,
194
197
  topic: "order.fulfilled",
195
198
  payload: toOrderData(order),
196
199
  gate: claimedByEventGate(key, eventId),
@@ -394,6 +394,24 @@ function placedMonth(placedAt: Date): string {
394
394
  return `${placedAt.getUTCFullYear()}${String(placedAt.getUTCMonth() + 1).padStart(2, "0")}`;
395
395
  }
396
396
 
397
+ /**
398
+ * Whether both order-contact keys for this tenant and stage can be opened or generated right now.
399
+ * Writes nothing ({@link activeKey} never persists a generated key), so a caller that must refuse
400
+ * before its own writes when the vault is unavailable checks this first.
401
+ */
402
+ export async function orderContactKeysAvailable(
403
+ db: Queryable, kms: KmsClient, tenantId: string, stage: VaultStage, now: Date,
404
+ ): Promise<boolean> {
405
+ try {
406
+ await activeKey(db, kms, keyContext(tenantId, stage, ORDER_KEY), now);
407
+ await activeKey(db, kms, keyContext(tenantId, stage, BIDX_KEY), now);
408
+ return true;
409
+ } catch (error) {
410
+ if (error instanceof VaultKeyUnavailableError) return false;
411
+ throw error;
412
+ }
413
+ }
414
+
397
415
  /** Seal one order's contact from a verified contact command. */
398
416
  export async function sealOrderContact(db: Queryable, kms: KmsClient, input: SealInput): Promise<SealOutcome> {
399
417
  try {
@@ -88,6 +88,7 @@ export async function requestClientIp(headers: Headers, cdnOriginSecret: string
88
88
 
89
89
  const FORM_CONTENT_TYPES = ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"];
90
90
  const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
91
+ const OAUTH_TOKEN_PATH = "/api/apps/oauth/token";
91
92
 
92
93
  /**
93
94
  * Astro's cross-site form check, against the origin the viewer actually used.
@@ -100,10 +101,17 @@ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
100
101
  * one on its own (unlike a cookie or cached Basic credentials), and a cross-site script
101
102
  * that sets it triggers a CORS preflight this Worker does not grant. Server-to-server
102
103
  * writes — CI staging a bundle's `text/plain` objects into R2 — authenticate that way.
104
+ *
105
+ * `POST /api/apps/oauth/token` is not a browser form target either. It is the RFC 6749
106
+ * token endpoint: an OAuth client posts `application/x-www-form-urlencoded` from a server,
107
+ * authenticated by the client secret it carries (form fields or HTTP Basic), never by a
108
+ * cookie, so a forged cross-site post gains nothing. Only that exact path and method are
109
+ * exempt.
103
110
  */
104
111
  export function crossSiteFormRefusal(request: Request, expectedOrigin: string): Response | null {
105
112
  if (SAFE_METHODS.has(request.method)) return null;
106
113
  if (/^bearer\s+\S/i.test(request.headers.get("authorization") ?? "")) return null;
114
+ if (request.method === "POST" && new URL(request.url).pathname === OAUTH_TOKEN_PATH) return null;
107
115
  if (request.headers.get("origin") === expectedOrigin) return null;
108
116
  const contentType = request.headers.get("content-type");
109
117
  if (contentType !== null) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.11.11",
3
+ "version": "6.12.0",
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",
@@ -201,6 +201,14 @@ export interface MeasuredFoxyOrderList {
201
201
  export const COMMERCE_STAGES = ["preview", "publication"] as const;
202
202
  export type CommerceStage = (typeof COMMERCE_STAGES)[number];
203
203
 
204
+ /** The env of a Private Apps install. Each commerce stage admits exactly one. */
205
+ export type AppInstallEnv = "production" | "test";
206
+
207
+ /** The single install env a commerce stage admits: `preview` → `test`, `publication` → `production`. */
208
+ export function appInstallEnvForStage(stage: CommerceStage): AppInstallEnv {
209
+ return stage === "publication" ? "production" : "test";
210
+ }
211
+
204
212
  export const PAYMENT_STATES = [
205
213
  "UNKNOWN",
206
214
  "pending",