@serfab/cadre-core 1.22.0 → 1.24.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 (314) hide show
  1. package/README.md +216 -294
  2. package/dist/arachnode-stub.d.ts +12 -4
  3. package/dist/arachnode-stub.js +15 -8
  4. package/dist/arachnode-stub.js.map +1 -1
  5. package/dist/cadre-invite-protocol.js +5 -4
  6. package/dist/cadre-invite-protocol.js.map +1 -1
  7. package/dist/cadre-node.d.ts +159 -53
  8. package/dist/cadre-node.js +276 -89
  9. package/dist/cadre-node.js.map +1 -1
  10. package/dist/control-authorization.d.ts +14 -2
  11. package/dist/control-authorization.js +8 -3
  12. package/dist/control-authorization.js.map +1 -1
  13. package/dist/control-cohort.d.ts +27 -13
  14. package/dist/control-cohort.js +21 -14
  15. package/dist/control-cohort.js.map +1 -1
  16. package/dist/control-database.d.ts +18 -16
  17. package/dist/control-database.js +57 -22
  18. package/dist/control-database.js.map +1 -1
  19. package/dist/control-protocol-guard.d.ts +1 -1
  20. package/dist/control-protocol-guard.js +7 -3
  21. package/dist/control-protocol-guard.js.map +1 -1
  22. package/dist/control-read-retry.d.ts +49 -11
  23. package/dist/control-read-retry.js +56 -15
  24. package/dist/control-read-retry.js.map +1 -1
  25. package/dist/control-retry.d.ts +32 -3
  26. package/dist/control-retry.js +35 -4
  27. package/dist/control-retry.js.map +1 -1
  28. package/dist/control-schema-version.d.ts +5 -5
  29. package/dist/control-schema-version.js +5 -5
  30. package/dist/control-schema-version.js.map +1 -1
  31. package/dist/control-schema.d.ts +5 -5
  32. package/dist/control-schema.js +1032 -1011
  33. package/dist/control-schema.js.map +1 -1
  34. package/dist/control-write-retry.d.ts +54 -65
  35. package/dist/control-write-retry.js +134 -158
  36. package/dist/control-write-retry.js.map +1 -1
  37. package/dist/delegate-admission.d.ts +1 -1
  38. package/dist/delegate-admission.js +1 -1
  39. package/dist/edge-node/config.d.ts +4 -3
  40. package/dist/edge-node/config.js +11 -9
  41. package/dist/edge-node/config.js.map +1 -1
  42. package/dist/edge-node/dissolve.d.ts +4 -4
  43. package/dist/edge-node/dissolve.js +4 -4
  44. package/dist/edge-node/edge-join.d.ts +1 -1
  45. package/dist/edge-node/edge-join.js +1 -1
  46. package/dist/edge-node/edge-node.js +2 -2
  47. package/dist/edge-node/edge-node.js.map +1 -1
  48. package/dist/edge-node/index.d.ts +1 -0
  49. package/dist/edge-node/index.js +1 -0
  50. package/dist/edge-node/index.js.map +1 -1
  51. package/dist/edge-node/join-credential.d.ts +1 -1
  52. package/dist/edge-node/join-credential.js +1 -1
  53. package/dist/edge-node/lazy-raw-storage.js +12 -0
  54. package/dist/edge-node/lazy-raw-storage.js.map +1 -1
  55. package/dist/edge-node/listen-addrs.d.ts +21 -0
  56. package/dist/edge-node/listen-addrs.js +25 -0
  57. package/dist/edge-node/listen-addrs.js.map +1 -0
  58. package/dist/edge-node/owner-grant.d.ts +1 -1
  59. package/dist/edge-node/owner-grant.js +1 -1
  60. package/dist/edge-node/platform.d.ts +5 -4
  61. package/dist/edge-node/platform.js.map +1 -1
  62. package/dist/edge-node/strand-move.d.ts +1 -1
  63. package/dist/edge-node/strand-move.js +1 -1
  64. package/dist/edge-node/strands.js +27 -11
  65. package/dist/edge-node/strands.js.map +1 -1
  66. package/dist/index.d.ts +7 -5
  67. package/dist/index.js +18 -7
  68. package/dist/index.js.map +1 -1
  69. package/dist/invitation-bootstrap.d.ts +28 -5
  70. package/dist/invitation-bootstrap.js +41 -8
  71. package/dist/invitation-bootstrap.js.map +1 -1
  72. package/dist/link-budget.d.ts +53 -4
  73. package/dist/link-budget.js +58 -5
  74. package/dist/link-budget.js.map +1 -1
  75. package/dist/machine-removal.d.ts +2 -2
  76. package/dist/machine-removal.js +4 -3
  77. package/dist/machine-removal.js.map +1 -1
  78. package/dist/membership-connection-gater.d.ts +2 -2
  79. package/dist/membership-connection-gater.js +2 -2
  80. package/dist/membership-view.d.ts +2 -2
  81. package/dist/membership-view.js +6 -3
  82. package/dist/membership-view.js.map +1 -1
  83. package/dist/node-claim-payload.d.ts +15 -7
  84. package/dist/node-claim-payload.js +25 -9
  85. package/dist/node-claim-payload.js.map +1 -1
  86. package/dist/node-class.d.ts +36 -0
  87. package/dist/node-class.js +26 -0
  88. package/dist/node-class.js.map +1 -0
  89. package/dist/node-default-transports.d.ts +50 -3
  90. package/dist/node-default-transports.js +48 -3
  91. package/dist/node-default-transports.js.map +1 -1
  92. package/dist/node-roles.d.ts +118 -0
  93. package/dist/node-roles.js +142 -0
  94. package/dist/node-roles.js.map +1 -0
  95. package/dist/node-transports.d.ts +6 -2
  96. package/dist/node-transports.js +39 -7
  97. package/dist/node-transports.js.map +1 -1
  98. package/dist/owner-anchor-sync.js +1 -1
  99. package/dist/owner-key-export.js +1 -1
  100. package/dist/owner-key-flows.d.ts +1 -1
  101. package/dist/owner-key-store.js +1 -1
  102. package/dist/owner-signer.js +1 -1
  103. package/dist/peer-authorization.d.ts +3 -1
  104. package/dist/peer-authorization.js +3 -1
  105. package/dist/peer-authorization.js.map +1 -1
  106. package/dist/peer-dial.d.ts +74 -10
  107. package/dist/peer-dial.js +89 -17
  108. package/dist/peer-dial.js.map +1 -1
  109. package/dist/peer-join-backfill.js +4 -4
  110. package/dist/peer-join-backfill.js.map +1 -1
  111. package/dist/peer-record.d.ts +34 -9
  112. package/dist/peer-record.js +66 -13
  113. package/dist/peer-record.js.map +1 -1
  114. package/dist/pending-join-runner.d.ts +1 -1
  115. package/dist/pending-join-runner.js +1 -1
  116. package/dist/provider/client.d.ts +6 -5
  117. package/dist/provider/client.js +3 -3
  118. package/dist/provider/client.js.map +1 -1
  119. package/dist/provider/descriptor.d.ts +1 -1
  120. package/dist/provider/descriptor.js +1 -1
  121. package/dist/provider/oauth.d.ts +1 -1
  122. package/dist/provider/oauth.js +1 -1
  123. package/dist/provider/rent-node.d.ts +4 -3
  124. package/dist/provider/rent-node.js +3 -3
  125. package/dist/provider/rent-node.js.map +1 -1
  126. package/dist/relay-addrs.d.ts +62 -7
  127. package/dist/relay-addrs.js +74 -11
  128. package/dist/relay-addrs.js.map +1 -1
  129. package/dist/relay-reservation.d.ts +1 -1
  130. package/dist/relay-reservation.js +1 -1
  131. package/dist/relay-server.d.ts +6 -5
  132. package/dist/relay-server.js +5 -5
  133. package/dist/relay-server.js.map +1 -1
  134. package/dist/schema-verification.d.ts +13 -10
  135. package/dist/schema-verification.js +32 -24
  136. package/dist/schema-verification.js.map +1 -1
  137. package/dist/sealed-party-key.js +1 -1
  138. package/dist/seed-bootstrap.d.ts +4 -3
  139. package/dist/seed-bootstrap.js +6 -7
  140. package/dist/seed-bootstrap.js.map +1 -1
  141. package/dist/strand-addr-protocol.d.ts +8 -6
  142. package/dist/strand-addr-protocol.js +12 -10
  143. package/dist/strand-addr-protocol.js.map +1 -1
  144. package/dist/strand-app-schema-report.d.ts +16 -2
  145. package/dist/strand-app-schema-report.js +15 -0
  146. package/dist/strand-app-schema-report.js.map +1 -1
  147. package/dist/strand-cohort.d.ts +1 -4
  148. package/dist/strand-cohort.js.map +1 -1
  149. package/dist/strand-commit-durability.d.ts +1 -1
  150. package/dist/strand-database.d.ts +13 -6
  151. package/dist/strand-database.js +17 -9
  152. package/dist/strand-database.js.map +1 -1
  153. package/dist/strand-first-sync-gate.d.ts +3 -2
  154. package/dist/strand-first-sync-gate.js +3 -2
  155. package/dist/strand-first-sync-gate.js.map +1 -1
  156. package/dist/strand-formation-deadlines.d.ts +2 -2
  157. package/dist/strand-formation-deadlines.js +2 -2
  158. package/dist/strand-formation-protocol.d.ts +1 -1
  159. package/dist/strand-formation-protocol.js +51 -16
  160. package/dist/strand-formation-protocol.js.map +1 -1
  161. package/dist/strand-instance-manager.d.ts +134 -42
  162. package/dist/strand-instance-manager.js +331 -76
  163. package/dist/strand-instance-manager.js.map +1 -1
  164. package/dist/strand-membership-reconciler.d.ts +8 -3
  165. package/dist/strand-membership-reconciler.js +8 -3
  166. package/dist/strand-membership-reconciler.js.map +1 -1
  167. package/dist/strand-membership-writer.d.ts +2 -2
  168. package/dist/strand-membership-writer.js +41 -39
  169. package/dist/strand-membership-writer.js.map +1 -1
  170. package/dist/strand-move.js +1 -1
  171. package/dist/strand-network-config.d.ts +15 -5
  172. package/dist/strand-network-config.js +7 -6
  173. package/dist/strand-network-config.js.map +1 -1
  174. package/dist/strand-party-key-rotation.d.ts +7 -3
  175. package/dist/strand-party-key-rotation.js +7 -3
  176. package/dist/strand-party-key-rotation.js.map +1 -1
  177. package/dist/strand-party-machines.d.ts +19 -8
  178. package/dist/strand-party-machines.js +26 -11
  179. package/dist/strand-party-machines.js.map +1 -1
  180. package/dist/strand-party-peers.d.ts +36 -14
  181. package/dist/strand-party-peers.js +24 -15
  182. package/dist/strand-party-peers.js.map +1 -1
  183. package/dist/strand-peer-redial.d.ts +1 -1
  184. package/dist/strand-peer-redial.js +1 -1
  185. package/dist/strand-reactivity.d.ts +20 -17
  186. package/dist/strand-reactivity.js +31 -18
  187. package/dist/strand-reactivity.js.map +1 -1
  188. package/dist/strand-revocation-enforcer.d.ts +3 -3
  189. package/dist/strand-revocation-enforcer.js +3 -3
  190. package/dist/strand-wake-protocol.d.ts +19 -7
  191. package/dist/strand-wake-protocol.js +22 -10
  192. package/dist/strand-wake-protocol.js.map +1 -1
  193. package/dist/strand-watcher.d.ts +1 -1
  194. package/dist/strand-watcher.js +1 -1
  195. package/dist/table-change-watch.js +1 -1
  196. package/dist/types.d.ts +127 -57
  197. package/dist/types.js.map +1 -1
  198. package/dist/webrtc-upgrade.d.ts +254 -0
  199. package/dist/webrtc-upgrade.js +355 -0
  200. package/dist/webrtc-upgrade.js.map +1 -0
  201. package/package.json +9 -9
  202. package/src/announce-addrs.ts +93 -93
  203. package/src/arachnode-stub.ts +18 -10
  204. package/src/bootstrap-peer-store-file.ts +44 -44
  205. package/src/bootstrap-peer-store.ts +214 -214
  206. package/src/cadre-invite-protocol.ts +741 -740
  207. package/src/cadre-node.ts +12462 -12252
  208. package/src/claim-proof.ts +147 -147
  209. package/src/control-authorization.ts +290 -276
  210. package/src/control-cohort.ts +223 -204
  211. package/src/control-database.ts +72 -28
  212. package/src/control-formation-recorder.ts +359 -359
  213. package/src/control-protocol-guard.ts +370 -366
  214. package/src/control-read-retry.ts +222 -180
  215. package/src/control-retry.ts +36 -4
  216. package/src/control-schema-version.ts +301 -301
  217. package/src/control-schema.ts +1108 -1087
  218. package/src/control-write-retry.ts +639 -669
  219. package/src/delegate-admission.ts +351 -351
  220. package/src/describe-thrown.ts +60 -60
  221. package/src/ed25519-key.ts +185 -185
  222. package/src/edge-node/config.ts +13 -10
  223. package/src/edge-node/dissolve.ts +252 -252
  224. package/src/edge-node/edge-join.ts +320 -320
  225. package/src/edge-node/edge-node.ts +1095 -1095
  226. package/src/edge-node/index.ts +60 -59
  227. package/src/edge-node/join-credential.ts +16 -16
  228. package/src/edge-node/lazy-raw-storage.ts +194 -178
  229. package/src/edge-node/listen-addrs.ts +26 -0
  230. package/src/edge-node/node-local.ts +84 -84
  231. package/src/edge-node/options.ts +195 -195
  232. package/src/edge-node/owner-grant.ts +63 -63
  233. package/src/edge-node/platform.ts +5 -4
  234. package/src/edge-node/strand-move.ts +266 -266
  235. package/src/edge-node/strands.ts +27 -12
  236. package/src/enrolled-machine-store-file.ts +43 -43
  237. package/src/enrolled-machine-store.ts +280 -280
  238. package/src/fetch-impl.ts +23 -23
  239. package/src/file-durable-slot.ts +64 -64
  240. package/src/file-safe-name.ts +32 -32
  241. package/src/formation-approval.ts +604 -604
  242. package/src/formation-token.ts +63 -63
  243. package/src/fs-atomic.ts +92 -92
  244. package/src/index.ts +987 -957
  245. package/src/invitation-bootstrap.ts +152 -118
  246. package/src/joined-strand-store.ts +553 -553
  247. package/src/key-store-file.ts +142 -142
  248. package/src/link-budget.ts +61 -5
  249. package/src/machine-removal.ts +211 -210
  250. package/src/member-redemption.ts +643 -643
  251. package/src/membership-connection-gater.ts +650 -650
  252. package/src/membership-view.ts +147 -144
  253. package/src/node-claim-payload.ts +34 -12
  254. package/src/node-class.ts +47 -0
  255. package/src/node-default-transports.ts +65 -3
  256. package/src/node-roles.ts +220 -0
  257. package/src/node-transports.ts +86 -49
  258. package/src/owner-anchor-sync.ts +172 -172
  259. package/src/owner-grant-protocol.ts +547 -547
  260. package/src/owner-key-export.ts +348 -348
  261. package/src/owner-key-flows.ts +109 -109
  262. package/src/owner-key-store.ts +1 -1
  263. package/src/owner-keys.ts +179 -179
  264. package/src/owner-signer.ts +92 -92
  265. package/src/peer-addr-book.ts +252 -252
  266. package/src/peer-authorization.ts +584 -582
  267. package/src/peer-dial.ts +698 -605
  268. package/src/peer-join-backfill.ts +961 -961
  269. package/src/peer-record.ts +71 -16
  270. package/src/pending-join-runner.ts +798 -798
  271. package/src/primary-lan-address.ts +47 -47
  272. package/src/provider/client.ts +327 -326
  273. package/src/provider/descriptor.ts +129 -129
  274. package/src/provider/index.ts +59 -59
  275. package/src/provider/oauth.ts +285 -285
  276. package/src/provider/rent-node.ts +276 -275
  277. package/src/relay-addrs.ts +90 -12
  278. package/src/relay-reservation.ts +1 -1
  279. package/src/relay-server.ts +99 -98
  280. package/src/schema-verification.ts +38 -23
  281. package/src/sealed-party-key.ts +190 -190
  282. package/src/seed-bootstrap.ts +8 -11
  283. package/src/seed-trust-policy.ts +353 -353
  284. package/src/self-address-update.ts +19 -19
  285. package/src/strand-addr-protocol.ts +17 -14
  286. package/src/strand-app-schema-report.ts +147 -122
  287. package/src/strand-cohort.ts +1 -5
  288. package/src/strand-commit-durability.ts +165 -165
  289. package/src/strand-database.ts +522 -510
  290. package/src/strand-first-sync-gate.ts +3 -2
  291. package/src/strand-formation-deadlines.ts +227 -227
  292. package/src/strand-formation-manager.ts +731 -731
  293. package/src/strand-formation-protocol.ts +1174 -1138
  294. package/src/strand-fret-addrs.ts +179 -179
  295. package/src/strand-instance-manager.ts +381 -85
  296. package/src/strand-membership-reconciler.ts +1315 -1310
  297. package/src/strand-membership-writer.ts +2152 -2150
  298. package/src/strand-move.ts +1 -1
  299. package/src/strand-network-config.ts +16 -6
  300. package/src/strand-offline.ts +178 -178
  301. package/src/strand-party-key-rotation.ts +440 -436
  302. package/src/strand-party-machines.ts +308 -293
  303. package/src/strand-party-peers.ts +151 -129
  304. package/src/strand-peer-redial.ts +1 -1
  305. package/src/strand-reactivity.ts +36 -19
  306. package/src/strand-revocation-enforcer.ts +758 -758
  307. package/src/strand-wake-protocol.ts +406 -394
  308. package/src/strand-watcher.ts +1 -1
  309. package/src/table-change-watch.ts +285 -285
  310. package/src/timed-step.ts +28 -28
  311. package/src/timeout-scheduler.ts +29 -29
  312. package/src/trusted-owner-store.ts +242 -242
  313. package/src/types.ts +3182 -3112
  314. package/src/webrtc-upgrade.ts +439 -0
@@ -1,436 +1,440 @@
1
- /**
2
- * Party key rotation: the driver that moves a party onto a fresh membership key in one closed
3
- * strand after a machine was removed from the cadre, so the removed machine is left holding a
4
- * key that is no longer a member there (docs/architecture.md → "Removing a machine").
5
- *
6
- * ## What it rests on
7
- *
8
- * - A `Strand.MemberPeer` binding is signed by the member key, which every machine of the
9
- * party holds, so any party machine can bind any peer id under the party's key. Which peer
10
- * ids are the party's remaining machines, and which the removed machine's, is the control
11
- * record's `StrandPeer` rows joined to the live machines (`strand-party-peers.ts`).
12
- * - The revoked-peer gate (`strand-revocation-enforcer.ts`) denies a peer id only when it has
13
- * an orphaned binding and no live one. A remaining machine bound under both the old key K and
14
- * the new key K' stays served when K leaves; the removed machine, bound under K alone, is
15
- * denied on the rows alone, with no new gate logic.
16
- * - `leaveStrand` is self-signed by the departing key, and `removeManager`'s resign branch
17
- * needs another manager standing. So K can remove itself once K' is a manager, and no second
18
- * party is involved in a strand the party manages.
19
- * - The founder bootstrap skips `Member` and `Manager` when either table has rows, so a founder
20
- * restart after a rotation never tries to re-seat K' as a founding row.
21
- *
22
- * ## Where the new key lives before it is current
23
- *
24
- * The removal transaction writes a `PendingStrandPartyKey` row per closed strand the party holds
25
- * a key for, in the same owner approval as the machine's tombstone (`ControlDatabase.removeMachine`),
26
- * so the removal and the intent to rotate are exactly as durable as each other. That same
27
- * transaction reaches the removed machine, so the row carries K' public half in the clear and its
28
- * private half sealed to the identity keys of the machines that remain (`sealed-party-key.ts`);
29
- * `CadreNode` opens it under this machine's identity key before handing it to the driver
30
- * ({@link StrandPartyKeyRotationDeps.readPending}), and a machine the key was not sealed to
31
- * cannot drive. That row is the run's input; the `StrandPartyKey` row stays K until the last step.
32
- *
33
- * ## One run
34
- *
35
- * Runs on an OWNER machine that runs the strand and can open the pending key (an owner signer is
36
- * enrolled, the instance is live with a database, the key is sealed to this machine's identity);
37
- * `CadreNode` decides that and never asks any other machine to drive.
38
- * Each run reads the pending row and the strand's rows and continues from wherever the state
39
- * says it is. Every step reads before it writes, and a duplicate-row rejection counts as done,
40
- * so two owner machines driving one strand converge:
41
- *
42
- * 1. **Clean up superseded keys.** A second removal while a rotation is pending replaced the
43
- * pending key, and the replaced key may already hold a seat (a driver seated it before the
44
- * replacement). For each public key in `Superseded` that holds a `Member` row: `removeManager`
45
- * by K if it holds a `Manager` row, then `revokeMember` by K. Its bindings become orphans
46
- * beside K's, harmless to remaining machines, which are bound under K and then K'. A
47
- * superseded key that IS the current key is skipped: another driver finished the earlier
48
- * rotation and this one continues from it.
49
- * 2. **Seat K'.** `addMemberByManager(K, K')`. When K holds no `Manager` row and K' is not yet a
50
- * member, the run stops here as `needs-another-party` (one event per pending stamp) and the
51
- * row stays: K' is seated from outside, by the membership reconciler redeeming the host's fresh
52
- * invitation under K' (`strand-membership-reconciler.ts` → "Redeeming under the pending key")
53
- * or by the strand's manager admitting K' by hand, and the reconciler kicks this driver when
54
- * it sees the seat (docs/strands.md → Replacing the party's key). The run then continues from
55
- * step 3; step 4 is skipped, since K is no manager, and step 5 is K's self-signed leave alone.
56
- * 3. **Bind under K'**: this machine's own strand peer id and every live sibling's, each
57
- * `registerMemberPeer(K', id)` (insert-if-absent). Self-signed by K', so this step also runs
58
- * after K has left.
59
- * 4. **Promote K'**: `addManager(K, K')`, when K is a manager. After the bindings, so a key that
60
- * was seated but never bound cannot exist beyond step 2.
61
- * 5. **K steps down**: `removeManager`'s resign branch signed by K (K' now stands, so the sole
62
- * manager guard does not fire), then `leaveStrand` signed by K. The removed machine's binding
63
- * under K is now the orphan; remaining machines are live under K'.
64
- * 6. **Swap the control row**, one transaction and one owner approval across every strand whose
65
- * steps 1 to 5 completed in this run ({@link StrandPartyKeyRotationDeps.swapKeys}). Deferred
66
- * while a control write could fork the party, like every background control write; the
67
- * strands are reported `pending` and the growth drain re-runs them. After the swap the
68
- * running instance is re-keyed and `strand:party-key-rotated` is emitted.
69
- *
70
- * Crash recovery is the same run: pending row present and K' not a member → step 2; K' a member
71
- * but K still one → steps 3 to 5 as needed; K gone from the strand, control still K → step 6;
72
- * no pending row → nothing. A run that finds K' already current (another driver swapped) ends.
73
- *
74
- * ## Single flight
75
- *
76
- * One run per strand at a time: a call that names a strand already being driven waits for that
77
- * run's outcome rather than starting a second. Strands in one call are prepared one after
78
- * another and swapped together.
79
- */
80
-
81
- import debug from 'debug';
82
- import type { Database } from '@quereus/quereus';
83
- import type { Ed25519KeyPair } from './ed25519-key.js';
84
- import { strandMemberKeyPair } from './strand-member-key.js';
85
- import {
86
- addManager,
87
- addMemberByManager,
88
- isStrandManager,
89
- isStrandMember,
90
- leaveStrand,
91
- listMemberPeers,
92
- registerMemberPeer,
93
- removeManager,
94
- revokeMember,
95
- type StrandWriteOptions,
96
- } from './strand-membership-writer.js';
97
- import type { StrandKeyRotationOutcome } from './types.js';
98
- import { describeThrown } from './describe-thrown.js';
99
-
100
- const log = debug('sereus:cadre:strand-party-key-rotation');
101
-
102
- /** Every strand write here runs in a transaction of its own, never joining one the app has open. */
103
- const OWN_TRANSACTION: StrandWriteOptions = { joinOpenTransaction: false };
104
-
105
- /** What became of one strand in a run ({@link StrandKeyRotationOutcome.outcome}). */
106
- export type RotationOutcome = StrandKeyRotationOutcome['outcome'];
107
-
108
- /** One strand's finished steps 1 to 5, ready for the control swap (step 6). */
109
- export interface StrandPartyKeySwapEntry {
110
- strandId: string;
111
- /** The key the control row names now, encoded as `StrandPartyKey.PrivateKey`. */
112
- oldKey: string;
113
- /** The key the strand's rows now name as the party's member, same encoding. */
114
- newKey: string;
115
- }
116
-
117
- /**
118
- * The strand's pending row with its key opened for this machine
119
- * ({@link StrandPartyKeyRotationDeps.readPending}): what `PendingStrandPartyKeyRow` carries sealed
120
- * (`sealed-party-key.ts`), in the clear, as the driver seats and binds under it.
121
- */
122
- export interface OpenedPendingPartyKey {
123
- /** The key being moved to, encoded as `StrandPartyKey.PrivateKey`. */
124
- privateKey: string;
125
- /** Public keys (base64url) of earlier pending keys the row replaced; a seat any of them holds must be revoked. */
126
- superseded: readonly string[];
127
- /** The row's single-use nonce; `needs-another-party` is reported once per stamp. */
128
- stampId: string;
129
- }
130
-
131
- /** The seams the driver reads and writes through; `CadreNode` builds one over its control database and strand manager. */
132
- export interface StrandPartyKeyRotationDeps {
133
- /**
134
- * The strand's pending row opened for this machine, or null when no rotation is pending there.
135
- * Rejects when it cannot be read, or cannot be opened here (sealed to other machines).
136
- */
137
- readPending(strandId: string): Promise<OpenedPendingPartyKey | null>;
138
- /** The strand's `StrandPartyKey.PrivateKey`, or null when the party holds no key there. */
139
- readCurrentKey(strandId: string): Promise<string | null>;
140
- /**
141
- * The strand peer ids of the party's other live machines in the strand
142
- * (`PartyStrandPeers.live`), read fresh. Rejects when they cannot be read.
143
- */
144
- readSiblingPeerIds(strandId: string): Promise<readonly string[]>;
145
- /** The strand's live database, read per step; `undefined` means the strand does not run here now. */
146
- getDatabase(strandId: string): Database | undefined;
147
- /** This machine's own peer id in the strand, read per step. */
148
- getOwnPeerId(strandId: string): string | undefined;
149
- /**
150
- * Step 6: the control-row swap for every entry, one transaction and one owner approval.
151
- * Resolves the strand ids actually swapped (an entry another driver already swapped is
152
- * skipped), or `'deferred'` when a control write now could fork the party.
153
- */
154
- swapKeys(entries: readonly StrandPartyKeySwapEntry[]): Promise<readonly string[] | 'deferred'>;
155
- /** After the swap committed: re-key the running instance and tell the app. */
156
- onRotated(strandId: string, newKey: string): Promise<void>;
157
- /** Step 2 found no manager seat for the party; once per pending stamp. */
158
- onBlocked(strandId: string, reason: 'needs-another-party'): void;
159
- }
160
-
161
- /** How far one strand got before the swap. */
162
- type Prepared =
163
- | { kind: 'ready'; entry: StrandPartyKeySwapEntry }
164
- | { kind: 'blocked'; stampId: string }
165
- | { kind: 'nothing' }
166
- | { kind: 'failed'; error: unknown };
167
-
168
- /** The rows of one strand a run reads before it writes. */
169
- interface RotationState {
170
- oldKey: Ed25519KeyPair;
171
- newKey: Ed25519KeyPair;
172
- oldIsMember: boolean;
173
- oldIsManager: boolean;
174
- newIsMember: boolean;
175
- newIsManager: boolean;
176
- }
177
-
178
- export class StrandPartyKeyRotationDriver {
179
- /** The run in flight per strand; a call naming the strand joins it. */
180
- private readonly inFlight = new Map<string, Promise<RotationOutcome>>();
181
- /** The pending stamp each strand's `needs-another-party` was last reported for. */
182
- private readonly reportedBlocked = new Map<string, string>();
183
-
184
- constructor(private readonly deps: StrandPartyKeyRotationDeps) {}
185
-
186
- /**
187
- * Drive every strand in `strandIds` through the steps its state calls for, then swap the
188
- * control rows of the ones that finished in one transaction. Never rejects: a strand whose
189
- * step failed is `pending` with a log, and the next trigger re-runs it.
190
- */
191
- async drive(strandIds: readonly string[], cause: string): Promise<StrandKeyRotationOutcome[]> {
192
- const ids = [...new Set(strandIds)];
193
- const joined = ids.filter((strandId) => this.inFlight.has(strandId));
194
- const fresh = ids.filter((strandId) => !this.inFlight.has(strandId));
195
- const outcomes = new Map<string, RotationOutcome>();
196
- if (fresh.length > 0) {
197
- for (const [strandId, outcome] of await this.startRun(fresh, cause)) {
198
- outcomes.set(strandId, outcome);
199
- }
200
- }
201
- if (joined.length > 0) {
202
- // The run in flight read its pending rows before this call was made, so a row written
203
- // since (a second removal) would otherwise wait for the next trigger: the joined strands
204
- // are driven again once it ends. A strand with nothing left costs one pending read.
205
- await Promise.all(joined.map((strandId) => this.inFlight.get(strandId)));
206
- for (const outcome of await this.drive(joined, cause)) {
207
- outcomes.set(outcome.strandId, outcome.outcome);
208
- }
209
- }
210
- return ids.map((strandId) => ({ strandId, outcome: outcomes.get(strandId) ?? 'pending' }));
211
- }
212
-
213
- /** Start one run and register it as the run in flight for each of its strands until it ends. `run` never rejects, so neither does the registration. */
214
- private startRun(strandIds: readonly string[], cause: string): Promise<Map<string, RotationOutcome>> {
215
- const run = this.run(strandIds, cause);
216
- for (const strandId of strandIds) {
217
- const own = run.then((result) => result.get(strandId) ?? 'pending');
218
- this.inFlight.set(strandId, own);
219
- void own.finally(() => {
220
- if (this.inFlight.get(strandId) === own) {
221
- this.inFlight.delete(strandId);
222
- }
223
- });
224
- }
225
- return run;
226
- }
227
-
228
- /** Steps 1 to 5 per strand, then one swap over the ready ones. */
229
- private async run(strandIds: readonly string[], cause: string): Promise<Map<string, RotationOutcome>> {
230
- log('Party key rotation run over %d strand(s) (%s)', strandIds.length, cause);
231
- const outcomes = new Map<string, RotationOutcome>();
232
- const ready: StrandPartyKeySwapEntry[] = [];
233
- for (const strandId of strandIds) {
234
- const prepared = await this.prepare(strandId);
235
- switch (prepared.kind) {
236
- case 'ready':
237
- ready.push(prepared.entry);
238
- break;
239
- case 'blocked':
240
- outcomes.set(strandId, 'needs-another-party');
241
- this.reportBlocked(strandId, prepared.stampId);
242
- break;
243
- case 'nothing':
244
- outcomes.set(strandId, 'rotated');
245
- break;
246
- case 'failed':
247
- outcomes.set(strandId, 'pending');
248
- log('Party key rotation of strand %s left unfinished (retried on the next trigger): %s', strandId, describeThrown(prepared.error));
249
- break;
250
- }
251
- }
252
- for (const [strandId, outcome] of await this.swap(ready)) {
253
- outcomes.set(strandId, outcome);
254
- }
255
- return outcomes;
256
- }
257
-
258
- /** Step 6 for every ready strand, then the re-key of each one swapped. */
259
- private async swap(ready: readonly StrandPartyKeySwapEntry[]): Promise<Map<string, RotationOutcome>> {
260
- const outcomes = new Map<string, RotationOutcome>();
261
- if (ready.length === 0) {
262
- return outcomes;
263
- }
264
- let swapped: readonly string[];
265
- try {
266
- const result = await this.deps.swapKeys(ready);
267
- if (result === 'deferred') {
268
- log('Party key swap of %d strand(s) deferred: no sibling reachable and the party has other members; re-run on growth', ready.length);
269
- for (const entry of ready) {
270
- outcomes.set(entry.strandId, 'pending');
271
- }
272
- return outcomes;
273
- }
274
- swapped = result;
275
- } catch (error) {
276
- log('Party key swap of %d strand(s) failed (retried on the next trigger): %s', ready.length, describeThrown(error));
277
- for (const entry of ready) {
278
- outcomes.set(entry.strandId, 'pending');
279
- }
280
- return outcomes;
281
- }
282
- for (const entry of ready) {
283
- // An entry the swap skipped names a key already current (another driver swapped it), or a
284
- // row that moved on; either way the strand's rows are on the new key, so it is rotated.
285
- outcomes.set(entry.strandId, 'rotated');
286
- if (swapped.includes(entry.strandId)) {
287
- await this.notifyRotated(entry);
288
- }
289
- }
290
- return outcomes;
291
- }
292
-
293
- /**
294
- * The re-key after a committed swap. A failure is logged and the strand stays `rotated`: the
295
- * control row names the new key, and the party key watch re-keys the instance from it on its
296
- * next run (`CadreNode.onPartyKeyTablesChanged`).
297
- */
298
- private async notifyRotated(entry: StrandPartyKeySwapEntry): Promise<void> {
299
- try {
300
- await this.deps.onRotated(entry.strandId, entry.newKey);
301
- } catch (error) {
302
- log('Party key rotation of strand %s: re-keying the running instance after the swap failed (the party key watch retries it): %s', entry.strandId, describeThrown(error));
303
- }
304
- }
305
-
306
- /** Steps 1 to 5 for one strand, from the state its rows are in. */
307
- private async prepare(strandId: string): Promise<Prepared> {
308
- try {
309
- const pending = await this.deps.readPending(strandId);
310
- if (pending === null) {
311
- return { kind: 'nothing' };
312
- }
313
- const current = await this.deps.readCurrentKey(strandId);
314
- if (current === null) {
315
- log('Party key rotation of strand %s: the party holds no key there; nothing to rotate', strandId);
316
- return { kind: 'nothing' };
317
- }
318
- if (current === pending.privateKey) {
319
- return { kind: 'nothing' };
320
- }
321
- const db = this.deps.getDatabase(strandId);
322
- if (db === undefined) {
323
- return { kind: 'failed', error: new Error('the strand does not run here now') };
324
- }
325
- const state = await readRotationState(db, current, pending.privateKey);
326
- await this.cleanUpSuperseded(db, state, pending.superseded);
327
- if (!state.newIsMember) {
328
- if (!state.oldIsManager) {
329
- return { kind: 'blocked', stampId: pending.stampId };
330
- }
331
- await addMemberByManager(db, { managerKeyPair: state.oldKey, memberKey: state.newKey.publicKeyB64 }, OWN_TRANSACTION);
332
- log('Party key rotation of strand %s: new key seated as member', strandId);
333
- }
334
- await this.bindMachines(strandId, db, state.newKey);
335
- if (state.oldIsManager && !state.newIsManager) {
336
- await addManager(db, { byManagerKeyPair: state.oldKey, newManagerKey: state.newKey.publicKeyB64 }, OWN_TRANSACTION);
337
- log('Party key rotation of strand %s: new key promoted to manager', strandId);
338
- }
339
- await stepDown(db, state);
340
- return { kind: 'ready', entry: { strandId, oldKey: current, newKey: pending.privateKey } };
341
- } catch (error) {
342
- return { kind: 'failed', error };
343
- }
344
- }
345
-
346
- /**
347
- * Step 1: a superseded key holding a seat is revoked by K. Skips the current key itself
348
- * (another driver finished the rotation it was pending for) and, when K holds no manager seat,
349
- * leaves the seat with a log for the other party's manager.
350
- *
351
- * NOTE: a superseded key that holds a seat in a strand the party does not manage can only be
352
- * revoked by that strand's manager: the row carries superseded PUBLIC halves only, so this
353
- * driver cannot `leaveStrand` as that key. Fine now, since reaching it takes a second removal
354
- * between the host's re-admission of the first pending key and the swap that follows it within
355
- * seconds on the redeeming owner machine. If it is ever hit, seal the superseded private halves
356
- * into the row too, so the driver can self-leave them.
357
- */
358
- private async cleanUpSuperseded(db: Database, state: RotationState, superseded: readonly string[]): Promise<void> {
359
- for (const key of superseded) {
360
- if (key === state.oldKey.publicKeyB64 || key === state.newKey.publicKeyB64 || !await isStrandMember(db, key)) {
361
- continue;
362
- }
363
- if (!state.oldIsManager) {
364
- log('Superseded party key %s still holds a seat and this party has no manager seat to revoke it; left for the other party\'s manager', key);
365
- continue;
366
- }
367
- if (await isStrandManager(db, key)) {
368
- await removeManager(db, { byManagerKeyPair: state.oldKey, targetManagerKey: key }, OWN_TRANSACTION);
369
- }
370
- await revokeMember(db, { managerKeyPair: state.oldKey, memberKey: key }, OWN_TRANSACTION);
371
- log('Superseded party key %s revoked', key);
372
- }
373
- }
374
-
375
- /** Step 3: every remaining machine's peer id bound under the new key; bindings already present are skipped. */
376
- private async bindMachines(strandId: string, db: Database, newKey: Ed25519KeyPair): Promise<void> {
377
- const own = this.deps.getOwnPeerId(strandId);
378
- const ids = new Set(await this.deps.readSiblingPeerIds(strandId));
379
- if (own !== undefined) {
380
- ids.add(own);
381
- }
382
- const bound = new Set(await listMemberPeers(db, newKey.publicKeyB64));
383
- for (const peerId of ids) {
384
- if (!bound.has(peerId)) {
385
- await registerMemberPeer(db, { memberKeyPair: newKey, peerId }, OWN_TRANSACTION);
386
- log('Party key rotation of strand %s: %s bound under the new key', strandId, peerId);
387
- }
388
- }
389
- }
390
-
391
- private reportBlocked(strandId: string, stampId: string): void {
392
- if (this.reportedBlocked.get(strandId) === stampId) {
393
- return;
394
- }
395
- this.reportedBlocked.set(strandId, stampId);
396
- log('Party key rotation of strand %s blocked: this party holds no manager seat there, so another party\'s manager has to admit the new key', strandId);
397
- try {
398
- this.deps.onBlocked(strandId, 'needs-another-party');
399
- } catch (error) {
400
- log('Party key rotation of strand %s: the blocked report threw: %s', strandId, describeThrown(error));
401
- }
402
- }
403
- }
404
-
405
- /** The rows steps 1 to 5 decide from, read before any write. */
406
- async function readRotationState(db: Database, currentKey: string, pendingKey: string): Promise<RotationState> {
407
- const oldKey = strandMemberKeyPair(currentKey);
408
- const newKey = strandMemberKeyPair(pendingKey);
409
- return {
410
- oldKey,
411
- newKey,
412
- oldIsMember: await isStrandMember(db, oldKey.publicKeyB64),
413
- oldIsManager: await isStrandManager(db, oldKey.publicKeyB64),
414
- newIsMember: await isStrandMember(db, newKey.publicKeyB64),
415
- newIsManager: await isStrandManager(db, newKey.publicKeyB64),
416
- };
417
- }
418
-
419
- /**
420
- * Step 5: K resigns its manager seat, then leaves. Both writers are no-ops over an absent row,
421
- * so a run that finds K already gone writes nothing here. The resign runs only when K' holds a
422
- * manager seat, so the strand never loses its last manager to this step.
423
- */
424
- async function stepDown(db: Database, state: RotationState): Promise<void> {
425
- if (!state.oldIsMember) {
426
- return;
427
- }
428
- if (state.oldIsManager) {
429
- if (!await isStrandManager(db, state.newKey.publicKeyB64)) {
430
- throw new Error('the new party key holds no manager seat, so the old key cannot resign without emptying the strand\'s managers');
431
- }
432
- await removeManager(db, { byManagerKeyPair: state.oldKey, targetManagerKey: state.oldKey.publicKeyB64 }, OWN_TRANSACTION);
433
- }
434
- await leaveStrand(db, { memberKeyPair: state.oldKey }, OWN_TRANSACTION);
435
- log('Old party key %s left the strand', state.oldKey.publicKeyB64);
436
- }
1
+ /**
2
+ * Party key rotation: the driver that moves a party onto a fresh membership key in one closed
3
+ * strand after a machine was removed from the cadre, so the removed machine is left holding a
4
+ * key that is no longer a member there (docs/cadre/membership.md → "Removing a machine").
5
+ *
6
+ * ## What it rests on
7
+ *
8
+ * - A `Strand.MemberPeer` binding is signed by the member key, which every machine of the
9
+ * party holds, so any party machine can bind any peer id under the party's key. Which peer
10
+ * ids are the party's remaining machines, and which the removed machine's, is the control
11
+ * record's `StrandPeer` rows joined to the live machines (`strand-party-peers.ts`).
12
+ * - The revoked-peer gate (`strand-revocation-enforcer.ts`) denies a peer id only when it has
13
+ * an orphaned binding and no live one. A remaining machine bound under both the old key K and
14
+ * the new key K' stays served when K leaves; the removed machine, bound under K alone, is
15
+ * denied on the rows alone, with no new gate logic.
16
+ * - `leaveStrand` is self-signed by the departing key, and `removeManager`'s resign branch
17
+ * needs another manager standing. So K can remove itself once K' is a manager, and no second
18
+ * party is involved in a strand the party manages.
19
+ * - The founder bootstrap skips `Member` and `Manager` when either table has rows, so a founder
20
+ * restart after a rotation never tries to re-seat K' as a founding row.
21
+ *
22
+ * ## Where the new key lives before it is current
23
+ *
24
+ * The removal transaction writes a `PendingStrandPartyKey` row per closed strand the party holds
25
+ * a key for, in the same owner approval as the machine's tombstone (`ControlDatabase.removeMachine`),
26
+ * so the removal and the intent to rotate are exactly as durable as each other. That same
27
+ * transaction reaches the removed machine, so the row carries K' public half in the clear and its
28
+ * private half sealed to the identity keys of the machines that remain (`sealed-party-key.ts`);
29
+ * `CadreNode` opens it under this machine's identity key before handing it to the driver
30
+ * ({@link StrandPartyKeyRotationDeps.readPending}), and a machine the key was not sealed to
31
+ * cannot drive. That row is the run's input; the `StrandPartyKey` row stays K until the last step.
32
+ *
33
+ * ## One run
34
+ *
35
+ * Runs on an OWNER machine that runs the strand and can open the pending key (an owner signer is
36
+ * enrolled, the instance is live with a database, the key is sealed to this machine's identity);
37
+ * `CadreNode` decides that and never asks any other machine to drive.
38
+ * Each run reads the pending row and the strand's rows and continues from wherever the state
39
+ * says it is. Every step reads before it writes, and a duplicate-row rejection counts as done,
40
+ * so two owner machines driving one strand converge:
41
+ *
42
+ * 1. **Clean up superseded keys.** A second removal while a rotation is pending replaced the
43
+ * pending key, and the replaced key may already hold a seat (a driver seated it before the
44
+ * replacement). For each public key in `Superseded` that holds a `Member` row: `removeManager`
45
+ * by K if it holds a `Manager` row, then `revokeMember` by K. Its bindings become orphans
46
+ * beside K's, harmless to remaining machines, which are bound under K and then K'. A
47
+ * superseded key that IS the current key is skipped: another driver finished the earlier
48
+ * rotation and this one continues from it.
49
+ * 2. **Seat K'.** `addMemberByManager(K, K')`. When K holds no `Manager` row and K' is not yet a
50
+ * member, the run stops here as `needs-another-party` (one event per pending stamp) and the
51
+ * row stays: K' is seated from outside, by the membership reconciler redeeming the host's fresh
52
+ * invitation under K' (`strand-membership-reconciler.ts` → "Redeeming under the pending key")
53
+ * or by the strand's manager admitting K' by hand, and the reconciler kicks this driver when
54
+ * it sees the seat (docs/strands/keys.md → Replacing the party's key). The run then continues from
55
+ * step 3; step 4 is skipped, since K is no manager, and step 5 is K's self-signed leave alone.
56
+ * 3. **Bind under K'**: this machine's own strand peer id and every live sibling's, each
57
+ * `registerMemberPeer(K', id)` (insert-if-absent). Self-signed by K', so this step also runs
58
+ * after K has left. Every live machine, whether it stores the strand's blocks or runs it as a
59
+ * client: a machine left unbound here is refused by the party's serving machines once K leaves
60
+ * and cannot write its own binding to recover (`docs/strands/membership.md` → "Binding the
61
+ * party's machines"). The one machine this can miss is one whose `StrandPeer` row has not
62
+ * reached this node yet; a sibling's membership loop binds it under K' when the row arrives.
63
+ * 4. **Promote K'**: `addManager(K, K')`, when K is a manager. After the bindings, so a key that
64
+ * was seated but never bound cannot exist beyond step 2.
65
+ * 5. **K steps down**: `removeManager`'s resign branch signed by K (K' now stands, so the sole
66
+ * manager guard does not fire), then `leaveStrand` signed by K. The removed machine's binding
67
+ * under K is now the orphan; remaining machines are live under K'.
68
+ * 6. **Swap the control row**, one transaction and one owner approval across every strand whose
69
+ * steps 1 to 5 completed in this run ({@link StrandPartyKeyRotationDeps.swapKeys}). Deferred
70
+ * while a control write could fork the party, like every background control write; the
71
+ * strands are reported `pending` and the growth drain re-runs them. After the swap the
72
+ * running instance is re-keyed and `strand:party-key-rotated` is emitted.
73
+ *
74
+ * Crash recovery is the same run: pending row present and K' not a member → step 2; K' a member
75
+ * but K still one → steps 3 to 5 as needed; K gone from the strand, control still K → step 6;
76
+ * no pending row → nothing. A run that finds K' already current (another driver swapped) ends.
77
+ *
78
+ * ## Single flight
79
+ *
80
+ * One run per strand at a time: a call that names a strand already being driven waits for that
81
+ * run's outcome rather than starting a second. Strands in one call are prepared one after
82
+ * another and swapped together.
83
+ */
84
+
85
+ import debug from 'debug';
86
+ import type { Database } from '@quereus/quereus';
87
+ import type { Ed25519KeyPair } from './ed25519-key.js';
88
+ import { strandMemberKeyPair } from './strand-member-key.js';
89
+ import {
90
+ addManager,
91
+ addMemberByManager,
92
+ isStrandManager,
93
+ isStrandMember,
94
+ leaveStrand,
95
+ listMemberPeers,
96
+ registerMemberPeer,
97
+ removeManager,
98
+ revokeMember,
99
+ type StrandWriteOptions,
100
+ } from './strand-membership-writer.js';
101
+ import type { StrandKeyRotationOutcome } from './types.js';
102
+ import { describeThrown } from './describe-thrown.js';
103
+
104
+ const log = debug('sereus:cadre:strand-party-key-rotation');
105
+
106
+ /** Every strand write here runs in a transaction of its own, never joining one the app has open. */
107
+ const OWN_TRANSACTION: StrandWriteOptions = { joinOpenTransaction: false };
108
+
109
+ /** What became of one strand in a run ({@link StrandKeyRotationOutcome.outcome}). */
110
+ export type RotationOutcome = StrandKeyRotationOutcome['outcome'];
111
+
112
+ /** One strand's finished steps 1 to 5, ready for the control swap (step 6). */
113
+ export interface StrandPartyKeySwapEntry {
114
+ strandId: string;
115
+ /** The key the control row names now, encoded as `StrandPartyKey.PrivateKey`. */
116
+ oldKey: string;
117
+ /** The key the strand's rows now name as the party's member, same encoding. */
118
+ newKey: string;
119
+ }
120
+
121
+ /**
122
+ * The strand's pending row with its key opened for this machine
123
+ * ({@link StrandPartyKeyRotationDeps.readPending}): what `PendingStrandPartyKeyRow` carries sealed
124
+ * (`sealed-party-key.ts`), in the clear, as the driver seats and binds under it.
125
+ */
126
+ export interface OpenedPendingPartyKey {
127
+ /** The key being moved to, encoded as `StrandPartyKey.PrivateKey`. */
128
+ privateKey: string;
129
+ /** Public keys (base64url) of earlier pending keys the row replaced; a seat any of them holds must be revoked. */
130
+ superseded: readonly string[];
131
+ /** The row's single-use nonce; `needs-another-party` is reported once per stamp. */
132
+ stampId: string;
133
+ }
134
+
135
+ /** The seams the driver reads and writes through; `CadreNode` builds one over its control database and strand manager. */
136
+ export interface StrandPartyKeyRotationDeps {
137
+ /**
138
+ * The strand's pending row opened for this machine, or null when no rotation is pending there.
139
+ * Rejects when it cannot be read, or cannot be opened here (sealed to other machines).
140
+ */
141
+ readPending(strandId: string): Promise<OpenedPendingPartyKey | null>;
142
+ /** The strand's `StrandPartyKey.PrivateKey`, or null when the party holds no key there. */
143
+ readCurrentKey(strandId: string): Promise<string | null>;
144
+ /**
145
+ * The strand peer ids of the party's other live machines in the strand
146
+ * (`PartyStrandPeers.live`), read fresh. Rejects when they cannot be read.
147
+ */
148
+ readSiblingPeerIds(strandId: string): Promise<readonly string[]>;
149
+ /** The strand's live database, read per step; `undefined` means the strand does not run here now. */
150
+ getDatabase(strandId: string): Database | undefined;
151
+ /** This machine's own peer id in the strand, read per step. */
152
+ getOwnPeerId(strandId: string): string | undefined;
153
+ /**
154
+ * Step 6: the control-row swap for every entry, one transaction and one owner approval.
155
+ * Resolves the strand ids actually swapped (an entry another driver already swapped is
156
+ * skipped), or `'deferred'` when a control write now could fork the party.
157
+ */
158
+ swapKeys(entries: readonly StrandPartyKeySwapEntry[]): Promise<readonly string[] | 'deferred'>;
159
+ /** After the swap committed: re-key the running instance and tell the app. */
160
+ onRotated(strandId: string, newKey: string): Promise<void>;
161
+ /** Step 2 found no manager seat for the party; once per pending stamp. */
162
+ onBlocked(strandId: string, reason: 'needs-another-party'): void;
163
+ }
164
+
165
+ /** How far one strand got before the swap. */
166
+ type Prepared =
167
+ | { kind: 'ready'; entry: StrandPartyKeySwapEntry }
168
+ | { kind: 'blocked'; stampId: string }
169
+ | { kind: 'nothing' }
170
+ | { kind: 'failed'; error: unknown };
171
+
172
+ /** The rows of one strand a run reads before it writes. */
173
+ interface RotationState {
174
+ oldKey: Ed25519KeyPair;
175
+ newKey: Ed25519KeyPair;
176
+ oldIsMember: boolean;
177
+ oldIsManager: boolean;
178
+ newIsMember: boolean;
179
+ newIsManager: boolean;
180
+ }
181
+
182
+ export class StrandPartyKeyRotationDriver {
183
+ /** The run in flight per strand; a call naming the strand joins it. */
184
+ private readonly inFlight = new Map<string, Promise<RotationOutcome>>();
185
+ /** The pending stamp each strand's `needs-another-party` was last reported for. */
186
+ private readonly reportedBlocked = new Map<string, string>();
187
+
188
+ constructor(private readonly deps: StrandPartyKeyRotationDeps) {}
189
+
190
+ /**
191
+ * Drive every strand in `strandIds` through the steps its state calls for, then swap the
192
+ * control rows of the ones that finished in one transaction. Never rejects: a strand whose
193
+ * step failed is `pending` with a log, and the next trigger re-runs it.
194
+ */
195
+ async drive(strandIds: readonly string[], cause: string): Promise<StrandKeyRotationOutcome[]> {
196
+ const ids = [...new Set(strandIds)];
197
+ const joined = ids.filter((strandId) => this.inFlight.has(strandId));
198
+ const fresh = ids.filter((strandId) => !this.inFlight.has(strandId));
199
+ const outcomes = new Map<string, RotationOutcome>();
200
+ if (fresh.length > 0) {
201
+ for (const [strandId, outcome] of await this.startRun(fresh, cause)) {
202
+ outcomes.set(strandId, outcome);
203
+ }
204
+ }
205
+ if (joined.length > 0) {
206
+ // The run in flight read its pending rows before this call was made, so a row written
207
+ // since (a second removal) would otherwise wait for the next trigger: the joined strands
208
+ // are driven again once it ends. A strand with nothing left costs one pending read.
209
+ await Promise.all(joined.map((strandId) => this.inFlight.get(strandId)));
210
+ for (const outcome of await this.drive(joined, cause)) {
211
+ outcomes.set(outcome.strandId, outcome.outcome);
212
+ }
213
+ }
214
+ return ids.map((strandId) => ({ strandId, outcome: outcomes.get(strandId) ?? 'pending' }));
215
+ }
216
+
217
+ /** Start one run and register it as the run in flight for each of its strands until it ends. `run` never rejects, so neither does the registration. */
218
+ private startRun(strandIds: readonly string[], cause: string): Promise<Map<string, RotationOutcome>> {
219
+ const run = this.run(strandIds, cause);
220
+ for (const strandId of strandIds) {
221
+ const own = run.then((result) => result.get(strandId) ?? 'pending');
222
+ this.inFlight.set(strandId, own);
223
+ void own.finally(() => {
224
+ if (this.inFlight.get(strandId) === own) {
225
+ this.inFlight.delete(strandId);
226
+ }
227
+ });
228
+ }
229
+ return run;
230
+ }
231
+
232
+ /** Steps 1 to 5 per strand, then one swap over the ready ones. */
233
+ private async run(strandIds: readonly string[], cause: string): Promise<Map<string, RotationOutcome>> {
234
+ log('Party key rotation run over %d strand(s) (%s)', strandIds.length, cause);
235
+ const outcomes = new Map<string, RotationOutcome>();
236
+ const ready: StrandPartyKeySwapEntry[] = [];
237
+ for (const strandId of strandIds) {
238
+ const prepared = await this.prepare(strandId);
239
+ switch (prepared.kind) {
240
+ case 'ready':
241
+ ready.push(prepared.entry);
242
+ break;
243
+ case 'blocked':
244
+ outcomes.set(strandId, 'needs-another-party');
245
+ this.reportBlocked(strandId, prepared.stampId);
246
+ break;
247
+ case 'nothing':
248
+ outcomes.set(strandId, 'rotated');
249
+ break;
250
+ case 'failed':
251
+ outcomes.set(strandId, 'pending');
252
+ log('Party key rotation of strand %s left unfinished (retried on the next trigger): %s', strandId, describeThrown(prepared.error));
253
+ break;
254
+ }
255
+ }
256
+ for (const [strandId, outcome] of await this.swap(ready)) {
257
+ outcomes.set(strandId, outcome);
258
+ }
259
+ return outcomes;
260
+ }
261
+
262
+ /** Step 6 for every ready strand, then the re-key of each one swapped. */
263
+ private async swap(ready: readonly StrandPartyKeySwapEntry[]): Promise<Map<string, RotationOutcome>> {
264
+ const outcomes = new Map<string, RotationOutcome>();
265
+ if (ready.length === 0) {
266
+ return outcomes;
267
+ }
268
+ let swapped: readonly string[];
269
+ try {
270
+ const result = await this.deps.swapKeys(ready);
271
+ if (result === 'deferred') {
272
+ log('Party key swap of %d strand(s) deferred: no sibling reachable and the party has other members; re-run on growth', ready.length);
273
+ for (const entry of ready) {
274
+ outcomes.set(entry.strandId, 'pending');
275
+ }
276
+ return outcomes;
277
+ }
278
+ swapped = result;
279
+ } catch (error) {
280
+ log('Party key swap of %d strand(s) failed (retried on the next trigger): %s', ready.length, describeThrown(error));
281
+ for (const entry of ready) {
282
+ outcomes.set(entry.strandId, 'pending');
283
+ }
284
+ return outcomes;
285
+ }
286
+ for (const entry of ready) {
287
+ // An entry the swap skipped names a key already current (another driver swapped it), or a
288
+ // row that moved on; either way the strand's rows are on the new key, so it is rotated.
289
+ outcomes.set(entry.strandId, 'rotated');
290
+ if (swapped.includes(entry.strandId)) {
291
+ await this.notifyRotated(entry);
292
+ }
293
+ }
294
+ return outcomes;
295
+ }
296
+
297
+ /**
298
+ * The re-key after a committed swap. A failure is logged and the strand stays `rotated`: the
299
+ * control row names the new key, and the party key watch re-keys the instance from it on its
300
+ * next run (`CadreNode.onPartyKeyTablesChanged`).
301
+ */
302
+ private async notifyRotated(entry: StrandPartyKeySwapEntry): Promise<void> {
303
+ try {
304
+ await this.deps.onRotated(entry.strandId, entry.newKey);
305
+ } catch (error) {
306
+ log('Party key rotation of strand %s: re-keying the running instance after the swap failed (the party key watch retries it): %s', entry.strandId, describeThrown(error));
307
+ }
308
+ }
309
+
310
+ /** Steps 1 to 5 for one strand, from the state its rows are in. */
311
+ private async prepare(strandId: string): Promise<Prepared> {
312
+ try {
313
+ const pending = await this.deps.readPending(strandId);
314
+ if (pending === null) {
315
+ return { kind: 'nothing' };
316
+ }
317
+ const current = await this.deps.readCurrentKey(strandId);
318
+ if (current === null) {
319
+ log('Party key rotation of strand %s: the party holds no key there; nothing to rotate', strandId);
320
+ return { kind: 'nothing' };
321
+ }
322
+ if (current === pending.privateKey) {
323
+ return { kind: 'nothing' };
324
+ }
325
+ const db = this.deps.getDatabase(strandId);
326
+ if (db === undefined) {
327
+ return { kind: 'failed', error: new Error('the strand does not run here now') };
328
+ }
329
+ const state = await readRotationState(db, current, pending.privateKey);
330
+ await this.cleanUpSuperseded(db, state, pending.superseded);
331
+ if (!state.newIsMember) {
332
+ if (!state.oldIsManager) {
333
+ return { kind: 'blocked', stampId: pending.stampId };
334
+ }
335
+ await addMemberByManager(db, { managerKeyPair: state.oldKey, memberKey: state.newKey.publicKeyB64 }, OWN_TRANSACTION);
336
+ log('Party key rotation of strand %s: new key seated as member', strandId);
337
+ }
338
+ await this.bindMachines(strandId, db, state.newKey);
339
+ if (state.oldIsManager && !state.newIsManager) {
340
+ await addManager(db, { byManagerKeyPair: state.oldKey, newManagerKey: state.newKey.publicKeyB64 }, OWN_TRANSACTION);
341
+ log('Party key rotation of strand %s: new key promoted to manager', strandId);
342
+ }
343
+ await stepDown(db, state);
344
+ return { kind: 'ready', entry: { strandId, oldKey: current, newKey: pending.privateKey } };
345
+ } catch (error) {
346
+ return { kind: 'failed', error };
347
+ }
348
+ }
349
+
350
+ /**
351
+ * Step 1: a superseded key holding a seat is revoked by K. Skips the current key itself
352
+ * (another driver finished the rotation it was pending for) and, when K holds no manager seat,
353
+ * leaves the seat with a log for the other party's manager.
354
+ *
355
+ * NOTE: a superseded key that holds a seat in a strand the party does not manage can only be
356
+ * revoked by that strand's manager: the row carries superseded PUBLIC halves only, so this
357
+ * driver cannot `leaveStrand` as that key. Fine now, since reaching it takes a second removal
358
+ * between the host's re-admission of the first pending key and the swap that follows it within
359
+ * seconds on the redeeming owner machine. If it is ever hit, seal the superseded private halves
360
+ * into the row too, so the driver can self-leave them.
361
+ */
362
+ private async cleanUpSuperseded(db: Database, state: RotationState, superseded: readonly string[]): Promise<void> {
363
+ for (const key of superseded) {
364
+ if (key === state.oldKey.publicKeyB64 || key === state.newKey.publicKeyB64 || !await isStrandMember(db, key)) {
365
+ continue;
366
+ }
367
+ if (!state.oldIsManager) {
368
+ log('Superseded party key %s still holds a seat and this party has no manager seat to revoke it; left for the other party\'s manager', key);
369
+ continue;
370
+ }
371
+ if (await isStrandManager(db, key)) {
372
+ await removeManager(db, { byManagerKeyPair: state.oldKey, targetManagerKey: key }, OWN_TRANSACTION);
373
+ }
374
+ await revokeMember(db, { managerKeyPair: state.oldKey, memberKey: key }, OWN_TRANSACTION);
375
+ log('Superseded party key %s revoked', key);
376
+ }
377
+ }
378
+
379
+ /** Step 3: every remaining machine's peer id bound under the new key; bindings already present are skipped. */
380
+ private async bindMachines(strandId: string, db: Database, newKey: Ed25519KeyPair): Promise<void> {
381
+ const own = this.deps.getOwnPeerId(strandId);
382
+ const ids = new Set(await this.deps.readSiblingPeerIds(strandId));
383
+ if (own !== undefined) {
384
+ ids.add(own);
385
+ }
386
+ const bound = new Set(await listMemberPeers(db, newKey.publicKeyB64));
387
+ for (const peerId of ids) {
388
+ if (!bound.has(peerId)) {
389
+ await registerMemberPeer(db, { memberKeyPair: newKey, peerId }, OWN_TRANSACTION);
390
+ log('Party key rotation of strand %s: %s bound under the new key', strandId, peerId);
391
+ }
392
+ }
393
+ }
394
+
395
+ private reportBlocked(strandId: string, stampId: string): void {
396
+ if (this.reportedBlocked.get(strandId) === stampId) {
397
+ return;
398
+ }
399
+ this.reportedBlocked.set(strandId, stampId);
400
+ log('Party key rotation of strand %s blocked: this party holds no manager seat there, so another party\'s manager has to admit the new key', strandId);
401
+ try {
402
+ this.deps.onBlocked(strandId, 'needs-another-party');
403
+ } catch (error) {
404
+ log('Party key rotation of strand %s: the blocked report threw: %s', strandId, describeThrown(error));
405
+ }
406
+ }
407
+ }
408
+
409
+ /** The rows steps 1 to 5 decide from, read before any write. */
410
+ async function readRotationState(db: Database, currentKey: string, pendingKey: string): Promise<RotationState> {
411
+ const oldKey = strandMemberKeyPair(currentKey);
412
+ const newKey = strandMemberKeyPair(pendingKey);
413
+ return {
414
+ oldKey,
415
+ newKey,
416
+ oldIsMember: await isStrandMember(db, oldKey.publicKeyB64),
417
+ oldIsManager: await isStrandManager(db, oldKey.publicKeyB64),
418
+ newIsMember: await isStrandMember(db, newKey.publicKeyB64),
419
+ newIsManager: await isStrandManager(db, newKey.publicKeyB64),
420
+ };
421
+ }
422
+
423
+ /**
424
+ * Step 5: K resigns its manager seat, then leaves. Both writers are no-ops over an absent row,
425
+ * so a run that finds K already gone writes nothing here. The resign runs only when K' holds a
426
+ * manager seat, so the strand never loses its last manager to this step.
427
+ */
428
+ async function stepDown(db: Database, state: RotationState): Promise<void> {
429
+ if (!state.oldIsMember) {
430
+ return;
431
+ }
432
+ if (state.oldIsManager) {
433
+ if (!await isStrandManager(db, state.newKey.publicKeyB64)) {
434
+ throw new Error('the new party key holds no manager seat, so the old key cannot resign without emptying the strand\'s managers');
435
+ }
436
+ await removeManager(db, { byManagerKeyPair: state.oldKey, targetManagerKey: state.oldKey.publicKeyB64 }, OWN_TRANSACTION);
437
+ }
438
+ await leaveStrand(db, { memberKeyPair: state.oldKey }, OWN_TRANSACTION);
439
+ log('Old party key %s left the strand', state.oldKey.publicKeyB64);
440
+ }