@serfab/cadre-core 1.14.0 → 1.16.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 (171) hide show
  1. package/README.md +293 -274
  2. package/dist/cadre-invite-protocol.d.ts +64 -29
  3. package/dist/cadre-invite-protocol.js +207 -38
  4. package/dist/cadre-invite-protocol.js.map +1 -1
  5. package/dist/cadre-join-request.d.ts +42 -0
  6. package/dist/cadre-join-request.js +144 -0
  7. package/dist/cadre-join-request.js.map +1 -0
  8. package/dist/cadre-node.d.ts +375 -79
  9. package/dist/cadre-node.js +758 -186
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/control-database.d.ts +92 -12
  12. package/dist/control-database.js +323 -142
  13. package/dist/control-database.js.map +1 -1
  14. package/dist/control-schema.d.ts +1 -1
  15. package/dist/control-schema.js +19 -3
  16. package/dist/control-schema.js.map +1 -1
  17. package/dist/ed25519-key.d.ts +7 -9
  18. package/dist/ed25519-key.js +20 -10
  19. package/dist/ed25519-key.js.map +1 -1
  20. package/dist/fetch-impl.d.ts +12 -0
  21. package/dist/fetch-impl.js +23 -0
  22. package/dist/fetch-impl.js.map +1 -0
  23. package/dist/file-durable-slot.js +2 -1
  24. package/dist/file-durable-slot.js.map +1 -1
  25. package/dist/file-safe-name.d.ts +25 -0
  26. package/dist/file-safe-name.js +29 -0
  27. package/dist/file-safe-name.js.map +1 -0
  28. package/dist/formation-approval.js +5 -11
  29. package/dist/formation-approval.js.map +1 -1
  30. package/dist/fs-atomic.d.ts +0 -19
  31. package/dist/fs-atomic.js +3 -24
  32. package/dist/fs-atomic.js.map +1 -1
  33. package/dist/index.d.ts +12 -5
  34. package/dist/index.js +31 -6
  35. package/dist/index.js.map +1 -1
  36. package/dist/invitation-bootstrap.d.ts +50 -12
  37. package/dist/invitation-bootstrap.js +76 -13
  38. package/dist/invitation-bootstrap.js.map +1 -1
  39. package/dist/joined-strand-store.d.ts +7 -0
  40. package/dist/joined-strand-store.js +9 -0
  41. package/dist/joined-strand-store.js.map +1 -1
  42. package/dist/key-store-file.js +2 -1
  43. package/dist/key-store-file.js.map +1 -1
  44. package/dist/link-budget.d.ts +9 -4
  45. package/dist/link-budget.js +9 -4
  46. package/dist/link-budget.js.map +1 -1
  47. package/dist/machine-removal.d.ts +78 -0
  48. package/dist/machine-removal.js +166 -0
  49. package/dist/machine-removal.js.map +1 -0
  50. package/dist/membership-connection-gater.d.ts +6 -5
  51. package/dist/membership-connection-gater.js +6 -5
  52. package/dist/membership-connection-gater.js.map +1 -1
  53. package/dist/node-claim-payload.d.ts +55 -0
  54. package/dist/node-claim-payload.js +108 -4
  55. package/dist/node-claim-payload.js.map +1 -1
  56. package/dist/node-default-transports.d.ts +27 -0
  57. package/dist/node-default-transports.js +35 -0
  58. package/dist/node-default-transports.js.map +1 -0
  59. package/dist/node-transports.d.ts +30 -0
  60. package/dist/node-transports.js +40 -0
  61. package/dist/node-transports.js.map +1 -0
  62. package/dist/peer-dial.d.ts +124 -27
  63. package/dist/peer-dial.js +254 -30
  64. package/dist/peer-dial.js.map +1 -1
  65. package/dist/peer-join-backfill.js +6 -0
  66. package/dist/peer-join-backfill.js.map +1 -1
  67. package/dist/peer-record.d.ts +6 -45
  68. package/dist/peer-record.js +8 -50
  69. package/dist/peer-record.js.map +1 -1
  70. package/dist/primary-lan-address.d.ts +8 -0
  71. package/dist/primary-lan-address.js +46 -0
  72. package/dist/primary-lan-address.js.map +1 -0
  73. package/dist/provider/client.d.ts +131 -0
  74. package/dist/provider/client.js +226 -0
  75. package/dist/provider/client.js.map +1 -0
  76. package/dist/provider/descriptor.d.ts +41 -0
  77. package/dist/provider/descriptor.js +103 -0
  78. package/dist/provider/descriptor.js.map +1 -0
  79. package/dist/provider/index.d.ts +9 -0
  80. package/dist/provider/index.js +10 -0
  81. package/dist/provider/index.js.map +1 -0
  82. package/dist/provider/oauth.d.ts +125 -0
  83. package/dist/provider/oauth.js +199 -0
  84. package/dist/provider/oauth.js.map +1 -0
  85. package/dist/provider/rent-node.d.ts +101 -0
  86. package/dist/provider/rent-node.js +220 -0
  87. package/dist/provider/rent-node.js.map +1 -0
  88. package/dist/relay-addrs.d.ts +9 -4
  89. package/dist/relay-addrs.js +9 -4
  90. package/dist/relay-addrs.js.map +1 -1
  91. package/dist/relay-reservation.d.ts +51 -16
  92. package/dist/relay-reservation.js +107 -24
  93. package/dist/relay-reservation.js.map +1 -1
  94. package/dist/seed-bootstrap.d.ts +22 -5
  95. package/dist/seed-bootstrap.js +48 -25
  96. package/dist/seed-bootstrap.js.map +1 -1
  97. package/dist/strand-commit-durability.d.ts +54 -0
  98. package/dist/strand-commit-durability.js +74 -0
  99. package/dist/strand-commit-durability.js.map +1 -0
  100. package/dist/strand-database.d.ts +23 -8
  101. package/dist/strand-database.js +41 -13
  102. package/dist/strand-database.js.map +1 -1
  103. package/dist/strand-first-sync-gate.d.ts +7 -1
  104. package/dist/strand-first-sync-gate.js +7 -1
  105. package/dist/strand-first-sync-gate.js.map +1 -1
  106. package/dist/strand-formation-protocol.js +4 -1
  107. package/dist/strand-formation-protocol.js.map +1 -1
  108. package/dist/strand-fret-addrs.d.ts +19 -1
  109. package/dist/strand-fret-addrs.js +27 -9
  110. package/dist/strand-fret-addrs.js.map +1 -1
  111. package/dist/strand-instance-manager.d.ts +81 -19
  112. package/dist/strand-instance-manager.js +216 -105
  113. package/dist/strand-instance-manager.js.map +1 -1
  114. package/dist/strand-move.d.ts +124 -0
  115. package/dist/strand-move.js +438 -0
  116. package/dist/strand-move.js.map +1 -0
  117. package/dist/strand-network-config.js +7 -6
  118. package/dist/strand-network-config.js.map +1 -1
  119. package/dist/strand-peer-redial.d.ts +113 -0
  120. package/dist/strand-peer-redial.js +236 -0
  121. package/dist/strand-peer-redial.js.map +1 -0
  122. package/dist/strand-wake-protocol.js +10 -7
  123. package/dist/strand-wake-protocol.js.map +1 -1
  124. package/dist/types.d.ts +212 -4
  125. package/dist/types.js +10 -0
  126. package/dist/types.js.map +1 -1
  127. package/package.json +18 -10
  128. package/src/cadre-invite-protocol.ts +1052 -864
  129. package/src/cadre-join-request.ts +167 -0
  130. package/src/cadre-node.ts +10003 -9381
  131. package/src/control-database.ts +4663 -4451
  132. package/src/control-schema.ts +19 -3
  133. package/src/ed25519-key.ts +20 -10
  134. package/src/fetch-impl.ts +23 -0
  135. package/src/file-durable-slot.ts +64 -63
  136. package/src/file-safe-name.ts +32 -0
  137. package/src/formation-approval.ts +604 -610
  138. package/src/fs-atomic.ts +92 -117
  139. package/src/index.ts +71 -4
  140. package/src/invitation-bootstrap.ts +91 -13
  141. package/src/joined-strand-store.ts +508 -498
  142. package/src/key-store-file.ts +142 -141
  143. package/src/link-budget.ts +9 -4
  144. package/src/machine-removal.ts +216 -0
  145. package/src/membership-connection-gater.ts +638 -637
  146. package/src/node-claim-payload.ts +138 -4
  147. package/src/node-default-transports.ts +38 -0
  148. package/src/node-transports.ts +49 -0
  149. package/src/peer-dial.ts +604 -336
  150. package/src/peer-join-backfill.ts +6 -0
  151. package/src/peer-record.ts +159 -202
  152. package/src/primary-lan-address.ts +47 -0
  153. package/src/provider/client.ts +326 -0
  154. package/src/provider/descriptor.ts +129 -0
  155. package/src/provider/index.ts +59 -0
  156. package/src/provider/oauth.ts +285 -0
  157. package/src/provider/rent-node.ts +275 -0
  158. package/src/relay-addrs.ts +9 -4
  159. package/src/relay-reservation.ts +1211 -1121
  160. package/src/seed-bootstrap.ts +1502 -1471
  161. package/src/strand-commit-durability.ts +116 -0
  162. package/src/strand-database.ts +46 -14
  163. package/src/strand-first-sync-gate.ts +7 -1
  164. package/src/strand-formation-protocol.ts +1039 -1036
  165. package/src/strand-fret-addrs.ts +179 -145
  166. package/src/strand-instance-manager.ts +2026 -1883
  167. package/src/strand-move.ts +585 -0
  168. package/src/strand-network-config.ts +7 -6
  169. package/src/strand-peer-redial.ts +307 -0
  170. package/src/strand-wake-protocol.ts +10 -7
  171. package/src/types.ts +220 -4
@@ -1,1471 +1,1502 @@
1
- import debug from 'debug';
2
- import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
3
- import { digest, sign, verify, getPublicKey } from '@optimystic/quereus-plugin-crypto';
4
- import type { Libp2p, Connection, PeerId, Stream } from '@libp2p/interface';
5
- import { multiaddr, type Multiaddr } from '@multiformats/multiaddr';
6
- import { peerIdFromString } from '@libp2p/peer-id';
7
- import { type ControlStream, withDeadline, exchangeFrame, readStreamToEnd, replyAndClose } from './control-stream.js';
8
- import {
9
- dialPeerAddrs,
10
- SelfRelayOnlyError,
11
- PeerUnreachableError,
12
- DEFAULT_PEER_DIAL_BUDGET,
13
- type PeerDialBudget,
14
- } from './peer-dial.js';
15
- import { withTrailingPeerId } from './peer-record.js';
16
- import { relayedRequestBudgetMs } from './link-budget.js';
17
- import type {
18
- ControlNetworkSeed,
19
- SeedPeer,
20
- SeedMessage,
21
- SeedAckMessage,
22
- SeedRefusalCode,
23
- SeedDeliveryTarget,
24
- AuthorizePeerOptions,
25
- ApplySeedResult,
26
- AddDroneOptions,
27
- DroneInitResult,
28
- CadreInviteRow,
29
- PeerAddressRecord,
30
- DeviceTokenRecord,
31
- RevocationRow,
32
- RevocationLedgerOpenResult
33
- } from './types.js';
34
- import type { ControlDatabase } from './control-database.js';
35
- import { generateStampId } from './control-database.js';
36
- import { canonicalJson } from './canonical-json.js';
37
- import { deviceTokenAddDigest } from './peer-authorization.js';
38
- import { ed25519PublicKeyB64FromPeerId } from './ed25519-key.js';
39
- import {
40
- type SeedTrustPolicy,
41
- type SeedTrustDecision,
42
- anchoredTrustPolicy,
43
- } from './seed-trust-policy.js';
44
- import type { TrustedOwnerStore } from './trusted-owner-store.js';
45
-
46
- const log = debug('sereus:cadre:seed-bootstrap');
47
-
48
- /** Protocol ID for seed delivery */
49
- export const SEED_PROTOCOL = '/sereus/seed/1.0.0';
50
-
51
- /** Maximum seed message size (1MB) */
52
- const MAX_SEED_SIZE = 1024 * 1024;
53
-
54
- /**
55
- * Default time the receiver waits for an inbound seed frame before aborting (ms). It covers the
56
- * read only: the trust decision and the peer-store merge run after it.
57
- */
58
- // eslint-disable-next-line no-restricted-syntax -- link-independent: a receiver cap on one seed frame on a stream the peer already opened; it bounds a peer that opens a stream and never sends, not the dial
59
- const DEFAULT_SEED_READ_TIMEOUT_MS = 10_000;
60
-
61
- /** Default cap on concurrent inbound seed streams a single peer can pin open. */
62
- const DEFAULT_MAX_CONCURRENT_SEEDS = 100;
63
-
64
- /**
65
- * Decode a 4-byte big-endian length-prefixed frame; returns the body bytes.
66
- *
67
- * Guards every parse site against malformed input: a buffer too short to hold
68
- * the prefix, a declared length exceeding `maxLength`, and a declared length
69
- * exceeding the bytes actually present. Returns a view (`subarray`, no copy) —
70
- * the body is handed straight to `TextDecoder`.
71
- */
72
- export function decodeLengthPrefixedFrame(data: Uint8Array, maxLength = MAX_SEED_SIZE): Uint8Array {
73
- if (data.length < 4) {
74
- throw new Error(`Seed frame too short: ${data.length} bytes, need ≥4 for length prefix`);
75
- }
76
- // Pass the full (buffer, byteOffset, byteLength) triple so the read is correct
77
- // even for a non-zero-offset view, not just the fresh zero-offset arrays
78
- // current callers pass.
79
- const length = new DataView(data.buffer, data.byteOffset, data.byteLength).getUint32(0, false);
80
- const available = data.length - 4;
81
- if (length > maxLength) {
82
- throw new Error(`Seed frame declares length ${length} exceeding max ${maxLength}`);
83
- }
84
- if (length > available) {
85
- throw new Error(`Seed frame declares length ${length} but only ${available} body bytes present`);
86
- }
87
- return data.subarray(4, 4 + length);
88
- }
89
-
90
- /**
91
- * Canonical byte representation of the authenticated seed fields.
92
- *
93
- * Routes both the creator (`createSeed`) and the verifier
94
- * (`validateSeedSignature`) through one builder so the signed bytes are
95
- * identical regardless of key insertion order. `canonicalJson` sorts keys and
96
- * drops `undefined`, so the signed payload is exactly `{ partyId, peers }` —
97
- * the fields the producer actually emits.
98
- */
99
- export function canonicalSeedPayload(
100
- seed: Pick<ControlNetworkSeed, 'partyId' | 'peers'>
101
- ): string {
102
- return canonicalJson({ partyId: seed.partyId, peers: seed.peers });
103
- }
104
-
105
- /**
106
- * The digest a seed's signature covers: sha256 over {@link canonicalSeedPayload},
107
- * base64url. One function so the signer (`createSeed`), the verifier
108
- * (`validateSeedSignature`) and the claim proof (`claim-proof.ts`, which binds a
109
- * proof to one seed through this value) all name the same bytes.
110
- */
111
- export function seedDigest(seed: Pick<ControlNetworkSeed, 'partyId' | 'peers'>): string {
112
- return digest([canonicalSeedPayload(seed)], 'sha256', 'base64url') as string;
113
- }
114
-
115
- /**
116
- * An {@link ApplySeedResult} for a seed refused before the owner-dial loop ran,
117
- * so the dial counters read zero rather than being absent.
118
- */
119
- function seedRejected(error: string, code?: SeedRefusalCode): ApplySeedResult {
120
- return {
121
- success: false,
122
- peersAdded: 0,
123
- error,
124
- ...(code !== undefined ? { code } : {}),
125
- ownerDialsAttempted: 0,
126
- ownerDialsFailed: 0,
127
- };
128
- }
129
-
130
- /** What rides beside a seed into {@link SeedBootstrapService.verifyAndMergeSeed}. */
131
- interface SeedApplyOptions {
132
- /** Per-call policy override, used instead of the service-configured default for this seed only. */
133
- trustPolicy?: SeedTrustPolicy;
134
- /** The claim proof the message carried, when the seed came over the wire. */
135
- claimProof?: string;
136
- /** The delivering peer, when the seed came over the wire. */
137
- remotePeerId?: string;
138
- }
139
-
140
- /** What dialing a seed's owner peers produced — the owner-dial half of an {@link ApplySeedResult}. */
141
- type OwnerDialCounts = Pick<ApplySeedResult, 'ownerDialsAttempted' | 'ownerDialsFailed'>;
142
-
143
- /**
144
- * Parse each address, dropping (and logging) any that is malformed, so one bad
145
- * entry cannot keep a peer's valid addresses from being dialed.
146
- */
147
- function parseDialAddrs(addrs: readonly string[]): Multiaddr[] {
148
- const parsed: Multiaddr[] = [];
149
- for (const addr of addrs) {
150
- try {
151
- parsed.push(multiaddr(addr));
152
- } catch (error) {
153
- log('Skipping malformed dial address %s: %o', addr, error);
154
- }
155
- }
156
- return parsed;
157
- }
158
-
159
- /**
160
- * Merge a peer list's addresses into `node`'s peer store, so the node can dial them: the
161
- * seed's peers after its signature and trust checks, the dial hints a member returns on
162
- * a cadre invitation redemption (`cadre-invite-protocol.ts`), or the node a seed is being
163
- * delivered to ({@link SeedBootstrapService.deliverSeed}). Best-effort per peer — one
164
- * unparsable entry costs that peer, not the rest — and a peer with no address is skipped,
165
- * since there is nothing to dial. Returns how many peers were merged.
166
- */
167
- export async function mergeSeedPeers(node: Libp2p, peers: readonly SeedPeer[]): Promise<number> {
168
- let peersAdded = 0;
169
- for (const peer of peers) {
170
- if (peer.multiaddrs.length === 0) {
171
- continue;
172
- }
173
- try {
174
- const peerId = peerIdFromString(peer.peerId);
175
- const addrs = peer.multiaddrs.map(ma => multiaddr(ma));
176
- await node.peerStore.merge(peerId, { multiaddrs: addrs });
177
- peersAdded++;
178
- log('Added peer to store: %s with %d addrs', peer.peerId, addrs.length);
179
- } catch (error) {
180
- log('Failed to add peer %s: %o', peer.peerId, error);
181
- }
182
- }
183
- return peersAdded;
184
- }
185
-
186
- /** Opens a seed delivery's stream under the delivery deadline's signal. */
187
- type SeedStreamOpener = (signal: AbortSignal) => Promise<Stream>;
188
-
189
- /**
190
- * A delivery target's addresses, each bound to its peer id (`withTrailingPeerId`) so the dial
191
- * authenticates the node it aims at rather than trusting whoever answers. An address that does
192
- * not parse, or that names another peer, throws: that is the caller's mistake, not the node
193
- * being unreachable.
194
- */
195
- function deliveryDialAddrs(peerId: string, addrs: readonly string[]): Multiaddr[] {
196
- return addrs.map((text) => {
197
- const bound = withTrailingPeerId(multiaddr(text), peerId);
198
- if (!bound) {
199
- throw new Error(`Seed delivery to ${peerId}: address ${text} names another peer`);
200
- }
201
- return bound;
202
- });
203
- }
204
-
205
- /**
206
- * A connection to `peerId` that `node` already holds and a seed stream can use: open and without
207
- * relay limits, the rule libp2p applies when `dialProtocol` reuses a connection.
208
- */
209
- function openUnlimitedConnection(node: Libp2p, peerId: PeerId): Connection | undefined {
210
- return node.getConnections(peerId).find((c) => c.status === 'open' && c.limits === undefined);
211
- }
212
-
213
- /**
214
- * Configuration for the SeedBootstrapService
215
- */
216
- export interface SeedBootstrapConfig {
217
- /** Party ID for this cadre */
218
- partyId: string;
219
- /** Owner private key for signing seeds and peer authorizations (base64url) */
220
- ownerPrivateKey?: string;
221
- /** Owner public key (base64url) - derived from private key if not provided */
222
- ownerPublicKey?: string;
223
- /**
224
- * Trust anchor for incoming seeds. Decides whether a signature-verified
225
- * `signerKey` should be trusted, against the receiver's anchored owner
226
- * keys (NOT the seed body). Defaults to `anchoredTrustPolicy()`, which
227
- * rejects any signer not already in {@link trustedOwners}. An enrollment
228
- * caller can pass a per-seed override to `applySeed` instead.
229
- *
230
- * A `CadreNode` forwards its node-wide `CadreNodeConfig.seedTrustPolicy` here
231
- * — that is the only seam the inbound libp2p seed-protocol handler can use,
232
- * since a network-delivered seed has no per-call override.
233
- */
234
- trustPolicy?: SeedTrustPolicy;
235
- /**
236
- * The node-local, NON-replicated trusted-owner anchor. Supplies
237
- * `SeedTrustContext.knownOwnerKeys` for every {@link applySeed}, and receives
238
- * a key accepted via a pin/TOFU (see `SeedTrustDecision.anchorAs`).
239
- *
240
- * Deliberately NOT `ControlDatabase.getOwnerKeys()`: the replicated
241
- * `OwnerKey` table is pollutable — any connecting node can genesis-insert its
242
- * own key and let it replicate — so a seed signed by a stranger's self-issued
243
- * owner key would pass a table-anchored check. A `CadreNode` passes its
244
- * `getTrustedOwnerStore()` here. Unset (e.g. a directly-constructed service in
245
- * a test) means an EMPTY anchor: only a pinned/TOFU policy can accept a seed.
246
- */
247
- trustedOwners?: TrustedOwnerStore;
248
- /**
249
- * Time the inbound seed handler waits for the seed frame before aborting the
250
- * read (ms). Defaults to {@link DEFAULT_SEED_READ_TIMEOUT_MS}. Bounds a
251
- * buggy/compromised own-cadre node that opens a stream and never half-closes.
252
- */
253
- seedReadTimeoutMs?: number;
254
- /**
255
- * Cap on concurrent inbound seed streams (defaults to
256
- * {@link DEFAULT_MAX_CONCURRENT_SEEDS}). Over the cap, a non-accepting ack is
257
- * returned without applying any seed.
258
- */
259
- maxConcurrentSeeds?: number;
260
- /**
261
- * The host's declared link round trip (`NetworkConfig.linkRoundTripMs`), from which
262
- * {@link seedDeliverTimeoutMs}'s default is derived. Unset means the declared default.
263
- */
264
- linkRoundTripMs?: number;
265
- /**
266
- * Time {@link SeedBootstrapService.deliverSeed} waits for the request — opening the
267
- * stream, write, ack read — before aborting (ms). For a multiaddr string, or a peer id
268
- * with no addresses, opening the stream includes the dial; for a peer id with addresses
269
- * the connection is formed first, outside this limit and within {@link dialBudget}.
270
- * Bounds the SENDER against a seed target that accepts the stream and then never replies;
271
- * the target is a not-yet-trusted node during onboarding, so this is the more exposed
272
- * direction than the receiver knobs above.
273
- *
274
- * Defaults to `relayedRequestBudgetMs(linkRoundTripMs)` (`link-budget.ts`; 28.5 s at the
275
- * default declaration): one dial that may need a relay, then one request and its answer —
276
- * sized for the forms that dial inside it. Delivery does not set `runOnLimitedConnection`,
277
- * so it does not use a limited relayed connection today; the relayed-dial count is the upper
278
- * bound on the dial it can use, the same choice `CadreNode.controlDialBudget` makes for every
279
- * address. It holds only link work because the receiver acks before its owner dials.
280
- *
281
- * NOTE: no transfer allowance — a seed is a peer list of a few KB, and `MAX_SEED_SIZE` (1 MiB)
282
- * is a defensive cap. If seeds ever grow toward that cap, add an allowance the way
283
- * `PUSH_TRANSFER_ALLOWANCE_MS` does.
284
- */
285
- seedDeliverTimeoutMs?: number;
286
- /**
287
- * Time limits for each peer this service dials from a list of addresses —
288
- * {@link SeedBootstrapService.applySeed}'s owner dials and
289
- * {@link SeedBootstrapService.deliverSeed}'s dial of a peer id with addresses — per
290
- * address and per peer (see `peer-dial.ts`). Defaults to {@link DEFAULT_PEER_DIAL_BUDGET}; a `CadreNode`
291
- * passes its `network.controlCohort` limits.
292
- */
293
- dialBudget?: PeerDialBudget;
294
- }
295
-
296
- /**
297
- * Event callbacks for seed-related events
298
- */
299
- export interface SeedEventCallbacks {
300
- /** Called when a seed is received via the protocol */
301
- onSeedReceived?: (partyId: string, peerId: string) => void;
302
- /**
303
- * Called when a seed is successfully applied.
304
- *
305
- * `seed` is the applied seed itself: the inbound protocol handler applies it
306
- * INSIDE the service, so this callback is the only seam through which a
307
- * `CadreNode` sees a wire-delivered seed's contents — which it needs to
308
- * retain the owner-flagged peers as cold-start bootstrap dial targets.
309
- */
310
- onSeedApplied?: (partyId: string, peersAdded: number, seed: ControlNetworkSeed) => void;
311
- /** Called when seed application fails */
312
- onSeedError?: (partyId: string, error: string) => void;
313
- }
314
-
315
- /**
316
- * SeedBootstrapService handles control network seed generation and delivery.
317
- *
318
- * Seeds solve the cold-start problem: new nodes need control data to validate
319
- * connections, but can't get data without connecting first. Seeds pre-populate
320
- * the new node's cache with peer information.
321
- */
322
- export class SeedBootstrapService {
323
- private readonly config: SeedBootstrapConfig;
324
- private libp2pNode: Libp2p | null = null;
325
- private controlDatabase: ControlDatabase | null = null;
326
- private readonly ownerPublicKey: string | null;
327
- private readonly trustPolicy: SeedTrustPolicy;
328
- private readonly seedReadTimeoutMs: number;
329
- private readonly maxConcurrentSeeds: number;
330
- private readonly seedDeliverTimeoutMs: number;
331
- private readonly dialBudget: PeerDialBudget;
332
- /** In-flight inbound seed streams, used to enforce {@link maxConcurrentSeeds}. */
333
- private activeStreams = 0;
334
- private eventCallbacks: SeedEventCallbacks = {};
335
-
336
- constructor(config: SeedBootstrapConfig) {
337
- this.config = config;
338
- this.trustPolicy = config.trustPolicy ?? anchoredTrustPolicy();
339
- this.seedReadTimeoutMs = config.seedReadTimeoutMs ?? DEFAULT_SEED_READ_TIMEOUT_MS;
340
- this.maxConcurrentSeeds = config.maxConcurrentSeeds ?? DEFAULT_MAX_CONCURRENT_SEEDS;
341
- this.seedDeliverTimeoutMs = config.seedDeliverTimeoutMs ?? relayedRequestBudgetMs(config.linkRoundTripMs);
342
- this.dialBudget = config.dialBudget ?? DEFAULT_PEER_DIAL_BUDGET;
343
-
344
- // Derive public key from private key if not provided
345
- if (config.ownerPrivateKey && !config.ownerPublicKey) {
346
- this.ownerPublicKey = getPublicKey(
347
- config.ownerPrivateKey,
348
- 'ed25519',
349
- 'base64url',
350
- 'base64url'
351
- ) as string;
352
- } else {
353
- this.ownerPublicKey = config.ownerPublicKey ?? null;
354
- }
355
-
356
- log('SeedBootstrapService created for party: %s', config.partyId);
357
- }
358
-
359
- /**
360
- * Set event callbacks for seed-related events.
361
- * Used by CadreNode to emit events.
362
- */
363
- setEventCallbacks(callbacks: SeedEventCallbacks): void {
364
- this.eventCallbacks = callbacks;
365
- }
366
-
367
- /**
368
- * Whether this service holds an owner private key, i.e. can produce the
369
- * owner signatures that gate `CadrePeer` / `DeviceToken` inserts, deletes,
370
- * and re-authorizations. A seed-listener-only service (`enableSeedListener`,
371
- * no owner key) returns false: it can receive/apply seeds but cannot author
372
- * or re-issue owner writes. Used by the write-while-alone re-replication
373
- * drain to skip owner work on a non-owner node.
374
- */
375
- canAuthorize(): boolean {
376
- return !!this.config.ownerPrivateKey;
377
- }
378
-
379
- /**
380
- * Initialize the service with libp2p node and control database.
381
- *
382
- * `registerHandler` (default true) gates registration of the shared inbound
383
- * `/sereus/seed/1.0.0` handler on `libp2pNode`. Persistent services
384
- * (`initializeSeedBootstrap`, `enableSeedListener`) own that handler and leave
385
- * it on. The throwaway temp service CadreNode builds in `applySeed` passes
386
- * `false`: it only needs the stored `libp2pNode` / `controlDatabase` for
387
- * dialing and known-key lookup, and must NOT bind a discarded closure to the
388
- * shared node (a handler leak, and a second
389
- * `handle()` of the same protocol throws `DuplicateProtocolHandlerError`).
390
- *
391
- * Rejects when libp2p refuses the registration; the node and database are
392
- * kept only once the handler is in place, so a failed service holds nothing
393
- * for {@link shutdown} to unhandle.
394
- */
395
- async initialize(
396
- libp2pNode: Libp2p,
397
- controlDatabase: ControlDatabase,
398
- options?: { registerHandler?: boolean }
399
- ): Promise<void> {
400
- // Register the seed protocol handler unless the caller opted out (temp services).
401
- if (options?.registerHandler ?? true) {
402
- await this.registerProtocolHandler(libp2pNode);
403
- }
404
-
405
- this.libp2pNode = libp2pNode;
406
- this.controlDatabase = controlDatabase;
407
- log('SeedBootstrapService initialized');
408
- }
409
-
410
- /**
411
- * Authorize a new peer to join the cadre.
412
- * Signs a membership voucher with the owner key and inserts into CadrePeer table.
413
- *
414
- * The owner vouches the `PublicKey <-> PeerId` binding: rather than trust a
415
- * caller-supplied key, the binding is enforced by construction — `PublicKey` is
416
- * DERIVED from the (Ed25519) `peerId`. A non-Ed25519 peer id yields a null
417
- * `PublicKey`, and such a row can never be self-updated (it has no key to
418
- * verify against), which is correct. The row is inserted with a fresh
419
- * `UpdatedAt` but no self-signature (`Sig` null) — the owner cannot produce
420
- * the peer's self-signature, so the peer must self-publish (see
421
- * {@link CadreNode.registerSelf}) before the row resolves.
422
- */
423
- async authorizePeer(options: AuthorizePeerOptions): Promise<void> {
424
- const { peerId, multiaddrs } = options;
425
- log('Authorizing peer: %s', peerId);
426
- // CadrePeer.Multiaddr stores a comma-joined list; use '' when no addrs provided.
427
- const multiaddrStr = multiaddrs?.length ? multiaddrs.join(',') : '';
428
- await this.insertCadrePeerRow({
429
- peerId,
430
- publicKey: ed25519PublicKeyB64FromPeerId(peerId),
431
- multiaddr: multiaddrStr,
432
- updatedAt: Date.now(),
433
- sig: null,
434
- });
435
- log('Peer %s authorized successfully', peerId);
436
- }
437
-
438
- /**
439
- * Owner-signed INSERT of this node's OWN self-signed address record.
440
- *
441
- * Used by {@link CadreNode.registerSelf} when the node is not yet a member and
442
- * is its own owner (it holds the owner key): the row is owner-signed
443
- * (satisfying `AuthorizedInsert`) AND carries a valid self-`Sig`, so it resolves
444
- * immediately without a follow-up self-update.
445
- *
446
- * @returns `true` when this call seated the row, `false` when a concurrent writer
447
- * (e.g. an {@link authorizePeer} of this node's own id) had already seated it —
448
- * in which case the row in the database is NOT this record and carries whatever
449
- * `Sig` that writer had, so the caller must self-update to publish its signature.
450
- */
451
- async insertSelfPeerRecord(record: PeerAddressRecord): Promise<boolean> {
452
- return await this.insertCadrePeerRow({
453
- peerId: record.peerId,
454
- publicKey: record.publicKey,
455
- multiaddr: record.addrs.join(','),
456
- updatedAt: record.updatedAt,
457
- sig: record.sig,
458
- });
459
- }
460
-
461
- /**
462
- * Shared owner-signed `CadrePeer` INSERT — the row fields and the owner-key
463
- * precondition; the stamp mint, voucher signature, write lock, existence check and
464
- * membership notify are all {@link ControlDatabase.insertCadrePeer}'s (see there for
465
- * the anti-replay and insert-race rationale). No `CadrePeer` write may bypass that
466
- * method: the write is what admits the peer's traffic.
467
- *
468
- * The DB check precedes the owner-key check here, matching the order this method has
469
- * always surfaced them (the owner-key error used to come out of the signer, after the
470
- * DB check).
471
- *
472
- * @returns `true` when this call performed the INSERT, `false` when the row was
473
- * already seated by a concurrent writer. The loser needs to know: an authorize seats
474
- * a row with a null `Sig`, so a self-publish that lost the race must fall through to
475
- * a self-update or its record never lands.
476
- */
477
- private async insertCadrePeerRow(row: {
478
- peerId: string;
479
- publicKey: string | null;
480
- multiaddr: string;
481
- updatedAt: number;
482
- sig: string | null;
483
- }): Promise<boolean> {
484
- if (!this.controlDatabase) {
485
- throw new Error('Control database not initialized');
486
- }
487
- const ownerKey = this.requireOwnerPublicKey();
488
- return await this.controlDatabase.insertCadrePeer(
489
- row, ownerKey, message => this.signMessageBytes(message),
490
- );
491
- }
492
-
493
- /**
494
- * Owner-signed INSERT of a peer's OWN self-signed `DeviceToken` row.
495
- *
496
- * Counterpart to {@link insertSelfPeerRecord} for the device-token registry: the
497
- * row is owner-signed (satisfying `DeviceToken.AuthorizedInsert` via the
498
- * 'add'-tagged digest, {@link deviceTokenAddDigest}) AND carries the peer's
499
- * own self-`Sig` over the token payload. The owner signature covers the WHOLE row
500
- * (every column, ending in a freshly minted single-use `StampId`) — but covering the
501
- * token contents is not the same as vouching them: the peer's `Sig` (verified at
502
- * resolve time against the bound `CadrePeer.PublicKey`) is what makes the row
503
- * resolvable. Used by {@link CadreNode.registerDeviceToken} for the first publish
504
- * when the node is its own owner.
505
- *
506
- * The stamp is per-INSERT, so a re-register after a clear mints a fresh one and a
507
- * fresh signature — unaffected by the cleared row's retired stamp
508
- * (`DeviceToken.NotRevoked`).
509
- */
510
- async insertSelfDeviceToken(record: DeviceTokenRecord): Promise<void> {
511
- const stampId = generateStampId(record.peerId);
512
- const signature = this.signDigest(deviceTokenAddDigest(this.config.partyId, { ...record, stampId }));
513
- if (!this.controlDatabase) {
514
- throw new Error('Control database not initialized');
515
- }
516
- await this.controlDatabase.execWrite(`
517
- insert into CadreControl.DeviceToken (PeerId, Platform, Token, UpdatedAt, Sig, StampId)
518
- with context OwnerKey = ?, Signature = ?
519
- values (?, ?, ?, ?, ?, ?)
520
- `, [this.ownerPublicKey, signature, record.peerId, record.platform, record.token, record.updatedAt, record.sig, stampId], 'device-token-insert');
521
- log('Device token inserted (owner-signed): %s', record.peerId);
522
- }
523
-
524
- /**
525
- * Owner-signed DELETE of a peer's `DeviceToken` row (logout / token
526
- * invalidation). The `DeviceToken.AuthorizedDelete` constraint validates an owner
527
- * signature over the 'remove'-tagged digest bound to the STORED row's
528
- * (PeerId, StampId) — deliberately distinct from the insert digest, so a captured
529
- * insert approval can never be replayed to clear a token. Like {@link removePeer}
530
- * for `CadrePeer`, clearing a token requires the owner key.
531
- *
532
- * The delete and the `Revocation` tombstone retiring the row's `StampId` commit in
533
- * ONE transaction — `DeviceToken.RevocationRecorded` refuses a bare delete, and
534
- * without the tombstone the stamp would free up and the never-expiring insert
535
- * approval (which the cleared device holds a copy of) would re-seat the token. The
536
- * tombstone carries its OWN owner signature: retiring a stamp permanently forecloses
537
- * that row, so it is an owner action in its own right.
538
- *
539
- * Both digests, the stamp read, and the transaction come from
540
- * {@link ControlDatabase.deleteDeviceToken} — one shared implementation across
541
- * `CadrePeer` / `DeviceToken` / `Strand` / `ValidationKey`. What stays here is the
542
- * owner-key precondition; a no-op on an already-absent row is the shared body's
543
- * behavior, and unlike {@link removePeer} nothing here rides on it.
544
- */
545
- async deleteDeviceToken(peerId: string): Promise<void> {
546
- // Fail fast on a keyless service BEFORE the DB read, so a non-owner gets the
547
- // owner-key error rather than a silent no-op on an absent row.
548
- const ownerKey = this.requireOwnerPublicKey();
549
- if (!this.controlDatabase) {
550
- throw new Error('Control database not initialized');
551
- }
552
- await this.controlDatabase.deleteDeviceToken(
553
- peerId, ownerKey, message => this.signMessageBytes(message),
554
- );
555
- }
556
-
557
- /**
558
- * Return the configured owner private key, or throw if none is set. The single
559
- * precondition gate for every owner-signed write. {@link removePeer} /
560
- * {@link reauthorizePeer} read the row's `StampId` from the DB BEFORE they sign, so
561
- * they call this up front — otherwise a keyless service would either surface the
562
- * wrong "Control database not initialized" error or, worse, silently no-op when the
563
- * target row is absent (the early `stampId === null` return) instead of rejecting.
564
- */
565
- private requireOwnerPrivateKey(): string {
566
- if (!this.config.ownerPrivateKey) {
567
- throw new Error('Owner private key required to authorize peers');
568
- }
569
- return this.config.ownerPrivateKey;
570
- }
571
-
572
- /**
573
- * The owner PUBLIC key that rides in every owner-signed write's context, non-null.
574
- *
575
- * The field is nullable because a read-only service carries no owner key at all, but the
576
- * constructor derives the public key whenever `ownerPrivateKey` is set — so gating on
577
- * {@link requireOwnerPrivateKey} first makes the pair inseparable and the second throw
578
- * unreachable. Callers that must reject a keyless service BEFORE any DB read use this as
579
- * their first line and get the owner-key precondition for free.
580
- */
581
- private requireOwnerPublicKey(): string {
582
- this.requireOwnerPrivateKey();
583
- if (!this.ownerPublicKey) {
584
- throw new Error('Owner public key required to authorize peers');
585
- }
586
- return this.ownerPublicKey;
587
- }
588
-
589
- /**
590
- * Sign a base64url digest with the owner key (ed25519). The single place the
591
- * owner private key is applied; callers pass the canonical domain-tagged digest for
592
- * the specific action ({@link deviceTokenAddDigest}), or the raw-bytes form via
593
- * {@link signMessageBytes}. Throws if no owner key is set.
594
- */
595
- private signDigest(digestB64url: string): string {
596
- return sign(
597
- digestB64url,
598
- this.requireOwnerPrivateKey(),
599
- 'ed25519',
600
- 'base64url',
601
- 'base64url',
602
- 'base64url'
603
- ) as string;
604
- }
605
-
606
- /**
607
- * Adapt the control database's raw-bytes `signMessage` callback (every guarded delete
608
- * takes one) to {@link signDigest}'s base64url-string form. Both encodings hash to the
609
- * same signed bytes (`sign` decodes its base64url input), so a signature minted here
610
- * satisfies the same schema CHECK as one from the callers that sign the bytes directly — see
611
- * `control-revocation-replay.spec.ts`'s "raw-bytes and digest-string signers agree".
612
- */
613
- private signMessageBytes(message: Uint8Array): string {
614
- return this.signDigest(uint8ArrayToString(message, 'base64url'));
615
- }
616
-
617
- /**
618
- * Remove a peer from the cadre by owner signature.
619
- *
620
- * The `CadrePeer.AuthorizedDelete` (`check on delete`) constraint validates a
621
- * signature over the DISTINCT 'remove'-tagged digest
622
- * `digest('CadreControl.CadrePeer', 'remove', party_id(), old.PeerId, old.StampId)` by an owner
623
- * key — deliberately NOT the insert voucher digest, so the row's stored `VouchSig` can
624
- * never be replayed to delete.
625
- *
626
- * The delete and the `Revocation` tombstone retiring the row's `StampId` commit in ONE
627
- * transaction — `CadrePeer.RevocationRecorded` refuses a bare delete, and without the
628
- * tombstone the stamp would free up and the original admission approval (which never
629
- * expires, and which the removed peer holds a copy of) would re-seat the row.
630
- *
631
- * The tombstone is separately owner-signed (satisfying `Revocation.Authorized`):
632
- * retiring a stamp evicts that peer party-wide and permanently forecloses re-admitting
633
- * the row, so it is an owner action in its own right, not a side effect the delete's
634
- * signature covers.
635
- *
636
- * Both digests, the stamp read, the transaction, and the post-commit membership notify
637
- * come from {@link ControlDatabase.deleteCadrePeer} — one shared implementation across
638
- * `CadrePeer` / `DeviceToken` / `Strand` / `ValidationKey`. What stays here is the
639
- * owner-key precondition and the absent-row gate the notify depends on (below).
640
- */
641
- async removePeer(peerId: string): Promise<void> {
642
- // Fail fast on a keyless service BEFORE any DB read: a non-owner cannot sign the
643
- // remove digest, and this precedence (owner key, then control DB) is what the
644
- // unit contract asserts.
645
- const ownerKey = this.requireOwnerPublicKey();
646
- if (!this.controlDatabase) {
647
- throw new Error('Control database not initialized');
648
- }
649
- // This absent-row gate must stay OUTSIDE the delete, even though the delete repeats it
650
- // internally: deleteCadrePeer's membership notify fires whenever its body resolves,
651
- // with no idea whether the body wrote anything, so delegating an absent peer would
652
- // fire a spurious membership notification.
653
- // NOTE: deleteCadrePeer re-reads the StampId, so a peer removed by another writer
654
- // between the two reads no-ops silently yet still notifies. Narrow concurrent-removal
655
- // window only — the common "already absent" case is caught here.
656
- const stampId = await this.controlDatabase.queryCadrePeerStampId(peerId);
657
- if (stampId === null) {
658
- log('removePeer: no CadrePeer row for %s (already absent)', peerId);
659
- return;
660
- }
661
-
662
- log('Removing peer: %s', peerId);
663
-
664
- await this.controlDatabase.deleteCadrePeer(
665
- peerId, ownerKey, message => this.signMessageBytes(message),
666
- );
667
-
668
- log('Peer %s removed successfully (stamp retired)', peerId);
669
- }
670
-
671
- /**
672
- * Seat `ownerPublicKey` as a further owner, signed by this service's owner key. The
673
- * liveness check, the stamp, the signature and the membership notify are
674
- * {@link ControlDatabase.insertOwnerKeyVouched}'s; what stays here is the owner-key
675
- * precondition, checked before any read (see {@link removePeer}).
676
- *
677
- * @returns `true` when the row was seated, `false` when the key is already a live owner.
678
- */
679
- async addOwner(ownerPublicKey: string): Promise<boolean> {
680
- const ownerKey = this.requireOwnerPublicKey();
681
- if (!this.controlDatabase) {
682
- throw new Error('Control database not initialized');
683
- }
684
- return await this.controlDatabase.insertOwnerKeyVouched(
685
- ownerPublicKey, ownerKey, message => this.signMessageBytes(message),
686
- );
687
- }
688
-
689
- /**
690
- * Remove `ownerPublicKey` from the owners, signed by this service's owner key: the delete
691
- * and its `Revocation` tombstone in one transaction. The by-name refusals (self-removal,
692
- * the last owner), the digests and the membership notify are
693
- * {@link ControlDatabase.deleteOwnerKey}'s; what stays here is the owner-key precondition,
694
- * checked before any read (see {@link removePeer}).
695
- *
696
- * @returns `true` when the row was removed, `false` when the key is not a live owner here.
697
- */
698
- async removeOwner(ownerPublicKey: string): Promise<boolean> {
699
- const ownerKey = this.requireOwnerPublicKey();
700
- if (!this.controlDatabase) {
701
- throw new Error('Control database not initialized');
702
- }
703
- return await this.controlDatabase.deleteOwnerKey(
704
- ownerPublicKey, ownerKey, message => this.signMessageBytes(message),
705
- );
706
- }
707
-
708
- /**
709
- * Owner "re-touch" of an existing `CadrePeer` membership row: bump `UpdatedAt` and
710
- * re-vouch the row so it is re-emitted as a fresh, broadcasting transaction. This is
711
- * the write-while-alone re-replication primitive (`control-write-ensure-replicated`):
712
- * a membership row that committed local-only (its block's cluster ≤1 at insert) is
713
- * pushed to the cohort once it grows.
714
- *
715
- * The stamp read, the voucher signature, the write lock and the membership notify are
716
- * {@link ControlDatabase.reauthorizeCadrePeer}'s — including the caveat that it rebinds
717
- * `VouchOwner` to this node's owner key. What stays here is the owner-key precondition.
718
- *
719
- * A no-op (no throw, no notify) when the row does not exist.
720
- *
721
- * @param peerId - the membership row to re-touch.
722
- * @param updatedAt - the strictly-increasing freshness stamp to write.
723
- * @throws if no owner private key is configured (a non-owner cannot
724
- * re-sign another peer's row) or the control database is not initialized.
725
- */
726
- async reauthorizePeer(peerId: string, updatedAt: number): Promise<void> {
727
- // Fail fast on a keyless service before any DB read (see removePeer): a non-owner
728
- // cannot re-sign the voucher, and must not silently no-op on an absent row.
729
- const ownerKey = this.requireOwnerPublicKey();
730
- if (!this.controlDatabase) {
731
- throw new Error('Control database not initialized');
732
- }
733
- const retouched = await this.controlDatabase.reauthorizeCadrePeer(
734
- peerId, updatedAt, ownerKey, message => this.signMessageBytes(message),
735
- );
736
- if (!retouched) {
737
- log('reauthorizePeer: no CadrePeer row for %s (nothing to re-touch)', peerId);
738
- return;
739
- }
740
- log('Peer %s re-authorized (UpdatedAt=%d) for write-while-alone re-replication', peerId, updatedAt);
741
- }
742
-
743
- /**
744
- * Owner re-issue of a batch of `Revocation` tombstones: bump each row's
745
- * `ReissuedAt` so the storage layer re-broadcasts a tombstone that committed
746
- * while the node was alone. The delete-while-alone counterpart of
747
- * {@link reauthorizePeer} — a removed row cannot be re-touched (it is gone),
748
- * but its tombstone can, and every membership read treats a retired stamp as
749
- * absent.
750
- *
751
- * The signatures, the single transaction, and the strictly-monotonic
752
- * `reissuedAt` contract are {@link ControlDatabase.reissueRevocations}'s. What
753
- * stays here is the owner-key precondition.
754
- *
755
- * @returns how many tombstones were re-issued (`rows.length` on success).
756
- * @throws if no owner private key is configured or the control database is not
757
- * initialized.
758
- */
759
- async reissueRevocations(rows: readonly RevocationRow[], reissuedAt: number): Promise<number> {
760
- // Fail fast on a keyless service before any DB work (see removePeer): a
761
- // non-owner cannot sign the reissue digests.
762
- const ownerKey = this.requireOwnerPublicKey();
763
- if (!this.controlDatabase) {
764
- throw new Error('Control database not initialized');
765
- }
766
- return this.controlDatabase.reissueRevocations(
767
- rows, reissuedAt, ownerKey, message => this.signMessageBytes(message),
768
- );
769
- }
770
-
771
- /**
772
- * Owner filing of the singleton `Revocation` ledger marker, so the table is never a
773
- * never-written block that the storage layer re-consults on every read.
774
- *
775
- * The signature, the insert-if-absent guard and the `'already-open'` mapping are
776
- * {@link ControlDatabase.openRevocationLedger}'s. What stays here is the owner-key
777
- * precondition.
778
- *
779
- * @throws if no owner private key is configured or the control database is not
780
- * initialized.
781
- */
782
- async openRevocationLedger(): Promise<RevocationLedgerOpenResult> {
783
- // Fail fast on a keyless service before any DB work (see removePeer): a
784
- // non-owner cannot sign the marker's append digest.
785
- const ownerKey = this.requireOwnerPublicKey();
786
- if (!this.controlDatabase) {
787
- throw new Error('Control database not initialized');
788
- }
789
- return this.controlDatabase.openRevocationLedger(
790
- ownerKey, message => this.signMessageBytes(message),
791
- );
792
- }
793
-
794
- /**
795
- * Owner-signed INSERT of a `CadreInvite` row — an invitation any member machine can redeem
796
- * on this owner's behalf ({@link ControlDatabase.insertCadreInvite}). The keypair mint, the
797
- * expiry and use-count defaults, and the bundle the holder receives are
798
- * `CadreNode.createCadreInvitation`'s; what stays here is the owner-key precondition and
799
- * the signature, as {@link insertSelfDeviceToken} keeps them for device tokens.
800
- *
801
- * @returns the row as stored, which the invitation bundle carries verbatim.
802
- * @throws if no owner private key is configured or the control database is not initialized.
803
- */
804
- async insertCadreInvite(invite: Parameters<ControlDatabase['insertCadreInvite']>[0]): Promise<CadreInviteRow> {
805
- // Fail fast on a keyless service before any DB work (see removePeer).
806
- const ownerKey = this.requireOwnerPublicKey();
807
- if (!this.controlDatabase) {
808
- throw new Error('Control database not initialized');
809
- }
810
- return await this.controlDatabase.insertCadreInvite(invite, ownerKey, message => this.signMessageBytes(message));
811
- }
812
-
813
- /**
814
- * Owner-signed WITHDRAWAL of a `CadreInvite`: the `Revocation` tombstone over its stamp, with
815
- * the row kept ({@link ControlDatabase.withdrawCadreInvite}). What stays here is the
816
- * owner-key precondition.
817
- *
818
- * @returns `true` when this call filed the tombstone, `false` when the row is absent here or
819
- * already withdrawn.
820
- * @throws if no owner private key is configured or the control database is not initialized.
821
- */
822
- async withdrawCadreInvite(key: string): Promise<boolean> {
823
- const ownerKey = this.requireOwnerPublicKey();
824
- if (!this.controlDatabase) {
825
- throw new Error('Control database not initialized');
826
- }
827
- return await this.controlDatabase.withdrawCadreInvite(key, ownerKey, message => this.signMessageBytes(message));
828
- }
829
-
830
- /**
831
- * Create a seed from the current control network state.
832
- * The seed contains peer information and is signed by an owner.
833
- */
834
- async createSeed(): Promise<ControlNetworkSeed> {
835
- if (!this.config.ownerPrivateKey || !this.ownerPublicKey) {
836
- throw new Error('Owner key required to create seeds');
837
- }
838
-
839
- if (!this.controlDatabase || !this.libp2pNode) {
840
- throw new Error('Service not initialized');
841
- }
842
-
843
- log('Creating seed for party: %s', this.config.partyId);
844
-
845
- // Query all peers from the control database
846
- const peers = await this.queryPeers();
847
-
848
- // Create the seed data (without signature)
849
- const seedData = {
850
- partyId: this.config.partyId,
851
- peers,
852
- };
853
-
854
- // Sign the seed over its canonical byte representation
855
- const signature = sign(
856
- seedDigest(seedData),
857
- this.config.ownerPrivateKey,
858
- 'ed25519',
859
- 'base64url',
860
- 'base64url',
861
- 'base64url'
862
- ) as string;
863
-
864
- const seed: ControlNetworkSeed = {
865
- ...seedData,
866
- signature,
867
- signerKey: this.ownerPublicKey,
868
- };
869
-
870
- log('Created seed with %d peers', peers.length);
871
- return seed;
872
- }
873
-
874
- /**
875
- * Apply a seed to populate the peer cache and enable connections.
876
- *
877
- * Validates the seed signature, then evaluates a trust anchor for the
878
- * `signerKey` that does NOT come from the seed body: the receiver's
879
- * node-local {@link SeedBootstrapConfig.trustedOwners} anchor, optionally
880
- * augmented by pinned keys or TOFU via the configured/overriding
881
- * `SeedTrustPolicy`. A forged self-asserting seed — one that merely lists its
882
- * own signer as an owner peer — no longer passes, and neither does one signed
883
- * by a key a stranger genesis-inserted into the replicated `OwnerKey` table.
884
- *
885
- * A key accepted via a pin/TOFU is persisted into the anchor (the policy says
886
- * so via `SeedTrustDecision.anchorAs`), so the next seed from that owner is
887
- * anchored without re-supplying the pin.
888
- *
889
- * @param seed - The seed to apply (already transport-decoded).
890
- * @param options.trustPolicy - Per-call policy override (e.g. a
891
- * `pinnedKeyTrustPolicy` built from an operator pin) used instead of the
892
- * service-configured default for this seed only.
893
- */
894
- async applySeed(
895
- seed: ControlNetworkSeed,
896
- options?: { trustPolicy?: SeedTrustPolicy }
897
- ): Promise<ApplySeedResult> {
898
- const merged = await this.verifyAndMergeSeed(seed, options);
899
- if (!merged.success) {
900
- return merged;
901
- }
902
- return { ...merged, ...await this.dialSeedOwners(seed) };
903
- }
904
-
905
- /**
906
- * The first half of {@link applySeed}: check the signature and the signer's trust, then merge
907
- * the seed's peer addresses into the peer store. Every rejection happens here, so this result is
908
- * what the inbound handler acks with; the owner dials that follow cannot change it.
909
- */
910
- private async verifyAndMergeSeed(
911
- seed: ControlNetworkSeed,
912
- options?: SeedApplyOptions
913
- ): Promise<ApplySeedResult> {
914
- if (!this.libp2pNode) {
915
- return seedRejected('Service not initialized');
916
- }
917
-
918
- // NOTE: `seed.partyId` is never checked against `config.partyId`. Trust is keyed on
919
- // `signerKey` vs the anchor, and the anchor a stray-party seed could write into
920
- // belongs to THIS party, which only a caller-supplied pin for that signer can reach.
921
- // The one reader of the seed's party is the claim policy, which records it as the
922
- // party the node now serves (`CadreNodeConfig.claim.record`): a mismatch is still not
923
- // rejected there because an unclaimed node's own party is a placeholder, and the
924
- // claim seed is the first thing to name the real one. If any other path ever
925
- // branches on the seed's partyId (or the anchor becomes multi-party), reject a
926
- // mismatch here instead.
927
- log('Applying seed for party: %s', seed.partyId);
928
-
929
- // One digest serves the signature check and the trust context: a claim proof is
930
- // bound to the seed through the same value the signature covers.
931
- const digestB64 = seedDigest(seed);
932
- if (!this.validateSeedSignature(seed, digestB64)) {
933
- return seedRejected('Invalid seed signature');
934
- }
935
-
936
- // Evaluate the trust anchor for the signer key. The known-owner set comes
937
- // from the receiver's NODE-LOCAL anchor — never from the seed itself, and
938
- // never from the replicated OwnerKey table (a stranger can genesis-insert
939
- // its own key there and let it replicate into every peer's copy). A node
940
- // whose anchor was never seeded, with no policy override, sees an empty set
941
- // and rejects.
942
- const knownOwnerKeys = this.config.trustedOwners?.all() ?? new Set<string>();
943
- const policy = options?.trustPolicy ?? this.trustPolicy;
944
- const decision = await policy.evaluate({
945
- partyId: seed.partyId,
946
- signerKey: seed.signerKey,
947
- knownOwnerKeys,
948
- // Optional-chained like `dialSeedOwners`: partial libp2p handles (unit-test doubles)
949
- // omit `peerId`. A real node always has one, and a proof bound to a real peer id can
950
- // only fail against '' — the safe direction.
951
- localPeerId: this.libp2pNode.peerId?.toString() ?? '',
952
- seedDigest: digestB64,
953
- claimProof: options?.claimProof,
954
- remotePeerId: options?.remotePeerId,
955
- });
956
- if (!decision.trusted) {
957
- return seedRejected(decision.reason ?? 'Signer key not trusted by trust policy', decision.code);
958
- }
959
- await this.anchorAcceptedSigner(seed.signerKey, decision);
960
-
961
- const peersAdded = await mergeSeedPeers(this.libp2pNode, seed.peers);
962
- log('Merged seed: %d peers added', peersAdded);
963
- return { success: true, peersAdded, ownerDialsAttempted: 0, ownerDialsFailed: 0 };
964
- }
965
-
966
- /**
967
- * The second half of {@link applySeed}: dial the seed's owner peers to establish connections.
968
- *
969
- * Best-effort and COUNTED: an owner that is momentarily down leaves this node seeded but
970
- * unconnected, which the caller can only see if the outcome is reported (see
971
- * `ApplySeedResult.ownerDialsFailed`). Recovery is not this loop's job —
972
- * `CadreNode.dialColdStartBootstrap` retries these same addresses on every control-cohort
973
- * reconcile pass until the control database has siblings.
974
- *
975
- * The inbound handler runs this AFTER it has acked and closed the stream
976
- * ({@link handleSeedStream}), because an unreachable owner can take `dialBudget.totalMs`.
977
- */
978
- private async dialSeedOwners(seed: ControlNetworkSeed): Promise<OwnerDialCounts> {
979
- const node = this.libp2pNode;
980
- if (!node) {
981
- log('Seed service shut down before its owner dials; none attempted');
982
- return { ownerDialsAttempted: 0, ownerDialsFailed: 0 };
983
- }
984
- // `createSeed` projects every non-revoked CadrePeer row, so an owner applying
985
- // a seed minted after it joined finds ITSELF in the owner list. Dialing self always
986
- // throws, which would report a healthy owner as "seeded but stranded".
987
- // Optional-chained: partial libp2p handles (unit-test doubles) omit `peerId`,
988
- // and an undefined self simply matches nothing.
989
- // Every one of an owner's addresses is a candidate, each on its own time limit
990
- // (`dialPeerAddrs`), so an owner whose first address never answers neither
991
- // stalls seed application nor goes undialed at its other addresses.
992
- const selfPeerId = node.peerId?.toString();
993
- let ownerDialsAttempted = 0;
994
- let ownerDialsFailed = 0;
995
- for (const peer of seed.peers.filter(p => p.isOwner)) {
996
- if (peer.multiaddrs.length === 0 || peer.peerId === selfPeerId) {
997
- continue;
998
- }
999
- ownerDialsAttempted++;
1000
- try {
1001
- const addrs = parseDialAddrs(peer.multiaddrs);
1002
-
1003
- log('Dialing owner peer: %s (%d addr(s))', peer.peerId, addrs.length);
1004
- await dialPeerAddrs(node, addrs, this.dialBudget, `Owner dial of ${peer.peerId}`);
1005
- } catch (error) {
1006
- // Counted even when the owner reaches us only through our own relay: this node is still
1007
- // not connected to it, and `ownerDialsFailed` is how the caller learns that.
1008
- ownerDialsFailed++;
1009
- if (error instanceof SelfRelayOnlyError) {
1010
- log('Owner peer %s is reachable only by relaying through this node; waiting for it to reconnect', peer.peerId);
1011
- } else {
1012
- log('Failed to dial peer %s: %o', peer.peerId, error);
1013
- }
1014
- // Continue - not all peers need to be reachable
1015
- }
1016
- }
1017
-
1018
- log('Dialed seed owners: %d/%d owner dial(s) failed', ownerDialsFailed, ownerDialsAttempted);
1019
- return { ownerDialsAttempted, ownerDialsFailed };
1020
- }
1021
-
1022
- /**
1023
- * Persist a signer that a pin/TOFU accepted into the node-local anchor, so a
1024
- * later seed from the same owner is anchored without re-supplying the pin
1025
- * or re-prompting. Only the policy decides this happens (`anchorAs` is unset
1026
- * when the key was already anchored, so a plain re-apply writes nothing) and
1027
- * `trust()` is idempotent, keeping the original provenance for a known key.
1028
- *
1029
- * Failure to PERSIST does not fail the seed: `trust()` reflects the key in the
1030
- * in-memory anchor synchronously, so this seed and the rest of the session are
1031
- * unaffected — only durability across a restart is lost, and that is logged.
1032
- * That holds for pins and TOFU, which are re-supplied at the next start; a claim
1033
- * is the opposite case, so `claimSecretTrustPolicy` anchors its signer itself,
1034
- * awaits durability, and never sets `anchorAs` (the type excludes `'claim'`).
1035
- *
1036
- * NOTE: anchoring a key can flip `CadrePeer` rows ALREADY present from
1037
- * unauthorized to authorized, which the write-driven membership-gate refresh
1038
- * (`ControlDatabase.mutateCadrePeer`) cannot see — no row was written. The anchor
1039
- * is mutated from two places: here, on seed application, where both seed paths
1040
- * refresh the gate explicitly afterwards (`CadreNode.applySeed`, `onSeedApplied`);
1041
- * and by the anchor sync (`CadreNode.syncOwnerAnchor`), which runs INSIDE the
1042
- * membership refresh, ahead of the membership read, so its changes are judged by
1043
- * the same pass. If some future path anchors an owner outside both, it owes the
1044
- * same `CadreNode.refreshMembershipGate()` — or the anchor needs its own hub.
1045
- */
1046
- private async anchorAcceptedSigner(signerKey: string, decision: SeedTrustDecision): Promise<void> {
1047
- if (!decision.anchorAs || !this.config.trustedOwners) {
1048
- return;
1049
- }
1050
- try {
1051
- await this.config.trustedOwners.trust(signerKey, decision.anchorAs);
1052
- log('Anchored seed signer %s as %s', signerKey, decision.anchorAs);
1053
- } catch (error) {
1054
- log('Failed to persist accepted seed signer into the trusted-owner anchor: %o', error);
1055
- }
1056
- }
1057
-
1058
- /**
1059
- * Encode a seed for out-of-band delivery (e.g., QR code, copy/paste).
1060
- */
1061
- encodeSeed(seed: ControlNetworkSeed): string {
1062
- const json = JSON.stringify(seed);
1063
- return uint8ArrayToString(new TextEncoder().encode(json), 'base64url');
1064
- }
1065
-
1066
- /**
1067
- * Decode a seed from base64url encoding.
1068
- */
1069
- decodeSeed(encoded: string): ControlNetworkSeed {
1070
- const bytes = uint8ArrayFromString(encoded, 'base64url');
1071
- const json = new TextDecoder().decode(bytes);
1072
- return JSON.parse(json) as ControlNetworkSeed;
1073
- }
1074
-
1075
- /**
1076
- * Deliver a seed directly to a peer via the /sereus/seed/1.0.0 protocol.
1077
- *
1078
- * `target` is a multiaddr string, dialed as given, or a peer id with its addresses
1079
- * ({@link SeedDeliveryTarget}). For the second, the connection is formed first and on
1080
- * its own limits ({@link connectForDelivery}): an open one is reused, otherwise each
1081
- * address is dialed in turn, so one that never answers cannot use up the time a later
1082
- * one needed. Its addresses are also merged into the peer store, so identify and later
1083
- * dials see them. A peer id with no addresses is dialed by id, which reuses an open
1084
- * connection or tries the peer store's addresses. `options.claimProof` rides beside
1085
- * the seed in the message when the target is a brand-new node being claimed
1086
- * (`claim-proof.ts`).
1087
- *
1088
- * Sender hardening: the request — opening the stream (with its dial, for the forms
1089
- * that dial by `dialProtocol`), write, ack read — is bounded by {@link seedDeliverTimeoutMs},
1090
- * and the ack is capped at {@link MAX_SEED_SIZE}. The target is a NOT-YET-TRUSTED node the
1091
- * instigator chose to dial during onboarding, so an unbounded read here is strictly more
1092
- * exposed than the membership-gated receiver paths: without the bound a target that accepts
1093
- * the stream and never replies parks this call forever, and one that streams arbitrary bytes
1094
- * as a fake ack exhausts memory. A peer id with addresses can therefore take up to
1095
- * `dialBudget.totalMs` plus {@link seedDeliverTimeoutMs} (114.5 s at the default declared
1096
- * link) when none of its addresses answers.
1097
- *
1098
- * @throws {PeerUnreachableError} for a peer id with addresses, when no connection to it
1099
- * formed; nothing was sent. Anything else thrown after the connection formed means the
1100
- * node was reached and the exchange failed.
1101
- */
1102
- async deliverSeed(
1103
- target: SeedDeliveryTarget,
1104
- seed: ControlNetworkSeed,
1105
- options?: { claimProof?: string },
1106
- ): Promise<SeedAckMessage> {
1107
- if (!this.libp2pNode) {
1108
- throw new Error('Service not initialized');
1109
- }
1110
- const label = typeof target === 'string' ? target : target.peerId;
1111
- log('Delivering seed to: %s', label);
1112
-
1113
- const openStream = await this.seedStreamOpener(this.libp2pNode, target);
1114
- return await withDeadline(
1115
- this.seedDeliverTimeoutMs,
1116
- `Seed delivery to ${label}`,
1117
- (signal) => this.sendSeed(openStream, seed, options?.claimProof, signal),
1118
- );
1119
- }
1120
-
1121
- /**
1122
- * The part of {@link deliverSeed} that runs before its deadline: how the delivery's stream
1123
- * will be opened, with any connection it needs already formed.
1124
- */
1125
- private async seedStreamOpener(node: Libp2p, target: SeedDeliveryTarget): Promise<SeedStreamOpener> {
1126
- if (typeof target === 'string') {
1127
- const addr = multiaddr(target);
1128
- return (signal) => node.dialProtocol(addr, SEED_PROTOCOL, { signal });
1129
- }
1130
- const peerId = peerIdFromString(target.peerId);
1131
- const addrs = deliveryDialAddrs(target.peerId, target.multiaddrs);
1132
- await mergeSeedPeers(node, [{ peerId: target.peerId, multiaddrs: target.multiaddrs, isOwner: false }]);
1133
- if (addrs.length === 0) {
1134
- return (signal) => node.dialProtocol(peerId, SEED_PROTOCOL, { signal });
1135
- }
1136
- const connection = await this.connectForDelivery(node, peerId, addrs);
1137
- return (signal) => connection.newStream(SEED_PROTOCOL, { signal });
1138
- }
1139
-
1140
- /**
1141
- * A connection to `peerId` for {@link deliverSeed}: one already open, or one dialed from
1142
- * `addrs` by {@link dialPeerAddrs} — each address on `dialBudget.perAddressMs`, the whole
1143
- * peer within `dialBudget.totalMs`, direct addresses before relayed ones and the given
1144
- * order otherwise.
1145
- *
1146
- * @throws {PeerUnreachableError} when no connection formed, with the dial's error as `cause`.
1147
- */
1148
- private async connectForDelivery(node: Libp2p, peerId: PeerId, addrs: readonly Multiaddr[]): Promise<Connection> {
1149
- const open = openUnlimitedConnection(node, peerId);
1150
- if (open) {
1151
- log('Seed delivery to %s reuses an open connection', peerId);
1152
- return open;
1153
- }
1154
- // NOTE: a relayed address can return a limited connection, on which `sendSeed`'s stream
1155
- // open then fails as a plain error rather than `PeerUnreachableError`, though nothing was
1156
- // sent. Claim codes carry no relay addresses today; if a delivery target ever may, count a
1157
- // limited connection as unreachable here.
1158
- try {
1159
- return await dialPeerAddrs(node, addrs, this.dialBudget, `Seed delivery dial of ${peerId}`);
1160
- } catch (error) {
1161
- throw new PeerUnreachableError(peerId.toString(), error);
1162
- }
1163
- }
1164
-
1165
- /**
1166
- * Open one stream to the target, send the seed frame, half-close, and read the ack.
1167
- *
1168
- * `signal` is the deadline from {@link deliverSeed}: it goes to `openStream` so a
1169
- * timeout while dialing or opening the stream aborts it, and into {@link exchangeFrame}
1170
- * so a timeout after the stream is open resets it — releasing the otherwise unbounded
1171
- * ack-read.
1172
- *
1173
- * Deliberately NOT `runOnLimitedConnection`: a wake sets it because a wake is a
1174
- * tiny frame over a relay, whereas a seed is up to 1MB, so a relayed address that
1175
- * forms only a limited connection fails here when the stream is opened. Changing
1176
- * that is a separate decision.
1177
- */
1178
- private async sendSeed(
1179
- openStream: SeedStreamOpener,
1180
- seed: ControlNetworkSeed,
1181
- claimProof: string | undefined,
1182
- signal: AbortSignal,
1183
- ): Promise<SeedAckMessage> {
1184
- const rawStream = await openStream(signal);
1185
-
1186
- const message: SeedMessage = {
1187
- partyId: seed.partyId,
1188
- peers: seed.peers,
1189
- signature: seed.signature,
1190
- signerKey: seed.signerKey,
1191
- ...(claimProof !== undefined ? { claimProof } : {}),
1192
- };
1193
-
1194
- const ack = await exchangeFrame(
1195
- rawStream as unknown as ControlStream,
1196
- signal,
1197
- message,
1198
- (stream) => this.readSeedAck(stream),
1199
- 'Seed delivery aborted by timeout',
1200
- );
1201
-
1202
- log('Seed delivery response: accepted=%s', ack.accepted);
1203
- return ack;
1204
- }
1205
-
1206
- /**
1207
- * Read the ack frame a delivery target writes back, bounded by
1208
- * {@link seedDeliverTimeoutMs} and capped at {@link MAX_SEED_SIZE} — an
1209
- * untrusted target must not be able to stream unlimited bytes as a fake ack.
1210
- * Decoding runs inside {@link exchangeFrame}'s `try`, so a malformed or
1211
- * non-JSON ack resets the stream rather than leaking it.
1212
- */
1213
- private async readSeedAck(stream: ControlStream): Promise<SeedAckMessage> {
1214
- const data = await readStreamToEnd(stream, {
1215
- maxBytes: MAX_SEED_SIZE,
1216
- timeoutMs: this.seedDeliverTimeoutMs,
1217
- label: 'Seed ack',
1218
- });
1219
- const body = decodeLengthPrefixedFrame(data, MAX_SEED_SIZE);
1220
- return JSON.parse(new TextDecoder().decode(body)) as SeedAckMessage;
1221
- }
1222
-
1223
- /**
1224
- * Get this node's circuit relay address for inclusion in seeds.
1225
- * Returns null if no relay address is available.
1226
- */
1227
- async getRelayAddress(): Promise<string | null> {
1228
- if (!this.libp2pNode) {
1229
- return null;
1230
- }
1231
-
1232
- const addrs = this.libp2pNode.getMultiaddrs();
1233
-
1234
- // Find a circuit relay address
1235
- const relayAddr = addrs.find(addr => addr.toString().includes('/p2p-circuit/'));
1236
-
1237
- return relayAddr?.toString() ?? null;
1238
- }
1239
-
1240
- /**
1241
- * Validate a seed's signature.
1242
- *
1243
- * @param digestB64 - The seed's {@link seedDigest}, when the caller already computed it
1244
- * (`verifyAndMergeSeed` shares one digest between this check and the trust context).
1245
- */
1246
- validateSeedSignature(seed: ControlNetworkSeed, digestB64 = seedDigest(seed)): boolean {
1247
- try {
1248
- // The digest is over the shared canonical payload, so verification is
1249
- // independent of key order; the payload is the fixed `{ partyId, peers }`
1250
- // the producer emits.
1251
- return verify(
1252
- digestB64,
1253
- seed.signature,
1254
- seed.signerKey,
1255
- 'ed25519',
1256
- 'base64url',
1257
- 'base64url',
1258
- 'base64url'
1259
- );
1260
- } catch (error) {
1261
- log('Seed signature validation failed: %o', error);
1262
- return false;
1263
- }
1264
- }
1265
-
1266
- /**
1267
- * The peers a seed carries: the control database's own projection
1268
- * ({@link ControlDatabase.querySeedPeers}, shared with the cadre invitation redemption
1269
- * reply), which reads through the revocation filter and flags owners from the replicated
1270
- * `OwnerKey` table — a dial hint, not a trust decision (the NOTE at `projectSeedPeers`).
1271
- */
1272
- private async queryPeers(): Promise<SeedPeer[]> {
1273
- if (!this.controlDatabase) {
1274
- return [];
1275
- }
1276
- return await this.controlDatabase.querySeedPeers();
1277
- }
1278
-
1279
- /**
1280
- * Register the seed protocol handler. The inbound closure just delegates to
1281
- * {@link handleSeedStream} — extracted as a method so it has a unit-test seam
1282
- * (mirroring wake's `handleStream`) the inline closure never had.
1283
- */
1284
- private async registerProtocolHandler(libp2pNode: Libp2p): Promise<void> {
1285
- await libp2pNode.handle(SEED_PROTOCOL, async (rawStream: unknown, rawConnection: unknown) => {
1286
- const remotePeerId = (rawConnection as Connection).remotePeer.toString();
1287
- await this.handleSeedStream(rawStream as ControlStream, remotePeerId);
1288
- });
1289
-
1290
- log('Registered seed protocol handler: %s', SEED_PROTOCOL);
1291
- }
1292
-
1293
- /**
1294
- * Read one inbound seed frame, verify and merge it, write the ack and close the
1295
- * stream, then dial the seed's owners.
1296
- *
1297
- * The ack and the close come BEFORE the owner dials: an unreachable owner can hold
1298
- * a dial for `dialBudget.totalMs` (86 s at the default declared link), which is not
1299
- * link time and does not belong inside the sender's delivery deadline. The close is
1300
- * what releases the sender, which reads the ack to end-of-stream. The stream stays
1301
- * counted in {@link activeStreams} through the dials, so {@link maxConcurrentSeeds}
1302
- * still bounds concurrent owner-dial phases.
1303
- *
1304
- * Hardened against a buggy/compromised own-cadre node: a concurrency cap (over
1305
- * {@link maxConcurrentSeeds}, reply without applying), a read timeout (a peer
1306
- * that never half-closes is aborted inside `readStreamToEnd`), and the existing
1307
- * malformed/oversized-frame guard — all reported as a non-accepting
1308
- * {@link SeedAckMessage} rather than a dropped/hung stream.
1309
- *
1310
- * NOTE: a receiver configured with an interactive trust-on-first-use policy asks a
1311
- * human before acking, and that wait sits inside the sender's delivery deadline. If
1312
- * TOFU is ever used on this wire path, ack "pending" or move the confirmation out of
1313
- * the exchange.
1314
- */
1315
- private async handleSeedStream(stream: ControlStream, remotePeerId: string): Promise<void> {
1316
- log('Incoming seed delivery from: %s', remotePeerId);
1317
-
1318
- if (this.activeStreams >= this.maxConcurrentSeeds) {
1319
- log('Rejecting seed from %s: %d concurrent streams at cap %d', remotePeerId, this.activeStreams, this.maxConcurrentSeeds);
1320
- await replyAndClose(stream, { accepted: false, reason: 'Too many concurrent seed deliveries' } satisfies SeedAckMessage, 'Seed');
1321
- return;
1322
- }
1323
-
1324
- this.activeStreams++;
1325
- let acked = false;
1326
- try {
1327
- const { seed, claimProof } = await this.readSeedFrame(stream);
1328
- this.eventCallbacks.onSeedReceived?.(seed.partyId, remotePeerId);
1329
-
1330
- const merged = await this.verifyAndMergeSeed(seed, { claimProof, remotePeerId });
1331
- acked = true;
1332
- await replyAndClose(
1333
- stream,
1334
- { accepted: merged.success, reason: merged.error, code: merged.code } satisfies SeedAckMessage,
1335
- 'Seed',
1336
- );
1337
-
1338
- if (merged.success) {
1339
- await this.dialSeedOwners(seed);
1340
- this.eventCallbacks.onSeedApplied?.(seed.partyId, merged.peersAdded, seed);
1341
- } else {
1342
- this.eventCallbacks.onSeedError?.(seed.partyId, merged.error ?? 'Unknown error');
1343
- }
1344
- } catch (error) {
1345
- log('Error handling seed delivery: %o', error);
1346
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
1347
- this.eventCallbacks.onSeedError?.(this.config.partyId, errorMessage);
1348
- // Once acked the stream is closed, so a later failure has no reply to make.
1349
- if (!acked) {
1350
- await replyAndClose(stream, { accepted: false, reason: errorMessage } satisfies SeedAckMessage, 'Seed');
1351
- }
1352
- } finally {
1353
- this.activeStreams--;
1354
- }
1355
- }
1356
-
1357
- /**
1358
- * Read the inbound seed frame to EOF (bounded and size-capped) and decode it. The
1359
- * claim proof comes back beside the seed: it is not part of what the owner signed, so
1360
- * `ControlNetworkSeed` does not carry it.
1361
- */
1362
- private async readSeedFrame(stream: ControlStream): Promise<{ seed: ControlNetworkSeed; claimProof?: string }> {
1363
- const data = await readStreamToEnd(stream, {
1364
- maxBytes: MAX_SEED_SIZE,
1365
- timeoutMs: this.seedReadTimeoutMs,
1366
- label: 'Seed',
1367
- });
1368
- const message = JSON.parse(new TextDecoder().decode(decodeLengthPrefixedFrame(data))) as SeedMessage;
1369
- return {
1370
- seed: {
1371
- partyId: message.partyId,
1372
- peers: message.peers,
1373
- signature: message.signature,
1374
- signerKey: message.signerKey,
1375
- },
1376
- claimProof: message.claimProof,
1377
- };
1378
- }
1379
-
1380
- /**
1381
- * Shutdown the service.
1382
- */
1383
- async shutdown(): Promise<void> {
1384
- if (this.libp2pNode) {
1385
- await this.libp2pNode.unhandle(SEED_PROTOCOL);
1386
- }
1387
- this.libp2pNode = null;
1388
- this.controlDatabase = null;
1389
- log('SeedBootstrapService shutdown');
1390
- }
1391
-
1392
- // ============================================================================
1393
- // Helper Functions for Common Scenarios
1394
- // ============================================================================
1395
-
1396
- /**
1397
- * Add a drone to the cadre (phone/server adds provider-hosted node).
1398
- *
1399
- * Use this when you've spawned a drone via provider API and received its
1400
- * peer ID and multiaddrs. This method:
1401
- * 1. Authorizes the drone peer
1402
- * 2. Creates a seed including all current peers
1403
- * 3. Returns the seed for sending to provider API
1404
- *
1405
- * Nothing here dials the drone or remembers its addresses beyond the unsigned
1406
- * `CadrePeer` row, which no resolver accepts. `CadreNode.addDrone` is the entry
1407
- * point that also retains them as a durable dial target, so the adder's
1408
- * reconcile pass can open the connection — the drone cannot dial an owner that
1409
- * does not listen. Call `CadreNode.reconcileControlCohort()` after delivering
1410
- * the seed to dial at once.
1411
- *
1412
- * @param options - Drone peer info from provider API
1413
- * @returns Seed and encoded seed for drone initialization
1414
- */
1415
- async addDrone(options: AddDroneOptions): Promise<DroneInitResult> {
1416
- const { dronePeerId, droneMultiaddrs } = options;
1417
-
1418
- log('Adding drone: %s', dronePeerId);
1419
-
1420
- // 1. Authorize the new drone peer
1421
- await this.authorizePeer({ peerId: dronePeerId, multiaddrs: droneMultiaddrs });
1422
-
1423
- // 2. Create seed with current state
1424
- const seed = await this.createSeed();
1425
-
1426
- // 3. Encode for transport
1427
- const encodedSeed = this.encodeSeed(seed);
1428
-
1429
- log('Drone %s added, seed created with %d peers', dronePeerId, seed.peers.length);
1430
-
1431
- return { seed, encodedSeed };
1432
- }
1433
-
1434
- /**
1435
- * Add a phone to the cadre with relay support.
1436
- *
1437
- * Use this when both nodes are NAT'd (phone-to-phone). This method:
1438
- * 1. Authorizes the new phone peer
1439
- * 2. Creates a seed with relay addresses for dialing
1440
- *
1441
- * @param phonePeerId - Peer ID of the new phone
1442
- * @returns Seed with relay addresses for out-of-band delivery
1443
- */
1444
- async addPhoneWithRelay(phonePeerId: string): Promise<DroneInitResult> {
1445
- log('Adding phone with relay: %s', phonePeerId);
1446
-
1447
- // 1. Authorize the new phone peer (no multiaddrs - NAT'd)
1448
- await this.authorizePeer({ peerId: phonePeerId });
1449
-
1450
- // 2. Get relay address for this node
1451
- const relayAddr = await this.getRelayAddress();
1452
-
1453
- // 3. Create seed - will include our relay address if available
1454
- const seed = await this.createSeed();
1455
-
1456
- // If we have a relay address, make sure it's in our peer entry
1457
- if (relayAddr && this.libp2pNode) {
1458
- const ourPeerId = this.libp2pNode.peerId.toString();
1459
- const ourPeer = seed.peers.find(p => p.peerId === ourPeerId);
1460
- if (ourPeer && !ourPeer.multiaddrs.includes(relayAddr)) {
1461
- ourPeer.multiaddrs.push(relayAddr);
1462
- }
1463
- }
1464
-
1465
- const encodedSeed = this.encodeSeed(seed);
1466
-
1467
- log('Phone %s added with relay, seed created', phonePeerId);
1468
-
1469
- return { seed, encodedSeed };
1470
- }
1471
- }
1
+ import debug from 'debug';
2
+ import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
3
+ import { digest, sign, verify, getPublicKey } from '@optimystic/quereus-plugin-crypto';
4
+ import type { Libp2p, Connection, PeerId, Stream } from '@libp2p/interface';
5
+ import { multiaddr, type Multiaddr } from '@multiformats/multiaddr';
6
+ import { peerIdFromString } from '@libp2p/peer-id';
7
+ import { type ControlStream, withDeadline, exchangeFrame, readStreamToEnd, replyAndClose } from './control-stream.js';
8
+ import {
9
+ dialPeerAddrs,
10
+ SelfRelayOnlyError,
11
+ PeerUnreachableError,
12
+ DEFAULT_PEER_DIAL_BUDGET,
13
+ type PeerDialBudget,
14
+ withTrailingPeerId,
15
+ } from './peer-dial.js';
16
+ import { relayedRequestBudgetMs } from './link-budget.js';
17
+ import type {
18
+ ControlNetworkSeed,
19
+ SeedPeer,
20
+ SeedMessage,
21
+ SeedAckMessage,
22
+ SeedRefusalCode,
23
+ SeedDeliveryTarget,
24
+ AuthorizePeerOptions,
25
+ ApplySeedResult,
26
+ AddDroneOptions,
27
+ DroneInitResult,
28
+ CadreInviteRow,
29
+ NodeProfile,
30
+ PeerAddressRecord,
31
+ DeviceTokenRecord,
32
+ RevocationRow,
33
+ RevocationLedgerOpenResult
34
+ } from './types.js';
35
+ import type { ControlDatabase, MachineRemovalWrites } from './control-database.js';
36
+ import { generateStampId } from './control-database.js';
37
+ import { canonicalJson } from './canonical-json.js';
38
+ import { deviceTokenAddDigest } from './peer-authorization.js';
39
+ import { ed25519PublicKeyB64FromPeerId } from './ed25519-key.js';
40
+ import {
41
+ type SeedTrustPolicy,
42
+ type SeedTrustDecision,
43
+ anchoredTrustPolicy,
44
+ } from './seed-trust-policy.js';
45
+ import type { TrustedOwnerStore } from './trusted-owner-store.js';
46
+
47
+ const log = debug('sereus:cadre:seed-bootstrap');
48
+
49
+ /** Protocol ID for seed delivery */
50
+ export const SEED_PROTOCOL = '/sereus/seed/1.0.0';
51
+
52
+ /** Maximum seed message size (1MB) */
53
+ const MAX_SEED_SIZE = 1024 * 1024;
54
+
55
+ /**
56
+ * Default time the receiver waits for an inbound seed frame before aborting (ms). It covers the
57
+ * read only: the trust decision and the peer-store merge run after it.
58
+ */
59
+ // eslint-disable-next-line no-restricted-syntax -- link-independent: a receiver cap on one seed frame on a stream the peer already opened; it bounds a peer that opens a stream and never sends, not the dial
60
+ const DEFAULT_SEED_READ_TIMEOUT_MS = 10_000;
61
+
62
+ /** Default cap on concurrent inbound seed streams a single peer can pin open. */
63
+ const DEFAULT_MAX_CONCURRENT_SEEDS = 100;
64
+
65
+ /**
66
+ * Decode a 4-byte big-endian length-prefixed frame; returns the body bytes.
67
+ *
68
+ * Guards every parse site against malformed input: a buffer too short to hold
69
+ * the prefix, a declared length exceeding `maxLength`, and a declared length
70
+ * exceeding the bytes actually present. Returns a view (`subarray`, no copy) —
71
+ * the body is handed straight to `TextDecoder`.
72
+ */
73
+ export function decodeLengthPrefixedFrame(data: Uint8Array, maxLength = MAX_SEED_SIZE): Uint8Array {
74
+ if (data.length < 4) {
75
+ throw new Error(`Seed frame too short: ${data.length} bytes, need ≥4 for length prefix`);
76
+ }
77
+ // Pass the full (buffer, byteOffset, byteLength) triple so the read is correct
78
+ // even for a non-zero-offset view, not just the fresh zero-offset arrays
79
+ // current callers pass.
80
+ const length = new DataView(data.buffer, data.byteOffset, data.byteLength).getUint32(0, false);
81
+ const available = data.length - 4;
82
+ if (length > maxLength) {
83
+ throw new Error(`Seed frame declares length ${length} exceeding max ${maxLength}`);
84
+ }
85
+ if (length > available) {
86
+ throw new Error(`Seed frame declares length ${length} but only ${available} body bytes present`);
87
+ }
88
+ return data.subarray(4, 4 + length);
89
+ }
90
+
91
+ /**
92
+ * Canonical byte representation of the authenticated seed fields.
93
+ *
94
+ * Routes both the creator (`createSeed`) and the verifier
95
+ * (`validateSeedSignature`) through one builder so the signed bytes are
96
+ * identical regardless of key insertion order. `canonicalJson` sorts keys and
97
+ * drops `undefined`, so the signed payload is exactly `{ partyId, peers }` —
98
+ * the fields the producer actually emits.
99
+ */
100
+ export function canonicalSeedPayload(
101
+ seed: Pick<ControlNetworkSeed, 'partyId' | 'peers'>
102
+ ): string {
103
+ return canonicalJson({ partyId: seed.partyId, peers: seed.peers });
104
+ }
105
+
106
+ /**
107
+ * The digest a seed's signature covers: sha256 over {@link canonicalSeedPayload},
108
+ * base64url. One function so the signer (`createSeed`), the verifier
109
+ * (`validateSeedSignature`) and the claim proof (`claim-proof.ts`, which binds a
110
+ * proof to one seed through this value) all name the same bytes.
111
+ */
112
+ export function seedDigest(seed: Pick<ControlNetworkSeed, 'partyId' | 'peers'>): string {
113
+ return digest([canonicalSeedPayload(seed)], 'sha256', 'base64url') as string;
114
+ }
115
+
116
+ /**
117
+ * An {@link ApplySeedResult} for a seed refused before the owner-dial loop ran,
118
+ * so the dial counters read zero rather than being absent.
119
+ */
120
+ function seedRejected(error: string, code?: SeedRefusalCode): ApplySeedResult {
121
+ return {
122
+ success: false,
123
+ peersAdded: 0,
124
+ error,
125
+ ...(code !== undefined ? { code } : {}),
126
+ ownerDialsAttempted: 0,
127
+ ownerDialsFailed: 0,
128
+ };
129
+ }
130
+
131
+ /** What rides beside a seed into {@link SeedBootstrapService.verifyAndMergeSeed}. */
132
+ interface SeedApplyOptions {
133
+ /** Per-call policy override, used instead of the service-configured default for this seed only. */
134
+ trustPolicy?: SeedTrustPolicy;
135
+ /** The claim proof the message carried, when the seed came over the wire. */
136
+ claimProof?: string;
137
+ /** The delivering peer, when the seed came over the wire. */
138
+ remotePeerId?: string;
139
+ }
140
+
141
+ /** What dialing a seed's owner peers produced — the owner-dial half of an {@link ApplySeedResult}. */
142
+ type OwnerDialCounts = Pick<ApplySeedResult, 'ownerDialsAttempted' | 'ownerDialsFailed'>;
143
+
144
+ /**
145
+ * Parse each address, dropping (and logging) any that is malformed, so one bad
146
+ * entry cannot keep a peer's valid addresses from being dialed.
147
+ */
148
+ function parseDialAddrs(addrs: readonly string[]): Multiaddr[] {
149
+ const parsed: Multiaddr[] = [];
150
+ for (const addr of addrs) {
151
+ try {
152
+ parsed.push(multiaddr(addr));
153
+ } catch (error) {
154
+ log('Skipping malformed dial address %s: %o', addr, error);
155
+ }
156
+ }
157
+ return parsed;
158
+ }
159
+
160
+ /**
161
+ * Merge a peer list's addresses into `node`'s peer store, so the node can dial them: the
162
+ * seed's peers after its signature and trust checks, the dial hints a member returns on
163
+ * a cadre invitation redemption (`cadre-invite-protocol.ts`), or the node a seed is being
164
+ * delivered to ({@link SeedBootstrapService.deliverSeed}). Best-effort per peer — one
165
+ * unparsable entry costs that peer, not the rest — and a peer with no address is skipped,
166
+ * since there is nothing to dial. Returns how many peers were merged.
167
+ */
168
+ export async function mergeSeedPeers(node: Libp2p, peers: readonly SeedPeer[]): Promise<number> {
169
+ let peersAdded = 0;
170
+ for (const peer of peers) {
171
+ if (peer.multiaddrs.length === 0) {
172
+ continue;
173
+ }
174
+ try {
175
+ const peerId = peerIdFromString(peer.peerId);
176
+ const addrs = peer.multiaddrs.map(ma => multiaddr(ma));
177
+ await node.peerStore.merge(peerId, { multiaddrs: addrs });
178
+ peersAdded++;
179
+ log('Added peer to store: %s with %d addrs', peer.peerId, addrs.length);
180
+ } catch (error) {
181
+ log('Failed to add peer %s: %o', peer.peerId, error);
182
+ }
183
+ }
184
+ return peersAdded;
185
+ }
186
+
187
+ /** Opens a seed delivery's stream under the delivery deadline's signal. */
188
+ type SeedStreamOpener = (signal: AbortSignal) => Promise<Stream>;
189
+
190
+ /**
191
+ * A delivery target's addresses, each bound to its peer id (`withTrailingPeerId`) so the dial
192
+ * authenticates the node it aims at rather than trusting whoever answers. An address that does
193
+ * not parse, or that names another peer, throws: that is the caller's mistake, not the node
194
+ * being unreachable.
195
+ */
196
+ function deliveryDialAddrs(peerId: string, addrs: readonly string[]): Multiaddr[] {
197
+ return addrs.map((text) => {
198
+ const bound = withTrailingPeerId(multiaddr(text), peerId);
199
+ if (!bound) {
200
+ throw new Error(`Seed delivery to ${peerId}: address ${text} names another peer`);
201
+ }
202
+ return bound;
203
+ });
204
+ }
205
+
206
+ /**
207
+ * Configuration for the SeedBootstrapService
208
+ */
209
+ export interface SeedBootstrapConfig {
210
+ /** Party ID for this cadre */
211
+ partyId: string;
212
+ /** Owner private key for signing seeds and peer authorizations (base64url) */
213
+ ownerPrivateKey?: string;
214
+ /** Owner public key (base64url) - derived from private key if not provided */
215
+ ownerPublicKey?: string;
216
+ /**
217
+ * Trust anchor for incoming seeds. Decides whether a signature-verified
218
+ * `signerKey` should be trusted, against the receiver's anchored owner
219
+ * keys (NOT the seed body). Defaults to `anchoredTrustPolicy()`, which
220
+ * rejects any signer not already in {@link trustedOwners}. An enrollment
221
+ * caller can pass a per-seed override to `applySeed` instead.
222
+ *
223
+ * A `CadreNode` forwards its node-wide `CadreNodeConfig.seedTrustPolicy` here
224
+ * — that is the only seam the inbound libp2p seed-protocol handler can use,
225
+ * since a network-delivered seed has no per-call override.
226
+ */
227
+ trustPolicy?: SeedTrustPolicy;
228
+ /**
229
+ * The node-local, NON-replicated trusted-owner anchor. Supplies
230
+ * `SeedTrustContext.knownOwnerKeys` for every {@link applySeed}, and receives
231
+ * a key accepted via a pin/TOFU (see `SeedTrustDecision.anchorAs`).
232
+ *
233
+ * Deliberately NOT `ControlDatabase.getOwnerKeys()`: the replicated
234
+ * `OwnerKey` table is pollutable — any connecting node can genesis-insert its
235
+ * own key and let it replicate — so a seed signed by a stranger's self-issued
236
+ * owner key would pass a table-anchored check. A `CadreNode` passes its
237
+ * `getTrustedOwnerStore()` here. Unset (e.g. a directly-constructed service in
238
+ * a test) means an EMPTY anchor: only a pinned/TOFU policy can accept a seed.
239
+ */
240
+ trustedOwners?: TrustedOwnerStore;
241
+ /**
242
+ * Time the inbound seed handler waits for the seed frame before aborting the
243
+ * read (ms). Defaults to {@link DEFAULT_SEED_READ_TIMEOUT_MS}. Bounds a
244
+ * buggy/compromised own-cadre node that opens a stream and never half-closes.
245
+ */
246
+ seedReadTimeoutMs?: number;
247
+ /**
248
+ * Cap on concurrent inbound seed streams (defaults to
249
+ * {@link DEFAULT_MAX_CONCURRENT_SEEDS}). Over the cap, a non-accepting ack is
250
+ * returned without applying any seed.
251
+ */
252
+ maxConcurrentSeeds?: number;
253
+ /**
254
+ * The host's declared link round trip (`NetworkConfig.linkRoundTripMs`), from which
255
+ * {@link seedDeliverTimeoutMs}'s default is derived. Unset means the declared default.
256
+ */
257
+ linkRoundTripMs?: number;
258
+ /**
259
+ * Time {@link SeedBootstrapService.deliverSeed} waits for the request — opening the
260
+ * stream, write, ack read — before aborting (ms). For a multiaddr string, or a peer id
261
+ * with no addresses, opening the stream includes the dial; for a peer id with addresses
262
+ * the connection is formed first, outside this limit and within {@link dialBudget}.
263
+ * Bounds the SENDER against a seed target that accepts the stream and then never replies;
264
+ * the target is a not-yet-trusted node during onboarding, so this is the more exposed
265
+ * direction than the receiver knobs above.
266
+ *
267
+ * Defaults to `relayedRequestBudgetMs(linkRoundTripMs)` (`link-budget.ts`; 28.5 s at the
268
+ * default declaration): one dial that may need a relay, then one request and its answer —
269
+ * sized for the forms that dial inside it. Delivery does not set `runOnLimitedConnection`,
270
+ * so it does not use a limited relayed connection today; the relayed-dial count is the upper
271
+ * bound on the dial it can use, the same choice `CadreNode.controlDialBudget` makes for every
272
+ * address. It holds only link work because the receiver acks before its owner dials.
273
+ *
274
+ * NOTE: no transfer allowance — a seed is a peer list of a few KB, and `MAX_SEED_SIZE` (1 MiB)
275
+ * is a defensive cap. If seeds ever grow toward that cap, add an allowance the way
276
+ * `PUSH_TRANSFER_ALLOWANCE_MS` does.
277
+ */
278
+ seedDeliverTimeoutMs?: number;
279
+ /**
280
+ * Time limits for each peer this service dials from a list of addresses —
281
+ * {@link SeedBootstrapService.applySeed}'s owner dials and
282
+ * {@link SeedBootstrapService.deliverSeed}'s dial of a peer id with addresses — per
283
+ * address and per peer (see `peer-dial.ts`). Defaults to {@link DEFAULT_PEER_DIAL_BUDGET}; a `CadreNode`
284
+ * passes its `network.controlCohort` limits.
285
+ */
286
+ dialBudget?: PeerDialBudget;
287
+ }
288
+
289
+ /**
290
+ * Event callbacks for seed-related events
291
+ */
292
+ export interface SeedEventCallbacks {
293
+ /** Called when a seed is received via the protocol */
294
+ onSeedReceived?: (partyId: string, peerId: string) => void;
295
+ /**
296
+ * Called when a seed is successfully applied.
297
+ *
298
+ * `seed` is the applied seed itself: the inbound protocol handler applies it
299
+ * INSIDE the service, so this callback is the only seam through which a
300
+ * `CadreNode` sees a wire-delivered seed's contents — which it needs to
301
+ * retain the owner-flagged peers as cold-start bootstrap dial targets.
302
+ */
303
+ onSeedApplied?: (partyId: string, peersAdded: number, seed: ControlNetworkSeed) => void;
304
+ /** Called when seed application fails */
305
+ onSeedError?: (partyId: string, error: string) => void;
306
+ }
307
+
308
+ /**
309
+ * SeedBootstrapService handles control network seed generation and delivery.
310
+ *
311
+ * Seeds solve the cold-start problem: new nodes need control data to validate
312
+ * connections, but can't get data without connecting first. Seeds pre-populate
313
+ * the new node's cache with peer information.
314
+ */
315
+ export class SeedBootstrapService {
316
+ private readonly config: SeedBootstrapConfig;
317
+ private libp2pNode: Libp2p | null = null;
318
+ private controlDatabase: ControlDatabase | null = null;
319
+ private readonly ownerPublicKey: string | null;
320
+ private readonly trustPolicy: SeedTrustPolicy;
321
+ private readonly seedReadTimeoutMs: number;
322
+ private readonly maxConcurrentSeeds: number;
323
+ private readonly seedDeliverTimeoutMs: number;
324
+ private readonly dialBudget: PeerDialBudget;
325
+ /** In-flight inbound seed streams, used to enforce {@link maxConcurrentSeeds}. */
326
+ private activeStreams = 0;
327
+ private eventCallbacks: SeedEventCallbacks = {};
328
+
329
+ constructor(config: SeedBootstrapConfig) {
330
+ this.config = config;
331
+ this.trustPolicy = config.trustPolicy ?? anchoredTrustPolicy();
332
+ this.seedReadTimeoutMs = config.seedReadTimeoutMs ?? DEFAULT_SEED_READ_TIMEOUT_MS;
333
+ this.maxConcurrentSeeds = config.maxConcurrentSeeds ?? DEFAULT_MAX_CONCURRENT_SEEDS;
334
+ this.seedDeliverTimeoutMs = config.seedDeliverTimeoutMs ?? relayedRequestBudgetMs(config.linkRoundTripMs);
335
+ this.dialBudget = config.dialBudget ?? DEFAULT_PEER_DIAL_BUDGET;
336
+
337
+ // Derive public key from private key if not provided
338
+ if (config.ownerPrivateKey && !config.ownerPublicKey) {
339
+ this.ownerPublicKey = getPublicKey(
340
+ config.ownerPrivateKey,
341
+ 'ed25519',
342
+ 'base64url',
343
+ 'base64url'
344
+ ) as string;
345
+ } else {
346
+ this.ownerPublicKey = config.ownerPublicKey ?? null;
347
+ }
348
+
349
+ log('SeedBootstrapService created for party: %s', config.partyId);
350
+ }
351
+
352
+ /**
353
+ * Set event callbacks for seed-related events.
354
+ * Used by CadreNode to emit events.
355
+ */
356
+ setEventCallbacks(callbacks: SeedEventCallbacks): void {
357
+ this.eventCallbacks = callbacks;
358
+ }
359
+
360
+ /**
361
+ * Whether this service holds an owner private key, i.e. can produce the
362
+ * owner signatures that gate `CadrePeer` / `DeviceToken` inserts, deletes,
363
+ * and re-authorizations. A seed-listener-only service (`enableSeedListener`,
364
+ * no owner key) returns false: it can receive/apply seeds but cannot author
365
+ * or re-issue owner writes. Used by the write-while-alone re-replication
366
+ * drain to skip owner work on a non-owner node.
367
+ */
368
+ canAuthorize(): boolean {
369
+ return !!this.config.ownerPrivateKey;
370
+ }
371
+
372
+ /**
373
+ * Initialize the service with libp2p node and control database.
374
+ *
375
+ * `registerHandler` (default true) gates registration of the shared inbound
376
+ * `/sereus/seed/1.0.0` handler on `libp2pNode`. Persistent services
377
+ * (`initializeSeedBootstrap`, `enableSeedListener`) own that handler and leave
378
+ * it on. The throwaway temp service CadreNode builds in `applySeed` passes
379
+ * `false`: it only needs the stored `libp2pNode` / `controlDatabase` for
380
+ * dialing and known-key lookup, and must NOT bind a discarded closure to the
381
+ * shared node (a handler leak, and a second
382
+ * `handle()` of the same protocol throws `DuplicateProtocolHandlerError`).
383
+ *
384
+ * Rejects when libp2p refuses the registration; the node and database are
385
+ * kept only once the handler is in place, so a failed service holds nothing
386
+ * for {@link shutdown} to unhandle.
387
+ */
388
+ async initialize(
389
+ libp2pNode: Libp2p,
390
+ controlDatabase: ControlDatabase,
391
+ options?: { registerHandler?: boolean }
392
+ ): Promise<void> {
393
+ // Register the seed protocol handler unless the caller opted out (temp services).
394
+ if (options?.registerHandler ?? true) {
395
+ await this.registerProtocolHandler(libp2pNode);
396
+ }
397
+
398
+ this.libp2pNode = libp2pNode;
399
+ this.controlDatabase = controlDatabase;
400
+ log('SeedBootstrapService initialized');
401
+ }
402
+
403
+ /**
404
+ * Authorize a new peer to join the cadre.
405
+ * Signs a membership voucher with the owner key and inserts into CadrePeer table.
406
+ *
407
+ * The owner vouches the `PublicKey <-> PeerId` binding: rather than trust a
408
+ * caller-supplied key, the binding is enforced by construction — `PublicKey` is
409
+ * DERIVED from the (Ed25519) `peerId`. A non-Ed25519 peer id yields a null
410
+ * `PublicKey`, and such a row can never be self-updated (it has no key to
411
+ * verify against), which is correct. The row is inserted with a fresh
412
+ * `UpdatedAt` but no self-signature (`Sig` null) — the owner cannot produce
413
+ * the peer's self-signature, so the peer must self-publish (see
414
+ * {@link CadreNode.registerSelf}) before the row resolves.
415
+ */
416
+ async authorizePeer(options: AuthorizePeerOptions): Promise<void> {
417
+ const { peerId, multiaddrs } = options;
418
+ log('Authorizing peer: %s', peerId);
419
+ // CadrePeer.Multiaddr stores a comma-joined list; use '' when no addrs provided.
420
+ const multiaddrStr = multiaddrs?.length ? multiaddrs.join(',') : '';
421
+ await this.insertCadrePeerRow({
422
+ peerId,
423
+ publicKey: ed25519PublicKeyB64FromPeerId(peerId),
424
+ multiaddr: multiaddrStr,
425
+ updatedAt: Date.now(),
426
+ sig: null,
427
+ profile: null,
428
+ });
429
+ log('Peer %s authorized successfully', peerId);
430
+ }
431
+
432
+ /**
433
+ * Owner-signed INSERT of this node's OWN self-signed address record.
434
+ *
435
+ * Used by {@link CadreNode.registerSelf} when the node is not yet a member and
436
+ * is its own owner (it holds the owner key): the row is owner-signed
437
+ * (satisfying `AuthorizedInsert`) AND carries a valid self-`Sig`, so it resolves
438
+ * immediately without a follow-up self-update.
439
+ *
440
+ * @returns `true` when this call seated the row, `false` when a concurrent writer
441
+ * (e.g. an {@link authorizePeer} of this node's own id) had already seated it —
442
+ * in which case the row in the database is NOT this record and carries whatever
443
+ * `Sig` that writer had, so the caller must self-update to publish its signature.
444
+ */
445
+ async insertSelfPeerRecord(record: PeerAddressRecord): Promise<boolean> {
446
+ return await this.insertCadrePeerRow({
447
+ peerId: record.peerId,
448
+ publicKey: record.publicKey,
449
+ multiaddr: record.addrs.join(','),
450
+ updatedAt: record.updatedAt,
451
+ sig: record.sig,
452
+ profile: record.profile,
453
+ });
454
+ }
455
+
456
+ /**
457
+ * Shared owner-signed `CadrePeer` INSERT — the row fields and the owner-key
458
+ * precondition; the stamp mint, voucher signature, write lock, existence check and
459
+ * membership notify are all {@link ControlDatabase.insertCadrePeer}'s (see there for
460
+ * the anti-replay and insert-race rationale). No `CadrePeer` write may bypass that
461
+ * method: the write is what admits the peer's traffic.
462
+ *
463
+ * The DB check precedes the owner-key check here, matching the order this method has
464
+ * always surfaced them (the owner-key error used to come out of the signer, after the
465
+ * DB check).
466
+ *
467
+ * @returns `true` when this call performed the INSERT, `false` when the row was
468
+ * already seated by a concurrent writer. The loser needs to know: an authorize seats
469
+ * a row with a null `Sig`, so a self-publish that lost the race must fall through to
470
+ * a self-update or its record never lands.
471
+ */
472
+ private async insertCadrePeerRow(row: {
473
+ peerId: string;
474
+ publicKey: string | null;
475
+ multiaddr: string;
476
+ updatedAt: number;
477
+ sig: string | null;
478
+ profile: NodeProfile | null;
479
+ }): Promise<boolean> {
480
+ if (!this.controlDatabase) {
481
+ throw new Error('Control database not initialized');
482
+ }
483
+ const ownerKey = this.requireOwnerPublicKey();
484
+ return await this.controlDatabase.insertCadrePeer(
485
+ row, ownerKey, message => this.signMessageBytes(message),
486
+ );
487
+ }
488
+
489
+ /**
490
+ * Owner-signed INSERT of a peer's OWN self-signed `DeviceToken` row.
491
+ *
492
+ * Counterpart to {@link insertSelfPeerRecord} for the device-token registry: the
493
+ * row is owner-signed (satisfying `DeviceToken.AuthorizedInsert` via the
494
+ * 'add'-tagged digest, {@link deviceTokenAddDigest}) AND carries the peer's
495
+ * own self-`Sig` over the token payload. The owner signature covers the WHOLE row
496
+ * (every column, ending in a freshly minted single-use `StampId`) — but covering the
497
+ * token contents is not the same as vouching them: the peer's `Sig` (verified at
498
+ * resolve time against the bound `CadrePeer.PublicKey`) is what makes the row
499
+ * resolvable. Used by {@link CadreNode.registerDeviceToken} for the first publish
500
+ * when the node is its own owner.
501
+ *
502
+ * The stamp is per-INSERT, so a re-register after a clear mints a fresh one and a
503
+ * fresh signature — unaffected by the cleared row's retired stamp
504
+ * (`DeviceToken.NotRevoked`).
505
+ */
506
+ async insertSelfDeviceToken(record: DeviceTokenRecord): Promise<void> {
507
+ const stampId = generateStampId(record.peerId);
508
+ const signature = this.signDigest(deviceTokenAddDigest(this.config.partyId, { ...record, stampId }));
509
+ if (!this.controlDatabase) {
510
+ throw new Error('Control database not initialized');
511
+ }
512
+ await this.controlDatabase.execWrite(`
513
+ insert into CadreControl.DeviceToken (PeerId, Platform, Token, UpdatedAt, Sig, StampId)
514
+ with context OwnerKey = ?, Signature = ?
515
+ values (?, ?, ?, ?, ?, ?)
516
+ `, [this.ownerPublicKey, signature, record.peerId, record.platform, record.token, record.updatedAt, record.sig, stampId], 'device-token-insert');
517
+ log('Device token inserted (owner-signed): %s', record.peerId);
518
+ }
519
+
520
+ /**
521
+ * Owner-signed DELETE of a peer's `DeviceToken` row (logout / token
522
+ * invalidation). The `DeviceToken.AuthorizedDelete` constraint validates an owner
523
+ * signature over the 'remove'-tagged digest bound to the STORED row's
524
+ * (PeerId, StampId) — deliberately distinct from the insert digest, so a captured
525
+ * insert approval can never be replayed to clear a token. Like {@link removePeer}
526
+ * for `CadrePeer`, clearing a token requires the owner key.
527
+ *
528
+ * The delete and the `Revocation` tombstone retiring the row's `StampId` commit in
529
+ * ONE transaction — `DeviceToken.RevocationRecorded` refuses a bare delete, and
530
+ * without the tombstone the stamp would free up and the never-expiring insert
531
+ * approval (which the cleared device holds a copy of) would re-seat the token. The
532
+ * tombstone carries its OWN owner signature: retiring a stamp permanently forecloses
533
+ * that row, so it is an owner action in its own right.
534
+ *
535
+ * Both digests, the stamp read, and the transaction come from
536
+ * {@link ControlDatabase.deleteDeviceToken} — one shared implementation across
537
+ * `CadrePeer` / `DeviceToken` / `Strand` / `ValidationKey`. What stays here is the
538
+ * owner-key precondition; a no-op on an already-absent row is the shared body's
539
+ * behavior, and unlike {@link removePeer} nothing here rides on it.
540
+ */
541
+ async deleteDeviceToken(peerId: string): Promise<void> {
542
+ // Fail fast on a keyless service BEFORE the DB read, so a non-owner gets the
543
+ // owner-key error rather than a silent no-op on an absent row.
544
+ const ownerKey = this.requireOwnerPublicKey();
545
+ if (!this.controlDatabase) {
546
+ throw new Error('Control database not initialized');
547
+ }
548
+ await this.controlDatabase.deleteDeviceToken(
549
+ peerId, ownerKey, message => this.signMessageBytes(message),
550
+ );
551
+ }
552
+
553
+ /**
554
+ * Return the configured owner private key, or throw if none is set. The single
555
+ * precondition gate for every owner-signed write. {@link removePeer} /
556
+ * {@link reauthorizePeer} read the row's `StampId` from the DB BEFORE they sign, so
557
+ * they call this up front — otherwise a keyless service would either surface the
558
+ * wrong "Control database not initialized" error or, worse, silently no-op when the
559
+ * target row is absent (the early `stampId === null` return) instead of rejecting.
560
+ */
561
+ private requireOwnerPrivateKey(): string {
562
+ if (!this.config.ownerPrivateKey) {
563
+ throw new Error('Owner private key required to authorize peers');
564
+ }
565
+ return this.config.ownerPrivateKey;
566
+ }
567
+
568
+ /**
569
+ * The owner PUBLIC key that rides in every owner-signed write's context, non-null.
570
+ *
571
+ * The field is nullable because a read-only service carries no owner key at all, but the
572
+ * constructor derives the public key whenever `ownerPrivateKey` is set — so gating on
573
+ * {@link requireOwnerPrivateKey} first makes the pair inseparable and the second throw
574
+ * unreachable. Callers that must reject a keyless service BEFORE any DB read use this as
575
+ * their first line and get the owner-key precondition for free.
576
+ */
577
+ private requireOwnerPublicKey(): string {
578
+ this.requireOwnerPrivateKey();
579
+ if (!this.ownerPublicKey) {
580
+ throw new Error('Owner public key required to authorize peers');
581
+ }
582
+ return this.ownerPublicKey;
583
+ }
584
+
585
+ /**
586
+ * Sign a base64url digest with the owner key (ed25519). The single place the
587
+ * owner private key is applied; callers pass the canonical domain-tagged digest for
588
+ * the specific action ({@link deviceTokenAddDigest}), or the raw-bytes form via
589
+ * {@link signMessageBytes}. Throws if no owner key is set.
590
+ */
591
+ private signDigest(digestB64url: string): string {
592
+ return sign(
593
+ digestB64url,
594
+ this.requireOwnerPrivateKey(),
595
+ 'ed25519',
596
+ 'base64url',
597
+ 'base64url',
598
+ 'base64url'
599
+ ) as string;
600
+ }
601
+
602
+ /**
603
+ * Adapt the control database's raw-bytes `signMessage` callback (every guarded delete
604
+ * takes one) to {@link signDigest}'s base64url-string form. Both encodings hash to the
605
+ * same signed bytes (`sign` decodes its base64url input), so a signature minted here
606
+ * satisfies the same schema CHECK as one from the callers that sign the bytes directly — see
607
+ * `control-revocation-replay.spec.ts`'s "raw-bytes and digest-string signers agree".
608
+ */
609
+ private signMessageBytes(message: Uint8Array): string {
610
+ return this.signDigest(uint8ArrayToString(message, 'base64url'));
611
+ }
612
+
613
+ /**
614
+ * Remove a peer from the cadre by owner signature.
615
+ *
616
+ * The `CadrePeer.AuthorizedDelete` (`check on delete`) constraint validates a
617
+ * signature over the DISTINCT 'remove'-tagged digest
618
+ * `digest('CadreControl.CadrePeer', 'remove', party_id(), old.PeerId, old.StampId)` by an owner
619
+ * key — deliberately NOT the insert voucher digest, so the row's stored `VouchSig` can
620
+ * never be replayed to delete.
621
+ *
622
+ * The delete and the `Revocation` tombstone retiring the row's `StampId` commit in ONE
623
+ * transaction — `CadrePeer.RevocationRecorded` refuses a bare delete, and without the
624
+ * tombstone the stamp would free up and the original admission approval (which never
625
+ * expires, and which the removed peer holds a copy of) would re-seat the row.
626
+ *
627
+ * The tombstone is separately owner-signed (satisfying `Revocation.Authorized`):
628
+ * retiring a stamp evicts that peer party-wide and permanently forecloses re-admitting
629
+ * the row, so it is an owner action in its own right, not a side effect the delete's
630
+ * signature covers.
631
+ *
632
+ * Both digests, the stamp read, the transaction, and the post-commit membership notify
633
+ * come from {@link ControlDatabase.deleteCadrePeer} — one shared implementation across
634
+ * `CadrePeer` / `DeviceToken` / `Strand` / `ValidationKey`. What stays here is the
635
+ * owner-key precondition and the absent-row gate the notify depends on (below).
636
+ */
637
+ async removePeer(peerId: string): Promise<void> {
638
+ // Fail fast on a keyless service BEFORE any DB read: a non-owner cannot sign the
639
+ // remove digest, and this precedence (owner key, then control DB) is what the
640
+ // unit contract asserts.
641
+ const ownerKey = this.requireOwnerPublicKey();
642
+ if (!this.controlDatabase) {
643
+ throw new Error('Control database not initialized');
644
+ }
645
+ // This absent-row gate must stay OUTSIDE the delete, even though the delete repeats it
646
+ // internally: deleteCadrePeer's membership notify fires whenever its body resolves,
647
+ // with no idea whether the body wrote anything, so delegating an absent peer would
648
+ // fire a spurious membership notification.
649
+ // NOTE: deleteCadrePeer re-reads the StampId, so a peer removed by another writer
650
+ // between the two reads no-ops silently yet still notifies. Narrow concurrent-removal
651
+ // window only — the common "already absent" case is caught here.
652
+ const stampId = await this.controlDatabase.queryCadrePeerStampId(peerId);
653
+ if (stampId === null) {
654
+ log('removePeer: no CadrePeer row for %s (already absent)', peerId);
655
+ return;
656
+ }
657
+
658
+ log('Removing peer: %s', peerId);
659
+
660
+ await this.controlDatabase.deleteCadrePeer(
661
+ peerId, ownerKey, message => this.signMessageBytes(message),
662
+ );
663
+
664
+ log('Peer %s removed successfully (stamp retired)', peerId);
665
+ }
666
+
667
+ /**
668
+ * Seat `ownerPublicKey` as a further owner, signed by this service's owner key. The
669
+ * liveness check, the stamp, the signature and the membership notify are
670
+ * {@link ControlDatabase.insertOwnerKeyVouched}'s; what stays here is the owner-key
671
+ * precondition, checked before any read (see {@link removePeer}).
672
+ *
673
+ * @returns `true` when the row was seated, `false` when the key is already a live owner.
674
+ */
675
+ async addOwner(ownerPublicKey: string): Promise<boolean> {
676
+ const ownerKey = this.requireOwnerPublicKey();
677
+ if (!this.controlDatabase) {
678
+ throw new Error('Control database not initialized');
679
+ }
680
+ return await this.controlDatabase.insertOwnerKeyVouched(
681
+ ownerPublicKey, ownerKey, message => this.signMessageBytes(message),
682
+ );
683
+ }
684
+
685
+ /**
686
+ * Remove `ownerPublicKey` from the owners, signed by this service's owner key: the delete
687
+ * and its `Revocation` tombstone in one transaction. The by-name refusals (self-removal,
688
+ * the last owner), the digests and the membership notify are
689
+ * {@link ControlDatabase.deleteOwnerKey}'s; what stays here is the owner-key precondition,
690
+ * checked before any read (see {@link removePeer}).
691
+ *
692
+ * @returns `true` when the row was removed, `false` when the key is not a live owner here.
693
+ */
694
+ async removeOwner(ownerPublicKey: string): Promise<boolean> {
695
+ const ownerKey = this.requireOwnerPublicKey();
696
+ if (!this.controlDatabase) {
697
+ throw new Error('Control database not initialized');
698
+ }
699
+ return await this.controlDatabase.deleteOwnerKey(
700
+ ownerPublicKey, ownerKey, message => this.signMessageBytes(message),
701
+ );
702
+ }
703
+
704
+ /**
705
+ * Re-vouch another owner's row under this service's owner key, so it stands on a remaining
706
+ * owner's signature before the owner that added it is removed
707
+ * ({@link ControlDatabase.revouchOwnerKey}; for `CadreNode.removeMachine` only). What stays
708
+ * here is the owner-key precondition, checked before any read (see {@link removePeer}).
709
+ *
710
+ * @returns `true` when the row was re-vouched, `false` when the key is not a live owner here.
711
+ */
712
+ async revouchOwner(ownerPublicKey: string): Promise<boolean> {
713
+ const ownerKey = this.requireOwnerPublicKey();
714
+ if (!this.controlDatabase) {
715
+ throw new Error('Control database not initialized');
716
+ }
717
+ return await this.controlDatabase.revouchOwnerKey(
718
+ ownerPublicKey, ownerKey, message => this.signMessageBytes(message),
719
+ );
720
+ }
721
+
722
+ /**
723
+ * Remove a machine completely, signed by this service's owner key: its `CadrePeer` row, its
724
+ * `OwnerKey` row when `target.ownerKey` names one, its `DeviceToken` row, and the
725
+ * withdrawal of every invitation in `target.inviteKeys`, all in one transaction
726
+ * ({@link ControlDatabase.removeMachine}). What stays here is the owner-key precondition,
727
+ * checked before any read (see {@link removePeer}).
728
+ */
729
+ async removeMachine(target: Parameters<ControlDatabase['removeMachine']>[0]): Promise<MachineRemovalWrites> {
730
+ const ownerKey = this.requireOwnerPublicKey();
731
+ if (!this.controlDatabase) {
732
+ throw new Error('Control database not initialized');
733
+ }
734
+ return await this.controlDatabase.removeMachine(
735
+ target, ownerKey, message => this.signMessageBytes(message),
736
+ );
737
+ }
738
+
739
+ /**
740
+ * Owner "re-touch" of an existing `CadrePeer` membership row: bump `UpdatedAt` and
741
+ * re-vouch the row so it is re-emitted as a fresh, broadcasting transaction. This is
742
+ * the write-while-alone re-replication primitive (`control-write-ensure-replicated`):
743
+ * a membership row that committed local-only (its block's cluster ≤1 at insert) is
744
+ * pushed to the cohort once it grows.
745
+ *
746
+ * The stamp read, the voucher signature, the write lock and the membership notify are
747
+ * {@link ControlDatabase.reauthorizeCadrePeer}'s — including the caveat that it rebinds
748
+ * `VouchOwner` to this node's owner key. What stays here is the owner-key precondition.
749
+ *
750
+ * A no-op (no throw, no notify) when the row does not exist.
751
+ *
752
+ * @param peerId - the membership row to re-touch.
753
+ * @param updatedAt - the strictly-increasing freshness stamp to write.
754
+ * @throws if no owner private key is configured (a non-owner cannot
755
+ * re-sign another peer's row) or the control database is not initialized.
756
+ */
757
+ async reauthorizePeer(peerId: string, updatedAt: number): Promise<void> {
758
+ // Fail fast on a keyless service before any DB read (see removePeer): a non-owner
759
+ // cannot re-sign the voucher, and must not silently no-op on an absent row.
760
+ const ownerKey = this.requireOwnerPublicKey();
761
+ if (!this.controlDatabase) {
762
+ throw new Error('Control database not initialized');
763
+ }
764
+ const retouched = await this.controlDatabase.reauthorizeCadrePeer(
765
+ peerId, updatedAt, ownerKey, message => this.signMessageBytes(message),
766
+ );
767
+ if (!retouched) {
768
+ log('reauthorizePeer: no CadrePeer row for %s (nothing to re-touch)', peerId);
769
+ return;
770
+ }
771
+ log('Peer %s re-authorized (UpdatedAt=%d) for write-while-alone re-replication', peerId, updatedAt);
772
+ }
773
+
774
+ /**
775
+ * Owner re-issue of a batch of `Revocation` tombstones: bump each row's
776
+ * `ReissuedAt` so the storage layer re-broadcasts a tombstone that committed
777
+ * while the node was alone. The delete-while-alone counterpart of
778
+ * {@link reauthorizePeer} — a removed row cannot be re-touched (it is gone),
779
+ * but its tombstone can, and every membership read treats a retired stamp as
780
+ * absent.
781
+ *
782
+ * The signatures, the single transaction, and the strictly-monotonic
783
+ * `reissuedAt` contract are {@link ControlDatabase.reissueRevocations}'s. What
784
+ * stays here is the owner-key precondition.
785
+ *
786
+ * @returns how many tombstones were re-issued (`rows.length` on success).
787
+ * @throws if no owner private key is configured or the control database is not
788
+ * initialized.
789
+ */
790
+ async reissueRevocations(rows: readonly RevocationRow[], reissuedAt: number): Promise<number> {
791
+ // Fail fast on a keyless service before any DB work (see removePeer): a
792
+ // non-owner cannot sign the reissue digests.
793
+ const ownerKey = this.requireOwnerPublicKey();
794
+ if (!this.controlDatabase) {
795
+ throw new Error('Control database not initialized');
796
+ }
797
+ return this.controlDatabase.reissueRevocations(
798
+ rows, reissuedAt, ownerKey, message => this.signMessageBytes(message),
799
+ );
800
+ }
801
+
802
+ /**
803
+ * Owner filing of the singleton `Revocation` ledger marker, so the table is never a
804
+ * never-written block that the storage layer re-consults on every read.
805
+ *
806
+ * The signature, the insert-if-absent guard and the `'already-open'` mapping are
807
+ * {@link ControlDatabase.openRevocationLedger}'s. What stays here is the owner-key
808
+ * precondition.
809
+ *
810
+ * @throws if no owner private key is configured or the control database is not
811
+ * initialized.
812
+ */
813
+ async openRevocationLedger(): Promise<RevocationLedgerOpenResult> {
814
+ // Fail fast on a keyless service before any DB work (see removePeer): a
815
+ // non-owner cannot sign the marker's append digest.
816
+ const ownerKey = this.requireOwnerPublicKey();
817
+ if (!this.controlDatabase) {
818
+ throw new Error('Control database not initialized');
819
+ }
820
+ return this.controlDatabase.openRevocationLedger(
821
+ ownerKey, message => this.signMessageBytes(message),
822
+ );
823
+ }
824
+
825
+ /**
826
+ * Owner-signed INSERT of a `CadreInvite` row — an invitation any member machine can redeem
827
+ * on this owner's behalf ({@link ControlDatabase.insertCadreInvite}). The keypair mint, the
828
+ * expiry and use-count defaults, and the bundle the holder receives are
829
+ * `CadreNode.createCadreInvitation`'s; what stays here is the owner-key precondition and
830
+ * the signature, as {@link insertSelfDeviceToken} keeps them for device tokens.
831
+ *
832
+ * @returns the row as stored, which the invitation bundle carries verbatim.
833
+ * @throws if no owner private key is configured or the control database is not initialized.
834
+ */
835
+ async insertCadreInvite(invite: Parameters<ControlDatabase['insertCadreInvite']>[0]): Promise<CadreInviteRow> {
836
+ // Fail fast on a keyless service before any DB work (see removePeer).
837
+ const ownerKey = this.requireOwnerPublicKey();
838
+ if (!this.controlDatabase) {
839
+ throw new Error('Control database not initialized');
840
+ }
841
+ return await this.controlDatabase.insertCadreInvite(invite, ownerKey, message => this.signMessageBytes(message));
842
+ }
843
+
844
+ /**
845
+ * Owner-signed WITHDRAWAL of a `CadreInvite`: the `Revocation` tombstone over its stamp, with
846
+ * the row kept ({@link ControlDatabase.withdrawCadreInvite}). What stays here is the
847
+ * owner-key precondition.
848
+ *
849
+ * @returns `true` when this call filed the tombstone, `false` when the row is absent here or
850
+ * already withdrawn.
851
+ * @throws if no owner private key is configured or the control database is not initialized.
852
+ */
853
+ async withdrawCadreInvite(key: string): Promise<boolean> {
854
+ const ownerKey = this.requireOwnerPublicKey();
855
+ if (!this.controlDatabase) {
856
+ throw new Error('Control database not initialized');
857
+ }
858
+ return await this.controlDatabase.withdrawCadreInvite(key, ownerKey, message => this.signMessageBytes(message));
859
+ }
860
+
861
+ /**
862
+ * Create a seed from the current control network state.
863
+ * The seed contains peer information and is signed by an owner.
864
+ */
865
+ async createSeed(): Promise<ControlNetworkSeed> {
866
+ if (!this.config.ownerPrivateKey || !this.ownerPublicKey) {
867
+ throw new Error('Owner key required to create seeds');
868
+ }
869
+
870
+ if (!this.controlDatabase || !this.libp2pNode) {
871
+ throw new Error('Service not initialized');
872
+ }
873
+
874
+ log('Creating seed for party: %s', this.config.partyId);
875
+
876
+ // Query all peers from the control database
877
+ const peers = await this.queryPeers();
878
+
879
+ // Create the seed data (without signature)
880
+ const seedData = {
881
+ partyId: this.config.partyId,
882
+ peers,
883
+ };
884
+
885
+ // Sign the seed over its canonical byte representation
886
+ const signature = sign(
887
+ seedDigest(seedData),
888
+ this.config.ownerPrivateKey,
889
+ 'ed25519',
890
+ 'base64url',
891
+ 'base64url',
892
+ 'base64url'
893
+ ) as string;
894
+
895
+ const seed: ControlNetworkSeed = {
896
+ ...seedData,
897
+ signature,
898
+ signerKey: this.ownerPublicKey,
899
+ };
900
+
901
+ log('Created seed with %d peers', peers.length);
902
+ return seed;
903
+ }
904
+
905
+ /**
906
+ * Apply a seed to populate the peer cache and enable connections.
907
+ *
908
+ * Validates the seed signature, then evaluates a trust anchor for the
909
+ * `signerKey` that does NOT come from the seed body: the receiver's
910
+ * node-local {@link SeedBootstrapConfig.trustedOwners} anchor, optionally
911
+ * augmented by pinned keys or TOFU via the configured/overriding
912
+ * `SeedTrustPolicy`. A forged self-asserting seed — one that merely lists its
913
+ * own signer as an owner peer — no longer passes, and neither does one signed
914
+ * by a key a stranger genesis-inserted into the replicated `OwnerKey` table.
915
+ *
916
+ * A key accepted via a pin/TOFU is persisted into the anchor (the policy says
917
+ * so via `SeedTrustDecision.anchorAs`), so the next seed from that owner is
918
+ * anchored without re-supplying the pin.
919
+ *
920
+ * @param seed - The seed to apply (already transport-decoded).
921
+ * @param options.trustPolicy - Per-call policy override (e.g. a
922
+ * `pinnedKeyTrustPolicy` built from an operator pin) used instead of the
923
+ * service-configured default for this seed only.
924
+ */
925
+ async applySeed(
926
+ seed: ControlNetworkSeed,
927
+ options?: { trustPolicy?: SeedTrustPolicy }
928
+ ): Promise<ApplySeedResult> {
929
+ const merged = await this.verifyAndMergeSeed(seed, options);
930
+ if (!merged.success) {
931
+ return merged;
932
+ }
933
+ return { ...merged, ...await this.dialSeedOwners(seed) };
934
+ }
935
+
936
+ /**
937
+ * The first half of {@link applySeed}: check the signature and the signer's trust, then merge
938
+ * the seed's peer addresses into the peer store. Every rejection happens here, so this result is
939
+ * what the inbound handler acks with; the owner dials that follow cannot change it.
940
+ */
941
+ private async verifyAndMergeSeed(
942
+ seed: ControlNetworkSeed,
943
+ options?: SeedApplyOptions
944
+ ): Promise<ApplySeedResult> {
945
+ if (!this.libp2pNode) {
946
+ return seedRejected('Service not initialized');
947
+ }
948
+
949
+ // NOTE: `seed.partyId` is never checked against `config.partyId`. Trust is keyed on
950
+ // `signerKey` vs the anchor, and the anchor a stray-party seed could write into
951
+ // belongs to THIS party, which only a caller-supplied pin for that signer can reach.
952
+ // The one reader of the seed's party is the claim policy, which records it as the
953
+ // party the node now serves (`CadreNodeConfig.claim.record`): a mismatch is still not
954
+ // rejected there because an unclaimed node's own party is a placeholder, and the
955
+ // claim seed is the first thing to name the real one. If any other path ever
956
+ // branches on the seed's partyId (or the anchor becomes multi-party), reject a
957
+ // mismatch here instead.
958
+ log('Applying seed for party: %s', seed.partyId);
959
+
960
+ // One digest serves the signature check and the trust context: a claim proof is
961
+ // bound to the seed through the same value the signature covers.
962
+ const digestB64 = seedDigest(seed);
963
+ if (!this.validateSeedSignature(seed, digestB64)) {
964
+ return seedRejected('Invalid seed signature');
965
+ }
966
+
967
+ // Evaluate the trust anchor for the signer key. The known-owner set comes
968
+ // from the receiver's NODE-LOCAL anchor — never from the seed itself, and
969
+ // never from the replicated OwnerKey table (a stranger can genesis-insert
970
+ // its own key there and let it replicate into every peer's copy). A node
971
+ // whose anchor was never seeded, with no policy override, sees an empty set
972
+ // and rejects.
973
+ const knownOwnerKeys = this.config.trustedOwners?.all() ?? new Set<string>();
974
+ const policy = options?.trustPolicy ?? this.trustPolicy;
975
+ const decision = await policy.evaluate({
976
+ partyId: seed.partyId,
977
+ signerKey: seed.signerKey,
978
+ knownOwnerKeys,
979
+ // Optional-chained like `dialSeedOwners`: partial libp2p handles (unit-test doubles)
980
+ // omit `peerId`. A real node always has one, and a proof bound to a real peer id can
981
+ // only fail against '' — the safe direction.
982
+ localPeerId: this.libp2pNode.peerId?.toString() ?? '',
983
+ seedDigest: digestB64,
984
+ claimProof: options?.claimProof,
985
+ remotePeerId: options?.remotePeerId,
986
+ });
987
+ if (!decision.trusted) {
988
+ return seedRejected(decision.reason ?? 'Signer key not trusted by trust policy', decision.code);
989
+ }
990
+ await this.anchorAcceptedSigner(seed.signerKey, decision);
991
+
992
+ const peersAdded = await mergeSeedPeers(this.libp2pNode, seed.peers);
993
+ log('Merged seed: %d peers added', peersAdded);
994
+ return { success: true, peersAdded, ownerDialsAttempted: 0, ownerDialsFailed: 0 };
995
+ }
996
+
997
+ /**
998
+ * The second half of {@link applySeed}: dial the seed's owner peers to establish connections.
999
+ *
1000
+ * Best-effort and COUNTED: an owner that is momentarily down leaves this node seeded but
1001
+ * unconnected, which the caller can only see if the outcome is reported (see
1002
+ * `ApplySeedResult.ownerDialsFailed`). Recovery is not this loop's job —
1003
+ * `CadreNode.dialColdStartBootstrap` retries these same addresses on every control-cohort
1004
+ * reconcile pass until the control database has siblings.
1005
+ *
1006
+ * The inbound handler runs this AFTER it has acked and closed the stream
1007
+ * ({@link handleSeedStream}), because an unreachable owner can take `dialBudget.totalMs`.
1008
+ */
1009
+ private async dialSeedOwners(seed: ControlNetworkSeed): Promise<OwnerDialCounts> {
1010
+ const node = this.libp2pNode;
1011
+ if (!node) {
1012
+ log('Seed service shut down before its owner dials; none attempted');
1013
+ return { ownerDialsAttempted: 0, ownerDialsFailed: 0 };
1014
+ }
1015
+ // `createSeed` projects every non-revoked CadrePeer row, so an owner applying
1016
+ // a seed minted after it joined finds ITSELF in the owner list. Dialing self always
1017
+ // throws, which would report a healthy owner as "seeded but stranded".
1018
+ // Optional-chained: partial libp2p handles (unit-test doubles) omit `peerId`,
1019
+ // and an undefined self simply matches nothing.
1020
+ // Every one of an owner's addresses is a candidate, each on its own time limit
1021
+ // (`dialPeerAddrs`), so an owner whose first address never answers neither
1022
+ // stalls seed application nor goes undialed at its other addresses. The seed's
1023
+ // addresses carry no peer id; the dial binds each to the owner's.
1024
+ const selfPeerId = node.peerId?.toString();
1025
+ let ownerDialsAttempted = 0;
1026
+ let ownerDialsFailed = 0;
1027
+ for (const peer of seed.peers.filter(p => p.isOwner)) {
1028
+ if (peer.multiaddrs.length === 0 || peer.peerId === selfPeerId) {
1029
+ continue;
1030
+ }
1031
+ ownerDialsAttempted++;
1032
+ try {
1033
+ const addrs = parseDialAddrs(peer.multiaddrs);
1034
+
1035
+ log('Dialing owner peer: %s (%d addr(s))', peer.peerId, addrs.length);
1036
+ await dialPeerAddrs(node, peer.peerId, addrs, this.dialBudget, `Owner dial of ${peer.peerId}`);
1037
+ } catch (error) {
1038
+ // Counted even when the owner reaches us only through our own relay: this node is still
1039
+ // not connected to it, and `ownerDialsFailed` is how the caller learns that.
1040
+ ownerDialsFailed++;
1041
+ if (error instanceof SelfRelayOnlyError) {
1042
+ log('Owner peer %s is reachable only by relaying through this node; waiting for it to reconnect', peer.peerId);
1043
+ } else {
1044
+ log('Failed to dial peer %s: %o', peer.peerId, error);
1045
+ }
1046
+ // Continue - not all peers need to be reachable
1047
+ }
1048
+ }
1049
+
1050
+ log('Dialed seed owners: %d/%d owner dial(s) failed', ownerDialsFailed, ownerDialsAttempted);
1051
+ return { ownerDialsAttempted, ownerDialsFailed };
1052
+ }
1053
+
1054
+ /**
1055
+ * Persist a signer that a pin/TOFU accepted into the node-local anchor, so a
1056
+ * later seed from the same owner is anchored without re-supplying the pin
1057
+ * or re-prompting. Only the policy decides this happens (`anchorAs` is unset
1058
+ * when the key was already anchored, so a plain re-apply writes nothing) and
1059
+ * `trust()` is idempotent, keeping the original provenance for a known key.
1060
+ *
1061
+ * Failure to PERSIST does not fail the seed: `trust()` reflects the key in the
1062
+ * in-memory anchor synchronously, so this seed and the rest of the session are
1063
+ * unaffected — only durability across a restart is lost, and that is logged.
1064
+ * That holds for pins and TOFU, which are re-supplied at the next start; a claim
1065
+ * is the opposite case, so `claimSecretTrustPolicy` anchors its signer itself,
1066
+ * awaits durability, and never sets `anchorAs` (the type excludes `'claim'`).
1067
+ *
1068
+ * NOTE: anchoring a key can flip `CadrePeer` rows ALREADY present from
1069
+ * unauthorized to authorized, which the write-driven membership-gate refresh
1070
+ * (`ControlDatabase.mutateCadrePeer`) cannot see — no row was written. The anchor
1071
+ * is mutated from two places: here, on seed application, where both seed paths
1072
+ * refresh the gate explicitly afterwards (`CadreNode.applySeed`, `onSeedApplied`);
1073
+ * and by the anchor sync (`CadreNode.syncOwnerAnchor`), which runs INSIDE the
1074
+ * membership refresh, ahead of the membership read, so its changes are judged by
1075
+ * the same pass. If some future path anchors an owner outside both, it owes the
1076
+ * same `CadreNode.refreshMembershipGate()` — or the anchor needs its own hub.
1077
+ */
1078
+ private async anchorAcceptedSigner(signerKey: string, decision: SeedTrustDecision): Promise<void> {
1079
+ if (!decision.anchorAs || !this.config.trustedOwners) {
1080
+ return;
1081
+ }
1082
+ try {
1083
+ await this.config.trustedOwners.trust(signerKey, decision.anchorAs);
1084
+ log('Anchored seed signer %s as %s', signerKey, decision.anchorAs);
1085
+ } catch (error) {
1086
+ log('Failed to persist accepted seed signer into the trusted-owner anchor: %o', error);
1087
+ }
1088
+ }
1089
+
1090
+ /**
1091
+ * Encode a seed for out-of-band delivery (e.g., QR code, copy/paste).
1092
+ */
1093
+ encodeSeed(seed: ControlNetworkSeed): string {
1094
+ const json = JSON.stringify(seed);
1095
+ return uint8ArrayToString(new TextEncoder().encode(json), 'base64url');
1096
+ }
1097
+
1098
+ /**
1099
+ * Decode a seed from base64url encoding.
1100
+ */
1101
+ decodeSeed(encoded: string): ControlNetworkSeed {
1102
+ const bytes = uint8ArrayFromString(encoded, 'base64url');
1103
+ const json = new TextDecoder().decode(bytes);
1104
+ return JSON.parse(json) as ControlNetworkSeed;
1105
+ }
1106
+
1107
+ /**
1108
+ * Deliver a seed directly to a peer via the /sereus/seed/1.0.0 protocol.
1109
+ *
1110
+ * `target` is a multiaddr string, dialed as given, or a peer id with its addresses
1111
+ * ({@link SeedDeliveryTarget}). For the second, the connection is formed first and on
1112
+ * its own limits ({@link connectForDelivery}): an open one is reused, otherwise each
1113
+ * address is dialed in turn, so one that never answers cannot use up the time a later
1114
+ * one needed. Its addresses are also merged into the peer store, so identify and later
1115
+ * dials see them. A peer id with no addresses is dialed by id, which reuses an open
1116
+ * connection or tries the peer store's addresses. `options.claimProof` rides beside
1117
+ * the seed in the message when the target is a brand-new node being claimed
1118
+ * (`claim-proof.ts`).
1119
+ *
1120
+ * Sender hardening: the request — opening the stream (with its dial, for the forms
1121
+ * that dial by `dialProtocol`), write, ack read — is bounded by {@link seedDeliverTimeoutMs},
1122
+ * and the ack is capped at {@link MAX_SEED_SIZE}. The target is a NOT-YET-TRUSTED node the
1123
+ * instigator chose to dial during onboarding, so an unbounded read here is strictly more
1124
+ * exposed than the membership-gated receiver paths: without the bound a target that accepts
1125
+ * the stream and never replies parks this call forever, and one that streams arbitrary bytes
1126
+ * as a fake ack exhausts memory. A peer id with addresses can therefore take up to
1127
+ * `dialBudget.totalMs` plus {@link seedDeliverTimeoutMs} (114.5 s at the default declared
1128
+ * link) when none of its addresses answers.
1129
+ *
1130
+ * @throws {PeerUnreachableError} for a peer id with addresses, when no connection to it
1131
+ * formed; nothing was sent. Anything else thrown after the connection formed means the
1132
+ * node was reached and the exchange failed.
1133
+ */
1134
+ async deliverSeed(
1135
+ target: SeedDeliveryTarget,
1136
+ seed: ControlNetworkSeed,
1137
+ options?: { claimProof?: string },
1138
+ ): Promise<SeedAckMessage> {
1139
+ if (!this.libp2pNode) {
1140
+ throw new Error('Service not initialized');
1141
+ }
1142
+ const label = typeof target === 'string' ? target : target.peerId;
1143
+ log('Delivering seed to: %s', label);
1144
+
1145
+ const openStream = await this.seedStreamOpener(this.libp2pNode, target);
1146
+ return await withDeadline(
1147
+ this.seedDeliverTimeoutMs,
1148
+ `Seed delivery to ${label}`,
1149
+ (signal) => this.sendSeed(openStream, seed, options?.claimProof, signal),
1150
+ );
1151
+ }
1152
+
1153
+ /**
1154
+ * The part of {@link deliverSeed} that runs before its deadline: how the delivery's stream
1155
+ * will be opened, with any connection it needs already formed.
1156
+ */
1157
+ private async seedStreamOpener(node: Libp2p, target: SeedDeliveryTarget): Promise<SeedStreamOpener> {
1158
+ if (typeof target === 'string') {
1159
+ const addr = multiaddr(target);
1160
+ // NOTE: this one-address form goes through libp2p's dial queue, which joins it to any dial
1161
+ // of the same peer in flight and then waits on that job's address, not this one. Nothing is
1162
+ // skipped (there is one address), only delayed; if a seed delivered to a bare multiaddr is
1163
+ // ever seen timing out while something else dials that peer, open it with `dialAddr`.
1164
+ return (signal) => node.dialProtocol(addr, SEED_PROTOCOL, { signal });
1165
+ }
1166
+ const peerId = peerIdFromString(target.peerId);
1167
+ const addrs = deliveryDialAddrs(target.peerId, target.multiaddrs);
1168
+ await mergeSeedPeers(node, [{ peerId: target.peerId, multiaddrs: target.multiaddrs, isOwner: false }]);
1169
+ if (addrs.length === 0) {
1170
+ return (signal) => node.dialProtocol(peerId, SEED_PROTOCOL, { signal });
1171
+ }
1172
+ const connection = await this.connectForDelivery(node, peerId, addrs);
1173
+ return (signal) => connection.newStream(SEED_PROTOCOL, { signal });
1174
+ }
1175
+
1176
+ /**
1177
+ * A connection to `peerId` for {@link deliverSeed}, from {@link dialPeerAddrs}: one already
1178
+ * open without relay limits, or one dialed from `addrs` — each address on
1179
+ * `dialBudget.perAddressMs`, the whole peer within `dialBudget.totalMs`, direct addresses
1180
+ * before relayed ones and the given order otherwise.
1181
+ *
1182
+ * @throws {PeerUnreachableError} when no connection formed, with the dial's error as `cause`.
1183
+ */
1184
+ private async connectForDelivery(node: Libp2p, peerId: PeerId, addrs: readonly Multiaddr[]): Promise<Connection> {
1185
+ // NOTE: a relayed address can return a limited connection, on which `sendSeed`'s stream
1186
+ // open then fails as a plain error rather than `PeerUnreachableError`, though nothing was
1187
+ // sent. Claim codes carry no relay addresses today; if a delivery target ever may, count a
1188
+ // limited connection as unreachable here.
1189
+ try {
1190
+ return await dialPeerAddrs(node, peerId.toString(), addrs, this.dialBudget, `Seed delivery dial of ${peerId}`);
1191
+ } catch (error) {
1192
+ throw new PeerUnreachableError(peerId.toString(), error);
1193
+ }
1194
+ }
1195
+
1196
+ /**
1197
+ * Open one stream to the target, send the seed frame, half-close, and read the ack.
1198
+ *
1199
+ * `signal` is the deadline from {@link deliverSeed}: it goes to `openStream` so a
1200
+ * timeout while dialing or opening the stream aborts it, and into {@link exchangeFrame}
1201
+ * so a timeout after the stream is open resets it — releasing the otherwise unbounded
1202
+ * ack-read.
1203
+ *
1204
+ * Deliberately NOT `runOnLimitedConnection`: a wake sets it because a wake is a
1205
+ * tiny frame over a relay, whereas a seed is up to 1MB, so a relayed address that
1206
+ * forms only a limited connection fails here when the stream is opened. Changing
1207
+ * that is a separate decision.
1208
+ */
1209
+ private async sendSeed(
1210
+ openStream: SeedStreamOpener,
1211
+ seed: ControlNetworkSeed,
1212
+ claimProof: string | undefined,
1213
+ signal: AbortSignal,
1214
+ ): Promise<SeedAckMessage> {
1215
+ const rawStream = await openStream(signal);
1216
+
1217
+ const message: SeedMessage = {
1218
+ partyId: seed.partyId,
1219
+ peers: seed.peers,
1220
+ signature: seed.signature,
1221
+ signerKey: seed.signerKey,
1222
+ ...(claimProof !== undefined ? { claimProof } : {}),
1223
+ };
1224
+
1225
+ const ack = await exchangeFrame(
1226
+ rawStream as unknown as ControlStream,
1227
+ signal,
1228
+ message,
1229
+ (stream) => this.readSeedAck(stream),
1230
+ 'Seed delivery aborted by timeout',
1231
+ );
1232
+
1233
+ log('Seed delivery response: accepted=%s', ack.accepted);
1234
+ return ack;
1235
+ }
1236
+
1237
+ /**
1238
+ * Read the ack frame a delivery target writes back, bounded by
1239
+ * {@link seedDeliverTimeoutMs} and capped at {@link MAX_SEED_SIZE} — an
1240
+ * untrusted target must not be able to stream unlimited bytes as a fake ack.
1241
+ * Decoding runs inside {@link exchangeFrame}'s `try`, so a malformed or
1242
+ * non-JSON ack resets the stream rather than leaking it.
1243
+ */
1244
+ private async readSeedAck(stream: ControlStream): Promise<SeedAckMessage> {
1245
+ const data = await readStreamToEnd(stream, {
1246
+ maxBytes: MAX_SEED_SIZE,
1247
+ timeoutMs: this.seedDeliverTimeoutMs,
1248
+ label: 'Seed ack',
1249
+ });
1250
+ const body = decodeLengthPrefixedFrame(data, MAX_SEED_SIZE);
1251
+ return JSON.parse(new TextDecoder().decode(body)) as SeedAckMessage;
1252
+ }
1253
+
1254
+ /**
1255
+ * Get this node's circuit relay address for inclusion in seeds.
1256
+ * Returns null if no relay address is available.
1257
+ */
1258
+ async getRelayAddress(): Promise<string | null> {
1259
+ if (!this.libp2pNode) {
1260
+ return null;
1261
+ }
1262
+
1263
+ const addrs = this.libp2pNode.getMultiaddrs();
1264
+
1265
+ // Find a circuit relay address
1266
+ const relayAddr = addrs.find(addr => addr.toString().includes('/p2p-circuit/'));
1267
+
1268
+ return relayAddr?.toString() ?? null;
1269
+ }
1270
+
1271
+ /**
1272
+ * Validate a seed's signature.
1273
+ *
1274
+ * @param digestB64 - The seed's {@link seedDigest}, when the caller already computed it
1275
+ * (`verifyAndMergeSeed` shares one digest between this check and the trust context).
1276
+ */
1277
+ validateSeedSignature(seed: ControlNetworkSeed, digestB64 = seedDigest(seed)): boolean {
1278
+ try {
1279
+ // The digest is over the shared canonical payload, so verification is
1280
+ // independent of key order; the payload is the fixed `{ partyId, peers }`
1281
+ // the producer emits.
1282
+ return verify(
1283
+ digestB64,
1284
+ seed.signature,
1285
+ seed.signerKey,
1286
+ 'ed25519',
1287
+ 'base64url',
1288
+ 'base64url',
1289
+ 'base64url'
1290
+ );
1291
+ } catch (error) {
1292
+ log('Seed signature validation failed: %o', error);
1293
+ return false;
1294
+ }
1295
+ }
1296
+
1297
+ /**
1298
+ * The peers a seed carries: the control database's own projection
1299
+ * ({@link ControlDatabase.querySeedPeers}, shared with the cadre invitation redemption
1300
+ * reply), which reads through the revocation filter and flags owners from the replicated
1301
+ * `OwnerKey` table — a dial hint, not a trust decision (the NOTE at `projectSeedPeers`).
1302
+ */
1303
+ private async queryPeers(): Promise<SeedPeer[]> {
1304
+ if (!this.controlDatabase) {
1305
+ return [];
1306
+ }
1307
+ return await this.controlDatabase.querySeedPeers();
1308
+ }
1309
+
1310
+ /**
1311
+ * Register the seed protocol handler. The inbound closure just delegates to
1312
+ * {@link handleSeedStream} — extracted as a method so it has a unit-test seam
1313
+ * (mirroring wake's `handleStream`) the inline closure never had.
1314
+ */
1315
+ private async registerProtocolHandler(libp2pNode: Libp2p): Promise<void> {
1316
+ await libp2pNode.handle(SEED_PROTOCOL, async (rawStream: unknown, rawConnection: unknown) => {
1317
+ const remotePeerId = (rawConnection as Connection).remotePeer.toString();
1318
+ await this.handleSeedStream(rawStream as ControlStream, remotePeerId);
1319
+ });
1320
+
1321
+ log('Registered seed protocol handler: %s', SEED_PROTOCOL);
1322
+ }
1323
+
1324
+ /**
1325
+ * Read one inbound seed frame, verify and merge it, write the ack and close the
1326
+ * stream, then dial the seed's owners.
1327
+ *
1328
+ * The ack and the close come BEFORE the owner dials: an unreachable owner can hold
1329
+ * a dial for `dialBudget.totalMs` (86 s at the default declared link), which is not
1330
+ * link time and does not belong inside the sender's delivery deadline. The close is
1331
+ * what releases the sender, which reads the ack to end-of-stream. The stream stays
1332
+ * counted in {@link activeStreams} through the dials, so {@link maxConcurrentSeeds}
1333
+ * still bounds concurrent owner-dial phases.
1334
+ *
1335
+ * Hardened against a buggy/compromised own-cadre node: a concurrency cap (over
1336
+ * {@link maxConcurrentSeeds}, reply without applying), a read timeout (a peer
1337
+ * that never half-closes is aborted inside `readStreamToEnd`), and the existing
1338
+ * malformed/oversized-frame guard — all reported as a non-accepting
1339
+ * {@link SeedAckMessage} rather than a dropped/hung stream.
1340
+ *
1341
+ * NOTE: a receiver configured with an interactive trust-on-first-use policy asks a
1342
+ * human before acking, and that wait sits inside the sender's delivery deadline. If
1343
+ * TOFU is ever used on this wire path, ack "pending" or move the confirmation out of
1344
+ * the exchange.
1345
+ */
1346
+ private async handleSeedStream(stream: ControlStream, remotePeerId: string): Promise<void> {
1347
+ log('Incoming seed delivery from: %s', remotePeerId);
1348
+
1349
+ if (this.activeStreams >= this.maxConcurrentSeeds) {
1350
+ log('Rejecting seed from %s: %d concurrent streams at cap %d', remotePeerId, this.activeStreams, this.maxConcurrentSeeds);
1351
+ await replyAndClose(stream, { accepted: false, reason: 'Too many concurrent seed deliveries' } satisfies SeedAckMessage, 'Seed');
1352
+ return;
1353
+ }
1354
+
1355
+ this.activeStreams++;
1356
+ let acked = false;
1357
+ try {
1358
+ const { seed, claimProof } = await this.readSeedFrame(stream);
1359
+ this.eventCallbacks.onSeedReceived?.(seed.partyId, remotePeerId);
1360
+
1361
+ const merged = await this.verifyAndMergeSeed(seed, { claimProof, remotePeerId });
1362
+ acked = true;
1363
+ await replyAndClose(
1364
+ stream,
1365
+ { accepted: merged.success, reason: merged.error, code: merged.code } satisfies SeedAckMessage,
1366
+ 'Seed',
1367
+ );
1368
+
1369
+ if (merged.success) {
1370
+ await this.dialSeedOwners(seed);
1371
+ this.eventCallbacks.onSeedApplied?.(seed.partyId, merged.peersAdded, seed);
1372
+ } else {
1373
+ this.eventCallbacks.onSeedError?.(seed.partyId, merged.error ?? 'Unknown error');
1374
+ }
1375
+ } catch (error) {
1376
+ log('Error handling seed delivery: %o', error);
1377
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
1378
+ this.eventCallbacks.onSeedError?.(this.config.partyId, errorMessage);
1379
+ // Once acked the stream is closed, so a later failure has no reply to make.
1380
+ if (!acked) {
1381
+ await replyAndClose(stream, { accepted: false, reason: errorMessage } satisfies SeedAckMessage, 'Seed');
1382
+ }
1383
+ } finally {
1384
+ this.activeStreams--;
1385
+ }
1386
+ }
1387
+
1388
+ /**
1389
+ * Read the inbound seed frame to EOF (bounded and size-capped) and decode it. The
1390
+ * claim proof comes back beside the seed: it is not part of what the owner signed, so
1391
+ * `ControlNetworkSeed` does not carry it.
1392
+ */
1393
+ private async readSeedFrame(stream: ControlStream): Promise<{ seed: ControlNetworkSeed; claimProof?: string }> {
1394
+ const data = await readStreamToEnd(stream, {
1395
+ maxBytes: MAX_SEED_SIZE,
1396
+ timeoutMs: this.seedReadTimeoutMs,
1397
+ label: 'Seed',
1398
+ });
1399
+ const message = JSON.parse(new TextDecoder().decode(decodeLengthPrefixedFrame(data))) as SeedMessage;
1400
+ return {
1401
+ seed: {
1402
+ partyId: message.partyId,
1403
+ peers: message.peers,
1404
+ signature: message.signature,
1405
+ signerKey: message.signerKey,
1406
+ },
1407
+ claimProof: message.claimProof,
1408
+ };
1409
+ }
1410
+
1411
+ /**
1412
+ * Shutdown the service.
1413
+ */
1414
+ async shutdown(): Promise<void> {
1415
+ if (this.libp2pNode) {
1416
+ await this.libp2pNode.unhandle(SEED_PROTOCOL);
1417
+ }
1418
+ this.libp2pNode = null;
1419
+ this.controlDatabase = null;
1420
+ log('SeedBootstrapService shutdown');
1421
+ }
1422
+
1423
+ // ============================================================================
1424
+ // Helper Functions for Common Scenarios
1425
+ // ============================================================================
1426
+
1427
+ /**
1428
+ * Add a drone to the cadre (phone/server adds provider-hosted node).
1429
+ *
1430
+ * Use this when you've spawned a drone via provider API and received its
1431
+ * peer ID and multiaddrs. This method:
1432
+ * 1. Authorizes the drone peer
1433
+ * 2. Creates a seed including all current peers
1434
+ * 3. Returns the seed for sending to provider API
1435
+ *
1436
+ * Nothing here dials the drone or remembers its addresses beyond the unsigned
1437
+ * `CadrePeer` row, which no resolver accepts. `CadreNode.addDrone` is the entry
1438
+ * point that also retains them as a durable dial target, so the adder's
1439
+ * reconcile pass can open the connection — the drone cannot dial an owner that
1440
+ * does not listen. Call `CadreNode.reconcileControlCohort()` after delivering
1441
+ * the seed to dial at once.
1442
+ *
1443
+ * @param options - Drone peer info from provider API
1444
+ * @returns Seed and encoded seed for drone initialization
1445
+ */
1446
+ async addDrone(options: AddDroneOptions): Promise<DroneInitResult> {
1447
+ const { dronePeerId, droneMultiaddrs } = options;
1448
+
1449
+ log('Adding drone: %s', dronePeerId);
1450
+
1451
+ // 1. Authorize the new drone peer
1452
+ await this.authorizePeer({ peerId: dronePeerId, multiaddrs: droneMultiaddrs });
1453
+
1454
+ // 2. Create seed with current state
1455
+ const seed = await this.createSeed();
1456
+
1457
+ // 3. Encode for transport
1458
+ const encodedSeed = this.encodeSeed(seed);
1459
+
1460
+ log('Drone %s added, seed created with %d peers', dronePeerId, seed.peers.length);
1461
+
1462
+ return { seed, encodedSeed };
1463
+ }
1464
+
1465
+ /**
1466
+ * Add a phone to the cadre with relay support.
1467
+ *
1468
+ * Use this when both nodes are NAT'd (phone-to-phone). This method:
1469
+ * 1. Authorizes the new phone peer
1470
+ * 2. Creates a seed with relay addresses for dialing
1471
+ *
1472
+ * @param phonePeerId - Peer ID of the new phone
1473
+ * @returns Seed with relay addresses for out-of-band delivery
1474
+ */
1475
+ async addPhoneWithRelay(phonePeerId: string): Promise<DroneInitResult> {
1476
+ log('Adding phone with relay: %s', phonePeerId);
1477
+
1478
+ // 1. Authorize the new phone peer (no multiaddrs - NAT'd)
1479
+ await this.authorizePeer({ peerId: phonePeerId });
1480
+
1481
+ // 2. Get relay address for this node
1482
+ const relayAddr = await this.getRelayAddress();
1483
+
1484
+ // 3. Create seed - will include our relay address if available
1485
+ const seed = await this.createSeed();
1486
+
1487
+ // If we have a relay address, make sure it's in our peer entry
1488
+ if (relayAddr && this.libp2pNode) {
1489
+ const ourPeerId = this.libp2pNode.peerId.toString();
1490
+ const ourPeer = seed.peers.find(p => p.peerId === ourPeerId);
1491
+ if (ourPeer && !ourPeer.multiaddrs.includes(relayAddr)) {
1492
+ ourPeer.multiaddrs.push(relayAddr);
1493
+ }
1494
+ }
1495
+
1496
+ const encodedSeed = this.encodeSeed(seed);
1497
+
1498
+ log('Phone %s added with relay, seed created', phonePeerId);
1499
+
1500
+ return { seed, encodedSeed };
1501
+ }
1502
+ }