@serfab/cadre-core 0.7.1 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +9 -8
  2. package/dist/authority-key.d.ts +41 -0
  3. package/dist/authority-key.js +52 -0
  4. package/dist/authority-key.js.map +1 -0
  5. package/dist/cadre-node.d.ts +770 -11
  6. package/dist/cadre-node.js +1900 -88
  7. package/dist/cadre-node.js.map +1 -1
  8. package/dist/canonical-datetime.d.ts +33 -0
  9. package/dist/canonical-datetime.js +38 -0
  10. package/dist/canonical-datetime.js.map +1 -0
  11. package/dist/canonical-json.d.ts +12 -0
  12. package/dist/canonical-json.js +33 -0
  13. package/dist/canonical-json.js.map +1 -0
  14. package/dist/control-cohort.d.ts +63 -0
  15. package/dist/control-cohort.js +80 -0
  16. package/dist/control-cohort.js.map +1 -0
  17. package/dist/control-database.d.ts +259 -5
  18. package/dist/control-database.js +541 -128
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +89 -0
  21. package/dist/control-formation-recorder.js +139 -0
  22. package/dist/control-formation-recorder.js.map +1 -0
  23. package/dist/control-schema.d.ts +12 -0
  24. package/dist/control-schema.js +199 -0
  25. package/dist/control-schema.js.map +1 -0
  26. package/dist/control-stream.d.ts +54 -0
  27. package/dist/control-stream.js +104 -0
  28. package/dist/control-stream.js.map +1 -0
  29. package/dist/device-token.d.ts +50 -0
  30. package/dist/device-token.js +66 -0
  31. package/dist/device-token.js.map +1 -0
  32. package/dist/diagnostics/connection-path.d.ts +118 -0
  33. package/dist/diagnostics/connection-path.js +204 -0
  34. package/dist/diagnostics/connection-path.js.map +1 -0
  35. package/dist/diagnostics/webrtc-turn-tracker.d.ts +50 -0
  36. package/dist/diagnostics/webrtc-turn-tracker.js +196 -0
  37. package/dist/diagnostics/webrtc-turn-tracker.js.map +1 -0
  38. package/dist/hibernation-manager.d.ts +79 -0
  39. package/dist/hibernation-manager.js +173 -23
  40. package/dist/hibernation-manager.js.map +1 -1
  41. package/dist/index.d.ts +25 -4
  42. package/dist/index.js +59 -4
  43. package/dist/index.js.map +1 -1
  44. package/dist/key-store-file.d.ts +52 -0
  45. package/dist/key-store-file.js +194 -0
  46. package/dist/key-store-file.js.map +1 -0
  47. package/dist/key-store.d.ts +75 -0
  48. package/dist/key-store.js +66 -0
  49. package/dist/key-store.js.map +1 -0
  50. package/dist/peer-authorization.d.ts +26 -0
  51. package/dist/peer-authorization.js +40 -0
  52. package/dist/peer-authorization.js.map +1 -0
  53. package/dist/peer-record.d.ts +89 -0
  54. package/dist/peer-record.js +117 -0
  55. package/dist/peer-record.js.map +1 -0
  56. package/dist/push-credentials.d.ts +34 -0
  57. package/dist/push-credentials.js +81 -0
  58. package/dist/push-credentials.js.map +1 -0
  59. package/dist/push-fanout.d.ts +137 -0
  60. package/dist/push-fanout.js +197 -0
  61. package/dist/push-fanout.js.map +1 -0
  62. package/dist/push-notifier-apns.d.ts +53 -0
  63. package/dist/push-notifier-apns.js +195 -0
  64. package/dist/push-notifier-apns.js.map +1 -0
  65. package/dist/push-notifier-fcm.d.ts +38 -0
  66. package/dist/push-notifier-fcm.js +183 -0
  67. package/dist/push-notifier-fcm.js.map +1 -0
  68. package/dist/push-notifier-shared.d.ts +18 -0
  69. package/dist/push-notifier-shared.js +25 -0
  70. package/dist/push-notifier-shared.js.map +1 -0
  71. package/dist/push-notifier.d.ts +71 -0
  72. package/dist/push-notifier.js +50 -0
  73. package/dist/push-notifier.js.map +1 -0
  74. package/dist/schema-verification.d.ts +11 -2
  75. package/dist/schema-verification.js +15 -4
  76. package/dist/schema-verification.js.map +1 -1
  77. package/dist/seed-bootstrap.d.ts +197 -9
  78. package/dist/seed-bootstrap.js +396 -137
  79. package/dist/seed-bootstrap.js.map +1 -1
  80. package/dist/seed-trust-policy.d.ts +63 -0
  81. package/dist/seed-trust-policy.js +56 -0
  82. package/dist/seed-trust-policy.js.map +1 -0
  83. package/dist/strand-addr-protocol.d.ts +132 -0
  84. package/dist/strand-addr-protocol.js +313 -0
  85. package/dist/strand-addr-protocol.js.map +1 -0
  86. package/dist/strand-cohort.d.ts +54 -0
  87. package/dist/strand-cohort.js +38 -0
  88. package/dist/strand-cohort.js.map +1 -0
  89. package/dist/strand-database.d.ts +54 -6
  90. package/dist/strand-database.js +88 -100
  91. package/dist/strand-database.js.map +1 -1
  92. package/dist/strand-formation-manager.d.ts +79 -19
  93. package/dist/strand-formation-manager.js +196 -104
  94. package/dist/strand-formation-manager.js.map +1 -1
  95. package/dist/strand-formation-protocol.d.ts +162 -0
  96. package/dist/strand-formation-protocol.js +279 -0
  97. package/dist/strand-formation-protocol.js.map +1 -0
  98. package/dist/strand-instance-manager.d.ts +73 -4
  99. package/dist/strand-instance-manager.js +167 -41
  100. package/dist/strand-instance-manager.js.map +1 -1
  101. package/dist/strand-member-key.d.ts +29 -0
  102. package/dist/strand-member-key.js +38 -0
  103. package/dist/strand-member-key.js.map +1 -0
  104. package/dist/strand-member-registry.d.ts +98 -0
  105. package/dist/strand-member-registry.js +129 -0
  106. package/dist/strand-member-registry.js.map +1 -0
  107. package/dist/strand-membership-writer.d.ts +361 -0
  108. package/dist/strand-membership-writer.js +449 -0
  109. package/dist/strand-membership-writer.js.map +1 -0
  110. package/dist/strand-solicitation.d.ts +77 -2
  111. package/dist/strand-solicitation.js +25 -4
  112. package/dist/strand-solicitation.js.map +1 -1
  113. package/dist/strand-wake-payload.d.ts +30 -0
  114. package/dist/strand-wake-payload.js +20 -0
  115. package/dist/strand-wake-payload.js.map +1 -0
  116. package/dist/strand-wake-protocol.d.ts +114 -0
  117. package/dist/strand-wake-protocol.js +257 -0
  118. package/dist/strand-wake-protocol.js.map +1 -0
  119. package/dist/strand-watcher.d.ts +6 -2
  120. package/dist/strand-watcher.js +57 -17
  121. package/dist/strand-watcher.js.map +1 -1
  122. package/dist/types.d.ts +406 -23
  123. package/dist/types.js +22 -5
  124. package/dist/types.js.map +1 -1
  125. package/package.json +14 -8
  126. package/src/authority-key.ts +68 -0
  127. package/src/cadre-node.ts +2937 -948
  128. package/src/canonical-datetime.ts +39 -0
  129. package/src/canonical-json.ts +30 -0
  130. package/src/control-cohort.ts +103 -0
  131. package/src/control-database.ts +931 -383
  132. package/src/control-formation-recorder.ts +151 -0
  133. package/src/control-schema.ts +198 -0
  134. package/src/control-stream.ts +128 -0
  135. package/src/device-token.ts +89 -0
  136. package/src/diagnostics/connection-path.ts +277 -0
  137. package/src/diagnostics/webrtc-turn-tracker.ts +222 -0
  138. package/src/hibernation-manager.ts +197 -28
  139. package/src/index.ts +273 -79
  140. package/src/key-store-file.ts +203 -0
  141. package/src/key-store.ts +99 -0
  142. package/src/peer-authorization.ts +53 -0
  143. package/src/peer-record.ts +146 -0
  144. package/src/push-credentials.ts +84 -0
  145. package/src/push-fanout.ts +272 -0
  146. package/src/push-notifier-apns.ts +243 -0
  147. package/src/push-notifier-fcm.ts +221 -0
  148. package/src/push-notifier-shared.ts +28 -0
  149. package/src/push-notifier.ts +93 -0
  150. package/src/schema-verification.ts +18 -4
  151. package/src/seed-bootstrap.ts +464 -188
  152. package/src/seed-trust-policy.ts +107 -0
  153. package/src/strand-addr-protocol.ts +410 -0
  154. package/src/strand-cohort.ts +77 -0
  155. package/src/strand-database.ts +113 -141
  156. package/src/strand-formation-manager.ts +233 -142
  157. package/src/strand-formation-protocol.ts +391 -0
  158. package/src/strand-instance-manager.ts +207 -56
  159. package/src/strand-member-key.ts +39 -0
  160. package/src/strand-member-registry.ts +177 -0
  161. package/src/strand-membership-writer.ts +640 -0
  162. package/src/strand-solicitation.ts +93 -4
  163. package/src/strand-wake-payload.ts +32 -0
  164. package/src/strand-wake-protocol.ts +331 -0
  165. package/src/strand-watcher.ts +61 -17
  166. package/src/types.ts +1012 -582
package/dist/types.d.ts CHANGED
@@ -1,6 +1,16 @@
1
- import type { Libp2p, PeerId, PrivateKey } from '@libp2p/interface';
1
+ import type { ConnectionGater, Libp2p, PeerId, PrivateKey } from '@libp2p/interface';
2
2
  import type { IRawStorage, Libp2pTransports } from '@optimystic/db-p2p';
3
+ import type { IRepo } from '@optimystic/db-core';
3
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
+ /**
8
+ * Extended Libp2p node with the coordinatedRepo attached by db-p2p's
9
+ * createLibp2pNode after node creation (not surfaced on the base Libp2p type).
10
+ */
11
+ export interface Libp2pNodeWithRepo extends Libp2p {
12
+ coordinatedRepo: IRepo;
13
+ }
4
14
  /**
5
15
  * Node profile determines storage participation
6
16
  */
@@ -31,11 +41,31 @@ export interface HibernationTimeouts {
31
41
  idleTimeout: number;
32
42
  /** Time before transitioning from idle to hibernating */
33
43
  hibernateTimeout: number;
34
- /** Interval for check-ins while hibernating */
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
+ */
35
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;
36
62
  }
37
63
  /**
38
- * Default hibernation timeouts per latency hint
64
+ * Default hibernation timeouts per latency hint.
65
+ *
66
+ * `checkInInterval` is the BASE delay; `checkInMaxInterval` is the per-hint
67
+ * ceiling the exponential backoff escalates toward (interactive minutes→~1h,
68
+ * background minutes→~6h, archive ~1h→~3 days).
39
69
  */
40
70
  export declare const HIBERNATION_TIMEOUTS: Record<LatencyHint, HibernationTimeouts>;
41
71
  /**
@@ -108,6 +138,37 @@ export interface NetworkConfig {
108
138
  * and externally-mapped port — see `@serfab/cadre-host`'s NatService.
109
139
  */
110
140
  inviteAddressResolver?: () => Promise<string[]>;
141
+ /**
142
+ * Optional libp2p connection gater, threaded to both the control node and every
143
+ * strand's cohort node. libp2p's browser default denies dialing insecure
144
+ * WebSockets and private/loopback addresses; callers that must dial local or
145
+ * unsecured peers (the web reference dialing a `127.0.0.1/.../ws` responder,
146
+ * Playwright e2e, RN simulators) supply a permissive gater here — e.g.
147
+ * `{ denyDialMultiaddr: () => false }`. See `@optimystic/db-p2p`'s
148
+ * `libp2p-node-base` for the underlying option.
149
+ */
150
+ connectionGater?: ConnectionGater;
151
+ /**
152
+ * Tuning for the proactive control-cohort dial routine
153
+ * ({@link CadreNode.reconcileControlCohort}), which keeps a party's control
154
+ * nodes connected so the `CadreControl` collections form a replicating cohort.
155
+ * Both fields are optional; omit for the defaults
156
+ * ({@link DEFAULT_CONTROL_COHORT_TARGET_DEGREE} /
157
+ * {@link DEFAULT_CONTROL_COHORT_RECONCILE_MS}).
158
+ */
159
+ controlCohort?: {
160
+ /**
161
+ * Cap on the number of NON-authority siblings dialed per reconcile pass
162
+ * (backbone/authority members are always dialed and do not count). Defaults
163
+ * to {@link DEFAULT_CONTROL_COHORT_TARGET_DEGREE}.
164
+ */
165
+ targetDegree?: number;
166
+ /**
167
+ * Recurring reconcile cadence in ms. Defaults to
168
+ * {@link DEFAULT_CONTROL_COHORT_RECONCILE_MS}.
169
+ */
170
+ reconcileMs?: number;
171
+ };
111
172
  }
112
173
  /**
113
174
  * Hibernation configuration
@@ -117,7 +178,19 @@ export interface HibernationConfig {
117
178
  defaultLatencyHint?: LatencyHint;
118
179
  /** Custom timeouts per latency hint (overrides defaults) */
119
180
  customTimeouts?: Partial<Record<LatencyHint, Partial<HibernationTimeouts>>>;
181
+ /**
182
+ * How long a hibernating strand stays resumed during a check-in to let its
183
+ * strand network connect to reachable cohort peers (and the app drive
184
+ * pull-on-read activity) before re-hibernating if still idle. Defaults to
185
+ * {@link DEFAULT_CHECKIN_WINDOW_MS}.
186
+ */
187
+ checkInWindowMs?: number;
120
188
  }
189
+ /**
190
+ * Default duration of the resume-and-probe window during a strand check-in.
191
+ * See {@link HibernationConfig.checkInWindowMs}.
192
+ */
193
+ export declare const DEFAULT_CHECKIN_WINDOW_MS: number;
121
194
  /**
122
195
  * Control network configuration
123
196
  */
@@ -131,8 +204,28 @@ export interface ControlNetworkConfig {
131
204
  * Main configuration for a CadreNode
132
205
  */
133
206
  export interface CadreNodeConfig {
134
- /** If provided, use this keypair for the node identity */
207
+ /**
208
+ * If provided, use this keypair for the node identity (direct injection).
209
+ * Mutually exclusive with {@link keyStore} — supplying both is a configuration
210
+ * error (fail closed) thrown by `start()` before any network bring-up.
211
+ */
135
212
  privateKey?: PrivateKey;
213
+ /**
214
+ * Pluggable secure store for node key material. When set, the node loads its
215
+ * identity from `keyStore` under {@link identityKeyId}, generating + persisting
216
+ * a fresh Ed25519 key on first run (protobuf bytes are the canonical stored
217
+ * form). Mutually exclusive with {@link privateKey}. Absent ⇒ legacy behavior
218
+ * (use `privateKey`, else libp2p generates an ephemeral key).
219
+ *
220
+ * In the single-key reference model the authority signing key is *derived from*
221
+ * the node identity (see {@link CadreNode.getIdentityAuthorityKey}), so
222
+ * protecting the identity in a secure enclave protects the authority key too.
223
+ * A future separate-authority slot (`authorityKeyId`) is anticipated but not
224
+ * built here.
225
+ */
226
+ keyStore?: KeyStore;
227
+ /** Slot id for the node identity in {@link keyStore}. Default: `'cadre/identity'`. */
228
+ identityKeyId?: KeyId;
136
229
  /** Control network connection settings */
137
230
  controlNetwork: ControlNetworkConfig;
138
231
  /** Node profile: transaction-only or storage */
@@ -147,6 +240,33 @@ export interface CadreNodeConfig {
147
240
  hibernation?: HibernationConfig;
148
241
  /** Polling interval for strand watcher in ms (default: 5000) */
149
242
  strandWatchInterval?: number;
243
+ /**
244
+ * Require a valid author signature on every sApp schema before a strand is
245
+ * formed or joined. Defaults to true (fail closed): an unsigned schema is
246
+ * rejected before any libp2p node or schema DDL is brought up. Set false ONLY
247
+ * for dev/test where unsigned demo schemas are used.
248
+ */
249
+ requireSignedSchemas?: boolean;
250
+ /**
251
+ * Node-wide default trust anchor for INBOUND control-network seeds. Forwarded
252
+ * into every SeedBootstrapService this node constructs (authority, receive-only
253
+ * listener, and the temp service used by applySeed when no service exists), and
254
+ * used as the service-level default the libp2p seed-protocol handler relies on
255
+ * (that path has no per-call override seam). Defaults to dbAnchoredTrustPolicy()
256
+ * inside SeedBootstrapService when unset — a cold-start node then rejects every
257
+ * seed. A per-call `applySeed(seed, { trustPolicy })` override still wins over
258
+ * this default for callers that hold out-of-band material (e.g. a pinned key
259
+ * from a CadreInvite).
260
+ */
261
+ seedTrustPolicy?: SeedTrustPolicy;
262
+ /**
263
+ * Platform push-delivery credentials (FCM and/or APNs). When present, the node
264
+ * can deliver strand-wake data messages to suspended mobile peers over the
265
+ * platform push channel — the server fan-out constructs a `PushNotifier` from
266
+ * this. Absent ⇒ no platform push (control-network push-wake only). Injected
267
+ * per node by `cadre-host`; `privateKey` fields are secrets and are never logged.
268
+ */
269
+ push?: PushCredentials;
150
270
  }
151
271
  /**
152
272
  * Status of a strand instance
@@ -184,6 +304,27 @@ export interface StrandInstance {
184
304
  /** Error message if status is 'error' */
185
305
  error?: string;
186
306
  }
307
+ /**
308
+ * Outcome of an on-demand {@link CadreNode.serviceWake} — the mobile push-wake
309
+ * cycle (resume → bounded window → re-hibernate-if-idle) run imperatively for a
310
+ * single strand.
311
+ */
312
+ export interface ServiceWakeResult {
313
+ /** The strand the wake was requested for. */
314
+ strandId: string;
315
+ /**
316
+ * Whether the wake was actually serviced. `false` when the node is not
317
+ * running, or the strand is unknown to this node (not a member-participated
318
+ * strand) — never a thrown error, so a background task can branch on it.
319
+ */
320
+ serviced: boolean;
321
+ /**
322
+ * Whether activity landed during the wake window. `true` leaves the strand
323
+ * active; `false` re-hibernates it (or the strand was already live, in which
324
+ * case it reflects current liveness). Always `false` when `serviced` is `false`.
325
+ */
326
+ hadActivity: boolean;
327
+ }
187
328
  /**
188
329
  * Strand row from control network - basic membership info
189
330
  */
@@ -203,7 +344,13 @@ export interface SAppConfig {
203
344
  version: string;
204
345
  /** The declarative schema DDL */
205
346
  schema: string;
206
- /** Author's signature over the schema for verification (omit to skip verification) */
347
+ /**
348
+ * Author's signature over the schema for verification. Required under the
349
+ * default `requireSignedSchemas` node policy — a config without it is rejected
350
+ * before strand bring-up. Optional in the type because authoring/serialization
351
+ * must represent an as-yet-unsigned config; omitting it is honored only when
352
+ * the node explicitly relaxes the policy (`requireSignedSchemas: false`, dev/test).
353
+ */
207
354
  signature?: string;
208
355
  /** Latency hint for hibernation behavior (optional, defaults to config) */
209
356
  latencyHint?: LatencyHint;
@@ -231,10 +378,22 @@ export interface StrandConfig {
231
378
  /** sApp configuration provided by the hosting application */
232
379
  sAppConfig: SAppConfig;
233
380
  /**
234
- * Lifecycle mode for this strand instance. Defaults to `'networked'` when omitted
235
- * to preserve the historical behavior for multi-peer callers.
381
+ * Lifecycle mode for this strand instance. When omitted, CadreNode infers the
382
+ * mode from cohort membership (`bootstrap` for a solo/first node with no other
383
+ * `CadrePeer` rows, `networked` once the cohort has other members). An explicit
384
+ * value always wins.
236
385
  */
237
386
  mode?: StrandMode;
387
+ /**
388
+ * Whether THIS node is the strand's founder — the party that provisioned and
389
+ * published the strand (the responder in formation, the creator in host/solo
390
+ * paths; the same party that calls {@link CadreNode.publishStrand}). The founder
391
+ * runs the one-time membership bootstrap at bring-up (writes `Strand.Header`, and
392
+ * for a closed strand the founding `Member`+`Authority`). A joiner leaves this
393
+ * `false`/unset and writes nothing — it receives those rows via Optimystic sync.
394
+ * Defaults to `false`.
395
+ */
396
+ founder?: boolean;
238
397
  }
239
398
  /**
240
399
  * Result of creating a new cadre peer
@@ -286,6 +445,13 @@ export interface FormStrandResult {
286
445
  invitePrivateKey: string;
287
446
  /** The strand that was created */
288
447
  strandId: string;
448
+ /**
449
+ * The strand's membership key (closed-strand read-gating secret), delivered through
450
+ * the formation protocol after consent (provision-then-record). Present only for a
451
+ * closed strand the responder returned with its key; undefined otherwise. Distinct
452
+ * from {@link invitePrivateKey} (the initiator's own generated signing key).
453
+ */
454
+ memberPrivateKey?: string;
289
455
  }
290
456
  /**
291
457
  * Result of validating a strand formation request
@@ -347,6 +513,17 @@ export interface CadreNodeEvents {
347
513
  'strand:waking': {
348
514
  strandId: string;
349
515
  };
516
+ /**
517
+ * Emitted when the control network advertises a strand this node has no
518
+ * registered `sAppConfig` for — i.e. a strand created by another member. The
519
+ * hosting app decides whether to join it (register a config + `addStrand`,
520
+ * e.g. via a chat `joinChatStrand` helper). Carries the full {@link StrandRow}
521
+ * so the app can join without re-querying the control DB.
522
+ */
523
+ 'strand:discovered': {
524
+ strandId: string;
525
+ strand: StrandRow;
526
+ };
350
527
  'control:connected': void;
351
528
  'control:disconnected': void;
352
529
  /** Emitted when a seed is received via the seed protocol */
@@ -365,6 +542,175 @@ export interface CadreNodeEvents {
365
542
  error: string;
366
543
  };
367
544
  }
545
+ /**
546
+ * A peer's self-published, freshness-stamped, self-signed address record.
547
+ *
548
+ * This is the logical shape of a `CadreControl.CadrePeer` row. A node publishes
549
+ * its own record (signing with the ed25519 key behind its PeerId); any node can
550
+ * resolve another member's current signaling/relay multiaddrs from only its
551
+ * PeerId by reading the record, re-verifying the self-signature against
552
+ * `publicKey`, checking freshness, and applying a trust gate.
553
+ *
554
+ * The signature covers `peerId`, the comma-joined `addrs`, and `updatedAt` — see
555
+ * `peerRecordSignedPayload`. `publicKey` is NOT inside the signed payload: it is
556
+ * the key the signature is verified *with*, and its libp2p-identity binding to
557
+ * `peerId` is checked separately at resolve time, so re-signing it would be
558
+ * redundant.
559
+ */
560
+ export interface PeerAddressRecord {
561
+ /** libp2p peer ID (base58btc) — the row key. */
562
+ peerId: string;
563
+ /** ed25519 public key (base64url) whose libp2p identity IS `peerId`. */
564
+ publicKey: string;
565
+ /** Current dialable multiaddrs, signaling (`/p2p-circuit`) first. */
566
+ addrs: string[];
567
+ /** epoch ms — freshness; strictly increasing per peer. */
568
+ updatedAt: number;
569
+ /** ed25519 self-signature over the signed payload, base64url. */
570
+ sig: string;
571
+ }
572
+ /**
573
+ * Outcome of {@link CadreNode.registerSelf}, surfaced so callers (e.g. the CLI
574
+ * `--authority` branch) can log what happened:
575
+ * - `inserted` — the first authority-signed INSERT of this node's `CadrePeer` row.
576
+ * - `refreshed` — a self-signed UPDATE of an existing row (heartbeat / addr change).
577
+ * - `skipped` — nothing written (no self-signing key, or not yet a member with no
578
+ * authority service to self-insert).
579
+ */
580
+ export type SelfRegistrationOutcome = 'inserted' | 'refreshed' | 'skipped';
581
+ /**
582
+ * Options for {@link CadreNode.resolvePeerAddrs}.
583
+ */
584
+ export interface ResolveOpts {
585
+ /**
586
+ * Freshness ceiling in ms. A record older than this is filtered out (a
587
+ * resolver must never hand back a dead relay reservation). Defaults to
588
+ * {@link DEFAULT_PEER_RECORD_MAX_AGE_MS}.
589
+ */
590
+ maxAgeMs?: number;
591
+ /** Return only `/p2p-circuit` signaling addrs (the WebRTC dial input). */
592
+ signalingOnly?: boolean;
593
+ /**
594
+ * Pluggable trust gate, evaluated after signature + freshness pass. Defaults
595
+ * to {@link currentMemberTrustPolicy} (any existing — therefore
596
+ * authority-vouched — CadrePeer member is trusted). Inject a stricter policy
597
+ * (e.g. from `seed-signerkey-trust-policy`) to reject otherwise-valid records
598
+ * before dialing.
599
+ */
600
+ trustPolicy?: PeerResolveTrustPolicy;
601
+ }
602
+ /**
603
+ * Context handed to a {@link PeerResolveTrustPolicy} when gating a resolution.
604
+ */
605
+ export interface PeerResolveContext {
606
+ /** The peer being resolved. */
607
+ peerId: string;
608
+ /** The record's ed25519 public key (already bound to `peerId` and verified). */
609
+ publicKey: string;
610
+ /** The party whose control network produced the record. */
611
+ partyId: string;
612
+ /** The full verified, fresh record. */
613
+ record: PeerAddressRecord;
614
+ }
615
+ /**
616
+ * Decides whether a signature-verified, fresh peer-address record should be
617
+ * trusted enough to dial. The seam through which a richer trust model
618
+ * (trust circle, pinned keys) composes with `resolvePeerAddrs`.
619
+ */
620
+ export interface PeerResolveTrustPolicy {
621
+ evaluate(ctx: PeerResolveContext): Promise<boolean> | boolean;
622
+ }
623
+ /** Platform push channel a {@link DeviceTokenRecord} targets. */
624
+ export type PushPlatform = 'fcm' | 'apns';
625
+ /**
626
+ * A mobile cadre peer's self-published, freshness-stamped, self-signed platform
627
+ * push token.
628
+ *
629
+ * This is the logical shape of a `CadreControl.DeviceToken` row. A phone publishes
630
+ * its own record (signing with the ed25519 key behind its PeerId); a server peer
631
+ * resolves it from the phone's PeerId to deliver a push-wake over FCM/APNs when a
632
+ * control-network dial cannot reach the OS-suspended process. The signature covers
633
+ * `peerId`, `platform`, `token`, and `updatedAt` — see `deviceTokenSignedPayload`.
634
+ *
635
+ * Unlike {@link PeerAddressRecord}, the record carries NO public key: it is verified
636
+ * against the `CadrePeer.PublicKey` bound to the same `peerId`, so a `DeviceToken`
637
+ * with no backing `CadrePeer` row can never be resolved.
638
+ */
639
+ export interface DeviceTokenRecord {
640
+ /** libp2p peer ID (base58btc) — the row key and the CadrePeer this token belongs to. */
641
+ peerId: string;
642
+ /** Push channel: `'fcm'` (Android/Firebase) or `'apns'` (Apple). */
643
+ platform: PushPlatform;
644
+ /** Opaque platform device/registration token. */
645
+ token: string;
646
+ /** epoch ms — freshness; strictly increasing per self-update (replay guard). */
647
+ updatedAt: number;
648
+ /** ed25519 self-signature over the signed payload, base64url. */
649
+ sig: string;
650
+ }
651
+ /**
652
+ * Options for {@link CadreNode.resolveDeviceToken}.
653
+ */
654
+ export interface ResolveDeviceTokenOpts {
655
+ /**
656
+ * Optional freshness ceiling in ms. Defaults to NO ceiling (a record is fresh
657
+ * as long as its `updatedAt` is positive): unlike a relay reservation, a device
658
+ * push token stays valid until it rotates, so a long-suspended phone must remain
659
+ * resolvable for push-wake. Set this to bound staleness explicitly.
660
+ */
661
+ maxAgeMs?: number;
662
+ }
663
+ /**
664
+ * Platform push-delivery credentials injected into a participating node's config
665
+ * (`CadreNodeConfig.push`). Provisioned per spawned node by `cadre-host` and read
666
+ * by `createPushNotifier` to construct the FCM and/or APNs senders. A platform
667
+ * whose block is absent is simply not deliverable (the router returns a
668
+ * best-effort "no credentials" failure rather than throwing).
669
+ *
670
+ * Secret hygiene: every `privateKey` field is a secret — never logged (treated
671
+ * like the node's startup/seed tokens).
672
+ */
673
+ export interface PushCredentials {
674
+ /** FCM (Android / Firebase) service-account credentials. */
675
+ fcm?: FcmCredentials;
676
+ /** APNs (Apple) auth-key credentials. */
677
+ apns?: ApnsCredentials;
678
+ /**
679
+ * Per-`(peer, strand)` minimum gap between push-wakes the server fan-out emits —
680
+ * the anti-spam cooldown a chatty strand needs. Default
681
+ * {@link DEFAULT_PUSH_COOLDOWN_MS} (5 min). In-memory, acceptably lossy across
682
+ * restarts (`serviceWake` is idempotent, so a duplicate wake is harmless).
683
+ */
684
+ cooldownMs?: number;
685
+ /**
686
+ * Per-strand burst-coalescing window for the fan-out: a second activity trigger
687
+ * within this window is dropped (one wake is enough). Default
688
+ * {@link DEFAULT_PUSH_DEBOUNCE_MS} (10 s).
689
+ */
690
+ debounceMs?: number;
691
+ }
692
+ /** Google service-account fields needed for FCM HTTP v1 OAuth2. */
693
+ export interface FcmCredentials {
694
+ /** GCP project id → `POST https://fcm.googleapis.com/v1/projects/{projectId}/messages:send`. */
695
+ projectId: string;
696
+ /** Service-account email (JWT `iss`/`sub`). */
697
+ clientEmail: string;
698
+ /** Service-account RSA private key, PEM. Secret — never logged. */
699
+ privateKey: string;
700
+ }
701
+ /** Apple APNs auth-key (.p8) fields. */
702
+ export interface ApnsCredentials {
703
+ /** APNs key id (JWT header `kid`). */
704
+ keyId: string;
705
+ /** Apple team id (JWT `iss`). */
706
+ teamId: string;
707
+ /** App bundle id → `apns-topic` header. */
708
+ bundleId: string;
709
+ /** `.p8` ES256 private key, PEM. Secret — never logged. */
710
+ privateKey: string;
711
+ /** `true` → `api.push.apple.com`; false/undefined → `api.sandbox.push.apple.com`. */
712
+ production?: boolean;
713
+ }
368
714
  /**
369
715
  * A peer entry in a control network seed.
370
716
  * Contains connection information for a cadre peer.
@@ -390,25 +736,11 @@ export interface ControlNetworkSeed {
390
736
  partyId: string;
391
737
  /** Known peers in the cadre */
392
738
  peers: SeedPeer[];
393
- /** Optional signed transactions to pre-populate the cache */
394
- transactions?: SignedTransaction[];
395
739
  /** Signature over the seed by an authority key */
396
740
  signature: string;
397
741
  /** The authority key that signed this seed */
398
742
  signerKey: string;
399
743
  }
400
- /**
401
- * A signed transaction for inclusion in seeds.
402
- * Allows pre-populating the control network cache.
403
- */
404
- export interface SignedTransaction {
405
- /** Transaction ID */
406
- id: string;
407
- /** Serialized transaction data */
408
- data: string;
409
- /** Signature over the transaction */
410
- signature: string;
411
- }
412
744
  /**
413
745
  * Message sent from instigator to new node during seed delivery.
414
746
  * Delivered via /sereus/seed/1.0.0 libp2p protocol.
@@ -418,8 +750,6 @@ export interface SeedMessage {
418
750
  partyId: string;
419
751
  /** Known peers in the cadre */
420
752
  peers: SeedPeer[];
421
- /** Optional transactions to pre-populate cache */
422
- transactions?: SignedTransaction[];
423
753
  /** Signature by an authority key */
424
754
  signature: string;
425
755
  /** The authority key that signed this message */
@@ -434,6 +764,52 @@ export interface SeedAckMessage {
434
764
  /** Reason for rejection (if not accepted) */
435
765
  reason?: string;
436
766
  }
767
+ /**
768
+ * Request sent over the control network's `WAKE_PROTOCOL` from a same-cadre peer
769
+ * to a hibernating peer, asking it to bring a strand online and pull pending
770
+ * activity. The receiver gates this on cadre membership before honoring it.
771
+ */
772
+ export interface WakeRequest {
773
+ /** The strand the sender knows has pending activity. */
774
+ strandId: string;
775
+ /** Optional cause hint, e.g. `"activity"` (a server saw new traffic) or `"manual"`. */
776
+ reason?: string;
777
+ }
778
+ /**
779
+ * Acknowledgment of a {@link WakeRequest}, returned on the same stream.
780
+ */
781
+ export interface WakeAck {
782
+ /** Whether the receiver honored the wake (member + participated strand). */
783
+ accepted: boolean;
784
+ /** The strand's status after the wake (present when `accepted`). */
785
+ status?: StrandStatus;
786
+ /** Reason for rejection (non-member, unknown strand, malformed frame). */
787
+ reason?: string;
788
+ }
789
+ /**
790
+ * Control-network request from one of a party's own cadre nodes to a sibling,
791
+ * asking "what are your live multiaddrs for this strand's separate network?".
792
+ * Used to seed a strand mesh from co-cadre nodes that already run that strand.
793
+ * The receiver gates this on cadre membership before answering.
794
+ */
795
+ export interface StrandAddrRequest {
796
+ /** The strand whose strand-network address the requester wants to seed from. */
797
+ strandId: string;
798
+ }
799
+ /**
800
+ * Response to a {@link StrandAddrRequest}, carrying the responder's strand-node
801
+ * multiaddrs, returned on the same stream.
802
+ */
803
+ export interface StrandAddrResponse {
804
+ /** Echoes the requested strand id (empty on a reject/error reply). */
805
+ strandId: string;
806
+ /**
807
+ * Dialable strand-network multiaddr strings (signaling/`p2p-circuit` first);
808
+ * empty when the responder is a non-member, or does not currently run that
809
+ * strand, or the exchange failed.
810
+ */
811
+ multiaddrs: string[];
812
+ }
437
813
  /**
438
814
  * Options for authorizing a new peer in the cadre.
439
815
  */
@@ -467,6 +843,13 @@ export interface CadreInvite {
467
843
  partyId: string;
468
844
  /** Multiaddrs to dial the authority */
469
845
  authorityAddrs: string[];
846
+ /**
847
+ * Authority ed25519 public keys (base64url) of the cadre, carried out-of-band
848
+ * so a cold-start invitee can pin the trusted authority set before applying
849
+ * any seed (the seed itself cannot vouch for its own signer). Populated by
850
+ * `createInvite` from the issuer's `AuthorityKey` table.
851
+ */
852
+ authorityKeys?: string[];
470
853
  /** Optional invite token for validation */
471
854
  token?: string;
472
855
  /** Timestamp when invite was created */
package/dist/types.js CHANGED
@@ -1,26 +1,43 @@
1
1
  /**
2
- * Default hibernation timeouts per latency hint
2
+ * Default hibernation timeouts per latency hint.
3
+ *
4
+ * `checkInInterval` is the BASE delay; `checkInMaxInterval` is the per-hint
5
+ * ceiling the exponential backoff escalates toward (interactive minutes→~1h,
6
+ * background minutes→~6h, archive ~1h→~3 days).
3
7
  */
4
8
  export const HIBERNATION_TIMEOUTS = {
5
9
  realtime: {
6
10
  idleTimeout: Infinity, // Never idle
7
11
  hibernateTimeout: Infinity, // Never hibernate
8
- checkInInterval: Infinity // N/A
12
+ checkInInterval: Infinity, // N/A
13
+ checkInBackoffFactor: 2,
14
+ checkInMaxInterval: Infinity // N/A
9
15
  },
10
16
  interactive: {
11
17
  idleTimeout: 5 * 60 * 1000, // 5 minutes
12
18
  hibernateTimeout: 15 * 60 * 1000, // 15 minutes after idle
13
- checkInInterval: 30 * 1000 // 30 seconds
19
+ checkInInterval: 30 * 1000, // base: 30 seconds
20
+ checkInBackoffFactor: 2,
21
+ checkInMaxInterval: 60 * 60 * 1000 // cap: ~1 hour
14
22
  },
15
23
  background: {
16
24
  idleTimeout: 1 * 60 * 1000, // 1 minute
17
25
  hibernateTimeout: 5 * 60 * 1000, // 5 minutes after idle
18
- checkInInterval: 5 * 60 * 1000 // 5 minutes
26
+ checkInInterval: 5 * 60 * 1000, // base: 5 minutes
27
+ checkInBackoffFactor: 2,
28
+ checkInMaxInterval: 6 * 60 * 60 * 1000 // cap: ~6 hours
19
29
  },
20
30
  archive: {
21
31
  idleTimeout: 10 * 1000, // 10 seconds
22
32
  hibernateTimeout: 30 * 1000, // 30 seconds after idle
23
- checkInInterval: 60 * 60 * 1000 // 1 hour
33
+ checkInInterval: 60 * 60 * 1000, // base: 1 hour
34
+ checkInBackoffFactor: 2,
35
+ checkInMaxInterval: 3 * 24 * 60 * 60 * 1000 // cap: ~3 days
24
36
  }
25
37
  };
38
+ /**
39
+ * Default duration of the resume-and-probe window during a strand check-in.
40
+ * See {@link HibernationConfig.checkInWindowMs}.
41
+ */
42
+ export const DEFAULT_CHECKIN_WINDOW_MS = 15 * 1000;
26
43
  //# sourceMappingURL=types.js.map
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAmCA;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAA6C;IAC5E,QAAQ,EAAE;QACR,WAAW,EAAE,QAAQ,EAAS,aAAa;QAC3C,gBAAgB,EAAE,QAAQ,EAAI,kBAAkB;QAChD,eAAe,EAAE,QAAQ,CAAK,MAAM;KACrC;IACD,WAAW,EAAE;QACX,WAAW,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,EAAI,YAAY;QAC1C,gBAAgB,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI,EAAE,wBAAwB;QAC1D,eAAe,EAAE,EAAE,GAAG,IAAI,CAAI,aAAa;KAC5C;IACD,UAAU,EAAE;QACV,WAAW,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,EAAI,WAAW;QACzC,gBAAgB,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,EAAG,uBAAuB;QACzD,eAAe,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,CAAI,YAAY;KAC/C;IACD,OAAO,EAAE;QACP,WAAW,EAAE,EAAE,GAAG,IAAI,EAAQ,aAAa;QAC3C,gBAAgB,EAAE,EAAE,GAAG,IAAI,EAAG,wBAAwB;QACtD,eAAe,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI,CAAG,SAAS;KAC5C;CACF,CAAC"}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA8DA;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAA6C;IAC5E,QAAQ,EAAE;QACR,WAAW,EAAE,QAAQ,EAAS,aAAa;QAC3C,gBAAgB,EAAE,QAAQ,EAAI,kBAAkB;QAChD,eAAe,EAAE,QAAQ,EAAK,MAAM;QACpC,oBAAoB,EAAE,CAAC;QACvB,kBAAkB,EAAE,QAAQ,CAAE,MAAM;KACrC;IACD,WAAW,EAAE;QACX,WAAW,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,EAAI,YAAY;QAC1C,gBAAgB,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI,EAAE,wBAAwB;QAC1D,eAAe,EAAE,EAAE,GAAG,IAAI,EAAI,mBAAmB;QACjD,oBAAoB,EAAE,CAAC;QACvB,kBAAkB,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,eAAe;KACnD;IACD,UAAU,EAAE;QACV,WAAW,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,EAAI,WAAW;QACzC,gBAAgB,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,EAAG,uBAAuB;QACzD,eAAe,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,EAAI,kBAAkB;QACpD,oBAAoB,EAAE,CAAC;QACvB,kBAAkB,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,gBAAgB;KACxD;IACD,OAAO,EAAE;QACP,WAAW,EAAE,EAAE,GAAG,IAAI,EAAQ,aAAa;QAC3C,gBAAgB,EAAE,EAAE,GAAG,IAAI,EAAG,wBAAwB;QACtD,eAAe,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI,EAAG,eAAe;QACjD,oBAAoB,EAAE,CAAC;QACvB,kBAAkB,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,eAAe;KAC5D;CACF,CAAC;AA4HF;;;GAGG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,EAAE,GAAG,IAAI,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@serfab/cadre-core",
3
- "version": "0.7.1",
3
+ "version": "0.8.1",
4
4
  "type": "module",
5
5
  "description": "Core library for Sereus cadre nodes - manages control networks and strand participation",
6
6
  "main": "dist/index.js",
@@ -19,6 +19,10 @@
19
19
  },
20
20
  "types": "./dist/index.d.ts",
21
21
  "import": "./dist/index.js"
22
+ },
23
+ "./key-store-file": {
24
+ "types": "./dist/key-store-file.d.ts",
25
+ "import": "./dist/key-store-file.js"
22
26
  }
23
27
  },
24
28
  "repository": {
@@ -39,6 +43,7 @@
39
43
  "scripts": {
40
44
  "clean": "rimraf dist",
41
45
  "build": "tsc -p tsconfig.build.json",
46
+ "typecheck": "tsc -p tsconfig.typecheck.json --noEmit",
42
47
  "test": "vitest run",
43
48
  "dev:test": "vitest"
44
49
  },
@@ -49,7 +54,7 @@
49
54
  "@libp2p/tcp": "^11.0.10",
50
55
  "@types/debug": "^4.1.12",
51
56
  "@types/node": "^25.0.10",
52
- "aegir": "^45.2.1",
57
+ "@vitest/coverage-v8": "^4.0.17",
53
58
  "rimraf": "^6.1.2",
54
59
  "typescript": "^5.9.3",
55
60
  "vitest": "^4.0.17"
@@ -58,12 +63,13 @@
58
63
  "@libp2p/crypto": "^5.1.13",
59
64
  "@libp2p/interface": "^3.1.0",
60
65
  "@libp2p/peer-id": "^6.0.4",
61
- "@optimystic/db-core": "^0.13.4",
62
- "@optimystic/db-p2p": "^0.13.4",
63
- "@optimystic/quereus-plugin-crypto": "^0.13.4",
64
- "@optimystic/quereus-plugin-optimystic": "^0.13.4",
65
- "@quereus/quereus": "^3.1.1",
66
- "@serfab/strand-proto": "^0.7.1",
66
+ "@multiformats/multiaddr": "^12.5.1",
67
+ "@optimystic/db-core": "^0.14.1",
68
+ "@optimystic/db-p2p": "^0.14.1",
69
+ "@optimystic/quereus-plugin-crypto": "^0.14.1",
70
+ "@optimystic/quereus-plugin-optimystic": "^0.14.1",
71
+ "@quereus/quereus": "^4.2.1",
72
+ "@serfab/quereus-plugin-sereus": "^0.8.1",
67
73
  "debug": "^4.4.3",
68
74
  "libp2p": "^3.1.3",
69
75
  "uint8arrays": "^5.1.0"