@serfab/cadre-core 1.21.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 (106) 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 +587 -173
  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/sealed-party-key.d.ts +32 -0
  34. package/dist/sealed-party-key.js +162 -0
  35. package/dist/sealed-party-key.js.map +1 -0
  36. package/dist/seed-bootstrap.d.ts +10 -3
  37. package/dist/seed-bootstrap.js +12 -0
  38. package/dist/seed-bootstrap.js.map +1 -1
  39. package/dist/strand-addr-protocol.d.ts +56 -6
  40. package/dist/strand-addr-protocol.js +57 -5
  41. package/dist/strand-addr-protocol.js.map +1 -1
  42. package/dist/strand-commit-durability.d.ts +33 -2
  43. package/dist/strand-commit-durability.js +44 -4
  44. package/dist/strand-commit-durability.js.map +1 -1
  45. package/dist/strand-database.d.ts +35 -5
  46. package/dist/strand-database.js +34 -10
  47. package/dist/strand-database.js.map +1 -1
  48. package/dist/strand-instance-manager.d.ts +133 -9
  49. package/dist/strand-instance-manager.js +266 -42
  50. package/dist/strand-instance-manager.js.map +1 -1
  51. package/dist/strand-membership-reconciler.d.ts +250 -51
  52. package/dist/strand-membership-reconciler.js +410 -66
  53. package/dist/strand-membership-reconciler.js.map +1 -1
  54. package/dist/strand-membership-writer.d.ts +7 -0
  55. package/dist/strand-membership-writer.js +9 -0
  56. package/dist/strand-membership-writer.js.map +1 -1
  57. package/dist/strand-party-key-rotation.d.ts +177 -0
  58. package/dist/strand-party-key-rotation.js +340 -0
  59. package/dist/strand-party-key-rotation.js.map +1 -0
  60. package/dist/strand-party-machines.d.ts +111 -0
  61. package/dist/strand-party-machines.js +258 -0
  62. package/dist/strand-party-machines.js.map +1 -0
  63. package/dist/strand-party-peers.d.ts +101 -0
  64. package/dist/strand-party-peers.js +49 -0
  65. package/dist/strand-party-peers.js.map +1 -0
  66. package/dist/strand-peer-redial.d.ts +34 -7
  67. package/dist/strand-peer-redial.js +46 -13
  68. package/dist/strand-peer-redial.js.map +1 -1
  69. package/dist/strand-revocation-enforcer.d.ts +15 -1
  70. package/dist/strand-revocation-enforcer.js +16 -9
  71. package/dist/strand-revocation-enforcer.js.map +1 -1
  72. package/dist/strand-transport-key.js +3 -0
  73. package/dist/strand-transport-key.js.map +1 -1
  74. package/dist/strand-watcher.d.ts +7 -4
  75. package/dist/strand-watcher.js +12 -7
  76. package/dist/strand-watcher.js.map +1 -1
  77. package/dist/types.d.ts +160 -13
  78. package/dist/types.js.map +1 -1
  79. package/package.json +9 -8
  80. package/src/cadre-node.ts +12252 -11528
  81. package/src/control-authorization.ts +41 -1
  82. package/src/control-database.ts +6123 -5603
  83. package/src/control-schema.ts +71 -7
  84. package/src/ed25519-key.ts +12 -1
  85. package/src/index.ts +957 -924
  86. package/src/machine-removal.ts +80 -1
  87. package/src/membership-connection-gater.ts +13 -1
  88. package/src/owner-keys.ts +2 -1
  89. package/src/owner-signer.ts +92 -94
  90. package/src/peer-authorization.ts +27 -3
  91. package/src/sealed-party-key.ts +190 -0
  92. package/src/seed-bootstrap.ts +17 -3
  93. package/src/strand-addr-protocol.ts +67 -6
  94. package/src/strand-commit-durability.ts +54 -5
  95. package/src/strand-database.ts +47 -11
  96. package/src/strand-instance-manager.ts +330 -42
  97. package/src/strand-membership-reconciler.ts +1310 -942
  98. package/src/strand-membership-writer.ts +10 -0
  99. package/src/strand-party-key-rotation.ts +436 -0
  100. package/src/strand-party-machines.ts +293 -0
  101. package/src/strand-party-peers.ts +129 -0
  102. package/src/strand-peer-redial.ts +61 -14
  103. package/src/strand-revocation-enforcer.ts +27 -9
  104. package/src/strand-transport-key.ts +3 -0
  105. package/src/strand-watcher.ts +12 -7
  106. package/src/types.ts +3112 -2963
@@ -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) {
@@ -1084,10 +1110,12 @@ export class ControlDatabase {
1084
1110
  // steps still missing. No row is lost either way: rows keep a dropped column's field until they
1085
1111
  // are rewritten, and nothing reads it.
1086
1112
  //
1087
- // NOTE: a cohort that keeps refusing the commit now ends the retries with a thrown error, so a
1088
- // machine migrating while its siblings are offline fails its start. No release has migrated
1089
- // yet (`CONTROL_SCHEMA_VERSION` is the baseline). The first version that does should decide
1090
- // whether that start waits, as the `App` apply does (`applyAppSchemaOrDefer`).
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`).
1091
1119
  //
1092
1120
  // Only the "cohort did not answer, nothing committed" class is retried; the classifier
1093
1121
  // vetoes indeterminate commits and does not match `Missing block`, which is a durable
@@ -1470,8 +1498,8 @@ export class ControlDatabase {
1470
1498
  * such collections, and nothing creates them later: the start-time schema apply runs on every
1471
1499
  * machine, possibly alone, where committing one would be exactly the fork genesis avoids.
1472
1500
  *
1473
- * NOTE: one `sync()` per collection, in sequence: 32 collections for today's schema (17 tables,
1474
- * 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
1475
1503
  * transactor (started, then `ensureOwnerKey` alone, 3 runs each): 64–105 ms in memory and
1476
1504
  * 750–820 ms on `FileRawStorage`, about 25 ms per collection on disk, roughly 1/75 of the edge
1477
1505
  * node's 60 s `DEFAULT_OWNER_GENESIS_TIMEOUT_MS`. Under the whole cadre-core suite's load (151
@@ -1587,15 +1615,25 @@ export class ControlDatabase {
1587
1615
  async queryCadrePeers(retry = true) {
1588
1616
  this.ensureInitialized();
1589
1617
  const revoked = await this.queryRevokedStamps('CadrePeer', retry);
1590
- const rows = [];
1591
- for (const row of await this.readMembershipRows(this.cadrePeerView, retry)) {
1592
- const peer = cadrePeerRowOf(row);
1593
- if (peer.stampId !== null && revoked.has(peer.stampId)) {
1594
- continue;
1595
- }
1596
- rows.push(peer);
1597
- }
1598
- 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 };
1599
1637
  }
1600
1638
  /**
1601
1639
  * The cadre's peers as a seed or a redemption reply carries them: every live `CadrePeer`
@@ -1686,6 +1724,10 @@ export class ControlDatabase {
1686
1724
  queryStrandPartyKeyStampId(strandId) {
1687
1725
  return this.queryStampId('StrandPartyKey', strandId);
1688
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
+ }
1689
1731
  /** `JoinedStrand` stamp nonce — bound into {@link deleteJoinedStrand}'s remove digest. */
1690
1732
  queryJoinedStrandStampId(strandId) {
1691
1733
  return this.queryStampId('JoinedStrand', strandId);
@@ -1704,6 +1746,85 @@ export class ControlDatabase {
1704
1746
  }
1705
1747
  return null;
1706
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
+ }
1707
1828
  /** `ValidationKey` stamp nonce — bound into {@link deleteValidationKey}'s remove digest. */
1708
1829
  queryValidationKeyStampId(key) {
1709
1830
  return this.queryStampId('ValidationKey', key);
@@ -1780,9 +1901,11 @@ export class ControlDatabase {
1780
1901
  * admission gate's 2 s deadline (`ADMISSION_DECISION_TIMEOUT_MS`), skip the retry for this
1781
1902
  * read when the first attempt fails `cohort-unreachable`.
1782
1903
  */
1783
- async readRevocationRowsOrNone(retry) {
1904
+ async readRevocationRowsOrNone(retry, served = 'view') {
1784
1905
  try {
1785
- return await this.readMembershipRows(this.revocationView, retry);
1906
+ return served === 'fresh'
1907
+ ? await this.revocationView.readThrough(retry)
1908
+ : await this.readMembershipRows(this.revocationView, retry);
1786
1909
  }
1787
1910
  catch (error) {
1788
1911
  if (!isCohortUnreachableRead(error)) {
@@ -1921,11 +2044,11 @@ export class ControlDatabase {
1921
2044
  }
1922
2045
  const record = sign(current);
1923
2046
  // Bare `exec` — inside the non-re-entrant write lock (see insertCadrePeer).
1924
- await this.db.exec(`
1925
- update CadreControl.CadrePeer
1926
- with context OwnerKey = null, Signature = ?
1927
- set Multiaddr = ?, UpdatedAt = ?, Profile = ?, Sig = ?
1928
- 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 = ?
1929
2052
  `, [record.sig, record.addrs.join(','), record.updatedAt, record.profile, record.sig, peerId]);
1930
2053
  return record;
1931
2054
  }, LOST_UPDATE_RETRY_POLICY, 'self-record-update');
@@ -1977,11 +2100,11 @@ export class ControlDatabase {
1977
2100
  */
1978
2101
  async updateSelfDeviceToken(record) {
1979
2102
  this.ensureInitialized();
1980
- await this.execWrite(`
1981
- update CadreControl.DeviceToken
1982
- with context OwnerKey = null, Signature = ?
1983
- set Platform = ?, Token = ?, UpdatedAt = ?, Sig = ?
1984
- 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 = ?
1985
2108
  `, [record.sig, record.platform, record.token, record.updatedAt, record.sig, record.peerId], 'device-token-update');
1986
2109
  log('Self device token updated: %s (platform=%s, updatedAt=%d)', record.peerId, record.platform, record.updatedAt);
1987
2110
  }
@@ -2004,10 +2127,10 @@ export class ControlDatabase {
2004
2127
  // not-null/unique anti-replay constraint — the StampId is a real column value, not the
2005
2128
  // optimystic `StampId()` SQL function.
2006
2129
  const stampId = generateStampId(this.config.libp2pNode.peerId.toString());
2007
- await this.execWrite(`
2008
- insert into CadreControl.OwnerKey (Key, Label, StampId)
2009
- with context OwnerKey = null, Signature = null
2010
- values (?, ?, ?)
2130
+ await this.execWrite(`
2131
+ insert into CadreControl.OwnerKey (Key, Label, StampId)
2132
+ with context OwnerKey = null, Signature = null
2133
+ values (?, ?, ?)
2011
2134
  `, [key, storedLabel, stampId], 'owner-key-insert');
2012
2135
  log('Owner key inserted');
2013
2136
  }
@@ -2074,10 +2197,10 @@ export class ControlDatabase {
2074
2197
  * NOT re-entrant.
2075
2198
  */
2076
2199
  async execOwnerKeyVouchedInsert(row, ownerKey, signature) {
2077
- await this.db.exec(`
2078
- insert into CadreControl.OwnerKey (Key, Label, StampId, VouchOwner, VouchSig)
2079
- with context OwnerKey = ?, Signature = ?
2080
- values (?, ?, ?, ?, ?)
2200
+ await this.db.exec(`
2201
+ insert into CadreControl.OwnerKey (Key, Label, StampId, VouchOwner, VouchSig)
2202
+ with context OwnerKey = ?, Signature = ?
2203
+ values (?, ?, ?, ?, ?)
2081
2204
  `, [ownerKey, signature, row.key, row.label, row.stampId, ownerKey, signature]);
2082
2205
  }
2083
2206
  /**
@@ -2159,14 +2282,28 @@ export class ControlDatabase {
2159
2282
  * `DeviceToken` row when it has one, each with the `Revocation` tombstone retiring its stamp
2160
2283
  * ({@link deleteGuardedRow}'s statement pair, composed bare as {@link deleteStrandAndPartyKey}
2161
2284
  * composes it), plus a withdrawal tombstone for every `CadreInvite` in `target.inviteKeys`
2162
- * that is still live here ({@link withdrawCadreInvite}'s body). One transaction so no reader
2163
- * sees the machine half removed: a row gone but its push token resolvable, or an invitation
2164
- * it could redeem again still open. Owner keys are never touched: they are the person's, and
2165
- * 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.
2166
2302
  *
2167
2303
  * Through {@link mutateCadrePeer}, the membership hub. Every stamp is read inside the locked
2168
2304
  * body, and a row whose stamp is already retired (held without its delete) is skipped rather
2169
- * 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.
2170
2307
  *
2171
2308
  * Opted into {@link LOST_UPDATE_RETRY_POLICY} for the reason on {@link deleteCadrePeer}: every
2172
2309
  * stamp and signature is minted inside the body, and the invitation keys come from the
@@ -2175,17 +2312,19 @@ export class ControlDatabase {
2175
2312
  * before). A lost update after a sibling tree of the transaction already synced arrives as a
2176
2313
  * partial commit and stays declined.
2177
2314
  *
2178
- * The caller decides which invitations the machine could use, from its plan
2179
- * (`CadreNode.planMachineRemoval`).
2315
+ * The caller decides which invitations the machine could use and which strands to rotate,
2316
+ * from its plan (`CadreNode.planMachineRemoval`).
2180
2317
  */
2181
2318
  async removeMachine(target, ownerKey, signMessage) {
2182
2319
  return await this.mutateCadrePeer('machine-remove', async () => {
2183
- const removals = await this.signMachineRemovals(target.peerId, signMessage);
2320
+ const retired = await this.retiredStampsByTable();
2321
+ const removals = await this.signMachineRemovals(target.peerId, retired, signMessage);
2184
2322
  const withdrawals = await this.signWithdrawals('CadreInvite', target.inviteKeys, signMessage);
2185
2323
  if (removals.length === 0 && withdrawals.length === 0) {
2186
2324
  log('removeMachine: nothing live names %s here (already removed)', target.peerId);
2187
2325
  return { removedPeer: false, removedDeviceToken: false, withdrawnInvitations: [] };
2188
2326
  }
2327
+ const rotations = await this.signPendingPartyKeyReplacements(target.pendingPartyKeys ?? [], retired('PendingStrandPartyKey'), ownerKey, signMessage);
2189
2328
  await this.inTransaction('remove machine', async () => {
2190
2329
  for (const removal of removals) {
2191
2330
  await this.execGuardedRemoval(removal, ownerKey);
@@ -2193,15 +2332,24 @@ export class ControlDatabase {
2193
2332
  for (const withdrawal of withdrawals) {
2194
2333
  await this.execTombstone(withdrawal.ref, withdrawal.signature, ownerKey);
2195
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
+ }
2196
2341
  });
2197
2342
  const removed = new Set(removals.map((removal) => removal.ref.tableName));
2198
- 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);
2199
2344
  for (const removal of removals) {
2200
2345
  this.notifyGuardedDelete(removal.ref);
2201
2346
  }
2202
2347
  for (const withdrawal of withdrawals) {
2203
2348
  this.notifyGuardedDelete(withdrawal.ref);
2204
2349
  }
2350
+ for (const rotation of rotations) {
2351
+ this.notifyRowRetirement(rotation.retirement);
2352
+ }
2205
2353
  return {
2206
2354
  removedPeer: removed.has('CadrePeer'),
2207
2355
  removedDeviceToken: removed.has('DeviceToken'),
@@ -2210,19 +2358,24 @@ export class ControlDatabase {
2210
2358
  }, LOST_UPDATE_RETRY_POLICY);
2211
2359
  }
2212
2360
  /**
2213
- * The guarded removals {@link removeMachine} runs, signed over each row's current stamp:
2214
- * the `CadrePeer` row and the `DeviceToken` row, each when present. Inside the locked body
2215
- * (every read `retry: false`); one `Revocation` scan serves the retired-stamp check for both
2216
- * 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.
2217
2363
  */
2218
- async signMachineRemovals(peerId, signMessage) {
2364
+ async retiredStampsByTable() {
2219
2365
  const retiredByTable = new Map();
2220
2366
  for (const tombstone of await this.queryRevocations(false)) {
2221
2367
  const stamps = retiredByTable.get(tombstone.tableName) ?? new Set();
2222
2368
  stamps.add(tombstone.stampId);
2223
2369
  retiredByTable.set(tombstone.tableName, stamps);
2224
2370
  }
2225
- 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) {
2226
2379
  const liveStamp = async (table, keyValue) => {
2227
2380
  const stampId = await this.queryStampId(table, keyValue, false);
2228
2381
  return stampId !== null && !retired(table).has(stampId) ? stampId : null;
@@ -2236,6 +2389,75 @@ export class ControlDatabase {
2236
2389
  }
2237
2390
  return removals;
2238
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
+ }
2239
2461
  /**
2240
2462
  * Insert a strand into the control database using an owner signature.
2241
2463
  *
@@ -2276,10 +2498,10 @@ export class ControlDatabase {
2276
2498
  // StampId is a real, unique column (single-use anti-replay), no longer a context value.
2277
2499
  // FounderOwnerKey must equal the signing owner or the constraint rejects the row.
2278
2500
  return {
2279
- sql: `
2280
- insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId, FounderOwnerKey, FounderPeerId)
2281
- with context OwnerKey = ?, Signature = ?
2282
- values (?, ?, ?, ?, ?, ?)
2501
+ sql: `
2502
+ insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId, FounderOwnerKey, FounderPeerId)
2503
+ with context OwnerKey = ?, Signature = ?
2504
+ values (?, ?, ?, ?, ?, ?)
2283
2505
  `,
2284
2506
  params: [ownerKey, signature, strandId, type, memberPrivateKey ?? null, stampId, ownerKey, peerId],
2285
2507
  };
@@ -2374,21 +2596,30 @@ export class ControlDatabase {
2374
2596
  return false;
2375
2597
  }
2376
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));
2377
2603
  const strandRemoval = await signGuardedRemoval(this.config.partyId, 'Strand', strandId, strandStamp, signMessage);
2378
2604
  const partyKeyRemoval = partyKeyStamp === null
2379
2605
  ? null
2380
2606
  : await signGuardedRemoval(this.config.partyId, 'StrandPartyKey', strandId, partyKeyStamp, signMessage);
2607
+ const pendingRetirement = pending === null ? null : await this.signPendingKeyRetirement(strandId, pending, signMessage);
2381
2608
  await this.inTransaction('delete Strand', async () => {
2382
2609
  await this.execGuardedRemoval(strandRemoval, ownerKey);
2383
2610
  if (partyKeyRemoval !== null) {
2384
2611
  await this.execGuardedRemoval(partyKeyRemoval, ownerKey);
2385
2612
  }
2613
+ if (pendingRetirement !== null) {
2614
+ await this.execRowRetirement(pendingRetirement, ownerKey);
2615
+ }
2386
2616
  });
2387
- 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');
2388
2618
  this.notifyGuardedDelete(strandRemoval.ref);
2389
2619
  if (partyKeyRemoval !== null) {
2390
2620
  this.notifyGuardedDelete(partyKeyRemoval.ref);
2391
2621
  }
2622
+ this.notifyRowRetirement(pendingRetirement);
2392
2623
  return true;
2393
2624
  }
2394
2625
  /**
@@ -2422,10 +2653,10 @@ export class ControlDatabase {
2422
2653
  const message = buildAuthorizationMessage('CadreControl.StrandPartyKey', 'add', this.config.partyId, [strandId, privateKey, stampId]);
2423
2654
  const signature = await signMessage(message);
2424
2655
  return {
2425
- sql: `
2426
- insert into CadreControl.StrandPartyKey (Id, PrivateKey, StampId)
2427
- with context OwnerKey = ?, Signature = ?
2428
- values (?, ?, ?)
2656
+ sql: `
2657
+ insert into CadreControl.StrandPartyKey (Id, PrivateKey, StampId)
2658
+ with context OwnerKey = ?, Signature = ?
2659
+ values (?, ?, ?)
2429
2660
  `,
2430
2661
  params: [ownerKey, signature, strandId, privateKey, stampId],
2431
2662
  };
@@ -2445,6 +2676,165 @@ export class ControlDatabase {
2445
2676
  deleteStrandPartyKey(strandId, ownerKey, signMessage) {
2446
2677
  return this.lockedWithRetry(() => this.deleteGuardedRow('StrandPartyKey', strandId, ownerKey, signMessage), {}, 'strand-party-key-delete');
2447
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
+ }
2448
2838
  /**
2449
2839
  * Record, party-wide, a strand this party joined from another party (`JoinedStrand` row),
2450
2840
  * using an owner signature.
@@ -2465,10 +2855,10 @@ export class ControlDatabase {
2465
2855
  // Id, Type, MemberPrivateKey ('' when null), StampId.
2466
2856
  const message = buildAuthorizationMessage('CadreControl.JoinedStrand', 'add', this.config.partyId, [row.Id, row.Type, row.MemberPrivateKey ?? '', stampId]);
2467
2857
  const signature = await signMessage(message);
2468
- await this.execWrite(`
2469
- insert into CadreControl.JoinedStrand (Id, Type, MemberPrivateKey, StampId)
2470
- with context OwnerKey = ?, Signature = ?
2471
- values (?, ?, ?, ?)
2858
+ await this.execWrite(`
2859
+ insert into CadreControl.JoinedStrand (Id, Type, MemberPrivateKey, StampId)
2860
+ with context OwnerKey = ?, Signature = ?
2861
+ values (?, ?, ?, ?)
2472
2862
  `, [ownerKey, signature, row.Id, row.Type, row.MemberPrivateKey, stampId], 'joined-strand-insert');
2473
2863
  log('Joined strand inserted: %s', row.Id);
2474
2864
  }
@@ -2595,10 +2985,10 @@ export class ControlDatabase {
2595
2985
  }
2596
2986
  /** One unsigned outcome delete (see {@link deleteJoinOutcomes}; a failure's is also authorized by the join superseding it). */
2597
2987
  async deleteJoinOutcome(table, requestStampId) {
2598
- await this.db.exec(`
2599
- delete from CadreControl.${table}
2600
- with context OwnerKey = null, Signature = null
2601
- where RequestStampId = ?
2988
+ await this.db.exec(`
2989
+ delete from CadreControl.${table}
2990
+ with context OwnerKey = null, Signature = null
2991
+ where RequestStampId = ?
2602
2992
  `, [requestStampId]);
2603
2993
  }
2604
2994
  /**
@@ -2622,10 +3012,10 @@ export class ControlDatabase {
2622
3012
  // Field order MUST match the schema's ValidationKey `AuthorizedInsert` verify: Key, StampId.
2623
3013
  const message = buildAuthorizationMessage('CadreControl.ValidationKey', 'add', this.config.partyId, [key, stampId]);
2624
3014
  const signature = await signMessage(message);
2625
- await this.execWrite(`
2626
- insert into CadreControl.ValidationKey (Key, StampId)
2627
- with context OwnerKey = ?, Signature = ?
2628
- values (?, ?)
3015
+ await this.execWrite(`
3016
+ insert into CadreControl.ValidationKey (Key, StampId)
3017
+ with context OwnerKey = ?, Signature = ?
3018
+ values (?, ?)
2629
3019
  `, [ownerKey, signature, key, stampId], 'validation-key-insert');
2630
3020
  log('Validation key inserted: %s', key);
2631
3021
  }
@@ -2703,10 +3093,10 @@ export class ControlDatabase {
2703
3093
  // Persist the vouching (owner, signature) onto the row (VouchOwner/VouchSig) —
2704
3094
  // identical to the context pair, which the AuthorizedInsert constraint binds — so a
2705
3095
  // reader can later re-check the voucher against its node-local trusted-owner anchor.
2706
- await this.db.exec(`
2707
- insert into CadreControl.CadrePeer (PeerId, PublicKey, Multiaddr, UpdatedAt, Sig, Profile, StampId, VouchOwner, VouchSig)
2708
- with context OwnerKey = ?, Signature = ?
2709
- 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 (?, ?, ?, ?, ?, ?, ?, ?, ?)
2710
3100
  `, [ownerKey, signature, row.peerId, row.publicKey, row.multiaddr, row.updatedAt, row.sig, row.profile, stampId, ownerKey, signature]);
2711
3101
  return true;
2712
3102
  });
@@ -2795,19 +3185,19 @@ export class ControlDatabase {
2795
3185
  const signature = await signMessage(buildAuthorizationMessage('CadreControl.CadrePeer', 'vouch', this.config.partyId, [peerId, target.stampId]));
2796
3186
  // Bare `exec` — inside the non-re-entrant write lock (see insertCadrePeer).
2797
3187
  if (mode === 'rebroadcast') {
2798
- await this.db.exec(`
2799
- update CadreControl.CadrePeer
2800
- with context OwnerKey = ?, Signature = ?
2801
- set UpdatedAt = ?, VouchOwner = ?, VouchSig = ?, VouchUsage = null
2802
- 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 = ?
2803
3193
  `, [ownerKey, signature, Math.max(Date.now(), target.updatedAt + 1), ownerKey, signature, peerId]);
2804
3194
  }
2805
3195
  else {
2806
- await this.db.exec(`
2807
- update CadreControl.CadrePeer
2808
- with context OwnerKey = ?, Signature = ?
2809
- set VouchOwner = ?, VouchSig = ?, VouchUsage = null
2810
- 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 = ?
2811
3201
  `, [ownerKey, signature, ownerKey, signature, peerId]);
2812
3202
  }
2813
3203
  return 'retouched';
@@ -2917,13 +3307,22 @@ export class ControlDatabase {
2917
3307
  * come from closed literal unions — no caller-supplied string reaches the statement.
2918
3308
  */
2919
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) {
2920
3320
  const { tableName, rowKey, stampId } = removal.ref;
2921
- await this.db.exec(`
2922
- delete from CadreControl.${tableName}
2923
- with context OwnerKey = ?, Signature = ?
2924
- 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 = ?
2925
3325
  `, [ownerKey, removal.signature, rowKey, stampId]);
2926
- await this.execTombstone(removal.ref, removal.revocationSignature, ownerKey);
2927
3326
  }
2928
3327
  /**
2929
3328
  * File the owner-signed `Revocation` tombstone retiring one row incarnation — the second
@@ -2939,10 +3338,10 @@ export class ControlDatabase {
2939
3338
  * equal), so a node that receives the row by replication can tell which owner filed it.
2940
3339
  */
2941
3340
  async execTombstone(ref, revocationSignature, ownerKey) {
2942
- await this.db.exec(`
2943
- insert into CadreControl.Revocation (TableName, RowKey, StampId, ReissuedAt, SignerKey, SignerSig)
2944
- with context OwnerKey = ?, Signature = ?
2945
- 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, ?, ?)
2946
3345
  `, [ownerKey, revocationSignature, ref.tableName, ref.rowKey, ref.stampId, ownerKey, revocationSignature]);
2947
3346
  }
2948
3347
  /**
@@ -3026,10 +3425,10 @@ export class ControlDatabase {
3026
3425
  log('reap %s: %s holds a fresh incarnation (live stamp differs from the tombstoned one); leaving it', table, rowKey);
3027
3426
  return false;
3028
3427
  }
3029
- const sql = `
3030
- delete from CadreControl.${table}
3031
- with context OwnerKey = null, Signature = null
3032
- 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 = ?
3033
3432
  `;
3034
3433
  if (table === 'CadrePeer') {
3035
3434
  // Through mutateCadrePeer so the "EVERY CadrePeer writer goes through here"
@@ -3081,7 +3480,7 @@ export class ControlDatabase {
3081
3480
  *
3082
3481
  * Two rows are deliberately left alone:
3083
3482
  *
3084
- * - **Tables outside {@link REAPABLE_TABLES}** (`Strand`, `StrandPartyKey`, `OwnerKey`)
3483
+ * - **Tables outside {@link REAPABLE_TABLES}** (`Strand`, `StrandPartyKey`, `PendingStrandPartyKey`, `OwnerKey`)
3085
3484
  * — no reap branch exists on their `AuthorizedDelete`, so the delete would throw
3086
3485
  * rather than no-op.
3087
3486
  * - **This node's OWN `CadrePeer` / `DeviceToken` row** (`selfPeerId`). Reaping it would
@@ -3204,11 +3603,11 @@ export class ControlDatabase {
3204
3603
  // output minted per row incarnation (generateStampId), so it identifies one
3205
3604
  // row across all TableName values. Do NOT "fix" this by adding TableName to
3206
3605
  // the where clause.
3207
- await this.db.exec(`
3208
- update CadreControl.Revocation
3209
- with context OwnerKey = ?, Signature = ?
3210
- set ReissuedAt = ?
3211
- where StampId = ?
3606
+ await this.db.exec(`
3607
+ update CadreControl.Revocation
3608
+ with context OwnerKey = ?, Signature = ?
3609
+ set ReissuedAt = ?
3610
+ where StampId = ?
3212
3611
  `, [ownerKey, signature, reissuedAt, row.stampId]);
3213
3612
  executed++;
3214
3613
  }
@@ -3609,10 +4008,10 @@ export class ControlDatabase {
3609
4008
  // signed source-of-truth and the stored value are produced once. StampId is a real,
3610
4009
  // unique column (single-use anti-replay), no longer a context value.
3611
4010
  return {
3612
- sql: `
3613
- insert into CadreControl.FormationInvite (Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId, StampId)
3614
- with context OwnerKey = ?, Signature = ?
3615
- values (?, ?, ?, ?, ?, ?, ?)
4011
+ sql: `
4012
+ insert into CadreControl.FormationInvite (Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId, StampId)
4013
+ with context OwnerKey = ?, Signature = ?
4014
+ values (?, ?, ?, ?, ?, ?, ?)
3616
4015
  `,
3617
4016
  params: [
3618
4017
  ownerKey, signature,
@@ -3682,10 +4081,10 @@ export class ControlDatabase {
3682
4081
  // Hard-coded open + keyless + explicit null founder columns: the
3683
4082
  // consent branch admits no other shape (no signature means no
3684
4083
  // trustworthy founder machine to record — see the schema's comment).
3685
- await this.db.exec(`
3686
- insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId, FounderOwnerKey, FounderPeerId)
3687
- with context OwnerKey = null, Signature = null
3688
- 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)
3689
4088
  `, [strandId, strandStampId]);
3690
4089
  // 2. FormationUsage row — authorised by the matching FormationInvite, and
3691
4090
  // carrying the strand's stamp so it authorizes THIS row and no other.
@@ -3804,10 +4203,10 @@ export class ControlDatabase {
3804
4203
  // robustness/consistency change, matching the strand layer's `consumeInvite`,
3805
4204
  // not a fix for an observable mis-ordering.
3806
4205
  const nowCanonical = await canonicalDatetime(this.db, opts.nowMs);
3807
- await this.db.exec(`
3808
- insert into CadreControl.FormationUsage (Token, UsageStampId, PeerKey, PeerSig, Disclosure, StrandId, StrandStampId)
3809
- with context Now = ?, ValidationKey = ?, ValidationSignature = ?
3810
- 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 (?, ?, ?, ?, ?, ?, ?)
3811
4210
  `, [
3812
4211
  nowCanonical, opts.validationKey, opts.validationSignature,
3813
4212
  opts.token, opts.usageStampId, opts.peerKey,
@@ -4056,10 +4455,10 @@ export class ControlDatabase {
4056
4455
  }
4057
4456
  /** Bare `CadreInvite` insert shared by {@link insertCadreInvite} and {@link seatCadreInvite}; the caller holds the lock. */
4058
4457
  async execCadreInviteInsert(row) {
4059
- await this.db.exec(`
4060
- insert into CadreControl.CadreInvite (Key, PeerId, ExpiresAt, TotalUses, IssuerKey, IssuerSig, StampId)
4061
- with context OwnerKey = ?, Signature = ?
4062
- 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 (?, ?, ?, ?, ?, ?, ?)
4063
4462
  `, [
4064
4463
  row.issuerKey, row.issuerSig,
4065
4464
  row.key, row.peerId, row.expiresAt, row.totalUses,
@@ -4360,16 +4759,16 @@ export class ControlDatabase {
4360
4759
  const peerStampId = generateStampId(peerId);
4361
4760
  const nowCanonical = await canonicalDatetime(this.db, nowMs);
4362
4761
  await this.inTransaction('cadre-invite-redeem', async () => {
4363
- await this.db.exec(`
4364
- insert into CadreControl.CadrePeer (PeerId, PublicKey, Multiaddr, UpdatedAt, Sig, Profile, StampId, VouchOwner, VouchSig, VouchUsage)
4365
- with context OwnerKey = null, Signature = null
4366
- 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, ?)
4367
4766
  `, [peerId, peerKey, multiaddr, record?.updatedAt ?? nowMs, record?.sig ?? null, record?.profile ?? null,
4368
4767
  peerStampId, invite.issuerKey, usageStampId]);
4369
- await this.db.exec(`
4370
- insert into CadreControl.CadreInviteUsage (UsageStampId, InviteKey, PeerId, PeerKey, PeerStampId, InviteSig, PeerSig)
4371
- with context Now = ?
4372
- values (?, ?, ?, ?, ?, ?, ?)
4768
+ await this.db.exec(`
4769
+ insert into CadreControl.CadreInviteUsage (UsageStampId, InviteKey, PeerId, PeerKey, PeerStampId, InviteSig, PeerSig)
4770
+ with context Now = ?
4771
+ values (?, ?, ?, ?, ?, ?, ?)
4373
4772
  `, [nowCanonical, usageStampId, inviteKey, peerId, peerKey, peerStampId, inviteSig, peerSig]);
4374
4773
  });
4375
4774
  log('Redeemed cadre invitation %s: %s admitted (usage %s)', inviteKey, peerId, usageStampId);
@@ -4450,10 +4849,10 @@ export class ControlDatabase {
4450
4849
  }
4451
4850
  /** Bare `OwnerGrant` insert shared by {@link insertOwnerGrant} and {@link seatOwnerGrant}; the caller holds the lock. */
4452
4851
  async execOwnerGrantInsert(row) {
4453
- await this.db.exec(`
4454
- insert into CadreControl.OwnerGrant (Key, Label, ExpiresAt, TotalUses, IssuerKey, IssuerSig, StampId)
4455
- with context OwnerKey = ?, Signature = ?
4456
- 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 (?, ?, ?, ?, ?, ?, ?)
4457
4856
  `, [
4458
4857
  row.issuerKey, row.issuerSig,
4459
4858
  row.key, row.label, row.expiresAt, row.totalUses,
@@ -4583,15 +4982,15 @@ export class ControlDatabase {
4583
4982
  const seatedStampId = generateStampId(this.config.libp2pNode.peerId.toString());
4584
4983
  const nowCanonical = await canonicalDatetime(this.db, nowMs);
4585
4984
  await this.inTransaction('owner-grant-redeem', async () => {
4586
- await this.db.exec(`
4587
- insert into CadreControl.OwnerKey (Key, Label, StampId, VouchOwner, VouchSig, VouchUsage)
4588
- with context OwnerKey = null, Signature = null
4589
- 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, ?)
4590
4989
  `, [seatedKey, grant.label, seatedStampId, grant.issuerKey, usageStampId]);
4591
- await this.db.exec(`
4592
- insert into CadreControl.OwnerGrantUsage (UsageStampId, GrantKey, SeatedKey, SeatedStampId, GrantSig, OwnerSig)
4593
- with context Now = ?
4594
- values (?, ?, ?, ?, ?, ?)
4990
+ await this.db.exec(`
4991
+ insert into CadreControl.OwnerGrantUsage (UsageStampId, GrantKey, SeatedKey, SeatedStampId, GrantSig, OwnerSig)
4992
+ with context Now = ?
4993
+ values (?, ?, ?, ?, ?, ?)
4595
4994
  `, [nowCanonical, usageStampId, grantKey, seatedKey, seatedStampId, grantSig, ownerSig]);
4596
4995
  });
4597
4996
  log('Redeemed owner grant %s: %s seated as an owner (usage %s)', grantKey, seatedKey, usageStampId);
@@ -4614,13 +5013,31 @@ export class ControlDatabase {
4614
5013
  * null handle instead of committing. The tail never rejects (it swallows both
4615
5014
  * outcomes), so the bare await is safe.
4616
5015
  *
4617
- * NOTE: this makes `close()` wait on a stuck write. Acceptable today — every locked
4618
- * body is a bounded local `exec` — but revisit (bounded drain, or abandon after a
4619
- * 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.
4620
5029
  */
4621
5030
  async close() {
4622
5031
  this.tableWatches.disposeAll();
4623
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
+ }
4624
5041
  if (this.collectionFactory) {
4625
5042
  await this.collectionFactory.shutdown();
4626
5043
  this.collectionFactory = null;
@@ -4630,10 +5047,7 @@ export class ControlDatabase {
4630
5047
  this.tableWatches.disposeAll();
4631
5048
  // Here, not first: a read started during the awaits above must not install either.
4632
5049
  this.invalidateMembershipViews();
4633
- if (this.db) {
4634
- void this.db.close();
4635
- this.db = null;
4636
- }
5050
+ this.db = null;
4637
5051
  this.initialized = false;
4638
5052
  log('ControlDatabase closed');
4639
5053
  }