@serfab/cadre-core 1.20.0 → 1.22.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.
Files changed (113) hide show
  1. package/README.md +294 -294
  2. package/dist/cadre-node.d.ts +329 -53
  3. package/dist/cadre-node.js +767 -85
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-authorization.d.ts +32 -2
  6. package/dist/control-authorization.js +19 -0
  7. package/dist/control-authorization.js.map +1 -1
  8. package/dist/control-database.d.ts +236 -23
  9. package/dist/control-database.js +601 -178
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-schema.d.ts +3 -3
  12. package/dist/control-schema.js +71 -7
  13. package/dist/control-schema.js.map +1 -1
  14. package/dist/ed25519-key.d.ts +8 -0
  15. package/dist/ed25519-key.js +11 -1
  16. package/dist/ed25519-key.js.map +1 -1
  17. package/dist/index.d.ts +5 -1
  18. package/dist/index.js +13 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/machine-removal.d.ts +51 -1
  21. package/dist/machine-removal.js +42 -1
  22. package/dist/machine-removal.js.map +1 -1
  23. package/dist/membership-connection-gater.d.ts +8 -0
  24. package/dist/membership-connection-gater.js +13 -1
  25. package/dist/membership-connection-gater.js.map +1 -1
  26. package/dist/owner-keys.js +2 -1
  27. package/dist/owner-keys.js.map +1 -1
  28. package/dist/owner-signer.js +3 -4
  29. package/dist/owner-signer.js.map +1 -1
  30. package/dist/peer-authorization.d.ts +14 -2
  31. package/dist/peer-authorization.js +24 -1
  32. package/dist/peer-authorization.js.map +1 -1
  33. package/dist/relay-reservation.js +20 -1
  34. package/dist/relay-reservation.js.map +1 -1
  35. package/dist/sealed-party-key.d.ts +32 -0
  36. package/dist/sealed-party-key.js +162 -0
  37. package/dist/sealed-party-key.js.map +1 -0
  38. package/dist/seed-bootstrap.d.ts +10 -3
  39. package/dist/seed-bootstrap.js +12 -0
  40. package/dist/seed-bootstrap.js.map +1 -1
  41. package/dist/strand-addr-protocol.d.ts +56 -6
  42. package/dist/strand-addr-protocol.js +57 -5
  43. package/dist/strand-addr-protocol.js.map +1 -1
  44. package/dist/strand-app-schema-report.d.ts +6 -3
  45. package/dist/strand-app-schema-report.js +13 -7
  46. package/dist/strand-app-schema-report.js.map +1 -1
  47. package/dist/strand-commit-durability.d.ts +33 -2
  48. package/dist/strand-commit-durability.js +44 -4
  49. package/dist/strand-commit-durability.js.map +1 -1
  50. package/dist/strand-database.d.ts +36 -6
  51. package/dist/strand-database.js +35 -11
  52. package/dist/strand-database.js.map +1 -1
  53. package/dist/strand-instance-manager.d.ts +133 -9
  54. package/dist/strand-instance-manager.js +266 -42
  55. package/dist/strand-instance-manager.js.map +1 -1
  56. package/dist/strand-membership-reconciler.d.ts +250 -51
  57. package/dist/strand-membership-reconciler.js +410 -66
  58. package/dist/strand-membership-reconciler.js.map +1 -1
  59. package/dist/strand-membership-writer.d.ts +7 -0
  60. package/dist/strand-membership-writer.js +9 -0
  61. package/dist/strand-membership-writer.js.map +1 -1
  62. package/dist/strand-party-key-rotation.d.ts +177 -0
  63. package/dist/strand-party-key-rotation.js +340 -0
  64. package/dist/strand-party-key-rotation.js.map +1 -0
  65. package/dist/strand-party-machines.d.ts +111 -0
  66. package/dist/strand-party-machines.js +258 -0
  67. package/dist/strand-party-machines.js.map +1 -0
  68. package/dist/strand-party-peers.d.ts +101 -0
  69. package/dist/strand-party-peers.js +49 -0
  70. package/dist/strand-party-peers.js.map +1 -0
  71. package/dist/strand-peer-redial.d.ts +34 -7
  72. package/dist/strand-peer-redial.js +46 -13
  73. package/dist/strand-peer-redial.js.map +1 -1
  74. package/dist/strand-revocation-enforcer.d.ts +15 -1
  75. package/dist/strand-revocation-enforcer.js +16 -9
  76. package/dist/strand-revocation-enforcer.js.map +1 -1
  77. package/dist/strand-transport-key.js +3 -0
  78. package/dist/strand-transport-key.js.map +1 -1
  79. package/dist/strand-watcher.d.ts +7 -4
  80. package/dist/strand-watcher.js +12 -7
  81. package/dist/strand-watcher.js.map +1 -1
  82. package/dist/types.d.ts +165 -17
  83. package/dist/types.js.map +1 -1
  84. package/package.json +9 -8
  85. package/src/cadre-node.ts +12252 -11528
  86. package/src/control-authorization.ts +41 -1
  87. package/src/control-database.ts +6123 -5594
  88. package/src/control-schema.ts +71 -7
  89. package/src/ed25519-key.ts +12 -1
  90. package/src/index.ts +957 -924
  91. package/src/machine-removal.ts +80 -1
  92. package/src/membership-connection-gater.ts +13 -1
  93. package/src/owner-keys.ts +2 -1
  94. package/src/owner-signer.ts +92 -94
  95. package/src/peer-authorization.ts +27 -3
  96. package/src/relay-reservation.ts +28 -1
  97. package/src/sealed-party-key.ts +190 -0
  98. package/src/seed-bootstrap.ts +17 -3
  99. package/src/strand-addr-protocol.ts +67 -6
  100. package/src/strand-app-schema-report.ts +17 -10
  101. package/src/strand-commit-durability.ts +54 -5
  102. package/src/strand-database.ts +48 -12
  103. package/src/strand-instance-manager.ts +330 -42
  104. package/src/strand-membership-reconciler.ts +1310 -942
  105. package/src/strand-membership-writer.ts +10 -0
  106. package/src/strand-party-key-rotation.ts +436 -0
  107. package/src/strand-party-machines.ts +293 -0
  108. package/src/strand-party-peers.ts +129 -0
  109. package/src/strand-peer-redial.ts +61 -14
  110. package/src/strand-revocation-enforcer.ts +27 -9
  111. package/src/strand-transport-key.ts +3 -0
  112. package/src/strand-watcher.ts +12 -7
  113. package/src/types.ts +3112 -2962
@@ -8,9 +8,10 @@ import { createEmptyCollections } from '@serfab/quereus-plugin-sereus';
8
8
  import { APPLY_CONTROL_SCHEMA, CONTROL_SCHEMA_DECLARATION, CONTROL_SCHEMA_NAME, controlSchemaFileDeclaration } from './control-schema.js';
9
9
  import { refuseIncompatibleControlStore } from './control-schema-version.js';
10
10
  import { canonicalDatetime } from './canonical-datetime.js';
11
- import { controlAuthorizationFields, unboundAuthorizationFields, cadreInviteRowFields, ownerGrantRowFields, CONTROL_TABLES } from './control-authorization.js';
11
+ import { controlAuthorizationFields, unboundAuthorizationFields, cadreInviteRowFields, ownerGrantRowFields, strandPeerRowFields, pendingStrandPartyKeyRowFields, CONTROL_TABLES } from './control-authorization.js';
12
12
  import { requireEd25519PublicKeyB64 } from './ed25519-key.js';
13
- import { verifyCadreInviteRow, verifyOwnerGrantRow } from './peer-authorization.js';
13
+ import { strandMemberKeyPair } from './strand-member-key.js';
14
+ import { verifyCadreInviteRow, verifyOwnerGrantRow, verifyStrandPeerRow } from './peer-authorization.js';
14
15
  import { OWNER_KEY_MAX_LABEL } from './owner-key-export.js';
15
16
  import { retryControlWrite, LOST_UPDATE_RETRY_POLICY, SCHEMA_INIT_RETRY_POLICY } from './control-write-retry.js';
16
17
  import { isCohortUnreachableRead, retryControlRead } from './control-read-retry.js';
@@ -375,6 +376,7 @@ const GUARDED_KEY_COLUMN = {
375
376
  ValidationKey: 'Key',
376
377
  Strand: 'Id',
377
378
  StrandPartyKey: 'Id',
379
+ PendingStrandPartyKey: 'Id',
378
380
  JoinedStrand: 'Id',
379
381
  JoinRequest: 'Id',
380
382
  DeviceToken: 'PeerId',
@@ -383,6 +385,18 @@ const GUARDED_KEY_COLUMN = {
383
385
  };
384
386
  /** The write-reason prefix each {@link IssuedTable}'s seat and withdrawal log under. */
385
387
  const ISSUED_TABLE_REASON = { CadreInvite: 'cadre-invite', OwnerGrant: 'owner-grant' };
388
+ /** The columns every `PendingStrandPartyKey` read takes, as {@link pendingPartyKeyOfRow} maps them. */
389
+ const PENDING_PARTY_KEY_COLUMNS = 'PublicKey, SealedKey, Superseded, StampId';
390
+ const PENDING_PARTY_KEY_SELECT = `select ${PENDING_PARTY_KEY_COLUMNS} from CadreControl.PendingStrandPartyKey where Id = ?`;
391
+ function pendingPartyKeyOfRow(row) {
392
+ const superseded = row.Superseded;
393
+ return {
394
+ publicKey: row.PublicKey,
395
+ sealedKey: row.SealedKey,
396
+ superseded: superseded === null ? [] : superseded.split(','),
397
+ stampId: row.StampId,
398
+ };
399
+ }
386
400
  /**
387
401
  * The exact bytes an owner signs to append one `Revocation` tombstone — `Revocation.Authorized`
388
402
  * binds the whole (TableName, RowKey, StampId) row under its own domain tag. Shared by both
@@ -550,10 +564,10 @@ function issuedRowStillOpen(row, withdrawn, owners, nowMs) {
550
564
  /**
551
565
  * Guarded tables a node may reap locally once their tombstone has committed — the
552
566
  * tables whose `AuthorizedDelete` carries the REAP branch (see the constraint comment on
553
- * `CadrePeer.AuthorizedDelete` in the schema). `Strand` and `StrandPartyKey` are
554
- * deliberately absent: their rows carry `MemberPrivateKey` / `PrivateKey` — party
555
- * secrets stored nowhere else (tickets/backlog/debt-strand-tombstone-reap.md owns any
556
- * future change). `JoinedStrand` also carries a `MemberPrivateKey` but IS reapable: that
567
+ * `CadrePeer.AuthorizedDelete` in the schema). `Strand`, `StrandPartyKey` and
568
+ * `PendingStrandPartyKey` are deliberately absent: their rows carry `MemberPrivateKey` /
569
+ * `PrivateKey` / `SealedKey` — party secrets stored nowhere else (tickets/backlog/debt-strand-tombstone-reap.md
570
+ * owns any future change). `JoinedStrand` also carries a `MemberPrivateKey` but IS reapable: that
557
571
  * secret is the joined strand's shared read key, which its founding party and every member
558
572
  * hold, so a reaped row is recoverable by re-forming. `JoinRequest` is reapable for the same
559
573
  * reason: the inviting party and the user also hold its invitation. `OwnerKey` has no
@@ -565,7 +579,7 @@ export const REAPABLE_TABLES = ['CadrePeer', 'DeviceToken', 'ValidationKey', 'Jo
565
579
  /**
566
580
  * Runtime membership test for {@link REAPABLE_TABLES}, narrowing a tombstone's
567
581
  * `TableName` to the subset {@link ControlDatabase.reapRevokedRow} accepts. A tombstone
568
- * naming an excluded table (`Strand`, `OwnerKey`, `CadreInvite`, `OwnerGrant`) is skipped silently —
582
+ * naming an excluded table (`Strand`, `PendingStrandPartyKey`, `OwnerKey`, `CadreInvite`, `OwnerGrant`) is skipped silently —
569
583
  * `Strand` tombstones are the common case in a party that has unpublished a strand, so a
570
584
  * log line per skip would be per-pass noise.
571
585
  */
@@ -581,6 +595,18 @@ const isReapableTable = (table) => REAPABLE_TABLE_SET.has(table);
581
595
  const REVOCATION_SELECT_SQL = 'select TableName, RowKey, StampId, ReissuedAt, SignerKey, SignerSig from CadreControl.Revocation';
582
596
  const CADRE_PEER_SELECT_SQL = 'select PeerId, Multiaddr, StampId, VouchOwner, VouchSig, VouchUsage, PublicKey, UpdatedAt, Profile, Sig from CadreControl.CadrePeer';
583
597
  const OWNER_KEY_SELECT_SQL = 'select Key, Label, StampId, VouchOwner, VouchSig, VouchUsage from CadreControl.OwnerKey';
598
+ /** The `CadrePeer` rows of `rows` whose stamp is not in `revoked` — the live ones, as every reader judges them. */
599
+ function liveCadrePeerRows(rows, revoked) {
600
+ const live = [];
601
+ for (const row of rows) {
602
+ const peer = cadrePeerRowOf(row);
603
+ if (peer.stampId !== null && revoked.has(peer.stampId)) {
604
+ continue;
605
+ }
606
+ live.push(peer);
607
+ }
608
+ return live;
609
+ }
584
610
  /** A stored `CadrePeer` row as a {@link CadrePeerRow}. */
585
611
  function cadrePeerRowOf(row) {
586
612
  return {
@@ -729,32 +755,32 @@ function formationInviteRowOf(row) {
729
755
  strandId: row.StrandId ?? null,
730
756
  };
731
757
  }
732
- const JOIN_REQUEST_INSERT_SQL = `
733
- insert into CadreControl.JoinRequest (Id, Invitation, Disclosure, RequestedAt, ExpiresAt, StampId)
734
- with context OwnerKey = ?, Signature = ?
735
- values (?, ?, ?, ?, ?, ?)
758
+ const JOIN_REQUEST_INSERT_SQL = `
759
+ insert into CadreControl.JoinRequest (Id, Invitation, Disclosure, RequestedAt, ExpiresAt, StampId)
760
+ with context OwnerKey = ?, Signature = ?
761
+ values (?, ?, ?, ?, ?, ?)
736
762
  `;
737
- const JOIN_SUCCESS_INSERT_SQL = `
738
- insert into CadreControl.JoinSuccess (RequestStampId, RecordedAt, StrandId, MembershipInvite)
739
- with context OwnerKey = ?, Signature = ?
740
- values (?, ?, ?, ?)
763
+ const JOIN_SUCCESS_INSERT_SQL = `
764
+ insert into CadreControl.JoinSuccess (RequestStampId, RecordedAt, StrandId, MembershipInvite)
765
+ with context OwnerKey = ?, Signature = ?
766
+ values (?, ?, ?, ?)
741
767
  `;
742
- const JOIN_FAILURE_INSERT_SQL = `
743
- insert into CadreControl.JoinFailure (RequestStampId, RecordedAt, Code, Reason)
744
- with context OwnerKey = ?, Signature = ?
745
- values (?, ?, ?, ?)
768
+ const JOIN_FAILURE_INSERT_SQL = `
769
+ insert into CadreControl.JoinFailure (RequestStampId, RecordedAt, Code, Reason)
770
+ with context OwnerKey = ?, Signature = ?
771
+ values (?, ?, ?, ?)
746
772
  `;
747
773
  /**
748
774
  * A request with its outcome in one statement: the outcome tables are keyed by the request's
749
775
  * stamp, so the join finds exactly this incarnation's outcome.
750
776
  */
751
- const PENDING_JOIN_SELECT_SQL = `
752
- select R.Id, R.Invitation, R.Disclosure, R.RequestedAt, R.ExpiresAt, R.StampId,
753
- S.RecordedAt as JoinedAt, S.StrandId, S.MembershipInvite,
754
- F.RecordedAt as FailedAt, F.Code, F.Reason
755
- from CadreControl.JoinRequest R
756
- left join CadreControl.JoinSuccess S on S.RequestStampId = R.StampId
757
- left join CadreControl.JoinFailure F on F.RequestStampId = R.StampId
777
+ const PENDING_JOIN_SELECT_SQL = `
778
+ select R.Id, R.Invitation, R.Disclosure, R.RequestedAt, R.ExpiresAt, R.StampId,
779
+ S.RecordedAt as JoinedAt, S.StrandId, S.MembershipInvite,
780
+ F.RecordedAt as FailedAt, F.Code, F.Reason
781
+ from CadreControl.JoinRequest R
782
+ left join CadreControl.JoinSuccess S on S.RequestStampId = R.StampId
783
+ left join CadreControl.JoinFailure F on F.RequestStampId = R.StampId
758
784
  `;
759
785
  /** A {@link PENDING_JOIN_SELECT_SQL} row as read. */
760
786
  function pendingJoinOf(row) {
@@ -908,6 +934,10 @@ export class ControlDatabase {
908
934
  default_key_network: 'libp2p',
909
935
  default_network_name: networkName,
910
936
  enable_cache: true,
937
+ // Every member holds every control block (`CONTROL_REPLICATION_BREADTH`), so a control read
938
+ // answers from this machine's own replica. Left unset, the `network` transactor would price
939
+ // these tables as `distributed`.
940
+ cost_profile: 'localDisk',
911
941
  });
912
942
  // Register vtables and functions manually since we need access to collectionFactory
913
943
  for (const vtable of pluginResult.vtables) {
@@ -1070,15 +1100,22 @@ export class ControlDatabase {
1070
1100
  // `catalog-only` kinds, from Optimystic 1.16.0): the plugin's `alterTable` arms (add column,
1071
1101
  // drop column, add and drop CHECK) and the tag change write the table's catalog record under
1072
1102
  // the batch's per-statement checkpoint, so a step that throws withdraws its own write, and a
1073
- // batch whose commit fails is discarded whole and the tables it wrote re-persist on their next
1074
- // touch. A change the record already holds — another machine migrated first — is adopted with
1075
- // nothing written, and an undo of an adopted change touches this machine's catalog only. The
1076
- // one arm Quereus marks irreversible is `drop column`: once it has run, a later failure
1077
- // unwinds nothing (the apply reports the schema as partially migrated), the plugin's
1078
- // `endSchemaBatch` commits the steps that landed — or, when that commit fails, marks their
1079
- // tables to re-persist on next touch — and the retry's diff runs only the steps still
1080
- // missing. No row is lost either way: rows keep a dropped column's field until they are
1081
- // rewritten, and nothing reads it.
1103
+ // batch whose commit fails is discarded whole and undone in a second batch (Quereus 4.25.0), so
1104
+ // the retry plans the whole change again. A change the record already holds — another machine
1105
+ // migrated first — is adopted with nothing written, and an undo of an adopted change touches
1106
+ // this machine's catalog only. The one arm Quereus marks irreversible is `drop column`: once it
1107
+ // has run, a later failure unwinds nothing (the apply reports the schema as partially
1108
+ // migrated), the plugin's `endSchemaBatch` commits the steps that landed — or, when that commit
1109
+ // fails, marks their tables to re-persist on next touch — and the retry's diff runs only the
1110
+ // steps still missing. No row is lost either way: rows keep a dropped column's field until they
1111
+ // are rewritten, and nothing reads it.
1112
+ //
1113
+ // NOTE: a cohort that keeps refusing the commit ends the retries with a thrown error and fails
1114
+ // the start, and this start does not wait. A machine whose siblings are offline does not reach
1115
+ // that: the bring-up quiet period holds every connection off, so the apply commits alone
1116
+ // (measured 2026-11-03, a v3 store with one sibling at an unrouted address migrated to v4 in a
1117
+ // 117 ms start). If a start ever fails here on a refused commit, make it wait, as the `App`
1118
+ // apply does (`applyAppSchemaOrDefer`).
1082
1119
  //
1083
1120
  // Only the "cohort did not answer, nothing committed" class is retried; the classifier
1084
1121
  // vetoes indeterminate commits and does not match `Missing block`, which is a durable
@@ -1461,8 +1498,8 @@ export class ControlDatabase {
1461
1498
  * such collections, and nothing creates them later: the start-time schema apply runs on every
1462
1499
  * machine, possibly alone, where committing one would be exactly the fork genesis avoids.
1463
1500
  *
1464
- * NOTE: one `sync()` per collection, in sequence: 32 collections for today's schema (17 tables,
1465
- * 3 indexes, 12 `unique` columns). Measured 2026-10-20 on a lone `CadreNode` over the network
1501
+ * NOTE: one `sync()` per collection, in sequence: 35 collections for today's schema (19 tables,
1502
+ * 3 indexes, 13 `unique` columns), 32 when this was measured. Measured 2026-10-20 on a lone `CadreNode` over the network
1466
1503
  * transactor (started, then `ensureOwnerKey` alone, 3 runs each): 64–105 ms in memory and
1467
1504
  * 750–820 ms on `FileRawStorage`, about 25 ms per collection on disk, roughly 1/75 of the edge
1468
1505
  * node's 60 s `DEFAULT_OWNER_GENESIS_TIMEOUT_MS`. Under the whole cadre-core suite's load (151
@@ -1578,15 +1615,25 @@ export class ControlDatabase {
1578
1615
  async queryCadrePeers(retry = true) {
1579
1616
  this.ensureInitialized();
1580
1617
  const revoked = await this.queryRevokedStamps('CadrePeer', retry);
1581
- const rows = [];
1582
- for (const row of await this.readMembershipRows(this.cadrePeerView, retry)) {
1583
- const peer = cadrePeerRowOf(row);
1584
- if (peer.stampId !== null && revoked.has(peer.stampId)) {
1585
- continue;
1586
- }
1587
- rows.push(peer);
1588
- }
1589
- return rows;
1618
+ return liveCadrePeerRows(await this.readMembershipRows(this.cadrePeerView, retry), revoked);
1619
+ }
1620
+ /**
1621
+ * The live `CadrePeer` rows as {@link queryCadrePeers} judges them, and every `Revocation`
1622
+ * tombstone, both read through storage now rather than served from the membership views.
1623
+ * For the one reader that races the views' lag: the membership reconciler's sibling binding
1624
+ * (`strand-party-peers.ts`), which must not bind a machine under a key because the removal
1625
+ * that tombstoned it reached storage with no change event, which the view would serve for
1626
+ * up to `MEMBERSHIP_VIEW_MAX_AGE_MS`. The chain tables stay on the views: a chain row missing
1627
+ * makes a machine untrusted, which that reader ignores rather than acts on. One read of each
1628
+ * table; the tombstones filter the rows and are returned, so the caller joins them once.
1629
+ */
1630
+ async queryMachineRowsFresh() {
1631
+ this.ensureInitialized();
1632
+ const tombstones = (await this.readRevocationRowsOrNone(true, 'fresh'))
1633
+ .filter((row) => row.TableName !== REVOCATION_LEDGER_MARKER.tableName)
1634
+ .map(revocationRowOf);
1635
+ const revoked = new Set(tombstones.filter((tombstone) => tombstone.tableName === 'CadrePeer').map((tombstone) => tombstone.stampId));
1636
+ return { peers: liveCadrePeerRows(await this.cadrePeerView.readThrough(true), revoked), tombstones };
1590
1637
  }
1591
1638
  /**
1592
1639
  * The cadre's peers as a seed or a redemption reply carries them: every live `CadrePeer`
@@ -1677,6 +1724,10 @@ export class ControlDatabase {
1677
1724
  queryStrandPartyKeyStampId(strandId) {
1678
1725
  return this.queryStampId('StrandPartyKey', strandId);
1679
1726
  }
1727
+ /** `PendingStrandPartyKey` stamp nonce, retired or not — bound into {@link deletePendingStrandPartyKey}'s remove digest. */
1728
+ queryPendingStrandPartyKeyStampId(strandId) {
1729
+ return this.queryStampId('PendingStrandPartyKey', strandId);
1730
+ }
1680
1731
  /** `JoinedStrand` stamp nonce — bound into {@link deleteJoinedStrand}'s remove digest. */
1681
1732
  queryJoinedStrandStampId(strandId) {
1682
1733
  return this.queryStampId('JoinedStrand', strandId);
@@ -1695,6 +1746,85 @@ export class ControlDatabase {
1695
1746
  }
1696
1747
  return null;
1697
1748
  }
1749
+ /**
1750
+ * The key this party is moving to in one strand, or null when no rotation is pending there. The
1751
+ * key itself rides sealed (`sealedKey`); `CadreNode` opens it under this machine's identity key
1752
+ * before driving the rotation, and a reader that only asks whether a rotation is pending never
1753
+ * needs to.
1754
+ *
1755
+ * A row whose stamp is retired reads as absent, as {@link queryPendingJoin} treats one: the
1756
+ * table has no reap branch, so a node that received the tombstone without the delete keeps the
1757
+ * physical row, and a replayed approval can re-seat a removed row on a node that has not seen
1758
+ * its tombstone. Either way a key that was replaced, perhaps because a removed machine had it,
1759
+ * must not read as the key to move to.
1760
+ */
1761
+ async queryPendingStrandPartyKey(strandId) {
1762
+ this.ensureInitialized();
1763
+ const revoked = await this.queryRevokedStamps('PendingStrandPartyKey');
1764
+ const rows = await this.readRows(PENDING_PARTY_KEY_SELECT, [strandId], 'pending-strand-party-key');
1765
+ const row = rows[0];
1766
+ if (row === undefined || revoked.has(row.StampId)) {
1767
+ return null;
1768
+ }
1769
+ return pendingPartyKeyOfRow(row);
1770
+ }
1771
+ /** Every {@link queryPendingStrandPartyKey} row at once, by strand id, a retired stamp hidden the same way. */
1772
+ async queryPendingStrandPartyKeys() {
1773
+ this.ensureInitialized();
1774
+ const revoked = await this.queryRevokedStamps('PendingStrandPartyKey');
1775
+ const rows = await this.readRows(`select Id, ${PENDING_PARTY_KEY_COLUMNS} from CadreControl.PendingStrandPartyKey`, undefined, 'pending-strand-party-keys');
1776
+ const pending = new Map();
1777
+ for (const row of rows) {
1778
+ if (!revoked.has(row.StampId)) {
1779
+ pending.set(row.Id, pendingPartyKeyOfRow(row));
1780
+ }
1781
+ }
1782
+ return pending;
1783
+ }
1784
+ /**
1785
+ * Every machine's signed statement of its peer id in one strand. A row whose signature does
1786
+ * not verify against the key its `PeerId` derives from is dropped ({@link verifyStrandPeerRow}).
1787
+ * Which rows are live machines and which removed ones is the caller's question.
1788
+ *
1789
+ * NOTE: on a party whose store migrated to this table, nothing holds its collection until a
1790
+ * machine writes it, so a read asks the cohort to prove it empty and can fail while the other
1791
+ * machines are offline (`backlog/feat-strand-tables-added-by-a-later-schema-get-their-collection`).
1792
+ * A failure propagates rather than reading as "no rows": decide that with the caller that would
1793
+ * act on an empty list.
1794
+ */
1795
+ async queryStrandPeers(strandId) {
1796
+ this.ensureInitialized();
1797
+ const rows = await this.readStrandPeerRows(strandId, true);
1798
+ return rows.filter((row) => {
1799
+ const verified = verifyStrandPeerRow(this.config.partyId, row);
1800
+ if (!verified) {
1801
+ log('StrandPeer row dropped: signature does not verify for machine %s in strand %s', row.peerId, strandId);
1802
+ }
1803
+ return verified;
1804
+ });
1805
+ }
1806
+ /**
1807
+ * The raw `StrandPeer` rows of one strand. Filters on the leading primary-key column only and
1808
+ * compares again here: the optimystic module serves an equality on the whole composite key
1809
+ * with a single point lookup that can miss a row on a networked table, and declines a partial
1810
+ * match, which then scans (`scanMemberPeers` in `strand-membership-writer.ts`).
1811
+ * `retry: false` inside a locked write body.
1812
+ *
1813
+ * NOTE: because the predicate is not pushed down, this walks every strand's rows per call. Fine
1814
+ * at party scale; if a party ever runs many strands on many machines, this wants a reliable
1815
+ * composite-key seek rather than a secondary index, which would restore the seek dependency.
1816
+ */
1817
+ async readStrandPeerRows(strandId, retry) {
1818
+ const rows = await this.readRows('select StrandId, PeerId, StrandPeerId, Sig from CadreControl.StrandPeer where StrandId = ?', [strandId], 'strand-peers', retry);
1819
+ return rows
1820
+ .filter((row) => row.StrandId === strandId)
1821
+ .map((row) => ({
1822
+ strandId,
1823
+ peerId: row.PeerId,
1824
+ strandPeerId: row.StrandPeerId,
1825
+ sig: row.Sig,
1826
+ }));
1827
+ }
1698
1828
  /** `ValidationKey` stamp nonce — bound into {@link deleteValidationKey}'s remove digest. */
1699
1829
  queryValidationKeyStampId(key) {
1700
1830
  return this.queryStampId('ValidationKey', key);
@@ -1771,9 +1901,11 @@ export class ControlDatabase {
1771
1901
  * admission gate's 2 s deadline (`ADMISSION_DECISION_TIMEOUT_MS`), skip the retry for this
1772
1902
  * read when the first attempt fails `cohort-unreachable`.
1773
1903
  */
1774
- async readRevocationRowsOrNone(retry) {
1904
+ async readRevocationRowsOrNone(retry, served = 'view') {
1775
1905
  try {
1776
- return await this.readMembershipRows(this.revocationView, retry);
1906
+ return served === 'fresh'
1907
+ ? await this.revocationView.readThrough(retry)
1908
+ : await this.readMembershipRows(this.revocationView, retry);
1777
1909
  }
1778
1910
  catch (error) {
1779
1911
  if (!isCohortUnreachableRead(error)) {
@@ -1912,11 +2044,11 @@ export class ControlDatabase {
1912
2044
  }
1913
2045
  const record = sign(current);
1914
2046
  // Bare `exec` — inside the non-re-entrant write lock (see insertCadrePeer).
1915
- await this.db.exec(`
1916
- update CadreControl.CadrePeer
1917
- with context OwnerKey = null, Signature = ?
1918
- set Multiaddr = ?, UpdatedAt = ?, Profile = ?, Sig = ?
1919
- where PeerId = ?
2047
+ await this.db.exec(`
2048
+ update CadreControl.CadrePeer
2049
+ with context OwnerKey = null, Signature = ?
2050
+ set Multiaddr = ?, UpdatedAt = ?, Profile = ?, Sig = ?
2051
+ where PeerId = ?
1920
2052
  `, [record.sig, record.addrs.join(','), record.updatedAt, record.profile, record.sig, peerId]);
1921
2053
  return record;
1922
2054
  }, LOST_UPDATE_RETRY_POLICY, 'self-record-update');
@@ -1968,11 +2100,11 @@ export class ControlDatabase {
1968
2100
  */
1969
2101
  async updateSelfDeviceToken(record) {
1970
2102
  this.ensureInitialized();
1971
- await this.execWrite(`
1972
- update CadreControl.DeviceToken
1973
- with context OwnerKey = null, Signature = ?
1974
- set Platform = ?, Token = ?, UpdatedAt = ?, Sig = ?
1975
- where PeerId = ?
2103
+ await this.execWrite(`
2104
+ update CadreControl.DeviceToken
2105
+ with context OwnerKey = null, Signature = ?
2106
+ set Platform = ?, Token = ?, UpdatedAt = ?, Sig = ?
2107
+ where PeerId = ?
1976
2108
  `, [record.sig, record.platform, record.token, record.updatedAt, record.sig, record.peerId], 'device-token-update');
1977
2109
  log('Self device token updated: %s (platform=%s, updatedAt=%d)', record.peerId, record.platform, record.updatedAt);
1978
2110
  }
@@ -1995,10 +2127,10 @@ export class ControlDatabase {
1995
2127
  // not-null/unique anti-replay constraint — the StampId is a real column value, not the
1996
2128
  // optimystic `StampId()` SQL function.
1997
2129
  const stampId = generateStampId(this.config.libp2pNode.peerId.toString());
1998
- await this.execWrite(`
1999
- insert into CadreControl.OwnerKey (Key, Label, StampId)
2000
- with context OwnerKey = null, Signature = null
2001
- values (?, ?, ?)
2130
+ await this.execWrite(`
2131
+ insert into CadreControl.OwnerKey (Key, Label, StampId)
2132
+ with context OwnerKey = null, Signature = null
2133
+ values (?, ?, ?)
2002
2134
  `, [key, storedLabel, stampId], 'owner-key-insert');
2003
2135
  log('Owner key inserted');
2004
2136
  }
@@ -2065,10 +2197,10 @@ export class ControlDatabase {
2065
2197
  * NOT re-entrant.
2066
2198
  */
2067
2199
  async execOwnerKeyVouchedInsert(row, ownerKey, signature) {
2068
- await this.db.exec(`
2069
- insert into CadreControl.OwnerKey (Key, Label, StampId, VouchOwner, VouchSig)
2070
- with context OwnerKey = ?, Signature = ?
2071
- values (?, ?, ?, ?, ?)
2200
+ await this.db.exec(`
2201
+ insert into CadreControl.OwnerKey (Key, Label, StampId, VouchOwner, VouchSig)
2202
+ with context OwnerKey = ?, Signature = ?
2203
+ values (?, ?, ?, ?, ?)
2072
2204
  `, [ownerKey, signature, row.key, row.label, row.stampId, ownerKey, signature]);
2073
2205
  }
2074
2206
  /**
@@ -2150,14 +2282,28 @@ export class ControlDatabase {
2150
2282
  * `DeviceToken` row when it has one, each with the `Revocation` tombstone retiring its stamp
2151
2283
  * ({@link deleteGuardedRow}'s statement pair, composed bare as {@link deleteStrandAndPartyKey}
2152
2284
  * composes it), plus a withdrawal tombstone for every `CadreInvite` in `target.inviteKeys`
2153
- * that is still live here ({@link withdrawCadreInvite}'s body). One transaction so no reader
2154
- * sees the machine half removed: a row gone but its push token resolvable, or an invitation
2155
- * it could redeem again still open. Owner keys are never touched: they are the person's, and
2156
- * removing one is {@link deleteOwnerKey}.
2285
+ * that is still live here ({@link withdrawCadreInvite}'s body), plus, for every strand in
2286
+ * `target.pendingPartyKeys`, a `PendingStrandPartyKey` row holding the key the party moves
2287
+ * to there (`strand-party-key-rotation.ts` moves it). One transaction so no reader sees the
2288
+ * machine half removed: a row gone but its push token resolvable, an invitation it could
2289
+ * redeem again still open, or its tombstone without the intent to rotate, which the strand
2290
+ * membership reconciler reads as "no rotation" and would then clear the binding the rotation
2291
+ * means to orphan (`strand-membership-reconciler.ts` → "Binding the party's other machines").
2292
+ * Owner keys are never touched: they are the person's, and removing one is
2293
+ * {@link deleteOwnerKey}.
2294
+ *
2295
+ * A strand that already holds a pending row gets it replaced: the stored row is retired
2296
+ * ({@link signPendingKeyRetirement}) and the fresh row's `Superseded` carries the replaced
2297
+ * key's public half after the stored row's own list, because the replaced key may already
2298
+ * have reached the machine being removed, and a seat it holds must be revoked. A stored row
2299
+ * whose stamp is already retired (held without its delete) is replaced the same way, with
2300
+ * no second tombstone. The caller seals each fresh key to the machines that remain
2301
+ * ({@link PendingPartyKeyEntry}); this writer never sees a pending key in the clear.
2157
2302
  *
2158
2303
  * Through {@link mutateCadrePeer}, the membership hub. Every stamp is read inside the locked
2159
2304
  * body, and a row whose stamp is already retired (held without its delete) is skipped rather
2160
- * than tombstoned twice. Nothing to remove writes nothing and returns all false.
2305
+ * than tombstoned twice. Nothing to remove writes nothing, pending rows included, and returns
2306
+ * all false: the machine was removed elsewhere, and that removal wrote the rotation rows.
2161
2307
  *
2162
2308
  * Opted into {@link LOST_UPDATE_RETRY_POLICY} for the reason on {@link deleteCadrePeer}: every
2163
2309
  * stamp and signature is minted inside the body, and the invitation keys come from the
@@ -2166,17 +2312,19 @@ export class ControlDatabase {
2166
2312
  * before). A lost update after a sibling tree of the transaction already synced arrives as a
2167
2313
  * partial commit and stays declined.
2168
2314
  *
2169
- * The caller decides which invitations the machine could use, from its plan
2170
- * (`CadreNode.planMachineRemoval`).
2315
+ * The caller decides which invitations the machine could use and which strands to rotate,
2316
+ * from its plan (`CadreNode.planMachineRemoval`).
2171
2317
  */
2172
2318
  async removeMachine(target, ownerKey, signMessage) {
2173
2319
  return await this.mutateCadrePeer('machine-remove', async () => {
2174
- const removals = await this.signMachineRemovals(target.peerId, signMessage);
2320
+ const retired = await this.retiredStampsByTable();
2321
+ const removals = await this.signMachineRemovals(target.peerId, retired, signMessage);
2175
2322
  const withdrawals = await this.signWithdrawals('CadreInvite', target.inviteKeys, signMessage);
2176
2323
  if (removals.length === 0 && withdrawals.length === 0) {
2177
2324
  log('removeMachine: nothing live names %s here (already removed)', target.peerId);
2178
2325
  return { removedPeer: false, removedDeviceToken: false, withdrawnInvitations: [] };
2179
2326
  }
2327
+ const rotations = await this.signPendingPartyKeyReplacements(target.pendingPartyKeys ?? [], retired('PendingStrandPartyKey'), ownerKey, signMessage);
2180
2328
  await this.inTransaction('remove machine', async () => {
2181
2329
  for (const removal of removals) {
2182
2330
  await this.execGuardedRemoval(removal, ownerKey);
@@ -2184,15 +2332,24 @@ export class ControlDatabase {
2184
2332
  for (const withdrawal of withdrawals) {
2185
2333
  await this.execTombstone(withdrawal.ref, withdrawal.signature, ownerKey);
2186
2334
  }
2335
+ for (const rotation of rotations) {
2336
+ if (rotation.retirement !== null) {
2337
+ await this.execRowRetirement(rotation.retirement, ownerKey);
2338
+ }
2339
+ await this.db.exec(rotation.insert.sql, rotation.insert.params);
2340
+ }
2187
2341
  });
2188
2342
  const removed = new Set(removals.map((removal) => removal.ref.tableName));
2189
- log('Machine %s removed: %s; %d invitation(s) withdrawn', target.peerId, [...removed].join(', ') || 'no row', withdrawals.length);
2343
+ log('Machine %s removed: %s; %d invitation(s) withdrawn; %d strand party key rotation(s) recorded', target.peerId, [...removed].join(', ') || 'no row', withdrawals.length, rotations.length);
2190
2344
  for (const removal of removals) {
2191
2345
  this.notifyGuardedDelete(removal.ref);
2192
2346
  }
2193
2347
  for (const withdrawal of withdrawals) {
2194
2348
  this.notifyGuardedDelete(withdrawal.ref);
2195
2349
  }
2350
+ for (const rotation of rotations) {
2351
+ this.notifyRowRetirement(rotation.retirement);
2352
+ }
2196
2353
  return {
2197
2354
  removedPeer: removed.has('CadrePeer'),
2198
2355
  removedDeviceToken: removed.has('DeviceToken'),
@@ -2201,19 +2358,24 @@ export class ControlDatabase {
2201
2358
  }, LOST_UPDATE_RETRY_POLICY);
2202
2359
  }
2203
2360
  /**
2204
- * The guarded removals {@link removeMachine} runs, signed over each row's current stamp:
2205
- * the `CadrePeer` row and the `DeviceToken` row, each when present. Inside the locked body
2206
- * (every read `retry: false`); one `Revocation` scan serves the retired-stamp check for both
2207
- * tables.
2361
+ * Every retired stamp held here, by table, from ONE `Revocation` scan inside a locked body
2362
+ * (`retry: false`), for a writer that checks several rows' stamps before one transaction.
2208
2363
  */
2209
- async signMachineRemovals(peerId, signMessage) {
2364
+ async retiredStampsByTable() {
2210
2365
  const retiredByTable = new Map();
2211
2366
  for (const tombstone of await this.queryRevocations(false)) {
2212
2367
  const stamps = retiredByTable.get(tombstone.tableName) ?? new Set();
2213
2368
  stamps.add(tombstone.stampId);
2214
2369
  retiredByTable.set(tombstone.tableName, stamps);
2215
2370
  }
2216
- const retired = (table) => retiredByTable.get(table) ?? new Set();
2371
+ return (table) => retiredByTable.get(table) ?? new Set();
2372
+ }
2373
+ /**
2374
+ * The guarded removals {@link removeMachine} runs, signed over each row's current stamp:
2375
+ * the `CadrePeer` row and the `DeviceToken` row, each when present. Inside the locked body
2376
+ * (every read `retry: false`); `retired` is the body's one `Revocation` scan.
2377
+ */
2378
+ async signMachineRemovals(peerId, retired, signMessage) {
2217
2379
  const liveStamp = async (table, keyValue) => {
2218
2380
  const stampId = await this.queryStampId(table, keyValue, false);
2219
2381
  return stampId !== null && !retired(table).has(stampId) ? stampId : null;
@@ -2227,6 +2389,75 @@ export class ControlDatabase {
2227
2389
  }
2228
2390
  return removals;
2229
2391
  }
2392
+ /**
2393
+ * The `PendingStrandPartyKey` writes {@link removeMachine} runs for `entries`: per strand, the
2394
+ * retirement of the row it already holds, if any, and the insert of the fresh key, whose
2395
+ * `Superseded` extends the stored row's list with the stored key's public half, read from the
2396
+ * row in the clear, so a remover that cannot open the stored row still replaces it. Signed
2397
+ * inside the locked body, before the transaction.
2398
+ *
2399
+ * NOTE: two owners removing different machines while partitioned each seal their fresh key to
2400
+ * the machine the other removed, and the row that survives the merge names it as a recipient;
2401
+ * the removed machine is then cut by the strand's rows alone, as before sealing. Revisit if a
2402
+ * partitioned double removal is seen to hand a removed machine a key it uses.
2403
+ */
2404
+ async signPendingPartyKeyReplacements(entries, retiredPendingStamps, ownerKey, signMessage) {
2405
+ const replacements = [];
2406
+ for (const entry of entries) {
2407
+ const stored = await this.readStoredPendingPartyKey(entry.strandId, retiredPendingStamps);
2408
+ const superseded = stored === null ? [] : [...new Set([...stored.superseded, stored.publicKey])];
2409
+ replacements.push({
2410
+ retirement: stored === null ? null : await this.signPendingKeyRetirement(entry.strandId, stored, signMessage),
2411
+ insert: await this.signPendingStrandPartyKeyInsert(entry.strandId, entry, superseded, ownerKey, signMessage),
2412
+ });
2413
+ }
2414
+ return replacements;
2415
+ }
2416
+ /**
2417
+ * The `PendingStrandPartyKey` row physically stored for `strandId`, retired or not, or null.
2418
+ * For a locked write body (`retry: false`): the public reader
2419
+ * ({@link queryPendingStrandPartyKey}) hides a retired row, and a writer replacing the row has
2420
+ * to remove the physical one either way.
2421
+ */
2422
+ async readStoredPendingPartyKey(strandId, retiredPendingStamps) {
2423
+ const rows = await this.readRows(PENDING_PARTY_KEY_SELECT, [strandId], 'pending-strand-party-key-stored', false);
2424
+ const row = rows[0];
2425
+ if (row === undefined) {
2426
+ return null;
2427
+ }
2428
+ const pending = pendingPartyKeyOfRow(row);
2429
+ return { ...pending, retired: retiredPendingStamps.has(pending.stampId) };
2430
+ }
2431
+ /**
2432
+ * The owner-signed removal of a stored `PendingStrandPartyKey` row ({@link RowRetirement}): with
2433
+ * its tombstone when the row is live, as every guarded removal; without one when its stamp is
2434
+ * already retired (the tombstone reached this node without the delete; the table has no reap
2435
+ * branch, so a second tombstone would collide on `Revocation`'s key and leave the row).
2436
+ */
2437
+ async signPendingKeyRetirement(strandId, stored, signMessage) {
2438
+ return {
2439
+ removal: await signGuardedRemoval(this.config.partyId, 'PendingStrandPartyKey', strandId, stored.stampId, signMessage),
2440
+ filesTombstone: !stored.retired,
2441
+ };
2442
+ }
2443
+ /**
2444
+ * Run one {@link RowRetirement} inside the caller's transaction: the guarded statement pair,
2445
+ * or the signed delete alone when the tombstone already exists.
2446
+ */
2447
+ async execRowRetirement(retirement, ownerKey) {
2448
+ if (retirement.filesTombstone) {
2449
+ await this.execGuardedRemoval(retirement.removal, ownerKey);
2450
+ }
2451
+ else {
2452
+ await this.execSignedDelete(retirement.removal, ownerKey);
2453
+ }
2454
+ }
2455
+ /** Fire the guarded-delete listener for a {@link RowRetirement} that filed a tombstone; a null or tombstone-less one fires nothing. */
2456
+ notifyRowRetirement(retirement) {
2457
+ if (retirement?.filesTombstone) {
2458
+ this.notifyGuardedDelete(retirement.removal.ref);
2459
+ }
2460
+ }
2230
2461
  /**
2231
2462
  * Insert a strand into the control database using an owner signature.
2232
2463
  *
@@ -2267,10 +2498,10 @@ export class ControlDatabase {
2267
2498
  // StampId is a real, unique column (single-use anti-replay), no longer a context value.
2268
2499
  // FounderOwnerKey must equal the signing owner or the constraint rejects the row.
2269
2500
  return {
2270
- sql: `
2271
- insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId, FounderOwnerKey, FounderPeerId)
2272
- with context OwnerKey = ?, Signature = ?
2273
- values (?, ?, ?, ?, ?, ?)
2501
+ sql: `
2502
+ insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId, FounderOwnerKey, FounderPeerId)
2503
+ with context OwnerKey = ?, Signature = ?
2504
+ values (?, ?, ?, ?, ?, ?)
2274
2505
  `,
2275
2506
  params: [ownerKey, signature, strandId, type, memberPrivateKey ?? null, stampId, ownerKey, peerId],
2276
2507
  };
@@ -2365,21 +2596,30 @@ export class ControlDatabase {
2365
2596
  return false;
2366
2597
  }
2367
2598
  const partyKeyStamp = await this.queryStampId('StrandPartyKey', strandId, false);
2599
+ // A rotation still pending for the strand goes with the party key: the row holds a private
2600
+ // key for a strand the party no longer has, nothing else removes it, and the table has no
2601
+ // reap branch (`strand-party-key-rotation.ts`).
2602
+ const pending = await this.readStoredPendingPartyKey(strandId, await this.queryRevokedStamps('PendingStrandPartyKey', false));
2368
2603
  const strandRemoval = await signGuardedRemoval(this.config.partyId, 'Strand', strandId, strandStamp, signMessage);
2369
2604
  const partyKeyRemoval = partyKeyStamp === null
2370
2605
  ? null
2371
2606
  : await signGuardedRemoval(this.config.partyId, 'StrandPartyKey', strandId, partyKeyStamp, signMessage);
2607
+ const pendingRetirement = pending === null ? null : await this.signPendingKeyRetirement(strandId, pending, signMessage);
2372
2608
  await this.inTransaction('delete Strand', async () => {
2373
2609
  await this.execGuardedRemoval(strandRemoval, ownerKey);
2374
2610
  if (partyKeyRemoval !== null) {
2375
2611
  await this.execGuardedRemoval(partyKeyRemoval, ownerKey);
2376
2612
  }
2613
+ if (pendingRetirement !== null) {
2614
+ await this.execRowRetirement(pendingRetirement, ownerKey);
2615
+ }
2377
2616
  });
2378
- log('Strand deleted: %s (stamp retired%s)', strandId, partyKeyRemoval === null ? '' : '; party key deleted, stamp retired');
2617
+ log('Strand deleted: %s (stamp retired%s%s)', strandId, partyKeyRemoval === null ? '' : '; party key deleted, stamp retired', pendingRetirement === null ? '' : '; pending party key deleted');
2379
2618
  this.notifyGuardedDelete(strandRemoval.ref);
2380
2619
  if (partyKeyRemoval !== null) {
2381
2620
  this.notifyGuardedDelete(partyKeyRemoval.ref);
2382
2621
  }
2622
+ this.notifyRowRetirement(pendingRetirement);
2383
2623
  return true;
2384
2624
  }
2385
2625
  /**
@@ -2413,10 +2653,10 @@ export class ControlDatabase {
2413
2653
  const message = buildAuthorizationMessage('CadreControl.StrandPartyKey', 'add', this.config.partyId, [strandId, privateKey, stampId]);
2414
2654
  const signature = await signMessage(message);
2415
2655
  return {
2416
- sql: `
2417
- insert into CadreControl.StrandPartyKey (Id, PrivateKey, StampId)
2418
- with context OwnerKey = ?, Signature = ?
2419
- values (?, ?, ?)
2656
+ sql: `
2657
+ insert into CadreControl.StrandPartyKey (Id, PrivateKey, StampId)
2658
+ with context OwnerKey = ?, Signature = ?
2659
+ values (?, ?, ?)
2420
2660
  `,
2421
2661
  params: [ownerKey, signature, strandId, privateKey, stampId],
2422
2662
  };
@@ -2436,6 +2676,165 @@ export class ControlDatabase {
2436
2676
  deleteStrandPartyKey(strandId, ownerKey, signMessage) {
2437
2677
  return this.lockedWithRetry(() => this.deleteGuardedRow('StrandPartyKey', strandId, ownerKey, signMessage), {}, 'strand-party-key-delete');
2438
2678
  }
2679
+ /**
2680
+ * Insert the key this party is moving to in one strand (`PendingStrandPartyKey` row), under an
2681
+ * owner signature, before the strand is touched.
2682
+ *
2683
+ * @param strandId - The strand whose party key is being replaced.
2684
+ * @param key - The new key: its public half (base64url) and its private half sealed to the
2685
+ * machines that may drive the move (`sealPartyKey` in `sealed-party-key.ts`).
2686
+ * @param superseded - Public keys (base64url) of earlier pending keys this row replaces.
2687
+ * @param ownerKey - Public key of the authorizing owner.
2688
+ * @param signMessage - Signs the raw message bytes with that owner's private key.
2689
+ */
2690
+ async insertPendingStrandPartyKey(strandId, key, superseded, ownerKey, signMessage) {
2691
+ this.ensureInitialized();
2692
+ const insert = await this.signPendingStrandPartyKeyInsert(strandId, key, superseded, ownerKey, signMessage);
2693
+ await this.execWrite(insert.sql, insert.params, 'pending-strand-party-key-insert');
2694
+ log('Pending strand party key inserted for strand: %s', strandId);
2695
+ }
2696
+ /**
2697
+ * The stamped, owner-signed `PendingStrandPartyKey` insert. Apart from
2698
+ * {@link insertPendingStrandPartyKey} so a writer can run it inside a larger transaction, as
2699
+ * {@link signStrandPartyKeyInsert} is. The public half and each superseded key must be a
2700
+ * well-formed public key: `Superseded` is comma-joined, base64url is what keeps the join
2701
+ * reversible, and the public half is what a later removal copies into it.
2702
+ */
2703
+ async signPendingStrandPartyKeyInsert(strandId, key, superseded, ownerKey, signMessage) {
2704
+ const fields = {
2705
+ strandId,
2706
+ publicKey: requireEd25519PublicKeyB64(key.publicKey, 'pending party key'),
2707
+ sealedKey: key.sealedKey,
2708
+ superseded: superseded.length === 0
2709
+ ? null
2710
+ : superseded.map((key) => requireEd25519PublicKeyB64(key, 'superseded party key')).join(','),
2711
+ stampId: generateStampId(this.config.libp2pNode.peerId.toString()),
2712
+ };
2713
+ const message = buildAuthorizationMessage('CadreControl.PendingStrandPartyKey', 'add', this.config.partyId, pendingStrandPartyKeyRowFields(fields));
2714
+ return {
2715
+ sql: `
2716
+ insert into CadreControl.PendingStrandPartyKey (Id, PublicKey, SealedKey, Superseded, StampId)
2717
+ with context OwnerKey = ?, Signature = ?
2718
+ values (?, ?, ?, ?, ?)
2719
+ `,
2720
+ params: [ownerKey, await signMessage(message), fields.strandId, fields.publicKey, fields.sealedKey, fields.superseded, fields.stampId],
2721
+ };
2722
+ }
2723
+ /**
2724
+ * Owner-signed removal of one `PendingStrandPartyKey` row with its tombstone, as
2725
+ * {@link deleteStrandPartyKey}. A no-op when the row does not exist — `false` then, `true`
2726
+ * when a row was actually removed.
2727
+ */
2728
+ deletePendingStrandPartyKey(strandId, ownerKey, signMessage) {
2729
+ return this.lockedWithRetry(() => this.deleteGuardedRow('PendingStrandPartyKey', strandId, ownerKey, signMessage), {}, 'pending-strand-party-key-delete');
2730
+ }
2731
+ /**
2732
+ * Move this party's membership key in each of `entries`' strands from `oldKey` to `newKey` in
2733
+ * the control record, in ONE transaction: per strand, the `StrandPartyKey` row's guarded
2734
+ * removal and a fresh insert naming `newKey` ({@link revouchOwnerKey}'s delete-and-re-add
2735
+ * idiom, under the same owner approval), and the retirement of the strand's
2736
+ * `PendingStrandPartyKey` row when its public half is `newKey`'s. The last step of a party key
2737
+ * rotation (`strand-party-key-rotation.ts`): the strand's rows already name `newKey` as the
2738
+ * party's member, so a reader that sees the new control row sees a key that counts.
2739
+ *
2740
+ * NOTE: the swapped `StrandPartyKey` row holds `newKey` in the clear and replicates to every
2741
+ * party machine, as it always has, since a machine admitted later has to read it; the pending
2742
+ * row is sealed, this one is not. The removed machine could receive it only from a sibling that
2743
+ * holds the swap but not yet the tombstone, and the swap runs strictly after the removal
2744
+ * committed; the `machine-removal-rotates-party-key` scenario asserts the removed machine stays
2745
+ * on the old key. Sealing this row too would mean re-sealing it at every admission. Revisit if
2746
+ * that assertion fails or such a sibling is observed.
2747
+ *
2748
+ * Decided inside the locked body, per strand, over the rows as stored (every read
2749
+ * `retry: false`): a row already naming `newKey` was swapped by another machine's driver and
2750
+ * is skipped; a row naming neither key, or no row at all (the strand left the party), is left
2751
+ * alone with a log, since the driver re-plans from the rows it finds; a pending row naming
2752
+ * another key (a later removal replaced it) stays, because that key is the next rotation's,
2753
+ * which the driver runs from `newKey`. A stale `StrandPartyKey` or pending row (stamp already
2754
+ * retired) is removed without a second tombstone ({@link RowRetirement}).
2755
+ *
2756
+ * @returns The strand ids whose control row was swapped here.
2757
+ */
2758
+ async swapStrandPartyKeys(entries, ownerKey, signMessage) {
2759
+ this.ensureInitialized();
2760
+ return await this.lockedWithRetry(async () => {
2761
+ const retired = await this.retiredStampsByTable();
2762
+ const swaps = [];
2763
+ for (const entry of entries) {
2764
+ const stored = await this.readStoredPartyKey(entry.strandId);
2765
+ if (stored === null || stored.privateKey === entry.newKey || stored.privateKey !== entry.oldKey) {
2766
+ log('swapStrandPartyKeys: strand %s %s; nothing to swap', entry.strandId, stored === null ? 'has no party key row here' : stored.privateKey === entry.newKey ? 'already names the new key' : 'names a key this swap did not start from');
2767
+ continue;
2768
+ }
2769
+ const pending = await this.readStoredPendingPartyKey(entry.strandId, retired('PendingStrandPartyKey'));
2770
+ const newPublicKey = strandMemberKeyPair(entry.newKey).publicKeyB64;
2771
+ swaps.push({
2772
+ strandId: entry.strandId,
2773
+ keyRetirement: {
2774
+ removal: await signGuardedRemoval(this.config.partyId, 'StrandPartyKey', entry.strandId, stored.stampId, signMessage),
2775
+ filesTombstone: !retired('StrandPartyKey').has(stored.stampId),
2776
+ },
2777
+ insert: await this.signStrandPartyKeyInsert(entry.strandId, entry.newKey, ownerKey, signMessage),
2778
+ pendingRetirement: pending !== null && pending.publicKey === newPublicKey
2779
+ ? await this.signPendingKeyRetirement(entry.strandId, pending, signMessage)
2780
+ : null,
2781
+ });
2782
+ }
2783
+ if (swaps.length === 0) {
2784
+ return [];
2785
+ }
2786
+ // Bare `exec` for the insert: the lock is held, and `execWrite` would take it again.
2787
+ await this.inTransaction('swap strand party keys', async () => {
2788
+ for (const swap of swaps) {
2789
+ await this.execRowRetirement(swap.keyRetirement, ownerKey);
2790
+ await this.db.exec(swap.insert.sql, swap.insert.params);
2791
+ if (swap.pendingRetirement !== null) {
2792
+ await this.execRowRetirement(swap.pendingRetirement, ownerKey);
2793
+ }
2794
+ }
2795
+ });
2796
+ for (const swap of swaps) {
2797
+ log('Strand party key swapped for %s (old stamp retired%s)', swap.strandId, swap.pendingRetirement === null ? '' : '; pending row deleted');
2798
+ this.notifyRowRetirement(swap.keyRetirement);
2799
+ this.notifyRowRetirement(swap.pendingRetirement);
2800
+ }
2801
+ return swaps.map((swap) => swap.strandId);
2802
+ }, {}, 'strand-party-key-swap');
2803
+ }
2804
+ /** The `StrandPartyKey` row stored for `strandId` with its stamp, for a locked write body (`retry: false`), or null. */
2805
+ async readStoredPartyKey(strandId) {
2806
+ const rows = await this.readRows('select PrivateKey, StampId from CadreControl.StrandPartyKey where Id = ?', [strandId], 'strand-party-key-stored', false);
2807
+ const row = rows[0];
2808
+ return row === undefined ? null : { privateKey: row.PrivateKey, stampId: row.StampId };
2809
+ }
2810
+ /**
2811
+ * Publish this machine's peer id in one strand (`StrandPeer` row), signed by this machine's
2812
+ * own identity key. Insert-if-absent: `true` when a row was written, `false` when this machine
2813
+ * already has one for the strand. The schema refuses the insert while this node does not hold
2814
+ * the machine's `CadrePeer` row, and that rejection propagates.
2815
+ *
2816
+ * @param row - The strand, and this machine's peer id in it (`strandTransportKey`).
2817
+ * @param sign - Signs the raw message bytes with the identity key behind this machine's
2818
+ * control peer id. A callback for the reason {@link updateSelfPeerRecord} takes one: this
2819
+ * class holds no private key.
2820
+ */
2821
+ async insertStrandPeer(row, sign) {
2822
+ this.ensureInitialized();
2823
+ const peerId = this.config.libp2pNode.peerId.toString();
2824
+ const fields = { strandId: row.strandId, peerId, strandPeerId: row.strandPeerId };
2825
+ return this.lockedWithRetry(async () => {
2826
+ // retry: false — this guard runs inside the locked write body (see queryStampId's NOTE).
2827
+ const held = (await this.readStrandPeerRows(row.strandId, false)).find((stored) => stored.peerId === peerId);
2828
+ if (held !== undefined) {
2829
+ log('StrandPeer row already present for strand %s (names %s); insert skipped', row.strandId, held.strandPeerId);
2830
+ return false;
2831
+ }
2832
+ const sig = await sign(buildAuthorizationMessage('CadreControl.StrandPeer', 'add', this.config.partyId, strandPeerRowFields(fields)));
2833
+ // Bare `exec`: already inside the write lock, which is NOT re-entrant.
2834
+ await this.db.exec('insert into CadreControl.StrandPeer (StrandId, PeerId, StrandPeerId, Sig) values (?, ?, ?, ?)', [fields.strandId, fields.peerId, fields.strandPeerId, sig]);
2835
+ return true;
2836
+ }, {}, 'strand-peer-insert');
2837
+ }
2439
2838
  /**
2440
2839
  * Record, party-wide, a strand this party joined from another party (`JoinedStrand` row),
2441
2840
  * using an owner signature.
@@ -2456,10 +2855,10 @@ export class ControlDatabase {
2456
2855
  // Id, Type, MemberPrivateKey ('' when null), StampId.
2457
2856
  const message = buildAuthorizationMessage('CadreControl.JoinedStrand', 'add', this.config.partyId, [row.Id, row.Type, row.MemberPrivateKey ?? '', stampId]);
2458
2857
  const signature = await signMessage(message);
2459
- await this.execWrite(`
2460
- insert into CadreControl.JoinedStrand (Id, Type, MemberPrivateKey, StampId)
2461
- with context OwnerKey = ?, Signature = ?
2462
- values (?, ?, ?, ?)
2858
+ await this.execWrite(`
2859
+ insert into CadreControl.JoinedStrand (Id, Type, MemberPrivateKey, StampId)
2860
+ with context OwnerKey = ?, Signature = ?
2861
+ values (?, ?, ?, ?)
2463
2862
  `, [ownerKey, signature, row.Id, row.Type, row.MemberPrivateKey, stampId], 'joined-strand-insert');
2464
2863
  log('Joined strand inserted: %s', row.Id);
2465
2864
  }
@@ -2586,10 +2985,10 @@ export class ControlDatabase {
2586
2985
  }
2587
2986
  /** One unsigned outcome delete (see {@link deleteJoinOutcomes}; a failure's is also authorized by the join superseding it). */
2588
2987
  async deleteJoinOutcome(table, requestStampId) {
2589
- await this.db.exec(`
2590
- delete from CadreControl.${table}
2591
- with context OwnerKey = null, Signature = null
2592
- where RequestStampId = ?
2988
+ await this.db.exec(`
2989
+ delete from CadreControl.${table}
2990
+ with context OwnerKey = null, Signature = null
2991
+ where RequestStampId = ?
2593
2992
  `, [requestStampId]);
2594
2993
  }
2595
2994
  /**
@@ -2613,10 +3012,10 @@ export class ControlDatabase {
2613
3012
  // Field order MUST match the schema's ValidationKey `AuthorizedInsert` verify: Key, StampId.
2614
3013
  const message = buildAuthorizationMessage('CadreControl.ValidationKey', 'add', this.config.partyId, [key, stampId]);
2615
3014
  const signature = await signMessage(message);
2616
- await this.execWrite(`
2617
- insert into CadreControl.ValidationKey (Key, StampId)
2618
- with context OwnerKey = ?, Signature = ?
2619
- values (?, ?)
3015
+ await this.execWrite(`
3016
+ insert into CadreControl.ValidationKey (Key, StampId)
3017
+ with context OwnerKey = ?, Signature = ?
3018
+ values (?, ?)
2620
3019
  `, [ownerKey, signature, key, stampId], 'validation-key-insert');
2621
3020
  log('Validation key inserted: %s', key);
2622
3021
  }
@@ -2694,10 +3093,10 @@ export class ControlDatabase {
2694
3093
  // Persist the vouching (owner, signature) onto the row (VouchOwner/VouchSig) —
2695
3094
  // identical to the context pair, which the AuthorizedInsert constraint binds — so a
2696
3095
  // reader can later re-check the voucher against its node-local trusted-owner anchor.
2697
- await this.db.exec(`
2698
- insert into CadreControl.CadrePeer (PeerId, PublicKey, Multiaddr, UpdatedAt, Sig, Profile, StampId, VouchOwner, VouchSig)
2699
- with context OwnerKey = ?, Signature = ?
2700
- values (?, ?, ?, ?, ?, ?, ?, ?, ?)
3096
+ await this.db.exec(`
3097
+ insert into CadreControl.CadrePeer (PeerId, PublicKey, Multiaddr, UpdatedAt, Sig, Profile, StampId, VouchOwner, VouchSig)
3098
+ with context OwnerKey = ?, Signature = ?
3099
+ values (?, ?, ?, ?, ?, ?, ?, ?, ?)
2701
3100
  `, [ownerKey, signature, row.peerId, row.publicKey, row.multiaddr, row.updatedAt, row.sig, row.profile, stampId, ownerKey, signature]);
2702
3101
  return true;
2703
3102
  });
@@ -2786,19 +3185,19 @@ export class ControlDatabase {
2786
3185
  const signature = await signMessage(buildAuthorizationMessage('CadreControl.CadrePeer', 'vouch', this.config.partyId, [peerId, target.stampId]));
2787
3186
  // Bare `exec` — inside the non-re-entrant write lock (see insertCadrePeer).
2788
3187
  if (mode === 'rebroadcast') {
2789
- await this.db.exec(`
2790
- update CadreControl.CadrePeer
2791
- with context OwnerKey = ?, Signature = ?
2792
- set UpdatedAt = ?, VouchOwner = ?, VouchSig = ?, VouchUsage = null
2793
- where PeerId = ?
3188
+ await this.db.exec(`
3189
+ update CadreControl.CadrePeer
3190
+ with context OwnerKey = ?, Signature = ?
3191
+ set UpdatedAt = ?, VouchOwner = ?, VouchSig = ?, VouchUsage = null
3192
+ where PeerId = ?
2794
3193
  `, [ownerKey, signature, Math.max(Date.now(), target.updatedAt + 1), ownerKey, signature, peerId]);
2795
3194
  }
2796
3195
  else {
2797
- await this.db.exec(`
2798
- update CadreControl.CadrePeer
2799
- with context OwnerKey = ?, Signature = ?
2800
- set VouchOwner = ?, VouchSig = ?, VouchUsage = null
2801
- where PeerId = ?
3196
+ await this.db.exec(`
3197
+ update CadreControl.CadrePeer
3198
+ with context OwnerKey = ?, Signature = ?
3199
+ set VouchOwner = ?, VouchSig = ?, VouchUsage = null
3200
+ where PeerId = ?
2802
3201
  `, [ownerKey, signature, ownerKey, signature, peerId]);
2803
3202
  }
2804
3203
  return 'retouched';
@@ -2908,13 +3307,22 @@ export class ControlDatabase {
2908
3307
  * come from closed literal unions — no caller-supplied string reaches the statement.
2909
3308
  */
2910
3309
  async execGuardedRemoval(removal, ownerKey) {
3310
+ await this.execSignedDelete(removal, ownerKey);
3311
+ await this.execTombstone(removal.ref, removal.revocationSignature, ownerKey);
3312
+ }
3313
+ /**
3314
+ * The delete half of {@link execGuardedRemoval}, alone: for a row whose stamp a committed
3315
+ * tombstone already retires ({@link RowRetirement} with no tombstone to file). The table's
3316
+ * `RevocationRecorded` check is met by that tombstone, and `AuthorizedDelete` by the owner
3317
+ * signature here, which the reap branch other tables carry does not exist for the key tables.
3318
+ */
3319
+ async execSignedDelete(removal, ownerKey) {
2911
3320
  const { tableName, rowKey, stampId } = removal.ref;
2912
- await this.db.exec(`
2913
- delete from CadreControl.${tableName}
2914
- with context OwnerKey = ?, Signature = ?
2915
- where ${GUARDED_KEY_COLUMN[tableName]} = ? and StampId = ?
3321
+ await this.db.exec(`
3322
+ delete from CadreControl.${tableName}
3323
+ with context OwnerKey = ?, Signature = ?
3324
+ where ${GUARDED_KEY_COLUMN[tableName]} = ? and StampId = ?
2916
3325
  `, [ownerKey, removal.signature, rowKey, stampId]);
2917
- await this.execTombstone(removal.ref, removal.revocationSignature, ownerKey);
2918
3326
  }
2919
3327
  /**
2920
3328
  * File the owner-signed `Revocation` tombstone retiring one row incarnation — the second
@@ -2930,10 +3338,10 @@ export class ControlDatabase {
2930
3338
  * equal), so a node that receives the row by replication can tell which owner filed it.
2931
3339
  */
2932
3340
  async execTombstone(ref, revocationSignature, ownerKey) {
2933
- await this.db.exec(`
2934
- insert into CadreControl.Revocation (TableName, RowKey, StampId, ReissuedAt, SignerKey, SignerSig)
2935
- with context OwnerKey = ?, Signature = ?
2936
- values (?, ?, ?, 0, ?, ?)
3341
+ await this.db.exec(`
3342
+ insert into CadreControl.Revocation (TableName, RowKey, StampId, ReissuedAt, SignerKey, SignerSig)
3343
+ with context OwnerKey = ?, Signature = ?
3344
+ values (?, ?, ?, 0, ?, ?)
2937
3345
  `, [ownerKey, revocationSignature, ref.tableName, ref.rowKey, ref.stampId, ownerKey, revocationSignature]);
2938
3346
  }
2939
3347
  /**
@@ -3017,10 +3425,10 @@ export class ControlDatabase {
3017
3425
  log('reap %s: %s holds a fresh incarnation (live stamp differs from the tombstoned one); leaving it', table, rowKey);
3018
3426
  return false;
3019
3427
  }
3020
- const sql = `
3021
- delete from CadreControl.${table}
3022
- with context OwnerKey = null, Signature = null
3023
- where ${GUARDED_KEY_COLUMN[table]} = ? and StampId = ?
3428
+ const sql = `
3429
+ delete from CadreControl.${table}
3430
+ with context OwnerKey = null, Signature = null
3431
+ where ${GUARDED_KEY_COLUMN[table]} = ? and StampId = ?
3024
3432
  `;
3025
3433
  if (table === 'CadrePeer') {
3026
3434
  // Through mutateCadrePeer so the "EVERY CadrePeer writer goes through here"
@@ -3072,7 +3480,7 @@ export class ControlDatabase {
3072
3480
  *
3073
3481
  * Two rows are deliberately left alone:
3074
3482
  *
3075
- * - **Tables outside {@link REAPABLE_TABLES}** (`Strand`, `StrandPartyKey`, `OwnerKey`)
3483
+ * - **Tables outside {@link REAPABLE_TABLES}** (`Strand`, `StrandPartyKey`, `PendingStrandPartyKey`, `OwnerKey`)
3076
3484
  * — no reap branch exists on their `AuthorizedDelete`, so the delete would throw
3077
3485
  * rather than no-op.
3078
3486
  * - **This node's OWN `CadrePeer` / `DeviceToken` row** (`selfPeerId`). Reaping it would
@@ -3195,11 +3603,11 @@ export class ControlDatabase {
3195
3603
  // output minted per row incarnation (generateStampId), so it identifies one
3196
3604
  // row across all TableName values. Do NOT "fix" this by adding TableName to
3197
3605
  // the where clause.
3198
- await this.db.exec(`
3199
- update CadreControl.Revocation
3200
- with context OwnerKey = ?, Signature = ?
3201
- set ReissuedAt = ?
3202
- where StampId = ?
3606
+ await this.db.exec(`
3607
+ update CadreControl.Revocation
3608
+ with context OwnerKey = ?, Signature = ?
3609
+ set ReissuedAt = ?
3610
+ where StampId = ?
3203
3611
  `, [ownerKey, signature, reissuedAt, row.stampId]);
3204
3612
  executed++;
3205
3613
  }
@@ -3600,10 +4008,10 @@ export class ControlDatabase {
3600
4008
  // signed source-of-truth and the stored value are produced once. StampId is a real,
3601
4009
  // unique column (single-use anti-replay), no longer a context value.
3602
4010
  return {
3603
- sql: `
3604
- insert into CadreControl.FormationInvite (Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId, StampId)
3605
- with context OwnerKey = ?, Signature = ?
3606
- values (?, ?, ?, ?, ?, ?, ?)
4011
+ sql: `
4012
+ insert into CadreControl.FormationInvite (Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId, StampId)
4013
+ with context OwnerKey = ?, Signature = ?
4014
+ values (?, ?, ?, ?, ?, ?, ?)
3607
4015
  `,
3608
4016
  params: [
3609
4017
  ownerKey, signature,
@@ -3673,10 +4081,10 @@ export class ControlDatabase {
3673
4081
  // Hard-coded open + keyless + explicit null founder columns: the
3674
4082
  // consent branch admits no other shape (no signature means no
3675
4083
  // trustworthy founder machine to record — see the schema's comment).
3676
- await this.db.exec(`
3677
- insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId, FounderOwnerKey, FounderPeerId)
3678
- with context OwnerKey = null, Signature = null
3679
- values (?, 'o', null, ?, null, null)
4084
+ await this.db.exec(`
4085
+ insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId, FounderOwnerKey, FounderPeerId)
4086
+ with context OwnerKey = null, Signature = null
4087
+ values (?, 'o', null, ?, null, null)
3680
4088
  `, [strandId, strandStampId]);
3681
4089
  // 2. FormationUsage row — authorised by the matching FormationInvite, and
3682
4090
  // carrying the strand's stamp so it authorizes THIS row and no other.
@@ -3795,10 +4203,10 @@ export class ControlDatabase {
3795
4203
  // robustness/consistency change, matching the strand layer's `consumeInvite`,
3796
4204
  // not a fix for an observable mis-ordering.
3797
4205
  const nowCanonical = await canonicalDatetime(this.db, opts.nowMs);
3798
- await this.db.exec(`
3799
- insert into CadreControl.FormationUsage (Token, UsageStampId, PeerKey, PeerSig, Disclosure, StrandId, StrandStampId)
3800
- with context Now = ?, ValidationKey = ?, ValidationSignature = ?
3801
- values (?, ?, ?, ?, ?, ?, ?)
4206
+ await this.db.exec(`
4207
+ insert into CadreControl.FormationUsage (Token, UsageStampId, PeerKey, PeerSig, Disclosure, StrandId, StrandStampId)
4208
+ with context Now = ?, ValidationKey = ?, ValidationSignature = ?
4209
+ values (?, ?, ?, ?, ?, ?, ?)
3802
4210
  `, [
3803
4211
  nowCanonical, opts.validationKey, opts.validationSignature,
3804
4212
  opts.token, opts.usageStampId, opts.peerKey,
@@ -4047,10 +4455,10 @@ export class ControlDatabase {
4047
4455
  }
4048
4456
  /** Bare `CadreInvite` insert shared by {@link insertCadreInvite} and {@link seatCadreInvite}; the caller holds the lock. */
4049
4457
  async execCadreInviteInsert(row) {
4050
- await this.db.exec(`
4051
- insert into CadreControl.CadreInvite (Key, PeerId, ExpiresAt, TotalUses, IssuerKey, IssuerSig, StampId)
4052
- with context OwnerKey = ?, Signature = ?
4053
- values (?, ?, ?, ?, ?, ?, ?)
4458
+ await this.db.exec(`
4459
+ insert into CadreControl.CadreInvite (Key, PeerId, ExpiresAt, TotalUses, IssuerKey, IssuerSig, StampId)
4460
+ with context OwnerKey = ?, Signature = ?
4461
+ values (?, ?, ?, ?, ?, ?, ?)
4054
4462
  `, [
4055
4463
  row.issuerKey, row.issuerSig,
4056
4464
  row.key, row.peerId, row.expiresAt, row.totalUses,
@@ -4351,16 +4759,16 @@ export class ControlDatabase {
4351
4759
  const peerStampId = generateStampId(peerId);
4352
4760
  const nowCanonical = await canonicalDatetime(this.db, nowMs);
4353
4761
  await this.inTransaction('cadre-invite-redeem', async () => {
4354
- await this.db.exec(`
4355
- insert into CadreControl.CadrePeer (PeerId, PublicKey, Multiaddr, UpdatedAt, Sig, Profile, StampId, VouchOwner, VouchSig, VouchUsage)
4356
- with context OwnerKey = null, Signature = null
4357
- values (?, ?, ?, ?, ?, ?, ?, ?, null, ?)
4762
+ await this.db.exec(`
4763
+ insert into CadreControl.CadrePeer (PeerId, PublicKey, Multiaddr, UpdatedAt, Sig, Profile, StampId, VouchOwner, VouchSig, VouchUsage)
4764
+ with context OwnerKey = null, Signature = null
4765
+ values (?, ?, ?, ?, ?, ?, ?, ?, null, ?)
4358
4766
  `, [peerId, peerKey, multiaddr, record?.updatedAt ?? nowMs, record?.sig ?? null, record?.profile ?? null,
4359
4767
  peerStampId, invite.issuerKey, usageStampId]);
4360
- await this.db.exec(`
4361
- insert into CadreControl.CadreInviteUsage (UsageStampId, InviteKey, PeerId, PeerKey, PeerStampId, InviteSig, PeerSig)
4362
- with context Now = ?
4363
- values (?, ?, ?, ?, ?, ?, ?)
4768
+ await this.db.exec(`
4769
+ insert into CadreControl.CadreInviteUsage (UsageStampId, InviteKey, PeerId, PeerKey, PeerStampId, InviteSig, PeerSig)
4770
+ with context Now = ?
4771
+ values (?, ?, ?, ?, ?, ?, ?)
4364
4772
  `, [nowCanonical, usageStampId, inviteKey, peerId, peerKey, peerStampId, inviteSig, peerSig]);
4365
4773
  });
4366
4774
  log('Redeemed cadre invitation %s: %s admitted (usage %s)', inviteKey, peerId, usageStampId);
@@ -4441,10 +4849,10 @@ export class ControlDatabase {
4441
4849
  }
4442
4850
  /** Bare `OwnerGrant` insert shared by {@link insertOwnerGrant} and {@link seatOwnerGrant}; the caller holds the lock. */
4443
4851
  async execOwnerGrantInsert(row) {
4444
- await this.db.exec(`
4445
- insert into CadreControl.OwnerGrant (Key, Label, ExpiresAt, TotalUses, IssuerKey, IssuerSig, StampId)
4446
- with context OwnerKey = ?, Signature = ?
4447
- values (?, ?, ?, ?, ?, ?, ?)
4852
+ await this.db.exec(`
4853
+ insert into CadreControl.OwnerGrant (Key, Label, ExpiresAt, TotalUses, IssuerKey, IssuerSig, StampId)
4854
+ with context OwnerKey = ?, Signature = ?
4855
+ values (?, ?, ?, ?, ?, ?, ?)
4448
4856
  `, [
4449
4857
  row.issuerKey, row.issuerSig,
4450
4858
  row.key, row.label, row.expiresAt, row.totalUses,
@@ -4574,15 +4982,15 @@ export class ControlDatabase {
4574
4982
  const seatedStampId = generateStampId(this.config.libp2pNode.peerId.toString());
4575
4983
  const nowCanonical = await canonicalDatetime(this.db, nowMs);
4576
4984
  await this.inTransaction('owner-grant-redeem', async () => {
4577
- await this.db.exec(`
4578
- insert into CadreControl.OwnerKey (Key, Label, StampId, VouchOwner, VouchSig, VouchUsage)
4579
- with context OwnerKey = null, Signature = null
4580
- values (?, ?, ?, ?, null, ?)
4985
+ await this.db.exec(`
4986
+ insert into CadreControl.OwnerKey (Key, Label, StampId, VouchOwner, VouchSig, VouchUsage)
4987
+ with context OwnerKey = null, Signature = null
4988
+ values (?, ?, ?, ?, null, ?)
4581
4989
  `, [seatedKey, grant.label, seatedStampId, grant.issuerKey, usageStampId]);
4582
- await this.db.exec(`
4583
- insert into CadreControl.OwnerGrantUsage (UsageStampId, GrantKey, SeatedKey, SeatedStampId, GrantSig, OwnerSig)
4584
- with context Now = ?
4585
- values (?, ?, ?, ?, ?, ?)
4990
+ await this.db.exec(`
4991
+ insert into CadreControl.OwnerGrantUsage (UsageStampId, GrantKey, SeatedKey, SeatedStampId, GrantSig, OwnerSig)
4992
+ with context Now = ?
4993
+ values (?, ?, ?, ?, ?, ?)
4586
4994
  `, [nowCanonical, usageStampId, grantKey, seatedKey, seatedStampId, grantSig, ownerSig]);
4587
4995
  });
4588
4996
  log('Redeemed owner grant %s: %s seated as an owner (usage %s)', grantKey, seatedKey, usageStampId);
@@ -4605,13 +5013,31 @@ export class ControlDatabase {
4605
5013
  * null handle instead of committing. The tail never rejects (it swallows both
4606
5014
  * outcomes), so the bare await is safe.
4607
5015
  *
4608
- * NOTE: this makes `close()` wait on a stuck write. Acceptable today — every locked
4609
- * body is a bounded local `exec` — but revisit (bounded drain, or abandon after a
4610
- * deadline) if a write can ever hang.
5016
+ * Then closes the Quereus `Database` and waits for it, and only then shuts the collection
5017
+ * factory down (which stops the control node): Quereus's close stops every running
5018
+ * statement and open iterator and resolves once nothing reads or writes, so no statement
5019
+ * reaches stopped storage. The handle stays set across the awaits, so a second, concurrent
5020
+ * close awaits the same teardown (Quereus returns the first call's promise) rather than
5021
+ * skipping ahead to the storage shutdown. A rejected Quereus close is logged and the
5022
+ * teardown goes on, because callers stop storage once this resolves.
5023
+ *
5024
+ * NOTE: this makes `close()` wait on a stuck write, and on a statement in a network wait
5025
+ * (a control read the local replica could not answer), the latter bounded by Optimystic's
5026
+ * RPC deadlines. Acceptable today — every locked body is a bounded local `exec`, and control
5027
+ * reads answer from the local replica — but revisit (bounded drain, or abort in-flight
5028
+ * collection work before closing Quereus) if a write can ever hang or node stops show up slow.
4611
5029
  */
4612
5030
  async close() {
4613
5031
  this.tableWatches.disposeAll();
4614
5032
  await this.writeQueue;
5033
+ if (this.db) {
5034
+ try {
5035
+ await this.db.close();
5036
+ }
5037
+ catch (err) {
5038
+ log('Closing the control Quereus database failed; shutting storage down anyway: %O', err);
5039
+ }
5040
+ }
4615
5041
  if (this.collectionFactory) {
4616
5042
  await this.collectionFactory.shutdown();
4617
5043
  this.collectionFactory = null;
@@ -4621,10 +5047,7 @@ export class ControlDatabase {
4621
5047
  this.tableWatches.disposeAll();
4622
5048
  // Here, not first: a read started during the awaits above must not install either.
4623
5049
  this.invalidateMembershipViews();
4624
- if (this.db) {
4625
- void this.db.close();
4626
- this.db = null;
4627
- }
5050
+ this.db = null;
4628
5051
  this.initialized = false;
4629
5052
  log('ControlDatabase closed');
4630
5053
  }