@serfab/cadre-core 1.20.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +294 -294
  2. package/dist/cadre-node.d.ts +329 -53
  3. package/dist/cadre-node.js +767 -85
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-authorization.d.ts +32 -2
  6. package/dist/control-authorization.js +19 -0
  7. package/dist/control-authorization.js.map +1 -1
  8. package/dist/control-database.d.ts +236 -23
  9. package/dist/control-database.js +601 -178
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-schema.d.ts +3 -3
  12. package/dist/control-schema.js +71 -7
  13. package/dist/control-schema.js.map +1 -1
  14. package/dist/ed25519-key.d.ts +8 -0
  15. package/dist/ed25519-key.js +11 -1
  16. package/dist/ed25519-key.js.map +1 -1
  17. package/dist/index.d.ts +5 -1
  18. package/dist/index.js +13 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/machine-removal.d.ts +51 -1
  21. package/dist/machine-removal.js +42 -1
  22. package/dist/machine-removal.js.map +1 -1
  23. package/dist/membership-connection-gater.d.ts +8 -0
  24. package/dist/membership-connection-gater.js +13 -1
  25. package/dist/membership-connection-gater.js.map +1 -1
  26. package/dist/owner-keys.js +2 -1
  27. package/dist/owner-keys.js.map +1 -1
  28. package/dist/owner-signer.js +3 -4
  29. package/dist/owner-signer.js.map +1 -1
  30. package/dist/peer-authorization.d.ts +14 -2
  31. package/dist/peer-authorization.js +24 -1
  32. package/dist/peer-authorization.js.map +1 -1
  33. package/dist/relay-reservation.js +20 -1
  34. package/dist/relay-reservation.js.map +1 -1
  35. package/dist/sealed-party-key.d.ts +32 -0
  36. package/dist/sealed-party-key.js +162 -0
  37. package/dist/sealed-party-key.js.map +1 -0
  38. package/dist/seed-bootstrap.d.ts +10 -3
  39. package/dist/seed-bootstrap.js +12 -0
  40. package/dist/seed-bootstrap.js.map +1 -1
  41. package/dist/strand-addr-protocol.d.ts +56 -6
  42. package/dist/strand-addr-protocol.js +57 -5
  43. package/dist/strand-addr-protocol.js.map +1 -1
  44. package/dist/strand-app-schema-report.d.ts +6 -3
  45. package/dist/strand-app-schema-report.js +13 -7
  46. package/dist/strand-app-schema-report.js.map +1 -1
  47. package/dist/strand-commit-durability.d.ts +33 -2
  48. package/dist/strand-commit-durability.js +44 -4
  49. package/dist/strand-commit-durability.js.map +1 -1
  50. package/dist/strand-database.d.ts +36 -6
  51. package/dist/strand-database.js +35 -11
  52. package/dist/strand-database.js.map +1 -1
  53. package/dist/strand-instance-manager.d.ts +133 -9
  54. package/dist/strand-instance-manager.js +266 -42
  55. package/dist/strand-instance-manager.js.map +1 -1
  56. package/dist/strand-membership-reconciler.d.ts +250 -51
  57. package/dist/strand-membership-reconciler.js +410 -66
  58. package/dist/strand-membership-reconciler.js.map +1 -1
  59. package/dist/strand-membership-writer.d.ts +7 -0
  60. package/dist/strand-membership-writer.js +9 -0
  61. package/dist/strand-membership-writer.js.map +1 -1
  62. package/dist/strand-party-key-rotation.d.ts +177 -0
  63. package/dist/strand-party-key-rotation.js +340 -0
  64. package/dist/strand-party-key-rotation.js.map +1 -0
  65. package/dist/strand-party-machines.d.ts +111 -0
  66. package/dist/strand-party-machines.js +258 -0
  67. package/dist/strand-party-machines.js.map +1 -0
  68. package/dist/strand-party-peers.d.ts +101 -0
  69. package/dist/strand-party-peers.js +49 -0
  70. package/dist/strand-party-peers.js.map +1 -0
  71. package/dist/strand-peer-redial.d.ts +34 -7
  72. package/dist/strand-peer-redial.js +46 -13
  73. package/dist/strand-peer-redial.js.map +1 -1
  74. package/dist/strand-revocation-enforcer.d.ts +15 -1
  75. package/dist/strand-revocation-enforcer.js +16 -9
  76. package/dist/strand-revocation-enforcer.js.map +1 -1
  77. package/dist/strand-transport-key.js +3 -0
  78. package/dist/strand-transport-key.js.map +1 -1
  79. package/dist/strand-watcher.d.ts +7 -4
  80. package/dist/strand-watcher.js +12 -7
  81. package/dist/strand-watcher.js.map +1 -1
  82. package/dist/types.d.ts +165 -17
  83. package/dist/types.js.map +1 -1
  84. package/package.json +9 -8
  85. package/src/cadre-node.ts +12252 -11528
  86. package/src/control-authorization.ts +41 -1
  87. package/src/control-database.ts +6123 -5594
  88. package/src/control-schema.ts +71 -7
  89. package/src/ed25519-key.ts +12 -1
  90. package/src/index.ts +957 -924
  91. package/src/machine-removal.ts +80 -1
  92. package/src/membership-connection-gater.ts +13 -1
  93. package/src/owner-keys.ts +2 -1
  94. package/src/owner-signer.ts +92 -94
  95. package/src/peer-authorization.ts +27 -3
  96. package/src/relay-reservation.ts +28 -1
  97. package/src/sealed-party-key.ts +190 -0
  98. package/src/seed-bootstrap.ts +17 -3
  99. package/src/strand-addr-protocol.ts +67 -6
  100. package/src/strand-app-schema-report.ts +17 -10
  101. package/src/strand-commit-durability.ts +54 -5
  102. package/src/strand-database.ts +48 -12
  103. package/src/strand-instance-manager.ts +330 -42
  104. package/src/strand-membership-reconciler.ts +1310 -942
  105. package/src/strand-membership-writer.ts +10 -0
  106. package/src/strand-party-key-rotation.ts +436 -0
  107. package/src/strand-party-machines.ts +293 -0
  108. package/src/strand-party-peers.ts +129 -0
  109. package/src/strand-peer-redial.ts +61 -14
  110. package/src/strand-revocation-enforcer.ts +27 -9
  111. package/src/strand-transport-key.ts +3 -0
  112. package/src/strand-watcher.ts +12 -7
  113. package/src/types.ts +3112 -2962
@@ -1131,6 +1131,16 @@ export async function isStrandMember(db: Database, memberKey: string): Promise<b
1131
1131
  return await memberStampId(db, memberKey) != null;
1132
1132
  }
1133
1133
 
1134
+ /**
1135
+ * Whether `memberKey` holds a live `Strand.Manager` row, as seen by THIS database instance:
1136
+ * the sibling of {@link isStrandMember} for the manager seat, which the party key rotation
1137
+ * driver (`strand-party-key-rotation.ts`) reads to know whether the party can seat its own
1138
+ * new key. Same unfiltered scan, same local-visibility caveat.
1139
+ */
1140
+ export async function isStrandManager(db: Database, memberKey: string): Promise<boolean> {
1141
+ return await managerRow(db, memberKey) !== undefined;
1142
+ }
1143
+
1134
1144
  /** Parameters for {@link addMemberByManager}. */
1135
1145
  export interface AddMemberByManagerParams {
1136
1146
  /**
@@ -0,0 +1,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/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
+ }