@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.
@@ -27,7 +27,9 @@ import {
27
27
  cleanupStatement,
28
28
  deleteUnreferencedRetiredKeys,
29
29
  keyForKid,
30
+ keyRowRestore,
30
31
  rotateDueKeys,
32
+ type ActiveDataKey,
31
33
  } from "@/lib/customers/contactVault/dataKeys.js";
32
34
  import { openField, sealField, type FieldBinding } from "@/lib/customers/contactVault/fieldEnvelope.js";
33
35
  import { blindIndex, normalizeEmail, normalizePhone } from "@/lib/customers/contactVault/blindIndex.js";
@@ -351,6 +353,8 @@ export interface SealInput {
351
353
  regulated: boolean;
352
354
  now: Date;
353
355
  policy?: RetentionPolicy;
356
+ /** Key material from {@link prepareOrderContactKeys}; every attempt seals under it without reading the active key. */
357
+ keys?: PreparedOrderContactKeys;
354
358
  }
355
359
 
356
360
  interface SealSnapshot extends OrderSnapshot {
@@ -394,29 +398,79 @@ function placedMonth(placedAt: Date): string {
394
398
  return `${placedAt.getUTCFullYear()}${String(placedAt.getUTCMonth() + 1).padStart(2, "0")}`;
395
399
  }
396
400
 
401
+ /** Order-contact key material opened before a caller's own writes; see {@link prepareOrderContactKeys}. */
402
+ export interface PreparedOrderContactKeys {
403
+ readonly order: ActiveDataKey;
404
+ readonly bidx: ActiveDataKey;
405
+ /** Puts each key's row back, retired, if rotation swept it before the seal; first in the seal batch. */
406
+ readonly restore: readonly QueryStatement[];
407
+ }
408
+
397
409
  /**
398
- * Make both order-contact keys for this tenant and stage durable and open, for a caller that must
399
- * refuse before its own writes when the vault cannot seal. When either key cannot be opened or
400
- * generated it returns false having written nothing. Otherwise it stores any newly generated key
401
- * (the insert yields to an active key another writer stored first) and opens the stored keys, so a
402
- * following {@link sealOrderContact} reads keys that already exist rather than generating them.
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`: every seal attempt uses it without
415
+ * reading the active key or calling KMS, and its batch first restores a key row rotation retired and
416
+ * swept in between, so neither a KMS outage nor a rotation after the caller's writes stops the seal.
403
417
  */
404
418
  export async function prepareOrderContactKeys(
405
419
  db: Queryable, kms: KmsClient, tenantId: string, stage: VaultStage, now: Date,
406
- ): Promise<boolean> {
407
- const contexts = [keyContext(tenantId, stage, ORDER_KEY), keyContext(tenantId, stage, BIDX_KEY)];
420
+ ): Promise<PreparedOrderContactKeys | null> {
421
+ const orderCtx = keyContext(tenantId, stage, ORDER_KEY);
422
+ const bidxCtx = keyContext(tenantId, stage, BIDX_KEY);
423
+ let order: ActiveDataKey;
424
+ let bidx: ActiveDataKey;
408
425
  try {
409
- const opened = [];
410
- for (const ctx of contexts) opened.push(await activeKey(db, kms, ctx, now));
411
- const pending = opened.flatMap((key) => key.pending);
412
- if (pending.length === 0) return true;
413
- await requireBatch(db)(pending);
414
- for (const ctx of contexts) await activeKey(db, kms, ctx, now);
415
- return true;
426
+ order = await activeKey(db, kms, orderCtx, now);
427
+ bidx = await activeKey(db, kms, bidxCtx, now);
416
428
  } catch (error) {
417
- if (error instanceof VaultKeyUnavailableError) return false;
429
+ if (error instanceof VaultKeyUnavailableError) return null;
418
430
  throw error;
419
431
  }
432
+ const generated = ([[orderCtx, order], [bidxCtx, bidx]] as const).filter(([, key]) => key.pending.length > 0);
433
+ const refuse = async (): Promise<null> => {
434
+ if (generated.length > 0) await requireBatch(db)(generated.map(([ctx, key]) => unreferencedKeyCleanup(ctx, key.kid)));
435
+ return null;
436
+ };
437
+ if (generated.length > 0) {
438
+ await requireBatch(db)(generated.flatMap(([, key]) => key.pending));
439
+ try {
440
+ order = await storedKey(db, kms, orderCtx, order, now);
441
+ bidx = await storedKey(db, kms, bidxCtx, bidx, now);
442
+ } catch (error) {
443
+ if (!(error instanceof VaultKeyUnavailableError)) throw error;
444
+ return refuse();
445
+ }
446
+ }
447
+ const orderRestore = await keyRowRestore(db, orderCtx, order.kid, now);
448
+ const bidxRestore = await keyRowRestore(db, bidxCtx, bidx.kid, now);
449
+ if (!orderRestore || !bidxRestore) return refuse();
450
+ return { order, bidx, restore: [orderRestore, bidxRestore] };
451
+ }
452
+
453
+ /** The key to seal under after storing `mine`: itself when its insert landed, else the active winner. */
454
+ async function storedKey(db: Queryable, kms: KmsClient, ctx: EncryptionContext, mine: ActiveDataKey, now: Date): Promise<ActiveDataKey> {
455
+ if (mine.pending.length === 0) return mine;
456
+ const active = await db.first<{ kid: string }>(
457
+ `SELECT kid FROM contact_vault_data_keys WHERE tenant_id = ? AND stage = ? AND purpose = ? AND retired_at IS NULL`,
458
+ ctx.tenantId, ctx.stage, ctx.purpose,
459
+ );
460
+ if (active?.kid === mine.kid) return { kid: mine.kid, key: mine.key, pending: [] };
461
+ return activeKey(db, kms, ctx, now);
462
+ }
463
+
464
+ /** Removes `kid` when no order-contact record (or, for the blind-index key, contact message) names it. */
465
+ function unreferencedKeyCleanup(ctx: EncryptionContext, kid: string): QueryStatement {
466
+ const { tenantId, stage } = ctx;
467
+ return ctx.purpose === ORDER_KEY
468
+ ? cleanupStatement(ctx, kid,
469
+ `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND order_kid = ?`, [tenantId, stage, kid])
470
+ : cleanupStatement(ctx, kid,
471
+ `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND bidx_kid = ?
472
+ UNION ALL SELECT 1 FROM contact_messages WHERE tenant_id = ? AND stage = ? AND bidx_kid = ?`,
473
+ [tenantId, stage, kid, tenantId, stage, kid]);
420
474
  }
421
475
 
422
476
  /** Seal one order's contact from a verified contact command. */
@@ -462,8 +516,8 @@ async function sealAttempt(db: Queryable, kms: KmsClient, input: SealInput, atte
462
516
 
463
517
  const orderCtx = keyContext(tenantId, stage, ORDER_KEY);
464
518
  const bidxCtx = keyContext(tenantId, stage, BIDX_KEY);
465
- const orderKey = await activeKey(db, kms, orderCtx, now);
466
- const bidxKey = await activeKey(db, kms, bidxCtx, now);
519
+ const orderKey = input.keys?.order ?? await activeKey(db, kms, orderCtx, now);
520
+ const bidxKey = input.keys?.bidx ?? await activeKey(db, kms, bidxCtx, now);
467
521
 
468
522
  const factId = randomHex128();
469
523
  // A group whose expiry has already passed is never written: only live groups are sealed.
@@ -506,6 +560,7 @@ async function sealAttempt(db: Queryable, kms: KmsClient, input: SealInput, atte
506
560
  const vaultRowSql = `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND order_id = ? AND sealed_jti = ?`;
507
561
  const vaultRowParams = [tenantId, stage, orderId, sealedJti];
508
562
  const statements: QueryStatement[] = [
563
+ ...(input.keys?.restore ?? []),
509
564
  ...orderKey.pending,
510
565
  ...bidxKey.pending,
511
566
  {
@@ -544,16 +599,8 @@ async function sealAttempt(db: Queryable, kms: KmsClient, input: SealInput, atte
544
599
  params: [tenantId, stage, issuer, jti, nowIso, ...vaultRowParams],
545
600
  },
546
601
  ];
547
- if (orderKey.pending.length > 0) {
548
- statements.push(cleanupStatement(orderCtx, orderKey.kid,
549
- `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND order_kid = ?`, [tenantId, stage, orderKey.kid]));
550
- }
551
- if (bidxKey.pending.length > 0) {
552
- statements.push(cleanupStatement(bidxCtx, bidxKey.kid,
553
- `SELECT 1 FROM order_contact_vault WHERE tenant_id = ? AND stage = ? AND bidx_kid = ?
554
- UNION ALL SELECT 1 FROM contact_messages WHERE tenant_id = ? AND stage = ? AND bidx_kid = ?`,
555
- [tenantId, stage, bidxKey.kid, tenantId, stage, bidxKey.kid]));
556
- }
602
+ if (orderKey.pending.length > 0) statements.push(unreferencedKeyCleanup(orderCtx, orderKey.kid));
603
+ if (bidxKey.pending.length > 0) statements.push(unreferencedKeyCleanup(bidxCtx, bidxKey.kid));
557
604
  try {
558
605
  await requireBatch(db)(statements);
559
606
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.12.1",
3
+ "version": "6.12.3",
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",