@serfab/cadre-core 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/README.md +11 -10
  2. package/dist/cadre-node.d.ts +818 -19
  3. package/dist/cadre-node.js +1952 -99
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/canonical-datetime.d.ts +33 -0
  6. package/dist/canonical-datetime.js +38 -0
  7. package/dist/canonical-datetime.js.map +1 -0
  8. package/dist/canonical-json.d.ts +12 -0
  9. package/dist/canonical-json.js +33 -0
  10. package/dist/canonical-json.js.map +1 -0
  11. package/dist/control-cohort.d.ts +63 -0
  12. package/dist/control-cohort.js +80 -0
  13. package/dist/control-cohort.js.map +1 -0
  14. package/dist/control-database.d.ts +279 -8
  15. package/dist/control-database.js +563 -134
  16. package/dist/control-database.js.map +1 -1
  17. package/dist/control-formation-recorder.d.ts +89 -0
  18. package/dist/control-formation-recorder.js +139 -0
  19. package/dist/control-formation-recorder.js.map +1 -0
  20. package/dist/control-schema.d.ts +12 -0
  21. package/dist/control-schema.js +223 -0
  22. package/dist/control-schema.js.map +1 -0
  23. package/dist/control-stream.d.ts +54 -0
  24. package/dist/control-stream.js +104 -0
  25. package/dist/control-stream.js.map +1 -0
  26. package/dist/device-token.d.ts +50 -0
  27. package/dist/device-token.js +66 -0
  28. package/dist/device-token.js.map +1 -0
  29. package/dist/diagnostics/connection-path.d.ts +118 -0
  30. package/dist/diagnostics/connection-path.js +204 -0
  31. package/dist/diagnostics/connection-path.js.map +1 -0
  32. package/dist/diagnostics/webrtc-turn-tracker.d.ts +50 -0
  33. package/dist/diagnostics/webrtc-turn-tracker.js +196 -0
  34. package/dist/diagnostics/webrtc-turn-tracker.js.map +1 -0
  35. package/dist/ed25519-key.d.ts +42 -0
  36. package/dist/ed25519-key.js +51 -0
  37. package/dist/ed25519-key.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 +48 -0
  51. package/dist/peer-authorization.js +66 -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-node.d.ts +38 -0
  63. package/dist/push-node.js +48 -0
  64. package/dist/push-node.js.map +1 -0
  65. package/dist/push-notifier-apns.d.ts +61 -0
  66. package/dist/push-notifier-apns.js +199 -0
  67. package/dist/push-notifier-apns.js.map +1 -0
  68. package/dist/push-notifier-fcm.d.ts +44 -0
  69. package/dist/push-notifier-fcm.js +182 -0
  70. package/dist/push-notifier-fcm.js.map +1 -0
  71. package/dist/push-notifier-shared.d.ts +18 -0
  72. package/dist/push-notifier-shared.js +25 -0
  73. package/dist/push-notifier-shared.js.map +1 -0
  74. package/dist/push-notifier.d.ts +52 -0
  75. package/dist/push-notifier.js +22 -0
  76. package/dist/push-notifier.js.map +1 -0
  77. package/dist/schema-verification.d.ts +11 -2
  78. package/dist/schema-verification.js +15 -4
  79. package/dist/schema-verification.js.map +1 -1
  80. package/dist/seed-bootstrap.d.ts +228 -21
  81. package/dist/seed-bootstrap.js +489 -168
  82. package/dist/seed-bootstrap.js.map +1 -1
  83. package/dist/seed-trust-policy.d.ts +63 -0
  84. package/dist/seed-trust-policy.js +56 -0
  85. package/dist/seed-trust-policy.js.map +1 -0
  86. package/dist/strand-addr-protocol.d.ts +132 -0
  87. package/dist/strand-addr-protocol.js +313 -0
  88. package/dist/strand-addr-protocol.js.map +1 -0
  89. package/dist/strand-cohort.d.ts +54 -0
  90. package/dist/strand-cohort.js +38 -0
  91. package/dist/strand-cohort.js.map +1 -0
  92. package/dist/strand-database.d.ts +54 -6
  93. package/dist/strand-database.js +88 -100
  94. package/dist/strand-database.js.map +1 -1
  95. package/dist/strand-formation-manager.d.ts +79 -19
  96. package/dist/strand-formation-manager.js +196 -104
  97. package/dist/strand-formation-manager.js.map +1 -1
  98. package/dist/strand-formation-protocol.d.ts +162 -0
  99. package/dist/strand-formation-protocol.js +279 -0
  100. package/dist/strand-formation-protocol.js.map +1 -0
  101. package/dist/strand-instance-manager.d.ts +73 -4
  102. package/dist/strand-instance-manager.js +167 -41
  103. package/dist/strand-instance-manager.js.map +1 -1
  104. package/dist/strand-member-key.d.ts +29 -0
  105. package/dist/strand-member-key.js +38 -0
  106. package/dist/strand-member-key.js.map +1 -0
  107. package/dist/strand-member-registry.d.ts +98 -0
  108. package/dist/strand-member-registry.js +129 -0
  109. package/dist/strand-member-registry.js.map +1 -0
  110. package/dist/strand-membership-writer.d.ts +361 -0
  111. package/dist/strand-membership-writer.js +449 -0
  112. package/dist/strand-membership-writer.js.map +1 -0
  113. package/dist/strand-solicitation.d.ts +77 -2
  114. package/dist/strand-solicitation.js +25 -4
  115. package/dist/strand-solicitation.js.map +1 -1
  116. package/dist/strand-wake-payload.d.ts +30 -0
  117. package/dist/strand-wake-payload.js +20 -0
  118. package/dist/strand-wake-payload.js.map +1 -0
  119. package/dist/strand-wake-protocol.d.ts +114 -0
  120. package/dist/strand-wake-protocol.js +257 -0
  121. package/dist/strand-wake-protocol.js.map +1 -0
  122. package/dist/strand-watcher.d.ts +6 -2
  123. package/dist/strand-watcher.js +57 -17
  124. package/dist/strand-watcher.js.map +1 -1
  125. package/dist/types.d.ts +436 -33
  126. package/dist/types.js +22 -5
  127. package/dist/types.js.map +1 -1
  128. package/package.json +18 -8
  129. package/src/cadre-node.ts +2981 -948
  130. package/src/canonical-datetime.ts +39 -0
  131. package/src/canonical-json.ts +30 -0
  132. package/src/control-cohort.ts +103 -0
  133. package/src/control-database.ts +948 -383
  134. package/src/control-formation-recorder.ts +151 -0
  135. package/src/control-schema.ts +222 -0
  136. package/src/control-stream.ts +128 -0
  137. package/src/device-token.ts +89 -0
  138. package/src/diagnostics/connection-path.ts +277 -0
  139. package/src/diagnostics/webrtc-turn-tracker.ts +222 -0
  140. package/src/ed25519-key.ts +69 -0
  141. package/src/hibernation-manager.ts +197 -28
  142. package/src/index.ts +275 -79
  143. package/src/key-store-file.ts +203 -0
  144. package/src/key-store.ts +99 -0
  145. package/src/peer-authorization.ts +81 -0
  146. package/src/peer-record.ts +146 -0
  147. package/src/push-credentials.ts +84 -0
  148. package/src/push-fanout.ts +272 -0
  149. package/src/push-node.ts +64 -0
  150. package/src/push-notifier-apns.ts +247 -0
  151. package/src/push-notifier-fcm.ts +220 -0
  152. package/src/push-notifier-shared.ts +28 -0
  153. package/src/push-notifier.ts +52 -0
  154. package/src/schema-verification.ts +18 -4
  155. package/src/seed-bootstrap.ts +563 -223
  156. package/src/seed-trust-policy.ts +107 -0
  157. package/src/strand-addr-protocol.ts +410 -0
  158. package/src/strand-cohort.ts +77 -0
  159. package/src/strand-database.ts +113 -141
  160. package/src/strand-formation-manager.ts +233 -142
  161. package/src/strand-formation-protocol.ts +391 -0
  162. package/src/strand-instance-manager.ts +207 -56
  163. package/src/strand-member-key.ts +39 -0
  164. package/src/strand-member-registry.ts +177 -0
  165. package/src/strand-membership-writer.ts +640 -0
  166. package/src/strand-solicitation.ts +93 -4
  167. package/src/strand-wake-payload.ts +32 -0
  168. package/src/strand-wake-protocol.ts +331 -0
  169. package/src/strand-watcher.ts +61 -17
  170. package/src/types.ts +1032 -582
package/src/types.ts CHANGED
@@ -1,582 +1,1032 @@
1
- import type { Libp2p, PeerId, PrivateKey } from '@libp2p/interface';
2
- import type { IRawStorage, Libp2pTransports } from '@optimystic/db-p2p';
3
- import type { StrandDatabase } from './strand-database.js';
4
-
5
- /**
6
- * Node profile determines storage participation
7
- */
8
- export type NodeProfile = 'transaction' | 'storage';
9
-
10
- /**
11
- * Strand filter configuration - determines which strands this node participates in
12
- */
13
- export type StrandFilter =
14
- | { mode: 'all' } // All strands (default for servers)
15
- | { mode: 'sAppId'; sAppId: string } // Only strands for specific sApp
16
- | { mode: 'strandId'; strandId: string } // Single specific strand
17
- | { mode: 'none' }; // Control network only
18
-
19
- /**
20
- * Latency hint for strand hibernation behavior
21
- */
22
- export type LatencyHint = 'realtime' | 'interactive' | 'background' | 'archive';
23
-
24
- /**
25
- * Hibernation timeout configuration per latency hint (in milliseconds)
26
- */
27
- export interface HibernationTimeouts {
28
- /** Time before transitioning from active to idle */
29
- idleTimeout: number;
30
- /** Time before transitioning from idle to hibernating */
31
- hibernateTimeout: number;
32
- /** Interval for check-ins while hibernating */
33
- checkInInterval: number;
34
- }
35
-
36
- /**
37
- * Default hibernation timeouts per latency hint
38
- */
39
- export const HIBERNATION_TIMEOUTS: Record<LatencyHint, HibernationTimeouts> = {
40
- realtime: {
41
- idleTimeout: Infinity, // Never idle
42
- hibernateTimeout: Infinity, // Never hibernate
43
- checkInInterval: Infinity // N/A
44
- },
45
- interactive: {
46
- idleTimeout: 5 * 60 * 1000, // 5 minutes
47
- hibernateTimeout: 15 * 60 * 1000, // 15 minutes after idle
48
- checkInInterval: 30 * 1000 // 30 seconds
49
- },
50
- background: {
51
- idleTimeout: 1 * 60 * 1000, // 1 minute
52
- hibernateTimeout: 5 * 60 * 1000, // 5 minutes after idle
53
- checkInInterval: 5 * 60 * 1000 // 5 minutes
54
- },
55
- archive: {
56
- idleTimeout: 10 * 1000, // 10 seconds
57
- hibernateTimeout: 30 * 1000, // 30 seconds after idle
58
- checkInInterval: 60 * 60 * 1000 // 1 hour
59
- }
60
- };
61
-
62
- /**
63
- * Storage provider type - either an IRawStorage instance or a factory function.
64
- * Factory functions are useful for creating strand-specific storage instances.
65
- */
66
- export type RawStorageProvider = IRawStorage | ((strandId: string) => IRawStorage);
67
-
68
- /**
69
- * Storage configuration for storage profile nodes
70
- */
71
- export interface StorageConfig {
72
- /**
73
- * Storage provider - either an IRawStorage instance or a factory function.
74
- *
75
- * For Node.js environments, use FileRawStorage from @optimystic/db-p2p-storage-fs:
76
- * ```typescript
77
- * import { FileRawStorage } from '@optimystic/db-p2p-storage-fs';
78
- * storage: { provider: (strandId) => new FileRawStorage(`./data/${strandId}`) }
79
- * ```
80
- *
81
- * For React Native, use the appropriate storage from @optimystic/db-p2p-storage-rn:
82
- * ```typescript
83
- * import { RNRawStorage } from '@optimystic/db-p2p-storage-rn';
84
- * storage: { provider: (strandId) => new RNRawStorage(strandId) }
85
- * ```
86
- *
87
- * For in-memory storage (testing):
88
- * ```typescript
89
- * import { MemoryRawStorage } from '@optimystic/db-p2p';
90
- * storage: { provider: () => new MemoryRawStorage() }
91
- * ```
92
- */
93
- provider: RawStorageProvider;
94
- quotaBytes?: number;
95
- }
96
-
97
- /**
98
- * Network configuration for libp2p
99
- */
100
- export interface NetworkConfig {
101
- listenAddrs?: string[];
102
- announceAddrs?: string[];
103
- relayAddrs?: string[];
104
- /**
105
- * Enable circuit relay server - allows this node to relay connections for other peers.
106
- * When undefined, defaults to true for storage profile nodes (they typically have
107
- * better connectivity and uptime), false for transaction profile nodes.
108
- */
109
- enableRelay?: boolean;
110
- /**
111
- * Custom libp2p transports. When omitted, the default transports from
112
- * `@optimystic/db-p2p` are used (TCP + circuit relay for Node.js).
113
- *
114
- * React Native apps must supply WebSocket-based transports because TCP
115
- * is not available in the RN runtime:
116
- * ```typescript
117
- * import { webSockets } from '@libp2p/websockets';
118
- * import { circuitRelayTransport } from '@libp2p/circuit-relay-v2';
119
- *
120
- * network: {
121
- * transports: [webSockets(), circuitRelayTransport()],
122
- * listenAddrs: [] // RN nodes typically cannot listen
123
- * }
124
- * ```
125
- */
126
- transports?: Libp2pTransports;
127
- /**
128
- * Optional async resolver returning the multiaddrs to embed in invites
129
- * (and other authority-address contexts). When unset, `libp2pNode.getMultiaddrs()`
130
- * is used. Hosts behind NAT supply this to substitute their DDNS hostname
131
- * and externally-mapped port — see `@serfab/cadre-host`'s NatService.
132
- */
133
- inviteAddressResolver?: () => Promise<string[]>;
134
- }
135
-
136
- /**
137
- * Hibernation configuration
138
- */
139
- export interface HibernationConfig {
140
- enabled: boolean;
141
- defaultLatencyHint?: LatencyHint;
142
- /** Custom timeouts per latency hint (overrides defaults) */
143
- customTimeouts?: Partial<Record<LatencyHint, Partial<HibernationTimeouts>>>;
144
- }
145
-
146
- /**
147
- * Control network configuration
148
- */
149
- export interface ControlNetworkConfig {
150
- partyId: string;
151
- bootstrapNodes: string[];
152
- /** Optional path to the control schema file (defaults to bundled schema) */
153
- schemaPath?: string;
154
- }
155
-
156
- /**
157
- * Main configuration for a CadreNode
158
- */
159
- export interface CadreNodeConfig {
160
- /** If provided, use this keypair for the node identity */
161
- privateKey?: PrivateKey;
162
-
163
- /** Control network connection settings */
164
- controlNetwork: ControlNetworkConfig;
165
-
166
- /** Node profile: transaction-only or storage */
167
- profile: NodeProfile;
168
-
169
- /** Which strands to participate in */
170
- strandFilter?: StrandFilter;
171
-
172
- /** Storage configuration (only for storage profile) */
173
- storage?: StorageConfig;
174
-
175
- /** Network configuration */
176
- network?: NetworkConfig;
177
-
178
- /** Hibernation configuration */
179
- hibernation?: HibernationConfig;
180
-
181
- /** Polling interval for strand watcher in ms (default: 5000) */
182
- strandWatchInterval?: number;
183
- }
184
-
185
- /**
186
- * Status of a strand instance
187
- */
188
- export type StrandStatus =
189
- | 'starting'
190
- | 'active'
191
- | 'idle'
192
- | 'hibernating'
193
- | 'stopping'
194
- | 'stopped'
195
- | 'error';
196
-
197
- /**
198
- * App information from strand header
199
- */
200
- export interface SAppInfo {
201
- id: string;
202
- version: string;
203
- schema: string;
204
- signature?: string;
205
- }
206
-
207
- /**
208
- * Strand instance state
209
- */
210
- export interface StrandInstance {
211
- strandId: string;
212
- status: StrandStatus;
213
- sAppInfo?: SAppInfo;
214
-
215
- /** The libp2p node for this strand (only when active/idle) */
216
- libp2pNode?: Libp2p;
217
-
218
- /** The Quereus database for this strand (only when active/idle) */
219
- database?: StrandDatabase;
220
-
221
- /** Membership info for closed strands */
222
- memberKey?: string;
223
- memberPrivateKey?: string;
224
-
225
- /** Activity tracking */
226
- connectedPeers: number;
227
- lastActivity: Date;
228
- nextCheckIn?: Date;
229
-
230
- /** Latency hint from app or override */
231
- latencyHint: LatencyHint;
232
-
233
- /** Error message if status is 'error' */
234
- error?: string;
235
- }
236
-
237
- /**
238
- * Strand row from control network - basic membership info
239
- */
240
- export interface StrandRow {
241
- Id: string;
242
- MemberPrivateKey: string | null;
243
- Type: 'o' | 'c';
244
- }
245
-
246
- /**
247
- * sApp configuration provided by the hosting application when creating a strand.
248
- * This is what the app developer provides - NOT loaded from the network.
249
- */
250
- export interface SAppConfig {
251
- /** Public key of the sApp author */
252
- id: string;
253
- /** Version of the sApp */
254
- version: string;
255
- /** The declarative schema DDL */
256
- schema: string;
257
- /** Author's signature over the schema for verification (omit to skip verification) */
258
- signature?: string;
259
- /** Latency hint for hibernation behavior (optional, defaults to config) */
260
- latencyHint?: LatencyHint;
261
- }
262
-
263
- /**
264
- * Lifecycle mode for a strand.
265
- *
266
- * - `bootstrap`: newly created locally; no remote peers exist for this strand yet.
267
- * Schema apply and data operations route through a local (non-network) transactor
268
- * so a solo node can fully initialize without any peer round trips.
269
- * - `networked`: strand has (or is expected to have) remote peers. Operations route
270
- * through the network transactor.
271
- *
272
- * Transition `bootstrap -> networked` happens at first remote-peer enrollment for
273
- * the strand; because the transactor is fixed at plugin registration time, the
274
- * transition requires stopping and restarting the strand.
275
- */
276
- export type StrandMode = 'bootstrap' | 'networked';
277
-
278
- /**
279
- * Full strand configuration when adding a strand via the API
280
- */
281
- export interface StrandConfig {
282
- /** Strand row from control network */
283
- strandRow: StrandRow;
284
- /** sApp configuration provided by the hosting application */
285
- sAppConfig: SAppConfig;
286
- /**
287
- * Lifecycle mode for this strand instance. Defaults to `'networked'` when omitted
288
- * to preserve the historical behavior for multi-peer callers.
289
- */
290
- mode?: StrandMode;
291
- }
292
-
293
- /**
294
- * Result of creating a new cadre peer
295
- */
296
- export interface CreatePeerResult {
297
- peerId: PeerId;
298
- privateKey: Uint8Array;
299
- }
300
-
301
- // ============================================================================
302
- // Member Registration API Types (from api.md)
303
- // ============================================================================
304
-
305
- /**
306
- * Registration data for joining a strand as a member.
307
- * Sent from invited member to any cadre member to accept invitation.
308
- */
309
- export interface MemberRegistration {
310
- /** The strand being joined */
311
- strandId: string;
312
- /** The member's public key for this strand */
313
- key: string;
314
- /** Peer IDs of the member's cadre nodes that will participate */
315
- peerIds: string[];
316
- }
317
-
318
- /**
319
- * Result of member registration
320
- */
321
- export interface MemberRegistrationResult {
322
- success: boolean;
323
- reason?: string;
324
- }
325
-
326
- // ============================================================================
327
- // Strand Solicitation API Types (from api.md)
328
- // ============================================================================
329
-
330
- /**
331
- * Open invitation for strand formation.
332
- * Shared out-of-band to allow strangers to form strands.
333
- */
334
- export interface OpenInvitation {
335
- /** Unique token identifying this invitation */
336
- token: string;
337
- /** The sApp that will be used for the strand */
338
- sAppId: string;
339
- /** When this invitation expires */
340
- expiration: Date;
341
- /** Bootstrap addresses to contact the inviter's cadre */
342
- bootstrap: string[];
343
- }
344
-
345
- /**
346
- * Result of forming a strand via open invitation
347
- */
348
- export interface FormStrandResult {
349
- /** The member key assigned to the initiator for this strand */
350
- memberKey: string;
351
- /** Private key for the invitation (for signing future messages) */
352
- invitePrivateKey: string;
353
- /** The strand that was created */
354
- strandId: string;
355
- }
356
-
357
- /**
358
- * Result of validating a strand formation request
359
- */
360
- export interface ValidateFormationResult {
361
- /** Public key for validating this formation */
362
- validationKey: string;
363
- /** Signature over the formation approval */
364
- validationSignature: string;
365
- }
366
-
367
- /**
368
- * Disclosure object provided during strand formation.
369
- * Contains identity and context information from the initiator.
370
- */
371
- export interface StrandFormationDisclosure {
372
- /** Initiator's party identifier */
373
- partyId?: string;
374
- /** Additional identity bundle (app-specific) */
375
- identityBundle?: unknown;
376
- /** Human-readable purpose/reason for forming the strand */
377
- purpose?: string;
378
- /** Additional app-specific metadata */
379
- metadata?: Record<string, unknown>;
380
- }
381
-
382
- /**
383
- * Arachnode ring participation stub - will be implemented when arachnode is built
384
- */
385
- export interface ArachnodeConfig {
386
- /** Enable Arachnode subsystem (Ring Zulu + storage rings). Storage-profile only. */
387
- enableRingZulu: boolean;
388
- /** Storage ring participation (storage profile only) */
389
- storageRing?: {
390
- /** Which ring to participate in based on capacity */
391
- ring: number;
392
- /** Partition within the ring */
393
- partition?: number;
394
- };
395
- }
396
-
397
- /**
398
- * Events emitted by CadreNode
399
- */
400
- export interface CadreNodeEvents {
401
- 'strand:started': { strandId: string };
402
- 'strand:stopped': { strandId: string };
403
- 'strand:error': { strandId: string; error: Error };
404
- 'strand:idle': { strandId: string };
405
- 'strand:hibernating': { strandId: string };
406
- 'strand:waking': { strandId: string };
407
- 'control:connected': void;
408
- 'control:disconnected': void;
409
- /** Emitted when a seed is received via the seed protocol */
410
- 'seed:received': { partyId: string; peerId: string };
411
- /** Emitted when a seed is successfully applied */
412
- 'seed:applied': { partyId: string; peersAdded: number };
413
- /** Emitted when seed application fails */
414
- 'seed:error': { partyId: string; error: string };
415
- }
416
-
417
- // ============================================================================
418
- // Seed Bootstrap API Types (from architecture.md)
419
- // ============================================================================
420
-
421
- /**
422
- * A peer entry in a control network seed.
423
- * Contains connection information for a cadre peer.
424
- */
425
- export interface SeedPeer {
426
- /** Peer ID (libp2p identity) */
427
- peerId: string;
428
- /** Multiaddrs for connecting to this peer */
429
- multiaddrs: string[];
430
- /** Whether this peer holds an authority key */
431
- isAuthority: boolean;
432
- /** ed25519 public key (base64url) — present on authority peers for signerKey verification */
433
- publicKey?: string;
434
- }
435
-
436
- /**
437
- * Control network seed for bootstrapping new nodes.
438
- * Pre-populates a new node's cache to solve the cold-start problem:
439
- * new nodes need control data to validate connections, but can't get
440
- * data without connecting first.
441
- */
442
- export interface ControlNetworkSeed {
443
- /** Party ID this seed belongs to */
444
- partyId: string;
445
- /** Known peers in the cadre */
446
- peers: SeedPeer[];
447
- /** Optional signed transactions to pre-populate the cache */
448
- transactions?: SignedTransaction[];
449
- /** Signature over the seed by an authority key */
450
- signature: string;
451
- /** The authority key that signed this seed */
452
- signerKey: string;
453
- }
454
-
455
- /**
456
- * A signed transaction for inclusion in seeds.
457
- * Allows pre-populating the control network cache.
458
- */
459
- export interface SignedTransaction {
460
- /** Transaction ID */
461
- id: string;
462
- /** Serialized transaction data */
463
- data: string;
464
- /** Signature over the transaction */
465
- signature: string;
466
- }
467
-
468
- /**
469
- * Message sent from instigator to new node during seed delivery.
470
- * Delivered via /sereus/seed/1.0.0 libp2p protocol.
471
- */
472
- export interface SeedMessage {
473
- /** Party ID for the cadre */
474
- partyId: string;
475
- /** Known peers in the cadre */
476
- peers: SeedPeer[];
477
- /** Optional transactions to pre-populate cache */
478
- transactions?: SignedTransaction[];
479
- /** Signature by an authority key */
480
- signature: string;
481
- /** The authority key that signed this message */
482
- signerKey: string;
483
- }
484
-
485
- /**
486
- * Acknowledgment message from new node to instigator.
487
- */
488
- export interface SeedAckMessage {
489
- /** Whether the seed was accepted */
490
- accepted: boolean;
491
- /** Reason for rejection (if not accepted) */
492
- reason?: string;
493
- }
494
-
495
- /**
496
- * Options for authorizing a new peer in the cadre.
497
- */
498
- export interface AuthorizePeerOptions {
499
- /** Peer ID to authorize */
500
- peerId: string;
501
- /** Optional multiaddrs for the peer */
502
- multiaddrs?: string[];
503
- }
504
-
505
- /**
506
- * Result of applying a seed to a node.
507
- */
508
- export interface ApplySeedResult {
509
- /** Whether the seed was successfully applied */
510
- success: boolean;
511
- /** Number of peers added to the peer store */
512
- peersAdded: number;
513
- /** Error message if not successful */
514
- error?: string;
515
- }
516
-
517
- // ============================================================================
518
- // Seed Helper Types
519
- // ============================================================================
520
-
521
- /**
522
- * Node network topology type for seed helper scenarios.
523
- */
524
- export type NodeTopology = 'public' | 'nat';
525
-
526
- /**
527
- * Invite code for phone-to-server enrollment.
528
- * Used when a server invites a phone to join the cadre.
529
- */
530
- export interface CadreInvite {
531
- /** Party ID of the cadre */
532
- partyId: string;
533
- /** Multiaddrs to dial the authority */
534
- authorityAddrs: string[];
535
- /** Optional invite token for validation */
536
- token?: string;
537
- /** Timestamp when invite was created */
538
- createdAt: number;
539
- /** Optional expiration timestamp */
540
- expiresAt?: number;
541
- }
542
-
543
- /**
544
- * Options for adding a drone via provider API.
545
- */
546
- export interface AddDroneOptions {
547
- /** Peer ID of the new drone (returned from provider) */
548
- dronePeerId: string;
549
- /** Multiaddrs of the drone (returned from provider) */
550
- droneMultiaddrs: string[];
551
- }
552
-
553
- /**
554
- * Options for adding a phone via invite flow.
555
- */
556
- export interface AddPhoneOptions {
557
- /** Peer ID of the phone (sent by phone when it connects) */
558
- phonePeerId: string;
559
- /** Invite token for validation (must match issued invite) */
560
- token?: string;
561
- }
562
-
563
- /**
564
- * Result of preparing a seed for drone initialization.
565
- */
566
- export interface DroneInitResult {
567
- /** The seed to send to the provider API */
568
- seed: ControlNetworkSeed;
569
- /** Base64url encoded seed for transport */
570
- encodedSeed: string;
571
- }
572
-
573
- /**
574
- * Result of creating an invite for a phone.
575
- */
576
- export interface InviteResult {
577
- /** The invite to share out-of-band */
578
- invite: CadreInvite;
579
- /** Base64url encoded invite for QR/link */
580
- encodedInvite: string;
581
- }
582
-
1
+ import type { ConnectionGater, Libp2p, PeerId, PrivateKey } from '@libp2p/interface';
2
+ import type { IRawStorage, Libp2pTransports } from '@optimystic/db-p2p';
3
+ import type { IRepo } from '@optimystic/db-core';
4
+ import type { StrandDatabase } from './strand-database.js';
5
+ import type { SeedTrustPolicy } from './seed-trust-policy.js';
6
+ import type { KeyStore, KeyId } from './key-store.js';
7
+ import type { PushNotifier } from './push-notifier.js';
8
+
9
+ /**
10
+ * Extended Libp2p node with the coordinatedRepo attached by db-p2p's
11
+ * createLibp2pNode after node creation (not surfaced on the base Libp2p type).
12
+ */
13
+ export interface Libp2pNodeWithRepo extends Libp2p {
14
+ coordinatedRepo: IRepo;
15
+ }
16
+
17
+ /**
18
+ * Node profile determines storage participation
19
+ */
20
+ export type NodeProfile = 'transaction' | 'storage';
21
+
22
+ /**
23
+ * Strand filter configuration - determines which strands this node participates in
24
+ */
25
+ export type StrandFilter =
26
+ | { mode: 'all' } // All strands (default for servers)
27
+ | { mode: 'sAppId'; sAppId: string } // Only strands for specific sApp
28
+ | { mode: 'strandId'; strandId: string } // Single specific strand
29
+ | { mode: 'none' }; // Control network only
30
+
31
+ /**
32
+ * Latency hint for strand hibernation behavior
33
+ */
34
+ export type LatencyHint = 'realtime' | 'interactive' | 'background' | 'archive';
35
+
36
+ /**
37
+ * Hibernation timeout configuration per latency hint (in milliseconds)
38
+ */
39
+ export interface HibernationTimeouts {
40
+ /** Time before transitioning from active to idle */
41
+ idleTimeout: number;
42
+ /** Time before transitioning from idle to hibernating */
43
+ hibernateTimeout: number;
44
+ /**
45
+ * Base interval for the FIRST check-in after hibernating. Successive
46
+ * no-activity check-ins escalate this delay by {@link checkInBackoffFactor}
47
+ * (see {@link HibernationManager}'s self-rescheduling check-in chain).
48
+ */
49
+ checkInInterval: number;
50
+ /**
51
+ * Multiplier applied to the check-in delay after each check-in that finds no
52
+ * pending activity (must be >= 1; 1 disables escalation). Default 2 →
53
+ * doubling: base, base×2, base×4, … until {@link checkInMaxInterval}.
54
+ */
55
+ checkInBackoffFactor: number;
56
+ /**
57
+ * Upper bound on the escalating check-in delay — the concrete realization of
58
+ * the architecture's "minutes → hours → days" ceiling for this hint. Backoff
59
+ * never schedules a delay longer than this.
60
+ */
61
+ checkInMaxInterval: number;
62
+ }
63
+
64
+ /**
65
+ * Default hibernation timeouts per latency hint.
66
+ *
67
+ * `checkInInterval` is the BASE delay; `checkInMaxInterval` is the per-hint
68
+ * ceiling the exponential backoff escalates toward (interactive minutes→~1h,
69
+ * background minutes→~6h, archive ~1h→~3 days).
70
+ */
71
+ export const HIBERNATION_TIMEOUTS: Record<LatencyHint, HibernationTimeouts> = {
72
+ realtime: {
73
+ idleTimeout: Infinity, // Never idle
74
+ hibernateTimeout: Infinity, // Never hibernate
75
+ checkInInterval: Infinity, // N/A
76
+ checkInBackoffFactor: 2,
77
+ checkInMaxInterval: Infinity // N/A
78
+ },
79
+ interactive: {
80
+ idleTimeout: 5 * 60 * 1000, // 5 minutes
81
+ hibernateTimeout: 15 * 60 * 1000, // 15 minutes after idle
82
+ checkInInterval: 30 * 1000, // base: 30 seconds
83
+ checkInBackoffFactor: 2,
84
+ checkInMaxInterval: 60 * 60 * 1000 // cap: ~1 hour
85
+ },
86
+ background: {
87
+ idleTimeout: 1 * 60 * 1000, // 1 minute
88
+ hibernateTimeout: 5 * 60 * 1000, // 5 minutes after idle
89
+ checkInInterval: 5 * 60 * 1000, // base: 5 minutes
90
+ checkInBackoffFactor: 2,
91
+ checkInMaxInterval: 6 * 60 * 60 * 1000 // cap: ~6 hours
92
+ },
93
+ archive: {
94
+ idleTimeout: 10 * 1000, // 10 seconds
95
+ hibernateTimeout: 30 * 1000, // 30 seconds after idle
96
+ checkInInterval: 60 * 60 * 1000, // base: 1 hour
97
+ checkInBackoffFactor: 2,
98
+ checkInMaxInterval: 3 * 24 * 60 * 60 * 1000 // cap: ~3 days
99
+ }
100
+ };
101
+
102
+ /**
103
+ * Storage provider type - either an IRawStorage instance or a factory function.
104
+ * Factory functions are useful for creating strand-specific storage instances.
105
+ */
106
+ export type RawStorageProvider = IRawStorage | ((strandId: string) => IRawStorage);
107
+
108
+ /**
109
+ * Storage configuration for storage profile nodes
110
+ */
111
+ export interface StorageConfig {
112
+ /**
113
+ * Storage provider - either an IRawStorage instance or a factory function.
114
+ *
115
+ * For Node.js environments, use FileRawStorage from @optimystic/db-p2p-storage-fs:
116
+ * ```typescript
117
+ * import { FileRawStorage } from '@optimystic/db-p2p-storage-fs';
118
+ * storage: { provider: (strandId) => new FileRawStorage(`./data/${strandId}`) }
119
+ * ```
120
+ *
121
+ * For React Native, use the appropriate storage from @optimystic/db-p2p-storage-rn:
122
+ * ```typescript
123
+ * import { RNRawStorage } from '@optimystic/db-p2p-storage-rn';
124
+ * storage: { provider: (strandId) => new RNRawStorage(strandId) }
125
+ * ```
126
+ *
127
+ * For in-memory storage (testing):
128
+ * ```typescript
129
+ * import { MemoryRawStorage } from '@optimystic/db-p2p';
130
+ * storage: { provider: () => new MemoryRawStorage() }
131
+ * ```
132
+ */
133
+ provider: RawStorageProvider;
134
+ quotaBytes?: number;
135
+ }
136
+
137
+ /**
138
+ * Network configuration for libp2p
139
+ */
140
+ export interface NetworkConfig {
141
+ listenAddrs?: string[];
142
+ announceAddrs?: string[];
143
+ relayAddrs?: string[];
144
+ /**
145
+ * Enable circuit relay server - allows this node to relay connections for other peers.
146
+ * When undefined, defaults to true for storage profile nodes (they typically have
147
+ * better connectivity and uptime), false for transaction profile nodes.
148
+ */
149
+ enableRelay?: boolean;
150
+ /**
151
+ * Custom libp2p transports. When omitted, the default transports from
152
+ * `@optimystic/db-p2p` are used (TCP + circuit relay for Node.js).
153
+ *
154
+ * React Native apps must supply WebSocket-based transports because TCP
155
+ * is not available in the RN runtime:
156
+ * ```typescript
157
+ * import { webSockets } from '@libp2p/websockets';
158
+ * import { circuitRelayTransport } from '@libp2p/circuit-relay-v2';
159
+ *
160
+ * network: {
161
+ * transports: [webSockets(), circuitRelayTransport()],
162
+ * listenAddrs: [] // RN nodes typically cannot listen
163
+ * }
164
+ * ```
165
+ */
166
+ transports?: Libp2pTransports;
167
+ /**
168
+ * Optional async resolver returning the multiaddrs to embed in invites
169
+ * (and other owner-address contexts). When unset, `libp2pNode.getMultiaddrs()`
170
+ * is used. Hosts behind NAT supply this to substitute their DDNS hostname
171
+ * and externally-mapped port — see `@serfab/cadre-host`'s NatService.
172
+ */
173
+ inviteAddressResolver?: () => Promise<string[]>;
174
+ /**
175
+ * Optional libp2p connection gater, threaded to both the control node and every
176
+ * strand's cohort node. libp2p's browser default denies dialing insecure
177
+ * WebSockets and private/loopback addresses; callers that must dial local or
178
+ * unsecured peers (the web reference dialing a `127.0.0.1/.../ws` responder,
179
+ * Playwright e2e, RN simulators) supply a permissive gater here — e.g.
180
+ * `{ denyDialMultiaddr: () => false }`. See `@optimystic/db-p2p`'s
181
+ * `libp2p-node-base` for the underlying option.
182
+ */
183
+ connectionGater?: ConnectionGater;
184
+ /**
185
+ * Tuning for the proactive control-cohort dial routine
186
+ * ({@link CadreNode.reconcileControlCohort}), which keeps a party's control
187
+ * nodes connected so the `CadreControl` collections form a replicating cohort.
188
+ * Both fields are optional; omit for the defaults
189
+ * ({@link DEFAULT_CONTROL_COHORT_TARGET_DEGREE} /
190
+ * {@link DEFAULT_CONTROL_COHORT_RECONCILE_MS}).
191
+ */
192
+ controlCohort?: {
193
+ /**
194
+ * Cap on the number of NON-owner siblings dialed per reconcile pass
195
+ * (backbone/owner members are always dialed and do not count). Defaults
196
+ * to {@link DEFAULT_CONTROL_COHORT_TARGET_DEGREE}.
197
+ */
198
+ targetDegree?: number;
199
+ /**
200
+ * Recurring reconcile cadence in ms. Defaults to
201
+ * {@link DEFAULT_CONTROL_COHORT_RECONCILE_MS}.
202
+ */
203
+ reconcileMs?: number;
204
+ };
205
+ }
206
+
207
+ /**
208
+ * Hibernation configuration
209
+ */
210
+ export interface HibernationConfig {
211
+ enabled: boolean;
212
+ defaultLatencyHint?: LatencyHint;
213
+ /** Custom timeouts per latency hint (overrides defaults) */
214
+ customTimeouts?: Partial<Record<LatencyHint, Partial<HibernationTimeouts>>>;
215
+ /**
216
+ * How long a hibernating strand stays resumed during a check-in to let its
217
+ * strand network connect to reachable cohort peers (and the app drive
218
+ * pull-on-read activity) before re-hibernating if still idle. Defaults to
219
+ * {@link DEFAULT_CHECKIN_WINDOW_MS}.
220
+ */
221
+ checkInWindowMs?: number;
222
+ }
223
+
224
+ /**
225
+ * Default duration of the resume-and-probe window during a strand check-in.
226
+ * See {@link HibernationConfig.checkInWindowMs}.
227
+ */
228
+ export const DEFAULT_CHECKIN_WINDOW_MS = 15 * 1000;
229
+
230
+ /**
231
+ * Control network configuration
232
+ */
233
+ export interface ControlNetworkConfig {
234
+ partyId: string;
235
+ bootstrapNodes: string[];
236
+ /** Optional path to the control schema file (defaults to bundled schema) */
237
+ schemaPath?: string;
238
+ }
239
+
240
+ /**
241
+ * Main configuration for a CadreNode
242
+ */
243
+ export interface CadreNodeConfig {
244
+ /**
245
+ * If provided, use this keypair for the node identity (direct injection).
246
+ * Mutually exclusive with {@link keyStore} — supplying both is a configuration
247
+ * error (fail closed) thrown by `start()` before any network bring-up.
248
+ */
249
+ privateKey?: PrivateKey;
250
+
251
+ /**
252
+ * Pluggable secure store for node key material. When set, the node loads its
253
+ * identity from `keyStore` under {@link identityKeyId}, generating + persisting
254
+ * a fresh Ed25519 key on first run (protobuf bytes are the canonical stored
255
+ * form). Mutually exclusive with {@link privateKey}. Absent ⇒ legacy behavior
256
+ * (use `privateKey`, else libp2p generates an ephemeral key).
257
+ *
258
+ * In the single-key reference model the owner signing key is *derived from*
259
+ * the node identity (see {@link CadreNode.getIdentityOwnerKey}), so
260
+ * protecting the identity in a secure enclave protects the owner key too.
261
+ * A future separate-owner slot (`ownerKeyId`) is anticipated but not
262
+ * built here.
263
+ */
264
+ keyStore?: KeyStore;
265
+
266
+ /** Slot id for the node identity in {@link keyStore}. Default: `'cadre/identity'`. */
267
+ identityKeyId?: KeyId;
268
+
269
+ /** Control network connection settings */
270
+ controlNetwork: ControlNetworkConfig;
271
+
272
+ /** Node profile: transaction-only or storage */
273
+ profile: NodeProfile;
274
+
275
+ /** Which strands to participate in */
276
+ strandFilter?: StrandFilter;
277
+
278
+ /** Storage configuration (only for storage profile) */
279
+ storage?: StorageConfig;
280
+
281
+ /** Network configuration */
282
+ network?: NetworkConfig;
283
+
284
+ /** Hibernation configuration */
285
+ hibernation?: HibernationConfig;
286
+
287
+ /** Polling interval for strand watcher in ms (default: 5000) */
288
+ strandWatchInterval?: number;
289
+
290
+ /**
291
+ * Require a valid author signature on every sApp schema before a strand is
292
+ * formed or joined. Defaults to true (fail closed): an unsigned schema is
293
+ * rejected before any libp2p node or schema DDL is brought up. Set false ONLY
294
+ * for dev/test where unsigned demo schemas are used.
295
+ */
296
+ requireSignedSchemas?: boolean;
297
+
298
+ /**
299
+ * Node-wide default trust anchor for INBOUND control-network seeds. Forwarded
300
+ * into every SeedBootstrapService this node constructs (owner, receive-only
301
+ * listener, and the temp service used by applySeed when no service exists), and
302
+ * used as the service-level default the libp2p seed-protocol handler relies on
303
+ * (that path has no per-call override seam). Defaults to dbAnchoredTrustPolicy()
304
+ * inside SeedBootstrapService when unset — a cold-start node then rejects every
305
+ * seed. A per-call `applySeed(seed, { trustPolicy })` override still wins over
306
+ * this default for callers that hold out-of-band material (e.g. a pinned key
307
+ * from a CadreInvite).
308
+ */
309
+ seedTrustPolicy?: SeedTrustPolicy;
310
+
311
+ /**
312
+ * Platform push-delivery for suspended mobile peers. When present, the node's
313
+ * server fan-out can deliver strand-wake data messages over the platform push
314
+ * channel (FCM/APNs). Absent ⇒ no platform push (control-network push-wake only).
315
+ *
316
+ * The `notifier` is **injected**, not constructed here: a Node host builds it
317
+ * from `@serfab/cadre-core/push-node` (`createPushNotifier(credentials)`) and
318
+ * passes the instance, so the FCM/APNs modules (`node:crypto`/`node:http2`)
319
+ * stay out of the cross-platform core graph. Ownership transfers to the node on
320
+ * injection — `CadreNode.stop` closes the notifier (via `PushFanoutService`),
321
+ * releasing its APNs HTTP/2 session; a host must NOT also close an injected
322
+ * notifier itself. `cooldownMs`/`debounceMs` carry the fan-out anti-spam policy.
323
+ */
324
+ push?: {
325
+ /** The Node-constructed push router (see `@serfab/cadre-core/push-node`). */
326
+ notifier: PushNotifier;
327
+ /**
328
+ * Per-`(peer, strand)` minimum gap between push-wakes the fan-out emits.
329
+ * Default {@link DEFAULT_PUSH_COOLDOWN_MS} (5 min).
330
+ */
331
+ cooldownMs?: number;
332
+ /**
333
+ * Per-strand burst-coalescing window: a second trigger within it is dropped.
334
+ * Default {@link DEFAULT_PUSH_DEBOUNCE_MS} (10 s).
335
+ */
336
+ debounceMs?: number;
337
+ };
338
+ }
339
+
340
+ /**
341
+ * Status of a strand instance
342
+ */
343
+ export type StrandStatus =
344
+ | 'starting'
345
+ | 'active'
346
+ | 'idle'
347
+ | 'hibernating'
348
+ | 'stopping'
349
+ | 'stopped'
350
+ | 'error';
351
+
352
+ /**
353
+ * App information from strand header
354
+ */
355
+ export interface SAppInfo {
356
+ id: string;
357
+ version: string;
358
+ schema: string;
359
+ signature?: string;
360
+ }
361
+
362
+ /**
363
+ * Strand instance state
364
+ */
365
+ export interface StrandInstance {
366
+ strandId: string;
367
+ status: StrandStatus;
368
+ sAppInfo?: SAppInfo;
369
+
370
+ /** The libp2p node for this strand (only when active/idle) */
371
+ libp2pNode?: Libp2p;
372
+
373
+ /** The Quereus database for this strand (only when active/idle) */
374
+ database?: StrandDatabase;
375
+
376
+ /** Membership info for closed strands */
377
+ memberKey?: string;
378
+ memberPrivateKey?: string;
379
+
380
+ /** Activity tracking */
381
+ connectedPeers: number;
382
+ lastActivity: Date;
383
+ nextCheckIn?: Date;
384
+
385
+ /** Latency hint from app or override */
386
+ latencyHint: LatencyHint;
387
+
388
+ /** Error message if status is 'error' */
389
+ error?: string;
390
+ }
391
+
392
+ /**
393
+ * Outcome of an on-demand {@link CadreNode.serviceWake} — the mobile push-wake
394
+ * cycle (resume → bounded window → re-hibernate-if-idle) run imperatively for a
395
+ * single strand.
396
+ */
397
+ export interface ServiceWakeResult {
398
+ /** The strand the wake was requested for. */
399
+ strandId: string;
400
+ /**
401
+ * Whether the wake was actually serviced. `false` when the node is not
402
+ * running, or the strand is unknown to this node (not a member-participated
403
+ * strand) — never a thrown error, so a background task can branch on it.
404
+ */
405
+ serviced: boolean;
406
+ /**
407
+ * Whether activity landed during the wake window. `true` leaves the strand
408
+ * active; `false` re-hibernates it (or the strand was already live, in which
409
+ * case it reflects current liveness). Always `false` when `serviced` is `false`.
410
+ */
411
+ hadActivity: boolean;
412
+ }
413
+
414
+ /**
415
+ * Strand row from control network - basic membership info
416
+ */
417
+ export interface StrandRow {
418
+ Id: string;
419
+ MemberPrivateKey: string | null;
420
+ Type: 'o' | 'c';
421
+ }
422
+
423
+ /**
424
+ * sApp configuration provided by the hosting application when creating a strand.
425
+ * This is what the app developer provides - NOT loaded from the network.
426
+ */
427
+ export interface SAppConfig {
428
+ /** Public key of the sApp author */
429
+ id: string;
430
+ /** Version of the sApp */
431
+ version: string;
432
+ /** The declarative schema DDL */
433
+ schema: string;
434
+ /**
435
+ * Author's signature over the schema for verification. Required under the
436
+ * default `requireSignedSchemas` node policy — a config without it is rejected
437
+ * before strand bring-up. Optional in the type because authoring/serialization
438
+ * must represent an as-yet-unsigned config; omitting it is honored only when
439
+ * the node explicitly relaxes the policy (`requireSignedSchemas: false`, dev/test).
440
+ */
441
+ signature?: string;
442
+ /** Latency hint for hibernation behavior (optional, defaults to config) */
443
+ latencyHint?: LatencyHint;
444
+ }
445
+
446
+ /**
447
+ * Lifecycle mode for a strand.
448
+ *
449
+ * - `bootstrap`: newly created locally; no remote peers exist for this strand yet.
450
+ * Schema apply and data operations route through a local (non-network) transactor
451
+ * so a solo node can fully initialize without any peer round trips.
452
+ * - `networked`: strand has (or is expected to have) remote peers. Operations route
453
+ * through the network transactor.
454
+ *
455
+ * Transition `bootstrap -> networked` happens at first remote-peer enrollment for
456
+ * the strand; because the transactor is fixed at plugin registration time, the
457
+ * transition requires stopping and restarting the strand.
458
+ */
459
+ export type StrandMode = 'bootstrap' | 'networked';
460
+
461
+ /**
462
+ * Full strand configuration when adding a strand via the API
463
+ */
464
+ export interface StrandConfig {
465
+ /** Strand row from control network */
466
+ strandRow: StrandRow;
467
+ /** sApp configuration provided by the hosting application */
468
+ sAppConfig: SAppConfig;
469
+ /**
470
+ * Lifecycle mode for this strand instance. When omitted, CadreNode infers the
471
+ * mode from cohort membership (`bootstrap` for a solo/first node with no other
472
+ * `CadrePeer` rows, `networked` once the cohort has other members). An explicit
473
+ * value always wins.
474
+ */
475
+ mode?: StrandMode;
476
+ /**
477
+ * Whether THIS node is the strand's founder — the party that provisioned and
478
+ * published the strand (the responder in formation, the creator in host/solo
479
+ * paths; the same party that calls {@link CadreNode.publishStrand}). The founder
480
+ * runs the one-time membership bootstrap at bring-up (writes `Strand.Header`, and
481
+ * for a closed strand the founding `Member`+`Manager`). A joiner leaves this
482
+ * `false`/unset and writes nothing — it receives those rows via Optimystic sync.
483
+ * Defaults to `false`.
484
+ */
485
+ founder?: boolean;
486
+ }
487
+
488
+ /**
489
+ * Result of creating a new cadre peer
490
+ */
491
+ export interface CreatePeerResult {
492
+ peerId: PeerId;
493
+ privateKey: Uint8Array;
494
+ }
495
+
496
+ // ============================================================================
497
+ // Member Registration API Types (from api.md)
498
+ // ============================================================================
499
+
500
+ /**
501
+ * Registration data for joining a strand as a member.
502
+ * Sent from invited member to any cadre member to accept invitation.
503
+ */
504
+ export interface MemberRegistration {
505
+ /** The strand being joined */
506
+ strandId: string;
507
+ /** The member's public key for this strand */
508
+ key: string;
509
+ /** Peer IDs of the member's cadre nodes that will participate */
510
+ peerIds: string[];
511
+ }
512
+
513
+ /**
514
+ * Result of member registration
515
+ */
516
+ export interface MemberRegistrationResult {
517
+ success: boolean;
518
+ reason?: string;
519
+ }
520
+
521
+ // ============================================================================
522
+ // Strand Solicitation API Types (from api.md)
523
+ // ============================================================================
524
+
525
+ /**
526
+ * Open invitation for strand formation.
527
+ * Shared out-of-band to allow strangers to form strands.
528
+ */
529
+ export interface OpenInvitation {
530
+ /** Unique token identifying this invitation */
531
+ token: string;
532
+ /** The sApp that will be used for the strand */
533
+ sAppId: string;
534
+ /** When this invitation expires */
535
+ expiration: Date;
536
+ /** Bootstrap addresses to contact the inviter's cadre */
537
+ bootstrap: string[];
538
+ }
539
+
540
+ /**
541
+ * Result of forming a strand via open invitation
542
+ */
543
+ export interface FormStrandResult {
544
+ /** The member key assigned to the initiator for this strand */
545
+ memberKey: string;
546
+ /** Private key for the invitation (for signing future messages) */
547
+ invitePrivateKey: string;
548
+ /** The strand that was created */
549
+ strandId: string;
550
+ /**
551
+ * The strand's membership key (closed-strand read-gating secret), delivered through
552
+ * the formation protocol after consent (provision-then-record). Present only for a
553
+ * closed strand the responder returned with its key; undefined otherwise. Distinct
554
+ * from {@link invitePrivateKey} (the initiator's own generated signing key).
555
+ */
556
+ memberPrivateKey?: string;
557
+ }
558
+
559
+ /**
560
+ * Result of validating a strand formation request
561
+ */
562
+ export interface ValidateFormationResult {
563
+ /** Public key for validating this formation */
564
+ validationKey: string;
565
+ /** Signature over the formation approval */
566
+ validationSignature: string;
567
+ }
568
+
569
+ /**
570
+ * Disclosure object provided during strand formation.
571
+ * Contains identity and context information from the initiator.
572
+ */
573
+ export interface StrandFormationDisclosure {
574
+ /** Initiator's party identifier */
575
+ partyId?: string;
576
+ /** Additional identity bundle (app-specific) */
577
+ identityBundle?: unknown;
578
+ /** Human-readable purpose/reason for forming the strand */
579
+ purpose?: string;
580
+ /** Additional app-specific metadata */
581
+ metadata?: Record<string, unknown>;
582
+ }
583
+
584
+ /**
585
+ * Arachnode ring participation stub - will be implemented when arachnode is built
586
+ */
587
+ export interface ArachnodeConfig {
588
+ /** Enable Arachnode subsystem (Ring Zulu + storage rings). Storage-profile only. */
589
+ enableRingZulu: boolean;
590
+ /** Storage ring participation (storage profile only) */
591
+ storageRing?: {
592
+ /** Which ring to participate in based on capacity */
593
+ ring: number;
594
+ /** Partition within the ring */
595
+ partition?: number;
596
+ };
597
+ }
598
+
599
+ /**
600
+ * Events emitted by CadreNode
601
+ */
602
+ export interface CadreNodeEvents {
603
+ 'strand:started': { strandId: string };
604
+ 'strand:stopped': { strandId: string };
605
+ 'strand:error': { strandId: string; error: Error };
606
+ 'strand:idle': { strandId: string };
607
+ 'strand:hibernating': { strandId: string };
608
+ 'strand:waking': { strandId: string };
609
+ /**
610
+ * Emitted when the control network advertises a strand this node has no
611
+ * registered `sAppConfig` for — i.e. a strand created by another member. The
612
+ * hosting app decides whether to join it (register a config + `addStrand`,
613
+ * e.g. via a chat `joinChatStrand` helper). Carries the full {@link StrandRow}
614
+ * so the app can join without re-querying the control DB.
615
+ */
616
+ 'strand:discovered': { strandId: string; strand: StrandRow };
617
+ 'control:connected': void;
618
+ 'control:disconnected': void;
619
+ /** Emitted when a seed is received via the seed protocol */
620
+ 'seed:received': { partyId: string; peerId: string };
621
+ /** Emitted when a seed is successfully applied */
622
+ 'seed:applied': { partyId: string; peersAdded: number };
623
+ /** Emitted when seed application fails */
624
+ 'seed:error': { partyId: string; error: string };
625
+ }
626
+
627
+ // ============================================================================
628
+ // Peer Address Record / Resolution Types
629
+ // ============================================================================
630
+
631
+ /**
632
+ * A peer's self-published, freshness-stamped, self-signed address record.
633
+ *
634
+ * This is the logical shape of a `CadreControl.CadrePeer` row. A node publishes
635
+ * its own record (signing with the ed25519 key behind its PeerId); any node can
636
+ * resolve another member's current signaling/relay multiaddrs from only its
637
+ * PeerId by reading the record, re-verifying the self-signature against
638
+ * `publicKey`, checking freshness, and applying a trust gate.
639
+ *
640
+ * The signature covers `peerId`, the comma-joined `addrs`, and `updatedAt` — see
641
+ * `peerRecordSignedPayload`. `publicKey` is NOT inside the signed payload: it is
642
+ * the key the signature is verified *with*, and its libp2p-identity binding to
643
+ * `peerId` is checked separately at resolve time, so re-signing it would be
644
+ * redundant.
645
+ */
646
+ export interface PeerAddressRecord {
647
+ /** libp2p peer ID (base58btc) — the row key. */
648
+ peerId: string;
649
+ /** ed25519 public key (base64url) whose libp2p identity IS `peerId`. */
650
+ publicKey: string;
651
+ /** Current dialable multiaddrs, signaling (`/p2p-circuit`) first. */
652
+ addrs: string[];
653
+ /** epoch ms — freshness; strictly increasing per peer. */
654
+ updatedAt: number;
655
+ /** ed25519 self-signature over the signed payload, base64url. */
656
+ sig: string;
657
+ }
658
+
659
+ /**
660
+ * Outcome of {@link CadreNode.registerSelf}, surfaced so callers (e.g. the CLI
661
+ * `--owner` branch) can log what happened:
662
+ * - `inserted` — the first owner-signed INSERT of this node's `CadrePeer` row.
663
+ * - `refreshed` — a self-signed UPDATE of an existing row (heartbeat / addr change).
664
+ * - `skipped` — nothing written (no self-signing key, or not yet a member with no
665
+ * owner service to self-insert).
666
+ */
667
+ export type SelfRegistrationOutcome = 'inserted' | 'refreshed' | 'skipped';
668
+
669
+ /**
670
+ * Options for {@link CadreNode.resolvePeerAddrs}.
671
+ */
672
+ export interface ResolveOpts {
673
+ /**
674
+ * Freshness ceiling in ms. A record older than this is filtered out (a
675
+ * resolver must never hand back a dead relay reservation). Defaults to
676
+ * {@link DEFAULT_PEER_RECORD_MAX_AGE_MS}.
677
+ */
678
+ maxAgeMs?: number;
679
+ /** Return only `/p2p-circuit` signaling addrs (the WebRTC dial input). */
680
+ signalingOnly?: boolean;
681
+ /**
682
+ * Pluggable trust gate, evaluated after signature + freshness pass. Defaults
683
+ * to {@link currentMemberTrustPolicy} (any existing — therefore
684
+ * owner-vouched — CadrePeer member is trusted). Inject a stricter policy
685
+ * (e.g. from `seed-signerkey-trust-policy`) to reject otherwise-valid records
686
+ * before dialing.
687
+ */
688
+ trustPolicy?: PeerResolveTrustPolicy;
689
+ }
690
+
691
+ /**
692
+ * Context handed to a {@link PeerResolveTrustPolicy} when gating a resolution.
693
+ */
694
+ export interface PeerResolveContext {
695
+ /** The peer being resolved. */
696
+ peerId: string;
697
+ /** The record's ed25519 public key (already bound to `peerId` and verified). */
698
+ publicKey: string;
699
+ /** The party whose control network produced the record. */
700
+ partyId: string;
701
+ /** The full verified, fresh record. */
702
+ record: PeerAddressRecord;
703
+ }
704
+
705
+ /**
706
+ * Decides whether a signature-verified, fresh peer-address record should be
707
+ * trusted enough to dial. The seam through which a richer trust model
708
+ * (trust circle, pinned keys) composes with `resolvePeerAddrs`.
709
+ */
710
+ export interface PeerResolveTrustPolicy {
711
+ evaluate(ctx: PeerResolveContext): Promise<boolean> | boolean;
712
+ }
713
+
714
+ // ============================================================================
715
+ // Device Token Registry Types
716
+ // ============================================================================
717
+
718
+ /** Platform push channel a {@link DeviceTokenRecord} targets. */
719
+ export type PushPlatform = 'fcm' | 'apns';
720
+
721
+ /**
722
+ * A mobile cadre peer's self-published, freshness-stamped, self-signed platform
723
+ * push token.
724
+ *
725
+ * This is the logical shape of a `CadreControl.DeviceToken` row. A phone publishes
726
+ * its own record (signing with the ed25519 key behind its PeerId); a server peer
727
+ * resolves it from the phone's PeerId to deliver a push-wake over FCM/APNs when a
728
+ * control-network dial cannot reach the OS-suspended process. The signature covers
729
+ * `peerId`, `platform`, `token`, and `updatedAt` — see `deviceTokenSignedPayload`.
730
+ *
731
+ * Unlike {@link PeerAddressRecord}, the record carries NO public key: it is verified
732
+ * against the `CadrePeer.PublicKey` bound to the same `peerId`, so a `DeviceToken`
733
+ * with no backing `CadrePeer` row can never be resolved.
734
+ */
735
+ export interface DeviceTokenRecord {
736
+ /** libp2p peer ID (base58btc) — the row key and the CadrePeer this token belongs to. */
737
+ peerId: string;
738
+ /** Push channel: `'fcm'` (Android/Firebase) or `'apns'` (Apple). */
739
+ platform: PushPlatform;
740
+ /** Opaque platform device/registration token. */
741
+ token: string;
742
+ /** epoch ms — freshness; strictly increasing per self-update (replay guard). */
743
+ updatedAt: number;
744
+ /** ed25519 self-signature over the signed payload, base64url. */
745
+ sig: string;
746
+ }
747
+
748
+ /**
749
+ * Options for {@link CadreNode.resolveDeviceToken}.
750
+ */
751
+ export interface ResolveDeviceTokenOpts {
752
+ /**
753
+ * Optional freshness ceiling in ms. Defaults to NO ceiling (a record is fresh
754
+ * as long as its `updatedAt` is positive): unlike a relay reservation, a device
755
+ * push token stays valid until it rotates, so a long-suspended phone must remain
756
+ * resolvable for push-wake. Set this to bound staleness explicitly.
757
+ */
758
+ maxAgeMs?: number;
759
+ }
760
+
761
+ // ============================================================================
762
+ // Push Credentials (platform push delivery — see push-notifier.ts)
763
+ // ============================================================================
764
+
765
+ /**
766
+ * Platform push-delivery credentials injected into a participating node's config
767
+ * (`CadreNodeConfig.push`). Provisioned per spawned node by `cadre-host` and read
768
+ * by `createPushNotifier` to construct the FCM and/or APNs senders. A platform
769
+ * whose block is absent is simply not deliverable (the router returns a
770
+ * best-effort "no credentials" failure rather than throwing).
771
+ *
772
+ * Secret hygiene: every `privateKey` field is a secret — never logged (treated
773
+ * like the node's startup/seed tokens).
774
+ */
775
+ export interface PushCredentials {
776
+ /** FCM (Android / Firebase) service-account credentials. */
777
+ fcm?: FcmCredentials;
778
+ /** APNs (Apple) auth-key credentials. */
779
+ apns?: ApnsCredentials;
780
+ /**
781
+ * Per-`(peer, strand)` minimum gap between push-wakes the server fan-out emits —
782
+ * the anti-spam cooldown a chatty strand needs. Default
783
+ * {@link DEFAULT_PUSH_COOLDOWN_MS} (5 min). In-memory, acceptably lossy across
784
+ * restarts (`serviceWake` is idempotent, so a duplicate wake is harmless).
785
+ */
786
+ cooldownMs?: number;
787
+ /**
788
+ * Per-strand burst-coalescing window for the fan-out: a second activity trigger
789
+ * within this window is dropped (one wake is enough). Default
790
+ * {@link DEFAULT_PUSH_DEBOUNCE_MS} (10 s).
791
+ */
792
+ debounceMs?: number;
793
+ }
794
+
795
+ /** Google service-account fields needed for FCM HTTP v1 OAuth2. */
796
+ export interface FcmCredentials {
797
+ /** GCP project id → `POST https://fcm.googleapis.com/v1/projects/{projectId}/messages:send`. */
798
+ projectId: string;
799
+ /** Service-account email (JWT `iss`/`sub`). */
800
+ clientEmail: string;
801
+ /** Service-account RSA private key, PEM. Secret — never logged. */
802
+ privateKey: string;
803
+ }
804
+
805
+ /** Apple APNs auth-key (.p8) fields. */
806
+ export interface ApnsCredentials {
807
+ /** APNs key id (JWT header `kid`). */
808
+ keyId: string;
809
+ /** Apple team id (JWT `iss`). */
810
+ teamId: string;
811
+ /** App bundle id → `apns-topic` header. */
812
+ bundleId: string;
813
+ /** `.p8` ES256 private key, PEM. Secret — never logged. */
814
+ privateKey: string;
815
+ /** `true` → `api.push.apple.com`; false/undefined → `api.sandbox.push.apple.com`. */
816
+ production?: boolean;
817
+ }
818
+
819
+ // ============================================================================
820
+ // Seed Bootstrap API Types (from architecture.md)
821
+ // ============================================================================
822
+
823
+ /**
824
+ * A peer entry in a control network seed.
825
+ * Contains connection information for a cadre peer.
826
+ */
827
+ export interface SeedPeer {
828
+ /** Peer ID (libp2p identity) */
829
+ peerId: string;
830
+ /** Multiaddrs for connecting to this peer */
831
+ multiaddrs: string[];
832
+ /** Whether this peer holds an owner key */
833
+ isOwner: boolean;
834
+ /** ed25519 public key (base64url) — present on owner peers for signerKey verification */
835
+ publicKey?: string;
836
+ }
837
+
838
+ /**
839
+ * Control network seed for bootstrapping new nodes.
840
+ * Pre-populates a new node's cache to solve the cold-start problem:
841
+ * new nodes need control data to validate connections, but can't get
842
+ * data without connecting first.
843
+ */
844
+ export interface ControlNetworkSeed {
845
+ /** Party ID this seed belongs to */
846
+ partyId: string;
847
+ /** Known peers in the cadre */
848
+ peers: SeedPeer[];
849
+ /** Signature over the seed by an owner key */
850
+ signature: string;
851
+ /** The owner key that signed this seed */
852
+ signerKey: string;
853
+ }
854
+
855
+ /**
856
+ * Message sent from instigator to new node during seed delivery.
857
+ * Delivered via /sereus/seed/1.0.0 libp2p protocol.
858
+ */
859
+ export interface SeedMessage {
860
+ /** Party ID for the cadre */
861
+ partyId: string;
862
+ /** Known peers in the cadre */
863
+ peers: SeedPeer[];
864
+ /** Signature by an owner key */
865
+ signature: string;
866
+ /** The owner key that signed this message */
867
+ signerKey: string;
868
+ }
869
+
870
+ /**
871
+ * Acknowledgment message from new node to instigator.
872
+ */
873
+ export interface SeedAckMessage {
874
+ /** Whether the seed was accepted */
875
+ accepted: boolean;
876
+ /** Reason for rejection (if not accepted) */
877
+ reason?: string;
878
+ }
879
+
880
+ // ============================================================================
881
+ // Strand Wake (control-network push-wake protocol) — see strand-wake-protocol.ts
882
+ // ============================================================================
883
+
884
+ /**
885
+ * Request sent over the control network's `WAKE_PROTOCOL` from a same-cadre peer
886
+ * to a hibernating peer, asking it to bring a strand online and pull pending
887
+ * activity. The receiver gates this on cadre membership before honoring it.
888
+ */
889
+ export interface WakeRequest {
890
+ /** The strand the sender knows has pending activity. */
891
+ strandId: string;
892
+ /** Optional cause hint, e.g. `"activity"` (a server saw new traffic) or `"manual"`. */
893
+ reason?: string;
894
+ }
895
+
896
+ /**
897
+ * Acknowledgment of a {@link WakeRequest}, returned on the same stream.
898
+ */
899
+ export interface WakeAck {
900
+ /** Whether the receiver honored the wake (member + participated strand). */
901
+ accepted: boolean;
902
+ /** The strand's status after the wake (present when `accepted`). */
903
+ status?: StrandStatus;
904
+ /** Reason for rejection (non-member, unknown strand, malformed frame). */
905
+ reason?: string;
906
+ }
907
+
908
+ // ============================================================================
909
+ // Strand Address (control-network strand-address RPC) — see strand-addr-protocol.ts
910
+ // ============================================================================
911
+
912
+ /**
913
+ * Control-network request from one of a party's own cadre nodes to a sibling,
914
+ * asking "what are your live multiaddrs for this strand's separate network?".
915
+ * Used to seed a strand mesh from co-cadre nodes that already run that strand.
916
+ * The receiver gates this on cadre membership before answering.
917
+ */
918
+ export interface StrandAddrRequest {
919
+ /** The strand whose strand-network address the requester wants to seed from. */
920
+ strandId: string;
921
+ }
922
+
923
+ /**
924
+ * Response to a {@link StrandAddrRequest}, carrying the responder's strand-node
925
+ * multiaddrs, returned on the same stream.
926
+ */
927
+ export interface StrandAddrResponse {
928
+ /** Echoes the requested strand id (empty on a reject/error reply). */
929
+ strandId: string;
930
+ /**
931
+ * Dialable strand-network multiaddr strings (signaling/`p2p-circuit` first);
932
+ * empty when the responder is a non-member, or does not currently run that
933
+ * strand, or the exchange failed.
934
+ */
935
+ multiaddrs: string[];
936
+ }
937
+
938
+ /**
939
+ * Options for authorizing a new peer in the cadre.
940
+ */
941
+ export interface AuthorizePeerOptions {
942
+ /** Peer ID to authorize */
943
+ peerId: string;
944
+ /** Optional multiaddrs for the peer */
945
+ multiaddrs?: string[];
946
+ }
947
+
948
+ /**
949
+ * Result of applying a seed to a node.
950
+ */
951
+ export interface ApplySeedResult {
952
+ /** Whether the seed was successfully applied */
953
+ success: boolean;
954
+ /** Number of peers added to the peer store */
955
+ peersAdded: number;
956
+ /** Error message if not successful */
957
+ error?: string;
958
+ }
959
+
960
+ // ============================================================================
961
+ // Seed Helper Types
962
+ // ============================================================================
963
+
964
+ /**
965
+ * Node network topology type for seed helper scenarios.
966
+ */
967
+ export type NodeTopology = 'public' | 'nat';
968
+
969
+ /**
970
+ * Invite code for phone-to-server enrollment.
971
+ * Used when a server invites a phone to join the cadre.
972
+ */
973
+ export interface CadreInvite {
974
+ /** Party ID of the cadre */
975
+ partyId: string;
976
+ /** Multiaddrs to dial the owner */
977
+ ownerAddrs: string[];
978
+ /**
979
+ * Owner ed25519 public keys (base64url) of the cadre, carried out-of-band
980
+ * so a cold-start invitee can pin the trusted owner set before applying
981
+ * any seed (the seed itself cannot vouch for its own signer). Populated by
982
+ * `createInvite` from the issuer's `OwnerKey` table.
983
+ */
984
+ ownerKeys?: string[];
985
+ /** Optional invite token for validation */
986
+ token?: string;
987
+ /** Timestamp when invite was created */
988
+ createdAt: number;
989
+ /** Optional expiration timestamp */
990
+ expiresAt?: number;
991
+ }
992
+
993
+ /**
994
+ * Options for adding a drone via provider API.
995
+ */
996
+ export interface AddDroneOptions {
997
+ /** Peer ID of the new drone (returned from provider) */
998
+ dronePeerId: string;
999
+ /** Multiaddrs of the drone (returned from provider) */
1000
+ droneMultiaddrs: string[];
1001
+ }
1002
+
1003
+ /**
1004
+ * Options for adding a phone via invite flow.
1005
+ */
1006
+ export interface AddPhoneOptions {
1007
+ /** Peer ID of the phone (sent by phone when it connects) */
1008
+ phonePeerId: string;
1009
+ /** Invite token for validation (must match issued invite) */
1010
+ token?: string;
1011
+ }
1012
+
1013
+ /**
1014
+ * Result of preparing a seed for drone initialization.
1015
+ */
1016
+ export interface DroneInitResult {
1017
+ /** The seed to send to the provider API */
1018
+ seed: ControlNetworkSeed;
1019
+ /** Base64url encoded seed for transport */
1020
+ encodedSeed: string;
1021
+ }
1022
+
1023
+ /**
1024
+ * Result of creating an invite for a phone.
1025
+ */
1026
+ export interface InviteResult {
1027
+ /** The invite to share out-of-band */
1028
+ invite: CadreInvite;
1029
+ /** Base64url encoded invite for QR/link */
1030
+ encodedInvite: string;
1031
+ }
1032
+