@tokenoftrust/storefront-runner 6.12.0 → 6.12.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.
@@ -14,7 +14,7 @@
14
14
  * bound, the release assigns it and queues the processor's assignment webhook.
15
15
  */
16
16
  import type { Queryable } from "../catalog/d1/catalog.js";
17
- import { orderContactKeysAvailable, sealOrderContact } from "../orders/vault/orderContactVault.js";
17
+ import { prepareOrderContactKeys, sealOrderContact } from "../orders/vault/orderContactVault.js";
18
18
  import { readOrderContactCommand, type OrderContactCommand } from "../orders/vault/orderContact.js";
19
19
  import { grantConsent, grantedByHash } from "../integrations/apps/appContactConsents.js";
20
20
  import { readProcessor, setProcessor } from "./assignmentStore.js";
@@ -147,7 +147,11 @@ export async function bindTestProcessor(
147
147
  };
148
148
  }
149
149
 
150
- /** Write one synthetic preview order, its source authority, and its sealed RFC-reserved recipient. */
150
+ /**
151
+ * Write one synthetic preview order, its source authority, and its sealed RFC-reserved recipient.
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.
154
+ */
151
155
  export async function createSyntheticOrder(
152
156
  deps: SyntheticOrderDeps,
153
157
  scope: SyntheticScope,
@@ -159,10 +163,8 @@ export async function createSyntheticOrder(
159
163
  return { ok: false, code: "vault-key-unavailable" };
160
164
  }
161
165
  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 keys = await prepareOrderContactKeys(deps.db, kms, scope.tenantId, SYNTHETIC_STAGE, now);
167
+ if (!keys) return { ok: false, code: "vault-key-unavailable" };
166
168
  const nowIso = now.toISOString();
167
169
  const sourceOrderId = `${now.getTime()}${Math.floor(Math.random() * 1_000_000)}`;
168
170
  const orderId = `synthetic-${sourceOrderId}`;
@@ -197,6 +199,7 @@ export async function createSyntheticOrder(
197
199
  jti: `synthetic-seal-${orderId}`,
198
200
  regulated: false,
199
201
  now,
202
+ keys,
200
203
  });
201
204
  if (!sealed.ok) {
202
205
  return { ok: false, code: sealed.reason === "vault-key-unavailable" ? "vault-key-unavailable" : "contact-refused" };
@@ -28,6 +28,7 @@ import {
28
28
  deleteUnreferencedRetiredKeys,
29
29
  keyForKid,
30
30
  rotateDueKeys,
31
+ type ActiveDataKey,
31
32
  } from "@/lib/customers/contactVault/dataKeys.js";
32
33
  import { openField, sealField, type FieldBinding } from "@/lib/customers/contactVault/fieldEnvelope.js";
33
34
  import { blindIndex, normalizeEmail, normalizePhone } from "@/lib/customers/contactVault/blindIndex.js";
@@ -351,6 +352,11 @@ export interface SealInput {
351
352
  regulated: boolean;
352
353
  now: Date;
353
354
  policy?: RetentionPolicy;
355
+ /**
356
+ * Key material from {@link prepareOrderContactKeys}. The first attempt seals under it without
357
+ * reading the active key; a retry after a concurrent change reads the active key afresh.
358
+ */
359
+ keys?: PreparedOrderContactKeys;
354
360
  }
355
361
 
356
362
  interface SealSnapshot extends OrderSnapshot {
@@ -394,22 +400,67 @@ function placedMonth(placedAt: Date): string {
394
400
  return `${placedAt.getUTCFullYear()}${String(placedAt.getUTCMonth() + 1).padStart(2, "0")}`;
395
401
  }
396
402
 
403
+ /** Order-contact key material opened before a caller's own writes; see {@link prepareOrderContactKeys}. */
404
+ export interface PreparedOrderContactKeys {
405
+ readonly order: ActiveDataKey;
406
+ readonly bidx: ActiveDataKey;
407
+ }
408
+
397
409
  /**
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.
410
+ * Open both order-contact keys for this tenant and stage and make them durable, for a caller that must
411
+ * refuse before its own writes when the vault cannot seal. Returns null when a key cannot be opened or
412
+ * generated, leaving no key row of its own behind. Otherwise any newly generated key is stored (the
413
+ * insert yields to an active key another writer stored first, which is opened instead) and the
414
+ * returned material goes to {@link sealOrderContact} as `keys`: the seal uses it without reading the
415
+ * active key or calling KMS for it, and a stored kid stays sealable after rotation retires it.
401
416
  */
402
- export async function orderContactKeysAvailable(
417
+ export async function prepareOrderContactKeys(
403
418
  db: Queryable, kms: KmsClient, tenantId: string, stage: VaultStage, now: Date,
404
- ): Promise<boolean> {
419
+ ): Promise<PreparedOrderContactKeys | null> {
420
+ const orderCtx = keyContext(tenantId, stage, ORDER_KEY);
421
+ const bidxCtx = keyContext(tenantId, stage, BIDX_KEY);
422
+ let order: ActiveDataKey;
423
+ let bidx: ActiveDataKey;
405
424
  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;
425
+ order = await activeKey(db, kms, orderCtx, now);
426
+ bidx = await activeKey(db, kms, bidxCtx, now);
409
427
  } catch (error) {
410
- if (error instanceof VaultKeyUnavailableError) return false;
428
+ if (error instanceof VaultKeyUnavailableError) return null;
411
429
  throw error;
412
430
  }
431
+ const generated = ([[orderCtx, order], [bidxCtx, bidx]] as const).filter(([, key]) => key.pending.length > 0);
432
+ if (generated.length === 0) return { order, bidx };
433
+ await requireBatch(db)(generated.flatMap(([, key]) => key.pending));
434
+ try {
435
+ return { order: await storedKey(db, kms, orderCtx, order, now), bidx: await storedKey(db, kms, bidxCtx, bidx, now) };
436
+ } catch (error) {
437
+ if (!(error instanceof VaultKeyUnavailableError)) throw error;
438
+ await requireBatch(db)(generated.map(([ctx, key]) => unreferencedKeyCleanup(ctx, key.kid)));
439
+ return null;
440
+ }
441
+ }
442
+
443
+ /** The key to seal under after storing `mine`: itself when its insert landed, else the active winner. */
444
+ async function storedKey(db: Queryable, kms: KmsClient, ctx: EncryptionContext, mine: ActiveDataKey, now: Date): Promise<ActiveDataKey> {
445
+ if (mine.pending.length === 0) return mine;
446
+ const active = await db.first<{ kid: string }>(
447
+ `SELECT kid FROM contact_vault_data_keys WHERE tenant_id = ? AND stage = ? AND purpose = ? AND retired_at IS NULL`,
448
+ ctx.tenantId, ctx.stage, ctx.purpose,
449
+ );
450
+ if (active?.kid === mine.kid) return { kid: mine.kid, key: mine.key, pending: [] };
451
+ return activeKey(db, kms, ctx, now);
452
+ }
453
+
454
+ /** Removes `kid` when no order-contact record (or, for the blind-index key, contact message) names it. */
455
+ function unreferencedKeyCleanup(ctx: EncryptionContext, kid: string): QueryStatement {
456
+ const { tenantId, stage } = ctx;
457
+ return ctx.purpose === ORDER_KEY
458
+ ? cleanupStatement(ctx, kid,
459
+ `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND order_kid = ?`, [tenantId, stage, kid])
460
+ : cleanupStatement(ctx, kid,
461
+ `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND bidx_kid = ?
462
+ UNION ALL SELECT 1 FROM contact_messages WHERE tenant_id = ? AND stage = ? AND bidx_kid = ?`,
463
+ [tenantId, stage, kid, tenantId, stage, kid]);
413
464
  }
414
465
 
415
466
  /** Seal one order's contact from a verified contact command. */
@@ -455,8 +506,8 @@ async function sealAttempt(db: Queryable, kms: KmsClient, input: SealInput, atte
455
506
 
456
507
  const orderCtx = keyContext(tenantId, stage, ORDER_KEY);
457
508
  const bidxCtx = keyContext(tenantId, stage, BIDX_KEY);
458
- const orderKey = await activeKey(db, kms, orderCtx, now);
459
- const bidxKey = await activeKey(db, kms, bidxCtx, now);
509
+ const orderKey = input.keys?.order ?? await activeKey(db, kms, orderCtx, now);
510
+ const bidxKey = input.keys?.bidx ?? await activeKey(db, kms, bidxCtx, now);
460
511
 
461
512
  const factId = randomHex128();
462
513
  // A group whose expiry has already passed is never written: only live groups are sealed.
@@ -537,16 +588,8 @@ async function sealAttempt(db: Queryable, kms: KmsClient, input: SealInput, atte
537
588
  params: [tenantId, stage, issuer, jti, nowIso, ...vaultRowParams],
538
589
  },
539
590
  ];
540
- if (orderKey.pending.length > 0) {
541
- statements.push(cleanupStatement(orderCtx, orderKey.kid,
542
- `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND order_kid = ?`, [tenantId, stage, orderKey.kid]));
543
- }
544
- if (bidxKey.pending.length > 0) {
545
- statements.push(cleanupStatement(bidxCtx, bidxKey.kid,
546
- `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND bidx_kid = ?
547
- UNION ALL SELECT 1 FROM contact_messages WHERE tenant_id = ? AND stage = ? AND bidx_kid = ?`,
548
- [tenantId, stage, bidxKey.kid, tenantId, stage, bidxKey.kid]));
549
- }
591
+ if (orderKey.pending.length > 0) statements.push(unreferencedKeyCleanup(orderCtx, orderKey.kid));
592
+ if (bidxKey.pending.length > 0) statements.push(unreferencedKeyCleanup(bidxCtx, bidxKey.kid));
550
593
  try {
551
594
  await requireBatch(db)(statements);
552
595
  } catch (error) {
@@ -562,7 +605,7 @@ async function sealAttempt(db: Queryable, kms: KmsClient, input: SealInput, atte
562
605
  if (after) return after;
563
606
  // Nothing committed: the order's retention snapshot or the active key changed underneath. Re-read
564
607
  // and re-seal, bounded.
565
- if (attempts > 1) return sealAttempt(db, kms, input, attempts - 1);
608
+ if (attempts > 1) return sealAttempt(db, kms, { ...input, keys: undefined }, attempts - 1);
566
609
  throw new Error("contact-retention-changed");
567
610
  }
568
611
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.12.0",
3
+ "version": "6.12.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",