@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.
- package/README.md +294 -294
- package/dist/cadre-node.d.ts +329 -53
- package/dist/cadre-node.js +767 -85
- package/dist/cadre-node.js.map +1 -1
- package/dist/control-authorization.d.ts +32 -2
- package/dist/control-authorization.js +19 -0
- package/dist/control-authorization.js.map +1 -1
- package/dist/control-database.d.ts +236 -23
- package/dist/control-database.js +601 -178
- package/dist/control-database.js.map +1 -1
- package/dist/control-schema.d.ts +3 -3
- package/dist/control-schema.js +71 -7
- package/dist/control-schema.js.map +1 -1
- package/dist/ed25519-key.d.ts +8 -0
- package/dist/ed25519-key.js +11 -1
- package/dist/ed25519-key.js.map +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +13 -1
- package/dist/index.js.map +1 -1
- package/dist/machine-removal.d.ts +51 -1
- package/dist/machine-removal.js +42 -1
- package/dist/machine-removal.js.map +1 -1
- package/dist/membership-connection-gater.d.ts +8 -0
- package/dist/membership-connection-gater.js +13 -1
- package/dist/membership-connection-gater.js.map +1 -1
- package/dist/owner-keys.js +2 -1
- package/dist/owner-keys.js.map +1 -1
- package/dist/owner-signer.js +3 -4
- package/dist/owner-signer.js.map +1 -1
- package/dist/peer-authorization.d.ts +14 -2
- package/dist/peer-authorization.js +24 -1
- package/dist/peer-authorization.js.map +1 -1
- package/dist/relay-reservation.js +20 -1
- package/dist/relay-reservation.js.map +1 -1
- package/dist/sealed-party-key.d.ts +32 -0
- package/dist/sealed-party-key.js +162 -0
- package/dist/sealed-party-key.js.map +1 -0
- package/dist/seed-bootstrap.d.ts +10 -3
- package/dist/seed-bootstrap.js +12 -0
- package/dist/seed-bootstrap.js.map +1 -1
- package/dist/strand-addr-protocol.d.ts +56 -6
- package/dist/strand-addr-protocol.js +57 -5
- package/dist/strand-addr-protocol.js.map +1 -1
- package/dist/strand-app-schema-report.d.ts +6 -3
- package/dist/strand-app-schema-report.js +13 -7
- package/dist/strand-app-schema-report.js.map +1 -1
- package/dist/strand-commit-durability.d.ts +33 -2
- package/dist/strand-commit-durability.js +44 -4
- package/dist/strand-commit-durability.js.map +1 -1
- package/dist/strand-database.d.ts +36 -6
- package/dist/strand-database.js +35 -11
- package/dist/strand-database.js.map +1 -1
- package/dist/strand-instance-manager.d.ts +133 -9
- package/dist/strand-instance-manager.js +266 -42
- package/dist/strand-instance-manager.js.map +1 -1
- package/dist/strand-membership-reconciler.d.ts +250 -51
- package/dist/strand-membership-reconciler.js +410 -66
- package/dist/strand-membership-reconciler.js.map +1 -1
- package/dist/strand-membership-writer.d.ts +7 -0
- package/dist/strand-membership-writer.js +9 -0
- package/dist/strand-membership-writer.js.map +1 -1
- package/dist/strand-party-key-rotation.d.ts +177 -0
- package/dist/strand-party-key-rotation.js +340 -0
- package/dist/strand-party-key-rotation.js.map +1 -0
- package/dist/strand-party-machines.d.ts +111 -0
- package/dist/strand-party-machines.js +258 -0
- package/dist/strand-party-machines.js.map +1 -0
- package/dist/strand-party-peers.d.ts +101 -0
- package/dist/strand-party-peers.js +49 -0
- package/dist/strand-party-peers.js.map +1 -0
- package/dist/strand-peer-redial.d.ts +34 -7
- package/dist/strand-peer-redial.js +46 -13
- package/dist/strand-peer-redial.js.map +1 -1
- package/dist/strand-revocation-enforcer.d.ts +15 -1
- package/dist/strand-revocation-enforcer.js +16 -9
- package/dist/strand-revocation-enforcer.js.map +1 -1
- package/dist/strand-transport-key.js +3 -0
- package/dist/strand-transport-key.js.map +1 -1
- package/dist/strand-watcher.d.ts +7 -4
- package/dist/strand-watcher.js +12 -7
- package/dist/strand-watcher.js.map +1 -1
- package/dist/types.d.ts +165 -17
- package/dist/types.js.map +1 -1
- package/package.json +9 -8
- package/src/cadre-node.ts +12252 -11528
- package/src/control-authorization.ts +41 -1
- package/src/control-database.ts +6123 -5594
- package/src/control-schema.ts +71 -7
- package/src/ed25519-key.ts +12 -1
- package/src/index.ts +957 -924
- package/src/machine-removal.ts +80 -1
- package/src/membership-connection-gater.ts +13 -1
- package/src/owner-keys.ts +2 -1
- package/src/owner-signer.ts +92 -94
- package/src/peer-authorization.ts +27 -3
- package/src/relay-reservation.ts +28 -1
- package/src/sealed-party-key.ts +190 -0
- package/src/seed-bootstrap.ts +17 -3
- package/src/strand-addr-protocol.ts +67 -6
- package/src/strand-app-schema-report.ts +17 -10
- package/src/strand-commit-durability.ts +54 -5
- package/src/strand-database.ts +48 -12
- package/src/strand-instance-manager.ts +330 -42
- package/src/strand-membership-reconciler.ts +1310 -942
- package/src/strand-membership-writer.ts +10 -0
- package/src/strand-party-key-rotation.ts +436 -0
- package/src/strand-party-machines.ts +293 -0
- package/src/strand-party-peers.ts +129 -0
- package/src/strand-peer-redial.ts +61 -14
- package/src/strand-revocation-enforcer.ts +27 -9
- package/src/strand-transport-key.ts +3 -0
- package/src/strand-watcher.ts +12 -7
- package/src/types.ts +3112 -2962
package/dist/cadre-node.js
CHANGED
|
@@ -3,16 +3,16 @@ import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } fr
|
|
|
3
3
|
import { peerIdFromString, peerIdFromPrivateKey } from '@libp2p/peer-id';
|
|
4
4
|
import { generateKeyPair } from '@libp2p/crypto/keys';
|
|
5
5
|
import { createLibp2pNode } from '@optimystic/db-p2p';
|
|
6
|
-
import { wrapStorageWithCache, disposeStorageCache } from '@serfab/quereus-plugin-sereus';
|
|
6
|
+
import { wrapStorageWithCache, disposeStorageCache, appSchemaRefusalOf } from '@serfab/quereus-plugin-sereus';
|
|
7
7
|
import { multiaddr } from '@multiformats/multiaddr';
|
|
8
8
|
import { controlClusterPolicy, CONTROL_REPLICATION_BREADTH, DEFAULT_CHECKIN_WINDOW_MS, DEFAULT_CONNECTION_MONITOR } from './types.js';
|
|
9
9
|
import { generatePrivateKey } from '@optimystic/quereus-plugin-crypto';
|
|
10
|
-
import { ed25519KeyPairFromLibp2p, ed25519PublicKeyFromPrivate, requireEd25519PublicKeyB64 } from './ed25519-key.js';
|
|
10
|
+
import { ed25519KeyPairFromLibp2p, ed25519MessageSigner, ed25519PublicKeyFromPrivate, requireEd25519PublicKeyB64 } from './ed25519-key.js';
|
|
11
11
|
import { strandTransportKey } from './strand-transport-key.js';
|
|
12
12
|
import { isSendingStatus, StrandOfflineUnavailableError, StrandQueueNotEmptyError } from './strand-offline.js';
|
|
13
13
|
import { assertScopeKeyCharset, assertStrandScopeKey, controlStorageScope, InvalidStrandIdError, isValidStrandScopeKey } from './storage-scope.js';
|
|
14
14
|
import { generateStrandMemberKey, strandMemberKeyPair } from './strand-member-key.js';
|
|
15
|
-
import { assertNotPreSplitStrand, issueInvite, PreSplitStrandIdentityError, readStrandHeaderSAppId } from './strand-membership-writer.js';
|
|
15
|
+
import { assertNotPreSplitStrand, isStrandManager, isStrandMember, isStrandSealed, issueInvite, PreSplitStrandIdentityError, readStrandHeaderSAppId } from './strand-membership-writer.js';
|
|
16
16
|
import { MEMBERSHIP_INVITE_TTL_MS } from './strand-formation-manager.js';
|
|
17
17
|
import { DEFAULT_IDENTITY_KEY_ID } from './key-store.js';
|
|
18
18
|
import { loadOrCreateIdentityKey } from './identity-key.js';
|
|
@@ -26,7 +26,10 @@ import { addrKey, mergePeerAddrs, groupAddrsByPeerId } from './peer-addr-book.js
|
|
|
26
26
|
import { strandFretPeerAddrs } from './strand-fret-addrs.js';
|
|
27
27
|
import { verifyCadrePeerVoucher, verifyInvitationAdmission, verifyRevocationSigner } from './peer-authorization.js';
|
|
28
28
|
import { deriveOwnerAnchor } from './owner-anchor-sync.js';
|
|
29
|
-
import { describeMachines, planMachineRemoval, MachineRemovalRefusedError } from './machine-removal.js';
|
|
29
|
+
import { describeMachines, pendingRotationWaitingOn, planMachineRemoval, MachineRemovalRefusedError } from './machine-removal.js';
|
|
30
|
+
import { partitionPartyStrandPeers } from './strand-party-peers.js';
|
|
31
|
+
import { StrandPartyKeyRotationDriver } from './strand-party-key-rotation.js';
|
|
32
|
+
import { openPartyKey, partyKeyRecipients, sealPartyKey } from './sealed-party-key.js';
|
|
30
33
|
import { describeOwnerKeys, namedOwnerKey, planOwnerKeyRemoval, revouchWithinPlan, OwnerKeyAddRefusedError, OwnerKeyRemovalRefusedError } from './owner-keys.js';
|
|
31
34
|
import { ed25519PublicKeyB64FromPeerId } from './ed25519-key.js';
|
|
32
35
|
import { signPeerRecord, verifyPeerRecordSignature, isPeerRecordFresh, orderSignalingFirst, isSignalingAddr, currentMemberTrustPolicy, DEFAULT_PEER_RECORD_MAX_AGE_MS, DEFAULT_PEER_RECORD_HEARTBEAT_MS } from './peer-record.js';
|
|
@@ -56,7 +59,7 @@ import { cadreInvitationReach, selectCadreInvitationMembers, selectInvitationSib
|
|
|
56
59
|
import { createMembershipConnectionGater, UnauthorizedReservationBudget } from './membership-connection-gater.js';
|
|
57
60
|
import { controlNetworkName, installControlProtocolGuard, servesControlDatabase } from './control-protocol-guard.js';
|
|
58
61
|
import { StrandWakeService, dialWake } from './strand-wake-protocol.js';
|
|
59
|
-
import { StrandAddrService, collectStrandAddrs } from './strand-addr-protocol.js';
|
|
62
|
+
import { StrandAddrService, collectStrandAddrs, nextStrandAddrAsk } from './strand-addr-protocol.js';
|
|
60
63
|
import { DelegateAdmissionStore, extractCircuitRelayTargets, dueRelayAnnounces, prunePeerStrandKeys, peerStrandKey, recordRelayRefusals, relaysNotRefusing } from './delegate-admission.js';
|
|
61
64
|
import { relayCircuitAddrs, resolveListenAddrs, resolveTransportOptions, RelayReservationFailedError } from './relay-addrs.js';
|
|
62
65
|
import { selfAddressesChanged } from './self-address-update.js';
|
|
@@ -71,9 +74,10 @@ import { describeThrown, toError } from './describe-thrown.js';
|
|
|
71
74
|
const log = debug('sereus:cadre:node');
|
|
72
75
|
const timing = debug('sereus:cadre:timing');
|
|
73
76
|
/**
|
|
74
|
-
* How often a running strand re-asks each connected sibling that last
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
+
* How often a running strand re-asks each connected sibling that last answered WITH
|
|
78
|
+
* addresses for its strand-network addresses, and re-merges them into its own libp2p
|
|
79
|
+
* address book ({@link CadreNode.refreshStrandPeerAddrs}); also the longest wait
|
|
80
|
+
* after an answer with none ({@link nextStrandAddrAsk}).
|
|
77
81
|
* Overridable per node via `network.controlCohort.strandAddrRefreshMs`.
|
|
78
82
|
*
|
|
79
83
|
* Ten minutes sits comfortably inside the peerStore's one-hour address expiry
|
|
@@ -82,17 +86,6 @@ const timing = debug('sereus:cadre:timing');
|
|
|
82
86
|
* on, so the strand-addr RPC fan-out stays cheap.
|
|
83
87
|
*/
|
|
84
88
|
export const STRAND_PEER_ADDR_REFRESH_MS = 10 * 60 * 1000;
|
|
85
|
-
/**
|
|
86
|
-
* How soon {@link CadreNode.refreshStrandPeerAddrs} re-asks a sibling that did NOT
|
|
87
|
-
* answer — unreachable, `unavailable`, or `refused`. A refusal matters most: a
|
|
88
|
-
* phone asking before its `CadrePeer` row has replicated to the sibling is refused
|
|
89
|
-
* and its delegate grant goes unrecorded, and waiting the full
|
|
90
|
-
* {@link STRAND_PEER_ADDR_REFRESH_MS} for the next try is the delay this bounds.
|
|
91
|
-
* A pass arms its own wake for the earliest due time it leaves behind
|
|
92
|
-
* (`nextReconcileWakeMs`), so a sibling that keeps failing costs one timed-out
|
|
93
|
-
* RPC a minute, with no pass in between.
|
|
94
|
-
*/
|
|
95
|
-
export const STRAND_PEER_ADDR_RETRY_MS = 60 * 1000;
|
|
96
89
|
/**
|
|
97
90
|
* Default lifetime of an owner grant ({@link CadreNode.createOwnerGrant}): whoever holds the
|
|
98
91
|
* bundle can become an owner, so it is a bearer credential for admin rights and lives only
|
|
@@ -160,14 +153,6 @@ function addressesOfFirst(members, peerId) {
|
|
|
160
153
|
const names = (addr) => addr.endsWith(`/p2p/${peerId}`);
|
|
161
154
|
return [...members.filter(names), ...members.filter((addr) => !names(addr))];
|
|
162
155
|
}
|
|
163
|
-
/**
|
|
164
|
-
* Whether a sibling actually answered a strand-addr RPC — with addresses or
|
|
165
|
-
* without — as opposed to being unreachable, unavailable, or refusing us. Decides
|
|
166
|
-
* which of the refresh and retry intervals it waits before the next ask.
|
|
167
|
-
*/
|
|
168
|
-
function siblingAnswered(outcome) {
|
|
169
|
-
return outcome === 'answered' || outcome === 'empty';
|
|
170
|
-
}
|
|
171
156
|
/**
|
|
172
157
|
* `primary` followed by the entries of `extra` it does not already contain, de-duplicated
|
|
173
158
|
* and order-preserving.
|
|
@@ -571,14 +556,19 @@ export class CadreNode {
|
|
|
571
556
|
* missing key is due. Bounds {@link refreshStrandPeerAddrs}'s fan-out per
|
|
572
557
|
* (sibling, strand) rather than per strand, so a sibling that connects after a
|
|
573
558
|
* pass is asked on the pass its connection starts instead of waiting out a stamp
|
|
574
|
-
* another sibling's answer set.
|
|
575
|
-
*
|
|
576
|
-
*
|
|
577
|
-
*
|
|
578
|
-
*
|
|
579
|
-
* so a resumed strand and a reconnected sibling are both asked at once.
|
|
559
|
+
* another sibling's answer set. {@link nextStrandAddrAsk} sets each due time from the
|
|
560
|
+
* ask's outcome, and each pass arms its own wake for the earliest due time it leaves
|
|
561
|
+
* behind (`nextReconcileWakeMs`). Keys whose strand stopped running or whose sibling
|
|
562
|
+
* is no longer connected are pruned every pass, so a resumed strand and a reconnected
|
|
563
|
+
* sibling are both asked at once.
|
|
580
564
|
*/
|
|
581
565
|
this.strandAddrAskDueAt = new Map();
|
|
566
|
+
/**
|
|
567
|
+
* How far each (sibling, strand) has climbed {@link nextStrandAddrAsk}'s wait, keyed like
|
|
568
|
+
* {@link strandAddrAskDueAt} and pruned with it: a reconnected sibling may be a new
|
|
569
|
+
* incarnation, so it starts again at the first step.
|
|
570
|
+
*/
|
|
571
|
+
this.strandAddrAskStreak = new Map();
|
|
582
572
|
/**
|
|
583
573
|
* The strand-network addresses a formation carried back
|
|
584
574
|
* (`FormationResultMessage.strandAddrs`), by strand id: the responder's live strand
|
|
@@ -888,6 +878,57 @@ export class CadreNode {
|
|
|
888
878
|
this.selfPeerPublishDeferred = false;
|
|
889
879
|
/** This node's own `DeviceToken` self-write committed local-only (re-touched on growth). */
|
|
890
880
|
this.pendingSelfDeviceWrite = false;
|
|
881
|
+
/**
|
|
882
|
+
* This machine's `StrandPeer` rows ({@link publishStrandPeer}) that could not be written
|
|
883
|
+
* yet, by strand id → this machine's peer id in that strand: deferred while a write could
|
|
884
|
+
* fork the party, or refused because this machine's own `CadrePeer` row has not reached
|
|
885
|
+
* this node. Re-attempted by the growth drain ({@link publishDeferredStrandPeers}), by the
|
|
886
|
+
* party-machine watch when a `CadrePeer` row arrives (this machine's own included: a
|
|
887
|
+
* replica with no party key runs no reconciler, so that is its retry), and by each
|
|
888
|
+
* membership reconciler pass of the strand. Cleared on stop with the queues above: the next
|
|
889
|
+
* start's launches publish again.
|
|
890
|
+
*/
|
|
891
|
+
this.deferredStrandPeerWrites = new Map();
|
|
892
|
+
/** The latest rebuild queued per strand for a removed machine in its seed ({@link queueSeedRemovalRebuild}). */
|
|
893
|
+
this.seedRemovalRebuilds = new Map();
|
|
894
|
+
/**
|
|
895
|
+
* Strands whose `StrandPeer` row for this machine this process has found present (written
|
|
896
|
+
* by it, or already stored). Rows are never updated or deleted, so once present the row
|
|
897
|
+
* stays, and a later publish for the strand costs nothing. Per session.
|
|
898
|
+
*/
|
|
899
|
+
this.strandPeerRowsHeld = new Set();
|
|
900
|
+
/**
|
|
901
|
+
* The watch that wakes every closed strand's membership reconciler when the party's
|
|
902
|
+
* machines change ({@link StrandInstanceManager.notifyPartyPeersChanged}); taken in
|
|
903
|
+
* `start()` beside the gate watch, disposed in `stop()`.
|
|
904
|
+
*/
|
|
905
|
+
this.strandPartyPeersWatch = null;
|
|
906
|
+
/**
|
|
907
|
+
* The watch on `StrandPartyKey` and `PendingStrandPartyKey` ({@link onPartyKeyTablesChanged}):
|
|
908
|
+
* a swapped key replicated from the machine that finished a rotation re-keys the running
|
|
909
|
+
* strand here, and a pending row drives a rotation here when this is an owner machine running
|
|
910
|
+
* the strand. Taken in `start()`, disposed in `stop()`.
|
|
911
|
+
*/
|
|
912
|
+
this.strandPartyKeyWatch = null;
|
|
913
|
+
/**
|
|
914
|
+
* The party key rotation driver (`strand-party-key-rotation.ts`) over this node's control
|
|
915
|
+
* database and strand manager; one run per strand at a time. Driven by {@link removeMachine},
|
|
916
|
+
* a closed strand becoming writable here, an offline queue draining, the party key watch and
|
|
917
|
+
* the growth drain.
|
|
918
|
+
*/
|
|
919
|
+
this.partyKeyRotation = new StrandPartyKeyRotationDriver({
|
|
920
|
+
readPending: (strandId) => this.openPendingPartyKey(strandId),
|
|
921
|
+
readCurrentKey: (strandId) => this.requireControlDatabase('read a strand party key').queryStrandPartyKey(strandId),
|
|
922
|
+
readSiblingPeerIds: async (strandId) => (await this.readPartyStrandPeers(strandId)).live.map((peer) => peer.strandPeerId),
|
|
923
|
+
getDatabase: (strandId) => this.strandManager.getInstance(strandId)?.database?.getDatabase(),
|
|
924
|
+
getOwnPeerId: (strandId) => this.strandManager.getInstance(strandId)?.libp2pNode?.peerId.toString(),
|
|
925
|
+
swapKeys: (entries) => this.swapStrandPartyKeys(entries),
|
|
926
|
+
onRotated: async (strandId, newKey) => {
|
|
927
|
+
await this.strandManager.rekeyParty(strandId, newKey);
|
|
928
|
+
this.emit('strand:party-key-rotated', { strandId });
|
|
929
|
+
},
|
|
930
|
+
onBlocked: (strandId, reason) => this.emit('strand:party-key-rotation-blocked', { strandId, reason }),
|
|
931
|
+
});
|
|
891
932
|
/**
|
|
892
933
|
* Guards the one-shot, first-cohort-growth reconstruction: an owner re-touches
|
|
893
934
|
* every membership row it may have authored that could be unreplicated (covering
|
|
@@ -1171,6 +1212,40 @@ export class CadreNode {
|
|
|
1171
1212
|
// change on a touched table or the backstop. Nothing depends on a chain row until a
|
|
1172
1213
|
// `CadrePeer` or `OwnerKey` row refers to it, and that row is itself such a change.
|
|
1173
1214
|
this.membershipGateWatch = this.controlDatabase.watchMembershipTables(() => this.onMembershipGateTablesChanged(), { label: 'membership-gate' });
|
|
1215
|
+
// The party-machine watch: a `StrandPeer` row arriving, a machine's `CadrePeer` row
|
|
1216
|
+
// or a tombstone, written here or replicated in, first re-attempts this machine's own
|
|
1217
|
+
// deferred `StrandPeer` rows (the arrival may be its own `CadrePeer` row, which the
|
|
1218
|
+
// insert needs), then re-arms every closed strand's membership reconciler, which
|
|
1219
|
+
// binds the party's other machines under its current key
|
|
1220
|
+
// (`strand-membership-reconciler.ts` → "Binding the party's other machines"), and
|
|
1221
|
+
// re-reads the party's machines for every strand whose offline queue waits for them
|
|
1222
|
+
// (`strand-party-machines.ts`). Coalesced by the watch; a loop with nothing to do
|
|
1223
|
+
// confirms and stops again, and a row the re-attempt writes fires the watch once more
|
|
1224
|
+
// over an empty queue.
|
|
1225
|
+
//
|
|
1226
|
+
// NOTE: `CadrePeer` changes on every machine's self-record heartbeat, so each closed
|
|
1227
|
+
// strand's loop runs one confirming pass per heartbeat of any party machine, and on a
|
|
1228
|
+
// node offering offline mode each running strand's machine tracker one control read
|
|
1229
|
+
// (`readPartyStrandPeers`: the strand's rows and the machine rows read fresh); the
|
|
1230
|
+
// reconciler's pass NOTE says what the pass costs. If that read ever shows in a phone's
|
|
1231
|
+
// profile, refresh the trackers only on a `StrandPeer` or `Revocation` change and on a
|
|
1232
|
+
// `CadrePeer` row's appearance or disappearance, not on every heartbeat. A table this
|
|
1233
|
+
// `Database` has not yet touched hears local commits only (`table-change-watch.ts`):
|
|
1234
|
+
// `StrandPeer` is first read by the publish every strand launch makes, by the tracker's
|
|
1235
|
+
// first read, or by the growth drain's re-attempt of one deferred while alone, so a node
|
|
1236
|
+
// running a strand with a sibling reachable hears replicated rows from its first launch on.
|
|
1237
|
+
this.strandPartyPeersWatch = this.controlDatabase.watchTables(['CadreControl.StrandPeer', 'CadreControl.CadrePeer', 'CadreControl.Revocation'], async () => {
|
|
1238
|
+
await this.publishDeferredStrandPeers();
|
|
1239
|
+
this.strandManager.notifyPartyPeersChanged();
|
|
1240
|
+
}, { label: 'strand-party-peers' });
|
|
1241
|
+
// The party key watch: a `StrandPartyKey` row swapped on another machine re-keys the
|
|
1242
|
+
// running strand here, and a `PendingStrandPartyKey` row written here or replicated in is
|
|
1243
|
+
// driven here when this is an owner machine running the strand (`strand-party-key-rotation.ts`).
|
|
1244
|
+
// The backstop is the path for a swap this node's storage never announces, such as one
|
|
1245
|
+
// committed while it was restarting: the row shows up on a later read and raises no event,
|
|
1246
|
+
// and a strand left on the old key idles with no `Member` row to find. Shares the reconcile
|
|
1247
|
+
// backstop because a run is one row read per closed strand and the same bound suits both.
|
|
1248
|
+
this.strandPartyKeyWatch = this.controlDatabase.watchTables(['CadreControl.StrandPartyKey', 'CadreControl.PendingStrandPartyKey'], () => this.onPartyKeyTablesChanged(), { label: 'strand-party-key', backstopMs: this.controlReconcileBackstopMs() });
|
|
1174
1249
|
// Committed-delete seam → write-while-alone revocation queue. Same wiring
|
|
1175
1250
|
// window argument as the membership listener above.
|
|
1176
1251
|
this.controlDatabase.setGuardedDeleteListener((revocation) => this.noteGuardedDelete(revocation));
|
|
@@ -3380,6 +3455,8 @@ export class CadreNode {
|
|
|
3380
3455
|
this.pendingSelfPeerWrite = false;
|
|
3381
3456
|
this.selfPeerPublishDeferred = false;
|
|
3382
3457
|
this.pendingSelfDeviceWrite = false;
|
|
3458
|
+
this.deferredStrandPeerWrites.clear();
|
|
3459
|
+
this.strandPeerRowsHeld.clear();
|
|
3383
3460
|
// Self-record publication history is per-session too: a restarted node re-publishes
|
|
3384
3461
|
// from scratch, and carrying the previous lifetime's stamp forward would either
|
|
3385
3462
|
// suppress the stale-record warning or fire it on a node that just came up.
|
|
@@ -4393,6 +4470,12 @@ export class CadreNode {
|
|
|
4393
4470
|
await this.retouchSelfDeviceToken();
|
|
4394
4471
|
this.pendingSelfDeviceWrite = false;
|
|
4395
4472
|
}
|
|
4473
|
+
// This machine's `StrandPeer` rows deferred while alone or refused: each strand's
|
|
4474
|
+
// launch made its publish, so only what that publish could not write is here.
|
|
4475
|
+
await this.publishDeferredStrandPeers();
|
|
4476
|
+
// A party key rotation whose control swap was deferred while alone, or whose pending
|
|
4477
|
+
// row this node could not act on before: re-driven for every closed strand running here.
|
|
4478
|
+
await this.driveTrackedPendingRotations('cohort growth');
|
|
4396
4479
|
// 3. First growth: an owner reconstructs membership rows it may have
|
|
4397
4480
|
// authored that never replicated (covers writes from before this process
|
|
4398
4481
|
// started). Rows already tracked in the in-memory queue are handled by
|
|
@@ -5056,6 +5139,7 @@ export class CadreNode {
|
|
|
5056
5139
|
strandId: strand.Id,
|
|
5057
5140
|
error: toError(error)
|
|
5058
5141
|
});
|
|
5142
|
+
this.suppressIfAppSchemaRefused(strand.Id, sAppConfig, error);
|
|
5059
5143
|
// Rethrow after the event: the only caller is the StrandWatcher's
|
|
5060
5144
|
// onStrandAdded callback, which uses the rejection to decide whether the
|
|
5061
5145
|
// strand was really added. Swallowing it here would have the watcher mark
|
|
@@ -5065,6 +5149,27 @@ export class CadreNode {
|
|
|
5065
5149
|
throw error;
|
|
5066
5150
|
}
|
|
5067
5151
|
}
|
|
5152
|
+
/**
|
|
5153
|
+
* Stop the watcher relaunching a strand whose launch failed on an app schema that can never apply
|
|
5154
|
+
* to its tables (`AppSchemaRefusedError`, e.g. a `not null` column with no default added to a table
|
|
5155
|
+
* with rows): every relaunch would build the strand node and compose the database only to fail at the
|
|
5156
|
+
* same statement (gotchoices/sereus#57). The next {@link addStrand} lifts it, since a claim is the only
|
|
5157
|
+
* way the registered schema changes. Any other failure is left to the retry ladder.
|
|
5158
|
+
*
|
|
5159
|
+
* Not suppressed when a claim registered another config while this launch ran (`launchedWith` is
|
|
5160
|
+
* no longer the registered one): that claim already lifted any suppression, and its own call only
|
|
5161
|
+
* waited on this launch, so its schema has not been tried yet and the ladder must try it.
|
|
5162
|
+
* Returns whether it suppressed.
|
|
5163
|
+
*/
|
|
5164
|
+
suppressIfAppSchemaRefused(strandId, launchedWith, error) {
|
|
5165
|
+
const refusal = appSchemaRefusalOf(error);
|
|
5166
|
+
if (!refusal || this.sAppConfigs.get(strandId) !== launchedWith) {
|
|
5167
|
+
return false;
|
|
5168
|
+
}
|
|
5169
|
+
log('Strand %s: app schema refused, not relaunching until the strand is claimed again: %s', strandId, refusal.message);
|
|
5170
|
+
this.strandWatcher?.suppressStrand(strandId);
|
|
5171
|
+
return true;
|
|
5172
|
+
}
|
|
5068
5173
|
/**
|
|
5069
5174
|
* Offer a strand no local config claims to the hosting app as `strand:discovered`, so
|
|
5070
5175
|
* it can decide whether to join (register a config + addStrand); the strand-agnostic
|
|
@@ -5246,6 +5351,10 @@ export class CadreNode {
|
|
|
5246
5351
|
// the listener goes, keeps a closing commit from scheduling a gate refresh.
|
|
5247
5352
|
this.membershipGateWatch?.dispose();
|
|
5248
5353
|
this.membershipGateWatch = null;
|
|
5354
|
+
this.strandPartyPeersWatch?.dispose();
|
|
5355
|
+
this.strandPartyPeersWatch = null;
|
|
5356
|
+
this.strandPartyKeyWatch?.dispose();
|
|
5357
|
+
this.strandPartyKeyWatch = null;
|
|
5249
5358
|
this.controlDatabase.setMembershipChangeListener(null);
|
|
5250
5359
|
this.controlDatabase.setGuardedDeleteListener(null);
|
|
5251
5360
|
this.controlDatabase.setControlWriteAbandonedListener(null);
|
|
@@ -5289,6 +5398,9 @@ export class CadreNode {
|
|
|
5289
5398
|
this.hibernationManager.recordActivity(instance);
|
|
5290
5399
|
}
|
|
5291
5400
|
void this.recordReplicaSAppId(strandId);
|
|
5401
|
+
// A rotation pending for a strand that was still syncing when its row was written waits
|
|
5402
|
+
// for the database; this is the moment it exists.
|
|
5403
|
+
void this.driveRotationIfPending(strandId, 'strand writable');
|
|
5292
5404
|
this.emit('strand:writable', { strandId });
|
|
5293
5405
|
}
|
|
5294
5406
|
/**
|
|
@@ -5308,6 +5420,23 @@ export class CadreNode {
|
|
|
5308
5420
|
}
|
|
5309
5421
|
this.emit('strand:offline-status', event);
|
|
5310
5422
|
}
|
|
5423
|
+
/**
|
|
5424
|
+
* The state of a strand's offline queue. An empty queue is when a party key rotation it held up
|
|
5425
|
+
* can run: every membership write is refused while it lists a transaction
|
|
5426
|
+
* (`StrandOfflineQueueBusyError`), which is how a machine removal made on a held queue leaves its
|
|
5427
|
+
* strand `pending`.
|
|
5428
|
+
*
|
|
5429
|
+
* NOTE: a queue held for another reason (a second machine still unreachable) keeps the removed
|
|
5430
|
+
* machine a member of a closed strand until it drains, unless another owner machine drives the
|
|
5431
|
+
* rotation. If a lost phone's removal must not wait on that, let the rotation's writes past the
|
|
5432
|
+
* refusal, with the bounded wait the refusal exists to avoid.
|
|
5433
|
+
*/
|
|
5434
|
+
handleQueueState(event) {
|
|
5435
|
+
this.emit('strand:queue-state', event);
|
|
5436
|
+
if (event.state.depth === 0) {
|
|
5437
|
+
void this.driveRotationIfPending(event.strandId, 'offline queue drained');
|
|
5438
|
+
}
|
|
5439
|
+
}
|
|
5311
5440
|
// Hibernation callbacks
|
|
5312
5441
|
async handleStrandIdle(strandId) {
|
|
5313
5442
|
const instance = this.strandManager.getInstance(strandId);
|
|
@@ -5416,6 +5545,50 @@ export class CadreNode {
|
|
|
5416
5545
|
instance.status = 'hibernating';
|
|
5417
5546
|
}
|
|
5418
5547
|
}
|
|
5548
|
+
/**
|
|
5549
|
+
* Run {@link rebuildWithoutRemovedMachine} after any rebuild already queued for `strandId`, so
|
|
5550
|
+
* two removals give two rebuilds in turn. A later removal needs its own: the first may have
|
|
5551
|
+
* resolved its seed before the second's row was written. Never rejects.
|
|
5552
|
+
*/
|
|
5553
|
+
queueSeedRemovalRebuild(strandId) {
|
|
5554
|
+
const rebuild = (this.seedRemovalRebuilds.get(strandId) ?? Promise.resolve())
|
|
5555
|
+
.then(() => this.rebuildWithoutRemovedMachine(strandId))
|
|
5556
|
+
.catch((error) => {
|
|
5557
|
+
log('Rebuilding strand %s without a removed machine failed; a later wake resolves a fresh seed: %o', strandId, error);
|
|
5558
|
+
})
|
|
5559
|
+
.finally(() => {
|
|
5560
|
+
if (this.seedRemovalRebuilds.get(strandId) === rebuild) {
|
|
5561
|
+
this.seedRemovalRebuilds.delete(strandId);
|
|
5562
|
+
}
|
|
5563
|
+
});
|
|
5564
|
+
this.seedRemovalRebuilds.set(strandId, rebuild);
|
|
5565
|
+
}
|
|
5566
|
+
/**
|
|
5567
|
+
* Replace a running strand node whose launch seed names a machine removed from the cadre with one
|
|
5568
|
+
* built from a fresh seed, which a removed machine is not in, so an offline queue stops waiting
|
|
5569
|
+
* for it (`docs/strands.md` → Waiting for the party's own machines). The same pair hibernation
|
|
5570
|
+
* runs, so the app sees what it sees on a wake, and a queue is restored from its journal; the
|
|
5571
|
+
* quiesce waits for a build in flight. A strand that went down meanwhile takes a fresh seed at its
|
|
5572
|
+
* next wake, so it is left down.
|
|
5573
|
+
*
|
|
5574
|
+
* NOTE: accepted tradeoff — the rebuild drops the running database's in-memory followed commits.
|
|
5575
|
+
* An upstream "forget this peer" call would avoid the rebuild, but needs an Optimystic change for
|
|
5576
|
+
* a case a removal hits rarely. If rebuilds prove disruptive, ask for that call.
|
|
5577
|
+
*
|
|
5578
|
+
* NOTE: a force-hibernate landing between the quiesce and the resume is undone by the resume, and
|
|
5579
|
+
* its cancelled timers leave the strand up until the next activity. If a backgrounded phone is
|
|
5580
|
+
* seen holding a strand up after a removal, make the two steps one transition in the manager.
|
|
5581
|
+
*/
|
|
5582
|
+
async rebuildWithoutRemovedMachine(strandId) {
|
|
5583
|
+
const instance = this.strandManager.getInstance(strandId);
|
|
5584
|
+
if (!this._running || !instance || instance.status === 'hibernating' || this.strandManager.isQuiescing(strandId)) {
|
|
5585
|
+
log('Strand %s went down before its rebuild without a removed machine; leaving it down', strandId);
|
|
5586
|
+
return;
|
|
5587
|
+
}
|
|
5588
|
+
log('Strand %s: a machine removed from the cadre is in its launch seed; rebuilding its runtime', strandId);
|
|
5589
|
+
await this.handleStrandHibernate(strandId);
|
|
5590
|
+
await this.handleStrandWake(strandId);
|
|
5591
|
+
}
|
|
5419
5592
|
/**
|
|
5420
5593
|
* Rebuild a quiesced strand's runtime, re-resolving the volatile cohort input
|
|
5421
5594
|
* first: the discovery seed may have grown since the strand last ran. Shared by
|
|
@@ -5431,16 +5604,37 @@ export class CadreNode {
|
|
|
5431
5604
|
? peerIdFromPrivateKey(await strandTransportKey(this.identityKey, strandId)).toString()
|
|
5432
5605
|
: undefined;
|
|
5433
5606
|
const bootstrapNodes = await this.resolveCohortSeed(strandId, delegatePeerId);
|
|
5607
|
+
// The party's membership key as the control record names it now: a party key rotation can
|
|
5608
|
+
// finish while the strand hibernates, and the retained config would rebuild the reconciler
|
|
5609
|
+
// under the key that left the strand. A row that cannot be read keeps the retained key.
|
|
5610
|
+
const partyMemberPrivateKey = await this.storedStrandPartyKey(strandId);
|
|
5434
5611
|
// NOTE: no `servingMachines` override — see `launchStrand` for why a strand node
|
|
5435
5612
|
// declares no repair yardstick, and `StartStrandConfig.servingMachines` for the
|
|
5436
5613
|
// count that would legitimately go here once one exists.
|
|
5437
|
-
const instance = await this.strandManager.resumeStrand(strandId, { bootstrapNodes });
|
|
5614
|
+
const instance = await this.strandManager.resumeStrand(strandId, { bootstrapNodes, ...(partyMemberPrivateKey !== undefined && { partyMemberPrivateKey }) });
|
|
5438
5615
|
// Same reason as the launch path: `bootstrapNodes` only reaches the address
|
|
5439
5616
|
// book through @libp2p/bootstrap discovery, so merge it directly as well.
|
|
5440
5617
|
if (instance.libp2pNode) {
|
|
5441
5618
|
await this.mergeStrandPeerAddrs(instance.libp2pNode, bootstrapNodes, strandId);
|
|
5442
5619
|
}
|
|
5443
5620
|
void this.recordReplicaSAppId(strandId);
|
|
5621
|
+
void this.driveRotationIfPending(strandId, 'strand resumed');
|
|
5622
|
+
}
|
|
5623
|
+
/**
|
|
5624
|
+
* The party's `StrandPartyKey.PrivateKey` for `strandId` as stored now, for a resume;
|
|
5625
|
+
* `undefined` when there is none or the read fails (logged), so the caller keeps what it has.
|
|
5626
|
+
*/
|
|
5627
|
+
async storedStrandPartyKey(strandId) {
|
|
5628
|
+
if (!this.controlDatabase) {
|
|
5629
|
+
return undefined;
|
|
5630
|
+
}
|
|
5631
|
+
try {
|
|
5632
|
+
return await this.controlDatabase.queryStrandPartyKey(strandId) ?? undefined;
|
|
5633
|
+
}
|
|
5634
|
+
catch (error) {
|
|
5635
|
+
log('Resume of strand %s: the party key row could not be read; resuming under the retained key: %o', strandId, error);
|
|
5636
|
+
return undefined;
|
|
5637
|
+
}
|
|
5444
5638
|
}
|
|
5445
5639
|
/**
|
|
5446
5640
|
* Real cohort check-in for a hibernating strand (the `onCheckIn` callback).
|
|
@@ -5610,6 +5804,15 @@ export class CadreNode {
|
|
|
5610
5804
|
* strand in the watcher so this retry cannot resurrect it — a call to THIS method lifts
|
|
5611
5805
|
* that suppression again, since an explicit claim is a deliberate reversal of the
|
|
5612
5806
|
* deliberate stop.
|
|
5807
|
+
*
|
|
5808
|
+
* A launch refused on its app schema (`AppSchemaRefusedError`: the schema can never apply
|
|
5809
|
+
* to the tables the strand holds, such as a `not null` column with no default added to a
|
|
5810
|
+
* table with rows) is not handed to the relaunch, since every relaunch would fail the same
|
|
5811
|
+
* way after a full start-up. The strand is suppressed in the watcher instead, and the next
|
|
5812
|
+
* call to this method lifts that: a claim is the only way the registered schema changes,
|
|
5813
|
+
* so a different schema launches, and the same one makes one more attempt. A storage
|
|
5814
|
+
* replica this claim tried to give the schema in place keeps running and stays known to
|
|
5815
|
+
* the watcher.
|
|
5613
5816
|
*/
|
|
5614
5817
|
async addStrand(config) {
|
|
5615
5818
|
if (!this._running) {
|
|
@@ -5676,6 +5879,11 @@ export class CadreNode {
|
|
|
5676
5879
|
// shared `MemberPrivateKey` is read only by the founder bootstrap. If a joiner
|
|
5677
5880
|
// launch ever starts depending on that key, gate this hand-back on the passed row
|
|
5678
5881
|
// matching the control one.
|
|
5882
|
+
if (this.suppressIfAppSchemaRefused(strandRow.Id, sAppConfig, error) && this.strandManager.getInstance(strandRow.Id)) {
|
|
5883
|
+
// A storage replica this claim tried to give the schema in place keeps running, so the
|
|
5884
|
+
// watcher keeps it known: its removed-strand loop must still detach it on a party-wide removal.
|
|
5885
|
+
throw error;
|
|
5886
|
+
}
|
|
5679
5887
|
this.strandWatcher?.forgetStrand(strandRow.Id);
|
|
5680
5888
|
throw error;
|
|
5681
5889
|
}
|
|
@@ -5735,6 +5943,17 @@ export class CadreNode {
|
|
|
5735
5943
|
getStrandOfflineMode(strandId) {
|
|
5736
5944
|
return this.strandManager.offlineMode(strandId);
|
|
5737
5945
|
}
|
|
5946
|
+
/**
|
|
5947
|
+
* The party's other machines known to hold `strandId` (each has written its `StrandPeer` row for
|
|
5948
|
+
* it) with no open connection from this node's strand node: what a queued transaction reporting
|
|
5949
|
+
* `waitingFor: 'cohort'` may be waiting for, by control peer id (`listMachines`, `removeMachine`)
|
|
5950
|
+
* and strand peer id (docs/strands.md → "Waiting for the party's own machines"). Empty on a
|
|
5951
|
+
* strand not running here, and on a node offering no offline mode. Nothing releases the wait on
|
|
5952
|
+
* its own: the transaction is safe in the journal, and removing the machine is the user's call.
|
|
5953
|
+
*/
|
|
5954
|
+
getUnreachedStrandMachines(strandId) {
|
|
5955
|
+
return this.strandManager.unreachedPartyMachines(strandId);
|
|
5956
|
+
}
|
|
5738
5957
|
/**
|
|
5739
5958
|
* Publish a strand row to the shared control database under this node's own
|
|
5740
5959
|
* owner identity, so other cadre members discover it via control-network
|
|
@@ -6566,7 +6785,7 @@ export class CadreNode {
|
|
|
6566
6785
|
offline: this.config.strandOffline && {
|
|
6567
6786
|
...this.config.strandOffline,
|
|
6568
6787
|
onOfflineStatus: (event) => this.handleOfflineStatus(event),
|
|
6569
|
-
onQueueState: (event) => this.
|
|
6788
|
+
onQueueState: (event) => this.handleQueueState(event)
|
|
6570
6789
|
},
|
|
6571
6790
|
appSchema: {
|
|
6572
6791
|
onAppSchemaDeferred: (event) => this.emit('strand:app-schema-deferred', event),
|
|
@@ -6584,6 +6803,16 @@ export class CadreNode {
|
|
|
6584
6803
|
get: () => this.pendingMembershipInvites.get(strand.Id),
|
|
6585
6804
|
clear: (settled) => this.unstageMembershipInvite(strand.Id, settled)
|
|
6586
6805
|
},
|
|
6806
|
+
// The party's machines in this strand, for every strand whether or not this machine
|
|
6807
|
+
// holds the party key: a replica publishes its own StrandPeer row through it and, on a
|
|
6808
|
+
// closed strand, is bound by its siblings, while a machine with the key also binds them.
|
|
6809
|
+
// On a node offering offline mode the row is also what a sibling's queue waits for.
|
|
6810
|
+
partyPeers: this.partyStrandPeerSource(strand.Id),
|
|
6811
|
+
// The reconciler saw the party's pending key seated in the strand (it redeemed the host's
|
|
6812
|
+
// invitation under it, or another party's manager admitted it): the rotation driver can
|
|
6813
|
+
// now finish the move, when this is an owner machine the key is sealed to.
|
|
6814
|
+
onPartyKeySeated: (seatedStrandId) => void this.driveRotationIfPending(seatedStrandId, 'the pending key is seated in the strand'),
|
|
6815
|
+
onRemovedMachineInSeed: (seededStrandId) => this.queueSeedRemovalRebuild(seededStrandId),
|
|
6587
6816
|
// The RESOLVED flag, never the raw argument — see the doc comment above.
|
|
6588
6817
|
founder: resolvedFounder,
|
|
6589
6818
|
// Retained with the launch config, so a hibernation wake rebuilds under the
|
|
@@ -6600,6 +6829,10 @@ export class CadreNode {
|
|
|
6600
6829
|
}
|
|
6601
6830
|
this.hibernationManager.trackStrand(instance);
|
|
6602
6831
|
this.emit('strand:started', { strandId: strand.Id });
|
|
6832
|
+
// A rotation left pending for this strand (a removal made while it was not running here,
|
|
6833
|
+
// or on another machine) is finished here when this is an owner machine; a launch still
|
|
6834
|
+
// syncing has no database yet and is driven when it becomes writable.
|
|
6835
|
+
void this.driveRotationIfPending(strand.Id, 'strand launched');
|
|
6603
6836
|
return instance;
|
|
6604
6837
|
}
|
|
6605
6838
|
/**
|
|
@@ -6933,11 +7166,11 @@ export class CadreNode {
|
|
|
6933
7166
|
*
|
|
6934
7167
|
* Due times are per (sibling, strand) and set from each sibling's own outcome, so
|
|
6935
7168
|
* a sibling that connects late — a phone joining after the party's always-on
|
|
6936
|
-
* machines — is asked on the pass its connection starts, and one that
|
|
6937
|
-
*
|
|
6938
|
-
* within
|
|
6939
|
-
* {@link
|
|
6940
|
-
*
|
|
7169
|
+
* machines — is asked on the pass its connection starts, and one that gave no
|
|
7170
|
+
* address (it is restarting, its strand has not launched, or its view of the
|
|
7171
|
+
* membership does not include us yet) is retried within seconds, on the climbing
|
|
7172
|
+
* wait of {@link nextStrandAddrAsk}; the pass that stamped the retry arms a wake for
|
|
7173
|
+
* it ({@link armReconcileWake}).
|
|
6941
7174
|
*
|
|
6942
7175
|
* Distinct from {@link refreshDelegateGrants}, deliberately: that pass covers
|
|
6943
7176
|
* RELAYS on a `DELEGATE_GRANT_TTL_MS / 2` throttle to keep circuit-relay
|
|
@@ -6964,6 +7197,7 @@ export class CadreNode {
|
|
|
6964
7197
|
}
|
|
6965
7198
|
if (running.size === 0) {
|
|
6966
7199
|
this.strandAddrAskDueAt.clear();
|
|
7200
|
+
this.strandAddrAskStreak.clear();
|
|
6967
7201
|
return;
|
|
6968
7202
|
}
|
|
6969
7203
|
const targets = await this.strandAddrRefreshTargets();
|
|
@@ -6977,7 +7211,9 @@ export class CadreNode {
|
|
|
6977
7211
|
// phone restart, a new relay reservation) must be asked on its next connected
|
|
6978
7212
|
// tick. An enumeration failure prunes everything, which costs one extra round of
|
|
6979
7213
|
// asks, never a missed one.
|
|
6980
|
-
|
|
7214
|
+
const connected = new Set(targets.map((t) => t.peerId));
|
|
7215
|
+
prunePeerStrandKeys(this.strandAddrAskDueAt, running, connected);
|
|
7216
|
+
prunePeerStrandKeys(this.strandAddrAskStreak, running, connected);
|
|
6981
7217
|
await Promise.all([...running].map((strandId) => this.refreshOneStrandPeerAddrs(strandId, targets, now)));
|
|
6982
7218
|
}
|
|
6983
7219
|
/**
|
|
@@ -7123,21 +7359,20 @@ export class CadreNode {
|
|
|
7123
7359
|
}
|
|
7124
7360
|
/**
|
|
7125
7361
|
* RPC `due` siblings for `strandId` and set each one's next due time from its own
|
|
7126
|
-
* outcome
|
|
7127
|
-
*
|
|
7128
|
-
*
|
|
7129
|
-
*
|
|
7130
|
-
*
|
|
7362
|
+
* outcome ({@link nextStrandAddrAsk}). Stamped before the caller re-checks that the
|
|
7363
|
+
* strand is still running, so a strand torn down mid-pass still records who was asked.
|
|
7364
|
+
* Stamped from the pass's `now`, taken before the ask, so an ask that outlasted its wait
|
|
7365
|
+
* is due at once; that cannot spin, because the next ask has to outlast a wait at least as
|
|
7366
|
+
* long.
|
|
7131
7367
|
*/
|
|
7132
7368
|
async askSiblingsForStrandAddrs(controlNode, due, strandId, delegatePeerId, now) {
|
|
7133
7369
|
const { addrs, outcomes } = await this.collectSiblingStrandAddrs(controlNode, [...due], strandId, delegatePeerId);
|
|
7134
7370
|
const refreshMs = this.config.network?.controlCohort?.strandAddrRefreshMs ?? STRAND_PEER_ADDR_REFRESH_MS;
|
|
7135
|
-
// A configured refresh shorter than the retry must not leave a failing sibling
|
|
7136
|
-
// waiting longer than a healthy one.
|
|
7137
|
-
const retryMs = Math.min(refreshMs, STRAND_PEER_ADDR_RETRY_MS);
|
|
7138
7371
|
for (const [peerId, outcome] of outcomes) {
|
|
7139
|
-
const
|
|
7140
|
-
this.
|
|
7372
|
+
const key = peerStrandKey(peerId, strandId);
|
|
7373
|
+
const { waitMs, streak } = nextStrandAddrAsk(outcome, this.strandAddrAskStreak.get(key) ?? 0, refreshMs);
|
|
7374
|
+
this.strandAddrAskStreak.set(key, streak);
|
|
7375
|
+
this.strandAddrAskDueAt.set(key, now + waitMs);
|
|
7141
7376
|
}
|
|
7142
7377
|
return addrs;
|
|
7143
7378
|
}
|
|
@@ -8629,8 +8864,10 @@ export class CadreNode {
|
|
|
8629
8864
|
* "Writes made while alone"). A party with no other members cannot fork.
|
|
8630
8865
|
*
|
|
8631
8866
|
* What a caller does on `true` depends on the write. An `OwnerKey` add has no re-issue path at
|
|
8632
|
-
* all, so {@link addOwner}
|
|
8633
|
-
*
|
|
8867
|
+
* all, so {@link addOwner} and a local owner grant redemption refuse it `alone`.
|
|
8868
|
+
* {@link removeOwner} refuses any re-vouch `alone`: an owner row's re-add has no re-issue path,
|
|
8869
|
+
* and a peer row's new voucher is lost to the fork above while the removal's tombstone, in
|
|
8870
|
+
* another collection, still arrives. A background write nothing waits on (the self-record publishes
|
|
8634
8871
|
* {@link publishSelfRecordInBackground} makes, the pending-join runner's background attempts)
|
|
8635
8872
|
* waits for a reachable sibling.
|
|
8636
8873
|
*
|
|
@@ -8682,9 +8919,9 @@ export class CadreNode {
|
|
|
8682
8919
|
*
|
|
8683
8920
|
* Steps: re-plan ({@link planOwnerKeyRemoval}) and throw {@link OwnerKeyRemovalRefusedError}
|
|
8684
8921
|
* on a refusal; check `options.revouch` against the plan's dependents and throw before any
|
|
8685
|
-
* write when it names anything else; refuse `alone` ({@link controlWriteCouldFork}) when
|
|
8686
|
-
*
|
|
8687
|
-
* first**, under this node's key, the dependents the caller chose to keep and this node's own
|
|
8922
|
+
* write when it names anything else; refuse `alone` ({@link controlWriteCouldFork}) when any
|
|
8923
|
+
* row is to be re-vouched, this node's own included, since the new voucher might never reach
|
|
8924
|
+
* the other machines; **re-vouch first**, under this node's key, the dependents the caller chose to keep and this node's own
|
|
8688
8925
|
* row when the key vouched it (`ControlDatabase.revouchOwnerKey`, `reauthorizePeer`), so they
|
|
8689
8926
|
* are never untrusted in between, and stop before the removal if one fails (re-vouches
|
|
8690
8927
|
* already made stay, harmlessly); then the removal. The re-vouches and the removal are one owner approval. The
|
|
@@ -8707,7 +8944,7 @@ export class CadreNode {
|
|
|
8707
8944
|
throw new OwnerKeyRemovalRefusedError(key, plan.refusal);
|
|
8708
8945
|
}
|
|
8709
8946
|
const revouch = revouchWithinPlan(plan, options.revouch, this.peerId?.toString() ?? null);
|
|
8710
|
-
if (revouch.owners.length > 0 && await this.controlWriteCouldFork()) {
|
|
8947
|
+
if ((revouch.owners.length > 0 || revouch.peers.length > 0) && await this.controlWriteCouldFork()) {
|
|
8711
8948
|
throw new OwnerKeyRemovalRefusedError(key, 'alone');
|
|
8712
8949
|
}
|
|
8713
8950
|
// The plan already refused 'not-an-owner' when no enrolled signer is wired.
|
|
@@ -8755,13 +8992,9 @@ export class CadreNode {
|
|
|
8755
8992
|
* skipped.
|
|
8756
8993
|
*
|
|
8757
8994
|
* A failure rethrows and stops the call before the removal; re-vouches already made stay
|
|
8758
|
-
* (the row is only re-signed by a current owner) and the caller retries.
|
|
8759
|
-
*
|
|
8995
|
+
* (the row is only re-signed by a current owner) and the caller retries. Any re-vouch is
|
|
8996
|
+
* refused alone before this runs; one whose last connection drops while it runs is logged,
|
|
8760
8997
|
* as {@link addOwner}'s add is.
|
|
8761
|
-
*
|
|
8762
|
-
* NOTE: a peer re-touch committed alone is not queued, and the drain skips self-published
|
|
8763
|
-
* rows anyway, so the other machines may get the removal's tombstone without the new voucher
|
|
8764
|
-
* (`tickets/backlog/bug-owner-key-removal-revouch-made-alone-is-not-reissued`).
|
|
8765
8998
|
*/
|
|
8766
8999
|
async revouchDependents(service, revouch, sign) {
|
|
8767
9000
|
for (const key of revouch.owners) {
|
|
@@ -8773,6 +9006,10 @@ export class CadreNode {
|
|
|
8773
9006
|
}
|
|
8774
9007
|
for (const dependent of revouch.peers) {
|
|
8775
9008
|
await service.reauthorizePeer(dependent, 'revouch', sign);
|
|
9009
|
+
if (this.committedAlone()) {
|
|
9010
|
+
log('removeOwner: re-vouch of machine %s committed while ALONE (the last control connection dropped during the call): ' +
|
|
9011
|
+
'another member\'s write to the collection meanwhile forks it, and the other machines then drop this row.', dependent);
|
|
9012
|
+
}
|
|
8776
9013
|
}
|
|
8777
9014
|
}
|
|
8778
9015
|
/**
|
|
@@ -8789,22 +9026,27 @@ export class CadreNode {
|
|
|
8789
9026
|
}
|
|
8790
9027
|
/**
|
|
8791
9028
|
* What {@link removeMachine} would do for `peerId`, read without writing, for an app's
|
|
8792
|
-
* confirmation step ({@link MachineRemovalPlan}): whether this node may remove it
|
|
8793
|
-
* invitations it could come back through
|
|
9029
|
+
* confirmation step ({@link MachineRemovalPlan}): whether this node may remove it, which
|
|
9030
|
+
* invitations it could come back through, and where the party's key in each closed strand is
|
|
9031
|
+
* replaced (`planMachineRemoval` in `machine-removal.ts`).
|
|
8794
9032
|
*/
|
|
8795
9033
|
async planMachineRemoval(peerId) {
|
|
8796
9034
|
if (!this.controlDatabase) {
|
|
8797
9035
|
throw new Error('CadreNode must be started before planning a machine removal');
|
|
8798
9036
|
}
|
|
8799
|
-
|
|
9037
|
+
return await this.planRemovalAmong(this.controlDatabase, peerId, await this.readMachines(this.controlDatabase));
|
|
9038
|
+
}
|
|
9039
|
+
/** {@link planMachineRemoval} over `machines` already read, for {@link removeMachine}, which also seals the pending keys to them. */
|
|
9040
|
+
async planRemovalAmong(controlDatabase, peerId, machines) {
|
|
8800
9041
|
// NOTE: the invitation and usage lists come from the membership views, so on a node that
|
|
8801
9042
|
// heard of a row with no storage event (outside the block's cohort) an invitation issued
|
|
8802
9043
|
// elsewhere in the last MEMBERSHIP_VIEW_MAX_AGE_MS can be missing and left unwithdrawn. If
|
|
8803
9044
|
// removal must close that window, read both tables fresh here.
|
|
8804
|
-
const [invites, usages, owners] = await Promise.all([
|
|
8805
|
-
|
|
8806
|
-
|
|
8807
|
-
|
|
9045
|
+
const [invites, usages, owners, strands] = await Promise.all([
|
|
9046
|
+
controlDatabase.listCadreInviteStatuses(),
|
|
9047
|
+
controlDatabase.queryCadreInviteUsages(),
|
|
9048
|
+
controlDatabase.getOwnerKeys(),
|
|
9049
|
+
this.readClosedStrandStates(controlDatabase),
|
|
8808
9050
|
]);
|
|
8809
9051
|
return planMachineRemoval({
|
|
8810
9052
|
peerId,
|
|
@@ -8813,28 +9055,143 @@ export class CadreNode {
|
|
|
8813
9055
|
canSign: this.ownerSignerEnrolledIn(owners) !== null,
|
|
8814
9056
|
invites,
|
|
8815
9057
|
usages,
|
|
9058
|
+
strands,
|
|
8816
9059
|
});
|
|
8817
9060
|
}
|
|
9061
|
+
/** Every strand the party holds, own and joined. */
|
|
9062
|
+
async heldStrandRows(controlDatabase) {
|
|
9063
|
+
return [...await controlDatabase.queryStrands(), ...await controlDatabase.queryJoinedStrands()];
|
|
9064
|
+
}
|
|
9065
|
+
/**
|
|
9066
|
+
* Every closed strand the party holds a membership key for, own and joined, as this node runs
|
|
9067
|
+
* it ({@link ClosedStrandState}): the input to the plan's per-strand rotation site.
|
|
9068
|
+
*/
|
|
9069
|
+
async readClosedStrandStates(controlDatabase) {
|
|
9070
|
+
const rows = await this.heldStrandRows(controlDatabase);
|
|
9071
|
+
const states = [];
|
|
9072
|
+
const seen = new Set();
|
|
9073
|
+
for (const row of rows) {
|
|
9074
|
+
if (row.Type !== 'c' || seen.has(row.Id)) {
|
|
9075
|
+
continue;
|
|
9076
|
+
}
|
|
9077
|
+
seen.add(row.Id);
|
|
9078
|
+
const partyKey = await controlDatabase.queryStrandPartyKey(row.Id);
|
|
9079
|
+
if (partyKey !== null) {
|
|
9080
|
+
states.push(await this.closedStrandState(row.Id, partyKey));
|
|
9081
|
+
}
|
|
9082
|
+
}
|
|
9083
|
+
return states;
|
|
9084
|
+
}
|
|
9085
|
+
/**
|
|
9086
|
+
* {@link readClosedStrandStates} for one strand: its runtime here, and the party's manager seat
|
|
9087
|
+
* when a database is live and the party's key is known. A seat that cannot be read is `unknown`;
|
|
9088
|
+
* what acts on the strand finds out for itself.
|
|
9089
|
+
*/
|
|
9090
|
+
async closedStrandState(strandId, partyKey) {
|
|
9091
|
+
const instance = this.strandManager.getInstance(strandId);
|
|
9092
|
+
const db = instance?.database?.getDatabase();
|
|
9093
|
+
if (db === undefined) {
|
|
9094
|
+
return { strandId, runtime: instance?.status === 'hibernating' ? 'hibernating' : 'none', managerSeat: 'unknown' };
|
|
9095
|
+
}
|
|
9096
|
+
if (partyKey === null) {
|
|
9097
|
+
return { strandId, runtime: 'live', managerSeat: 'unknown' };
|
|
9098
|
+
}
|
|
9099
|
+
try {
|
|
9100
|
+
return { strandId, runtime: 'live', managerSeat: await isStrandManager(db, strandMemberKeyPair(partyKey).publicKeyB64) };
|
|
9101
|
+
}
|
|
9102
|
+
catch (error) {
|
|
9103
|
+
log('The manager seat of strand %s could not be read: %o', strandId, error);
|
|
9104
|
+
return { strandId, runtime: 'live', managerSeat: 'unknown' };
|
|
9105
|
+
}
|
|
9106
|
+
}
|
|
9107
|
+
/**
|
|
9108
|
+
* The party key replacements still waiting, for an app to list until each one finishes
|
|
9109
|
+
* ({@link PendingPartyKeyRotation}): one entry per live `PendingStrandPartyKey` row whose strand
|
|
9110
|
+
* the party still holds, own or joined. A row left behind by a joined strand the party has left
|
|
9111
|
+
* waits for a re-formation and is not listed. Public columns only, so a row sealed to other
|
|
9112
|
+
* machines lists too. Empty on a machine removed from the cadre, which cannot act on what it holds.
|
|
9113
|
+
*
|
|
9114
|
+
* NOTE: no event announces a change here; an app reads this on `strand:party-key-rotation-blocked`,
|
|
9115
|
+
* `strand:party-key-rotated` and after its own {@link removeMachine}, so a second device of the
|
|
9116
|
+
* party sees a row replicated to it on its next read. If an app ever needs a push, emit from
|
|
9117
|
+
* {@link onPartyKeyTablesChanged}.
|
|
9118
|
+
*
|
|
9119
|
+
* NOTE: `waitingOn` does not look at who the key is sealed to. If the party loses every machine a
|
|
9120
|
+
* row is sealed to and recovers as docs/strands.md describes (deleting its `StrandPartyKey` row,
|
|
9121
|
+
* re-joining under a fresh key), the row stays listed as `owner-machine`, then `another-party`,
|
|
9122
|
+
* though no machine can open it; only a later removal replaces it. If an app ever reaches this,
|
|
9123
|
+
* compare `partyKeyRecipients(row.sealedKey)` with the live machines and add a state for it.
|
|
9124
|
+
*/
|
|
9125
|
+
async listPendingPartyKeyRotations() {
|
|
9126
|
+
if (!this.controlDatabase) {
|
|
9127
|
+
throw new Error('CadreNode must be started before listing pending party key rotations');
|
|
9128
|
+
}
|
|
9129
|
+
if (this.removal !== null) {
|
|
9130
|
+
return [];
|
|
9131
|
+
}
|
|
9132
|
+
const controlDatabase = this.controlDatabase;
|
|
9133
|
+
const pending = await controlDatabase.queryPendingStrandPartyKeys();
|
|
9134
|
+
if (pending.size === 0) {
|
|
9135
|
+
return [];
|
|
9136
|
+
}
|
|
9137
|
+
const held = new Set((await this.heldStrandRows(controlDatabase)).map((row) => row.Id));
|
|
9138
|
+
const rotations = [];
|
|
9139
|
+
for (const [strandId, row] of pending) {
|
|
9140
|
+
if (held.has(strandId)) {
|
|
9141
|
+
const partyKey = await controlDatabase.queryStrandPartyKey(strandId);
|
|
9142
|
+
const strand = await this.pendingRotationStrandState(strandId, partyKey, row.publicKey);
|
|
9143
|
+
rotations.push({ strandId, publicKey: row.publicKey, superseded: row.superseded, waitingOn: pendingRotationWaitingOn(strand) });
|
|
9144
|
+
}
|
|
9145
|
+
}
|
|
9146
|
+
return rotations;
|
|
9147
|
+
}
|
|
9148
|
+
/** {@link closedStrandState} plus the strand reads only a pending replacement asks about; a read that fails is `unknown`, so one strand mid-teardown leaves the rest of the listing standing. */
|
|
9149
|
+
async pendingRotationStrandState(strandId, partyKey, pendingPublicKey) {
|
|
9150
|
+
const closed = await this.closedStrandState(strandId, partyKey);
|
|
9151
|
+
const db = this.strandManager.getInstance(strandId)?.database?.getDatabase();
|
|
9152
|
+
if (db === undefined) {
|
|
9153
|
+
return { ...closed, sealed: 'unknown', pendingKeySeated: 'unknown' };
|
|
9154
|
+
}
|
|
9155
|
+
try {
|
|
9156
|
+
return { ...closed, sealed: await isStrandSealed(db), pendingKeySeated: await isStrandMember(db, pendingPublicKey) };
|
|
9157
|
+
}
|
|
9158
|
+
catch (error) {
|
|
9159
|
+
log('The pending party key state of strand %s could not be read: %o', strandId, error);
|
|
9160
|
+
return { ...closed, sealed: 'unknown', pendingKeySeated: 'unknown' };
|
|
9161
|
+
}
|
|
9162
|
+
}
|
|
8818
9163
|
/**
|
|
8819
9164
|
* Remove a machine from the cadre completely, signed by this node's owner key: its
|
|
8820
|
-
* `CadrePeer` row, its `DeviceToken` row (a removed phone must not be push-woken)
|
|
8821
|
-
* withdrawal of every live invitation it could redeem to come back,
|
|
8822
|
-
*
|
|
9165
|
+
* `CadrePeer` row, its `DeviceToken` row (a removed phone must not be push-woken), a
|
|
9166
|
+
* withdrawal of every live invitation it could redeem to come back, and a
|
|
9167
|
+
* `PendingStrandPartyKey` row per closed strand the party holds a key for, in ONE transaction
|
|
9168
|
+
* ({@link ControlDatabase.removeMachine}), with a `Revocation` tombstone per removed row so the
|
|
8823
9169
|
* removal holds on every machine ("Deletes made while alone" in docs/architecture.md), under
|
|
8824
|
-
* one owner approval.
|
|
9170
|
+
* one owner approval. The pending row reaches the removed machine in that same transaction, so
|
|
9171
|
+
* the fresh key rides in it sealed to the machines that remain
|
|
9172
|
+
* ({@link pendingPartyKeyRecipients}): the removed machine holds the row and cannot open it. Afterwards this node forgets the machine as a dial target, and the
|
|
8825
9173
|
* refresh the write notifies hangs up its control connection ({@link hangUpRevokedControlPeers})
|
|
8826
9174
|
* before this resolves.
|
|
8827
9175
|
*
|
|
9176
|
+
* Then, for each closed strand that runs here (a hibernating one is woken first), the party
|
|
9177
|
+
* moves onto the fresh key in the strand's own rows and the control record
|
|
9178
|
+
* (`strand-party-key-rotation.ts`; a second owner approval for the swap), so the removed
|
|
9179
|
+
* machine is left holding a key that is no longer a member there and every machine's
|
|
9180
|
+
* revoked-peer gate denies it. The result says per strand whether that happened here
|
|
9181
|
+
* ({@link MachineRemovalResult.strands}): a strand not running here is finished by any owner
|
|
9182
|
+
* machine that runs it, and a strand the party does not manage waits for the other party's
|
|
9183
|
+
* manager.
|
|
9184
|
+
*
|
|
8828
9185
|
* Owner keys stay: they are the person's, not the machine's. A lost phone that held one can
|
|
8829
9186
|
* still sign, a fresh machine invitation it could redeem included, so removing that key
|
|
8830
9187
|
* ({@link removeOwner}) is the step that locks it out.
|
|
8831
9188
|
*
|
|
8832
|
-
* Not undone by this call: the machine keeps every row and strand block it already synced
|
|
8833
|
-
* and
|
|
8834
|
-
*
|
|
9189
|
+
* Not undone by this call: the machine keeps every row and strand block it already synced,
|
|
9190
|
+
* and each strand's read secret, so it can still read the blocks it holds. A fresh invitation
|
|
9191
|
+
* re-admits it later under fresh stamps.
|
|
8835
9192
|
*
|
|
8836
|
-
* @returns what was written ({@link MachineRemovalResult}); all false
|
|
8837
|
-
* the machine here (already removed elsewhere).
|
|
9193
|
+
* @returns what was written and rotated ({@link MachineRemovalResult}); all false and empty when
|
|
9194
|
+
* no live row names the machine here (already removed elsewhere).
|
|
8838
9195
|
* @throws {MachineRemovalRefusedError} `'not-an-owner'` or `'self'`, before any write.
|
|
8839
9196
|
*/
|
|
8840
9197
|
async removeMachine(peerId) {
|
|
@@ -8842,15 +9199,18 @@ export class CadreNode {
|
|
|
8842
9199
|
if (!service || !this.controlDatabase) {
|
|
8843
9200
|
throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
|
|
8844
9201
|
}
|
|
8845
|
-
const
|
|
9202
|
+
const machines = await this.readMachines(this.controlDatabase);
|
|
9203
|
+
const plan = await this.planRemovalAmong(this.controlDatabase, peerId, machines);
|
|
8846
9204
|
if (plan.refusal !== null) {
|
|
8847
9205
|
throw new MachineRemovalRefusedError(peerId, plan.refusal);
|
|
8848
9206
|
}
|
|
8849
9207
|
if (plan.machine === null) {
|
|
8850
9208
|
log('removeMachine(%s): no live row names it here; nothing to remove', peerId);
|
|
8851
|
-
return { removedPeer: false, removedDeviceToken: false, withdrawnInvitations: [] };
|
|
9209
|
+
return { removedPeer: false, removedDeviceToken: false, withdrawnInvitations: [], strands: [] };
|
|
8852
9210
|
}
|
|
8853
|
-
const
|
|
9211
|
+
const recipients = this.pendingPartyKeyRecipients(machines, peerId);
|
|
9212
|
+
const pendingPartyKeys = await Promise.all(plan.strands.map((strand) => this.mintPendingPartyKey(strand.strandId, recipients)));
|
|
9213
|
+
const writes = await service.removeMachine({ peerId, inviteKeys: plan.invitations, pendingPartyKeys });
|
|
8854
9214
|
if (writes.removedPeer) {
|
|
8855
9215
|
// Track + loudly flag a delete that committed local-only (security-relevant).
|
|
8856
9216
|
this.noteControlWrite(peerId, 'remove');
|
|
@@ -8860,15 +9220,254 @@ export class CadreNode {
|
|
|
8860
9220
|
void this.bootstrapPeerStore?.forget(peerId).catch((error) => {
|
|
8861
9221
|
log('removeMachine: persisting the removal of dial target %s failed (forgotten in memory): %o', peerId, error);
|
|
8862
9222
|
});
|
|
8863
|
-
log('removeMachine(%s): peer=%s deviceToken=%s invitations=%d', peerId, writes.removedPeer, writes.removedDeviceToken, writes.withdrawnInvitations.length);
|
|
8864
|
-
|
|
9223
|
+
log('removeMachine(%s): peer=%s deviceToken=%s invitations=%d strands=%d', peerId, writes.removedPeer, writes.removedDeviceToken, writes.withdrawnInvitations.length, plan.strands.length);
|
|
9224
|
+
const strands = writes.removedPeer ? await this.rotateAfterRemoval(plan.strands) : plan.strands.map((strand) => ({ strandId: strand.strandId, outcome: 'pending' }));
|
|
9225
|
+
return { ...writes, strands };
|
|
9226
|
+
}
|
|
9227
|
+
/**
|
|
9228
|
+
* The strand side of {@link removeMachine}: every strand the plan placed here is woken if it
|
|
9229
|
+
* hibernates, then driven through the rotation; a strand placed `later` is reported `pending`
|
|
9230
|
+
* without being touched. Never rejects: a wake that fails leaves its strand `pending`, as does an
|
|
9231
|
+
* offline queue holding transactions, whose drain drives it ({@link handleQueueState}).
|
|
9232
|
+
*/
|
|
9233
|
+
async rotateAfterRemoval(plans) {
|
|
9234
|
+
const here = plans.filter((plan) => plan.rotation !== 'later').map((plan) => plan.strandId);
|
|
9235
|
+
for (const strandId of here) {
|
|
9236
|
+
await this.wakeForRotation(strandId);
|
|
9237
|
+
}
|
|
9238
|
+
const driven = new Map((await this.partyKeyRotation.drive(here, 'machine removal')).map((outcome) => [outcome.strandId, outcome.outcome]));
|
|
9239
|
+
return plans.map((plan) => ({ strandId: plan.strandId, outcome: driven.get(plan.strandId) ?? 'pending' }));
|
|
9240
|
+
}
|
|
9241
|
+
/** Wake a hibernating strand so a rotation can run against its database; a failure is logged, and the strand stays pending. */
|
|
9242
|
+
async wakeForRotation(strandId) {
|
|
9243
|
+
const instance = this.strandManager.getInstance(strandId);
|
|
9244
|
+
if (!instance || instance.database || instance.status !== 'hibernating') {
|
|
9245
|
+
return;
|
|
9246
|
+
}
|
|
9247
|
+
try {
|
|
9248
|
+
await this.wakeStrand(strandId);
|
|
9249
|
+
}
|
|
9250
|
+
catch (error) {
|
|
9251
|
+
log('removeMachine: waking hibernating strand %s for its party key rotation failed (left pending): %o', strandId, error);
|
|
9252
|
+
}
|
|
9253
|
+
}
|
|
9254
|
+
/**
|
|
9255
|
+
* Who may open the pending keys a removal of `removedPeerId` writes: every live machine this
|
|
9256
|
+
* node trusts, and this node itself, the removed machine left out, each under the identity key
|
|
9257
|
+
* its peer id carries (`CadreMachine.publicKey`, derived from the id, never a stored column).
|
|
9258
|
+
* Which machines hold an owner key is recorded nowhere, so every one of them is a recipient.
|
|
9259
|
+
* This node is added from its own identity key, so it is a recipient before its own `CadrePeer`
|
|
9260
|
+
* row has landed.
|
|
9261
|
+
* NOTE: a node on an ephemeral identity (tests only; see {@link isControlNetworkMember}) seals to
|
|
9262
|
+
* the others alone and cannot drive what it wrote: logged, never a refusal, since locking out a
|
|
9263
|
+
* lost phone must not fail on it. If such a node ever becomes a supported deployment, it needs a
|
|
9264
|
+
* key to seal to.
|
|
9265
|
+
*
|
|
9266
|
+
* NOTE: a machine admitted after the removal is not a recipient, so an owner machine enrolled
|
|
9267
|
+
* while a rotation is pending cannot drive it; a recipient owner machine has to finish it. If a
|
|
9268
|
+
* party is seen stuck that way, the remedy is the replacement a second removal already writes
|
|
9269
|
+
* (`ControlDatabase.removeMachine`), minted for the machines present then.
|
|
9270
|
+
*/
|
|
9271
|
+
pendingPartyKeyRecipients(machines, removedPeerId) {
|
|
9272
|
+
const recipients = new Map();
|
|
9273
|
+
for (const machine of machines) {
|
|
9274
|
+
if (machine.peerId !== removedPeerId && (machine.isSelf || machine.trusted) && machine.publicKey !== null) {
|
|
9275
|
+
recipients.set(machine.peerId, { peerId: machine.peerId, publicKeyB64: machine.publicKey });
|
|
9276
|
+
}
|
|
9277
|
+
}
|
|
9278
|
+
const self = this.selfPartyKeyIdentity();
|
|
9279
|
+
if (self === null) {
|
|
9280
|
+
log('removeMachine: this node runs on an ephemeral identity, so the pending party keys it writes are sealed to the other machines only and cannot be driven here');
|
|
9281
|
+
}
|
|
9282
|
+
else {
|
|
9283
|
+
recipients.set(self.peerId, { peerId: self.peerId, publicKeyB64: self.publicKeyB64 });
|
|
9284
|
+
}
|
|
9285
|
+
return [...recipients.values()];
|
|
9286
|
+
}
|
|
9287
|
+
/** This machine as a sealed party key sees it: its control peer id with the identity key behind it ({@link getSelfSigningKey}), or null on an ephemeral identity. */
|
|
9288
|
+
selfPartyKeyIdentity() {
|
|
9289
|
+
const peerId = this.controlNode?.peerId.toString();
|
|
9290
|
+
const key = this.getSelfSigningKey();
|
|
9291
|
+
return peerId !== undefined && key !== null ? { peerId, ...key } : null;
|
|
9292
|
+
}
|
|
9293
|
+
/** The `PendingStrandPartyKey` row a removal writes for one strand: a fresh key, its public half in the clear and its private half sealed to `recipients`. */
|
|
9294
|
+
async mintPendingPartyKey(strandId, recipients) {
|
|
9295
|
+
const privateKey = await generateStrandMemberKey();
|
|
9296
|
+
return { strandId, publicKey: strandMemberKeyPair(privateKey).publicKeyB64, sealedKey: sealPartyKey(privateKey, strandId, recipients) };
|
|
9297
|
+
}
|
|
9298
|
+
/**
|
|
9299
|
+
* {@link StrandPartyKeyRotationDeps.readPending}: the strand's pending row with its key opened
|
|
9300
|
+
* under this machine's identity key, or null when none is pending. Rejects when the row is not
|
|
9301
|
+
* sealed to this machine, or this node runs on an ephemeral identity and can open nothing; the
|
|
9302
|
+
* driver then reports the strand `pending` with a log, and a recipient owner machine finishes
|
|
9303
|
+
* it. The background triggers ask {@link isPendingPartyKeyRecipient} first, so only the
|
|
9304
|
+
* removal's own drive reaches that rejection.
|
|
9305
|
+
*/
|
|
9306
|
+
async openPendingPartyKey(strandId) {
|
|
9307
|
+
const read = await this.readPendingPartyKey(strandId);
|
|
9308
|
+
switch (read.kind) {
|
|
9309
|
+
case 'none':
|
|
9310
|
+
return null;
|
|
9311
|
+
case 'opened':
|
|
9312
|
+
return read.key;
|
|
9313
|
+
case 'closed':
|
|
9314
|
+
throw new Error(read.why);
|
|
9315
|
+
}
|
|
9316
|
+
}
|
|
9317
|
+
/**
|
|
9318
|
+
* {@link PartyStrandPeerSource.pendingKey} for one strand: the same read as
|
|
9319
|
+
* {@link openPendingPartyKey}, answering a null key rather than rejecting when the row does not
|
|
9320
|
+
* open here, so the membership reconciler can tell "no rotation" from "a rotation this machine
|
|
9321
|
+
* cannot take part in" and neither consume nor burn an invitation in the latter case.
|
|
9322
|
+
*/
|
|
9323
|
+
async readPendingPartyKeyState(strandId) {
|
|
9324
|
+
const read = await this.readPendingPartyKey(strandId);
|
|
9325
|
+
switch (read.kind) {
|
|
9326
|
+
case 'none':
|
|
9327
|
+
return { pending: false };
|
|
9328
|
+
case 'opened':
|
|
9329
|
+
return { pending: true, key: read.key };
|
|
9330
|
+
case 'closed':
|
|
9331
|
+
return { pending: true, key: null };
|
|
9332
|
+
}
|
|
9333
|
+
}
|
|
9334
|
+
/**
|
|
9335
|
+
* One strand's `PendingStrandPartyKey` row as this machine can read it, shared by the driver's
|
|
9336
|
+
* seam and the reconciler's. Rejects when the row cannot be read, or carries an envelope that
|
|
9337
|
+
* does not decode or was sealed for another strand (`openPartyKey` throws on both).
|
|
9338
|
+
*/
|
|
9339
|
+
async readPendingPartyKey(strandId) {
|
|
9340
|
+
const row = await this.requireControlDatabase('read a pending strand party key').queryPendingStrandPartyKey(strandId);
|
|
9341
|
+
if (row === null) {
|
|
9342
|
+
return { kind: 'none' };
|
|
9343
|
+
}
|
|
9344
|
+
const self = this.selfPartyKeyIdentity();
|
|
9345
|
+
if (self === null) {
|
|
9346
|
+
return { kind: 'closed', why: `the pending party key of strand ${strandId} cannot be opened: this node runs on an ephemeral identity` };
|
|
9347
|
+
}
|
|
9348
|
+
const privateKey = openPartyKey(row.sealedKey, strandId, self);
|
|
9349
|
+
if (privateKey === null) {
|
|
9350
|
+
return { kind: 'closed', why: `the pending party key of strand ${strandId} is sealed to other machines, not to this one` };
|
|
9351
|
+
}
|
|
9352
|
+
return { kind: 'opened', key: { privateKey, superseded: row.superseded, stampId: row.stampId } };
|
|
9353
|
+
}
|
|
9354
|
+
/**
|
|
9355
|
+
* Whether `row`'s key is sealed to this machine. The background triggers ask before driving, so
|
|
9356
|
+
* a machine the key was not sealed to (admitted after the removal, or on an ephemeral identity)
|
|
9357
|
+
* logs one line rather than a failed run on every change of the table.
|
|
9358
|
+
*/
|
|
9359
|
+
isPendingPartyKeyRecipient(strandId, row) {
|
|
9360
|
+
const peerId = this.controlNode?.peerId.toString();
|
|
9361
|
+
if (peerId !== undefined && partyKeyRecipients(row.sealedKey).includes(peerId)) {
|
|
9362
|
+
return true;
|
|
9363
|
+
}
|
|
9364
|
+
log('Party key rotation pending for strand %s is sealed to other machines; one of them finishes it', strandId);
|
|
9365
|
+
return false;
|
|
9366
|
+
}
|
|
9367
|
+
/**
|
|
9368
|
+
* Drive the rotation pending for `strandId`, if one is, when this is an owner machine with the
|
|
9369
|
+
* strand's database live (`strand-party-key-rotation.ts`) and the pending key is sealed to it.
|
|
9370
|
+
* Called in the background from the strand lifecycle (launch, resume, writable, queue drained); a strand with
|
|
9371
|
+
* nothing pending costs one control read. Never on a machine removed from the cadre
|
|
9372
|
+
* ({@link removedFromCadre}): it may hold an owner key and a key an earlier removal sealed to
|
|
9373
|
+
* it, and it is no longer a member whatever it holds, as the owner re-issue drains already
|
|
9374
|
+
* stop. Never rejects.
|
|
9375
|
+
*/
|
|
9376
|
+
async driveRotationIfPending(strandId, cause) {
|
|
9377
|
+
try {
|
|
9378
|
+
if (!this._running || !this.controlDatabase || this.removal !== null || !this.strandManager.getInstance(strandId)?.database) {
|
|
9379
|
+
return;
|
|
9380
|
+
}
|
|
9381
|
+
const pending = await this.controlDatabase.queryPendingStrandPartyKey(strandId);
|
|
9382
|
+
if (pending === null || !this.isPendingPartyKeyRecipient(strandId, pending)) {
|
|
9383
|
+
return;
|
|
9384
|
+
}
|
|
9385
|
+
if (await this.enrolledOwnerSigner() === null) {
|
|
9386
|
+
log('Party key rotation pending for strand %s; this machine holds no enrolled owner key, so an owner machine running the strand finishes it', strandId);
|
|
9387
|
+
return;
|
|
9388
|
+
}
|
|
9389
|
+
await this.partyKeyRotation.drive([strandId], cause);
|
|
9390
|
+
}
|
|
9391
|
+
catch (error) {
|
|
9392
|
+
log('Party key rotation of strand %s (%s) could not be driven: %o', strandId, cause, error);
|
|
9393
|
+
}
|
|
9394
|
+
}
|
|
9395
|
+
/** {@link driveRotationIfPending} for every closed strand running here, one run; for the watch and the growth drain. */
|
|
9396
|
+
async driveTrackedPendingRotations(cause) {
|
|
9397
|
+
if (!this._running || !this.controlDatabase || this.removal !== null) {
|
|
9398
|
+
return;
|
|
9399
|
+
}
|
|
9400
|
+
const pending = [];
|
|
9401
|
+
for (const strandId of this.strandManager.trackedClosedStrandIds()) {
|
|
9402
|
+
try {
|
|
9403
|
+
if (!this.strandManager.getInstance(strandId)?.database) {
|
|
9404
|
+
continue;
|
|
9405
|
+
}
|
|
9406
|
+
const row = await this.controlDatabase.queryPendingStrandPartyKey(strandId);
|
|
9407
|
+
if (row !== null && this.isPendingPartyKeyRecipient(strandId, row)) {
|
|
9408
|
+
pending.push(strandId);
|
|
9409
|
+
}
|
|
9410
|
+
}
|
|
9411
|
+
catch (error) {
|
|
9412
|
+
log('Pending party key of strand %s could not be read (%s): %o', strandId, cause, error);
|
|
9413
|
+
}
|
|
9414
|
+
}
|
|
9415
|
+
if (pending.length === 0) {
|
|
9416
|
+
return;
|
|
9417
|
+
}
|
|
9418
|
+
if (await this.enrolledOwnerSigner() === null) {
|
|
9419
|
+
log('Party key rotation pending for %d strand(s); this machine holds no enrolled owner key, so an owner machine running them finishes it', pending.length);
|
|
9420
|
+
return;
|
|
9421
|
+
}
|
|
9422
|
+
await this.partyKeyRotation.drive(pending, cause);
|
|
9423
|
+
}
|
|
9424
|
+
/**
|
|
9425
|
+
* The party key watch's run: for every tracked closed strand, re-key the instance when the
|
|
9426
|
+
* `StrandPartyKey` row names a key other than the one it runs under (a rotation finished on
|
|
9427
|
+
* another machine), then drive whatever rotation is pending here.
|
|
9428
|
+
*/
|
|
9429
|
+
async onPartyKeyTablesChanged() {
|
|
9430
|
+
if (!this._running || !this.controlDatabase) {
|
|
9431
|
+
return;
|
|
9432
|
+
}
|
|
9433
|
+
for (const strandId of this.strandManager.trackedClosedStrandIds()) {
|
|
9434
|
+
try {
|
|
9435
|
+
const stored = await this.controlDatabase.queryStrandPartyKey(strandId);
|
|
9436
|
+
if (stored !== null && await this.strandManager.rekeyParty(strandId, stored) !== 'unchanged') {
|
|
9437
|
+
log('Strand %s re-keyed to the party key the control record names', strandId);
|
|
9438
|
+
}
|
|
9439
|
+
}
|
|
9440
|
+
catch (error) {
|
|
9441
|
+
log('Re-keying strand %s from the control record failed (retried on the next change): %o', strandId, error);
|
|
9442
|
+
}
|
|
9443
|
+
}
|
|
9444
|
+
await this.driveTrackedPendingRotations('party key tables changed');
|
|
9445
|
+
}
|
|
9446
|
+
/**
|
|
9447
|
+
* Step 6 of a party key rotation ({@link StrandPartyKeyRotationDeps.swapKeys}): the control
|
|
9448
|
+
* swap for every entry under one owner approval, deferred while a control write could fork the
|
|
9449
|
+
* party ({@link controlWriteCouldFork}); the growth drain re-drives it. The tombstones it files
|
|
9450
|
+
* ride the committed-delete seam like every other removal's.
|
|
9451
|
+
*/
|
|
9452
|
+
async swapStrandPartyKeys(entries) {
|
|
9453
|
+
const service = this.seedBootstrapService;
|
|
9454
|
+
if (!service || !this._running) {
|
|
9455
|
+
throw new Error('CadreNode is stopped: no owner service to swap a strand party key');
|
|
9456
|
+
}
|
|
9457
|
+
if (await this.controlWriteCouldFork()) {
|
|
9458
|
+
return 'deferred';
|
|
9459
|
+
}
|
|
9460
|
+
return await service.swapStrandPartyKeys(entries);
|
|
8865
9461
|
}
|
|
8866
9462
|
/**
|
|
8867
9463
|
* The read behind {@link listMachines}: the live `CadrePeer` rows projected as machines, with
|
|
8868
9464
|
* this node's membership predicate as the `trusted` test.
|
|
8869
9465
|
*/
|
|
8870
9466
|
async readMachines(controlDatabase) {
|
|
8871
|
-
|
|
9467
|
+
return await this.describeMachineRows(controlDatabase, await controlDatabase.queryCadrePeers());
|
|
9468
|
+
}
|
|
9469
|
+
/** {@link readMachines} over `rows` already read, for a caller that read them fresh. */
|
|
9470
|
+
async describeMachineRows(controlDatabase, rows) {
|
|
8872
9471
|
const chain = await this.chainFor(rows, this.invitationChainSource(controlDatabase, true));
|
|
8873
9472
|
const selfPeerId = this.peerId?.toString() ?? null;
|
|
8874
9473
|
return describeMachines({
|
|
@@ -8878,6 +9477,89 @@ export class CadreNode {
|
|
|
8878
9477
|
trusted: (row) => row.peerId !== selfPeerId && this.hasAnchoredProof(row, chain),
|
|
8879
9478
|
});
|
|
8880
9479
|
}
|
|
9480
|
+
/**
|
|
9481
|
+
* The control-database seam of one strand's launch for the party's machines in it
|
|
9482
|
+
* (`StartStrandConfig.partyPeers`, `strand-party-peers.ts`): this machine's own `StrandPeer`
|
|
9483
|
+
* row, the party's other machines' peer ids, and the party's pending key in the strand as this
|
|
9484
|
+
* machine can read it. The reads reject rather than answer "nothing" when the control database
|
|
9485
|
+
* is gone, which the reconciler and the offline queue's machine tracker treat as "unknown".
|
|
9486
|
+
*/
|
|
9487
|
+
partyStrandPeerSource(strandId) {
|
|
9488
|
+
return {
|
|
9489
|
+
publishOwn: (strandPeerId) => this.publishStrandPeer(strandId, strandPeerId),
|
|
9490
|
+
read: () => this.readPartyStrandPeers(strandId),
|
|
9491
|
+
pendingKey: () => this.readPendingPartyKeyState(strandId),
|
|
9492
|
+
};
|
|
9493
|
+
}
|
|
9494
|
+
/** The control database, or a throw naming what `purpose` needed it for, for a seam whose caller contains the throw. */
|
|
9495
|
+
requireControlDatabase(purpose) {
|
|
9496
|
+
if (!this._running || !this.controlDatabase) {
|
|
9497
|
+
throw new Error(`CadreNode is stopped: no control database to ${purpose}`);
|
|
9498
|
+
}
|
|
9499
|
+
return this.controlDatabase;
|
|
9500
|
+
}
|
|
9501
|
+
/**
|
|
9502
|
+
* Publish this machine's peer id in `strandId` to the party's control database — its
|
|
9503
|
+
* `StrandPeer` row, signed by the identity key as the self record is
|
|
9504
|
+
* ({@link ControlDatabase.insertStrandPeer}). Insert-if-absent, and remembered once present
|
|
9505
|
+
* ({@link strandPeerRowsHeld}), so the per-pass re-attempt the membership reconciler makes
|
|
9506
|
+
* costs nothing after the first. A background write like the self-record publish: nothing is
|
|
9507
|
+
* written while a write could fork the party ({@link controlWriteCouldFork}), and a refusal —
|
|
9508
|
+
* the schema wants this machine's own `CadrePeer` row, which may not have reached this node —
|
|
9509
|
+
* is logged; either leaves the row in {@link deferredStrandPeerWrites} for the growth drain,
|
|
9510
|
+
* the party-machine watch and the next reconciler pass. Written regardless of whether this machine holds the party's
|
|
9511
|
+
* member key: a storage replica is bound by its siblings. A node on an ephemeral identity
|
|
9512
|
+
* cannot sign the row and writes nothing. Never rejects.
|
|
9513
|
+
*/
|
|
9514
|
+
async publishStrandPeer(strandId, strandPeerId) {
|
|
9515
|
+
if (this.strandPeerRowsHeld.has(strandId) || !this._running || !this.controlDatabase) {
|
|
9516
|
+
return;
|
|
9517
|
+
}
|
|
9518
|
+
if (await this.controlWriteCouldFork()) {
|
|
9519
|
+
this.deferredStrandPeerWrites.set(strandId, strandPeerId);
|
|
9520
|
+
log('StrandPeer row for strand %s deferred: no sibling reachable and the party has other members; the next growth drain writes it', strandId);
|
|
9521
|
+
return;
|
|
9522
|
+
}
|
|
9523
|
+
const signingKey = this.getSelfSigningKey();
|
|
9524
|
+
if (!signingKey) {
|
|
9525
|
+
log('StrandPeer row for strand %s not written: this node runs on an ephemeral identity and cannot sign it', strandId);
|
|
9526
|
+
return;
|
|
9527
|
+
}
|
|
9528
|
+
try {
|
|
9529
|
+
const written = await this.controlDatabase.insertStrandPeer({ strandId, strandPeerId }, ed25519MessageSigner(signingKey.privateKeyB64));
|
|
9530
|
+
this.strandPeerRowsHeld.add(strandId);
|
|
9531
|
+
this.deferredStrandPeerWrites.delete(strandId);
|
|
9532
|
+
log('StrandPeer row for strand %s %s (this machine is %s there)', strandId, written ? 'written' : 'already present', strandPeerId);
|
|
9533
|
+
}
|
|
9534
|
+
catch (error) {
|
|
9535
|
+
this.deferredStrandPeerWrites.set(strandId, strandPeerId);
|
|
9536
|
+
log('StrandPeer row for strand %s refused (this machine\'s own CadrePeer row may not be here yet); retried on cohort growth and by the next membership pass: %o', strandId, error);
|
|
9537
|
+
}
|
|
9538
|
+
}
|
|
9539
|
+
/** The re-attempt of every `StrandPeer` row in {@link deferredStrandPeerWrites} (growth drain, party-machine watch); each contains its own failure. */
|
|
9540
|
+
async publishDeferredStrandPeers() {
|
|
9541
|
+
for (const [strandId, strandPeerId] of [...this.deferredStrandPeerWrites]) {
|
|
9542
|
+
await this.publishStrandPeer(strandId, strandPeerId);
|
|
9543
|
+
}
|
|
9544
|
+
}
|
|
9545
|
+
/**
|
|
9546
|
+
* The party's machines' peer ids in `strandId` ({@link PartyStrandPeers}): the strand's
|
|
9547
|
+
* `StrandPeer` rows joined to the party's live machines and its `CadrePeer` tombstones
|
|
9548
|
+
* (`partitionPartyStrandPeers`). The membership rows are read FRESH
|
|
9549
|
+
* ({@link ControlDatabase.queryMachineRowsFresh}), not from the membership views: a
|
|
9550
|
+
* sibling that binds a machine under the party's new key from a view that has not heard
|
|
9551
|
+
* of the machine's removal would bind the machine the rotation exists to shut out, and
|
|
9552
|
+
* the views' lag is exactly that window. Rejects when any read fails; never answers
|
|
9553
|
+
* "no machines" for a failed read.
|
|
9554
|
+
*/
|
|
9555
|
+
async readPartyStrandPeers(strandId) {
|
|
9556
|
+
const controlDatabase = this.requireControlDatabase('read the party\'s strand peers');
|
|
9557
|
+
const [rows, { peers, tombstones }] = await Promise.all([
|
|
9558
|
+
controlDatabase.queryStrandPeers(strandId),
|
|
9559
|
+
controlDatabase.queryMachineRowsFresh(),
|
|
9560
|
+
]);
|
|
9561
|
+
return partitionPartyStrandPeers(rows, await this.describeMachineRows(controlDatabase, peers), tombstones);
|
|
9562
|
+
}
|
|
8881
9563
|
/**
|
|
8882
9564
|
* Create a seed from the current control network state.
|
|
8883
9565
|
* The seed contains peer information and is signed by an owner.
|