@serfab/cadre-core 0.9.0 → 0.11.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 (193) hide show
  1. package/README.md +255 -253
  2. package/dist/bootstrap-peer-store-file.d.ts +13 -0
  3. package/dist/bootstrap-peer-store-file.js +42 -0
  4. package/dist/bootstrap-peer-store-file.js.map +1 -0
  5. package/dist/bootstrap-peer-store.d.ts +73 -0
  6. package/dist/bootstrap-peer-store.js +128 -0
  7. package/dist/bootstrap-peer-store.js.map +1 -0
  8. package/dist/cadre-node.d.ts +1121 -81
  9. package/dist/cadre-node.js +2276 -262
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/control-authorization.d.ts +93 -0
  12. package/dist/control-authorization.js +57 -0
  13. package/dist/control-authorization.js.map +1 -0
  14. package/dist/control-cohort.d.ts +26 -0
  15. package/dist/control-cohort.js +26 -0
  16. package/dist/control-cohort.js.map +1 -1
  17. package/dist/control-database.d.ts +959 -54
  18. package/dist/control-database.js +1421 -148
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +90 -10
  21. package/dist/control-formation-recorder.js +130 -14
  22. package/dist/control-formation-recorder.js.map +1 -1
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +651 -72
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-stream.d.ts +38 -4
  27. package/dist/control-stream.js +70 -4
  28. package/dist/control-stream.js.map +1 -1
  29. package/dist/control-write-retry.d.ts +161 -0
  30. package/dist/control-write-retry.js +412 -0
  31. package/dist/control-write-retry.js.map +1 -0
  32. package/dist/delegate-admission.d.ts +134 -0
  33. package/dist/delegate-admission.js +244 -0
  34. package/dist/delegate-admission.js.map +1 -0
  35. package/dist/device-token.d.ts +11 -11
  36. package/dist/device-token.js +14 -13
  37. package/dist/device-token.js.map +1 -1
  38. package/dist/ed25519-key.d.ts +26 -0
  39. package/dist/ed25519-key.js +56 -1
  40. package/dist/ed25519-key.js.map +1 -1
  41. package/dist/file-durable-slot.d.ts +20 -0
  42. package/dist/file-durable-slot.js +53 -0
  43. package/dist/file-durable-slot.js.map +1 -0
  44. package/dist/formation-approval.d.ts +157 -0
  45. package/dist/formation-approval.js +375 -0
  46. package/dist/formation-approval.js.map +1 -0
  47. package/dist/fs-atomic.d.ts +38 -0
  48. package/dist/fs-atomic.js +97 -0
  49. package/dist/fs-atomic.js.map +1 -0
  50. package/dist/identity-key.d.ts +49 -0
  51. package/dist/identity-key.js +81 -0
  52. package/dist/identity-key.js.map +1 -0
  53. package/dist/index.d.ts +17 -7
  54. package/dist/index.js +40 -6
  55. package/dist/index.js.map +1 -1
  56. package/dist/key-store-file.d.ts +2 -24
  57. package/dist/key-store-file.js +10 -77
  58. package/dist/key-store-file.js.map +1 -1
  59. package/dist/membership-connection-gater.d.ts +146 -0
  60. package/dist/membership-connection-gater.js +180 -0
  61. package/dist/membership-connection-gater.js.map +1 -0
  62. package/dist/node-local-snapshot.d.ts +109 -0
  63. package/dist/node-local-snapshot.js +182 -0
  64. package/dist/node-local-snapshot.js.map +1 -0
  65. package/dist/peer-addr-book.d.ts +92 -0
  66. package/dist/peer-addr-book.js +220 -0
  67. package/dist/peer-addr-book.js.map +1 -0
  68. package/dist/peer-authorization.d.ts +135 -18
  69. package/dist/peer-authorization.js +152 -21
  70. package/dist/peer-authorization.js.map +1 -1
  71. package/dist/peer-record.d.ts +21 -8
  72. package/dist/peer-record.js +26 -10
  73. package/dist/peer-record.js.map +1 -1
  74. package/dist/relay-addrs.d.ts +45 -0
  75. package/dist/relay-addrs.js +103 -0
  76. package/dist/relay-addrs.js.map +1 -0
  77. package/dist/relay-reservation.d.ts +266 -0
  78. package/dist/relay-reservation.js +613 -0
  79. package/dist/relay-reservation.js.map +1 -0
  80. package/dist/seed-bootstrap.d.ts +228 -56
  81. package/dist/seed-bootstrap.js +340 -198
  82. package/dist/seed-bootstrap.js.map +1 -1
  83. package/dist/seed-trust-policy.d.ts +47 -21
  84. package/dist/seed-trust-policy.js +24 -15
  85. package/dist/seed-trust-policy.js.map +1 -1
  86. package/dist/strand-addr-protocol.d.ts +42 -13
  87. package/dist/strand-addr-protocol.js +58 -52
  88. package/dist/strand-addr-protocol.js.map +1 -1
  89. package/dist/strand-backfill.d.ts +109 -0
  90. package/dist/strand-backfill.js +279 -0
  91. package/dist/strand-backfill.js.map +1 -0
  92. package/dist/strand-cohort.d.ts +4 -37
  93. package/dist/strand-cohort.js +4 -15
  94. package/dist/strand-cohort.js.map +1 -1
  95. package/dist/strand-database.d.ts +11 -16
  96. package/dist/strand-database.js +19 -7
  97. package/dist/strand-database.js.map +1 -1
  98. package/dist/strand-formation-manager.d.ts +36 -7
  99. package/dist/strand-formation-manager.js +115 -15
  100. package/dist/strand-formation-manager.js.map +1 -1
  101. package/dist/strand-formation-protocol.d.ts +103 -4
  102. package/dist/strand-formation-protocol.js +232 -4
  103. package/dist/strand-formation-protocol.js.map +1 -1
  104. package/dist/strand-instance-manager.d.ts +88 -19
  105. package/dist/strand-instance-manager.js +178 -34
  106. package/dist/strand-instance-manager.js.map +1 -1
  107. package/dist/strand-member-registry.d.ts +5 -5
  108. package/dist/strand-member-registry.js +18 -10
  109. package/dist/strand-member-registry.js.map +1 -1
  110. package/dist/strand-membership-writer.d.ts +484 -88
  111. package/dist/strand-membership-writer.js +751 -128
  112. package/dist/strand-membership-writer.js.map +1 -1
  113. package/dist/strand-solicitation.d.ts +99 -33
  114. package/dist/strand-solicitation.js +100 -52
  115. package/dist/strand-solicitation.js.map +1 -1
  116. package/dist/strand-transport-key.d.ts +40 -0
  117. package/dist/strand-transport-key.js +56 -0
  118. package/dist/strand-transport-key.js.map +1 -0
  119. package/dist/strand-wake-protocol.d.ts +9 -7
  120. package/dist/strand-wake-protocol.js +22 -46
  121. package/dist/strand-wake-protocol.js.map +1 -1
  122. package/dist/strand-watcher.d.ts +17 -2
  123. package/dist/strand-watcher.js +47 -3
  124. package/dist/strand-watcher.js.map +1 -1
  125. package/dist/trusted-owner-store-file.d.ts +12 -0
  126. package/dist/trusted-owner-store-file.js +39 -0
  127. package/dist/trusted-owner-store-file.js.map +1 -0
  128. package/dist/trusted-owner-store.d.ts +64 -0
  129. package/dist/trusted-owner-store.js +126 -0
  130. package/dist/trusted-owner-store.js.map +1 -0
  131. package/dist/types.d.ts +307 -44
  132. package/dist/types.js +13 -0
  133. package/dist/types.js.map +1 -1
  134. package/package.json +20 -8
  135. package/src/arachnode-stub.ts +159 -159
  136. package/src/bootstrap-peer-store-file.ts +44 -0
  137. package/src/bootstrap-peer-store.ts +172 -0
  138. package/src/cadre-node.ts +5158 -2981
  139. package/src/canonical-json.ts +30 -30
  140. package/src/control-authorization.ts +114 -0
  141. package/src/control-cohort.ts +130 -103
  142. package/src/control-database.ts +2406 -948
  143. package/src/control-formation-recorder.ts +305 -151
  144. package/src/control-schema.ts +651 -72
  145. package/src/control-stream.ts +205 -128
  146. package/src/control-write-retry.ts +483 -0
  147. package/src/delegate-admission.ts +302 -0
  148. package/src/device-token.ts +94 -89
  149. package/src/diagnostics/connection-path.ts +277 -277
  150. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  151. package/src/ed25519-key.ts +66 -1
  152. package/src/enrollment.ts +199 -199
  153. package/src/file-durable-slot.ts +61 -0
  154. package/src/formation-approval.ts +604 -0
  155. package/src/fs-atomic.ts +107 -0
  156. package/src/hibernation-manager.ts +437 -437
  157. package/src/identity-key.ts +109 -0
  158. package/src/index.ts +137 -5
  159. package/src/key-store-file.ts +132 -203
  160. package/src/key-store.ts +99 -99
  161. package/src/membership-connection-gater.ts +204 -0
  162. package/src/node-local-snapshot.ts +260 -0
  163. package/src/peer-addr-book.ts +250 -0
  164. package/src/peer-authorization.ts +259 -81
  165. package/src/peer-record.ts +164 -146
  166. package/src/push-credentials.ts +84 -84
  167. package/src/push-node.ts +64 -64
  168. package/src/push-notifier-apns.ts +247 -247
  169. package/src/push-notifier-fcm.ts +220 -220
  170. package/src/push-notifier-shared.ts +28 -28
  171. package/src/push-notifier.ts +52 -52
  172. package/src/relay-addrs.ts +111 -0
  173. package/src/relay-reservation.ts +823 -0
  174. package/src/seed-bootstrap.ts +409 -209
  175. package/src/seed-trust-policy.ts +140 -107
  176. package/src/strand-addr-protocol.ts +441 -410
  177. package/src/strand-backfill.ts +366 -0
  178. package/src/strand-cohort.ts +38 -77
  179. package/src/strand-database.ts +202 -204
  180. package/src/strand-formation-manager.ts +491 -368
  181. package/src/strand-formation-protocol.ts +692 -391
  182. package/src/strand-instance-manager.ts +201 -46
  183. package/src/strand-member-key.ts +39 -39
  184. package/src/strand-member-registry.ts +182 -177
  185. package/src/strand-membership-writer.ts +938 -146
  186. package/src/strand-solicitation.ts +472 -407
  187. package/src/strand-transport-key.ts +58 -0
  188. package/src/strand-wake-payload.ts +32 -32
  189. package/src/strand-wake-protocol.ts +314 -331
  190. package/src/strand-watcher.ts +314 -251
  191. package/src/trusted-owner-store-file.ts +41 -0
  192. package/src/trusted-owner-store.ts +171 -0
  193. package/src/types.ts +1309 -1032
package/src/types.ts CHANGED
@@ -1,1032 +1,1309 @@
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
-
1
+ import type { ConnectionGater, Libp2p, PeerId, PrivateKey } from '@libp2p/interface';
2
+ import type { IRawStorage, Libp2pTransports } from '@optimystic/db-p2p';
3
+ import type { IPeerNetwork, IRepo } from '@optimystic/db-core';
4
+ import type { StrandBackfillConfig } from './strand-backfill.js';
5
+ import type { StrandDatabase } from './strand-database.js';
6
+ import type { SeedTrustPolicy } from './seed-trust-policy.js';
7
+ import type { KeyStore, KeyId } from './key-store.js';
8
+ import type { TrustedOwnerStore, TrustSource } from './trusted-owner-store.js';
9
+ import type { BootstrapPeerStore } from './bootstrap-peer-store.js';
10
+ import type { PushNotifier } from './push-notifier.js';
11
+ import type { RevocableTable } from './control-authorization.js';
12
+
13
+ /**
14
+ * Extended Libp2p node with the coordinatedRepo attached by db-p2p's
15
+ * createLibp2pNode after node creation (not surfaced on the base Libp2p type).
16
+ */
17
+ export interface Libp2pNodeWithRepo extends Libp2p {
18
+ coordinatedRepo: IRepo;
19
+ /**
20
+ * The node's key-addressed peer network, attached by db-p2p's factory alongside
21
+ * `coordinatedRepo` (`libp2p-node-base.ts`). Optional deliberately: the base
22
+ * factory always assigns it, but it is not part of the upstream node type, so
23
+ * declaring it required would be a claim this repo cannot enforce. The strand
24
+ * backfill (`strand-backfill.ts`) logs once and stays inert when it is absent.
25
+ */
26
+ keyNetwork?: IPeerNetwork;
27
+ }
28
+
29
+ /**
30
+ * Node profile determines storage participation
31
+ */
32
+ export type NodeProfile = 'transaction' | 'storage';
33
+
34
+ /**
35
+ * Strand filter configuration - determines which strands this node participates in
36
+ */
37
+ export type StrandFilter =
38
+ | { mode: 'all' } // All strands (default for servers)
39
+ | { mode: 'sAppId'; sAppId: string } // Only strands for specific sApp
40
+ | { mode: 'strandId'; strandId: string } // Single specific strand
41
+ | { mode: 'none' }; // Control network only
42
+
43
+ /**
44
+ * Latency hint for strand hibernation behavior
45
+ */
46
+ export type LatencyHint = 'realtime' | 'interactive' | 'background' | 'archive';
47
+
48
+ /**
49
+ * Hibernation timeout configuration per latency hint (in milliseconds)
50
+ */
51
+ export interface HibernationTimeouts {
52
+ /** Time before transitioning from active to idle */
53
+ idleTimeout: number;
54
+ /** Time before transitioning from idle to hibernating */
55
+ hibernateTimeout: number;
56
+ /**
57
+ * Base interval for the FIRST check-in after hibernating. Successive
58
+ * no-activity check-ins escalate this delay by {@link checkInBackoffFactor}
59
+ * (see {@link HibernationManager}'s self-rescheduling check-in chain).
60
+ */
61
+ checkInInterval: number;
62
+ /**
63
+ * Multiplier applied to the check-in delay after each check-in that finds no
64
+ * pending activity (must be >= 1; 1 disables escalation). Default 2 →
65
+ * doubling: base, base×2, base×4, … until {@link checkInMaxInterval}.
66
+ */
67
+ checkInBackoffFactor: number;
68
+ /**
69
+ * Upper bound on the escalating check-in delay — the concrete realization of
70
+ * the architecture's "minutes → hours → days" ceiling for this hint. Backoff
71
+ * never schedules a delay longer than this.
72
+ */
73
+ checkInMaxInterval: number;
74
+ }
75
+
76
+ /**
77
+ * Default hibernation timeouts per latency hint.
78
+ *
79
+ * `checkInInterval` is the BASE delay; `checkInMaxInterval` is the per-hint
80
+ * ceiling the exponential backoff escalates toward (interactive minutes→~1h,
81
+ * background minutes→~6h, archive ~1h→~3 days).
82
+ */
83
+ export const HIBERNATION_TIMEOUTS: Record<LatencyHint, HibernationTimeouts> = {
84
+ realtime: {
85
+ idleTimeout: Infinity, // Never idle
86
+ hibernateTimeout: Infinity, // Never hibernate
87
+ checkInInterval: Infinity, // N/A
88
+ checkInBackoffFactor: 2,
89
+ checkInMaxInterval: Infinity // N/A
90
+ },
91
+ interactive: {
92
+ idleTimeout: 5 * 60 * 1000, // 5 minutes
93
+ hibernateTimeout: 15 * 60 * 1000, // 15 minutes after idle
94
+ checkInInterval: 30 * 1000, // base: 30 seconds
95
+ checkInBackoffFactor: 2,
96
+ checkInMaxInterval: 60 * 60 * 1000 // cap: ~1 hour
97
+ },
98
+ background: {
99
+ idleTimeout: 1 * 60 * 1000, // 1 minute
100
+ hibernateTimeout: 5 * 60 * 1000, // 5 minutes after idle
101
+ checkInInterval: 5 * 60 * 1000, // base: 5 minutes
102
+ checkInBackoffFactor: 2,
103
+ checkInMaxInterval: 6 * 60 * 60 * 1000 // cap: ~6 hours
104
+ },
105
+ archive: {
106
+ idleTimeout: 10 * 1000, // 10 seconds
107
+ hibernateTimeout: 30 * 1000, // 30 seconds after idle
108
+ checkInInterval: 60 * 60 * 1000, // base: 1 hour
109
+ checkInBackoffFactor: 2,
110
+ checkInMaxInterval: 3 * 24 * 60 * 60 * 1000 // cap: ~3 days
111
+ }
112
+ };
113
+
114
+ /**
115
+ * Storage provider - either an `IRawStorage` instance or a factory function.
116
+ * Factory functions are useful for creating strand-specific storage instances.
117
+ *
118
+ * **Called once per scope per runtime lifetime.** The scopes are the literal string
119
+ * `'control'` (once per `CadreNode.start()`) and each strand id (once per
120
+ * `startStrand`). Hibernation — `quiesceStrand` then `resumeStrand` — reuses the
121
+ * store already resolved for that strand and does NOT re-enter this callback.
122
+ *
123
+ * It IS re-entered for a scope after that scope's runtime has stopped
124
+ * (`stopStrand`, or a `stop()` then `start()` cycle on one `CadreNode`), so it must
125
+ * be able to hand back a store over the same durable backend a second time. A
126
+ * factory may mint a fresh object per call; it must not *need* to.
127
+ *
128
+ * cadre-core disposes only its own cache wrapper — it never closes the store you
129
+ * returned. Closing the underlying handle stays the embedder's job.
130
+ *
131
+ * **Prefer the factory form for any persistent backend.** One instance handed to
132
+ * every scope also shares ONE cache wrapper (`wrapStorageWithCache` memoizes per
133
+ * inner instance), and no scope solely owns it — so the first scope to stop retires
134
+ * the wrapper the still-running scopes are reading through. See
135
+ * `tickets/backlog/debt-storage-cache-wrap-unrefcounted.md`; an in-memory store is
136
+ * unaffected, since it is never wrapped.
137
+ */
138
+ export type RawStorageProvider = IRawStorage | ((strandId: string) => IRawStorage);
139
+
140
+ /**
141
+ * Storage configuration for storage profile nodes
142
+ */
143
+ export interface StorageConfig {
144
+ /**
145
+ * Storage provider - either an IRawStorage instance or a factory function.
146
+ * See {@link RawStorageProvider} for how often cadre-core calls it.
147
+ *
148
+ * For Node.js environments, use FileRawStorage from @optimystic/db-p2p-storage-fs:
149
+ * ```typescript
150
+ * import { FileRawStorage } from '@optimystic/db-p2p-storage-fs';
151
+ * storage: { provider: (strandId) => new FileRawStorage(`./data/${strandId}`) }
152
+ * ```
153
+ *
154
+ * For React Native, use the appropriate storage from @optimystic/db-p2p-storage-rn:
155
+ * ```typescript
156
+ * import { LevelDBRawStorage } from '@optimystic/db-p2p-storage-rn';
157
+ * // `db` is an open LevelDB handle (see `openOptimysticRNDb` over `rn-leveldb`)
158
+ * storage: { provider: (strandId) => new LevelDBRawStorage(openDb(`sereus-${strandId}`)) }
159
+ * ```
160
+ *
161
+ * For in-memory storage (testing):
162
+ * ```typescript
163
+ * import { MemoryRawStorage } from '@optimystic/db-p2p';
164
+ * storage: { provider: () => new MemoryRawStorage() }
165
+ * ```
166
+ */
167
+ provider: RawStorageProvider;
168
+ quotaBytes?: number;
169
+ }
170
+
171
+ /**
172
+ * Network configuration for libp2p
173
+ */
174
+ export interface NetworkConfig {
175
+ listenAddrs?: string[];
176
+ /**
177
+ * Addresses to advertise to peers instead of `listenAddrs` — for a node behind
178
+ * NAT or a reverse proxy that is reachable at a different address than it binds
179
+ * (e.g. `mynode.example.com:4001` in front of a `0.0.0.0:4001` listener).
180
+ *
181
+ * Accepted (settable in `cadre.yaml`, via `CADRE_ANNOUNCE_ADDRS`, and through the
182
+ * Docker entrypoint) but **not yet applied**: libp2p only takes announce addresses
183
+ * at construction (`addresses.announce` / `addresses.appendAnnounce`), and
184
+ * `@optimystic/db-p2p`'s `NodeOptions` has no field for either — there is nothing
185
+ * in this repo to wire this into. `CadreNode.start()` warns when this is set,
186
+ * rather than pretending it works. Unblocked by the `announce-addrs-option`
187
+ * request filed against `@optimystic/db-p2p`; wiring lands here once this repo's
188
+ * dependency range moves to a version carrying it.
189
+ *
190
+ * Use {@link relayAddrs} for reachability behind NAT today (a reserved relay slot
191
+ * gives the node a real dialable circuit address), or `inviteAddressResolver` to
192
+ * substitute a reachable address into invite payloads specifically — neither
193
+ * changes what this node advertises on the wire, but both cover the operator need
194
+ * this field cannot yet.
195
+ */
196
+ announceAddrs?: string[];
197
+ /**
198
+ * Circuit-relay servers this node reserves a slot on, so peers can reach it
199
+ * from behind NAT. Each entry is the relay's DIRECT dial multiaddr ending in
200
+ * its peerId — `/dns4/relay.example.com/tcp/4001/p2p/12D3KooW…` — with no
201
+ * `/p2p-circuit` suffix (one is appended for you; an entry that already has
202
+ * one is passed through unchanged).
203
+ *
204
+ * This is sugar for a circuit entry in {@link listenAddrs}: `relay-addrs.ts`
205
+ * resolves the two into one listen list, and listening on a relay's circuit
206
+ * addr is what makes libp2p dial it and hold the reservation. A relay named
207
+ * here therefore also becomes a delegate-announce target, so this node's
208
+ * strand nodes may reserve on it too (see `delegate-admission.ts`).
209
+ *
210
+ * Setting this gives the node a listener even when `listenAddrs` is `[]` —
211
+ * that is the point of naming a relay, but note that React Native hosts
212
+ * (`reference-app-rn`'s `cadre-phone.ts`) deliberately do NOT listen, and
213
+ * must not acquire a listener by accident.
214
+ *
215
+ * A malformed entry throws at node start rather than being silently dropped.
216
+ */
217
+ relayAddrs?: string[];
218
+ /**
219
+ * Enable circuit relay server - allows this node to relay connections for other peers.
220
+ * When undefined, defaults to true for storage profile nodes (they typically have
221
+ * better connectivity and uptime), false for transaction profile nodes.
222
+ */
223
+ enableRelay?: boolean;
224
+ /**
225
+ * Custom libp2p transports. When omitted, the default transports from
226
+ * `@optimystic/db-p2p` are used (TCP + circuit relay for Node.js).
227
+ *
228
+ * React Native apps must supply WebSocket-based transports because TCP
229
+ * is not available in the RN runtime:
230
+ * ```typescript
231
+ * import { webSockets } from '@libp2p/websockets';
232
+ * import { circuitRelayTransport } from '@libp2p/circuit-relay-v2';
233
+ *
234
+ * network: {
235
+ * transports: [webSockets(), circuitRelayTransport()],
236
+ * listenAddrs: [] // RN nodes typically cannot listen
237
+ * }
238
+ * ```
239
+ */
240
+ transports?: Libp2pTransports;
241
+ /**
242
+ * Optional async resolver returning the multiaddrs to embed in invites
243
+ * (and other owner-address contexts). When unset, `libp2pNode.getMultiaddrs()`
244
+ * is used. Hosts behind NAT supply this to substitute their DDNS hostname
245
+ * and externally-mapped port — see `@serfab/cadre-host`'s NatService.
246
+ */
247
+ inviteAddressResolver?: () => Promise<string[]>;
248
+ /**
249
+ * Optional libp2p connection gater, threaded to both the control node and every
250
+ * strand's cohort node. libp2p's browser default denies dialing insecure
251
+ * WebSockets and private/loopback addresses; callers that must dial local or
252
+ * unsecured peers (the web reference dialing a `127.0.0.1/.../ws` responder,
253
+ * Playwright e2e, RN simulators) supply a permissive gater here — e.g.
254
+ * `{ denyDialMultiaddr: () => false }`. See `@optimystic/db-p2p`'s
255
+ * `libp2p-node-base` for the underlying option.
256
+ *
257
+ * On the CONTROL node this gater is composed with the built-in membership
258
+ * admission gate (`membership-connection-gater.ts`): every hook supplied here
259
+ * is honored unchanged, and on inbound encrypted connections a deny from
260
+ * either this gater or the membership policy denies. Strand cohort nodes
261
+ * receive this gater as-is (their peers are legitimately cross-party).
262
+ */
263
+ connectionGater?: ConnectionGater;
264
+ /**
265
+ * Tuning for the proactive control-cohort dial routine
266
+ * ({@link CadreNode.reconcileControlCohort}), which keeps a party's control
267
+ * nodes connected so the `CadreControl` collections form a replicating cohort.
268
+ * Every field is optional; omit for the defaults
269
+ * ({@link DEFAULT_CONTROL_COHORT_TARGET_DEGREE} /
270
+ * {@link DEFAULT_CONTROL_COHORT_RECONCILE_MS} /
271
+ * {@link DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS} / `STRAND_PEER_ADDR_REFRESH_MS`).
272
+ */
273
+ controlCohort?: {
274
+ /**
275
+ * Cap on the number of NON-owner siblings dialed per reconcile pass
276
+ * (backbone/owner members are always dialed and do not count). Defaults
277
+ * to {@link DEFAULT_CONTROL_COHORT_TARGET_DEGREE}.
278
+ */
279
+ targetDegree?: number;
280
+ /**
281
+ * Recurring reconcile cadence in ms. Defaults to
282
+ * {@link DEFAULT_CONTROL_COHORT_RECONCILE_MS}.
283
+ */
284
+ reconcileMs?: number;
285
+ /**
286
+ * Budget for ONE sibling's proactive dial, in ms. Bounds a pass at
287
+ * (dialed siblings) × this, instead of leaving it to each address's own
288
+ * libp2p attempt timeout multiplied by address fan-out and relay hops.
289
+ * Defaults to {@link DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS}.
290
+ */
291
+ dialTimeoutMs?: number;
292
+ /**
293
+ * How often each running strand re-resolves its siblings' strand-network
294
+ * addresses into its own libp2p address book — a step of the reconcile pass,
295
+ * on its own much longer throttle. Defaults to `STRAND_PEER_ADDR_REFRESH_MS`
296
+ * (10 min); must stay well under the peerStore's one-hour address expiry.
297
+ */
298
+ strandAddrRefreshMs?: number;
299
+ };
300
+ }
301
+
302
+ /**
303
+ * Hibernation configuration
304
+ */
305
+ export interface HibernationConfig {
306
+ enabled: boolean;
307
+ defaultLatencyHint?: LatencyHint;
308
+ /** Custom timeouts per latency hint (overrides defaults) */
309
+ customTimeouts?: Partial<Record<LatencyHint, Partial<HibernationTimeouts>>>;
310
+ /**
311
+ * How long a hibernating strand stays resumed during a check-in to let its
312
+ * strand network connect to reachable cohort peers (and the app drive
313
+ * pull-on-read activity) before re-hibernating if still idle. Defaults to
314
+ * {@link DEFAULT_CHECKIN_WINDOW_MS}.
315
+ */
316
+ checkInWindowMs?: number;
317
+ }
318
+
319
+ /**
320
+ * Default duration of the resume-and-probe window during a strand check-in.
321
+ * See {@link HibernationConfig.checkInWindowMs}.
322
+ */
323
+ export const DEFAULT_CHECKIN_WINDOW_MS = 15 * 1000;
324
+
325
+ /**
326
+ * Control network configuration
327
+ */
328
+ export interface ControlNetworkConfig {
329
+ partyId: string;
330
+ bootstrapNodes: string[];
331
+ /** Optional path to the control schema file (defaults to bundled schema) */
332
+ schemaPath?: string;
333
+ }
334
+
335
+ /**
336
+ * Replication-breadth constants, both networks' cluster policies, and the strand
337
+ * resolver, re-exported so cadre embedders, the SQL plugin and the integration
338
+ * harness share one definition. Defined in `@serfab/quereus-plugin-sereus`
339
+ * because that package also creates libp2p nodes and cannot depend on this one.
340
+ * The control network's breadth is fixed ({@link CONTROL_REPLICATION_BREADTH},
341
+ * not configurable) and so is its consensus policy ({@link CONTROL_CLUSTER_POLICY}
342
+ * — notably the super-majority threshold, which it leaves at Optimystic's default
343
+ * by omission); the strand breadth defaults to
344
+ * {@link CadreNodeConfig.strandClusterSize} while its policy is the fixed
345
+ * {@link STRAND_CLUSTER_POLICY}.
346
+ */
347
+ export {
348
+ MIN_CLUSTER_SIZE,
349
+ CONTROL_REPLICATION_BREADTH,
350
+ CONTROL_CLUSTER_POLICY,
351
+ DEFAULT_STRAND_CLUSTER_SIZE,
352
+ STRAND_CLUSTER_POLICY,
353
+ resolveStrandClusterSize
354
+ } from '@serfab/quereus-plugin-sereus';
355
+
356
+ /**
357
+ * Main configuration for a CadreNode
358
+ */
359
+ export interface CadreNodeConfig {
360
+ /**
361
+ * If provided, use this keypair for the node identity (direct injection).
362
+ * Mutually exclusive with {@link keyStore} — supplying both is a configuration
363
+ * error (fail closed) thrown by `start()` before any network bring-up.
364
+ */
365
+ privateKey?: PrivateKey;
366
+
367
+ /**
368
+ * Pluggable secure store for node key material. When set, the node loads its
369
+ * identity from `keyStore` under {@link identityKeyId}, generating + persisting
370
+ * a fresh Ed25519 key on first run (protobuf bytes are the canonical stored
371
+ * form). Mutually exclusive with {@link privateKey}. Absent ⇒ legacy behavior
372
+ * (use `privateKey`, else libp2p generates an ephemeral key).
373
+ *
374
+ * In the single-key reference model the owner signing key is *derived from*
375
+ * the node identity (see {@link CadreNode.getIdentityOwnerKey}), so
376
+ * protecting the identity in a secure enclave protects the owner key too.
377
+ * A future separate-owner slot (`ownerKeyId`) is anticipated but not
378
+ * built here.
379
+ */
380
+ keyStore?: KeyStore;
381
+
382
+ /** Slot id for the node identity in {@link keyStore}. Default: `'cadre/identity'`. */
383
+ identityKeyId?: KeyId;
384
+
385
+ /** Control network connection settings */
386
+ controlNetwork: ControlNetworkConfig;
387
+
388
+ /** Node profile: transaction-only or storage */
389
+ profile: NodeProfile;
390
+
391
+ /** Which strands to participate in */
392
+ strandFilter?: StrandFilter;
393
+
394
+ /** Storage configuration (only for storage profile) */
395
+ storage?: StorageConfig;
396
+
397
+ /** Network configuration */
398
+ network?: NetworkConfig;
399
+
400
+ /**
401
+ * Number of nodes Optimystic is told a **strand** network's replication cluster
402
+ * should have, for every strand this node starts. The control network is not
403
+ * configurable — it always replicates to {@link CONTROL_REPLICATION_BREADTH}
404
+ * nodes, which is above any party's node count, because every member reads the
405
+ * whole control database and a member that misses a write may never learn the
406
+ * fact (see that constant for the full reasoning).
407
+ *
408
+ * Every node on the same strand should use the same value: the number bounds the
409
+ * cohort a member independently derives, and Optimystic's cluster-membership gate
410
+ * can reject a coordinator's smaller declared set as a downsize against a larger
411
+ * derived view.
412
+ *
413
+ * Frozen when the strand's libp2p node is created; a change takes effect on
414
+ * restart, not when cadre membership grows. Defaults to
415
+ * {@link DEFAULT_STRAND_CLUSTER_SIZE} (4 — the smallest breadth whose 0.75
416
+ * super-majority still commits with one holder offline); anything below
417
+ * {@link MIN_CLUSTER_SIZE} is rejected before a node is created. The cost of a
418
+ * small value is replication breadth and reliance on read repair, not commit
419
+ * correctness — but at 2 that read repair cannot converge, because a lone
420
+ * corroborator's stale answer is accepted as the cluster's truth.
421
+ */
422
+ strandClusterSize?: number;
423
+
424
+ /**
425
+ * Tuning for the strand peer-join block catch-up (see `strand-backfill.ts`):
426
+ * when a strand's libp2p node connects to a peer this runtime has not yet
427
+ * caught up, every block in the strand's own raw store is pushed to that peer,
428
+ * so a machine that joined the strand after blocks were committed still ends
429
+ * up physically holding them. Applies to every strand this node starts;
430
+ * strand-only — the control network has its own row-level re-issue queue
431
+ * (`drainPendingControlReplication`). Omit for the defaults
432
+ * (`DEFAULT_STRAND_BACKFILL`); `{ enabled: false }` restores the
433
+ * no-backfill behaviour.
434
+ */
435
+ strandBackfill?: StrandBackfillConfig;
436
+
437
+ /** Hibernation configuration */
438
+ hibernation?: HibernationConfig;
439
+
440
+ /** Polling interval for strand watcher in ms (default: 5000) */
441
+ strandWatchInterval?: number;
442
+
443
+ /**
444
+ * Require a valid author signature on every sApp schema before a strand is
445
+ * formed or joined. Defaults to true (fail closed): an unsigned schema is
446
+ * rejected before any libp2p node or schema DDL is brought up. Set false ONLY
447
+ * for dev/test where unsigned demo schemas are used.
448
+ */
449
+ requireSignedSchemas?: boolean;
450
+
451
+ /**
452
+ * Node-wide default trust anchor for INBOUND control-network seeds. Forwarded
453
+ * into every SeedBootstrapService this node constructs (owner, receive-only
454
+ * listener, and the temp service used by applySeed when no service exists), and
455
+ * used as the service-level default the libp2p seed-protocol handler relies on
456
+ * (that path has no per-call override seam). Defaults to anchoredTrustPolicy()
457
+ * inside SeedBootstrapService when unset — a node whose node-local trusted-owner
458
+ * anchor was never seeded then rejects every seed. A per-call
459
+ * `applySeed(seed, { trustPolicy })` override still wins over this default for
460
+ * callers that hold out-of-band material (e.g. a pinned key from a CadreInvite).
461
+ */
462
+ seedTrustPolicy?: SeedTrustPolicy;
463
+
464
+ /**
465
+ * Node-local trusted-owner anchor (see `trusted-owner-store.ts`): the
466
+ * NON-replicated, per-party record of owner keys established out of band —
467
+ * the anchor membership/seed trust can rest on, since the replicated
468
+ * `OwnerKey` table can be polluted by a stranger's self-genesis. Absent ⇒ an
469
+ * in-memory store is created at start() (ephemeral: anchored trust does not
470
+ * survive the process).
471
+ */
472
+ trustedOwners?: {
473
+ /**
474
+ * Injected store instance — e.g. a `FileTrustedOwnerStore` from the
475
+ * Node-only subpath `@serfab/cadre-core/trusted-owner-store-file`,
476
+ * persisted in the node's state directory (same injection/isolation pattern
477
+ * as {@link keyStore}). Its `partyId` must match `controlNetwork.partyId`;
478
+ * start() fails closed on a mismatch.
479
+ */
480
+ store?: TrustedOwnerStore;
481
+ /**
482
+ * Owner keys (base64url ed25519) established out of band and seeded into
483
+ * the store during start(): operator pins (e.g. cadre-cli
484
+ * `--pin-owner-key` / `CADRE_OWNER_KEYS`) or a `CadreInvite.ownerKeys`
485
+ * already known at config time. Seeding is idempotent across restarts.
486
+ */
487
+ pinnedKeys?: string[];
488
+ /**
489
+ * Provenance recorded for {@link pinnedKeys}. Default: 'operator'.
490
+ * ('genesis' is reserved for the node's own founding key, seeded
491
+ * internally by `initializeSeedBootstrap`.)
492
+ */
493
+ pinnedSource?: Exclude<TrustSource, 'genesis'>;
494
+ };
495
+
496
+ /**
497
+ * Node-local cold-start bootstrap-peer store (see `bootstrap-peer-store.ts`):
498
+ * the owner addresses an applied seed nominated, kept so
499
+ * `reconcileControlCohort`'s cold-start branch can keep retrying a node that
500
+ * was seeded but never managed to connect. Sibling of {@link trustedOwners} —
501
+ * same NON-replicated, per-party, injected-backend shape — but nothing here is
502
+ * trust-bearing: these are dial hints only, and every address is re-bound to
503
+ * its peer id before the dial. Absent ⇒ an in-memory store is created at
504
+ * start() (ephemeral: the retry set does not survive the process, and such a
505
+ * node is stranded permanently if it restarts before connecting).
506
+ *
507
+ * The Node CLI, the browser, and React Native all inject a durable backend
508
+ * today; only NativeScript stays ephemeral, tracked by the
509
+ * `ns-durable-node-local-stores` ticket (which covers the same gap for
510
+ * {@link trustedOwners}). A new platform needs no new store class: supply a
511
+ * `DurableSlot` for the platform's storage and inject
512
+ * `PersistentBootstrapPeerStore.open(slot, partyId)` /
513
+ * `PersistentTrustedOwnerStore.open(slot, partyId)`.
514
+ */
515
+ bootstrapPeers?: {
516
+ /**
517
+ * Injected store instance — e.g. a `FileBootstrapPeerStore` from the
518
+ * Node-only subpath `@serfab/cadre-core/bootstrap-peer-store-file`, persisted
519
+ * in the node's state directory (same injection/isolation pattern as
520
+ * {@link keyStore} / {@link trustedOwners}). Its `partyId` must match
521
+ * `controlNetwork.partyId`; start() fails closed on a mismatch.
522
+ */
523
+ store?: BootstrapPeerStore;
524
+ };
525
+
526
+ /**
527
+ * Platform push-delivery for suspended mobile peers. When present, the node's
528
+ * server fan-out can deliver strand-wake data messages over the platform push
529
+ * channel (FCM/APNs). Absent ⇒ no platform push (control-network push-wake only).
530
+ *
531
+ * The `notifier` is **injected**, not constructed here: a Node host builds it
532
+ * from `@serfab/cadre-core/push-node` (`createPushNotifier(credentials)`) and
533
+ * passes the instance, so the FCM/APNs modules (`node:crypto`/`node:http2`)
534
+ * stay out of the cross-platform core graph. Ownership transfers to the node on
535
+ * injection — `CadreNode.stop` closes the notifier (via `PushFanoutService`),
536
+ * releasing its APNs HTTP/2 session; a host must NOT also close an injected
537
+ * notifier itself. `cooldownMs`/`debounceMs` carry the fan-out anti-spam policy.
538
+ */
539
+ push?: {
540
+ /** The Node-constructed push router (see `@serfab/cadre-core/push-node`). */
541
+ notifier: PushNotifier;
542
+ /**
543
+ * Per-`(peer, strand)` minimum gap between push-wakes the fan-out emits.
544
+ * Default {@link DEFAULT_PUSH_COOLDOWN_MS} (5 min).
545
+ */
546
+ cooldownMs?: number;
547
+ /**
548
+ * Per-strand burst-coalescing window: a second trigger within it is dropped.
549
+ * Default {@link DEFAULT_PUSH_DEBOUNCE_MS} (10 s).
550
+ */
551
+ debounceMs?: number;
552
+ };
553
+ }
554
+
555
+ /**
556
+ * Status of a strand instance
557
+ */
558
+ export type StrandStatus =
559
+ | 'starting'
560
+ | 'active'
561
+ | 'idle'
562
+ | 'hibernating'
563
+ | 'stopping'
564
+ | 'stopped'
565
+ | 'error';
566
+
567
+ /**
568
+ * App information from strand header
569
+ */
570
+ export interface SAppInfo {
571
+ id: string;
572
+ version: string;
573
+ schema: string;
574
+ signature?: string;
575
+ }
576
+
577
+ /**
578
+ * Strand instance state
579
+ */
580
+ export interface StrandInstance {
581
+ strandId: string;
582
+ status: StrandStatus;
583
+ sAppInfo?: SAppInfo;
584
+
585
+ /** The libp2p node for this strand (only when active/idle) */
586
+ libp2pNode?: Libp2p;
587
+
588
+ /** The Quereus database for this strand (only when active/idle) */
589
+ database?: StrandDatabase;
590
+
591
+ /** Membership info for closed strands */
592
+ memberKey?: string;
593
+ memberPrivateKey?: string;
594
+
595
+ /** Activity tracking */
596
+ connectedPeers: number;
597
+ lastActivity: Date;
598
+ nextCheckIn?: Date;
599
+
600
+ /** Latency hint from app or override */
601
+ latencyHint: LatencyHint;
602
+
603
+ /** Error message if status is 'error' */
604
+ error?: string;
605
+ }
606
+
607
+ /**
608
+ * Outcome of an on-demand {@link CadreNode.serviceWake} — the mobile push-wake
609
+ * cycle (resume → bounded window → re-hibernate-if-idle) run imperatively for a
610
+ * single strand.
611
+ */
612
+ export interface ServiceWakeResult {
613
+ /** The strand the wake was requested for. */
614
+ strandId: string;
615
+ /**
616
+ * Whether the wake was actually serviced. `false` when the node is not
617
+ * running, or the strand is unknown to this node (not a member-participated
618
+ * strand) — never a thrown error, so a background task can branch on it.
619
+ */
620
+ serviced: boolean;
621
+ /**
622
+ * Whether activity landed during the wake window. `true` leaves the strand
623
+ * active; `false` re-hibernates it (or the strand was already live, in which
624
+ * case it reflects current liveness). Always `false` when `serviced` is `false`.
625
+ */
626
+ hadActivity: boolean;
627
+ }
628
+
629
+ /**
630
+ * Strand row from control network - basic membership info
631
+ */
632
+ export interface StrandRow {
633
+ Id: string;
634
+ MemberPrivateKey: string | null;
635
+ Type: 'o' | 'c';
636
+ }
637
+
638
+ /**
639
+ * sApp configuration provided by the hosting application when creating a strand.
640
+ * This is what the app developer provides - NOT loaded from the network.
641
+ */
642
+ export interface SAppConfig {
643
+ /** Public key of the sApp author */
644
+ id: string;
645
+ /** Version of the sApp */
646
+ version: string;
647
+ /** The declarative schema DDL */
648
+ schema: string;
649
+ /**
650
+ * Author's signature over the schema for verification. Required under the
651
+ * default `requireSignedSchemas` node policy — a config without it is rejected
652
+ * before strand bring-up. Optional in the type because authoring/serialization
653
+ * must represent an as-yet-unsigned config; omitting it is honored only when
654
+ * the node explicitly relaxes the policy (`requireSignedSchemas: false`, dev/test).
655
+ */
656
+ signature?: string;
657
+ /** Latency hint for hibernation behavior (optional, defaults to config) */
658
+ latencyHint?: LatencyHint;
659
+ }
660
+
661
+ /**
662
+ * Full strand configuration when adding a strand via the API
663
+ */
664
+ export interface StrandConfig {
665
+ /** Strand row from control network */
666
+ strandRow: StrandRow;
667
+ /** sApp configuration provided by the hosting application */
668
+ sAppConfig: SAppConfig;
669
+ /**
670
+ * Whether THIS node is the strand's founder — the party that provisioned and
671
+ * published the strand (the responder in formation, the creator in host/solo
672
+ * paths; the same party that calls {@link CadreNode.publishStrand}). The founder
673
+ * runs the one-time membership bootstrap at bring-up (writes `Strand.Header`, and
674
+ * for a closed strand the founding `Member`+`Manager`). A joiner leaves this
675
+ * `false`/unset and writes nothing — it receives those rows via Optimystic sync.
676
+ * Defaults to `false`.
677
+ */
678
+ founder?: boolean;
679
+ }
680
+
681
+ /**
682
+ * Result of creating a new cadre peer
683
+ */
684
+ export interface CreatePeerResult {
685
+ peerId: PeerId;
686
+ privateKey: Uint8Array;
687
+ }
688
+
689
+ // ============================================================================
690
+ // Member Registration API Types (from api.md)
691
+ // ============================================================================
692
+
693
+ /**
694
+ * Registration data for joining a strand as a member.
695
+ * Sent from invited member to any cadre member to accept invitation.
696
+ */
697
+ export interface MemberRegistration {
698
+ /** The strand being joined */
699
+ strandId: string;
700
+ /** The member's public key for this strand */
701
+ key: string;
702
+ /** Peer IDs of the member's cadre nodes that will participate */
703
+ peerIds: string[];
704
+ }
705
+
706
+ /**
707
+ * Result of member registration
708
+ */
709
+ export interface MemberRegistrationResult {
710
+ success: boolean;
711
+ reason?: string;
712
+ }
713
+
714
+ // ============================================================================
715
+ // Strand Solicitation API Types (from api.md)
716
+ // ============================================================================
717
+
718
+ /**
719
+ * Open invitation for strand formation.
720
+ * Shared out-of-band to allow strangers to form strands.
721
+ */
722
+ export interface OpenInvitation {
723
+ /** Unique token identifying this invitation */
724
+ token: string;
725
+ /** The sApp that will be used for the strand */
726
+ sAppId: string;
727
+ /** When this invitation expires */
728
+ expiration: Date;
729
+ /** Bootstrap addresses to contact the inviter's cadre */
730
+ bootstrap: string[];
731
+ }
732
+
733
+ /**
734
+ * Result of forming a strand via open invitation
735
+ */
736
+ export interface FormStrandResult {
737
+ /** The member key assigned to the initiator for this strand */
738
+ memberKey: string;
739
+ /** Private key for the invitation (for signing future messages) */
740
+ invitePrivateKey: string;
741
+ /** The strand that was created */
742
+ strandId: string;
743
+ /**
744
+ * The strand's membership key (closed-strand read-gating secret), delivered through
745
+ * the formation protocol after consent (provision-then-record). Present only for a
746
+ * closed strand the responder returned with its key; undefined otherwise. Distinct
747
+ * from {@link invitePrivateKey} (the initiator's own generated signing key).
748
+ */
749
+ memberPrivateKey?: string;
750
+ }
751
+
752
+ /**
753
+ * Disclosure object provided during strand formation.
754
+ * Contains identity and context information from the initiator.
755
+ */
756
+ export interface StrandFormationDisclosure {
757
+ /** Initiator's party identifier */
758
+ partyId?: string;
759
+ /** Additional identity bundle (app-specific) */
760
+ identityBundle?: unknown;
761
+ /** Human-readable purpose/reason for forming the strand */
762
+ purpose?: string;
763
+ /** Additional app-specific metadata */
764
+ metadata?: Record<string, unknown>;
765
+ }
766
+
767
+ /**
768
+ * Arachnode ring participation stub - will be implemented when arachnode is built
769
+ */
770
+ export interface ArachnodeConfig {
771
+ /** Enable Arachnode subsystem (Ring Zulu + storage rings). Storage-profile only. */
772
+ enableRingZulu: boolean;
773
+ /** Storage ring participation (storage profile only) */
774
+ storageRing?: {
775
+ /** Which ring to participate in based on capacity */
776
+ ring: number;
777
+ /** Partition within the ring */
778
+ partition?: number;
779
+ };
780
+ }
781
+
782
+ /**
783
+ * Events emitted by CadreNode
784
+ */
785
+ export interface CadreNodeEvents {
786
+ 'strand:started': { strandId: string };
787
+ 'strand:stopped': { strandId: string };
788
+ 'strand:error': { strandId: string; error: Error };
789
+ 'strand:idle': { strandId: string };
790
+ 'strand:hibernating': { strandId: string };
791
+ 'strand:waking': { strandId: string };
792
+ /**
793
+ * Emitted when the control network advertises a strand this node has no
794
+ * registered `sAppConfig` for — i.e. a strand created by another member. The
795
+ * hosting app decides whether to join it (register a config + `addStrand`,
796
+ * e.g. via a chat `joinChatStrand` helper). Carries the full {@link StrandRow}
797
+ * so the app can join without re-querying the control DB.
798
+ */
799
+ 'strand:discovered': { strandId: string; strand: StrandRow };
800
+ 'control:connected': void;
801
+ 'control:disconnected': void;
802
+ /** Emitted when a seed is received via the seed protocol */
803
+ 'seed:received': { partyId: string; peerId: string };
804
+ /** Emitted when a seed is successfully applied */
805
+ 'seed:applied': { partyId: string; peersAdded: number };
806
+ /** Emitted when seed application fails */
807
+ 'seed:error': { partyId: string; error: string };
808
+ }
809
+
810
+ // ============================================================================
811
+ // Peer Address Record / Resolution Types
812
+ // ============================================================================
813
+
814
+ /**
815
+ * A peer's self-published, freshness-stamped, self-signed address record.
816
+ *
817
+ * This is the logical shape of a `CadreControl.CadrePeer` row. A node publishes
818
+ * its own record (signing with the ed25519 key behind its PeerId); any node can
819
+ * resolve another member's current signaling/relay multiaddrs from only its
820
+ * PeerId by reading the record, re-verifying the self-signature against
821
+ * `publicKey`, checking freshness, and applying a trust gate.
822
+ *
823
+ * The signature covers `peerId`, the comma-joined `addrs`, and `updatedAt` — see
824
+ * `peerRecordSignedPayload`. `publicKey` is NOT inside the signed payload: it is
825
+ * the key the signature is verified *with*, and its libp2p-identity binding to
826
+ * `peerId` is checked separately at resolve time, so re-signing it would be
827
+ * redundant.
828
+ */
829
+ export interface PeerAddressRecord {
830
+ /** libp2p peer ID (base58btc) — the row key. */
831
+ peerId: string;
832
+ /** ed25519 public key (base64url) whose libp2p identity IS `peerId`. */
833
+ publicKey: string;
834
+ /** Current dialable multiaddrs, signaling (`/p2p-circuit`) first. */
835
+ addrs: string[];
836
+ /** epoch ms — freshness; strictly increasing per peer. */
837
+ updatedAt: number;
838
+ /** ed25519 self-signature over the signed payload, base64url. */
839
+ sig: string;
840
+ }
841
+
842
+ /**
843
+ * One `CadreControl.CadrePeer` row as read by `ControlDatabase.queryCadrePeers`:
844
+ * the addressing columns plus the persisted membership voucher.
845
+ *
846
+ * The voucher triple (`stampId`, `vouchOwner`, `vouchSig`) is what
847
+ * {@link CadreNode.listAuthorizedMembers} re-checks against the node-local
848
+ * trusted-owner anchor — it is null on a row written before the voucher columns
849
+ * existed, and all three must be present for the row to be authorizable. Named
850
+ * (rather than restated inline at each read site) so a future column addition
851
+ * cannot reach the query without the predicate seeing it.
852
+ */
853
+ export interface CadrePeerRow {
854
+ /** libp2p peer ID (base58btc) — the row key. */
855
+ peerId: string;
856
+ /** Comma-joined dialable multiaddrs as stored, or null when unpublished. */
857
+ multiaddr: string | null;
858
+ /** Single-use anti-replay nonce the voucher signature is bound to. */
859
+ stampId: string | null;
860
+ /** ed25519 public key (base64url) of the owner that vouched this row. */
861
+ vouchOwner: string | null;
862
+ /** That owner's signature over `digest('CadreControl.CadrePeer', 'vouch', peerId, stampId)`, base64url. */
863
+ vouchSig: string | null;
864
+ }
865
+
866
+ /** The voucher-bearing subset of a {@link CadrePeerRow} — what the authorized-membership predicate reads. */
867
+ export type CadrePeerVoucherFields = Pick<CadrePeerRow, 'peerId' | 'stampId' | 'vouchOwner' | 'vouchSig'>;
868
+
869
+ /**
870
+ * One `CadreControl.Revocation` tombstone as read by
871
+ * `ControlDatabase.queryRevocations`: the identity triple plus the `ReissuedAt`
872
+ * counter an owner bumps (`ControlDatabase.reissueRevocations`) to re-write — and
873
+ * therefore re-broadcast — a tombstone that committed while the node was alone.
874
+ */
875
+ export interface RevocationRow {
876
+ /** Which guarded table's stamp was retired. */
877
+ tableName: RevocableTable;
878
+ /** Primary key of the removed row (peer id / key / strand id). */
879
+ rowKey: string;
880
+ /** The retired single-use nonce — the tombstone's identity. */
881
+ stampId: string;
882
+ /** Monotonic re-issue counter; carries no semantics (see the schema comment). */
883
+ reissuedAt: number;
884
+ }
885
+
886
+ /**
887
+ * Outcome of {@link CadreNode.registerSelf}, surfaced so callers (e.g. the CLI
888
+ * `--owner` branch) can log what happened:
889
+ * - `inserted` — the first owner-signed INSERT of this node's `CadrePeer` row.
890
+ * - `refreshed` — a self-signed UPDATE of an existing row (heartbeat / addr change).
891
+ * Also reported when a first publish found its row seated by a concurrent
892
+ * `authorizePeer` of this node's own id and fell through to the UPDATE — the write
893
+ * really was an UPDATE, even though the caller's intent was a first publish.
894
+ * - `skipped` — nothing written (no self-signing key, not yet a member with no
895
+ * owner service to self-insert, or the row was removed mid-publish).
896
+ */
897
+ export type SelfRegistrationOutcome = 'inserted' | 'refreshed' | 'skipped';
898
+
899
+ /**
900
+ * Options for {@link CadreNode.resolvePeerAddrs}.
901
+ */
902
+ export interface ResolveOpts {
903
+ /**
904
+ * Freshness ceiling in ms. A record older than this is filtered out (a
905
+ * resolver must never hand back a dead relay reservation). Defaults to
906
+ * {@link DEFAULT_PEER_RECORD_MAX_AGE_MS}.
907
+ */
908
+ maxAgeMs?: number;
909
+ /** Return only `/p2p-circuit` signaling addrs (the WebRTC dial input). */
910
+ signalingOnly?: boolean;
911
+ /**
912
+ * Pluggable trust gate, evaluated after signature + freshness pass. Defaults
913
+ * to {@link currentMemberTrustPolicy} (any existing — therefore
914
+ * owner-vouched — CadrePeer member is trusted). Inject a stricter policy
915
+ * (e.g. from `seed-signerkey-trust-policy`) to reject otherwise-valid records
916
+ * before dialing.
917
+ */
918
+ trustPolicy?: PeerResolveTrustPolicy;
919
+ }
920
+
921
+ /**
922
+ * Context handed to a {@link PeerResolveTrustPolicy} when gating a resolution.
923
+ */
924
+ export interface PeerResolveContext {
925
+ /** The peer being resolved. */
926
+ peerId: string;
927
+ /** The record's ed25519 public key (already bound to `peerId` and verified). */
928
+ publicKey: string;
929
+ /** The party whose control network produced the record. */
930
+ partyId: string;
931
+ /** The full verified, fresh record. */
932
+ record: PeerAddressRecord;
933
+ }
934
+
935
+ /**
936
+ * Decides whether a signature-verified, fresh peer-address record should be
937
+ * trusted enough to dial. The seam through which a richer trust model
938
+ * (trust circle, pinned keys) composes with `resolvePeerAddrs`.
939
+ */
940
+ export interface PeerResolveTrustPolicy {
941
+ evaluate(ctx: PeerResolveContext): Promise<boolean> | boolean;
942
+ }
943
+
944
+ // ============================================================================
945
+ // Device Token Registry Types
946
+ // ============================================================================
947
+
948
+ /** Platform push channel a {@link DeviceTokenRecord} targets. */
949
+ export type PushPlatform = 'fcm' | 'apns';
950
+
951
+ /**
952
+ * A mobile cadre peer's self-published, freshness-stamped, self-signed platform
953
+ * push token.
954
+ *
955
+ * This is the logical shape of a `CadreControl.DeviceToken` row. A phone publishes
956
+ * its own record (signing with the ed25519 key behind its PeerId); a server peer
957
+ * resolves it from the phone's PeerId to deliver a push-wake over FCM/APNs when a
958
+ * control-network dial cannot reach the OS-suspended process. The signature covers
959
+ * `peerId`, `platform`, `token`, and `updatedAt` — see `deviceTokenSignedPayload`.
960
+ *
961
+ * Unlike {@link PeerAddressRecord}, the record carries NO public key: it is verified
962
+ * against the `CadrePeer.PublicKey` bound to the same `peerId`, so a `DeviceToken`
963
+ * with no backing `CadrePeer` row can never be resolved.
964
+ */
965
+ export interface DeviceTokenRecord {
966
+ /** libp2p peer ID (base58btc) — the row key and the CadrePeer this token belongs to. */
967
+ peerId: string;
968
+ /** Push channel: `'fcm'` (Android/Firebase) or `'apns'` (Apple). */
969
+ platform: PushPlatform;
970
+ /** Opaque platform device/registration token. */
971
+ token: string;
972
+ /** epoch ms — freshness; strictly increasing per self-update (replay guard). */
973
+ updatedAt: number;
974
+ /** ed25519 self-signature over the signed payload, base64url. */
975
+ sig: string;
976
+ }
977
+
978
+ /**
979
+ * A stored `CadreControl.DeviceToken` row: the self-signed
980
+ * {@link DeviceTokenRecord} plus the row's single-use `StampId` nonce.
981
+ *
982
+ * The stamp is deliberately OUTSIDE `DeviceTokenRecord`: the peer's own `Sig`
983
+ * covers only (peerId, platform, token, updatedAt), while the stamp is bound by
984
+ * the OWNER's insert/delete approvals. Readers need it to drop a row whose stamp
985
+ * has been retired into `CadreControl.Revocation` (a token resurrected by an
986
+ * approval replay on a node that had not yet converged on the tombstone).
987
+ */
988
+ export interface DeviceTokenRow extends DeviceTokenRecord {
989
+ /** Single-use authorization nonce; rotates on every (re)insert. */
990
+ stampId: string;
991
+ }
992
+
993
+ /**
994
+ * Options for {@link CadreNode.resolveDeviceToken}.
995
+ */
996
+ export interface ResolveDeviceTokenOpts {
997
+ /**
998
+ * Optional freshness ceiling in ms. Defaults to NO ceiling (a record is fresh
999
+ * as long as its `updatedAt` is positive): unlike a relay reservation, a device
1000
+ * push token stays valid until it rotates, so a long-suspended phone must remain
1001
+ * resolvable for push-wake. Set this to bound staleness explicitly.
1002
+ */
1003
+ maxAgeMs?: number;
1004
+ }
1005
+
1006
+ // ============================================================================
1007
+ // Push Credentials (platform push delivery — see push-notifier.ts)
1008
+ // ============================================================================
1009
+
1010
+ /**
1011
+ * Platform push-delivery credentials injected into a participating node's config
1012
+ * (`CadreNodeConfig.push`). Provisioned per spawned node by `cadre-host` and read
1013
+ * by `createPushNotifier` to construct the FCM and/or APNs senders. A platform
1014
+ * whose block is absent is simply not deliverable (the router returns a
1015
+ * best-effort "no credentials" failure rather than throwing).
1016
+ *
1017
+ * Secret hygiene: every `privateKey` field is a secret — never logged (treated
1018
+ * like the node's startup/seed tokens).
1019
+ */
1020
+ export interface PushCredentials {
1021
+ /** FCM (Android / Firebase) service-account credentials. */
1022
+ fcm?: FcmCredentials;
1023
+ /** APNs (Apple) auth-key credentials. */
1024
+ apns?: ApnsCredentials;
1025
+ /**
1026
+ * Per-`(peer, strand)` minimum gap between push-wakes the server fan-out emits —
1027
+ * the anti-spam cooldown a chatty strand needs. Default
1028
+ * {@link DEFAULT_PUSH_COOLDOWN_MS} (5 min). In-memory, acceptably lossy across
1029
+ * restarts (`serviceWake` is idempotent, so a duplicate wake is harmless).
1030
+ */
1031
+ cooldownMs?: number;
1032
+ /**
1033
+ * Per-strand burst-coalescing window for the fan-out: a second activity trigger
1034
+ * within this window is dropped (one wake is enough). Default
1035
+ * {@link DEFAULT_PUSH_DEBOUNCE_MS} (10 s).
1036
+ */
1037
+ debounceMs?: number;
1038
+ }
1039
+
1040
+ /** Google service-account fields needed for FCM HTTP v1 OAuth2. */
1041
+ export interface FcmCredentials {
1042
+ /** GCP project id → `POST https://fcm.googleapis.com/v1/projects/{projectId}/messages:send`. */
1043
+ projectId: string;
1044
+ /** Service-account email (JWT `iss`/`sub`). */
1045
+ clientEmail: string;
1046
+ /** Service-account RSA private key, PEM. Secret — never logged. */
1047
+ privateKey: string;
1048
+ }
1049
+
1050
+ /** Apple APNs auth-key (.p8) fields. */
1051
+ export interface ApnsCredentials {
1052
+ /** APNs key id (JWT header `kid`). */
1053
+ keyId: string;
1054
+ /** Apple team id (JWT `iss`). */
1055
+ teamId: string;
1056
+ /** App bundle id → `apns-topic` header. */
1057
+ bundleId: string;
1058
+ /** `.p8` ES256 private key, PEM. Secret — never logged. */
1059
+ privateKey: string;
1060
+ /** `true` → `api.push.apple.com`; false/undefined → `api.sandbox.push.apple.com`. */
1061
+ production?: boolean;
1062
+ }
1063
+
1064
+ // ============================================================================
1065
+ // Seed Bootstrap API Types (from architecture.md)
1066
+ // ============================================================================
1067
+
1068
+ /**
1069
+ * A peer entry in a control network seed.
1070
+ * Contains connection information for a cadre peer.
1071
+ */
1072
+ export interface SeedPeer {
1073
+ /** Peer ID (libp2p identity) */
1074
+ peerId: string;
1075
+ /** Multiaddrs for connecting to this peer */
1076
+ multiaddrs: string[];
1077
+ /** Whether this peer holds an owner key */
1078
+ isOwner: boolean;
1079
+ /** ed25519 public key (base64url) — present on owner peers for signerKey verification */
1080
+ publicKey?: string;
1081
+ }
1082
+
1083
+ /**
1084
+ * Control network seed for bootstrapping new nodes.
1085
+ * Pre-populates a new node's cache to solve the cold-start problem:
1086
+ * new nodes need control data to validate connections, but can't get
1087
+ * data without connecting first.
1088
+ */
1089
+ export interface ControlNetworkSeed {
1090
+ /** Party ID this seed belongs to */
1091
+ partyId: string;
1092
+ /** Known peers in the cadre */
1093
+ peers: SeedPeer[];
1094
+ /** Signature over the seed by an owner key */
1095
+ signature: string;
1096
+ /** The owner key that signed this seed */
1097
+ signerKey: string;
1098
+ }
1099
+
1100
+ /**
1101
+ * Message sent from instigator to new node during seed delivery.
1102
+ * Delivered via /sereus/seed/1.0.0 libp2p protocol.
1103
+ */
1104
+ export interface SeedMessage {
1105
+ /** Party ID for the cadre */
1106
+ partyId: string;
1107
+ /** Known peers in the cadre */
1108
+ peers: SeedPeer[];
1109
+ /** Signature by an owner key */
1110
+ signature: string;
1111
+ /** The owner key that signed this message */
1112
+ signerKey: string;
1113
+ }
1114
+
1115
+ /**
1116
+ * Acknowledgment message from new node to instigator.
1117
+ */
1118
+ export interface SeedAckMessage {
1119
+ /** Whether the seed was accepted */
1120
+ accepted: boolean;
1121
+ /** Reason for rejection (if not accepted) */
1122
+ reason?: string;
1123
+ }
1124
+
1125
+ // ============================================================================
1126
+ // Strand Wake (control-network push-wake protocol) — see strand-wake-protocol.ts
1127
+ // ============================================================================
1128
+
1129
+ /**
1130
+ * Request sent over the control network's `WAKE_PROTOCOL` from a same-cadre peer
1131
+ * to a hibernating peer, asking it to bring a strand online and pull pending
1132
+ * activity. The receiver gates this on cadre membership before honoring it.
1133
+ */
1134
+ export interface WakeRequest {
1135
+ /** The strand the sender knows has pending activity. */
1136
+ strandId: string;
1137
+ /** Optional cause hint, e.g. `"activity"` (a server saw new traffic) or `"manual"`. */
1138
+ reason?: string;
1139
+ }
1140
+
1141
+ /**
1142
+ * Acknowledgment of a {@link WakeRequest}, returned on the same stream.
1143
+ */
1144
+ export interface WakeAck {
1145
+ /** Whether the receiver honored the wake (member + participated strand). */
1146
+ accepted: boolean;
1147
+ /** The strand's status after the wake (present when `accepted`). */
1148
+ status?: StrandStatus;
1149
+ /** Reason for rejection (non-member, unknown strand, malformed frame). */
1150
+ reason?: string;
1151
+ }
1152
+
1153
+ // ============================================================================
1154
+ // Strand Address (control-network strand-address RPC) — see strand-addr-protocol.ts
1155
+ // ============================================================================
1156
+
1157
+ /**
1158
+ * Control-network request from one of a party's own cadre nodes to a sibling,
1159
+ * asking "what are your live multiaddrs for this strand's separate network?".
1160
+ * Used to seed a strand mesh from co-cadre nodes that already run that strand.
1161
+ * The receiver gates this on cadre membership before answering.
1162
+ */
1163
+ export interface StrandAddrRequest {
1164
+ /** The strand whose strand-network address the requester wants to seed from. */
1165
+ strandId: string;
1166
+ /**
1167
+ * The derived transport peerId the requester's own strand-`strandId` node
1168
+ * runs as (see `strand-transport-key.ts`). Present → the responder records a
1169
+ * delegate admission grant for it, so its own connection gate (and thus its
1170
+ * circuit-relay server, when it runs one) admits that peerId; absent →
1171
+ * today's behavior exactly. See `delegate-admission.ts` for the trust model.
1172
+ */
1173
+ delegatePeerId?: string;
1174
+ }
1175
+
1176
+ /**
1177
+ * Response to a {@link StrandAddrRequest}, carrying the responder's strand-node
1178
+ * multiaddrs, returned on the same stream.
1179
+ */
1180
+ export interface StrandAddrResponse {
1181
+ /** Echoes the requested strand id (empty on a reject/error reply). */
1182
+ strandId: string;
1183
+ /**
1184
+ * Dialable strand-network multiaddr strings (signaling/`p2p-circuit` first);
1185
+ * empty when the responder is a non-member, or does not currently run that
1186
+ * strand, or the exchange failed.
1187
+ */
1188
+ multiaddrs: string[];
1189
+ }
1190
+
1191
+ /**
1192
+ * Options for authorizing a new peer in the cadre.
1193
+ */
1194
+ export interface AuthorizePeerOptions {
1195
+ /** Peer ID to authorize */
1196
+ peerId: string;
1197
+ /** Optional multiaddrs for the peer */
1198
+ multiaddrs?: string[];
1199
+ }
1200
+
1201
+ /**
1202
+ * Result of applying a seed to a node.
1203
+ */
1204
+ export interface ApplySeedResult {
1205
+ /** Whether the seed was successfully applied */
1206
+ success: boolean;
1207
+ /** Number of peers added to the peer store */
1208
+ peersAdded: number;
1209
+ /** Error message if not successful */
1210
+ error?: string;
1211
+ /**
1212
+ * Owner-flagged seed peers this apply attempted to dial. Zero when the seed
1213
+ * carried no owner peer with an address, or when the seed was rejected before
1214
+ * the dial loop ran.
1215
+ */
1216
+ ownerDialsAttempted: number;
1217
+ /**
1218
+ * How many of those dials threw. `ownerDialsAttempted > 0 && ownerDialsFailed
1219
+ * === ownerDialsAttempted` means "seeded but stranded": the seed itself was
1220
+ * accepted (`success: true`) but no owner could be reached, so this node has
1221
+ * no connection to bootstrap its control database from. The node retries those
1222
+ * addresses on every control-cohort reconcile pass (see
1223
+ * `CadreNode.dialColdStartBootstrap`), so this is a signal, not a fatal error.
1224
+ *
1225
+ * Zero failures is NOT proof of a live connection: the receiving node's
1226
+ * membership gate denies AFTER the dialer's upgrade completes (see
1227
+ * `createMembershipConnectionGater`), so a dial can resolve and then be torn
1228
+ * down. Treat a non-zero value as certain failure and zero as "no failure
1229
+ * observed".
1230
+ */
1231
+ ownerDialsFailed: number;
1232
+ }
1233
+
1234
+ // ============================================================================
1235
+ // Seed Helper Types
1236
+ // ============================================================================
1237
+
1238
+ /**
1239
+ * Node network topology type for seed helper scenarios.
1240
+ */
1241
+ export type NodeTopology = 'public' | 'nat';
1242
+
1243
+ /**
1244
+ * Invite code for phone-to-server enrollment.
1245
+ * Used when a server invites a phone to join the cadre.
1246
+ */
1247
+ export interface CadreInvite {
1248
+ /** Party ID of the cadre */
1249
+ partyId: string;
1250
+ /** Multiaddrs to dial the owner */
1251
+ ownerAddrs: string[];
1252
+ /**
1253
+ * Owner ed25519 public keys (base64url) of the cadre, carried out-of-band
1254
+ * so a cold-start invitee can pin the trusted owner set before applying
1255
+ * any seed (the seed itself cannot vouch for its own signer). Populated by
1256
+ * `createInvite` from the issuer's OWN node-local trusted-owner anchor —
1257
+ * not its replicated `OwnerKey` table, because the invitee anchors whatever
1258
+ * arrives here and a stranger's genesis-inserted key must not ride an
1259
+ * otherwise-legitimate invite into a fresh node's anchor.
1260
+ */
1261
+ ownerKeys?: string[];
1262
+ /** Optional invite token for validation */
1263
+ token?: string;
1264
+ /** Timestamp when invite was created */
1265
+ createdAt: number;
1266
+ /** Optional expiration timestamp */
1267
+ expiresAt?: number;
1268
+ }
1269
+
1270
+ /**
1271
+ * Options for adding a drone via provider API.
1272
+ */
1273
+ export interface AddDroneOptions {
1274
+ /** Peer ID of the new drone (returned from provider) */
1275
+ dronePeerId: string;
1276
+ /** Multiaddrs of the drone (returned from provider) */
1277
+ droneMultiaddrs: string[];
1278
+ }
1279
+
1280
+ /**
1281
+ * Options for adding a phone via invite flow.
1282
+ */
1283
+ export interface AddPhoneOptions {
1284
+ /** Peer ID of the phone (sent by phone when it connects) */
1285
+ phonePeerId: string;
1286
+ /** Invite token for validation (must match issued invite) */
1287
+ token?: string;
1288
+ }
1289
+
1290
+ /**
1291
+ * Result of preparing a seed for drone initialization.
1292
+ */
1293
+ export interface DroneInitResult {
1294
+ /** The seed to send to the provider API */
1295
+ seed: ControlNetworkSeed;
1296
+ /** Base64url encoded seed for transport */
1297
+ encodedSeed: string;
1298
+ }
1299
+
1300
+ /**
1301
+ * Result of creating an invite for a phone.
1302
+ */
1303
+ export interface InviteResult {
1304
+ /** The invite to share out-of-band */
1305
+ invite: CadreInvite;
1306
+ /** Base64url encoded invite for QR/link */
1307
+ encodedInvite: string;
1308
+ }
1309
+