@serfab/cadre-core 0.7.1 → 0.8.1

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 (166) hide show
  1. package/README.md +9 -8
  2. package/dist/authority-key.d.ts +41 -0
  3. package/dist/authority-key.js +52 -0
  4. package/dist/authority-key.js.map +1 -0
  5. package/dist/cadre-node.d.ts +770 -11
  6. package/dist/cadre-node.js +1900 -88
  7. package/dist/cadre-node.js.map +1 -1
  8. package/dist/canonical-datetime.d.ts +33 -0
  9. package/dist/canonical-datetime.js +38 -0
  10. package/dist/canonical-datetime.js.map +1 -0
  11. package/dist/canonical-json.d.ts +12 -0
  12. package/dist/canonical-json.js +33 -0
  13. package/dist/canonical-json.js.map +1 -0
  14. package/dist/control-cohort.d.ts +63 -0
  15. package/dist/control-cohort.js +80 -0
  16. package/dist/control-cohort.js.map +1 -0
  17. package/dist/control-database.d.ts +259 -5
  18. package/dist/control-database.js +541 -128
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +89 -0
  21. package/dist/control-formation-recorder.js +139 -0
  22. package/dist/control-formation-recorder.js.map +1 -0
  23. package/dist/control-schema.d.ts +12 -0
  24. package/dist/control-schema.js +199 -0
  25. package/dist/control-schema.js.map +1 -0
  26. package/dist/control-stream.d.ts +54 -0
  27. package/dist/control-stream.js +104 -0
  28. package/dist/control-stream.js.map +1 -0
  29. package/dist/device-token.d.ts +50 -0
  30. package/dist/device-token.js +66 -0
  31. package/dist/device-token.js.map +1 -0
  32. package/dist/diagnostics/connection-path.d.ts +118 -0
  33. package/dist/diagnostics/connection-path.js +204 -0
  34. package/dist/diagnostics/connection-path.js.map +1 -0
  35. package/dist/diagnostics/webrtc-turn-tracker.d.ts +50 -0
  36. package/dist/diagnostics/webrtc-turn-tracker.js +196 -0
  37. package/dist/diagnostics/webrtc-turn-tracker.js.map +1 -0
  38. package/dist/hibernation-manager.d.ts +79 -0
  39. package/dist/hibernation-manager.js +173 -23
  40. package/dist/hibernation-manager.js.map +1 -1
  41. package/dist/index.d.ts +25 -4
  42. package/dist/index.js +59 -4
  43. package/dist/index.js.map +1 -1
  44. package/dist/key-store-file.d.ts +52 -0
  45. package/dist/key-store-file.js +194 -0
  46. package/dist/key-store-file.js.map +1 -0
  47. package/dist/key-store.d.ts +75 -0
  48. package/dist/key-store.js +66 -0
  49. package/dist/key-store.js.map +1 -0
  50. package/dist/peer-authorization.d.ts +26 -0
  51. package/dist/peer-authorization.js +40 -0
  52. package/dist/peer-authorization.js.map +1 -0
  53. package/dist/peer-record.d.ts +89 -0
  54. package/dist/peer-record.js +117 -0
  55. package/dist/peer-record.js.map +1 -0
  56. package/dist/push-credentials.d.ts +34 -0
  57. package/dist/push-credentials.js +81 -0
  58. package/dist/push-credentials.js.map +1 -0
  59. package/dist/push-fanout.d.ts +137 -0
  60. package/dist/push-fanout.js +197 -0
  61. package/dist/push-fanout.js.map +1 -0
  62. package/dist/push-notifier-apns.d.ts +53 -0
  63. package/dist/push-notifier-apns.js +195 -0
  64. package/dist/push-notifier-apns.js.map +1 -0
  65. package/dist/push-notifier-fcm.d.ts +38 -0
  66. package/dist/push-notifier-fcm.js +183 -0
  67. package/dist/push-notifier-fcm.js.map +1 -0
  68. package/dist/push-notifier-shared.d.ts +18 -0
  69. package/dist/push-notifier-shared.js +25 -0
  70. package/dist/push-notifier-shared.js.map +1 -0
  71. package/dist/push-notifier.d.ts +71 -0
  72. package/dist/push-notifier.js +50 -0
  73. package/dist/push-notifier.js.map +1 -0
  74. package/dist/schema-verification.d.ts +11 -2
  75. package/dist/schema-verification.js +15 -4
  76. package/dist/schema-verification.js.map +1 -1
  77. package/dist/seed-bootstrap.d.ts +197 -9
  78. package/dist/seed-bootstrap.js +396 -137
  79. package/dist/seed-bootstrap.js.map +1 -1
  80. package/dist/seed-trust-policy.d.ts +63 -0
  81. package/dist/seed-trust-policy.js +56 -0
  82. package/dist/seed-trust-policy.js.map +1 -0
  83. package/dist/strand-addr-protocol.d.ts +132 -0
  84. package/dist/strand-addr-protocol.js +313 -0
  85. package/dist/strand-addr-protocol.js.map +1 -0
  86. package/dist/strand-cohort.d.ts +54 -0
  87. package/dist/strand-cohort.js +38 -0
  88. package/dist/strand-cohort.js.map +1 -0
  89. package/dist/strand-database.d.ts +54 -6
  90. package/dist/strand-database.js +88 -100
  91. package/dist/strand-database.js.map +1 -1
  92. package/dist/strand-formation-manager.d.ts +79 -19
  93. package/dist/strand-formation-manager.js +196 -104
  94. package/dist/strand-formation-manager.js.map +1 -1
  95. package/dist/strand-formation-protocol.d.ts +162 -0
  96. package/dist/strand-formation-protocol.js +279 -0
  97. package/dist/strand-formation-protocol.js.map +1 -0
  98. package/dist/strand-instance-manager.d.ts +73 -4
  99. package/dist/strand-instance-manager.js +167 -41
  100. package/dist/strand-instance-manager.js.map +1 -1
  101. package/dist/strand-member-key.d.ts +29 -0
  102. package/dist/strand-member-key.js +38 -0
  103. package/dist/strand-member-key.js.map +1 -0
  104. package/dist/strand-member-registry.d.ts +98 -0
  105. package/dist/strand-member-registry.js +129 -0
  106. package/dist/strand-member-registry.js.map +1 -0
  107. package/dist/strand-membership-writer.d.ts +361 -0
  108. package/dist/strand-membership-writer.js +449 -0
  109. package/dist/strand-membership-writer.js.map +1 -0
  110. package/dist/strand-solicitation.d.ts +77 -2
  111. package/dist/strand-solicitation.js +25 -4
  112. package/dist/strand-solicitation.js.map +1 -1
  113. package/dist/strand-wake-payload.d.ts +30 -0
  114. package/dist/strand-wake-payload.js +20 -0
  115. package/dist/strand-wake-payload.js.map +1 -0
  116. package/dist/strand-wake-protocol.d.ts +114 -0
  117. package/dist/strand-wake-protocol.js +257 -0
  118. package/dist/strand-wake-protocol.js.map +1 -0
  119. package/dist/strand-watcher.d.ts +6 -2
  120. package/dist/strand-watcher.js +57 -17
  121. package/dist/strand-watcher.js.map +1 -1
  122. package/dist/types.d.ts +406 -23
  123. package/dist/types.js +22 -5
  124. package/dist/types.js.map +1 -1
  125. package/package.json +14 -8
  126. package/src/authority-key.ts +68 -0
  127. package/src/cadre-node.ts +2937 -948
  128. package/src/canonical-datetime.ts +39 -0
  129. package/src/canonical-json.ts +30 -0
  130. package/src/control-cohort.ts +103 -0
  131. package/src/control-database.ts +931 -383
  132. package/src/control-formation-recorder.ts +151 -0
  133. package/src/control-schema.ts +198 -0
  134. package/src/control-stream.ts +128 -0
  135. package/src/device-token.ts +89 -0
  136. package/src/diagnostics/connection-path.ts +277 -0
  137. package/src/diagnostics/webrtc-turn-tracker.ts +222 -0
  138. package/src/hibernation-manager.ts +197 -28
  139. package/src/index.ts +273 -79
  140. package/src/key-store-file.ts +203 -0
  141. package/src/key-store.ts +99 -0
  142. package/src/peer-authorization.ts +53 -0
  143. package/src/peer-record.ts +146 -0
  144. package/src/push-credentials.ts +84 -0
  145. package/src/push-fanout.ts +272 -0
  146. package/src/push-notifier-apns.ts +243 -0
  147. package/src/push-notifier-fcm.ts +221 -0
  148. package/src/push-notifier-shared.ts +28 -0
  149. package/src/push-notifier.ts +93 -0
  150. package/src/schema-verification.ts +18 -4
  151. package/src/seed-bootstrap.ts +464 -188
  152. package/src/seed-trust-policy.ts +107 -0
  153. package/src/strand-addr-protocol.ts +410 -0
  154. package/src/strand-cohort.ts +77 -0
  155. package/src/strand-database.ts +113 -141
  156. package/src/strand-formation-manager.ts +233 -142
  157. package/src/strand-formation-protocol.ts +391 -0
  158. package/src/strand-instance-manager.ts +207 -56
  159. package/src/strand-member-key.ts +39 -0
  160. package/src/strand-member-registry.ts +177 -0
  161. package/src/strand-membership-writer.ts +640 -0
  162. package/src/strand-solicitation.ts +93 -4
  163. package/src/strand-wake-payload.ts +32 -0
  164. package/src/strand-wake-protocol.ts +331 -0
  165. package/src/strand-watcher.ts +61 -17
  166. package/src/types.ts +1012 -582
package/src/cadre-node.ts CHANGED
@@ -1,948 +1,2937 @@
1
- import debug from 'debug';
2
- import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
3
- import type { Libp2p, PeerId } from '@libp2p/interface';
4
- import { createLibp2pNode } from '@optimystic/db-p2p';
5
- import type { IRepo } from '@optimystic/db-core';
6
- import type {
7
- CadreNodeConfig,
8
- StrandInstance,
9
- StrandRow,
10
- StrandConfig,
11
- SAppConfig,
12
- CadreNodeEvents,
13
- ControlNetworkSeed,
14
- ApplySeedResult,
15
- AddDroneOptions,
16
- AddPhoneOptions,
17
- DroneInitResult,
18
- InviteResult,
19
- CadreInvite,
20
- OpenInvitation,
21
- FormStrandResult,
22
- StrandFormationDisclosure
23
- } from './types.js';
24
- import { StrandWatcher, type StrandQueryable, type SAppIdLookup } from './strand-watcher.js';
25
- import { StrandInstanceManager } from './strand-instance-manager.js';
26
- import { EnrollmentService } from './enrollment.js';
27
- import { HibernationManager, type HibernationCallbacks } from './hibernation-manager.js';
28
- import { ControlDatabase } from './control-database.js';
29
- import { SeedBootstrapService } from './seed-bootstrap.js';
30
- import {
31
- StrandSolicitationService,
32
- type StrandSolicitationServiceOptions
33
- } from './strand-solicitation.js';
34
-
35
- const log = debug('sereus:cadre:node');
36
- const timing = debug('sereus:cadre:timing');
37
-
38
- type EventHandler<T> = (data: T) => void;
39
-
40
- /**
41
- * CadreNode is the main entry point for a cadre member.
42
- * It manages:
43
- * - Connection to the control network
44
- * - Watching for strand changes
45
- * - Starting/stopping strand instances
46
- * - Strand hibernation lifecycle
47
- * - Peer enrollment
48
- */
49
- export class CadreNode implements SAppIdLookup {
50
- private readonly config: CadreNodeConfig;
51
- private controlNode: Libp2p | null = null;
52
- private controlDatabase: ControlDatabase | null = null;
53
- private strandWatcher: StrandWatcher | null = null;
54
- private strandManager: StrandInstanceManager;
55
- private hibernationManager: HibernationManager;
56
- private enrollmentService: EnrollmentService;
57
- private seedBootstrapService: SeedBootstrapService | null = null;
58
- private strandSolicitationService: StrandSolicitationService | null = null;
59
- private running = false;
60
- private eventHandlers: Map<keyof CadreNodeEvents, Set<EventHandler<any>>> = new Map();
61
-
62
- /** Map of strandId -> sAppConfig for sAppId filtering and management */
63
- private sAppConfigs: Map<string, SAppConfig> = new Map();
64
-
65
- constructor(config: CadreNodeConfig) {
66
- this.config = config;
67
- this.strandManager = new StrandInstanceManager();
68
- this.enrollmentService = new EnrollmentService();
69
-
70
- // Create hibernation manager with callbacks
71
- const hibernationCallbacks: HibernationCallbacks = {
72
- onIdle: async (strandId) => this.handleStrandIdle(strandId),
73
- onHibernate: async (strandId) => this.handleStrandHibernate(strandId),
74
- onWake: async (strandId) => this.handleStrandWake(strandId)
75
- };
76
- this.hibernationManager = new HibernationManager(
77
- config.hibernation ?? { enabled: false },
78
- hibernationCallbacks
79
- );
80
-
81
- log('CadreNode created for party: %s', config.controlNetwork.partyId);
82
- }
83
-
84
- /**
85
- * SAppIdLookup implementation - get sAppId for a strand
86
- */
87
- getSAppId(strandId: string): string | undefined {
88
- return this.sAppConfigs.get(strandId)?.id;
89
- }
90
-
91
- /**
92
- * Get the peer ID of this node (available after start)
93
- */
94
- get peerId(): PeerId | undefined {
95
- return this.controlNode?.peerId;
96
- }
97
-
98
- /**
99
- * Get the multiaddrs of this node (available after start)
100
- */
101
- getMultiaddrs(): string[] {
102
- if (!this.controlNode) return [];
103
- return this.controlNode.getMultiaddrs().map(ma => ma.toString());
104
- }
105
-
106
- /**
107
- * Check if the node is running
108
- */
109
- get isRunning(): boolean {
110
- return this.running;
111
- }
112
-
113
- /**
114
- * Get all strand instances
115
- */
116
- getStrands(): Map<string, StrandInstance> {
117
- return this.strandManager.getInstances();
118
- }
119
-
120
- /**
121
- * Get a specific strand instance
122
- */
123
- getStrand(strandId: string): StrandInstance | undefined {
124
- return this.strandManager.getInstance(strandId);
125
- }
126
-
127
- /**
128
- * Get the enrollment service for adding new peers
129
- */
130
- getEnrollmentService(): EnrollmentService {
131
- return this.enrollmentService;
132
- }
133
-
134
- /**
135
- * Start the cadre node
136
- */
137
- async start(): Promise<void> {
138
- if (this.running) {
139
- log('CadreNode already running');
140
- return;
141
- }
142
-
143
- log('Starting CadreNode for party: %s', this.config.controlNetwork.partyId);
144
-
145
- try {
146
- const tTotal = performance.now();
147
-
148
- // Create the control network libp2p node
149
- let t0 = performance.now();
150
- this.controlNode = await this.createControlNode();
151
- timing('[start] createControlNode: %dms', Math.round(performance.now() - t0));
152
- log('Control node started with ID: %s', this.controlNode.peerId.toString());
153
-
154
- // Extract coordinatedRepo from the node (attached by createLibp2pNode)
155
- const coordinatedRepo = (this.controlNode as any).coordinatedRepo as IRepo;
156
- if (!coordinatedRepo) {
157
- throw new Error('coordinatedRepo not available on control node');
158
- }
159
-
160
- // Initialize the control database with the libp2p node
161
- t0 = performance.now();
162
- this.controlDatabase = new ControlDatabase({
163
- partyId: this.config.controlNetwork.partyId,
164
- libp2pNode: this.controlNode,
165
- coordinatedRepo,
166
- schemaPath: this.config.controlNetwork.schemaPath,
167
- });
168
- await this.controlDatabase.initialize();
169
- timing('[start] controlDatabase.initialize: %dms', Math.round(performance.now() - t0));
170
- log('Control database initialized');
171
-
172
- // Create strand queryable using the control database
173
- const queryable = this.createStrandQueryable();
174
-
175
- // Create and start the strand watcher with sAppId lookup
176
- this.strandWatcher = new StrandWatcher(
177
- queryable,
178
- {
179
- onStrandAdded: async (strand) => this.handleStrandAdded(strand),
180
- onStrandRemoved: async (strandId) => this.handleStrandRemoved(strandId)
181
- },
182
- this.config.strandFilter ?? { mode: 'all' },
183
- this.config.strandWatchInterval ?? 5000,
184
- this // CadreNode implements SAppIdLookup
185
- );
186
-
187
- t0 = performance.now();
188
- await this.strandWatcher.start();
189
- timing('[start] strandWatcher.start: %dms', Math.round(performance.now() - t0));
190
-
191
- // Start hibernation manager
192
- this.hibernationManager.start();
193
-
194
- this.running = true;
195
- this.emit('control:connected', undefined);
196
- timing('[start] total: %dms', Math.round(performance.now() - tTotal));
197
- log('CadreNode started successfully');
198
-
199
- // Schedule self-registration in background
200
- this.scheduleSelfRegistration();
201
-
202
- } catch (error) {
203
- log('Failed to start CadreNode: %o', error);
204
- await this.cleanup();
205
- throw error;
206
- }
207
- }
208
-
209
- /**
210
- * Stop the cadre node
211
- */
212
- async stop(): Promise<void> {
213
- if (!this.running) {
214
- log('CadreNode not running');
215
- return;
216
- }
217
-
218
- log('Stopping CadreNode');
219
- await this.cleanup();
220
- this.running = false;
221
- this.emit('control:disconnected', undefined);
222
- log('CadreNode stopped');
223
- }
224
-
225
- /**
226
- * Subscribe to events
227
- */
228
- on<K extends keyof CadreNodeEvents>(
229
- event: K,
230
- handler: EventHandler<CadreNodeEvents[K]>
231
- ): void {
232
- if (!this.eventHandlers.has(event)) {
233
- this.eventHandlers.set(event, new Set());
234
- }
235
- this.eventHandlers.get(event)!.add(handler);
236
- }
237
-
238
- /**
239
- * Unsubscribe from events
240
- */
241
- off<K extends keyof CadreNodeEvents>(
242
- event: K,
243
- handler: EventHandler<CadreNodeEvents[K]>
244
- ): void {
245
- this.eventHandlers.get(event)?.delete(handler);
246
- }
247
-
248
- private emit<K extends keyof CadreNodeEvents>(
249
- event: K,
250
- data: CadreNodeEvents[K]
251
- ): void {
252
- this.eventHandlers.get(event)?.forEach(handler => {
253
- try { handler(data); } catch (e) { log('Event handler error: %o', e); }
254
- });
255
- }
256
-
257
- private async createControlNode(): Promise<Libp2p> {
258
- const { controlNetwork, network, storage, profile, privateKey } = this.config;
259
-
260
- // Determine relay mode: if explicitly set in config, use that;
261
- // otherwise default to true for storage profile nodes (better connectivity/uptime)
262
- const enableRelay = network?.enableRelay ?? (profile === 'storage');
263
-
264
- // Create storage provider for control network
265
- // Uses the factory function pattern if provided to create control-network-specific storage
266
- const controlStorageProvider = storage?.provider
267
- ? (typeof storage.provider === 'function'
268
- ? storage.provider('control')
269
- : storage.provider)
270
- : undefined;
271
-
272
- const nodeOptions: Parameters<typeof createLibp2pNode>[0] = {
273
- port: 0,
274
- bootstrapNodes: controlNetwork.bootstrapNodes,
275
- networkName: `control-${controlNetwork.partyId}`,
276
- storage: controlStorageProvider,
277
- fretProfile: profile === 'storage' ? 'core' : 'edge',
278
- relay: enableRelay,
279
- clusterSize: 3,
280
- clusterPolicy: { allowDownsize: true, sizeTolerance: 0.5 },
281
- arachnode: { enableRingZulu: this.config.profile === 'storage' },
282
- ...(privateKey && { privateKey }),
283
- ...(network?.transports && { transports: network.transports }),
284
- ...(network?.listenAddrs && { listenAddrs: network.listenAddrs })
285
- };
286
-
287
- return await createLibp2pNode(nodeOptions);
288
- }
289
-
290
- private createStrandQueryable(): StrandQueryable {
291
- return {
292
- queryStrands: async (): Promise<StrandRow[]> => {
293
- if (!this.controlDatabase) {
294
- log('Control database not initialized, returning empty strands');
295
- return [];
296
- }
297
- log('Querying strands from control database');
298
- return await this.controlDatabase.queryStrands();
299
- }
300
- };
301
- }
302
-
303
- /**
304
- * Schedule self-registration in the CadrePeer table.
305
- * This runs as a background task after the node is started.
306
- */
307
- private scheduleSelfRegistration(): void {
308
- // Run in background - don't block start()
309
- setTimeout(async () => {
310
- try {
311
- await this.registerSelf();
312
- } catch (error) {
313
- log('Self-registration failed: %o', error);
314
- // Don't emit error event - this is a background task
315
- // The node can still function without self-registration
316
- }
317
- }, 1000); // Small delay to ensure node is fully started
318
- }
319
-
320
- /**
321
- * Register this peer in the CadrePeer table.
322
- * This allows other cadre members to discover this node.
323
- */
324
- private async registerSelf(): Promise<void> {
325
- if (!this.controlNode || !this.controlDatabase) {
326
- log('Cannot register self - node or database not initialized');
327
- return;
328
- }
329
-
330
- const peerId = this.controlNode.peerId.toString();
331
- const multiaddrs = this.controlNode.getMultiaddrs();
332
-
333
- if (multiaddrs.length === 0) {
334
- log('No multiaddrs available for self-registration');
335
- return;
336
- }
337
-
338
- // Use the first available multiaddr (typically the one with the peer ID)
339
- const multiaddr = multiaddrs[0]!.toString();
340
-
341
- log('Registering self: peerId=%s, multiaddr=%s', peerId, multiaddr);
342
-
343
- // TODO: This requires signing the update to satisfy the AuthorizedUpdate constraint
344
- // For now, we log what would happen. Full implementation requires:
345
- // 1. Either an authority key to authorize the insert
346
- // 2. Or the peer's private key to sign the update
347
- log('Self-registration requires authorization - skipping for now');
348
- // const db = this.controlDatabase.getDatabase();
349
- // await db.exec(
350
- // 'insert or replace into CadrePeer (PeerId, Multiaddr) values (?, ?)',
351
- // [peerId, multiaddr]
352
- // );
353
- }
354
-
355
- private async handleStrandAdded(strand: StrandRow): Promise<void> {
356
- log('Handling strand added from control network: %s', strand.Id);
357
-
358
- // Check if we have sApp config for this strand
359
- const sAppConfig = this.sAppConfigs.get(strand.Id);
360
- if (!sAppConfig) {
361
- log('No sAppConfig registered for strand %s - skipping auto-start', strand.Id);
362
- // Strand detected in control network but not yet configured via addStrand
363
- // This is normal - the app will call addStrand with the config
364
- return;
365
- }
366
-
367
- try {
368
- const instance = await this.strandManager.startStrand({
369
- strandRow: strand,
370
- sAppConfig,
371
- storage: this.config.storage,
372
- network: this.config.network,
373
- profile: this.config.profile,
374
- defaultLatencyHint: this.config.hibernation?.defaultLatencyHint ?? 'interactive',
375
- privateKey: this.config.privateKey
376
- });
377
-
378
- // Register with hibernation manager
379
- this.hibernationManager.trackStrand(instance);
380
-
381
- this.emit('strand:started', { strandId: strand.Id });
382
- } catch (error) {
383
- log('Error starting strand %s: %o', strand.Id, error);
384
- this.emit('strand:error', {
385
- strandId: strand.Id,
386
- error: error instanceof Error ? error : new Error(String(error))
387
- });
388
- }
389
- }
390
-
391
- private async handleStrandRemoved(strandId: string): Promise<void> {
392
- log('Handling strand removed: %s', strandId);
393
-
394
- try {
395
- // Untrack from hibernation
396
- this.hibernationManager.untrackStrand(strandId);
397
-
398
- // Remove sApp config
399
- this.sAppConfigs.delete(strandId);
400
-
401
- await this.strandManager.stopStrand(strandId);
402
- this.emit('strand:stopped', { strandId });
403
- } catch (error) {
404
- log('Error stopping strand %s: %o', strandId, error);
405
- this.emit('strand:error', {
406
- strandId,
407
- error: error instanceof Error ? error : new Error(String(error))
408
- });
409
- }
410
- }
411
-
412
- private async cleanup(): Promise<void> {
413
- // Stop hibernation manager
414
- this.hibernationManager.stop();
415
-
416
- // Stop seed bootstrap service
417
- if (this.seedBootstrapService) {
418
- await this.seedBootstrapService.shutdown();
419
- this.seedBootstrapService = null;
420
- }
421
-
422
- // Unregister strand solicitation service
423
- if (this.strandSolicitationService && this.controlNode) {
424
- this.strandSolicitationService.unregisterResponder(this.controlNode);
425
- this.strandSolicitationService = null;
426
- }
427
-
428
- // Stop strand watcher
429
- if (this.strandWatcher) {
430
- await this.strandWatcher.stop();
431
- this.strandWatcher = null;
432
- }
433
-
434
- // Stop all strand instances
435
- await this.strandManager.stopAll();
436
-
437
- // Clear sApp configs
438
- this.sAppConfigs.clear();
439
-
440
- // Close control database (this also shuts down the collection factory)
441
- if (this.controlDatabase) {
442
- await this.controlDatabase.close();
443
- this.controlDatabase = null;
444
- }
445
-
446
- // Stop control node
447
- if (this.controlNode) {
448
- await this.controlNode.stop();
449
- this.controlNode = null;
450
- }
451
- }
452
-
453
- // Hibernation callbacks
454
- private async handleStrandIdle(strandId: string): Promise<void> {
455
- const instance = this.strandManager.getInstance(strandId);
456
- if (instance) {
457
- instance.status = 'idle';
458
- log('Strand %s transitioned to idle', strandId);
459
- this.emit('strand:idle', { strandId });
460
- }
461
- }
462
-
463
- private async handleStrandHibernate(strandId: string): Promise<void> {
464
- const instance = this.strandManager.getInstance(strandId);
465
- if (instance) {
466
- instance.status = 'hibernating';
467
-
468
- // Optionally disconnect libp2p to save resources
469
- // For now we keep it connected but could stop it here
470
- log('Strand %s transitioned to hibernating', strandId);
471
- this.emit('strand:hibernating', { strandId });
472
- }
473
- }
474
-
475
- private async handleStrandWake(strandId: string): Promise<void> {
476
- const instance = this.strandManager.getInstance(strandId);
477
- if (instance) {
478
- instance.status = 'active';
479
- instance.lastActivity = new Date();
480
- log('Strand %s woke up', strandId);
481
- this.emit('strand:waking', { strandId });
482
- }
483
- }
484
-
485
- /**
486
- * Add a strand with its sApp configuration.
487
- * The hosting application must provide the sApp schema when creating a strand.
488
- */
489
- async addStrand(config: StrandConfig): Promise<StrandInstance> {
490
- if (!this.running) {
491
- throw new Error('CadreNode not running');
492
- }
493
-
494
- const { strandRow, sAppConfig, mode } = config;
495
-
496
- // Store sApp config for this strand
497
- this.sAppConfigs.set(strandRow.Id, sAppConfig);
498
- log('Registered sAppConfig for strand %s (sApp: %s, mode: %s)', strandRow.Id, sAppConfig.id, mode ?? 'networked');
499
-
500
- const instance = await this.strandManager.startStrand({
501
- strandRow,
502
- sAppConfig,
503
- storage: this.config.storage,
504
- network: this.config.network,
505
- profile: this.config.profile,
506
- defaultLatencyHint: this.config.hibernation?.defaultLatencyHint ?? 'interactive',
507
- privateKey: this.config.privateKey,
508
- mode
509
- });
510
-
511
- // Register with hibernation manager
512
- this.hibernationManager.trackStrand(instance);
513
-
514
- this.emit('strand:started', { strandId: strandRow.Id });
515
- return instance;
516
- }
517
-
518
- /**
519
- * Remove a strand
520
- */
521
- async removeStrand(strandId: string): Promise<void> {
522
- if (!this.running) {
523
- throw new Error('CadreNode not running');
524
- }
525
-
526
- // Untrack from hibernation
527
- this.hibernationManager.untrackStrand(strandId);
528
-
529
- // Remove sApp config
530
- this.sAppConfigs.delete(strandId);
531
-
532
- await this.strandManager.stopStrand(strandId);
533
- this.emit('strand:stopped', { strandId });
534
- }
535
-
536
- /**
537
- * Record activity on a strand (resets hibernation timer)
538
- */
539
- recordStrandActivity(strandId: string): void {
540
- const instance = this.strandManager.getInstance(strandId);
541
- if (instance) {
542
- this.hibernationManager.recordActivity(instance);
543
- }
544
- }
545
-
546
- /**
547
- * Force wake a hibernating strand
548
- */
549
- async wakeStrand(strandId: string): Promise<void> {
550
- await this.hibernationManager.wakeStrand(strandId);
551
- }
552
-
553
- /**
554
- * Get the control network node (for advanced use)
555
- */
556
- getControlNode(): Libp2p | null {
557
- return this.controlNode;
558
- }
559
-
560
- /**
561
- * Get the control database (for advanced queries)
562
- */
563
- getControlDatabase(): ControlDatabase | null {
564
- return this.controlDatabase;
565
- }
566
-
567
- /**
568
- * Force a poll of the strand watcher (for testing)
569
- */
570
- async forceStrandPoll(): Promise<void> {
571
- await this.strandWatcher?.forcePoll();
572
- }
573
-
574
- /**
575
- * Get the sApp configuration for a strand
576
- */
577
- getSAppConfig(strandId: string): SAppConfig | undefined {
578
- return this.sAppConfigs.get(strandId);
579
- }
580
-
581
- // ============================================================================
582
- // Seed Bootstrap API
583
- // ============================================================================
584
-
585
- /**
586
- * Initialize the seed bootstrap service with an authority key.
587
- * Must be called before using seed-related methods that require signing.
588
- *
589
- * @param authorityPrivateKey - The authority's private key (base64url encoded)
590
- */
591
- initializeSeedBootstrap(authorityPrivateKey: string): void {
592
- if (!this.controlNode || !this.controlDatabase) {
593
- throw new Error('CadreNode must be started before initializing seed bootstrap');
594
- }
595
-
596
- this.seedBootstrapService = new SeedBootstrapService({
597
- partyId: this.config.controlNetwork.partyId,
598
- authorityPrivateKey,
599
- ...(this.config.network?.inviteAddressResolver
600
- ? { inviteAddressResolver: this.config.network.inviteAddressResolver }
601
- : {}),
602
- });
603
-
604
- this.seedBootstrapService.setEventCallbacks({
605
- onSeedReceived: (partyId, peerId) => this.emit('seed:received', { partyId, peerId }),
606
- onSeedApplied: (partyId, peersAdded) => this.emit('seed:applied', { partyId, peersAdded }),
607
- onSeedError: (partyId, error) => this.emit('seed:error', { partyId, error }),
608
- });
609
-
610
- this.seedBootstrapService.initialize(this.controlNode, this.controlDatabase);
611
- log('Seed bootstrap service initialized');
612
- }
613
-
614
- /**
615
- * Enable the seed listener for receiving seeds via the /sereus/seed/1.0.0 protocol.
616
- * This is for drone nodes that need to receive seeds without being an authority.
617
- * Does not require an authority key.
618
- */
619
- enableSeedListener(): void {
620
- if (!this.controlNode || !this.controlDatabase) {
621
- throw new Error('CadreNode must be started before enabling seed listener');
622
- }
623
-
624
- // Don't re-initialize if already has a service
625
- if (this.seedBootstrapService) {
626
- log('Seed bootstrap service already initialized');
627
- return;
628
- }
629
-
630
- this.seedBootstrapService = new SeedBootstrapService({
631
- partyId: this.config.controlNetwork.partyId,
632
- // No authority key - this node only receives seeds
633
- ...(this.config.network?.inviteAddressResolver
634
- ? { inviteAddressResolver: this.config.network.inviteAddressResolver }
635
- : {}),
636
- });
637
-
638
- this.seedBootstrapService.setEventCallbacks({
639
- onSeedReceived: (partyId, peerId) => this.emit('seed:received', { partyId, peerId }),
640
- onSeedApplied: (partyId, peersAdded) => this.emit('seed:applied', { partyId, peersAdded }),
641
- onSeedError: (partyId, error) => this.emit('seed:error', { partyId, error }),
642
- });
643
-
644
- this.seedBootstrapService.initialize(this.controlNode, this.controlDatabase);
645
- log('Seed listener enabled');
646
- }
647
-
648
- /**
649
- * Get the seed bootstrap service (for advanced use)
650
- */
651
- getSeedBootstrapService(): SeedBootstrapService | null {
652
- return this.seedBootstrapService;
653
- }
654
-
655
- /**
656
- * Authorize a new peer to join the cadre.
657
- * Signs the peer ID with the authority key and inserts into CadrePeer table.
658
- *
659
- * @param peerId - The peer ID to authorize
660
- * @param multiaddrs - Optional multiaddrs for the peer
661
- */
662
- async authorizePeer(peerId: string, multiaddrs?: string[]): Promise<void> {
663
- if (!this.seedBootstrapService) {
664
- throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
665
- }
666
- await this.seedBootstrapService.authorizePeer({ peerId, multiaddrs });
667
- }
668
-
669
- /**
670
- * Remove a previously-authorized peer from the cadre.
671
- * Signs the peer ID with the authority key and deletes the CadrePeer row.
672
- *
673
- * @param peerId - The peer ID to remove
674
- */
675
- async removePeer(peerId: string): Promise<void> {
676
- if (!this.seedBootstrapService) {
677
- throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
678
- }
679
- await this.seedBootstrapService.removePeer(peerId);
680
- }
681
-
682
- /**
683
- * Create a seed from the current control network state.
684
- * The seed contains peer information and is signed by an authority.
685
- */
686
- async createSeed(): Promise<ControlNetworkSeed> {
687
- if (!this.seedBootstrapService) {
688
- throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
689
- }
690
- return await this.seedBootstrapService.createSeed();
691
- }
692
-
693
- /**
694
- * Apply a seed to populate the peer cache and enable connections.
695
- * Validates the seed signature before applying.
696
- */
697
- async applySeed(seed: ControlNetworkSeed): Promise<ApplySeedResult> {
698
- if (!this.seedBootstrapService) {
699
- // Create a temporary service for applying seeds (doesn't need authority key)
700
- const tempService = new SeedBootstrapService({
701
- partyId: seed.partyId,
702
- });
703
- if (this.controlNode && this.controlDatabase) {
704
- tempService.initialize(this.controlNode, this.controlDatabase);
705
- }
706
- return await tempService.applySeed(seed);
707
- }
708
- return await this.seedBootstrapService.applySeed(seed);
709
- }
710
-
711
- /**
712
- * Deliver a seed directly to a peer via the /sereus/seed/1.0.0 protocol.
713
- */
714
- async deliverSeed(targetMultiaddr: string, seed: ControlNetworkSeed): Promise<{ accepted: boolean; reason?: string }> {
715
- if (!this.seedBootstrapService) {
716
- throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
717
- }
718
- return await this.seedBootstrapService.deliverSeed(targetMultiaddr, seed);
719
- }
720
-
721
- /**
722
- * Encode a seed for out-of-band delivery (e.g., QR code, copy/paste).
723
- */
724
- encodeSeed(seed: ControlNetworkSeed): string {
725
- // Static method - doesn't need service initialization
726
- const json = JSON.stringify(seed);
727
- return uint8ArrayToString(new TextEncoder().encode(json), 'base64url');
728
- }
729
-
730
- /**
731
- * Decode a seed from base64url encoding.
732
- */
733
- decodeSeed(encoded: string): ControlNetworkSeed {
734
- // Static method - doesn't need service initialization
735
- const bytes = uint8ArrayFromString(encoded, 'base64url');
736
- const json = new TextDecoder().decode(bytes);
737
- return JSON.parse(json) as ControlNetworkSeed;
738
- }
739
-
740
- /**
741
- * Get this node's circuit relay address for inclusion in seeds.
742
- * Returns null if no relay address is available.
743
- */
744
- async getRelayAddress(): Promise<string | null> {
745
- if (!this.controlNode) {
746
- return null;
747
- }
748
-
749
- const addrs = this.controlNode.getMultiaddrs();
750
- const relayAddr = addrs.find(addr => addr.toString().includes('/p2p-circuit/'));
751
- return relayAddr?.toString() ?? null;
752
- }
753
-
754
- // ============================================================================
755
- // Seed Bootstrap Helper Methods
756
- // ============================================================================
757
-
758
- /**
759
- * Add a drone to the cadre (for phone/server adding provider-hosted node).
760
- * Creates authorization and seed for drone initialization.
761
- */
762
- async addDrone(options: AddDroneOptions): Promise<DroneInitResult> {
763
- if (!this.seedBootstrapService) {
764
- throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
765
- }
766
- return await this.seedBootstrapService.addDrone(options);
767
- }
768
-
769
- /**
770
- * Create an invite for a phone to join the cadre.
771
- * Use when a server wants to invite a NAT'd phone.
772
- */
773
- async createInvite(token?: string, expiresIn?: number): Promise<InviteResult> {
774
- if (!this.seedBootstrapService) {
775
- throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
776
- }
777
- return await this.seedBootstrapService.createInvite(token, expiresIn);
778
- }
779
-
780
- /**
781
- * Accept a phone connection using an invite.
782
- * Call this when a phone dials in with an invite token.
783
- */
784
- async acceptPhone(options: AddPhoneOptions, issuedInvite?: CadreInvite): Promise<void> {
785
- if (!this.seedBootstrapService) {
786
- throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
787
- }
788
- await this.seedBootstrapService.acceptPhone(options, issuedInvite);
789
- }
790
-
791
- /**
792
- * Add a phone to the cadre with relay support.
793
- * Use when both nodes are NAT'd (phone-to-phone).
794
- */
795
- async addPhoneWithRelay(phonePeerId: string): Promise<DroneInitResult> {
796
- if (!this.seedBootstrapService) {
797
- throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
798
- }
799
- return await this.seedBootstrapService.addPhoneWithRelay(phonePeerId);
800
- }
801
-
802
- /**
803
- * Encode an invite for out-of-band delivery (QR, link, etc.).
804
- */
805
- encodeInvite(invite: CadreInvite): string {
806
- const json = JSON.stringify(invite);
807
- return uint8ArrayToString(new TextEncoder().encode(json), 'base64url');
808
- }
809
-
810
- /**
811
- * Decode an invite from base64url encoding.
812
- */
813
- decodeInvite(encoded: string): CadreInvite {
814
- const bytes = uint8ArrayFromString(encoded, 'base64url');
815
- const json = new TextDecoder().decode(bytes);
816
- return JSON.parse(json) as CadreInvite;
817
- }
818
-
819
- /**
820
- * Dial an authority from an invite (for phone joining via invite).
821
- */
822
- async dialInvite(invite: CadreInvite): Promise<void> {
823
- if (!this.seedBootstrapService) {
824
- // Create a temporary service for dialing
825
- const tempService = new SeedBootstrapService({
826
- partyId: invite.partyId,
827
- });
828
- if (this.controlNode && this.controlDatabase) {
829
- tempService.initialize(this.controlNode, this.controlDatabase);
830
- }
831
- await tempService.dialInvite(invite);
832
- return;
833
- }
834
- await this.seedBootstrapService.dialInvite(invite);
835
- }
836
-
837
- // ============================================================================
838
- // Strand Solicitation API (strand-proto integration)
839
- // ============================================================================
840
-
841
- /**
842
- * Initialize the strand solicitation service.
843
- * This enables forming strands with other parties via open invitations.
844
- *
845
- * @param options - Configuration for the solicitation service
846
- */
847
- initializeStrandSolicitation(options?: StrandSolicitationServiceOptions): void {
848
- if (!this.controlNode) {
849
- throw new Error('CadreNode must be started before initializing strand solicitation');
850
- }
851
-
852
- this.strandSolicitationService = new StrandSolicitationService({
853
- ...options,
854
- partyId: this.config.controlNetwork.partyId,
855
- cadrePeerAddrs: this.getMultiaddrs()
856
- });
857
-
858
- // Register as responder on the control node
859
- this.strandSolicitationService.registerResponder(this.controlNode);
860
- log('Strand solicitation service initialized');
861
- }
862
-
863
- /**
864
- * Get the strand solicitation service (for advanced use)
865
- */
866
- getStrandSolicitationService(): StrandSolicitationService | null {
867
- return this.strandSolicitationService;
868
- }
869
-
870
- /**
871
- * Create an open invitation for others to form strands with this party.
872
- *
873
- * @param sAppId - The sApp to use for formed strands
874
- * @param expirationMs - How long the invitation is valid (ms from now)
875
- * @returns The open invitation to share out-of-band
876
- */
877
- async createOpenInvitation(
878
- sAppId: string,
879
- expirationMs: number = 24 * 60 * 60 * 1000 // 24 hours default
880
- ): Promise<OpenInvitation> {
881
- if (!this.strandSolicitationService) {
882
- // Create a temporary service for creating invitations
883
- this.initializeStrandSolicitation();
884
- }
885
-
886
- const bootstrap = this.getMultiaddrs();
887
- if (bootstrap.length === 0) {
888
- throw new Error('No multiaddrs available for invitation');
889
- }
890
-
891
- return await this.strandSolicitationService!.createOpenInvitation(
892
- sAppId,
893
- expirationMs,
894
- bootstrap
895
- );
896
- }
897
-
898
- /**
899
- * Form a strand with a responder via an open invitation.
900
- *
901
- * @param invitation - The open invitation received out-of-band
902
- * @param disclosure - Identity/context information to share with the responder
903
- * @returns The member key and strand info if successful
904
- */
905
- async formStrand(
906
- invitation: OpenInvitation,
907
- disclosure: StrandFormationDisclosure = {}
908
- ): Promise<FormStrandResult> {
909
- if (!this.controlNode) {
910
- throw new Error('CadreNode must be started before forming strands');
911
- }
912
-
913
- if (!this.strandSolicitationService) {
914
- this.initializeStrandSolicitation();
915
- }
916
-
917
- return await this.strandSolicitationService!.formStrand(
918
- invitation,
919
- disclosure,
920
- this.controlNode
921
- );
922
- }
923
-
924
- /**
925
- * Encode an open invitation for out-of-band delivery (QR, link, etc.).
926
- */
927
- encodeInvitation(invitation: OpenInvitation): string {
928
- const json = JSON.stringify({
929
- ...invitation,
930
- expiration: invitation.expiration.toISOString()
931
- });
932
- return uint8ArrayToString(new TextEncoder().encode(json), 'base64url');
933
- }
934
-
935
- /**
936
- * Decode an open invitation from base64url encoding.
937
- */
938
- decodeInvitation(encoded: string): OpenInvitation {
939
- const bytes = uint8ArrayFromString(encoded, 'base64url');
940
- const json = new TextDecoder().decode(bytes);
941
- const parsed = JSON.parse(json);
942
- return {
943
- ...parsed,
944
- expiration: new Date(parsed.expiration)
945
- };
946
- }
947
- }
948
-
1
+ import debug from 'debug';
2
+ import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
3
+ import type { Libp2p, PeerId, PrivateKey, Connection } from '@libp2p/interface';
4
+ import { generateKeyPair, privateKeyToProtobuf, privateKeyFromProtobuf } from '@libp2p/crypto/keys';
5
+ import { peerIdFromString } from '@libp2p/peer-id';
6
+ import { createLibp2pNode } from '@optimystic/db-p2p';
7
+ import { multiaddr } from '@multiformats/multiaddr';
8
+ import type { Multiaddr } from '@multiformats/multiaddr';
9
+ import type {
10
+ CadreNodeConfig,
11
+ StrandInstance,
12
+ StrandRow,
13
+ StrandConfig,
14
+ SAppConfig,
15
+ CadreNodeEvents,
16
+ ControlNetworkSeed,
17
+ ApplySeedResult,
18
+ AddDroneOptions,
19
+ AddPhoneOptions,
20
+ DroneInitResult,
21
+ InviteResult,
22
+ CadreInvite,
23
+ OpenInvitation,
24
+ FormStrandResult,
25
+ StrandFormationDisclosure,
26
+ StrandMode,
27
+ ResolveOpts,
28
+ SelfRegistrationOutcome,
29
+ ServiceWakeResult,
30
+ Libp2pNodeWithRepo,
31
+ PushPlatform,
32
+ DeviceTokenRecord,
33
+ ResolveDeviceTokenOpts
34
+ } from './types.js';
35
+ import { DEFAULT_CHECKIN_WINDOW_MS } from './types.js';
36
+ import { sign } from '@optimystic/quereus-plugin-crypto';
37
+ import { authorityKeyFromLibp2p, type AuthorityKeyPair } from './authority-key.js';
38
+ import { DEFAULT_IDENTITY_KEY_ID } from './key-store.js';
39
+ import { ed25519PublicKeyB64FromPeerId } from './seed-bootstrap.js';
40
+ import {
41
+ signPeerRecord,
42
+ verifyPeerRecordSignature,
43
+ isPeerRecordFresh,
44
+ orderSignalingFirst,
45
+ isSignalingAddr,
46
+ currentMemberTrustPolicy,
47
+ DEFAULT_PEER_RECORD_MAX_AGE_MS,
48
+ DEFAULT_PEER_RECORD_HEARTBEAT_MS
49
+ } from './peer-record.js';
50
+ import {
51
+ signDeviceTokenRecord,
52
+ verifyDeviceTokenSignature,
53
+ isPushPlatform
54
+ } from './device-token.js';
55
+ import { StrandWatcher, type StrandQueryable, type SAppIdLookup } from './strand-watcher.js';
56
+ import { StrandInstanceManager } from './strand-instance-manager.js';
57
+ import { deriveCohortMembers, selectStrandMode, type CohortSeed } from './strand-cohort.js';
58
+ import type { CohortPeerRow } from './strand-cohort.js';
59
+ import {
60
+ selectControlCohortDials,
61
+ DEFAULT_CONTROL_COHORT_RECONCILE_MS,
62
+ DEFAULT_CONTROL_COHORT_TARGET_DEGREE
63
+ } from './control-cohort.js';
64
+ import { EnrollmentService } from './enrollment.js';
65
+ import { HibernationManager, type HibernationCallbacks } from './hibernation-manager.js';
66
+ import { ControlDatabase } from './control-database.js';
67
+ import { SeedBootstrapService } from './seed-bootstrap.js';
68
+ import type { SeedTrustPolicy } from './seed-trust-policy.js';
69
+ import {
70
+ StrandSolicitationService,
71
+ type StrandSolicitationServiceOptions
72
+ } from './strand-solicitation.js';
73
+ import { StrandWakeService, dialWake } from './strand-wake-protocol.js';
74
+ import { StrandAddrService, collectStrandAddrs } from './strand-addr-protocol.js';
75
+ import { PushFanoutService } from './push-fanout.js';
76
+ import type { WakeAck, WakeRequest } from './types.js';
77
+ import {
78
+ summarizeConnectionPaths,
79
+ classifyTransport,
80
+ type ConnectionPathSummary,
81
+ type ConnectionLike
82
+ } from './diagnostics/connection-path.js';
83
+ import { TurnRelayTracker } from './diagnostics/webrtc-turn-tracker.js';
84
+
85
+ const log = debug('sereus:cadre:node');
86
+ const timing = debug('sereus:cadre:timing');
87
+
88
+ /**
89
+ * Window (ms) within which a queued TURN-relay settlement is correlated to a
90
+ * `connection:open`. Generous relative to the tight async gap between an
91
+ * `RTCPeerConnection` reaching `connected` and libp2p surfacing the connection.
92
+ */
93
+ const TURN_CONSUME_WINDOW_MS = 1000;
94
+
95
+ type EventHandler<T> = (data: T) => void;
96
+
97
+ /**
98
+ * CadreNode is the main entry point for a cadre member.
99
+ * It manages:
100
+ * - Connection to the control network
101
+ * - Watching for strand changes
102
+ * - Starting/stopping strand instances
103
+ * - Strand hibernation lifecycle
104
+ * - Peer enrollment
105
+ */
106
+ export class CadreNode implements SAppIdLookup {
107
+ private readonly config: CadreNodeConfig;
108
+ /**
109
+ * The resolved node identity key, set once by {@link resolveIdentityKey}
110
+ * during {@link start} (from `config.keyStore`, else `config.privateKey`).
111
+ * Left undefined when neither is configured — libp2p then generates an
112
+ * ephemeral key internally and there is no exposed authority key. Every
113
+ * identity-dependent path (control node creation, self-record signing, strand
114
+ * launch) reads this resolved field, never `config.privateKey` directly.
115
+ */
116
+ private identityKey: PrivateKey | undefined;
117
+ private controlNode: Libp2p | null = null;
118
+ private controlDatabase: ControlDatabase | null = null;
119
+ private strandWatcher: StrandWatcher | null = null;
120
+ private strandManager: StrandInstanceManager;
121
+ private hibernationManager: HibernationManager;
122
+ private enrollmentService: EnrollmentService;
123
+ private seedBootstrapService: SeedBootstrapService | null = null;
124
+ private strandSolicitationService: StrandSolicitationService | null = null;
125
+ private strandWakeService: StrandWakeService | null = null;
126
+ /**
127
+ * Control-network strand-address responder. Answers a co-cadre sibling's
128
+ * on-demand request for this node's live strand-network multiaddrs so the
129
+ * sibling can seed a strand mesh from us — the read side of the seed path that
130
+ * stops conflating control addresses with strand seeding.
131
+ */
132
+ private strandAddrService: StrandAddrService | null = null;
133
+ /**
134
+ * Server-side push-wake fan-out. Constructed by {@link start} only when
135
+ * `config.push` (FCM/APNs credentials) is present — without it the node behaves
136
+ * exactly as before (no notifier, no fan-out). Owns who/when to wake
137
+ * hibernating mobile peers on strand activity.
138
+ */
139
+ private pushFanoutService: PushFanoutService | null = null;
140
+ /** Backing field for the {@link running} / {@link isRunning} getters. */
141
+ private _running = false;
142
+ /**
143
+ * In-flight {@link serviceWake} operations keyed by strandId. Coalesces
144
+ * concurrent on-demand wakes for the same strand into one runtime build + one
145
+ * window + one re-hibernate decision (a second caller joins the first's
146
+ * promise), complementing {@link HibernationManager}'s wake coalescing.
147
+ */
148
+ private serviceWakePromises: Map<string, Promise<ServiceWakeResult>> = new Map();
149
+ /**
150
+ * Live wake-window waiters (see {@link holdWakeWindow}). Tracked so
151
+ * {@link cleanup} can clear the timer AND resolve the promise on teardown — a
152
+ * window must never fire (or hang an in-flight serviceWake) after stop().
153
+ */
154
+ private windowWaiters: Set<{ timer: ReturnType<typeof setTimeout>; resolve: () => void }> = new Set();
155
+ private eventHandlers: Map<keyof CadreNodeEvents, Set<EventHandler<never>>> = new Map();
156
+
157
+ /** Map of strandId -> sAppConfig for sAppId filtering and management */
158
+ private sAppConfigs: Map<string, SAppConfig> = new Map();
159
+
160
+ /**
161
+ * Most-recently pushed invite addresses (see {@link setInviteAddresses}).
162
+ * When non-null these take priority over `libp2pNode.getMultiaddrs()` when
163
+ * minting invites — the host pushes NAT-resolved addresses here so the
164
+ * control-network node never needs to dial back to the manager.
165
+ */
166
+ private latestInviteAddresses: string[] | null = null;
167
+
168
+ /** Initial self-registration timer (see {@link scheduleSelfRegistration}). */
169
+ private selfRegistrationTimer: ReturnType<typeof setTimeout> | null = null;
170
+ /** TTL heartbeat that re-publishes the self record before it goes stale. */
171
+ private recordRefreshTimer: ReturnType<typeof setInterval> | null = null;
172
+ /** Listener that re-publishes the self record when reachable addresses change. */
173
+ private selfPeerUpdateHandler: (() => void) | null = null;
174
+ /**
175
+ * Recurring proactive control-cohort dial cadence (see
176
+ * {@link reconcileControlCohort}). Wired alongside {@link recordRefreshTimer}
177
+ * in {@link startRecordRefresh} and torn down symmetrically in
178
+ * {@link stopRecordRefresh}; `.unref()`'d so it never keeps the loop alive.
179
+ */
180
+ private controlCohortReconcileTimer: ReturnType<typeof setInterval> | null = null;
181
+ /**
182
+ * Single-flight guard for {@link reconcileControlCohort}. The eager start pass,
183
+ * the recurring interval, and the `self:peer:update` trigger can fire close
184
+ * together; collapsing concurrent passes into one in-flight run prevents two
185
+ * passes from double-dialing the same siblings (mirrors {@link registerSelfInFlight}).
186
+ */
187
+ private reconcileControlCohortInFlight: Promise<void> | null = null;
188
+ /**
189
+ * Single-flight guard for {@link registerSelf}. Concurrent callers (the explicit
190
+ * CLI `--authority` publish, the 1s startup timer, the TTL heartbeat, and the
191
+ * address-change listener) share one in-flight publish so two of them can never
192
+ * both read "no row yet" and race a duplicate INSERT (a `CadrePeer` PK conflict).
193
+ */
194
+ private registerSelfInFlight: Promise<SelfRegistrationOutcome> | null = null;
195
+
196
+ // ── Write-while-alone re-replication (control-write-ensure-replicated) ──────
197
+ /**
198
+ * Re-replication queue for authority control writes that committed while this
199
+ * node was alone — `controlNode.getConnections().length === 0` at write time
200
+ * means the Optimystic commit was local-only (the block's cluster was ≤1) and
201
+ * never broadcast. Maps the affected subject peerId → the write to re-issue once
202
+ * the cohort grows. A later op for the same subject overwrites an earlier one
203
+ * (authorize then remove → remove wins). Drained on the 0→≥1 control-connection
204
+ * transition by {@link drainPendingControlReplication}.
205
+ */
206
+ private pendingPeerWrites: Map<string, 'authorize' | 'remove'> = new Map();
207
+ /** This node's own `CadrePeer` self-write committed local-only (re-touched on growth). */
208
+ private pendingSelfPeerWrite = false;
209
+ /** This node's own `DeviceToken` self-write committed local-only (re-touched on growth). */
210
+ private pendingSelfDeviceWrite = false;
211
+ /**
212
+ * Guards the one-shot, first-cohort-growth reconstruction: an authority re-touches
213
+ * every membership row it may have authored that could be unreplicated (covering
214
+ * writes made before this process started, which the in-memory queue cannot know).
215
+ * Set true after the first drain so later passes only drain the in-memory queue.
216
+ */
217
+ private reconstructedLocalOnlyWrites = false;
218
+ /** Single-flight guard for the re-replication drain (mirrors {@link registerSelfInFlight}). */
219
+ private drainControlReplicationInFlight: Promise<void> | null = null;
220
+ /**
221
+ * Tracks the control-connection presence edge so the drain fires only on the
222
+ * 0→≥1 transition (the earliest point a re-issue can broadcast), not on every
223
+ * subsequent `connection:open`. Re-armed to false once connections return to 0.
224
+ */
225
+ private hasControlConnection = false;
226
+ /** `connection:open` listener driving the growth-triggered drain (teardown in {@link stopRecordRefresh}). */
227
+ private controlConnectionOpenHandler: (() => void) | null = null;
228
+ /** `connection:close` listener re-arming the growth edge (teardown in {@link stopRecordRefresh}). */
229
+ private controlConnectionCloseHandler: (() => void) | null = null;
230
+
231
+ // ── WebRTC TURN-relay detection (turn-relayed-path-metrics) ─────────────────
232
+ /**
233
+ * Hooks `globalThis.RTCPeerConnection` to observe whether ICE selected a TURN
234
+ * relay candidate for each WebRTC session. Installed in {@link start}, disposed
235
+ * in {@link cleanup}; inert on Node.js (no `RTCPeerConnection`).
236
+ */
237
+ private readonly turnTracker = new TurnRelayTracker();
238
+ /**
239
+ * Peer IDs whose current WebRTC connection was observed to be TURN-relayed.
240
+ * Populated by {@link handleTurnConnectionOpen} (drains the tracker queue on a
241
+ * `/webrtc` `connection:open`), cleared per-peer on `connection:close`. Read by
242
+ * {@link getConnectionPaths} to promote `webrtc` → `webrtc-turn` (relayed).
243
+ */
244
+ private turnRelayedPeers: Set<string> = new Set();
245
+ /** `connection:open` listener feeding TURN detection (teardown in {@link stopRecordRefresh}). */
246
+ private turnConnectionOpenHandler: ((evt: CustomEvent<Connection>) => void) | null = null;
247
+ /** `connection:close` listener clearing a peer's TURN flag (teardown in {@link stopRecordRefresh}). */
248
+ private turnConnectionCloseHandler: ((evt: CustomEvent<Connection>) => void) | null = null;
249
+
250
+ constructor(config: CadreNodeConfig) {
251
+ this.config = config;
252
+ this.strandManager = new StrandInstanceManager();
253
+ this.enrollmentService = new EnrollmentService();
254
+
255
+ // Create hibernation manager with callbacks
256
+ const hibernationCallbacks: HibernationCallbacks = {
257
+ onIdle: async (strandId) => this.handleStrandIdle(strandId),
258
+ onHibernate: async (strandId) => this.handleStrandHibernate(strandId),
259
+ onWake: async (strandId) => this.handleStrandWake(strandId),
260
+ onCheckIn: async (strandId) => this.handleStrandCheckIn(strandId)
261
+ };
262
+ this.hibernationManager = new HibernationManager(
263
+ config.hibernation ?? { enabled: false },
264
+ hibernationCallbacks
265
+ );
266
+
267
+ log('CadreNode created for party: %s', config.controlNetwork.partyId);
268
+ }
269
+
270
+ /**
271
+ * SAppIdLookup implementation - get sAppId for a strand
272
+ */
273
+ getSAppId(strandId: string): string | undefined {
274
+ return this.sAppConfigs.get(strandId)?.id;
275
+ }
276
+
277
+ /**
278
+ * Get the peer ID of this node (available after start)
279
+ */
280
+ get peerId(): PeerId | undefined {
281
+ return this.controlNode?.peerId;
282
+ }
283
+
284
+ /**
285
+ * The party ID this node serves (control-network identity).
286
+ */
287
+ get partyId(): string {
288
+ return this.config.controlNetwork.partyId;
289
+ }
290
+
291
+ /**
292
+ * Get the multiaddrs of this node (available after start)
293
+ */
294
+ getMultiaddrs(): string[] {
295
+ if (!this.controlNode) return [];
296
+ return this.controlNode.getMultiaddrs().map(ma => ma.toString());
297
+ }
298
+
299
+ /**
300
+ * Check if the node is running
301
+ */
302
+ get isRunning(): boolean {
303
+ return this._running;
304
+ }
305
+
306
+ /**
307
+ * Synchronous lifecycle snapshot for headless callers (a mobile
308
+ * `BackgroundRunner` that boots in a background task and must *query* state
309
+ * rather than subscribe to `control:connected`/`control:disconnected`).
310
+ * Equivalent to {@link isRunning}.
311
+ */
312
+ get running(): boolean {
313
+ return this._running;
314
+ }
315
+
316
+ /**
317
+ * Synchronous readiness snapshot: whether the control network is currently
318
+ * connected (the node is running and its control-network libp2p node is up).
319
+ * Tracks the same edge the `control:connected`/`control:disconnected` events
320
+ * announce, but pollable.
321
+ */
322
+ get controlConnected(): boolean {
323
+ return this._running && this.controlNode !== null;
324
+ }
325
+
326
+ /**
327
+ * Classify every open control-network connection as relayed
328
+ * (`/p2p-circuit`) vs direct, tag its transport, and summarise counts plus a
329
+ * stuck-on-relay condition. Pure, read-only snapshot over
330
+ * `controlNode.getConnections()`. Returns an empty (all-zero) summary when
331
+ * the node has not been started.
332
+ *
333
+ * @param settleWindowMs - grace period before a relayed connection with no
334
+ * direct sibling is considered stuck (default 10_000ms)
335
+ */
336
+ getConnectionPaths(settleWindowMs?: number): ConnectionPathSummary {
337
+ const conns = this.controlNode?.getConnections() ?? [];
338
+ // Annotate each connection with the TURN-relay hint so a WebRTC session whose
339
+ // ICE selected a TURN candidate classifies as relayed/webrtc-turn rather than
340
+ // direct/webrtc (the multiaddr alone cannot reveal it).
341
+ const annotated: ConnectionLike[] = conns.map((c) => ({
342
+ remotePeer: c.remotePeer,
343
+ remoteAddr: c.remoteAddr,
344
+ direction: c.direction,
345
+ timeline: c.timeline,
346
+ turnRelayed: this.turnRelayedPeers.has(c.remotePeer.toString()),
347
+ }));
348
+ return summarizeConnectionPaths(annotated, settleWindowMs);
349
+ }
350
+
351
+ /**
352
+ * Get all strand instances
353
+ */
354
+ getStrands(): Map<string, StrandInstance> {
355
+ return this.strandManager.getInstances();
356
+ }
357
+
358
+ /**
359
+ * Get a specific strand instance
360
+ */
361
+ getStrand(strandId: string): StrandInstance | undefined {
362
+ return this.strandManager.getInstance(strandId);
363
+ }
364
+
365
+ /**
366
+ * Get the enrollment service for adding new peers
367
+ */
368
+ getEnrollmentService(): EnrollmentService {
369
+ return this.enrollmentService;
370
+ }
371
+
372
+ /**
373
+ * Start the cadre node
374
+ */
375
+ async start(): Promise<void> {
376
+ if (this._running) {
377
+ log('CadreNode already running');
378
+ return;
379
+ }
380
+
381
+ log('Starting CadreNode for party: %s', this.config.controlNetwork.partyId);
382
+
383
+ try {
384
+ const tTotal = performance.now();
385
+
386
+ // Install the WebRTC TURN-relay tracker BEFORE any libp2p bring-up, so it
387
+ // wraps globalThis.RTCPeerConnection before the control node can create one.
388
+ // Inert on Node.js (no RTCPeerConnection); disposed in cleanup().
389
+ this.turnTracker.install();
390
+
391
+ // Resolve the node identity (keyStore | privateKey | ephemeral) BEFORE any
392
+ // libp2p/network bring-up, so a misconfiguration or an access-denied secure
393
+ // store fails closed before a node is created.
394
+ await this.resolveIdentityKey();
395
+
396
+ // Create the control network libp2p node
397
+ let t0 = performance.now();
398
+ this.controlNode = await this.createControlNode();
399
+ timing('[start] createControlNode: %dms', Math.round(performance.now() - t0));
400
+ log('Control node started with ID: %s', this.controlNode.peerId.toString());
401
+
402
+ // Extract coordinatedRepo from the node (attached by createLibp2pNode)
403
+ const coordinatedRepo = (this.controlNode as Libp2pNodeWithRepo).coordinatedRepo;
404
+ if (!coordinatedRepo) {
405
+ throw new Error('coordinatedRepo not available on control node');
406
+ }
407
+
408
+ // Initialize the control database with the libp2p node
409
+ t0 = performance.now();
410
+ this.controlDatabase = new ControlDatabase({
411
+ partyId: this.config.controlNetwork.partyId,
412
+ libp2pNode: this.controlNode,
413
+ coordinatedRepo,
414
+ schemaPath: this.config.controlNetwork.schemaPath,
415
+ });
416
+ await this.controlDatabase.initialize();
417
+ timing('[start] controlDatabase.initialize: %dms', Math.round(performance.now() - t0));
418
+ log('Control database initialized');
419
+
420
+ // Create strand queryable using the control database
421
+ const queryable = this.createStrandQueryable();
422
+
423
+ // Create and start the strand watcher with sAppId lookup
424
+ this.strandWatcher = new StrandWatcher(
425
+ queryable,
426
+ {
427
+ onStrandAdded: async (strand) => this.handleStrandAdded(strand),
428
+ onStrandRemoved: async (strandId) => this.handleStrandRemoved(strandId)
429
+ },
430
+ this.config.strandFilter ?? { mode: 'all' },
431
+ this.config.strandWatchInterval ?? 5000,
432
+ this // CadreNode implements SAppIdLookup
433
+ );
434
+
435
+ t0 = performance.now();
436
+ await this.strandWatcher.start();
437
+ timing('[start] strandWatcher.start: %dms', Math.round(performance.now() - t0));
438
+
439
+ // Start hibernation manager
440
+ this.hibernationManager.start();
441
+
442
+ // Register the control-network push-wake receiver: a same-cadre peer can
443
+ // signal us to bring a hibernating strand online. Gated on CadrePeer
444
+ // membership; the wake routes through the same path as a local wake.
445
+ this.strandWakeService = new StrandWakeService({
446
+ isMember: (peerId) => this.isMember(peerId),
447
+ getStrand: (strandId) => this.strandManager.getInstance(strandId),
448
+ wake: (strandId) => this.wakeStrand(strandId),
449
+ });
450
+ this.strandWakeService.initialize(this.controlNode);
451
+
452
+ // Register the control-network strand-address responder: a same-cadre peer
453
+ // resolving a strand's bootstrap seed asks us for our live strand-network
454
+ // multiaddrs (its CadrePeer row only knows our *control* address). Gated on
455
+ // CadrePeer membership; answers only for strands we are actively meshing.
456
+ this.strandAddrService = new StrandAddrService({
457
+ isMember: (peerId) => this.isMember(peerId),
458
+ getStrandMultiaddrs: (strandId) => this.getStrandMultiaddrs(strandId),
459
+ });
460
+ this.strandAddrService.initialize(this.controlNode);
461
+
462
+ // Server-side push-wake fan-out: only when push credentials are configured.
463
+ // The PushNotifier reaches for node:http2/node:crypto, so it is loaded via a
464
+ // guarded DYNAMIC import — a cross-platform (RN/browser) node that never sets
465
+ // config.push never pulls those modules into its static graph. The fan-out
466
+ // service itself is import-clean (PushNotifier type only) and statically imported.
467
+ if (this.config.push) {
468
+ const { createPushNotifier } = await import('./push-notifier.js');
469
+ const notifier = createPushNotifier(this.config.push);
470
+ this.pushFanoutService = new PushFanoutService({
471
+ listMembers: () => this.listMembers(),
472
+ getStrand: (strandId) => this.strandManager.getInstance(strandId),
473
+ selfPeerId: () => this.controlNode?.peerId.toString(),
474
+ pushWake: (peerId, strandId, reason) => this.pushWake(peerId, strandId, reason),
475
+ resolveDeviceToken: (peerId) => this.resolveDeviceToken(peerId),
476
+ expireDeviceToken: (peerId) => this.expireDeviceToken(peerId),
477
+ notifier,
478
+ cooldownMs: this.config.push.cooldownMs,
479
+ debounceMs: this.config.push.debounceMs,
480
+ });
481
+ log('Push-wake fan-out enabled (FCM=%s, APNs=%s)', !!this.config.push.fcm, !!this.config.push.apns);
482
+ }
483
+
484
+ this._running = true;
485
+ this.emit('control:connected', undefined);
486
+ timing('[start] total: %dms', Math.round(performance.now() - tTotal));
487
+ log('CadreNode started successfully');
488
+
489
+ // Wire the control-connection growth listeners immediately (not via the
490
+ // delayed refresh path) so no early `connection:open` is missed — the
491
+ // write-while-alone re-replication drain must fire on the first 0→≥1 edge.
492
+ this.wireControlConnectionListeners();
493
+
494
+ // Schedule self-registration in background
495
+ this.scheduleSelfRegistration();
496
+
497
+ } catch (error) {
498
+ log('Failed to start CadreNode: %o', error);
499
+ await this.cleanup();
500
+ throw error;
501
+ }
502
+ }
503
+
504
+ /**
505
+ * Stop the cadre node
506
+ */
507
+ async stop(): Promise<void> {
508
+ if (!this._running) {
509
+ log('CadreNode not running');
510
+ return;
511
+ }
512
+
513
+ log('Stopping CadreNode');
514
+ await this.cleanup();
515
+ this._running = false;
516
+ this.emit('control:disconnected', undefined);
517
+ log('CadreNode stopped');
518
+ }
519
+
520
+ /**
521
+ * Subscribe to events
522
+ */
523
+ on<K extends keyof CadreNodeEvents>(
524
+ event: K,
525
+ handler: EventHandler<CadreNodeEvents[K]>
526
+ ): void {
527
+ if (!this.eventHandlers.has(event)) {
528
+ this.eventHandlers.set(event, new Set());
529
+ }
530
+ this.eventHandlers.get(event)!.add(handler);
531
+ }
532
+
533
+ /**
534
+ * Unsubscribe from events
535
+ */
536
+ off<K extends keyof CadreNodeEvents>(
537
+ event: K,
538
+ handler: EventHandler<CadreNodeEvents[K]>
539
+ ): void {
540
+ this.eventHandlers.get(event)?.delete(handler);
541
+ }
542
+
543
+ private emit<K extends keyof CadreNodeEvents>(
544
+ event: K,
545
+ data: CadreNodeEvents[K]
546
+ ): void {
547
+ this.eventHandlers.get(event)?.forEach(handler => {
548
+ try {
549
+ (handler as EventHandler<CadreNodeEvents[K]>)(data);
550
+ } catch (e) { log('Event handler error: %o', e); }
551
+ });
552
+ }
553
+
554
+ /**
555
+ * Resolve the node identity into {@link identityKey} exactly once, fail-closed,
556
+ * before any network bring-up. Resolution order:
557
+ *
558
+ * 1. Both `keyStore` and `privateKey` set ⇒ configuration error (throws).
559
+ * 2. `keyStore` set ⇒ load protobuf bytes from `identityKeyId` (default
560
+ * {@link DEFAULT_IDENTITY_KEY_ID}). Found ⇒ deserialize; empty ⇒ generate a
561
+ * fresh Ed25519 key, persist it, and use it. A rejected `get` (access denied
562
+ * / backend failure) PROPAGATES — we never generate a new key on a read
563
+ * error, which would silently orphan the real identity.
564
+ * 3. `privateKey` set ⇒ use it directly.
565
+ * 4. Neither ⇒ leave undefined; libp2p generates an ephemeral key.
566
+ *
567
+ * Idempotent: a second call (or a stop()→start() cycle) reuses the already
568
+ * resolved key rather than regenerating or re-persisting.
569
+ */
570
+ private async resolveIdentityKey(): Promise<void> {
571
+ if (this.identityKey) {
572
+ return;
573
+ }
574
+ const { keyStore, privateKey, identityKeyId } = this.config;
575
+
576
+ if (keyStore && privateKey) {
577
+ throw new Error(
578
+ 'CadreNodeConfig: `keyStore` and `privateKey` are mutually exclusive — ' +
579
+ 'configure at most one source for the node identity'
580
+ );
581
+ }
582
+
583
+ if (keyStore) {
584
+ const keyId = identityKeyId ?? DEFAULT_IDENTITY_KEY_ID;
585
+ // A rejection here (e.g. KeyStoreAccessError) must propagate — do NOT fall
586
+ // through to generation, which would orphan an existing but unreadable key.
587
+ const bytes = await keyStore.get(keyId);
588
+ if (bytes) {
589
+ // Corrupt/garbage bytes throw here; surface loudly rather than
590
+ // regenerating (which would orphan the real identity).
591
+ this.identityKey = privateKeyFromProtobuf(bytes);
592
+ log('Identity key loaded from key store (slot present)');
593
+ return;
594
+ }
595
+ const generated = await generateKeyPair('Ed25519');
596
+ await keyStore.set(keyId, privateKeyToProtobuf(generated));
597
+ this.identityKey = generated;
598
+ log('Identity key generated and persisted to key store (first run)');
599
+ return;
600
+ }
601
+
602
+ if (privateKey) {
603
+ this.identityKey = privateKey;
604
+ return;
605
+ }
606
+ // Neither configured: libp2p generates an ephemeral key internally.
607
+ }
608
+
609
+ private async createControlNode(): Promise<Libp2p> {
610
+ const { controlNetwork, network, storage, profile } = this.config;
611
+ const identityKey = this.identityKey;
612
+
613
+ // Determine relay mode: if explicitly set in config, use that;
614
+ // otherwise default to true for storage profile nodes (better connectivity/uptime)
615
+ const enableRelay = network?.enableRelay ?? (profile === 'storage');
616
+
617
+ // Create storage provider for control network
618
+ // Uses the factory function pattern if provided to create control-network-specific storage
619
+ const controlStorageProvider = storage?.provider
620
+ ? (typeof storage.provider === 'function'
621
+ ? storage.provider('control')
622
+ : storage.provider)
623
+ : undefined;
624
+
625
+ const nodeOptions: Parameters<typeof createLibp2pNode>[0] = {
626
+ port: 0,
627
+ bootstrapNodes: controlNetwork.bootstrapNodes,
628
+ networkName: `control-${controlNetwork.partyId}`,
629
+ storage: controlStorageProvider,
630
+ fretProfile: profile === 'storage' ? 'core' : 'edge',
631
+ relay: enableRelay,
632
+ clusterSize: 3,
633
+ clusterPolicy: { allowDownsize: true, sizeTolerance: 0.5 },
634
+ arachnode: { enableRingZulu: this.config.profile === 'storage' },
635
+ ...(identityKey && { privateKey: identityKey }),
636
+ ...(network?.transports && { transports: network.transports }),
637
+ ...(network?.listenAddrs && { listenAddrs: network.listenAddrs }),
638
+ ...(network?.connectionGater && { connectionGater: network.connectionGater })
639
+ };
640
+
641
+ return await createLibp2pNode(nodeOptions);
642
+ }
643
+
644
+ private createStrandQueryable(): StrandQueryable {
645
+ return {
646
+ queryStrands: async (): Promise<StrandRow[]> => {
647
+ if (!this.controlDatabase) {
648
+ log('Control database not initialized, returning empty strands');
649
+ return [];
650
+ }
651
+ log('Querying strands from control database');
652
+ return await this.controlDatabase.queryStrands();
653
+ }
654
+ };
655
+ }
656
+
657
+ /**
658
+ * Schedule the node's initial self-record publish + ongoing refresh shortly
659
+ * after start (non-blocking). {@link registerSelf} is idempotent and safely
660
+ * no-ops when it cannot yet sign/insert (e.g. authority key not installed),
661
+ * so the timer is harmless even when registration only becomes possible later.
662
+ */
663
+ private scheduleSelfRegistration(): void {
664
+ this.selfRegistrationTimer = setTimeout(() => {
665
+ void (async () => {
666
+ try {
667
+ await this.registerSelf();
668
+ } catch (error) {
669
+ // Background task — a failed publish must not crash the node.
670
+ log('Self-registration failed: %o', error);
671
+ }
672
+ // Wire the ongoing refresh + control-cohort reconcile cadence, then run
673
+ // an eager reconcile pass once the node has settled (the recurring
674
+ // interval was just armed inside startRecordRefresh).
675
+ this.startRecordRefresh();
676
+ void this.reconcileControlCohort().catch((error) =>
677
+ log('Control-cohort reconcile (start) failed: %o', error));
678
+ })();
679
+ }, 1000); // Small delay to ensure node is fully started
680
+ // Node-only: don't keep the event loop alive solely for this timer.
681
+ (this.selfRegistrationTimer as { unref?: () => void } | null)?.unref?.();
682
+ }
683
+
684
+ /**
685
+ * Publish (or refresh) this node's own signed `CadrePeer` address record so
686
+ * other members can resolve its current signaling/relay multiaddrs from its
687
+ * PeerId alone. Public, awaitable, and idempotent.
688
+ *
689
+ * - Builds a `PeerAddressRecord` from the node's current dialable addrs
690
+ * (signaling/`p2p-circuit` first), signed with the ed25519 key behind its
691
+ * PeerId (the resolved node identity from `keyStore`/`config.privateKey`).
692
+ * - If the row already exists: a self-signed UPDATE bumping `UpdatedAt`.
693
+ * - If not, and the node is its own authority: an authority-signed INSERT that
694
+ * also carries the self-signature.
695
+ * - Otherwise: logs and returns (a non-authority node with no row yet must
696
+ * wait for an authority to insert it; it can then self-refresh).
697
+ *
698
+ * Safe to call repeatedly (heartbeat / address-change driven); each successful
699
+ * publish strictly increases `UpdatedAt`. Concurrent calls are collapsed into a
700
+ * single in-flight publish (see {@link registerSelfInFlight}) so the explicit
701
+ * startup publish and the background timers can never race a duplicate INSERT.
702
+ *
703
+ * @returns what the publish did — `inserted`, `refreshed`, or `skipped`.
704
+ */
705
+ async registerSelf(): Promise<SelfRegistrationOutcome> {
706
+ // Join an in-flight publish rather than starting a second one. Without this,
707
+ // the explicit CLI call and the 1s timer could both observe "no row yet" and
708
+ // both attempt the INSERT — the loser hits a CadrePeer PK conflict.
709
+ if (this.registerSelfInFlight) {
710
+ return this.registerSelfInFlight;
711
+ }
712
+ const op = this.publishSelfRecord();
713
+ this.registerSelfInFlight = op;
714
+ try {
715
+ return await op;
716
+ } finally {
717
+ this.registerSelfInFlight = null;
718
+ }
719
+ }
720
+
721
+ /** The body of {@link registerSelf}; serialised by its single-flight guard. */
722
+ private async publishSelfRecord(): Promise<SelfRegistrationOutcome> {
723
+ if (!this._running || !this.controlNode || !this.controlDatabase) {
724
+ log('Cannot register self - node or database not initialized');
725
+ return 'skipped';
726
+ }
727
+
728
+ const signingKey = this.getSelfSigningKey();
729
+ if (!signingKey) {
730
+ log('registerSelf: no self-signing key available (node identity unavailable or not matching peerId); skipping');
731
+ return 'skipped';
732
+ }
733
+
734
+ const peerId = this.controlNode.peerId.toString();
735
+ const addrs = await this.collectSelfAddrs();
736
+ const existing = await this.controlDatabase.queryPeerRecord(peerId);
737
+
738
+ // Strictly increase UpdatedAt even on a same-millisecond re-publish.
739
+ const updatedAt = Math.max(Date.now(), (existing?.updatedAt ?? 0) + 1);
740
+ const record = signPeerRecord(
741
+ { peerId, publicKey: signingKey.publicKeyB64, addrs, updatedAt },
742
+ signingKey.privateKeyB64
743
+ );
744
+
745
+ if (existing) {
746
+ await this.controlDatabase.updateSelfPeerRecord(record);
747
+ if (this.committedAlone()) this.pendingSelfPeerWrite = true;
748
+ log('registerSelf: refreshed own CadrePeer record (updatedAt=%d, %d addrs)', updatedAt, addrs.length);
749
+ return 'refreshed';
750
+ }
751
+ if (this.seedBootstrapService) {
752
+ // First-time row: requires an authority signature (the node is its own
753
+ // authority). insertSelfPeerRecord throws if no authority key is present.
754
+ await this.seedBootstrapService.insertSelfPeerRecord(record);
755
+ if (this.committedAlone()) this.pendingSelfPeerWrite = true;
756
+ log('registerSelf: inserted own CadrePeer record (authority-signed, updatedAt=%d, %d addrs)', updatedAt, addrs.length);
757
+ return 'inserted';
758
+ }
759
+ log('registerSelf: not yet a CadrePeer member and no authority service to self-insert; skipping (an authority must add this peer first)');
760
+ return 'skipped';
761
+ }
762
+
763
+ /**
764
+ * The ed25519 keypair (base64url) the node signs its own record with — the key
765
+ * behind its libp2p PeerId. Sourced from the resolved {@link identityKey}
766
+ * (which a `keyStore` or `config.privateKey` supplies); returns null when
767
+ * absent (ephemeral identity) or (defensively) when it does not match the
768
+ * control node's PeerId, in which case self-publish is skipped rather than
769
+ * producing an unresolvable row.
770
+ */
771
+ private getSelfSigningKey(): { privateKeyB64: string; publicKeyB64: string } | null {
772
+ const peerId = this.controlNode?.peerId.toString();
773
+ if (!peerId || !this.identityKey) {
774
+ return null;
775
+ }
776
+ try {
777
+ const { privateKeyB64, publicKeyB64 } = authorityKeyFromLibp2p(this.identityKey);
778
+ if (publicKeyB64 === ed25519PublicKeyB64FromPeerId(peerId)) {
779
+ return { privateKeyB64, publicKeyB64 };
780
+ }
781
+ log('getSelfSigningKey: resolved identity key does not match control node peerId; cannot self-sign');
782
+ } catch (error) {
783
+ // Logs the error shape only; authorityKeyFromLibp2p never embeds key material.
784
+ log('getSelfSigningKey: failed to derive ed25519 key from identity key: %o', error);
785
+ }
786
+ return null;
787
+ }
788
+
789
+ /**
790
+ * The authority keypair (base64url Ed25519) derived from this node's resolved
791
+ * identity key. In the single-key reference model the authority signing key is
792
+ * *derived from* the node identity (see {@link authorityKeyFromLibp2p}), so the
793
+ * same key material protected in a secure enclave backs both.
794
+ *
795
+ * Exposed so the hosting app retains control of authority genesis: cadre-core
796
+ * resolves + protects the identity, then the app sources this pair to drive
797
+ * `ensureAuthorityKey(pub)` + `initializeSeedBootstrap(priv)` itself — cadre-core
798
+ * never silently runs genesis. A future separate-authority slot would return a
799
+ * distinct key here instead of the identity-derived one.
800
+ *
801
+ * @returns The base64url seed/public-key authority pair.
802
+ * @throws If called before {@link start} has resolved the identity, or when the
803
+ * node runs on an ephemeral libp2p key (no `keyStore`/`privateKey` configured),
804
+ * since that key is internal to libp2p and not exposed.
805
+ */
806
+ getIdentityAuthorityKey(): AuthorityKeyPair {
807
+ if (!this.identityKey) {
808
+ throw new Error(
809
+ 'getIdentityAuthorityKey: node identity not resolved — call start() first, and ' +
810
+ 'configure `keyStore` or `privateKey` (an ephemeral libp2p identity exposes no authority key)'
811
+ );
812
+ }
813
+ return authorityKeyFromLibp2p(this.identityKey);
814
+ }
815
+
816
+ /**
817
+ * Collect this node's current dialable addresses for publication, signaling
818
+ * (`/p2p-circuit`) first. Prefers the best invite/NAT-resolved set and folds
819
+ * in the relay/signaling address (the WebRTC dial input) when not already
820
+ * present.
821
+ */
822
+ private async collectSelfAddrs(): Promise<string[]> {
823
+ const resolved = await this.resolveInviteAddresses();
824
+ const relay = await this.getRelayAddress();
825
+ const merged = relay && !resolved.includes(relay) ? [...resolved, relay] : resolved;
826
+ return orderSignalingFirst([...new Set(merged)]);
827
+ }
828
+
829
+ /**
830
+ * Wire the ongoing self-record refresh: re-publish whenever libp2p reports an
831
+ * address change (relay reservation rotation, NAT change) and on a TTL
832
+ * heartbeat at half the freshness ceiling. Idempotent — repeated calls do not
833
+ * stack listeners/timers.
834
+ */
835
+ private startRecordRefresh(): void {
836
+ if (!this.controlNode || this.recordRefreshTimer) {
837
+ return;
838
+ }
839
+
840
+ const republish = (reason: string) => {
841
+ void this.registerSelf().catch((error) => log('Record refresh (%s) failed: %o', reason, error));
842
+ };
843
+ const reconcile = (reason: string) => {
844
+ void this.reconcileControlCohort().catch((error) =>
845
+ log('Control-cohort reconcile (%s) failed: %o', reason, error));
846
+ };
847
+
848
+ // Address churn re-publishes the self record AND re-checks the control cohort:
849
+ // a relay-reservation rotation / NAT change can drop a sibling connection, so
850
+ // the next pass should re-observe and re-dial it.
851
+ this.selfPeerUpdateHandler = () => {
852
+ republish('self:peer:update');
853
+ reconcile('self:peer:update');
854
+ };
855
+ this.controlNode.addEventListener('self:peer:update', this.selfPeerUpdateHandler);
856
+
857
+ this.recordRefreshTimer = setInterval(() => republish('heartbeat'), DEFAULT_PEER_RECORD_HEARTBEAT_MS);
858
+ (this.recordRefreshTimer as { unref?: () => void } | null)?.unref?.();
859
+
860
+ const reconcileMs = this.config.network?.controlCohort?.reconcileMs ?? DEFAULT_CONTROL_COHORT_RECONCILE_MS;
861
+ this.controlCohortReconcileTimer = setInterval(() => reconcile('interval'), reconcileMs);
862
+ (this.controlCohortReconcileTimer as { unref?: () => void } | null)?.unref?.();
863
+
864
+ log('Record refresh wired (heartbeat=%dms, cohortReconcile=%dms)',
865
+ DEFAULT_PEER_RECORD_HEARTBEAT_MS, reconcileMs);
866
+ }
867
+
868
+ /** Tear down the self-record refresh timers + listener (see {@link cleanup}). */
869
+ private stopRecordRefresh(): void {
870
+ if (this.selfRegistrationTimer) {
871
+ clearTimeout(this.selfRegistrationTimer);
872
+ this.selfRegistrationTimer = null;
873
+ }
874
+ if (this.recordRefreshTimer) {
875
+ clearInterval(this.recordRefreshTimer);
876
+ this.recordRefreshTimer = null;
877
+ }
878
+ if (this.controlCohortReconcileTimer) {
879
+ clearInterval(this.controlCohortReconcileTimer);
880
+ this.controlCohortReconcileTimer = null;
881
+ }
882
+ if (this.controlNode) {
883
+ if (this.selfPeerUpdateHandler) {
884
+ this.controlNode.removeEventListener('self:peer:update', this.selfPeerUpdateHandler);
885
+ }
886
+ if (this.controlConnectionOpenHandler) {
887
+ this.controlNode.removeEventListener('connection:open', this.controlConnectionOpenHandler);
888
+ }
889
+ if (this.controlConnectionCloseHandler) {
890
+ this.controlNode.removeEventListener('connection:close', this.controlConnectionCloseHandler);
891
+ }
892
+ if (this.turnConnectionOpenHandler) {
893
+ this.controlNode.removeEventListener('connection:open', this.turnConnectionOpenHandler);
894
+ }
895
+ if (this.turnConnectionCloseHandler) {
896
+ this.controlNode.removeEventListener('connection:close', this.turnConnectionCloseHandler);
897
+ }
898
+ }
899
+ this.selfPeerUpdateHandler = null;
900
+ this.controlConnectionOpenHandler = null;
901
+ this.controlConnectionCloseHandler = null;
902
+ this.turnConnectionOpenHandler = null;
903
+ this.turnConnectionCloseHandler = null;
904
+
905
+ // Reset the write-while-alone re-replication state so a stop()→start() cycle
906
+ // re-arms the growth edge and re-runs the first-growth reconstruction. Any
907
+ // queued local-only writes are moot once the node is torn down; authority
908
+ // inserts are re-covered by reconstruction on the next start, and the
909
+ // (already-loudly-logged) delete gap is tracked for follow-up.
910
+ this.hasControlConnection = false;
911
+ this.reconstructedLocalOnlyWrites = false;
912
+ this.pendingPeerWrites.clear();
913
+ this.pendingSelfPeerWrite = false;
914
+ this.pendingSelfDeviceWrite = false;
915
+ }
916
+
917
+ /**
918
+ * Resolve a peer's current, signed, trust-checkable multiaddrs from only its
919
+ * PeerId — the transport-agnostic input a NAT-to-NAT WebRTC (or any) dial path
920
+ * consumes, with no copy/paste of a relayed dial string.
921
+ *
922
+ * Reads the peer's `CadrePeer` record and gates it through, in order:
923
+ * 1. record present (else `[]`),
924
+ * 2. `publicKey <-> peerId` binding (the stored key's libp2p identity must be
925
+ * the requested peerId),
926
+ * 3. self-signature verifies against `publicKey`,
927
+ * 4. freshness — rejected once older than `maxAgeMs` (never a dead relay
928
+ * reservation),
929
+ * 5. the pluggable trust gate (`opts.trustPolicy`).
930
+ * Survivors are returned signaling (`/p2p-circuit`) first, filtered to
931
+ * signaling-only when requested, as parsed `Multiaddr`s (unparsable addrs
932
+ * dropped). Any gate failure yields an empty array rather than throwing.
933
+ */
934
+ async resolvePeerAddrs(peerId: string, opts: ResolveOpts = {}): Promise<Multiaddr[]> {
935
+ if (!this.controlDatabase) {
936
+ throw new Error('CadreNode must be started before resolving peer addrs');
937
+ }
938
+
939
+ const record = await this.controlDatabase.queryPeerRecord(peerId);
940
+ if (!record) {
941
+ log('resolvePeerAddrs: no record for %s', peerId);
942
+ return [];
943
+ }
944
+
945
+ // publicKey <-> peerId binding: the stored key must be the one embedded in
946
+ // the requested Ed25519 peer id (also rejects a non-Ed25519 / missing key).
947
+ if (!record.publicKey || ed25519PublicKeyB64FromPeerId(peerId) !== record.publicKey) {
948
+ log('resolvePeerAddrs: publicKey does not match peerId for %s', peerId);
949
+ return [];
950
+ }
951
+
952
+ // Self-signature over (peerId, addrs, updatedAt).
953
+ if (!verifyPeerRecordSignature(record)) {
954
+ log('resolvePeerAddrs: signature verification failed for %s', peerId);
955
+ return [];
956
+ }
957
+
958
+ // Freshness: never hand back a dead relay reservation.
959
+ const maxAgeMs = opts.maxAgeMs ?? DEFAULT_PEER_RECORD_MAX_AGE_MS;
960
+ if (!isPeerRecordFresh(record.updatedAt, maxAgeMs, Date.now())) {
961
+ log('resolvePeerAddrs: record for %s is stale (updatedAt=%d, maxAgeMs=%d)', peerId, record.updatedAt, maxAgeMs);
962
+ return [];
963
+ }
964
+
965
+ // Pluggable trust gate (defaults to current-member).
966
+ const trustPolicy = opts.trustPolicy ?? currentMemberTrustPolicy();
967
+ const trusted = await trustPolicy.evaluate({
968
+ peerId,
969
+ publicKey: record.publicKey,
970
+ partyId: this.partyId,
971
+ record,
972
+ });
973
+ if (!trusted) {
974
+ log('resolvePeerAddrs: trust policy rejected %s', peerId);
975
+ return [];
976
+ }
977
+
978
+ // Order signaling-first (the on-record order was what we verified above),
979
+ // optionally restrict to signaling addrs, then parse — dropping any addr
980
+ // that does not parse as a multiaddr.
981
+ let addrs = orderSignalingFirst(record.addrs);
982
+ if (opts.signalingOnly) {
983
+ addrs = addrs.filter(isSignalingAddr);
984
+ }
985
+ return this.parseMultiaddrs(addrs);
986
+ }
987
+
988
+ /** Parse multiaddr strings, dropping (and logging) any that fail to parse. */
989
+ private parseMultiaddrs(addrs: string[]): Multiaddr[] {
990
+ const out: Multiaddr[] = [];
991
+ for (const addr of addrs) {
992
+ try {
993
+ out.push(multiaddr(addr));
994
+ } catch (error) {
995
+ log('resolvePeerAddrs: dropping unparsable multiaddr %s: %o', addr, error);
996
+ }
997
+ }
998
+ return out;
999
+ }
1000
+
1001
+ // ============================================================================
1002
+ // Proactive control-cohort dial
1003
+ //
1004
+ // The control collections only replicate once a party's nodes are
1005
+ // transport-connected (so FRET seats each peer in the others' keyspace cohort)
1006
+ // AND a write happens while that cohort has ≥2 members. There is no production
1007
+ // mechanism that makes a party's control nodes actively connect to each other;
1008
+ // the convergence test does it by hand with a manual dial(). reconcileControlCohort
1009
+ // productionizes that: each node resolves its known siblings' control addresses
1010
+ // and proactively dials a bounded, backbone-preferential set, re-observing and
1011
+ // re-dialing dropped connections on each pass. See docs/architecture.md (Control
1012
+ // Network) and control-cohort.ts for the selection policy.
1013
+ // ============================================================================
1014
+
1015
+ /**
1016
+ * Run one proactive control-cohort dial pass to keep this node connected to its
1017
+ * cadre siblings (so the `CadreControl` collections form a replicating cohort).
1018
+ * Public so the cohort-growth-driven re-replication path
1019
+ * (`control-write-ensure-replicated`) and tests can trigger a pass on demand;
1020
+ * normally driven by the eager start pass, the recurring interval, and
1021
+ * `self:peer:update` (all wired in {@link startRecordRefresh}).
1022
+ *
1023
+ * Concurrent triggers collapse into a single in-flight pass
1024
+ * (see {@link reconcileControlCohortInFlight}) so two passes never double-dial.
1025
+ * Best-effort throughout: a failure to resolve/dial any one sibling is logged
1026
+ * and the pass continues; the whole pass is a no-op when the node is alone.
1027
+ */
1028
+ async reconcileControlCohort(): Promise<void> {
1029
+ if (this.reconcileControlCohortInFlight) {
1030
+ return this.reconcileControlCohortInFlight;
1031
+ }
1032
+ const op = this.runReconcileControlCohort();
1033
+ this.reconcileControlCohortInFlight = op;
1034
+ try {
1035
+ await op;
1036
+ } finally {
1037
+ this.reconcileControlCohortInFlight = null;
1038
+ }
1039
+ }
1040
+
1041
+ /** Body of {@link reconcileControlCohort}; serialised by its single-flight guard. */
1042
+ private async runReconcileControlCohort(): Promise<void> {
1043
+ // Shutdown / not-yet-started guard (mirrors publishSelfRecord). A pass that
1044
+ // fires after stop() began must early-return rather than touch a torn-down node.
1045
+ if (!this._running || !this.controlNode || !this.controlDatabase) {
1046
+ return;
1047
+ }
1048
+ const selfPeerId = this.controlNode.peerId.toString();
1049
+
1050
+ // 1. Enumerate known siblings. This membership read is itself a pull-on-read
1051
+ // that helps the CadrePeer table converge — a reader-only node converges
1052
+ // purely by these reads.
1053
+ const members = await this.listMembers();
1054
+ const siblings = members.filter((m) => m.peerId !== selfPeerId);
1055
+ if (siblings.length === 0) {
1056
+ // Genuinely alone (cold start with no rows, or a solo cadre): nothing to
1057
+ // dial. Must not throw or busy-loop.
1058
+ return;
1059
+ }
1060
+ // Re-guard after the await: a stop() may have raced the membership read.
1061
+ if (!this._running || !this.controlNode || !this.controlDatabase) {
1062
+ return;
1063
+ }
1064
+
1065
+ // 2. Classify backbone (authority) members and select a bounded dial set.
1066
+ const authorityKeys = await this.controlDatabase.getAuthorityKeys();
1067
+ if (!this._running || !this.controlNode) {
1068
+ return;
1069
+ }
1070
+ const targetDegree = this.config.network?.controlCohort?.targetDegree
1071
+ ?? DEFAULT_CONTROL_COHORT_TARGET_DEGREE;
1072
+ const { dials, cappedNonAuthority } = selectControlCohortDials(siblings, authorityKeys, targetDegree);
1073
+ if (cappedNonAuthority > 0) {
1074
+ // Don't silently bound coverage — surface what the out-degree cap dropped.
1075
+ log('reconcileControlCohort: capped %d non-authority sibling(s) at targetDegree=%d',
1076
+ cappedNonAuthority, targetDegree);
1077
+ }
1078
+
1079
+ // 3. Skip already-connected peers (no re-dial / churn for live connections).
1080
+ const connected = new Set(this.controlNode.getConnections().map((c) => c.remotePeer.toString()));
1081
+
1082
+ // 4. Resolve + dial each selected, not-yet-connected sibling, best-effort.
1083
+ let dialed = 0;
1084
+ for (const sibling of dials) {
1085
+ if (!this._running || !this.controlNode) {
1086
+ return;
1087
+ }
1088
+ if (connected.has(sibling.peerId)) {
1089
+ continue;
1090
+ }
1091
+ if (await this.dialControlSibling(sibling)) {
1092
+ dialed++;
1093
+ }
1094
+ }
1095
+ log('reconcileControlCohort: pass complete (siblings=%d, selected=%d, dialed=%d)',
1096
+ siblings.length, dials.length, dialed);
1097
+ }
1098
+
1099
+ /**
1100
+ * Resolve one sibling's control-network dial addresses and dial it, best-effort.
1101
+ * Returns whether a dial was attempted (false when no address resolves).
1102
+ *
1103
+ * A per-peer failure (NAT, offline, relay down, connection-gater denial) is
1104
+ * logged and swallowed so one unreachable sibling never aborts the pass —
1105
+ * exactly like {@link SeedBootstrapService.applySeed}'s authority-dial loop. A
1106
+ * failed dial is simply retried on the next pass.
1107
+ */
1108
+ private async dialControlSibling(sibling: CohortPeerRow): Promise<boolean> {
1109
+ const controlNode = this.controlNode;
1110
+ if (!controlNode) {
1111
+ return false;
1112
+ }
1113
+ const addrs = await this.resolveControlDialAddrs(sibling.peerId);
1114
+ if (addrs.length === 0) {
1115
+ log('reconcileControlCohort: no dialable control address for sibling %s; skipping', sibling.peerId);
1116
+ return false;
1117
+ }
1118
+ try {
1119
+ log('reconcileControlCohort: dialing sibling %s (%d addr(s))', sibling.peerId, addrs.length);
1120
+ await controlNode.dial(addrs);
1121
+ return true;
1122
+ } catch (error) {
1123
+ log('reconcileControlCohort: dial of sibling %s failed (continuing): %o', sibling.peerId, error);
1124
+ return false;
1125
+ }
1126
+ }
1127
+
1128
+ /**
1129
+ * Resolve a sibling's control-network dial addresses for the reconcile pass.
1130
+ *
1131
+ * Primary (steady state): the signed, fresh, trust-gated control addresses from
1132
+ * the converged `CadrePeer` record via {@link resolvePeerAddrs}. Fallback (cold
1133
+ * start): the libp2p peerStore entries `applySeed` populated, used only while the
1134
+ * record is not yet resolvable. Returns `[]` (never throws) when neither yields
1135
+ * an address — that sibling is skipped this pass.
1136
+ */
1137
+ private async resolveControlDialAddrs(peerId: string): Promise<Multiaddr[]> {
1138
+ const resolved = await this.resolvePeerAddrs(peerId);
1139
+ if (resolved.length > 0) {
1140
+ return resolved;
1141
+ }
1142
+ return this.peerStoreAddrs(peerId);
1143
+ }
1144
+
1145
+ /**
1146
+ * Cold-start fallback: the libp2p peerStore multiaddrs for `peerId` (seeded by
1147
+ * {@link SeedBootstrapService.applySeed}). Returns `[]` on a missing entry or any
1148
+ * parse/lookup failure — never throws.
1149
+ */
1150
+ private async peerStoreAddrs(peerId: string): Promise<Multiaddr[]> {
1151
+ if (!this.controlNode) {
1152
+ return [];
1153
+ }
1154
+ try {
1155
+ const peer = await this.controlNode.peerStore.get(peerIdFromString(peerId));
1156
+ // Re-parse through the top-level multiaddr parser so the returned type matches
1157
+ // resolvePeerAddrs (the peerStore bundles its own @multiformats/multiaddr copy).
1158
+ return this.parseMultiaddrs(peer.addresses.map((a) => a.multiaddr.toString()));
1159
+ } catch (error) {
1160
+ log('reconcileControlCohort: peerStore lookup for %s failed: %o', peerId, error);
1161
+ return [];
1162
+ }
1163
+ }
1164
+
1165
+ // ============================================================================
1166
+ // Write-while-alone re-replication (control-write-ensure-replicated)
1167
+ //
1168
+ // Optimystic's coordinator commits a control write WITHOUT broadcasting when the
1169
+ // block's cluster has ≤1 member. An authority that authorizes/removes a peer or
1170
+ // (re)publishes its own record while no sibling is connected therefore writes a
1171
+ // row that exists ONLY in its local control DB — a sibling that connects later
1172
+ // never observes it (pull-on-read routes to the block's cluster, which never
1173
+ // learned of the write). reconcileControlCohort shrinks the alone window but
1174
+ // cannot close it (a write in the instant before any sibling connects is still
1175
+ // local-only). The remedy: detect "wrote while alone" (0 connections is a sound
1176
+ // lower bound), queue the affected row, and RE-ISSUE the write once the cohort
1177
+ // grows (0→≥1 connection), as an idempotent monotonic update that now broadcasts.
1178
+ // See docs/architecture.md (Control Network → write-while-alone durability).
1179
+ // ============================================================================
1180
+
1181
+ /**
1182
+ * Whether a control write happening now would commit local-only. A sound lower
1183
+ * bound is "no connected control peers": 0 connections ⇒ the block's cluster is
1184
+ * ≤1 ⇒ Optimystic commits without broadcasting. This is the pragmatic proxy for
1185
+ * the precise signal (the block's `getClusterSize`); it over-approximates safely
1186
+ * — a connected-but-not-in-this-block's-cluster write may still be local-only and
1187
+ * is caught by the cohort's periodic pull-on-read instead. Re-issuing an already-
1188
+ * replicated row is harmless (an idempotent monotonic bump), so the coarse proxy
1189
+ * is acceptable as the agreed first cut.
1190
+ */
1191
+ private committedAlone(): boolean {
1192
+ return (this.controlNode?.getConnections().length ?? 0) === 0;
1193
+ }
1194
+
1195
+ /**
1196
+ * Record (or clear) a just-committed authority membership write in the
1197
+ * write-while-alone re-replication queue. If the control node had no connections
1198
+ * at commit, the Optimystic write was local-only and must be re-issued once the
1199
+ * cohort grows; otherwise the write replicated and any stale queue entry for this
1200
+ * subject is dropped.
1201
+ *
1202
+ * A `remove` that commits alone is a security-relevant durability gap (a revoked
1203
+ * peer may persist as a member elsewhere), so it is logged loudly — and, because
1204
+ * a physical delete leaves no local trace to re-issue from, its on-growth
1205
+ * re-issue is best-effort only (see {@link drainPendingPeerWrites}).
1206
+ */
1207
+ private noteControlWrite(peerId: string, kind: 'authorize' | 'remove'): void {
1208
+ if (!this.committedAlone()) {
1209
+ this.pendingPeerWrites.delete(peerId);
1210
+ return;
1211
+ }
1212
+ this.pendingPeerWrites.set(peerId, kind);
1213
+ if (kind === 'remove') {
1214
+ log('removePeer(%s) committed while ALONE (0 control connections): the deletion is ' +
1215
+ 'local-only, so a revoked peer may persist in the cohort until re-replication. The ' +
1216
+ 'on-growth re-issue is best-effort (a physical delete cannot be replayed without a ' +
1217
+ 'schema tombstone — see control-delete-while-alone-tombstone).', peerId);
1218
+ } else {
1219
+ log('authorizePeer(%s) committed while alone (0 control connections); queued for ' +
1220
+ 're-replication on cohort growth', peerId);
1221
+ }
1222
+ }
1223
+
1224
+ /**
1225
+ * Drain the write-while-alone re-replication queue: re-issue the writes that
1226
+ * committed local-only now that the cohort can broadcast them. Public so the
1227
+ * 0→≥1 growth trigger ({@link handleControlConnectionChange}) and tests can drive
1228
+ * it; concurrent calls collapse into one in-flight drain
1229
+ * ({@link drainControlReplicationInFlight}) so two growth signals never
1230
+ * double-issue. Best-effort throughout — a per-row failure leaves that entry
1231
+ * queued for the next growth rather than aborting the drain.
1232
+ */
1233
+ async drainPendingControlReplication(reason: string): Promise<void> {
1234
+ if (this.drainControlReplicationInFlight) {
1235
+ return this.drainControlReplicationInFlight;
1236
+ }
1237
+ const op = this.runDrainControlReplication(reason);
1238
+ this.drainControlReplicationInFlight = op;
1239
+ try {
1240
+ await op;
1241
+ } finally {
1242
+ this.drainControlReplicationInFlight = null;
1243
+ }
1244
+ }
1245
+
1246
+ /** Body of {@link drainPendingControlReplication}; serialised by its single-flight guard. */
1247
+ private async runDrainControlReplication(reason: string): Promise<void> {
1248
+ // Shutdown / not-yet-started guard (mirrors runReconcileControlCohort).
1249
+ if (!this._running || !this.controlNode || !this.controlDatabase) {
1250
+ return;
1251
+ }
1252
+ const firstGrowth = !this.reconstructedLocalOnlyWrites;
1253
+ log('Draining control re-replication (reason=%s, firstGrowth=%s, pendingPeers=%d, self=%s, deviceToken=%s)',
1254
+ reason, firstGrowth, this.pendingPeerWrites.size, this.pendingSelfPeerWrite, this.pendingSelfDeviceWrite);
1255
+
1256
+ // 1. Self rows. On the first growth always re-touch (covers a self row carried
1257
+ // over from a prior process that committed local-only before this start);
1258
+ // afterwards only when a self-write-while-alone was recorded this session.
1259
+ // registerSelf is idempotent + single-flight, so this never races a
1260
+ // duplicate publish with the heartbeat republish.
1261
+ if (firstGrowth || this.pendingSelfPeerWrite) {
1262
+ await this.registerSelf().catch((error) => log('drain: registerSelf failed: %o', error));
1263
+ this.pendingSelfPeerWrite = false;
1264
+ }
1265
+ if (firstGrowth || this.pendingSelfDeviceWrite) {
1266
+ await this.retouchSelfDeviceToken();
1267
+ this.pendingSelfDeviceWrite = false;
1268
+ }
1269
+
1270
+ // 2. First growth: an authority reconstructs membership rows it may have
1271
+ // authored that never replicated (covers writes from before this process
1272
+ // started). Rows already tracked in the in-memory queue are handled by
1273
+ // step 3 — skipped here to avoid a double re-touch.
1274
+ if (firstGrowth) {
1275
+ this.reconstructedLocalOnlyWrites = true;
1276
+ await this.reconstructAuthoredMembership();
1277
+ }
1278
+
1279
+ // 3. In-session pending authority membership writes (authorize / remove).
1280
+ await this.drainPendingPeerWrites();
1281
+ }
1282
+
1283
+ /**
1284
+ * Re-touch this node's own `DeviceToken` row (re-sign + bump `UpdatedAt` via
1285
+ * {@link registerDeviceToken}) so a self device-token that committed local-only
1286
+ * re-broadcasts on cohort growth. No-op when no row exists (nothing to
1287
+ * re-replicate) or the stored platform is unknown. Best-effort — never throws to
1288
+ * the drain.
1289
+ */
1290
+ private async retouchSelfDeviceToken(): Promise<void> {
1291
+ if (!this._running || !this.controlNode || !this.controlDatabase) {
1292
+ return;
1293
+ }
1294
+ const peerId = this.controlNode.peerId.toString();
1295
+ try {
1296
+ const existing = await this.controlDatabase.queryDeviceToken(peerId);
1297
+ if (!existing || !isPushPlatform(existing.platform)) {
1298
+ return;
1299
+ }
1300
+ await this.registerDeviceToken(existing.platform, existing.token);
1301
+ } catch (error) {
1302
+ log('drain: retouch self DeviceToken failed: %o', error);
1303
+ }
1304
+ }
1305
+
1306
+ /**
1307
+ * One-shot, first-cohort-growth reconstruction of the write-while-alone queue for
1308
+ * an AUTHORITY node: re-touch every membership row that may be an unreplicated
1309
+ * authority insert. A row is a candidate iff it is not self (handled by
1310
+ * {@link registerSelf}), is not already tracked in the in-memory queue (handled by
1311
+ * {@link drainPendingPeerWrites}), and carries no self-`Sig` yet (an
1312
+ * authority-authored row the peer has not self-published — the only kind safe to
1313
+ * bump without invalidating a self-signature). O(rows) on the small control
1314
+ * tables; safe to over-apply (a monotonic authority bump on an already-replicated
1315
+ * row is a no-op-equivalent).
1316
+ *
1317
+ * A node with no authority private key skips this entirely — it cannot re-sign
1318
+ * rows for other peers, and rows it merely holds are not its to re-issue. DELETEs
1319
+ * cannot be reconstructed here (a removed row leaves no local trace and the schema
1320
+ * carries no tombstone) — see the delete-path note in {@link drainPendingPeerWrites}.
1321
+ */
1322
+ private async reconstructAuthoredMembership(): Promise<void> {
1323
+ if (!this.controlDatabase || !this.controlNode) {
1324
+ return;
1325
+ }
1326
+ if (!this.seedBootstrapService?.canAuthorize()) {
1327
+ return;
1328
+ }
1329
+ const selfPeerId = this.controlNode.peerId.toString();
1330
+ const members = await this.controlDatabase.queryCadrePeers();
1331
+ let touched = 0;
1332
+ for (const member of members) {
1333
+ if (!this._running || !this.controlNode || !this.controlDatabase) {
1334
+ return;
1335
+ }
1336
+ if (member.peerId === selfPeerId || this.pendingPeerWrites.has(member.peerId)) {
1337
+ continue;
1338
+ }
1339
+ try {
1340
+ const record = await this.controlDatabase.queryPeerRecord(member.peerId);
1341
+ // Missing (raced a delete) or peer-owned (self-Sig present) → not ours to bump.
1342
+ if (!record || record.sig) {
1343
+ continue;
1344
+ }
1345
+ await this.reissuePeerAuthorize(member.peerId, record.updatedAt);
1346
+ touched++;
1347
+ } catch (error) {
1348
+ log('drain: reconstruction re-touch of %s failed (continuing): %o', member.peerId, error);
1349
+ }
1350
+ }
1351
+ if (touched > 0) {
1352
+ log('drain: reconstructed %d authority-authored membership row(s) on first cohort growth', touched);
1353
+ }
1354
+ }
1355
+
1356
+ /**
1357
+ * Drain the in-session write-while-alone queue: re-issue each pending authority
1358
+ * membership write now that the cohort can broadcast it. Sequential (no fan-out)
1359
+ * to avoid a thundering re-touch; an entry is cleared only on success, so a
1360
+ * failure (or a still-alone re-commit) leaves it queued for the next growth.
1361
+ *
1362
+ * - `authorize`: re-issue as an idempotent monotonic authority UPDATE
1363
+ * ({@link reissuePeerAuthorize}). Skipped (and cleared) if the row vanished
1364
+ * (raced a delete) or now carries a self-`Sig` (the peer self-published and owns
1365
+ * its republish).
1366
+ * - `remove` (security-relevant): a removePeer-while-alone physically removed the
1367
+ * row locally, so a re-issued DELETE matches nothing and does NOT propagate —
1368
+ * full delete durability requires a schema tombstone (deferred:
1369
+ * `control-delete-while-alone-tombstone`). We still attempt the re-issue
1370
+ * (harmless, and it propagates in the row-still-present case); the commit-alone
1371
+ * was already logged loudly in {@link noteControlWrite}.
1372
+ */
1373
+ private async drainPendingPeerWrites(): Promise<void> {
1374
+ if (this.pendingPeerWrites.size === 0) {
1375
+ return;
1376
+ }
1377
+ if (!this.seedBootstrapService?.canAuthorize()) {
1378
+ // A non-authority node cannot have authored these writes; drop any stray entries.
1379
+ this.pendingPeerWrites.clear();
1380
+ return;
1381
+ }
1382
+ for (const [peerId, kind] of [...this.pendingPeerWrites]) {
1383
+ if (!this._running || !this.controlNode || !this.controlDatabase) {
1384
+ return;
1385
+ }
1386
+ try {
1387
+ if (kind === 'authorize') {
1388
+ const record = await this.controlDatabase.queryPeerRecord(peerId);
1389
+ if (!record || record.sig) {
1390
+ // Removed since, or peer self-published — nothing for the authority to re-issue.
1391
+ this.pendingPeerWrites.delete(peerId);
1392
+ continue;
1393
+ }
1394
+ await this.reissuePeerAuthorize(peerId, record.updatedAt);
1395
+ } else {
1396
+ // Best-effort delete re-issue (see method doc): propagates only if the row
1397
+ // is somehow still present locally.
1398
+ await this.seedBootstrapService.removePeer(peerId);
1399
+ }
1400
+ this.pendingPeerWrites.delete(peerId);
1401
+ } catch (error) {
1402
+ log('drain: re-issue of %s (%s) failed; leaving queued for next growth: %o', peerId, kind, error);
1403
+ }
1404
+ }
1405
+ }
1406
+
1407
+ /**
1408
+ * Re-issue an authority membership row as a monotonic authority UPDATE: bump
1409
+ * `UpdatedAt` strictly above the stored value (and the wall clock) and re-sign via
1410
+ * the authority branch of `CadrePeer.AuthorizedUpdate`. The row already exists
1411
+ * locally (it committed there, just local-only), so this is an UPDATE, not the
1412
+ * original INSERT.
1413
+ */
1414
+ private async reissuePeerAuthorize(peerId: string, currentUpdatedAt: number): Promise<void> {
1415
+ if (!this.seedBootstrapService) {
1416
+ return;
1417
+ }
1418
+ const updatedAt = Math.max(Date.now(), (currentUpdatedAt ?? 0) + 1);
1419
+ await this.seedBootstrapService.reauthorizePeer(peerId, updatedAt);
1420
+ }
1421
+
1422
+ /**
1423
+ * On a control connection opening, detect the 0→≥1 transition and drain the
1424
+ * write-while-alone re-replication queue (single-flight; fires only on the edge,
1425
+ * not on every subsequent `connection:open`). Best-effort — a drain failure is
1426
+ * logged, not thrown.
1427
+ */
1428
+ private handleControlConnectionChange(): void {
1429
+ if (!this._running || !this.controlNode) {
1430
+ return;
1431
+ }
1432
+ const connected = this.controlNode.getConnections().length > 0;
1433
+ if (!connected || this.hasControlConnection) {
1434
+ return;
1435
+ }
1436
+ this.hasControlConnection = true;
1437
+ log('Control cohort grew (0 → ≥1 connection); draining write-while-alone re-replication queue');
1438
+ void this.drainPendingControlReplication('connection:open')
1439
+ .catch((error) => log('Control re-replication drain (connection:open) failed: %o', error));
1440
+ }
1441
+
1442
+ /** Re-arm the growth edge once all control connections drop, so a later reconnect re-drains. */
1443
+ private handleControlConnectionClose(): void {
1444
+ if (!this.controlNode) {
1445
+ return;
1446
+ }
1447
+ if (this.controlNode.getConnections().length === 0) {
1448
+ this.hasControlConnection = false;
1449
+ }
1450
+ }
1451
+
1452
+ /**
1453
+ * Wire the control-connection growth listeners that drive write-while-alone
1454
+ * re-replication. Wired in {@link start} (not the delayed refresh path) so no
1455
+ * early `connection:open` is missed; torn down in {@link stopRecordRefresh}.
1456
+ * Idempotent.
1457
+ */
1458
+ private wireControlConnectionListeners(): void {
1459
+ if (!this.controlNode || this.controlConnectionOpenHandler) {
1460
+ return;
1461
+ }
1462
+ this.controlConnectionOpenHandler = () => this.handleControlConnectionChange();
1463
+ this.controlConnectionCloseHandler = () => this.handleControlConnectionClose();
1464
+ this.controlNode.addEventListener('connection:open', this.controlConnectionOpenHandler);
1465
+ this.controlNode.addEventListener('connection:close', this.controlConnectionCloseHandler);
1466
+
1467
+ // TURN-relay detection: tag/untag peers whose WebRTC ICE used a TURN candidate.
1468
+ this.turnConnectionOpenHandler = (evt) => this.handleTurnConnectionOpen(evt.detail);
1469
+ this.turnConnectionCloseHandler = (evt) => this.handleTurnConnectionClose(evt.detail);
1470
+ this.controlNode.addEventListener('connection:open', this.turnConnectionOpenHandler);
1471
+ this.controlNode.addEventListener('connection:close', this.turnConnectionCloseHandler);
1472
+ }
1473
+
1474
+ /**
1475
+ * On a control connection opening: if it is a WebRTC connection, drain the TURN
1476
+ * tracker for the just-settled ICE verdict and, when it relayed, mark the peer
1477
+ * so {@link getConnectionPaths} classifies it `webrtc-turn` (relayed). The
1478
+ * settlement↔open correlation is timing-based and best-effort; an unknown
1479
+ * verdict degrades to not-relayed. Never throws to the event loop.
1480
+ */
1481
+ private handleTurnConnectionOpen(conn: Connection): void {
1482
+ try {
1483
+ const addr = conn.remoteAddr?.toString() ?? '';
1484
+ // Only a genuine `/webrtc` (ICE) session can be TURN-relayed and promoted to
1485
+ // webrtc-turn. Use the classifier (which checks `/webrtc-direct` first) rather
1486
+ // than a bare substring — `'/webrtc-direct'.includes('/webrtc')` is true, and a
1487
+ // webrtc-direct open must not drain a settlement meant for a real webrtc dial.
1488
+ if (classifyTransport(addr).transport !== 'webrtc') {
1489
+ return;
1490
+ }
1491
+ if (this.turnTracker.consume(TURN_CONSUME_WINDOW_MS) === true) {
1492
+ const peerId = conn.remotePeer.toString();
1493
+ this.turnRelayedPeers.add(peerId);
1494
+ log('TURN-relayed WebRTC connection detected for peer %s', peerId);
1495
+ }
1496
+ } catch (error) {
1497
+ log('handleTurnConnectionOpen failed: %o', error);
1498
+ }
1499
+ }
1500
+
1501
+ /** On a control connection closing, drop any TURN-relayed flag for its peer. */
1502
+ private handleTurnConnectionClose(conn: Connection): void {
1503
+ try {
1504
+ this.turnRelayedPeers.delete(conn.remotePeer.toString());
1505
+ } catch (error) {
1506
+ log('handleTurnConnectionClose failed: %o', error);
1507
+ }
1508
+ }
1509
+
1510
+ // ============================================================================
1511
+ // Device-token registry (control-network push-token publish + resolve)
1512
+ //
1513
+ // The control network is the only network a hibernating peer keeps connected,
1514
+ // so it is where a mobile peer self-publishes its FCM/APNs push token and where
1515
+ // a server peer resolves it to deliver a push-wake to a suspended app. The write
1516
+ // + gate paths mirror registerSelf / resolvePeerAddrs (see DeviceToken in
1517
+ // control-schema.ts and device-token.ts).
1518
+ // ============================================================================
1519
+
1520
+ /**
1521
+ * Publish (or refresh) this node's own self-signed `DeviceToken` row so a server
1522
+ * peer can resolve its FCM/APNs push token from its PeerId alone. Mirrors
1523
+ * {@link registerSelf}:
1524
+ *
1525
+ * - If the row already exists: a self-signed UPDATE bumping `UpdatedAt` (works
1526
+ * for any member — the `AuthorizedUpdate` self-branch verifies the new `Sig`
1527
+ * against the bound `CadrePeer.PublicKey`). Platform/Token may change here
1528
+ * (rotation / platform switch / reinstall are all normal self-updates).
1529
+ * - If not, and the node holds an authority service: an authority-signed INSERT
1530
+ * that also carries the self-signature.
1531
+ * - Otherwise: throws. Like `CadrePeer`, the first `DeviceToken` row requires an
1532
+ * authority signature; a non-authority peer (e.g. a phone) must have its row
1533
+ * seeded by an authority — typically the server it enrolled with — before it
1534
+ * can self-refresh. (Establishing that phone→server registration handshake is
1535
+ * the downstream "RN registration" ticket; this node only owns the cadre-core
1536
+ * write path.)
1537
+ *
1538
+ * `UpdatedAt` strictly increases on every publish (even a same-millisecond
1539
+ * re-publish), so a replayed older record is rejected by the schema.
1540
+ *
1541
+ * @param platform - `'fcm'` (Android/Firebase) or `'apns'` (Apple).
1542
+ * @param token - the opaque platform device/registration token.
1543
+ * @throws if the node is not started, exposes no self-signing key, or has no
1544
+ * existing row and no authority service to self-insert.
1545
+ */
1546
+ async registerDeviceToken(platform: PushPlatform, token: string): Promise<void> {
1547
+ if (!this._running || !this.controlNode || !this.controlDatabase) {
1548
+ throw new Error('CadreNode must be started before registering a device token');
1549
+ }
1550
+ const signingKey = this.getSelfSigningKey();
1551
+ if (!signingKey) {
1552
+ throw new Error(
1553
+ 'Cannot register device token: no self-signing key available ' +
1554
+ '(node identity unavailable or not matching the node PeerId).'
1555
+ );
1556
+ }
1557
+
1558
+ const peerId = this.controlNode.peerId.toString();
1559
+ const existing = await this.controlDatabase.queryDeviceToken(peerId);
1560
+ // Strictly increase UpdatedAt even on a same-millisecond re-publish (rotation).
1561
+ const updatedAt = Math.max(Date.now(), (existing?.updatedAt ?? 0) + 1);
1562
+ const record = signDeviceTokenRecord(
1563
+ { peerId, platform, token, updatedAt },
1564
+ signingKey.privateKeyB64
1565
+ );
1566
+
1567
+ if (existing) {
1568
+ await this.controlDatabase.updateSelfDeviceToken(record);
1569
+ if (this.committedAlone()) this.pendingSelfDeviceWrite = true;
1570
+ log('registerDeviceToken: refreshed own DeviceToken (platform=%s, updatedAt=%d)', platform, updatedAt);
1571
+ return;
1572
+ }
1573
+ if (this.seedBootstrapService) {
1574
+ await this.seedBootstrapService.insertSelfDeviceToken(record);
1575
+ if (this.committedAlone()) this.pendingSelfDeviceWrite = true;
1576
+ log('registerDeviceToken: inserted own DeviceToken (authority-signed, platform=%s, updatedAt=%d)', platform, updatedAt);
1577
+ return;
1578
+ }
1579
+ throw new Error(
1580
+ `Cannot register device token for ${peerId}: no existing row to self-update and no ` +
1581
+ 'authority service to self-insert. An authority must seed this peer\'s DeviceToken ' +
1582
+ 'row first (mirrors CadrePeer enrollment).'
1583
+ );
1584
+ }
1585
+
1586
+ /**
1587
+ * Resolve a cadre peer's FCM/APNs push token from only its PeerId — the input a
1588
+ * server's push-wake fan-out consumes to deliver a platform push to a suspended
1589
+ * app. Applies the same gating shape as {@link resolvePeerAddrs}, returning
1590
+ * `null` (never throwing) on any failure:
1591
+ *
1592
+ * 1. membership — the peer has a `CadrePeer` row with a `PublicKey`,
1593
+ * 2. `publicKey <-> peerId` binding — the stored key's libp2p identity is the
1594
+ * requested peerId,
1595
+ * 3. a `DeviceToken` row exists with a known {@link PushPlatform},
1596
+ * 4. self-signature verifies against the bound `CadrePeer.PublicKey`,
1597
+ * 5. freshness — `updatedAt` is positive and within `opts.maxAgeMs` (default:
1598
+ * no ceiling, since a push token is valid until it rotates).
1599
+ *
1600
+ * A peer that is not a current member, or whose token has no backing `CadrePeer`
1601
+ * record, resolves to `null` — a server must not attempt to push to a non-cadre
1602
+ * peer.
1603
+ */
1604
+ async resolveDeviceToken(peerId: string, opts: ResolveDeviceTokenOpts = {}): Promise<DeviceTokenRecord | null> {
1605
+ if (!this.controlDatabase) {
1606
+ throw new Error('CadreNode must be started before resolving a device token');
1607
+ }
1608
+
1609
+ // Membership + publicKey<->peerId binding: read the peer's CadrePeer row and
1610
+ // confirm the stored key is the one embedded in the requested Ed25519 peer id.
1611
+ const peerRecord = await this.controlDatabase.queryPeerRecord(peerId);
1612
+ if (!peerRecord || !peerRecord.publicKey) {
1613
+ log('resolveDeviceToken: no CadrePeer/PublicKey for %s', peerId);
1614
+ return null;
1615
+ }
1616
+ if (ed25519PublicKeyB64FromPeerId(peerId) !== peerRecord.publicKey) {
1617
+ log('resolveDeviceToken: publicKey does not match peerId for %s', peerId);
1618
+ return null;
1619
+ }
1620
+
1621
+ const record = await this.controlDatabase.queryDeviceToken(peerId);
1622
+ if (!record) {
1623
+ log('resolveDeviceToken: no device token for %s', peerId);
1624
+ return null;
1625
+ }
1626
+ if (!isPushPlatform(record.platform)) {
1627
+ log('resolveDeviceToken: unknown platform %s for %s', record.platform, peerId);
1628
+ return null;
1629
+ }
1630
+
1631
+ // Self-signature over (peerId, platform, token, updatedAt), verified against the
1632
+ // CadrePeer.PublicKey bound to this peerId.
1633
+ if (!verifyDeviceTokenSignature(record, peerRecord.publicKey)) {
1634
+ log('resolveDeviceToken: signature verification failed for %s', peerId);
1635
+ return null;
1636
+ }
1637
+
1638
+ // Freshness: a positive stamp, optionally bounded. No ceiling by default — a
1639
+ // suspended phone's token must stay resolvable for push-wake long after publish.
1640
+ const maxAgeMs = opts.maxAgeMs ?? Number.POSITIVE_INFINITY;
1641
+ if (!isPeerRecordFresh(record.updatedAt, maxAgeMs, Date.now())) {
1642
+ log('resolveDeviceToken: record for %s is stale (updatedAt=%d, maxAgeMs=%d)', peerId, record.updatedAt, maxAgeMs);
1643
+ return null;
1644
+ }
1645
+
1646
+ return record;
1647
+ }
1648
+
1649
+ /**
1650
+ * Delete this node's own `DeviceToken` row (logout / token invalidation). No-op
1651
+ * when no row exists. Like {@link registerDeviceToken}'s first insert, the delete
1652
+ * is gated on an authority signature (`DeviceToken.AuthorizedInsert` covers insert
1653
+ * AND delete), so it requires this node's authority service; a non-authority peer
1654
+ * must route the clear through its authority (downstream RN registration path).
1655
+ *
1656
+ * @throws if the node is not started, or a row exists but no authority service is
1657
+ * available to sign the delete.
1658
+ */
1659
+ async clearDeviceToken(): Promise<void> {
1660
+ if (!this._running || !this.controlNode || !this.controlDatabase) {
1661
+ throw new Error('CadreNode must be started before clearing a device token');
1662
+ }
1663
+ const peerId = this.controlNode.peerId.toString();
1664
+ const existing = await this.controlDatabase.queryDeviceToken(peerId);
1665
+ if (!existing) {
1666
+ log('clearDeviceToken: no DeviceToken row for %s; no-op', peerId);
1667
+ return;
1668
+ }
1669
+ if (!this.seedBootstrapService) {
1670
+ throw new Error(
1671
+ `Cannot clear device token for ${peerId}: delete requires an authority signature ` +
1672
+ 'and no authority service is initialized.'
1673
+ );
1674
+ }
1675
+ await this.seedBootstrapService.deleteDeviceToken(peerId);
1676
+ log('clearDeviceToken: deleted DeviceToken for %s', peerId);
1677
+ }
1678
+
1679
+ /**
1680
+ * Expire ANOTHER peer's stale `DeviceToken` after a platform reported it
1681
+ * unregistered during a push-wake fan-out. Unlike {@link clearDeviceToken}
1682
+ * (self-only — it hardcodes the local peerId), this takes an arbitrary peerId.
1683
+ *
1684
+ * - When this node holds an authority seed service, it deletes the row
1685
+ * (`deleteDeviceToken` is authority-gated and accepts any peerId), so the peer
1686
+ * is not retried until it re-registers.
1687
+ * - When this node is NOT an authority it cannot delete the row, so it only logs
1688
+ * that a re-registration is needed. The fan-out's own in-memory dead-token set
1689
+ * is what actually stops re-pushing to the dead token this process — see
1690
+ * {@link PushFanoutService}. That set is acceptably lossy across restarts (a
1691
+ * restart re-learns staleness on the next failed send).
1692
+ *
1693
+ * Best-effort: never throws to the (best-effort) fan-out caller.
1694
+ */
1695
+ async expireDeviceToken(peerId: string): Promise<void> {
1696
+ if (this.seedBootstrapService) {
1697
+ try {
1698
+ await this.seedBootstrapService.deleteDeviceToken(peerId);
1699
+ log('expireDeviceToken: authority-deleted stale DeviceToken for %s', peerId);
1700
+ } catch (error) {
1701
+ log('expireDeviceToken: authority delete for %s failed: %o', peerId, error);
1702
+ }
1703
+ return;
1704
+ }
1705
+ log('expireDeviceToken: %s token is stale but this node is not an authority; re-registration required', peerId);
1706
+ }
1707
+
1708
+ private async handleStrandAdded(strand: StrandRow): Promise<void> {
1709
+ log('Handling strand added from control network: %s', strand.Id);
1710
+
1711
+ // Check if we have sApp config for this strand
1712
+ const sAppConfig = this.sAppConfigs.get(strand.Id);
1713
+ if (!sAppConfig) {
1714
+ log('No sAppConfig registered for strand %s - emitting strand:discovered', strand.Id);
1715
+ // Strand created by another member and not yet configured locally. Surface
1716
+ // it as a discovery event so the hosting app can decide whether to join
1717
+ // (register a config + addStrand); the strand-agnostic seam keeps this
1718
+ // class free of any app's join policy. A self-configured strand (config
1719
+ // already present) keeps auto-starting below, unchanged.
1720
+ this.emit('strand:discovered', { strandId: strand.Id, strand });
1721
+ return;
1722
+ }
1723
+
1724
+ try {
1725
+ // Discovery path: no explicit mode — infer from cohort membership.
1726
+ await this.launchStrand(strand, sAppConfig);
1727
+ } catch (error) {
1728
+ log('Error starting strand %s: %o', strand.Id, error);
1729
+ this.emit('strand:error', {
1730
+ strandId: strand.Id,
1731
+ error: error instanceof Error ? error : new Error(String(error))
1732
+ });
1733
+ }
1734
+ }
1735
+
1736
+ private async handleStrandRemoved(strandId: string): Promise<void> {
1737
+ log('Handling strand removed: %s', strandId);
1738
+
1739
+ try {
1740
+ // Untrack from hibernation
1741
+ this.hibernationManager.untrackStrand(strandId);
1742
+
1743
+ // Remove sApp config
1744
+ this.sAppConfigs.delete(strandId);
1745
+
1746
+ await this.strandManager.stopStrand(strandId);
1747
+ this.emit('strand:stopped', { strandId });
1748
+ } catch (error) {
1749
+ log('Error stopping strand %s: %o', strandId, error);
1750
+ this.emit('strand:error', {
1751
+ strandId,
1752
+ error: error instanceof Error ? error : new Error(String(error))
1753
+ });
1754
+ }
1755
+ }
1756
+
1757
+ private async cleanup(): Promise<void> {
1758
+ // Resolve + clear any in-flight wake windows first, so an in-flight check-in
1759
+ // or serviceWake unblocks and tears down cleanly rather than firing a stale
1760
+ // window timer (or hanging) after the strand manager is stopped below.
1761
+ this.clearWindowWaiters();
1762
+
1763
+ // Stop self-record refresh timers + address-change listener (before the
1764
+ // control node is torn down, so removeEventListener has a live target).
1765
+ this.stopRecordRefresh();
1766
+
1767
+ // Restore the wrapped globalThis.RTCPeerConnection and drop TURN-relay state.
1768
+ this.turnTracker.dispose();
1769
+ this.turnRelayedPeers.clear();
1770
+
1771
+ // Stop hibernation manager
1772
+ this.hibernationManager.stop();
1773
+
1774
+ // Stop seed bootstrap service
1775
+ if (this.seedBootstrapService) {
1776
+ await this.seedBootstrapService.shutdown();
1777
+ this.seedBootstrapService = null;
1778
+ }
1779
+
1780
+ // Stop strand wake service (unregister the WAKE_PROTOCOL handler)
1781
+ if (this.strandWakeService) {
1782
+ await this.strandWakeService.shutdown();
1783
+ this.strandWakeService = null;
1784
+ }
1785
+
1786
+ // Stop strand-addr service (unregister the STRAND_ADDR_PROTOCOL handler so a
1787
+ // restart does not hit DuplicateProtocolHandlerError).
1788
+ if (this.strandAddrService) {
1789
+ await this.strandAddrService.shutdown();
1790
+ this.strandAddrService = null;
1791
+ }
1792
+
1793
+ // Tear down the push-wake fan-out (releases the notifier's APNs HTTP/2 session).
1794
+ if (this.pushFanoutService) {
1795
+ await this.pushFanoutService.close().catch((err) => log('Push fan-out close failed: %o', err));
1796
+ this.pushFanoutService = null;
1797
+ }
1798
+
1799
+ // Unregister strand solicitation service
1800
+ if (this.strandSolicitationService && this.controlNode) {
1801
+ this.strandSolicitationService.unregisterResponder(this.controlNode);
1802
+ this.strandSolicitationService = null;
1803
+ }
1804
+
1805
+ // Stop strand watcher
1806
+ if (this.strandWatcher) {
1807
+ await this.strandWatcher.stop();
1808
+ this.strandWatcher = null;
1809
+ }
1810
+
1811
+ // Stop all strand instances
1812
+ await this.strandManager.stopAll();
1813
+
1814
+ // Clear sApp configs
1815
+ this.sAppConfigs.clear();
1816
+
1817
+ // Close control database (this also shuts down the collection factory)
1818
+ if (this.controlDatabase) {
1819
+ await this.controlDatabase.close();
1820
+ this.controlDatabase = null;
1821
+ }
1822
+
1823
+ // Stop control node
1824
+ if (this.controlNode) {
1825
+ await this.controlNode.stop();
1826
+ this.controlNode = null;
1827
+ }
1828
+ }
1829
+
1830
+ // Hibernation callbacks
1831
+ private async handleStrandIdle(strandId: string): Promise<void> {
1832
+ const instance = this.strandManager.getInstance(strandId);
1833
+ if (instance) {
1834
+ instance.status = 'idle';
1835
+ log('Strand %s transitioned to idle', strandId);
1836
+ this.emit('strand:idle', { strandId });
1837
+ }
1838
+ }
1839
+
1840
+ /**
1841
+ * Hibernate a strand: release its strand-network resources via the strand
1842
+ * manager (stop the libp2p node, close the StrandDatabase) and mark it
1843
+ * `hibernating`. A quiesced strand holds no open strand-network connections,
1844
+ * transports, or DB handles. No-ops if the strand is missing; if already
1845
+ * quiesced (defensive), just marks status and emits.
1846
+ */
1847
+ private async handleStrandHibernate(strandId: string): Promise<void> {
1848
+ const instance = this.strandManager.getInstance(strandId);
1849
+ if (!instance) {
1850
+ log('handleStrandHibernate: strand %s not found', strandId);
1851
+ return;
1852
+ }
1853
+
1854
+ if (!instance.libp2pNode && !instance.database) {
1855
+ // Already quiesced — only the status flag needs updating.
1856
+ instance.status = 'hibernating';
1857
+ log('Strand %s already quiesced; marked hibernating', strandId);
1858
+ this.emit('strand:hibernating', { strandId });
1859
+ return;
1860
+ }
1861
+
1862
+ log('Hibernating strand %s — releasing strand-network resources', strandId);
1863
+ await this.strandManager.quiesceStrand(strandId);
1864
+ instance.status = 'hibernating';
1865
+ this.emit('strand:hibernating', { strandId });
1866
+ log('Strand %s hibernating (resources released)', strandId);
1867
+ }
1868
+
1869
+ /**
1870
+ * Wake a strand. If it was hibernating (quiesced — no libp2p node), re-resolve
1871
+ * the cohort discovery seed and mode exactly as `launchStrand` does and rebuild
1872
+ * its runtime via the strand manager. If it is still live (e.g. waking an idle
1873
+ * strand, which retains its resources), just flip the status. Overlapping wake
1874
+ * triggers are coalesced upstream by `HibernationManager`, so this runs once
1875
+ * per wake; `resumeStrand` is itself idempotent as a backstop.
1876
+ */
1877
+ private async handleStrandWake(strandId: string): Promise<void> {
1878
+ const instance = this.strandManager.getInstance(strandId);
1879
+ if (!instance) {
1880
+ log('handleStrandWake: strand %s not found', strandId);
1881
+ return;
1882
+ }
1883
+
1884
+ // Still live (idle wake, or defensive double-wake): no rebuild needed.
1885
+ if (instance.libp2pNode || instance.database) {
1886
+ instance.status = 'active';
1887
+ instance.lastActivity = new Date();
1888
+ log('Strand %s woke (already live)', strandId);
1889
+ this.emit('strand:waking', { strandId });
1890
+ return;
1891
+ }
1892
+
1893
+ // Quiesced: re-resolve volatile cohort inputs (the seed may have grown, the
1894
+ // mode may have shifted bootstrap → networked) and rebuild the runtime.
1895
+ log('Waking strand %s — rebuilding strand-network resources', strandId);
1896
+ await this.resumeStrandRuntime(strandId);
1897
+ instance.lastActivity = new Date();
1898
+ this.emit('strand:waking', { strandId });
1899
+ log('Strand %s awake (resources rebuilt)', strandId);
1900
+ }
1901
+
1902
+ /**
1903
+ * Rebuild a quiesced strand's runtime, re-resolving the volatile cohort inputs
1904
+ * first: the discovery seed may have grown and cohort membership may have
1905
+ * shifted the mode `bootstrap → networked` since the strand last ran. Shared by
1906
+ * the wake (`handleStrandWake`) and check-in (`handleStrandCheckIn`) paths so
1907
+ * both apply the same fresh seed/mode resolution. `resumeStrand` is idempotent
1908
+ * (returns the live instance unchanged) as a backstop against double-resume.
1909
+ */
1910
+ private async resumeStrandRuntime(strandId: string): Promise<void> {
1911
+ const seed = await this.resolveCohortSeed(strandId);
1912
+ const mode = selectStrandMode(undefined, seed.hasOtherPeers);
1913
+ await this.strandManager.resumeStrand(strandId, {
1914
+ bootstrapNodes: seed.bootstrapNodes,
1915
+ mode
1916
+ });
1917
+ }
1918
+
1919
+ /**
1920
+ * Real cohort check-in for a hibernating strand (the `onCheckIn` callback).
1921
+ *
1922
+ * Optimystic syncs pull-on-read, not on connect, and exposes no cheap
1923
+ * repo-level "pull pending" hook (`IRepo` is get/pend/commit/cancel only —
1924
+ * see the review handoff). So "query the cohort for pending activity" is
1925
+ * realized as a resume → bounded window → re-hibernate-if-idle cycle that
1926
+ * reuses the existing quiesce/resume primitives rather than a bespoke probe:
1927
+ *
1928
+ * 1. Resume the strand (rebuild node + db, re-resolve cohort seed/mode) so
1929
+ * its strand network can reach cohort peers — exactly as a wake does.
1930
+ * 2. Hold it resumed for a bounded window, during which the app may drive
1931
+ * reads (pull-on-read) and record activity.
1932
+ * 3. If activity was recorded during the window, leave the strand `active`
1933
+ * (the idle/hibernate timers + backoff reset take over). Otherwise
1934
+ * quiesce again and leave it `hibernating`, so `HibernationManager`
1935
+ * schedules the next, longer-delayed check-in.
1936
+ *
1937
+ * No-ops unless the strand is currently `hibernating` — a concurrent wake may
1938
+ * have already resumed it.
1939
+ */
1940
+ private async handleStrandCheckIn(strandId: string): Promise<void> {
1941
+ const instance = this.strandManager.getInstance(strandId);
1942
+ if (!instance) {
1943
+ log('handleStrandCheckIn: strand %s not found', strandId);
1944
+ return;
1945
+ }
1946
+ if (instance.status !== 'hibernating') {
1947
+ log('handleStrandCheckIn: strand %s not hibernating (status=%s); skipping', strandId, instance.status);
1948
+ return;
1949
+ }
1950
+
1951
+ try {
1952
+ // 1. Resume exactly as a wake does: re-resolve the (possibly grown) cohort
1953
+ // seed + mode, then rebuild the runtime.
1954
+ log('Check-in: resuming strand %s to probe the cohort for pending activity', strandId);
1955
+ await this.resumeStrandRuntime(strandId);
1956
+
1957
+ // 2-3. Bounded window for the strand network to connect + the app to act,
1958
+ // then re-hibernate-if-idle. Shared with the on-demand serviceWake.
1959
+ const windowMs = this.config.hibernation?.checkInWindowMs ?? DEFAULT_CHECKIN_WINDOW_MS;
1960
+ await this.runWakeWindow(instance, windowMs);
1961
+ } catch (err) {
1962
+ // A check-in that throws part-way — resume failing on a flaky network (the
1963
+ // very scenario hibernation targets), the window rejecting, or quiesce
1964
+ // throwing — must leave the strand HIBERNATING, not in the `error` status
1965
+ // that `resumeStrand` sets on failure. `HibernationManager.runCheckIn`
1966
+ // decides wake-vs-escalate purely from `instance.status` after this
1967
+ // resolves: an `error` status reads as "woke", which STOPS the check-in
1968
+ // chain and strands the strand with no runtime and no future check-in.
1969
+ // Forcing it back to `hibernating` (after a best-effort quiesce to release
1970
+ // any partially-rebuilt runtime) makes the manager escalate the backoff and
1971
+ // retry on the next tick.
1972
+ log('Check-in failed for strand %s; re-hibernating to retry on backoff: %o', strandId, err);
1973
+ await this.strandManager.quiesceStrand(strandId).catch((cleanupErr) => {
1974
+ log('Check-in cleanup quiesce for strand %s failed: %o', strandId, cleanupErr);
1975
+ });
1976
+ instance.status = 'hibernating';
1977
+ }
1978
+ }
1979
+
1980
+ /**
1981
+ * Window-then-decide for a just-resumed strand, shared by the check-in timer
1982
+ * path ({@link handleStrandCheckIn}) and the on-demand {@link serviceWake}:
1983
+ *
1984
+ * 1. Capture the post-resume activity marker. `recordActivity` assigns a
1985
+ * FRESH `Date`, so a changed reference after the window means real
1986
+ * activity landed during it — not millisecond-resolution noise.
1987
+ * 2. Hold the strand live for `windowMs` so its strand network reaches the
1988
+ * cohort and the app can drive pull-on-read activity.
1989
+ * 3. If activity landed, leave the strand `active` (return `true`); otherwise
1990
+ * quiesce and mark it `hibernating` again (return `false`).
1991
+ *
1992
+ * @returns whether activity was observed during the window (strand left active).
1993
+ */
1994
+ private async runWakeWindow(instance: StrandInstance, windowMs: number): Promise<boolean> {
1995
+ const strandId = instance.strandId;
1996
+ const activityMark = instance.lastActivity;
1997
+
1998
+ await this.holdWakeWindow(instance, windowMs);
1999
+
2000
+ const sawActivity = instance.lastActivity !== activityMark;
2001
+ if (sawActivity) {
2002
+ instance.status = 'active';
2003
+ this.emit('strand:waking', { strandId });
2004
+ log('Wake window: strand %s saw activity during the window; staying active', strandId);
2005
+ return true;
2006
+ }
2007
+
2008
+ log('Wake window: no activity for strand %s; re-hibernating', strandId);
2009
+ await this.strandManager.quiesceStrand(strandId);
2010
+ instance.status = 'hibernating';
2011
+ return false;
2012
+ }
2013
+
2014
+ /**
2015
+ * Hold a just-resumed strand live for `windowMs` (default
2016
+ * {@link DEFAULT_CHECKIN_WINDOW_MS} is applied by callers). A non-positive
2017
+ * window resolves immediately. The pending timer is tracked in
2018
+ * {@link windowWaiters} so {@link cleanup} can both clear it and resolve the
2019
+ * promise on teardown — a `stop()` during an in-flight window must neither fire
2020
+ * the timer afterward nor hang the awaiting check-in/serviceWake. Extracted as
2021
+ * its own method so tests can stub the wait (and inject activity during it).
2022
+ */
2023
+ private async holdWakeWindow(_instance: StrandInstance, windowMs: number): Promise<void> {
2024
+ if (windowMs <= 0) return;
2025
+ await new Promise<void>((resolve) => {
2026
+ const waiter = { timer: undefined as unknown as ReturnType<typeof setTimeout>, resolve };
2027
+ waiter.timer = setTimeout(() => {
2028
+ this.windowWaiters.delete(waiter);
2029
+ resolve();
2030
+ }, windowMs);
2031
+ this.windowWaiters.add(waiter);
2032
+ });
2033
+ }
2034
+
2035
+ /**
2036
+ * Clear every in-flight wake window: cancel its timer and resolve its promise
2037
+ * so any awaiting check-in/serviceWake completes promptly rather than hanging
2038
+ * past teardown. Called from {@link cleanup}.
2039
+ */
2040
+ private clearWindowWaiters(): void {
2041
+ for (const waiter of this.windowWaiters) {
2042
+ clearTimeout(waiter.timer);
2043
+ waiter.resolve();
2044
+ }
2045
+ this.windowWaiters.clear();
2046
+ }
2047
+
2048
+ /**
2049
+ * Add a strand with its sApp configuration.
2050
+ * The hosting application must provide the sApp schema when creating a strand.
2051
+ */
2052
+ async addStrand(config: StrandConfig): Promise<StrandInstance> {
2053
+ if (!this._running) {
2054
+ throw new Error('CadreNode not running');
2055
+ }
2056
+
2057
+ const { strandRow, sAppConfig, mode, founder } = config;
2058
+
2059
+ // Store sApp config for this strand
2060
+ this.sAppConfigs.set(strandRow.Id, sAppConfig);
2061
+ log('Registered sAppConfig for strand %s (sApp: %s, mode: %s, founder: %s)',
2062
+ strandRow.Id, sAppConfig.id, mode ?? 'inferred', founder ?? false);
2063
+
2064
+ // Pass `mode` (possibly undefined) through: an explicit mode wins, while a
2065
+ // caller that omits it gets the same cohort-inferred mode as the discovery path.
2066
+ // `founder` only flows from the explicit addStrand path — the control-discovered
2067
+ // join path never founds, so its rows arrive via sync (see handleStrandAdded).
2068
+ return await this.launchStrand(strandRow, sAppConfig, mode, founder);
2069
+ }
2070
+
2071
+ /**
2072
+ * Publish a strand row to the shared control database under this node's own
2073
+ * authority identity, so other cadre members discover it via control-network
2074
+ * sync (their {@link StrandWatcher} fires `strand:discovered`).
2075
+ *
2076
+ * This is the authority-signed `Strand` INSERT that {@link addStrand}
2077
+ * deliberately omits: `addStrand` only starts the LOCAL strand instance,
2078
+ * whereas publishing makes the strand visible cadre-wide. A typical creator
2079
+ * does both (start locally + publish); a discovering peer only does
2080
+ * `addStrand` (the row already exists).
2081
+ *
2082
+ * The insert is signed with the ed25519 key behind this node's PeerId — which
2083
+ * {@link authorityKeyFromLibp2p} also exposes as the node's authority keypair,
2084
+ * so peer identity and authority key are one and the same. That key must be
2085
+ * enrolled in `AuthorityKey` (e.g. via {@link ControlDatabase.ensureAuthorityKey}
2086
+ * at genesis) or the schema's `Strand.Authorized` constraint rejects the write.
2087
+ * Failing loudly here is intentional: a silently-unpublished strand would run
2088
+ * as a local-only island that no peer could ever discover or join.
2089
+ *
2090
+ * @param strandId - Unique strand identifier (typically the same id passed to
2091
+ * {@link addStrand}).
2092
+ * @param type - `'o'` for open (default) or `'c'` for closed.
2093
+ * @param memberPrivateKey - Optional membership key for a closed strand.
2094
+ * @throws if the node is not started, exposes no authority signing key, or the
2095
+ * control DB rejects the (unauthorized) insert.
2096
+ */
2097
+ async publishStrand(strandId: string, type: 'o' | 'c' = 'o', memberPrivateKey?: string): Promise<void> {
2098
+ if (!this._running || !this.controlDatabase) {
2099
+ throw new Error('CadreNode must be started before publishing a strand');
2100
+ }
2101
+ const signingKey = this.getSelfSigningKey();
2102
+ if (!signingKey) {
2103
+ throw new Error(
2104
+ `Cannot publish strand ${strandId}: no authority signing key available ` +
2105
+ '(node identity is unavailable or does not match the node PeerId). Run authority ' +
2106
+ 'genesis (ensureAuthorityKey + initializeSeedBootstrap) before publishing.'
2107
+ );
2108
+ }
2109
+ // insertStrand hands this callback the canonical row-bound message BYTES (see
2110
+ // buildAuthorizationMessage); ed25519-sign them directly (no pre-hash) with
2111
+ // the authority private key, returning a base64url signature.
2112
+ const signMessage = (message: Uint8Array): string =>
2113
+ sign(message, signingKey.privateKeyB64, 'ed25519', 'bytes', 'base64url', 'base64url') as string;
2114
+ await this.controlDatabase.insertStrand(strandId, type, signingKey.publicKeyB64, signMessage, memberPrivateKey);
2115
+ log('Published strand %s (type %s) to control DB under authority %s', strandId, type, signingKey.publicKeyB64);
2116
+ }
2117
+
2118
+ /**
2119
+ * Publish an authority-signed `FormationInvite` (open-invitation token) to the
2120
+ * shared control database, so a later {@link formStrand} redemption can be
2121
+ * validated against it (the consent branch of `Strand.Authorized`).
2122
+ *
2123
+ * Counterpart to {@link createOpenInvitation}, which only mints the
2124
+ * out-of-band {@link OpenInvitation} envelope: persisting the matching
2125
+ * `FormationInvite` row is what makes the token *redeemable* — the host's
2126
+ * {@link ControlFormationUsageRecorder} answers `isTokenValid`/`isTokenUsed`
2127
+ * from this row. A host minting a closed-strand invite does both (mint +
2128
+ * publish), exactly as the integration harness's `createInvitation` does.
2129
+ *
2130
+ * Signs with the same self-authority key as {@link publishStrand} (the ed25519
2131
+ * key behind this node's PeerId, which must be an enrolled `AuthorityKey`).
2132
+ * Throws loudly if the node isn't started or exposes no signing key.
2133
+ *
2134
+ * @param token - Invitation token (the `FormationInvite` primary key); use the
2135
+ * `token` of the {@link OpenInvitation} from {@link createOpenInvitation}.
2136
+ * @param sAppId - The sApp a redeemed strand will use.
2137
+ * @param options - Optional `expiresAtMs` (epoch ms), `totalUses`, `validationUrl`,
2138
+ * `strandId` (bind a closed/pre-existing host strand for provision-then-record).
2139
+ */
2140
+ async publishFormationInvite(
2141
+ token: string,
2142
+ sAppId: string,
2143
+ options: { expiresAtMs?: number; totalUses?: number; validationUrl?: string; strandId?: string } = {}
2144
+ ): Promise<void> {
2145
+ if (!this._running || !this.controlDatabase) {
2146
+ throw new Error('CadreNode must be started before publishing a formation invite');
2147
+ }
2148
+ const signingKey = this.getSelfSigningKey();
2149
+ if (!signingKey) {
2150
+ throw new Error(
2151
+ `Cannot publish formation invite ${token}: no authority signing key available ` +
2152
+ '(node identity is unavailable or does not match the node PeerId). Run authority ' +
2153
+ 'genesis (ensureAuthorityKey + initializeSeedBootstrap) before publishing.'
2154
+ );
2155
+ }
2156
+ const signMessage = (message: Uint8Array): string =>
2157
+ sign(message, signingKey.privateKeyB64, 'ed25519', 'bytes', 'base64url', 'base64url') as string;
2158
+ await this.controlDatabase.insertFormationInvite(token, sAppId, signingKey.publicKeyB64, signMessage, options);
2159
+ log('Published formation invite %s (sApp %s) under authority %s', token, sAppId, signingKey.publicKeyB64);
2160
+ }
2161
+
2162
+ /**
2163
+ * Shared strand launch path for both the explicit (`addStrand`) and the
2164
+ * control-discovered (`handleStrandAdded`) entry points. Resolves the cohort
2165
+ * seed, selects the mode, starts the strand, and registers it with the
2166
+ * hibernation manager before emitting `strand:started`.
2167
+ */
2168
+ private async launchStrand(
2169
+ strand: StrandRow,
2170
+ sAppConfig: SAppConfig,
2171
+ explicitMode?: StrandMode,
2172
+ founder?: boolean
2173
+ ): Promise<StrandInstance> {
2174
+ const seed = await this.resolveCohortSeed(strand.Id);
2175
+ const mode = selectStrandMode(explicitMode, seed.hasOtherPeers);
2176
+
2177
+ const instance = await this.strandManager.startStrand({
2178
+ strandRow: strand,
2179
+ sAppConfig,
2180
+ storage: this.config.storage,
2181
+ network: this.config.network,
2182
+ profile: this.config.profile,
2183
+ defaultLatencyHint: this.config.hibernation?.defaultLatencyHint ?? 'interactive',
2184
+ privateKey: this.identityKey,
2185
+ bootstrapNodes: seed.bootstrapNodes,
2186
+ mode,
2187
+ requireSignedSchemas: this.config.requireSignedSchemas,
2188
+ founder
2189
+ });
2190
+
2191
+ this.hibernationManager.trackStrand(instance);
2192
+ this.emit('strand:started', { strandId: strand.Id });
2193
+ return instance;
2194
+ }
2195
+
2196
+ /**
2197
+ * Resolve a strand's discovery seed. Membership (and thus mode) comes from the
2198
+ * control network's CadrePeer rows; the **strand-network** bootstrap addresses
2199
+ * are resolved on demand over the control mesh via the strand-addr RPC —
2200
+ * deliberately NOT from `CadrePeer.Multiaddr`, which carries *control*
2201
+ * addresses that must not seed the strand mesh.
2202
+ *
2203
+ * Only siblings we already hold an open control connection to are RPC'd: they
2204
+ * are the ones that can answer right now, and dialing them by peerId reuses the
2205
+ * live connection. When no connected sibling yet runs the strand the seed is
2206
+ * empty (`[]`) — mode still follows membership, and the empty seed self-heals
2207
+ * on the next resume / check-in pass. Returns an empty seed when the control DB
2208
+ * or node is absent (not yet started / torn down).
2209
+ */
2210
+ private async resolveCohortSeed(strandId: string): Promise<CohortSeed> {
2211
+ if (!this.controlDatabase || !this.controlNode) {
2212
+ return { bootstrapNodes: [], hasOtherPeers: false };
2213
+ }
2214
+ const peers = await this.controlDatabase.queryCadrePeers();
2215
+ const { otherPeerIds, hasOtherPeers } =
2216
+ deriveCohortMembers(peers, this.controlNode.peerId.toString());
2217
+
2218
+ // RPC only siblings we already have a control connection to — they can answer
2219
+ // now, and `dialProtocol` by peerId reuses the open connection.
2220
+ const connected = new Set(this.controlNode.getConnections().map((c) => c.remotePeer.toString()));
2221
+ const targets = otherPeerIds.filter((id) => connected.has(id));
2222
+ const bootstrapNodes = targets.length
2223
+ ? await collectStrandAddrs(this.controlNode, targets.map((peerId) => ({ peerId })), strandId)
2224
+ : [];
2225
+ return { bootstrapNodes, hasOtherPeers };
2226
+ }
2227
+
2228
+ /**
2229
+ * The local strand instance's dialable strand-network multiaddrs for the
2230
+ * strand-addr RPC, ordered signaling-first (reusing the control node's
2231
+ * {@link orderSignalingFirst}). Returns `[]` when the strand is not running
2232
+ * locally or has no live libp2p node (hibernating / quiescing / never
2233
+ * participated) — a node only answers for a strand it is actively meshing,
2234
+ * regardless of the strand's mode. A `bootstrap`-mode first node still has a
2235
+ * live node, so it answers and a later sibling can dial in.
2236
+ */
2237
+ private getStrandMultiaddrs(strandId: string): string[] {
2238
+ const node = this.strandManager.getInstance(strandId)?.libp2pNode;
2239
+ if (!node) {
2240
+ return [];
2241
+ }
2242
+ return orderSignalingFirst(node.getMultiaddrs().map((ma) => ma.toString()));
2243
+ }
2244
+
2245
+ /**
2246
+ * Remove a strand
2247
+ */
2248
+ async removeStrand(strandId: string): Promise<void> {
2249
+ if (!this._running) {
2250
+ throw new Error('CadreNode not running');
2251
+ }
2252
+
2253
+ // Untrack from hibernation
2254
+ this.hibernationManager.untrackStrand(strandId);
2255
+
2256
+ // Remove sApp config
2257
+ this.sAppConfigs.delete(strandId);
2258
+
2259
+ await this.strandManager.stopStrand(strandId);
2260
+ this.emit('strand:stopped', { strandId });
2261
+ }
2262
+
2263
+ /**
2264
+ * Record activity on a strand (resets hibernation timer).
2265
+ *
2266
+ * Also drives the server push-wake fan-out: whatever already drives activity on
2267
+ * this node's strand (its relay/app layer doing pull-on-read) additionally wakes
2268
+ * hibernating mobile peers — the same imperative seam local-wake uses, with no
2269
+ * new contract. No-op for the fan-out when push is not configured.
2270
+ */
2271
+ recordStrandActivity(strandId: string): void {
2272
+ const instance = this.strandManager.getInstance(strandId);
2273
+ if (instance) {
2274
+ this.hibernationManager.recordActivity(instance);
2275
+ }
2276
+ this.notifyStrandActivity(strandId);
2277
+ }
2278
+
2279
+ /**
2280
+ * Explicit fan-out trigger: an always-on host/relay/sApp calls this when it
2281
+ * observes activity for a strand this node participates in, to wake hibernating
2282
+ * mobile members over a direct control-network dial (falling back to FCM/APNs
2283
+ * for suspended phones). This is the supported, honest v1 trigger — Optimystic
2284
+ * exposes no passive repo-level "new transaction" hook to drive it automatically
2285
+ * (see the deferred passive-detector follow-up). No-op when push is not
2286
+ * configured; best-effort (never throws — the check-in wake is the backstop).
2287
+ *
2288
+ * @param strandId - the strand that saw activity.
2289
+ * @param reason - free-form cause hint carried in the wake (default `activity`).
2290
+ */
2291
+ notifyStrandActivity(strandId: string, reason?: string): void {
2292
+ void this.pushFanoutService?.notify(strandId, reason);
2293
+ }
2294
+
2295
+ /**
2296
+ * Force wake a hibernating strand
2297
+ */
2298
+ async wakeStrand(strandId: string): Promise<void> {
2299
+ await this.hibernationManager.wakeStrand(strandId);
2300
+ }
2301
+
2302
+ // ============================================================================
2303
+ // Mobile background lifecycle primitives
2304
+ //
2305
+ // Imperative control a mobile BackgroundRunner drives from OS app-state and
2306
+ // push events, rather than from the internal idle/hibernate/check-in timers.
2307
+ // ============================================================================
2308
+
2309
+ /**
2310
+ * Force a single strand to hibernate immediately, bypassing the idle/hibernate
2311
+ * timers — the background-entry path. No-op if the strand is realtime
2312
+ * (never-hibernate latency hint), already hibernating, or unknown.
2313
+ *
2314
+ * Routes through {@link HibernationManager.forceHibernate}, which cancels the
2315
+ * strand's pending idle/hibernate (and check-in) timers — so a stale timer
2316
+ * can't re-fire on or resurrect the strand — then runs the same `onHibernate`
2317
+ * path as the timer (`quiesceStrand` + `status='hibernating'` +
2318
+ * `strand:hibernating`). Unlike the timer path it does NOT re-arm check-ins:
2319
+ * the strand stays down until the caller drives a wake (e.g. {@link serviceWake}).
2320
+ */
2321
+ async hibernateStrand(strandId: string): Promise<void> {
2322
+ const instance = this.strandManager.getInstance(strandId);
2323
+ if (!instance) {
2324
+ log('hibernateStrand: strand %s unknown; no-op', strandId);
2325
+ return;
2326
+ }
2327
+ if (!this.hibernationManager.hibernates(instance)) {
2328
+ log('hibernateStrand: strand %s is realtime; no-op', strandId);
2329
+ return;
2330
+ }
2331
+ if (instance.status === 'hibernating') {
2332
+ log('hibernateStrand: strand %s already hibernating; no-op', strandId);
2333
+ return;
2334
+ }
2335
+ await this.hibernationManager.forceHibernate(instance);
2336
+ }
2337
+
2338
+ /**
2339
+ * Force-hibernate every tracked strand whose latency hint is not realtime,
2340
+ * tolerating per-strand failure (one strand failing to quiesce never aborts
2341
+ * the others). Realtime strands are left running — the caller keeps the control
2342
+ * connection and realtime strands alive for as long as the OS permits.
2343
+ *
2344
+ * @returns the strandIds actually hibernated (now in `hibernating` status);
2345
+ * realtime strands are excluded.
2346
+ */
2347
+ async hibernateAll(): Promise<string[]> {
2348
+ const hibernated: string[] = [];
2349
+ for (const [strandId, instance] of this.strandManager.getInstances()) {
2350
+ if (!this.hibernationManager.hibernates(instance)) {
2351
+ log('hibernateAll: skipping realtime strand %s', strandId);
2352
+ continue;
2353
+ }
2354
+ try {
2355
+ await this.hibernateStrand(strandId);
2356
+ if (instance.status === 'hibernating') {
2357
+ hibernated.push(strandId);
2358
+ }
2359
+ } catch (error) {
2360
+ // Collect-and-continue: a single strand's quiesce failure must not strand
2361
+ // the rest of the background-entry sweep.
2362
+ log('hibernateAll: strand %s failed to hibernate (continuing): %o', strandId, error);
2363
+ }
2364
+ }
2365
+ log('hibernateAll: hibernated %d strand(s)', hibernated.length);
2366
+ return hibernated;
2367
+ }
2368
+
2369
+ /**
2370
+ * On-demand equivalent of a check-in cycle, for a push-delivered wake on
2371
+ * mobile: resume the strand, hold it live for `windowMs` so its strand network
2372
+ * reaches the cohort and the app can pull pending activity, then re-hibernate
2373
+ * if no activity was recorded (else leave it active).
2374
+ *
2375
+ * Idempotent / coalesced two ways: concurrent `serviceWake`s for the same
2376
+ * strand share one in-flight operation ({@link serviceWakePromises}), and the
2377
+ * underlying resume coalesces with a racing push-wake via
2378
+ * {@link HibernationManager}'s wake coalescing — one runtime build, one window,
2379
+ * one re-hibernate decision. Returns `{ serviced: false }` (never throws) when
2380
+ * the node is not running or the strand is unknown, and surfaces a resume
2381
+ * failure as `{ serviced: true, hadActivity: false }` after re-hibernating.
2382
+ *
2383
+ * @param strandId - the strand a push said has pending activity.
2384
+ * @param opts.windowMs - override the live-window duration (defaults to the
2385
+ * configured `checkInWindowMs` / {@link DEFAULT_CHECKIN_WINDOW_MS}).
2386
+ */
2387
+ async serviceWake(strandId: string, opts?: { windowMs?: number }): Promise<ServiceWakeResult> {
2388
+ const existing = this.serviceWakePromises.get(strandId);
2389
+ if (existing) {
2390
+ log('serviceWake: joining in-flight wake for strand %s', strandId);
2391
+ return existing;
2392
+ }
2393
+ const op = this.runServiceWake(strandId, opts);
2394
+ this.serviceWakePromises.set(strandId, op);
2395
+ try {
2396
+ return await op;
2397
+ } finally {
2398
+ this.serviceWakePromises.delete(strandId);
2399
+ }
2400
+ }
2401
+
2402
+ /** Body of {@link serviceWake}; serialised per-strand by its coalescing guard. */
2403
+ private async runServiceWake(strandId: string, opts?: { windowMs?: number }): Promise<ServiceWakeResult> {
2404
+ // Not-running / control-absent guard (mirrors pushWake): a background task
2405
+ // must get a branchable result, never a throw.
2406
+ if (!this._running || !this.controlNode) {
2407
+ log('serviceWake: node not running; not serviced (strand %s)', strandId);
2408
+ return { strandId, serviced: false, hadActivity: false };
2409
+ }
2410
+
2411
+ const instance = this.strandManager.getInstance(strandId);
2412
+ if (!instance) {
2413
+ log('serviceWake: strand %s unknown to this node; not serviced', strandId);
2414
+ return { strandId, serviced: false, hadActivity: false };
2415
+ }
2416
+
2417
+ // Already live (active or idle — both retain their runtime): servicing is a
2418
+ // no-op success. Do NOT run a window that would re-hibernate a strand the app
2419
+ // may be actively using, and do NOT rebuild a second runtime.
2420
+ if (instance.libp2pNode || instance.database) {
2421
+ log('serviceWake: strand %s already live; no-op success', strandId);
2422
+ return { strandId, serviced: true, hadActivity: true };
2423
+ }
2424
+
2425
+ try {
2426
+ // Coalesced resume: routes through wakeStrand → HibernationManager.beginWake
2427
+ // so a racing push-wake shares this single runtime build.
2428
+ await this.wakeStrand(strandId);
2429
+ const windowMs = opts?.windowMs ?? this.config.hibernation?.checkInWindowMs ?? DEFAULT_CHECKIN_WINDOW_MS;
2430
+ const hadActivity = await this.runWakeWindow(instance, windowMs);
2431
+ return { strandId, serviced: true, hadActivity };
2432
+ } catch (error) {
2433
+ // Resume failing mid-window (network unreachable inside a Doze grant, etc.)
2434
+ // must not throw out of a background task: re-hibernate and report no
2435
+ // activity, mirroring handleStrandCheckIn's re-hibernate-on-error.
2436
+ log('serviceWake: strand %s failed during wake window; re-hibernating: %o', strandId, error);
2437
+ await this.strandManager.quiesceStrand(strandId).catch((cleanupErr) => {
2438
+ log('serviceWake cleanup quiesce for strand %s failed: %o', strandId, cleanupErr);
2439
+ });
2440
+ instance.status = 'hibernating';
2441
+ return { strandId, serviced: true, hadActivity: false };
2442
+ }
2443
+ }
2444
+
2445
+ /**
2446
+ * Get the control network node (for advanced use)
2447
+ */
2448
+ getControlNode(): Libp2p | null {
2449
+ return this.controlNode;
2450
+ }
2451
+
2452
+ /**
2453
+ * Get the control database (for advanced queries)
2454
+ */
2455
+ getControlDatabase(): ControlDatabase | null {
2456
+ return this.controlDatabase;
2457
+ }
2458
+
2459
+ /**
2460
+ * Force a poll of the strand watcher (for testing)
2461
+ */
2462
+ async forceStrandPoll(): Promise<void> {
2463
+ await this.strandWatcher?.forcePoll();
2464
+ }
2465
+
2466
+ /**
2467
+ * Get the sApp configuration for a strand
2468
+ */
2469
+ getSAppConfig(strandId: string): SAppConfig | undefined {
2470
+ return this.sAppConfigs.get(strandId);
2471
+ }
2472
+
2473
+ // ============================================================================
2474
+ // Seed Bootstrap API
2475
+ // ============================================================================
2476
+
2477
+ /**
2478
+ * Initialize the seed bootstrap service with an authority key.
2479
+ * Must be called before using seed-related methods that require signing.
2480
+ *
2481
+ * @param authorityPrivateKey - The authority's private key (base64url encoded)
2482
+ */
2483
+ initializeSeedBootstrap(authorityPrivateKey: string): void {
2484
+ if (!this.controlNode || !this.controlDatabase) {
2485
+ throw new Error('CadreNode must be started before initializing seed bootstrap');
2486
+ }
2487
+
2488
+ this.seedBootstrapService = new SeedBootstrapService({
2489
+ partyId: this.config.controlNetwork.partyId,
2490
+ authorityPrivateKey,
2491
+ inviteAddressResolver: () => this.resolveInviteAddresses(),
2492
+ trustPolicy: this.config.seedTrustPolicy,
2493
+ });
2494
+
2495
+ this.seedBootstrapService.setEventCallbacks({
2496
+ onSeedReceived: (partyId, peerId) => this.emit('seed:received', { partyId, peerId }),
2497
+ onSeedApplied: (partyId, peersAdded) => this.emit('seed:applied', { partyId, peersAdded }),
2498
+ onSeedError: (partyId, error) => this.emit('seed:error', { partyId, error }),
2499
+ });
2500
+
2501
+ this.seedBootstrapService.initialize(this.controlNode, this.controlDatabase);
2502
+ log('Seed bootstrap service initialized');
2503
+ }
2504
+
2505
+ /**
2506
+ * Push the multiaddrs that future invites should advertise. Pass `null` to
2507
+ * revert to the libp2p-reported addresses (the default). The host calls this
2508
+ * at spawn and on every NAT change.
2509
+ */
2510
+ setInviteAddresses(addresses: string[] | null): void {
2511
+ this.latestInviteAddresses = addresses;
2512
+ log('Invite addresses updated: %s', addresses ? `${addresses.length} pushed` : 'cleared (libp2p fallback)');
2513
+ }
2514
+
2515
+ /**
2516
+ * Resolve the addresses to embed in invites. Prefers pushed addresses, then
2517
+ * any config-supplied resolver, then the libp2p-observed multiaddrs.
2518
+ */
2519
+ private async resolveInviteAddresses(): Promise<string[]> {
2520
+ if (this.latestInviteAddresses !== null) {
2521
+ return this.latestInviteAddresses;
2522
+ }
2523
+ if (this.config.network?.inviteAddressResolver) {
2524
+ return this.config.network.inviteAddressResolver();
2525
+ }
2526
+ return this.getMultiaddrs();
2527
+ }
2528
+
2529
+ /**
2530
+ * Enumerate the cadre's `CadrePeer` membership.
2531
+ */
2532
+ async listMembers(): Promise<Array<{ peerId: string; multiaddr: string | null }>> {
2533
+ if (!this.controlDatabase) {
2534
+ throw new Error('CadreNode must be started before listing members');
2535
+ }
2536
+ return this.controlDatabase.queryCadrePeers();
2537
+ }
2538
+
2539
+ /**
2540
+ * Probe whether a given peer is a `CadrePeer` member.
2541
+ */
2542
+ async isMember(peerId: string): Promise<boolean> {
2543
+ const members = await this.listMembers();
2544
+ return members.some(m => m.peerId === peerId);
2545
+ }
2546
+
2547
+ /**
2548
+ * Push-wake a hibernating cadre peer over the control network.
2549
+ *
2550
+ * Resolves the target's signed control-network address from its `CadrePeer`
2551
+ * record (via {@link resolvePeerAddrs}, signaling/relay first — so a NAT'd peer
2552
+ * is reachable through its circuit-relay address), dials `WAKE_PROTOCOL`, sends
2553
+ * the {@link WakeRequest}, and returns the peer's {@link WakeAck}. The receiver
2554
+ * gates the request on cadre membership and only resumes a strand it already
2555
+ * participates in.
2556
+ *
2557
+ * @param targetPeerId - The hibernating cadre peer to wake.
2558
+ * @param strandId - The strand the caller knows has pending activity.
2559
+ * @param reason - Optional cause hint, e.g. `"activity"` or `"manual"`.
2560
+ * @throws if the node is not started or the target has no dialable address.
2561
+ */
2562
+ async pushWake(targetPeerId: string, strandId: string, reason?: string): Promise<WakeAck> {
2563
+ if (!this.controlNode) {
2564
+ throw new Error('CadreNode must be started before pushing wakes');
2565
+ }
2566
+ const addrs = await this.resolvePeerAddrs(targetPeerId);
2567
+ if (addrs.length === 0) {
2568
+ throw new Error(`No dialable control-network address for peer ${targetPeerId}`);
2569
+ }
2570
+ const request: WakeRequest = { strandId, reason };
2571
+ return await dialWake(this.controlNode, addrs, request);
2572
+ }
2573
+
2574
+ /**
2575
+ * Enable the seed listener for receiving seeds via the /sereus/seed/1.0.0 protocol.
2576
+ * This is for drone nodes that need to receive seeds without being an authority.
2577
+ * Does not require an authority key.
2578
+ */
2579
+ enableSeedListener(): void {
2580
+ if (!this.controlNode || !this.controlDatabase) {
2581
+ throw new Error('CadreNode must be started before enabling seed listener');
2582
+ }
2583
+
2584
+ // Don't re-initialize if already has a service
2585
+ if (this.seedBootstrapService) {
2586
+ log('Seed bootstrap service already initialized');
2587
+ return;
2588
+ }
2589
+
2590
+ this.seedBootstrapService = new SeedBootstrapService({
2591
+ partyId: this.config.controlNetwork.partyId,
2592
+ // No authority key - this node only receives seeds
2593
+ inviteAddressResolver: () => this.resolveInviteAddresses(),
2594
+ trustPolicy: this.config.seedTrustPolicy,
2595
+ });
2596
+
2597
+ this.seedBootstrapService.setEventCallbacks({
2598
+ onSeedReceived: (partyId, peerId) => this.emit('seed:received', { partyId, peerId }),
2599
+ onSeedApplied: (partyId, peersAdded) => this.emit('seed:applied', { partyId, peersAdded }),
2600
+ onSeedError: (partyId, error) => this.emit('seed:error', { partyId, error }),
2601
+ });
2602
+
2603
+ this.seedBootstrapService.initialize(this.controlNode, this.controlDatabase);
2604
+ log('Seed listener enabled');
2605
+ }
2606
+
2607
+ /**
2608
+ * Get the seed bootstrap service (for advanced use)
2609
+ */
2610
+ getSeedBootstrapService(): SeedBootstrapService | null {
2611
+ return this.seedBootstrapService;
2612
+ }
2613
+
2614
+ /**
2615
+ * Authorize a new peer to join the cadre.
2616
+ * Signs the peer ID with the authority key and inserts into CadrePeer table.
2617
+ *
2618
+ * @param peerId - The peer ID to authorize
2619
+ * @param multiaddrs - Optional multiaddrs for the peer
2620
+ */
2621
+ async authorizePeer(peerId: string, multiaddrs?: string[]): Promise<void> {
2622
+ if (!this.seedBootstrapService) {
2623
+ throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
2624
+ }
2625
+ await this.seedBootstrapService.authorizePeer({ peerId, multiaddrs });
2626
+ // Queue for re-replication if this committed local-only (no connected cohort).
2627
+ this.noteControlWrite(peerId, 'authorize');
2628
+ }
2629
+
2630
+ /**
2631
+ * Remove a previously-authorized peer from the cadre.
2632
+ * Signs the peer ID with the authority key and deletes the CadrePeer row.
2633
+ *
2634
+ * @param peerId - The peer ID to remove
2635
+ */
2636
+ async removePeer(peerId: string): Promise<void> {
2637
+ if (!this.seedBootstrapService) {
2638
+ throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
2639
+ }
2640
+ await this.seedBootstrapService.removePeer(peerId);
2641
+ // Track + loudly flag a delete that committed local-only (security-relevant).
2642
+ this.noteControlWrite(peerId, 'remove');
2643
+ }
2644
+
2645
+ /**
2646
+ * Create a seed from the current control network state.
2647
+ * The seed contains peer information and is signed by an authority.
2648
+ */
2649
+ async createSeed(): Promise<ControlNetworkSeed> {
2650
+ if (!this.seedBootstrapService) {
2651
+ throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
2652
+ }
2653
+ return await this.seedBootstrapService.createSeed();
2654
+ }
2655
+
2656
+ /**
2657
+ * Apply a seed to populate the peer cache and enable connections.
2658
+ *
2659
+ * Validates the seed signature, then evaluates a trust anchor for the signer
2660
+ * key (see `SeedTrustPolicy`). An enrollment caller can pass a per-seed
2661
+ * `trustPolicy` override — e.g. a `pinnedKeyTrustPolicy` built from a
2662
+ * `CadreInvite.authorityKeys` — so a cold-start node can accept its first
2663
+ * seed without reconfiguring the service.
2664
+ */
2665
+ async applySeed(
2666
+ seed: ControlNetworkSeed,
2667
+ options?: { trustPolicy?: SeedTrustPolicy }
2668
+ ): Promise<ApplySeedResult> {
2669
+ if (!this.seedBootstrapService) {
2670
+ // Create a temporary service for applying seeds (doesn't need authority key).
2671
+ // partyId is the attacker-influenced seed.partyId — it only labels logs; the
2672
+ // trust decision rests solely on signerKey vs the anchor set (configured
2673
+ // default below, or the per-call options.trustPolicy override).
2674
+ //
2675
+ // This temp service is discarded after the call, so it must NOT own the shared
2676
+ // node's inbound seed handler: pass { registerHandler: false }. That keeps
2677
+ // repeated service-less applySeed/dialInvite idempotent (no handler leak, no
2678
+ // DuplicateProtocolHandlerError). The temp service still applies this seed; a
2679
+ // node that wants to RECEIVE inbound seeds needs a persistent service
2680
+ // (enableSeedListener / initializeSeedBootstrap) to own the handler.
2681
+ const tempService = new SeedBootstrapService({
2682
+ partyId: seed.partyId,
2683
+ trustPolicy: this.config.seedTrustPolicy,
2684
+ });
2685
+ if (this.controlNode && this.controlDatabase) {
2686
+ tempService.initialize(this.controlNode, this.controlDatabase, { registerHandler: false });
2687
+ }
2688
+ return await tempService.applySeed(seed, options);
2689
+ }
2690
+ return await this.seedBootstrapService.applySeed(seed, options);
2691
+ }
2692
+
2693
+ /**
2694
+ * Deliver a seed directly to a peer via the /sereus/seed/1.0.0 protocol.
2695
+ */
2696
+ async deliverSeed(targetMultiaddr: string, seed: ControlNetworkSeed): Promise<{ accepted: boolean; reason?: string }> {
2697
+ if (!this.seedBootstrapService) {
2698
+ throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
2699
+ }
2700
+ return await this.seedBootstrapService.deliverSeed(targetMultiaddr, seed);
2701
+ }
2702
+
2703
+ /**
2704
+ * Encode a seed for out-of-band delivery (e.g., QR code, copy/paste).
2705
+ */
2706
+ encodeSeed(seed: ControlNetworkSeed): string {
2707
+ // Static method - doesn't need service initialization
2708
+ const json = JSON.stringify(seed);
2709
+ return uint8ArrayToString(new TextEncoder().encode(json), 'base64url');
2710
+ }
2711
+
2712
+ /**
2713
+ * Decode a seed from base64url encoding.
2714
+ */
2715
+ decodeSeed(encoded: string): ControlNetworkSeed {
2716
+ // Static method - doesn't need service initialization
2717
+ const bytes = uint8ArrayFromString(encoded, 'base64url');
2718
+ const json = new TextDecoder().decode(bytes);
2719
+ return JSON.parse(json) as ControlNetworkSeed;
2720
+ }
2721
+
2722
+ /**
2723
+ * Get this node's circuit relay address for inclusion in seeds.
2724
+ * Returns null if no relay address is available.
2725
+ */
2726
+ async getRelayAddress(): Promise<string | null> {
2727
+ if (!this.controlNode) {
2728
+ return null;
2729
+ }
2730
+
2731
+ const addrs = this.controlNode.getMultiaddrs();
2732
+ const relayAddr = addrs.find(addr => addr.toString().includes('/p2p-circuit/'));
2733
+ return relayAddr?.toString() ?? null;
2734
+ }
2735
+
2736
+ // ============================================================================
2737
+ // Seed Bootstrap Helper Methods
2738
+ // ============================================================================
2739
+
2740
+ /**
2741
+ * Add a drone to the cadre (for phone/server adding provider-hosted node).
2742
+ * Creates authorization and seed for drone initialization.
2743
+ */
2744
+ async addDrone(options: AddDroneOptions): Promise<DroneInitResult> {
2745
+ if (!this.seedBootstrapService) {
2746
+ throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
2747
+ }
2748
+ return await this.seedBootstrapService.addDrone(options);
2749
+ }
2750
+
2751
+ /**
2752
+ * Create an invite for a phone to join the cadre.
2753
+ * Use when a server wants to invite a NAT'd phone.
2754
+ */
2755
+ async createInvite(token?: string, expiresIn?: number): Promise<InviteResult> {
2756
+ if (!this.seedBootstrapService) {
2757
+ throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
2758
+ }
2759
+ return await this.seedBootstrapService.createInvite(token, expiresIn);
2760
+ }
2761
+
2762
+ /**
2763
+ * Accept a phone connection using an invite.
2764
+ * Call this when a phone dials in with an invite token.
2765
+ */
2766
+ async acceptPhone(options: AddPhoneOptions, issuedInvite?: CadreInvite): Promise<void> {
2767
+ if (!this.seedBootstrapService) {
2768
+ throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
2769
+ }
2770
+ await this.seedBootstrapService.acceptPhone(options, issuedInvite);
2771
+ }
2772
+
2773
+ /**
2774
+ * Add a phone to the cadre with relay support.
2775
+ * Use when both nodes are NAT'd (phone-to-phone).
2776
+ */
2777
+ async addPhoneWithRelay(phonePeerId: string): Promise<DroneInitResult> {
2778
+ if (!this.seedBootstrapService) {
2779
+ throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
2780
+ }
2781
+ return await this.seedBootstrapService.addPhoneWithRelay(phonePeerId);
2782
+ }
2783
+
2784
+ /**
2785
+ * Encode an invite for out-of-band delivery (QR, link, etc.).
2786
+ */
2787
+ encodeInvite(invite: CadreInvite): string {
2788
+ const json = JSON.stringify(invite);
2789
+ return uint8ArrayToString(new TextEncoder().encode(json), 'base64url');
2790
+ }
2791
+
2792
+ /**
2793
+ * Decode an invite from base64url encoding.
2794
+ */
2795
+ decodeInvite(encoded: string): CadreInvite {
2796
+ const bytes = uint8ArrayFromString(encoded, 'base64url');
2797
+ const json = new TextDecoder().decode(bytes);
2798
+ return JSON.parse(json) as CadreInvite;
2799
+ }
2800
+
2801
+ /**
2802
+ * Dial an authority from an invite (for phone joining via invite).
2803
+ */
2804
+ async dialInvite(invite: CadreInvite): Promise<void> {
2805
+ if (!this.seedBootstrapService) {
2806
+ // Create a temporary service that only dials the invite. It is discarded after
2807
+ // the call, so it does NOT own the shared node's inbound seed handler:
2808
+ // initialize with { registerHandler: false }. This temp dialInvite never
2809
+ // applies a seed itself — a node that wants to RECEIVE an inbound seed back
2810
+ // must have a persistent service (enableSeedListener / initializeSeedBootstrap)
2811
+ // own the /sereus/seed/1.0.0 handler. trustPolicy is therefore effectively dead
2812
+ // on this dial-only path; it is kept for symmetry with the applySeed temp site.
2813
+ const tempService = new SeedBootstrapService({
2814
+ partyId: invite.partyId,
2815
+ trustPolicy: this.config.seedTrustPolicy,
2816
+ });
2817
+ if (this.controlNode && this.controlDatabase) {
2818
+ tempService.initialize(this.controlNode, this.controlDatabase, { registerHandler: false });
2819
+ }
2820
+ await tempService.dialInvite(invite);
2821
+ return;
2822
+ }
2823
+ await this.seedBootstrapService.dialInvite(invite);
2824
+ }
2825
+
2826
+ // ============================================================================
2827
+ // Strand Solicitation API (native cadre-core formation transport)
2828
+ // ============================================================================
2829
+
2830
+ /**
2831
+ * Initialize the strand solicitation service.
2832
+ * This enables forming strands with other parties via open invitations.
2833
+ *
2834
+ * @param options - Configuration for the solicitation service
2835
+ */
2836
+ initializeStrandSolicitation(options?: StrandSolicitationServiceOptions): void {
2837
+ if (!this.controlNode) {
2838
+ throw new Error('CadreNode must be started before initializing strand solicitation');
2839
+ }
2840
+
2841
+ this.strandSolicitationService = new StrandSolicitationService({
2842
+ ...options,
2843
+ partyId: this.config.controlNetwork.partyId,
2844
+ cadrePeerAddrs: this.getMultiaddrs()
2845
+ });
2846
+
2847
+ // Register as responder on the control node
2848
+ this.strandSolicitationService.registerResponder(this.controlNode);
2849
+ log('Strand solicitation service initialized');
2850
+ }
2851
+
2852
+ /**
2853
+ * Get the strand solicitation service (for advanced use)
2854
+ */
2855
+ getStrandSolicitationService(): StrandSolicitationService | null {
2856
+ return this.strandSolicitationService;
2857
+ }
2858
+
2859
+ /**
2860
+ * Create an open invitation for others to form strands with this party.
2861
+ *
2862
+ * @param sAppId - The sApp to use for formed strands
2863
+ * @param expirationMs - How long the invitation is valid (ms from now)
2864
+ * @returns The open invitation to share out-of-band
2865
+ */
2866
+ async createOpenInvitation(
2867
+ sAppId: string,
2868
+ expirationMs: number = 24 * 60 * 60 * 1000 // 24 hours default
2869
+ ): Promise<OpenInvitation> {
2870
+ if (!this.strandSolicitationService) {
2871
+ // Create a temporary service for creating invitations
2872
+ this.initializeStrandSolicitation();
2873
+ }
2874
+
2875
+ const bootstrap = this.getMultiaddrs();
2876
+ if (bootstrap.length === 0) {
2877
+ throw new Error('No multiaddrs available for invitation');
2878
+ }
2879
+
2880
+ return await this.strandSolicitationService!.createOpenInvitation(
2881
+ sAppId,
2882
+ expirationMs,
2883
+ bootstrap
2884
+ );
2885
+ }
2886
+
2887
+ /**
2888
+ * Form a strand with a responder via an open invitation.
2889
+ *
2890
+ * @param invitation - The open invitation received out-of-band
2891
+ * @param disclosure - Identity/context information to share with the responder
2892
+ * @returns The member key and strand info if successful
2893
+ */
2894
+ async formStrand(
2895
+ invitation: OpenInvitation,
2896
+ disclosure: StrandFormationDisclosure = {}
2897
+ ): Promise<FormStrandResult> {
2898
+ if (!this.controlNode) {
2899
+ throw new Error('CadreNode must be started before forming strands');
2900
+ }
2901
+
2902
+ if (!this.strandSolicitationService) {
2903
+ this.initializeStrandSolicitation();
2904
+ }
2905
+
2906
+ return await this.strandSolicitationService!.formStrand(
2907
+ invitation,
2908
+ disclosure,
2909
+ this.controlNode
2910
+ );
2911
+ }
2912
+
2913
+ /**
2914
+ * Encode an open invitation for out-of-band delivery (QR, link, etc.).
2915
+ */
2916
+ encodeInvitation(invitation: OpenInvitation): string {
2917
+ const json = JSON.stringify({
2918
+ ...invitation,
2919
+ expiration: invitation.expiration.toISOString()
2920
+ });
2921
+ return uint8ArrayToString(new TextEncoder().encode(json), 'base64url');
2922
+ }
2923
+
2924
+ /**
2925
+ * Decode an open invitation from base64url encoding.
2926
+ */
2927
+ decodeInvitation(encoded: string): OpenInvitation {
2928
+ const bytes = uint8ArrayFromString(encoded, 'base64url');
2929
+ const json = new TextDecoder().decode(bytes);
2930
+ const parsed = JSON.parse(json);
2931
+ return {
2932
+ ...parsed,
2933
+ expiration: new Date(parsed.expiration)
2934
+ };
2935
+ }
2936
+ }
2937
+