@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.
- package/README.md +9 -8
- package/dist/authority-key.d.ts +41 -0
- package/dist/authority-key.js +52 -0
- package/dist/authority-key.js.map +1 -0
- package/dist/cadre-node.d.ts +770 -11
- package/dist/cadre-node.js +1900 -88
- package/dist/cadre-node.js.map +1 -1
- package/dist/canonical-datetime.d.ts +33 -0
- package/dist/canonical-datetime.js +38 -0
- package/dist/canonical-datetime.js.map +1 -0
- package/dist/canonical-json.d.ts +12 -0
- package/dist/canonical-json.js +33 -0
- package/dist/canonical-json.js.map +1 -0
- package/dist/control-cohort.d.ts +63 -0
- package/dist/control-cohort.js +80 -0
- package/dist/control-cohort.js.map +1 -0
- package/dist/control-database.d.ts +259 -5
- package/dist/control-database.js +541 -128
- package/dist/control-database.js.map +1 -1
- package/dist/control-formation-recorder.d.ts +89 -0
- package/dist/control-formation-recorder.js +139 -0
- package/dist/control-formation-recorder.js.map +1 -0
- package/dist/control-schema.d.ts +12 -0
- package/dist/control-schema.js +199 -0
- package/dist/control-schema.js.map +1 -0
- package/dist/control-stream.d.ts +54 -0
- package/dist/control-stream.js +104 -0
- package/dist/control-stream.js.map +1 -0
- package/dist/device-token.d.ts +50 -0
- package/dist/device-token.js +66 -0
- package/dist/device-token.js.map +1 -0
- package/dist/diagnostics/connection-path.d.ts +118 -0
- package/dist/diagnostics/connection-path.js +204 -0
- package/dist/diagnostics/connection-path.js.map +1 -0
- package/dist/diagnostics/webrtc-turn-tracker.d.ts +50 -0
- package/dist/diagnostics/webrtc-turn-tracker.js +196 -0
- package/dist/diagnostics/webrtc-turn-tracker.js.map +1 -0
- package/dist/hibernation-manager.d.ts +79 -0
- package/dist/hibernation-manager.js +173 -23
- package/dist/hibernation-manager.js.map +1 -1
- package/dist/index.d.ts +25 -4
- package/dist/index.js +59 -4
- package/dist/index.js.map +1 -1
- package/dist/key-store-file.d.ts +52 -0
- package/dist/key-store-file.js +194 -0
- package/dist/key-store-file.js.map +1 -0
- package/dist/key-store.d.ts +75 -0
- package/dist/key-store.js +66 -0
- package/dist/key-store.js.map +1 -0
- package/dist/peer-authorization.d.ts +26 -0
- package/dist/peer-authorization.js +40 -0
- package/dist/peer-authorization.js.map +1 -0
- package/dist/peer-record.d.ts +89 -0
- package/dist/peer-record.js +117 -0
- package/dist/peer-record.js.map +1 -0
- package/dist/push-credentials.d.ts +34 -0
- package/dist/push-credentials.js +81 -0
- package/dist/push-credentials.js.map +1 -0
- package/dist/push-fanout.d.ts +137 -0
- package/dist/push-fanout.js +197 -0
- package/dist/push-fanout.js.map +1 -0
- package/dist/push-notifier-apns.d.ts +53 -0
- package/dist/push-notifier-apns.js +195 -0
- package/dist/push-notifier-apns.js.map +1 -0
- package/dist/push-notifier-fcm.d.ts +38 -0
- package/dist/push-notifier-fcm.js +183 -0
- package/dist/push-notifier-fcm.js.map +1 -0
- package/dist/push-notifier-shared.d.ts +18 -0
- package/dist/push-notifier-shared.js +25 -0
- package/dist/push-notifier-shared.js.map +1 -0
- package/dist/push-notifier.d.ts +71 -0
- package/dist/push-notifier.js +50 -0
- package/dist/push-notifier.js.map +1 -0
- package/dist/schema-verification.d.ts +11 -2
- package/dist/schema-verification.js +15 -4
- package/dist/schema-verification.js.map +1 -1
- package/dist/seed-bootstrap.d.ts +197 -9
- package/dist/seed-bootstrap.js +396 -137
- package/dist/seed-bootstrap.js.map +1 -1
- package/dist/seed-trust-policy.d.ts +63 -0
- package/dist/seed-trust-policy.js +56 -0
- package/dist/seed-trust-policy.js.map +1 -0
- package/dist/strand-addr-protocol.d.ts +132 -0
- package/dist/strand-addr-protocol.js +313 -0
- package/dist/strand-addr-protocol.js.map +1 -0
- package/dist/strand-cohort.d.ts +54 -0
- package/dist/strand-cohort.js +38 -0
- package/dist/strand-cohort.js.map +1 -0
- package/dist/strand-database.d.ts +54 -6
- package/dist/strand-database.js +88 -100
- package/dist/strand-database.js.map +1 -1
- package/dist/strand-formation-manager.d.ts +79 -19
- package/dist/strand-formation-manager.js +196 -104
- package/dist/strand-formation-manager.js.map +1 -1
- package/dist/strand-formation-protocol.d.ts +162 -0
- package/dist/strand-formation-protocol.js +279 -0
- package/dist/strand-formation-protocol.js.map +1 -0
- package/dist/strand-instance-manager.d.ts +73 -4
- package/dist/strand-instance-manager.js +167 -41
- package/dist/strand-instance-manager.js.map +1 -1
- package/dist/strand-member-key.d.ts +29 -0
- package/dist/strand-member-key.js +38 -0
- package/dist/strand-member-key.js.map +1 -0
- package/dist/strand-member-registry.d.ts +98 -0
- package/dist/strand-member-registry.js +129 -0
- package/dist/strand-member-registry.js.map +1 -0
- package/dist/strand-membership-writer.d.ts +361 -0
- package/dist/strand-membership-writer.js +449 -0
- package/dist/strand-membership-writer.js.map +1 -0
- package/dist/strand-solicitation.d.ts +77 -2
- package/dist/strand-solicitation.js +25 -4
- package/dist/strand-solicitation.js.map +1 -1
- package/dist/strand-wake-payload.d.ts +30 -0
- package/dist/strand-wake-payload.js +20 -0
- package/dist/strand-wake-payload.js.map +1 -0
- package/dist/strand-wake-protocol.d.ts +114 -0
- package/dist/strand-wake-protocol.js +257 -0
- package/dist/strand-wake-protocol.js.map +1 -0
- package/dist/strand-watcher.d.ts +6 -2
- package/dist/strand-watcher.js +57 -17
- package/dist/strand-watcher.js.map +1 -1
- package/dist/types.d.ts +406 -23
- package/dist/types.js +22 -5
- package/dist/types.js.map +1 -1
- package/package.json +14 -8
- package/src/authority-key.ts +68 -0
- package/src/cadre-node.ts +2937 -948
- package/src/canonical-datetime.ts +39 -0
- package/src/canonical-json.ts +30 -0
- package/src/control-cohort.ts +103 -0
- package/src/control-database.ts +931 -383
- package/src/control-formation-recorder.ts +151 -0
- package/src/control-schema.ts +198 -0
- package/src/control-stream.ts +128 -0
- package/src/device-token.ts +89 -0
- package/src/diagnostics/connection-path.ts +277 -0
- package/src/diagnostics/webrtc-turn-tracker.ts +222 -0
- package/src/hibernation-manager.ts +197 -28
- package/src/index.ts +273 -79
- package/src/key-store-file.ts +203 -0
- package/src/key-store.ts +99 -0
- package/src/peer-authorization.ts +53 -0
- package/src/peer-record.ts +146 -0
- package/src/push-credentials.ts +84 -0
- package/src/push-fanout.ts +272 -0
- package/src/push-notifier-apns.ts +243 -0
- package/src/push-notifier-fcm.ts +221 -0
- package/src/push-notifier-shared.ts +28 -0
- package/src/push-notifier.ts +93 -0
- package/src/schema-verification.ts +18 -4
- package/src/seed-bootstrap.ts +464 -188
- package/src/seed-trust-policy.ts +107 -0
- package/src/strand-addr-protocol.ts +410 -0
- package/src/strand-cohort.ts +77 -0
- package/src/strand-database.ts +113 -141
- package/src/strand-formation-manager.ts +233 -142
- package/src/strand-formation-protocol.ts +391 -0
- package/src/strand-instance-manager.ts +207 -56
- package/src/strand-member-key.ts +39 -0
- package/src/strand-member-registry.ts +177 -0
- package/src/strand-membership-writer.ts +640 -0
- package/src/strand-solicitation.ts +93 -4
- package/src/strand-wake-payload.ts +32 -0
- package/src/strand-wake-protocol.ts +331 -0
- package/src/strand-watcher.ts +61 -17
- package/src/types.ts +1012 -582
package/dist/cadre-node.d.ts
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import type { Libp2p, PeerId } from '@libp2p/interface';
|
|
2
|
-
import type {
|
|
2
|
+
import type { Multiaddr } from '@multiformats/multiaddr';
|
|
3
|
+
import type { CadreNodeConfig, StrandInstance, StrandConfig, SAppConfig, CadreNodeEvents, ControlNetworkSeed, ApplySeedResult, AddDroneOptions, AddPhoneOptions, DroneInitResult, InviteResult, CadreInvite, OpenInvitation, FormStrandResult, StrandFormationDisclosure, ResolveOpts, SelfRegistrationOutcome, ServiceWakeResult, PushPlatform, DeviceTokenRecord, ResolveDeviceTokenOpts } from './types.js';
|
|
4
|
+
import { type AuthorityKeyPair } from './authority-key.js';
|
|
3
5
|
import { type SAppIdLookup } from './strand-watcher.js';
|
|
4
6
|
import { EnrollmentService } from './enrollment.js';
|
|
5
7
|
import { ControlDatabase } from './control-database.js';
|
|
6
8
|
import { SeedBootstrapService } from './seed-bootstrap.js';
|
|
9
|
+
import type { SeedTrustPolicy } from './seed-trust-policy.js';
|
|
7
10
|
import { StrandSolicitationService, type StrandSolicitationServiceOptions } from './strand-solicitation.js';
|
|
11
|
+
import type { WakeAck } from './types.js';
|
|
12
|
+
import { type ConnectionPathSummary } from './diagnostics/connection-path.js';
|
|
8
13
|
type EventHandler<T> = (data: T) => void;
|
|
9
14
|
/**
|
|
10
15
|
* CadreNode is the main entry point for a cadre member.
|
|
@@ -17,6 +22,15 @@ type EventHandler<T> = (data: T) => void;
|
|
|
17
22
|
*/
|
|
18
23
|
export declare class CadreNode implements SAppIdLookup {
|
|
19
24
|
private readonly config;
|
|
25
|
+
/**
|
|
26
|
+
* The resolved node identity key, set once by {@link resolveIdentityKey}
|
|
27
|
+
* during {@link start} (from `config.keyStore`, else `config.privateKey`).
|
|
28
|
+
* Left undefined when neither is configured — libp2p then generates an
|
|
29
|
+
* ephemeral key internally and there is no exposed authority key. Every
|
|
30
|
+
* identity-dependent path (control node creation, self-record signing, strand
|
|
31
|
+
* launch) reads this resolved field, never `config.privateKey` directly.
|
|
32
|
+
*/
|
|
33
|
+
private identityKey;
|
|
20
34
|
private controlNode;
|
|
21
35
|
private controlDatabase;
|
|
22
36
|
private strandWatcher;
|
|
@@ -25,10 +39,123 @@ export declare class CadreNode implements SAppIdLookup {
|
|
|
25
39
|
private enrollmentService;
|
|
26
40
|
private seedBootstrapService;
|
|
27
41
|
private strandSolicitationService;
|
|
28
|
-
private
|
|
42
|
+
private strandWakeService;
|
|
43
|
+
/**
|
|
44
|
+
* Control-network strand-address responder. Answers a co-cadre sibling's
|
|
45
|
+
* on-demand request for this node's live strand-network multiaddrs so the
|
|
46
|
+
* sibling can seed a strand mesh from us — the read side of the seed path that
|
|
47
|
+
* stops conflating control addresses with strand seeding.
|
|
48
|
+
*/
|
|
49
|
+
private strandAddrService;
|
|
50
|
+
/**
|
|
51
|
+
* Server-side push-wake fan-out. Constructed by {@link start} only when
|
|
52
|
+
* `config.push` (FCM/APNs credentials) is present — without it the node behaves
|
|
53
|
+
* exactly as before (no notifier, no fan-out). Owns who/when to wake
|
|
54
|
+
* hibernating mobile peers on strand activity.
|
|
55
|
+
*/
|
|
56
|
+
private pushFanoutService;
|
|
57
|
+
/** Backing field for the {@link running} / {@link isRunning} getters. */
|
|
58
|
+
private _running;
|
|
59
|
+
/**
|
|
60
|
+
* In-flight {@link serviceWake} operations keyed by strandId. Coalesces
|
|
61
|
+
* concurrent on-demand wakes for the same strand into one runtime build + one
|
|
62
|
+
* window + one re-hibernate decision (a second caller joins the first's
|
|
63
|
+
* promise), complementing {@link HibernationManager}'s wake coalescing.
|
|
64
|
+
*/
|
|
65
|
+
private serviceWakePromises;
|
|
66
|
+
/**
|
|
67
|
+
* Live wake-window waiters (see {@link holdWakeWindow}). Tracked so
|
|
68
|
+
* {@link cleanup} can clear the timer AND resolve the promise on teardown — a
|
|
69
|
+
* window must never fire (or hang an in-flight serviceWake) after stop().
|
|
70
|
+
*/
|
|
71
|
+
private windowWaiters;
|
|
29
72
|
private eventHandlers;
|
|
30
73
|
/** Map of strandId -> sAppConfig for sAppId filtering and management */
|
|
31
74
|
private sAppConfigs;
|
|
75
|
+
/**
|
|
76
|
+
* Most-recently pushed invite addresses (see {@link setInviteAddresses}).
|
|
77
|
+
* When non-null these take priority over `libp2pNode.getMultiaddrs()` when
|
|
78
|
+
* minting invites — the host pushes NAT-resolved addresses here so the
|
|
79
|
+
* control-network node never needs to dial back to the manager.
|
|
80
|
+
*/
|
|
81
|
+
private latestInviteAddresses;
|
|
82
|
+
/** Initial self-registration timer (see {@link scheduleSelfRegistration}). */
|
|
83
|
+
private selfRegistrationTimer;
|
|
84
|
+
/** TTL heartbeat that re-publishes the self record before it goes stale. */
|
|
85
|
+
private recordRefreshTimer;
|
|
86
|
+
/** Listener that re-publishes the self record when reachable addresses change. */
|
|
87
|
+
private selfPeerUpdateHandler;
|
|
88
|
+
/**
|
|
89
|
+
* Recurring proactive control-cohort dial cadence (see
|
|
90
|
+
* {@link reconcileControlCohort}). Wired alongside {@link recordRefreshTimer}
|
|
91
|
+
* in {@link startRecordRefresh} and torn down symmetrically in
|
|
92
|
+
* {@link stopRecordRefresh}; `.unref()`'d so it never keeps the loop alive.
|
|
93
|
+
*/
|
|
94
|
+
private controlCohortReconcileTimer;
|
|
95
|
+
/**
|
|
96
|
+
* Single-flight guard for {@link reconcileControlCohort}. The eager start pass,
|
|
97
|
+
* the recurring interval, and the `self:peer:update` trigger can fire close
|
|
98
|
+
* together; collapsing concurrent passes into one in-flight run prevents two
|
|
99
|
+
* passes from double-dialing the same siblings (mirrors {@link registerSelfInFlight}).
|
|
100
|
+
*/
|
|
101
|
+
private reconcileControlCohortInFlight;
|
|
102
|
+
/**
|
|
103
|
+
* Single-flight guard for {@link registerSelf}. Concurrent callers (the explicit
|
|
104
|
+
* CLI `--authority` publish, the 1s startup timer, the TTL heartbeat, and the
|
|
105
|
+
* address-change listener) share one in-flight publish so two of them can never
|
|
106
|
+
* both read "no row yet" and race a duplicate INSERT (a `CadrePeer` PK conflict).
|
|
107
|
+
*/
|
|
108
|
+
private registerSelfInFlight;
|
|
109
|
+
/**
|
|
110
|
+
* Re-replication queue for authority control writes that committed while this
|
|
111
|
+
* node was alone — `controlNode.getConnections().length === 0` at write time
|
|
112
|
+
* means the Optimystic commit was local-only (the block's cluster was ≤1) and
|
|
113
|
+
* never broadcast. Maps the affected subject peerId → the write to re-issue once
|
|
114
|
+
* the cohort grows. A later op for the same subject overwrites an earlier one
|
|
115
|
+
* (authorize then remove → remove wins). Drained on the 0→≥1 control-connection
|
|
116
|
+
* transition by {@link drainPendingControlReplication}.
|
|
117
|
+
*/
|
|
118
|
+
private pendingPeerWrites;
|
|
119
|
+
/** This node's own `CadrePeer` self-write committed local-only (re-touched on growth). */
|
|
120
|
+
private pendingSelfPeerWrite;
|
|
121
|
+
/** This node's own `DeviceToken` self-write committed local-only (re-touched on growth). */
|
|
122
|
+
private pendingSelfDeviceWrite;
|
|
123
|
+
/**
|
|
124
|
+
* Guards the one-shot, first-cohort-growth reconstruction: an authority re-touches
|
|
125
|
+
* every membership row it may have authored that could be unreplicated (covering
|
|
126
|
+
* writes made before this process started, which the in-memory queue cannot know).
|
|
127
|
+
* Set true after the first drain so later passes only drain the in-memory queue.
|
|
128
|
+
*/
|
|
129
|
+
private reconstructedLocalOnlyWrites;
|
|
130
|
+
/** Single-flight guard for the re-replication drain (mirrors {@link registerSelfInFlight}). */
|
|
131
|
+
private drainControlReplicationInFlight;
|
|
132
|
+
/**
|
|
133
|
+
* Tracks the control-connection presence edge so the drain fires only on the
|
|
134
|
+
* 0→≥1 transition (the earliest point a re-issue can broadcast), not on every
|
|
135
|
+
* subsequent `connection:open`. Re-armed to false once connections return to 0.
|
|
136
|
+
*/
|
|
137
|
+
private hasControlConnection;
|
|
138
|
+
/** `connection:open` listener driving the growth-triggered drain (teardown in {@link stopRecordRefresh}). */
|
|
139
|
+
private controlConnectionOpenHandler;
|
|
140
|
+
/** `connection:close` listener re-arming the growth edge (teardown in {@link stopRecordRefresh}). */
|
|
141
|
+
private controlConnectionCloseHandler;
|
|
142
|
+
/**
|
|
143
|
+
* Hooks `globalThis.RTCPeerConnection` to observe whether ICE selected a TURN
|
|
144
|
+
* relay candidate for each WebRTC session. Installed in {@link start}, disposed
|
|
145
|
+
* in {@link cleanup}; inert on Node.js (no `RTCPeerConnection`).
|
|
146
|
+
*/
|
|
147
|
+
private readonly turnTracker;
|
|
148
|
+
/**
|
|
149
|
+
* Peer IDs whose current WebRTC connection was observed to be TURN-relayed.
|
|
150
|
+
* Populated by {@link handleTurnConnectionOpen} (drains the tracker queue on a
|
|
151
|
+
* `/webrtc` `connection:open`), cleared per-peer on `connection:close`. Read by
|
|
152
|
+
* {@link getConnectionPaths} to promote `webrtc` → `webrtc-turn` (relayed).
|
|
153
|
+
*/
|
|
154
|
+
private turnRelayedPeers;
|
|
155
|
+
/** `connection:open` listener feeding TURN detection (teardown in {@link stopRecordRefresh}). */
|
|
156
|
+
private turnConnectionOpenHandler;
|
|
157
|
+
/** `connection:close` listener clearing a peer's TURN flag (teardown in {@link stopRecordRefresh}). */
|
|
158
|
+
private turnConnectionCloseHandler;
|
|
32
159
|
constructor(config: CadreNodeConfig);
|
|
33
160
|
/**
|
|
34
161
|
* SAppIdLookup implementation - get sAppId for a strand
|
|
@@ -38,6 +165,10 @@ export declare class CadreNode implements SAppIdLookup {
|
|
|
38
165
|
* Get the peer ID of this node (available after start)
|
|
39
166
|
*/
|
|
40
167
|
get peerId(): PeerId | undefined;
|
|
168
|
+
/**
|
|
169
|
+
* The party ID this node serves (control-network identity).
|
|
170
|
+
*/
|
|
171
|
+
get partyId(): string;
|
|
41
172
|
/**
|
|
42
173
|
* Get the multiaddrs of this node (available after start)
|
|
43
174
|
*/
|
|
@@ -46,6 +177,31 @@ export declare class CadreNode implements SAppIdLookup {
|
|
|
46
177
|
* Check if the node is running
|
|
47
178
|
*/
|
|
48
179
|
get isRunning(): boolean;
|
|
180
|
+
/**
|
|
181
|
+
* Synchronous lifecycle snapshot for headless callers (a mobile
|
|
182
|
+
* `BackgroundRunner` that boots in a background task and must *query* state
|
|
183
|
+
* rather than subscribe to `control:connected`/`control:disconnected`).
|
|
184
|
+
* Equivalent to {@link isRunning}.
|
|
185
|
+
*/
|
|
186
|
+
get running(): boolean;
|
|
187
|
+
/**
|
|
188
|
+
* Synchronous readiness snapshot: whether the control network is currently
|
|
189
|
+
* connected (the node is running and its control-network libp2p node is up).
|
|
190
|
+
* Tracks the same edge the `control:connected`/`control:disconnected` events
|
|
191
|
+
* announce, but pollable.
|
|
192
|
+
*/
|
|
193
|
+
get controlConnected(): boolean;
|
|
194
|
+
/**
|
|
195
|
+
* Classify every open control-network connection as relayed
|
|
196
|
+
* (`/p2p-circuit`) vs direct, tag its transport, and summarise counts plus a
|
|
197
|
+
* stuck-on-relay condition. Pure, read-only snapshot over
|
|
198
|
+
* `controlNode.getConnections()`. Returns an empty (all-zero) summary when
|
|
199
|
+
* the node has not been started.
|
|
200
|
+
*
|
|
201
|
+
* @param settleWindowMs - grace period before a relayed connection with no
|
|
202
|
+
* direct sibling is considered stuck (default 10_000ms)
|
|
203
|
+
*/
|
|
204
|
+
getConnectionPaths(settleWindowMs?: number): ConnectionPathSummary;
|
|
49
205
|
/**
|
|
50
206
|
* Get all strand instances
|
|
51
207
|
*/
|
|
@@ -75,41 +231,599 @@ export declare class CadreNode implements SAppIdLookup {
|
|
|
75
231
|
*/
|
|
76
232
|
off<K extends keyof CadreNodeEvents>(event: K, handler: EventHandler<CadreNodeEvents[K]>): void;
|
|
77
233
|
private emit;
|
|
234
|
+
/**
|
|
235
|
+
* Resolve the node identity into {@link identityKey} exactly once, fail-closed,
|
|
236
|
+
* before any network bring-up. Resolution order:
|
|
237
|
+
*
|
|
238
|
+
* 1. Both `keyStore` and `privateKey` set ⇒ configuration error (throws).
|
|
239
|
+
* 2. `keyStore` set ⇒ load protobuf bytes from `identityKeyId` (default
|
|
240
|
+
* {@link DEFAULT_IDENTITY_KEY_ID}). Found ⇒ deserialize; empty ⇒ generate a
|
|
241
|
+
* fresh Ed25519 key, persist it, and use it. A rejected `get` (access denied
|
|
242
|
+
* / backend failure) PROPAGATES — we never generate a new key on a read
|
|
243
|
+
* error, which would silently orphan the real identity.
|
|
244
|
+
* 3. `privateKey` set ⇒ use it directly.
|
|
245
|
+
* 4. Neither ⇒ leave undefined; libp2p generates an ephemeral key.
|
|
246
|
+
*
|
|
247
|
+
* Idempotent: a second call (or a stop()→start() cycle) reuses the already
|
|
248
|
+
* resolved key rather than regenerating or re-persisting.
|
|
249
|
+
*/
|
|
250
|
+
private resolveIdentityKey;
|
|
78
251
|
private createControlNode;
|
|
79
252
|
private createStrandQueryable;
|
|
80
253
|
/**
|
|
81
|
-
* Schedule self-
|
|
82
|
-
*
|
|
254
|
+
* Schedule the node's initial self-record publish + ongoing refresh shortly
|
|
255
|
+
* after start (non-blocking). {@link registerSelf} is idempotent and safely
|
|
256
|
+
* no-ops when it cannot yet sign/insert (e.g. authority key not installed),
|
|
257
|
+
* so the timer is harmless even when registration only becomes possible later.
|
|
83
258
|
*/
|
|
84
259
|
private scheduleSelfRegistration;
|
|
85
260
|
/**
|
|
86
|
-
*
|
|
87
|
-
*
|
|
261
|
+
* Publish (or refresh) this node's own signed `CadrePeer` address record so
|
|
262
|
+
* other members can resolve its current signaling/relay multiaddrs from its
|
|
263
|
+
* PeerId alone. Public, awaitable, and idempotent.
|
|
264
|
+
*
|
|
265
|
+
* - Builds a `PeerAddressRecord` from the node's current dialable addrs
|
|
266
|
+
* (signaling/`p2p-circuit` first), signed with the ed25519 key behind its
|
|
267
|
+
* PeerId (the resolved node identity from `keyStore`/`config.privateKey`).
|
|
268
|
+
* - If the row already exists: a self-signed UPDATE bumping `UpdatedAt`.
|
|
269
|
+
* - If not, and the node is its own authority: an authority-signed INSERT that
|
|
270
|
+
* also carries the self-signature.
|
|
271
|
+
* - Otherwise: logs and returns (a non-authority node with no row yet must
|
|
272
|
+
* wait for an authority to insert it; it can then self-refresh).
|
|
273
|
+
*
|
|
274
|
+
* Safe to call repeatedly (heartbeat / address-change driven); each successful
|
|
275
|
+
* publish strictly increases `UpdatedAt`. Concurrent calls are collapsed into a
|
|
276
|
+
* single in-flight publish (see {@link registerSelfInFlight}) so the explicit
|
|
277
|
+
* startup publish and the background timers can never race a duplicate INSERT.
|
|
278
|
+
*
|
|
279
|
+
* @returns what the publish did — `inserted`, `refreshed`, or `skipped`.
|
|
280
|
+
*/
|
|
281
|
+
registerSelf(): Promise<SelfRegistrationOutcome>;
|
|
282
|
+
/** The body of {@link registerSelf}; serialised by its single-flight guard. */
|
|
283
|
+
private publishSelfRecord;
|
|
284
|
+
/**
|
|
285
|
+
* The ed25519 keypair (base64url) the node signs its own record with — the key
|
|
286
|
+
* behind its libp2p PeerId. Sourced from the resolved {@link identityKey}
|
|
287
|
+
* (which a `keyStore` or `config.privateKey` supplies); returns null when
|
|
288
|
+
* absent (ephemeral identity) or (defensively) when it does not match the
|
|
289
|
+
* control node's PeerId, in which case self-publish is skipped rather than
|
|
290
|
+
* producing an unresolvable row.
|
|
291
|
+
*/
|
|
292
|
+
private getSelfSigningKey;
|
|
293
|
+
/**
|
|
294
|
+
* The authority keypair (base64url Ed25519) derived from this node's resolved
|
|
295
|
+
* identity key. In the single-key reference model the authority signing key is
|
|
296
|
+
* *derived from* the node identity (see {@link authorityKeyFromLibp2p}), so the
|
|
297
|
+
* same key material protected in a secure enclave backs both.
|
|
298
|
+
*
|
|
299
|
+
* Exposed so the hosting app retains control of authority genesis: cadre-core
|
|
300
|
+
* resolves + protects the identity, then the app sources this pair to drive
|
|
301
|
+
* `ensureAuthorityKey(pub)` + `initializeSeedBootstrap(priv)` itself — cadre-core
|
|
302
|
+
* never silently runs genesis. A future separate-authority slot would return a
|
|
303
|
+
* distinct key here instead of the identity-derived one.
|
|
304
|
+
*
|
|
305
|
+
* @returns The base64url seed/public-key authority pair.
|
|
306
|
+
* @throws If called before {@link start} has resolved the identity, or when the
|
|
307
|
+
* node runs on an ephemeral libp2p key (no `keyStore`/`privateKey` configured),
|
|
308
|
+
* since that key is internal to libp2p and not exposed.
|
|
309
|
+
*/
|
|
310
|
+
getIdentityAuthorityKey(): AuthorityKeyPair;
|
|
311
|
+
/**
|
|
312
|
+
* Collect this node's current dialable addresses for publication, signaling
|
|
313
|
+
* (`/p2p-circuit`) first. Prefers the best invite/NAT-resolved set and folds
|
|
314
|
+
* in the relay/signaling address (the WebRTC dial input) when not already
|
|
315
|
+
* present.
|
|
316
|
+
*/
|
|
317
|
+
private collectSelfAddrs;
|
|
318
|
+
/**
|
|
319
|
+
* Wire the ongoing self-record refresh: re-publish whenever libp2p reports an
|
|
320
|
+
* address change (relay reservation rotation, NAT change) and on a TTL
|
|
321
|
+
* heartbeat at half the freshness ceiling. Idempotent — repeated calls do not
|
|
322
|
+
* stack listeners/timers.
|
|
323
|
+
*/
|
|
324
|
+
private startRecordRefresh;
|
|
325
|
+
/** Tear down the self-record refresh timers + listener (see {@link cleanup}). */
|
|
326
|
+
private stopRecordRefresh;
|
|
327
|
+
/**
|
|
328
|
+
* Resolve a peer's current, signed, trust-checkable multiaddrs from only its
|
|
329
|
+
* PeerId — the transport-agnostic input a NAT-to-NAT WebRTC (or any) dial path
|
|
330
|
+
* consumes, with no copy/paste of a relayed dial string.
|
|
331
|
+
*
|
|
332
|
+
* Reads the peer's `CadrePeer` record and gates it through, in order:
|
|
333
|
+
* 1. record present (else `[]`),
|
|
334
|
+
* 2. `publicKey <-> peerId` binding (the stored key's libp2p identity must be
|
|
335
|
+
* the requested peerId),
|
|
336
|
+
* 3. self-signature verifies against `publicKey`,
|
|
337
|
+
* 4. freshness — rejected once older than `maxAgeMs` (never a dead relay
|
|
338
|
+
* reservation),
|
|
339
|
+
* 5. the pluggable trust gate (`opts.trustPolicy`).
|
|
340
|
+
* Survivors are returned signaling (`/p2p-circuit`) first, filtered to
|
|
341
|
+
* signaling-only when requested, as parsed `Multiaddr`s (unparsable addrs
|
|
342
|
+
* dropped). Any gate failure yields an empty array rather than throwing.
|
|
343
|
+
*/
|
|
344
|
+
resolvePeerAddrs(peerId: string, opts?: ResolveOpts): Promise<Multiaddr[]>;
|
|
345
|
+
/** Parse multiaddr strings, dropping (and logging) any that fail to parse. */
|
|
346
|
+
private parseMultiaddrs;
|
|
347
|
+
/**
|
|
348
|
+
* Run one proactive control-cohort dial pass to keep this node connected to its
|
|
349
|
+
* cadre siblings (so the `CadreControl` collections form a replicating cohort).
|
|
350
|
+
* Public so the cohort-growth-driven re-replication path
|
|
351
|
+
* (`control-write-ensure-replicated`) and tests can trigger a pass on demand;
|
|
352
|
+
* normally driven by the eager start pass, the recurring interval, and
|
|
353
|
+
* `self:peer:update` (all wired in {@link startRecordRefresh}).
|
|
354
|
+
*
|
|
355
|
+
* Concurrent triggers collapse into a single in-flight pass
|
|
356
|
+
* (see {@link reconcileControlCohortInFlight}) so two passes never double-dial.
|
|
357
|
+
* Best-effort throughout: a failure to resolve/dial any one sibling is logged
|
|
358
|
+
* and the pass continues; the whole pass is a no-op when the node is alone.
|
|
359
|
+
*/
|
|
360
|
+
reconcileControlCohort(): Promise<void>;
|
|
361
|
+
/** Body of {@link reconcileControlCohort}; serialised by its single-flight guard. */
|
|
362
|
+
private runReconcileControlCohort;
|
|
363
|
+
/**
|
|
364
|
+
* Resolve one sibling's control-network dial addresses and dial it, best-effort.
|
|
365
|
+
* Returns whether a dial was attempted (false when no address resolves).
|
|
366
|
+
*
|
|
367
|
+
* A per-peer failure (NAT, offline, relay down, connection-gater denial) is
|
|
368
|
+
* logged and swallowed so one unreachable sibling never aborts the pass —
|
|
369
|
+
* exactly like {@link SeedBootstrapService.applySeed}'s authority-dial loop. A
|
|
370
|
+
* failed dial is simply retried on the next pass.
|
|
371
|
+
*/
|
|
372
|
+
private dialControlSibling;
|
|
373
|
+
/**
|
|
374
|
+
* Resolve a sibling's control-network dial addresses for the reconcile pass.
|
|
375
|
+
*
|
|
376
|
+
* Primary (steady state): the signed, fresh, trust-gated control addresses from
|
|
377
|
+
* the converged `CadrePeer` record via {@link resolvePeerAddrs}. Fallback (cold
|
|
378
|
+
* start): the libp2p peerStore entries `applySeed` populated, used only while the
|
|
379
|
+
* record is not yet resolvable. Returns `[]` (never throws) when neither yields
|
|
380
|
+
* an address — that sibling is skipped this pass.
|
|
381
|
+
*/
|
|
382
|
+
private resolveControlDialAddrs;
|
|
383
|
+
/**
|
|
384
|
+
* Cold-start fallback: the libp2p peerStore multiaddrs for `peerId` (seeded by
|
|
385
|
+
* {@link SeedBootstrapService.applySeed}). Returns `[]` on a missing entry or any
|
|
386
|
+
* parse/lookup failure — never throws.
|
|
387
|
+
*/
|
|
388
|
+
private peerStoreAddrs;
|
|
389
|
+
/**
|
|
390
|
+
* Whether a control write happening now would commit local-only. A sound lower
|
|
391
|
+
* bound is "no connected control peers": 0 connections ⇒ the block's cluster is
|
|
392
|
+
* ≤1 ⇒ Optimystic commits without broadcasting. This is the pragmatic proxy for
|
|
393
|
+
* the precise signal (the block's `getClusterSize`); it over-approximates safely
|
|
394
|
+
* — a connected-but-not-in-this-block's-cluster write may still be local-only and
|
|
395
|
+
* is caught by the cohort's periodic pull-on-read instead. Re-issuing an already-
|
|
396
|
+
* replicated row is harmless (an idempotent monotonic bump), so the coarse proxy
|
|
397
|
+
* is acceptable as the agreed first cut.
|
|
398
|
+
*/
|
|
399
|
+
private committedAlone;
|
|
400
|
+
/**
|
|
401
|
+
* Record (or clear) a just-committed authority membership write in the
|
|
402
|
+
* write-while-alone re-replication queue. If the control node had no connections
|
|
403
|
+
* at commit, the Optimystic write was local-only and must be re-issued once the
|
|
404
|
+
* cohort grows; otherwise the write replicated and any stale queue entry for this
|
|
405
|
+
* subject is dropped.
|
|
406
|
+
*
|
|
407
|
+
* A `remove` that commits alone is a security-relevant durability gap (a revoked
|
|
408
|
+
* peer may persist as a member elsewhere), so it is logged loudly — and, because
|
|
409
|
+
* a physical delete leaves no local trace to re-issue from, its on-growth
|
|
410
|
+
* re-issue is best-effort only (see {@link drainPendingPeerWrites}).
|
|
411
|
+
*/
|
|
412
|
+
private noteControlWrite;
|
|
413
|
+
/**
|
|
414
|
+
* Drain the write-while-alone re-replication queue: re-issue the writes that
|
|
415
|
+
* committed local-only now that the cohort can broadcast them. Public so the
|
|
416
|
+
* 0→≥1 growth trigger ({@link handleControlConnectionChange}) and tests can drive
|
|
417
|
+
* it; concurrent calls collapse into one in-flight drain
|
|
418
|
+
* ({@link drainControlReplicationInFlight}) so two growth signals never
|
|
419
|
+
* double-issue. Best-effort throughout — a per-row failure leaves that entry
|
|
420
|
+
* queued for the next growth rather than aborting the drain.
|
|
421
|
+
*/
|
|
422
|
+
drainPendingControlReplication(reason: string): Promise<void>;
|
|
423
|
+
/** Body of {@link drainPendingControlReplication}; serialised by its single-flight guard. */
|
|
424
|
+
private runDrainControlReplication;
|
|
425
|
+
/**
|
|
426
|
+
* Re-touch this node's own `DeviceToken` row (re-sign + bump `UpdatedAt` via
|
|
427
|
+
* {@link registerDeviceToken}) so a self device-token that committed local-only
|
|
428
|
+
* re-broadcasts on cohort growth. No-op when no row exists (nothing to
|
|
429
|
+
* re-replicate) or the stored platform is unknown. Best-effort — never throws to
|
|
430
|
+
* the drain.
|
|
431
|
+
*/
|
|
432
|
+
private retouchSelfDeviceToken;
|
|
433
|
+
/**
|
|
434
|
+
* One-shot, first-cohort-growth reconstruction of the write-while-alone queue for
|
|
435
|
+
* an AUTHORITY node: re-touch every membership row that may be an unreplicated
|
|
436
|
+
* authority insert. A row is a candidate iff it is not self (handled by
|
|
437
|
+
* {@link registerSelf}), is not already tracked in the in-memory queue (handled by
|
|
438
|
+
* {@link drainPendingPeerWrites}), and carries no self-`Sig` yet (an
|
|
439
|
+
* authority-authored row the peer has not self-published — the only kind safe to
|
|
440
|
+
* bump without invalidating a self-signature). O(rows) on the small control
|
|
441
|
+
* tables; safe to over-apply (a monotonic authority bump on an already-replicated
|
|
442
|
+
* row is a no-op-equivalent).
|
|
443
|
+
*
|
|
444
|
+
* A node with no authority private key skips this entirely — it cannot re-sign
|
|
445
|
+
* rows for other peers, and rows it merely holds are not its to re-issue. DELETEs
|
|
446
|
+
* cannot be reconstructed here (a removed row leaves no local trace and the schema
|
|
447
|
+
* carries no tombstone) — see the delete-path note in {@link drainPendingPeerWrites}.
|
|
448
|
+
*/
|
|
449
|
+
private reconstructAuthoredMembership;
|
|
450
|
+
/**
|
|
451
|
+
* Drain the in-session write-while-alone queue: re-issue each pending authority
|
|
452
|
+
* membership write now that the cohort can broadcast it. Sequential (no fan-out)
|
|
453
|
+
* to avoid a thundering re-touch; an entry is cleared only on success, so a
|
|
454
|
+
* failure (or a still-alone re-commit) leaves it queued for the next growth.
|
|
455
|
+
*
|
|
456
|
+
* - `authorize`: re-issue as an idempotent monotonic authority UPDATE
|
|
457
|
+
* ({@link reissuePeerAuthorize}). Skipped (and cleared) if the row vanished
|
|
458
|
+
* (raced a delete) or now carries a self-`Sig` (the peer self-published and owns
|
|
459
|
+
* its republish).
|
|
460
|
+
* - `remove` (security-relevant): a removePeer-while-alone physically removed the
|
|
461
|
+
* row locally, so a re-issued DELETE matches nothing and does NOT propagate —
|
|
462
|
+
* full delete durability requires a schema tombstone (deferred:
|
|
463
|
+
* `control-delete-while-alone-tombstone`). We still attempt the re-issue
|
|
464
|
+
* (harmless, and it propagates in the row-still-present case); the commit-alone
|
|
465
|
+
* was already logged loudly in {@link noteControlWrite}.
|
|
466
|
+
*/
|
|
467
|
+
private drainPendingPeerWrites;
|
|
468
|
+
/**
|
|
469
|
+
* Re-issue an authority membership row as a monotonic authority UPDATE: bump
|
|
470
|
+
* `UpdatedAt` strictly above the stored value (and the wall clock) and re-sign via
|
|
471
|
+
* the authority branch of `CadrePeer.AuthorizedUpdate`. The row already exists
|
|
472
|
+
* locally (it committed there, just local-only), so this is an UPDATE, not the
|
|
473
|
+
* original INSERT.
|
|
474
|
+
*/
|
|
475
|
+
private reissuePeerAuthorize;
|
|
476
|
+
/**
|
|
477
|
+
* On a control connection opening, detect the 0→≥1 transition and drain the
|
|
478
|
+
* write-while-alone re-replication queue (single-flight; fires only on the edge,
|
|
479
|
+
* not on every subsequent `connection:open`). Best-effort — a drain failure is
|
|
480
|
+
* logged, not thrown.
|
|
481
|
+
*/
|
|
482
|
+
private handleControlConnectionChange;
|
|
483
|
+
/** Re-arm the growth edge once all control connections drop, so a later reconnect re-drains. */
|
|
484
|
+
private handleControlConnectionClose;
|
|
485
|
+
/**
|
|
486
|
+
* Wire the control-connection growth listeners that drive write-while-alone
|
|
487
|
+
* re-replication. Wired in {@link start} (not the delayed refresh path) so no
|
|
488
|
+
* early `connection:open` is missed; torn down in {@link stopRecordRefresh}.
|
|
489
|
+
* Idempotent.
|
|
490
|
+
*/
|
|
491
|
+
private wireControlConnectionListeners;
|
|
492
|
+
/**
|
|
493
|
+
* On a control connection opening: if it is a WebRTC connection, drain the TURN
|
|
494
|
+
* tracker for the just-settled ICE verdict and, when it relayed, mark the peer
|
|
495
|
+
* so {@link getConnectionPaths} classifies it `webrtc-turn` (relayed). The
|
|
496
|
+
* settlement↔open correlation is timing-based and best-effort; an unknown
|
|
497
|
+
* verdict degrades to not-relayed. Never throws to the event loop.
|
|
498
|
+
*/
|
|
499
|
+
private handleTurnConnectionOpen;
|
|
500
|
+
/** On a control connection closing, drop any TURN-relayed flag for its peer. */
|
|
501
|
+
private handleTurnConnectionClose;
|
|
502
|
+
/**
|
|
503
|
+
* Publish (or refresh) this node's own self-signed `DeviceToken` row so a server
|
|
504
|
+
* peer can resolve its FCM/APNs push token from its PeerId alone. Mirrors
|
|
505
|
+
* {@link registerSelf}:
|
|
506
|
+
*
|
|
507
|
+
* - If the row already exists: a self-signed UPDATE bumping `UpdatedAt` (works
|
|
508
|
+
* for any member — the `AuthorizedUpdate` self-branch verifies the new `Sig`
|
|
509
|
+
* against the bound `CadrePeer.PublicKey`). Platform/Token may change here
|
|
510
|
+
* (rotation / platform switch / reinstall are all normal self-updates).
|
|
511
|
+
* - If not, and the node holds an authority service: an authority-signed INSERT
|
|
512
|
+
* that also carries the self-signature.
|
|
513
|
+
* - Otherwise: throws. Like `CadrePeer`, the first `DeviceToken` row requires an
|
|
514
|
+
* authority signature; a non-authority peer (e.g. a phone) must have its row
|
|
515
|
+
* seeded by an authority — typically the server it enrolled with — before it
|
|
516
|
+
* can self-refresh. (Establishing that phone→server registration handshake is
|
|
517
|
+
* the downstream "RN registration" ticket; this node only owns the cadre-core
|
|
518
|
+
* write path.)
|
|
519
|
+
*
|
|
520
|
+
* `UpdatedAt` strictly increases on every publish (even a same-millisecond
|
|
521
|
+
* re-publish), so a replayed older record is rejected by the schema.
|
|
522
|
+
*
|
|
523
|
+
* @param platform - `'fcm'` (Android/Firebase) or `'apns'` (Apple).
|
|
524
|
+
* @param token - the opaque platform device/registration token.
|
|
525
|
+
* @throws if the node is not started, exposes no self-signing key, or has no
|
|
526
|
+
* existing row and no authority service to self-insert.
|
|
527
|
+
*/
|
|
528
|
+
registerDeviceToken(platform: PushPlatform, token: string): Promise<void>;
|
|
529
|
+
/**
|
|
530
|
+
* Resolve a cadre peer's FCM/APNs push token from only its PeerId — the input a
|
|
531
|
+
* server's push-wake fan-out consumes to deliver a platform push to a suspended
|
|
532
|
+
* app. Applies the same gating shape as {@link resolvePeerAddrs}, returning
|
|
533
|
+
* `null` (never throwing) on any failure:
|
|
534
|
+
*
|
|
535
|
+
* 1. membership — the peer has a `CadrePeer` row with a `PublicKey`,
|
|
536
|
+
* 2. `publicKey <-> peerId` binding — the stored key's libp2p identity is the
|
|
537
|
+
* requested peerId,
|
|
538
|
+
* 3. a `DeviceToken` row exists with a known {@link PushPlatform},
|
|
539
|
+
* 4. self-signature verifies against the bound `CadrePeer.PublicKey`,
|
|
540
|
+
* 5. freshness — `updatedAt` is positive and within `opts.maxAgeMs` (default:
|
|
541
|
+
* no ceiling, since a push token is valid until it rotates).
|
|
542
|
+
*
|
|
543
|
+
* A peer that is not a current member, or whose token has no backing `CadrePeer`
|
|
544
|
+
* record, resolves to `null` — a server must not attempt to push to a non-cadre
|
|
545
|
+
* peer.
|
|
546
|
+
*/
|
|
547
|
+
resolveDeviceToken(peerId: string, opts?: ResolveDeviceTokenOpts): Promise<DeviceTokenRecord | null>;
|
|
548
|
+
/**
|
|
549
|
+
* Delete this node's own `DeviceToken` row (logout / token invalidation). No-op
|
|
550
|
+
* when no row exists. Like {@link registerDeviceToken}'s first insert, the delete
|
|
551
|
+
* is gated on an authority signature (`DeviceToken.AuthorizedInsert` covers insert
|
|
552
|
+
* AND delete), so it requires this node's authority service; a non-authority peer
|
|
553
|
+
* must route the clear through its authority (downstream RN registration path).
|
|
554
|
+
*
|
|
555
|
+
* @throws if the node is not started, or a row exists but no authority service is
|
|
556
|
+
* available to sign the delete.
|
|
557
|
+
*/
|
|
558
|
+
clearDeviceToken(): Promise<void>;
|
|
559
|
+
/**
|
|
560
|
+
* Expire ANOTHER peer's stale `DeviceToken` after a platform reported it
|
|
561
|
+
* unregistered during a push-wake fan-out. Unlike {@link clearDeviceToken}
|
|
562
|
+
* (self-only — it hardcodes the local peerId), this takes an arbitrary peerId.
|
|
563
|
+
*
|
|
564
|
+
* - When this node holds an authority seed service, it deletes the row
|
|
565
|
+
* (`deleteDeviceToken` is authority-gated and accepts any peerId), so the peer
|
|
566
|
+
* is not retried until it re-registers.
|
|
567
|
+
* - When this node is NOT an authority it cannot delete the row, so it only logs
|
|
568
|
+
* that a re-registration is needed. The fan-out's own in-memory dead-token set
|
|
569
|
+
* is what actually stops re-pushing to the dead token this process — see
|
|
570
|
+
* {@link PushFanoutService}. That set is acceptably lossy across restarts (a
|
|
571
|
+
* restart re-learns staleness on the next failed send).
|
|
572
|
+
*
|
|
573
|
+
* Best-effort: never throws to the (best-effort) fan-out caller.
|
|
88
574
|
*/
|
|
89
|
-
|
|
575
|
+
expireDeviceToken(peerId: string): Promise<void>;
|
|
90
576
|
private handleStrandAdded;
|
|
91
577
|
private handleStrandRemoved;
|
|
92
578
|
private cleanup;
|
|
93
579
|
private handleStrandIdle;
|
|
580
|
+
/**
|
|
581
|
+
* Hibernate a strand: release its strand-network resources via the strand
|
|
582
|
+
* manager (stop the libp2p node, close the StrandDatabase) and mark it
|
|
583
|
+
* `hibernating`. A quiesced strand holds no open strand-network connections,
|
|
584
|
+
* transports, or DB handles. No-ops if the strand is missing; if already
|
|
585
|
+
* quiesced (defensive), just marks status and emits.
|
|
586
|
+
*/
|
|
94
587
|
private handleStrandHibernate;
|
|
588
|
+
/**
|
|
589
|
+
* Wake a strand. If it was hibernating (quiesced — no libp2p node), re-resolve
|
|
590
|
+
* the cohort discovery seed and mode exactly as `launchStrand` does and rebuild
|
|
591
|
+
* its runtime via the strand manager. If it is still live (e.g. waking an idle
|
|
592
|
+
* strand, which retains its resources), just flip the status. Overlapping wake
|
|
593
|
+
* triggers are coalesced upstream by `HibernationManager`, so this runs once
|
|
594
|
+
* per wake; `resumeStrand` is itself idempotent as a backstop.
|
|
595
|
+
*/
|
|
95
596
|
private handleStrandWake;
|
|
597
|
+
/**
|
|
598
|
+
* Rebuild a quiesced strand's runtime, re-resolving the volatile cohort inputs
|
|
599
|
+
* first: the discovery seed may have grown and cohort membership may have
|
|
600
|
+
* shifted the mode `bootstrap → networked` since the strand last ran. Shared by
|
|
601
|
+
* the wake (`handleStrandWake`) and check-in (`handleStrandCheckIn`) paths so
|
|
602
|
+
* both apply the same fresh seed/mode resolution. `resumeStrand` is idempotent
|
|
603
|
+
* (returns the live instance unchanged) as a backstop against double-resume.
|
|
604
|
+
*/
|
|
605
|
+
private resumeStrandRuntime;
|
|
606
|
+
/**
|
|
607
|
+
* Real cohort check-in for a hibernating strand (the `onCheckIn` callback).
|
|
608
|
+
*
|
|
609
|
+
* Optimystic syncs pull-on-read, not on connect, and exposes no cheap
|
|
610
|
+
* repo-level "pull pending" hook (`IRepo` is get/pend/commit/cancel only —
|
|
611
|
+
* see the review handoff). So "query the cohort for pending activity" is
|
|
612
|
+
* realized as a resume → bounded window → re-hibernate-if-idle cycle that
|
|
613
|
+
* reuses the existing quiesce/resume primitives rather than a bespoke probe:
|
|
614
|
+
*
|
|
615
|
+
* 1. Resume the strand (rebuild node + db, re-resolve cohort seed/mode) so
|
|
616
|
+
* its strand network can reach cohort peers — exactly as a wake does.
|
|
617
|
+
* 2. Hold it resumed for a bounded window, during which the app may drive
|
|
618
|
+
* reads (pull-on-read) and record activity.
|
|
619
|
+
* 3. If activity was recorded during the window, leave the strand `active`
|
|
620
|
+
* (the idle/hibernate timers + backoff reset take over). Otherwise
|
|
621
|
+
* quiesce again and leave it `hibernating`, so `HibernationManager`
|
|
622
|
+
* schedules the next, longer-delayed check-in.
|
|
623
|
+
*
|
|
624
|
+
* No-ops unless the strand is currently `hibernating` — a concurrent wake may
|
|
625
|
+
* have already resumed it.
|
|
626
|
+
*/
|
|
627
|
+
private handleStrandCheckIn;
|
|
628
|
+
/**
|
|
629
|
+
* Window-then-decide for a just-resumed strand, shared by the check-in timer
|
|
630
|
+
* path ({@link handleStrandCheckIn}) and the on-demand {@link serviceWake}:
|
|
631
|
+
*
|
|
632
|
+
* 1. Capture the post-resume activity marker. `recordActivity` assigns a
|
|
633
|
+
* FRESH `Date`, so a changed reference after the window means real
|
|
634
|
+
* activity landed during it — not millisecond-resolution noise.
|
|
635
|
+
* 2. Hold the strand live for `windowMs` so its strand network reaches the
|
|
636
|
+
* cohort and the app can drive pull-on-read activity.
|
|
637
|
+
* 3. If activity landed, leave the strand `active` (return `true`); otherwise
|
|
638
|
+
* quiesce and mark it `hibernating` again (return `false`).
|
|
639
|
+
*
|
|
640
|
+
* @returns whether activity was observed during the window (strand left active).
|
|
641
|
+
*/
|
|
642
|
+
private runWakeWindow;
|
|
643
|
+
/**
|
|
644
|
+
* Hold a just-resumed strand live for `windowMs` (default
|
|
645
|
+
* {@link DEFAULT_CHECKIN_WINDOW_MS} is applied by callers). A non-positive
|
|
646
|
+
* window resolves immediately. The pending timer is tracked in
|
|
647
|
+
* {@link windowWaiters} so {@link cleanup} can both clear it and resolve the
|
|
648
|
+
* promise on teardown — a `stop()` during an in-flight window must neither fire
|
|
649
|
+
* the timer afterward nor hang the awaiting check-in/serviceWake. Extracted as
|
|
650
|
+
* its own method so tests can stub the wait (and inject activity during it).
|
|
651
|
+
*/
|
|
652
|
+
private holdWakeWindow;
|
|
653
|
+
/**
|
|
654
|
+
* Clear every in-flight wake window: cancel its timer and resolve its promise
|
|
655
|
+
* so any awaiting check-in/serviceWake completes promptly rather than hanging
|
|
656
|
+
* past teardown. Called from {@link cleanup}.
|
|
657
|
+
*/
|
|
658
|
+
private clearWindowWaiters;
|
|
96
659
|
/**
|
|
97
660
|
* Add a strand with its sApp configuration.
|
|
98
661
|
* The hosting application must provide the sApp schema when creating a strand.
|
|
99
662
|
*/
|
|
100
663
|
addStrand(config: StrandConfig): Promise<StrandInstance>;
|
|
664
|
+
/**
|
|
665
|
+
* Publish a strand row to the shared control database under this node's own
|
|
666
|
+
* authority identity, so other cadre members discover it via control-network
|
|
667
|
+
* sync (their {@link StrandWatcher} fires `strand:discovered`).
|
|
668
|
+
*
|
|
669
|
+
* This is the authority-signed `Strand` INSERT that {@link addStrand}
|
|
670
|
+
* deliberately omits: `addStrand` only starts the LOCAL strand instance,
|
|
671
|
+
* whereas publishing makes the strand visible cadre-wide. A typical creator
|
|
672
|
+
* does both (start locally + publish); a discovering peer only does
|
|
673
|
+
* `addStrand` (the row already exists).
|
|
674
|
+
*
|
|
675
|
+
* The insert is signed with the ed25519 key behind this node's PeerId — which
|
|
676
|
+
* {@link authorityKeyFromLibp2p} also exposes as the node's authority keypair,
|
|
677
|
+
* so peer identity and authority key are one and the same. That key must be
|
|
678
|
+
* enrolled in `AuthorityKey` (e.g. via {@link ControlDatabase.ensureAuthorityKey}
|
|
679
|
+
* at genesis) or the schema's `Strand.Authorized` constraint rejects the write.
|
|
680
|
+
* Failing loudly here is intentional: a silently-unpublished strand would run
|
|
681
|
+
* as a local-only island that no peer could ever discover or join.
|
|
682
|
+
*
|
|
683
|
+
* @param strandId - Unique strand identifier (typically the same id passed to
|
|
684
|
+
* {@link addStrand}).
|
|
685
|
+
* @param type - `'o'` for open (default) or `'c'` for closed.
|
|
686
|
+
* @param memberPrivateKey - Optional membership key for a closed strand.
|
|
687
|
+
* @throws if the node is not started, exposes no authority signing key, or the
|
|
688
|
+
* control DB rejects the (unauthorized) insert.
|
|
689
|
+
*/
|
|
690
|
+
publishStrand(strandId: string, type?: 'o' | 'c', memberPrivateKey?: string): Promise<void>;
|
|
691
|
+
/**
|
|
692
|
+
* Publish an authority-signed `FormationInvite` (open-invitation token) to the
|
|
693
|
+
* shared control database, so a later {@link formStrand} redemption can be
|
|
694
|
+
* validated against it (the consent branch of `Strand.Authorized`).
|
|
695
|
+
*
|
|
696
|
+
* Counterpart to {@link createOpenInvitation}, which only mints the
|
|
697
|
+
* out-of-band {@link OpenInvitation} envelope: persisting the matching
|
|
698
|
+
* `FormationInvite` row is what makes the token *redeemable* — the host's
|
|
699
|
+
* {@link ControlFormationUsageRecorder} answers `isTokenValid`/`isTokenUsed`
|
|
700
|
+
* from this row. A host minting a closed-strand invite does both (mint +
|
|
701
|
+
* publish), exactly as the integration harness's `createInvitation` does.
|
|
702
|
+
*
|
|
703
|
+
* Signs with the same self-authority key as {@link publishStrand} (the ed25519
|
|
704
|
+
* key behind this node's PeerId, which must be an enrolled `AuthorityKey`).
|
|
705
|
+
* Throws loudly if the node isn't started or exposes no signing key.
|
|
706
|
+
*
|
|
707
|
+
* @param token - Invitation token (the `FormationInvite` primary key); use the
|
|
708
|
+
* `token` of the {@link OpenInvitation} from {@link createOpenInvitation}.
|
|
709
|
+
* @param sAppId - The sApp a redeemed strand will use.
|
|
710
|
+
* @param options - Optional `expiresAtMs` (epoch ms), `totalUses`, `validationUrl`,
|
|
711
|
+
* `strandId` (bind a closed/pre-existing host strand for provision-then-record).
|
|
712
|
+
*/
|
|
713
|
+
publishFormationInvite(token: string, sAppId: string, options?: {
|
|
714
|
+
expiresAtMs?: number;
|
|
715
|
+
totalUses?: number;
|
|
716
|
+
validationUrl?: string;
|
|
717
|
+
strandId?: string;
|
|
718
|
+
}): Promise<void>;
|
|
719
|
+
/**
|
|
720
|
+
* Shared strand launch path for both the explicit (`addStrand`) and the
|
|
721
|
+
* control-discovered (`handleStrandAdded`) entry points. Resolves the cohort
|
|
722
|
+
* seed, selects the mode, starts the strand, and registers it with the
|
|
723
|
+
* hibernation manager before emitting `strand:started`.
|
|
724
|
+
*/
|
|
725
|
+
private launchStrand;
|
|
726
|
+
/**
|
|
727
|
+
* Resolve a strand's discovery seed. Membership (and thus mode) comes from the
|
|
728
|
+
* control network's CadrePeer rows; the **strand-network** bootstrap addresses
|
|
729
|
+
* are resolved on demand over the control mesh via the strand-addr RPC —
|
|
730
|
+
* deliberately NOT from `CadrePeer.Multiaddr`, which carries *control*
|
|
731
|
+
* addresses that must not seed the strand mesh.
|
|
732
|
+
*
|
|
733
|
+
* Only siblings we already hold an open control connection to are RPC'd: they
|
|
734
|
+
* are the ones that can answer right now, and dialing them by peerId reuses the
|
|
735
|
+
* live connection. When no connected sibling yet runs the strand the seed is
|
|
736
|
+
* empty (`[]`) — mode still follows membership, and the empty seed self-heals
|
|
737
|
+
* on the next resume / check-in pass. Returns an empty seed when the control DB
|
|
738
|
+
* or node is absent (not yet started / torn down).
|
|
739
|
+
*/
|
|
740
|
+
private resolveCohortSeed;
|
|
741
|
+
/**
|
|
742
|
+
* The local strand instance's dialable strand-network multiaddrs for the
|
|
743
|
+
* strand-addr RPC, ordered signaling-first (reusing the control node's
|
|
744
|
+
* {@link orderSignalingFirst}). Returns `[]` when the strand is not running
|
|
745
|
+
* locally or has no live libp2p node (hibernating / quiescing / never
|
|
746
|
+
* participated) — a node only answers for a strand it is actively meshing,
|
|
747
|
+
* regardless of the strand's mode. A `bootstrap`-mode first node still has a
|
|
748
|
+
* live node, so it answers and a later sibling can dial in.
|
|
749
|
+
*/
|
|
750
|
+
private getStrandMultiaddrs;
|
|
101
751
|
/**
|
|
102
752
|
* Remove a strand
|
|
103
753
|
*/
|
|
104
754
|
removeStrand(strandId: string): Promise<void>;
|
|
105
755
|
/**
|
|
106
|
-
* Record activity on a strand (resets hibernation timer)
|
|
756
|
+
* Record activity on a strand (resets hibernation timer).
|
|
757
|
+
*
|
|
758
|
+
* Also drives the server push-wake fan-out: whatever already drives activity on
|
|
759
|
+
* this node's strand (its relay/app layer doing pull-on-read) additionally wakes
|
|
760
|
+
* hibernating mobile peers — the same imperative seam local-wake uses, with no
|
|
761
|
+
* new contract. No-op for the fan-out when push is not configured.
|
|
107
762
|
*/
|
|
108
763
|
recordStrandActivity(strandId: string): void;
|
|
764
|
+
/**
|
|
765
|
+
* Explicit fan-out trigger: an always-on host/relay/sApp calls this when it
|
|
766
|
+
* observes activity for a strand this node participates in, to wake hibernating
|
|
767
|
+
* mobile members over a direct control-network dial (falling back to FCM/APNs
|
|
768
|
+
* for suspended phones). This is the supported, honest v1 trigger — Optimystic
|
|
769
|
+
* exposes no passive repo-level "new transaction" hook to drive it automatically
|
|
770
|
+
* (see the deferred passive-detector follow-up). No-op when push is not
|
|
771
|
+
* configured; best-effort (never throws — the check-in wake is the backstop).
|
|
772
|
+
*
|
|
773
|
+
* @param strandId - the strand that saw activity.
|
|
774
|
+
* @param reason - free-form cause hint carried in the wake (default `activity`).
|
|
775
|
+
*/
|
|
776
|
+
notifyStrandActivity(strandId: string, reason?: string): void;
|
|
109
777
|
/**
|
|
110
778
|
* Force wake a hibernating strand
|
|
111
779
|
*/
|
|
112
780
|
wakeStrand(strandId: string): Promise<void>;
|
|
781
|
+
/**
|
|
782
|
+
* Force a single strand to hibernate immediately, bypassing the idle/hibernate
|
|
783
|
+
* timers — the background-entry path. No-op if the strand is realtime
|
|
784
|
+
* (never-hibernate latency hint), already hibernating, or unknown.
|
|
785
|
+
*
|
|
786
|
+
* Routes through {@link HibernationManager.forceHibernate}, which cancels the
|
|
787
|
+
* strand's pending idle/hibernate (and check-in) timers — so a stale timer
|
|
788
|
+
* can't re-fire on or resurrect the strand — then runs the same `onHibernate`
|
|
789
|
+
* path as the timer (`quiesceStrand` + `status='hibernating'` +
|
|
790
|
+
* `strand:hibernating`). Unlike the timer path it does NOT re-arm check-ins:
|
|
791
|
+
* the strand stays down until the caller drives a wake (e.g. {@link serviceWake}).
|
|
792
|
+
*/
|
|
793
|
+
hibernateStrand(strandId: string): Promise<void>;
|
|
794
|
+
/**
|
|
795
|
+
* Force-hibernate every tracked strand whose latency hint is not realtime,
|
|
796
|
+
* tolerating per-strand failure (one strand failing to quiesce never aborts
|
|
797
|
+
* the others). Realtime strands are left running — the caller keeps the control
|
|
798
|
+
* connection and realtime strands alive for as long as the OS permits.
|
|
799
|
+
*
|
|
800
|
+
* @returns the strandIds actually hibernated (now in `hibernating` status);
|
|
801
|
+
* realtime strands are excluded.
|
|
802
|
+
*/
|
|
803
|
+
hibernateAll(): Promise<string[]>;
|
|
804
|
+
/**
|
|
805
|
+
* On-demand equivalent of a check-in cycle, for a push-delivered wake on
|
|
806
|
+
* mobile: resume the strand, hold it live for `windowMs` so its strand network
|
|
807
|
+
* reaches the cohort and the app can pull pending activity, then re-hibernate
|
|
808
|
+
* if no activity was recorded (else leave it active).
|
|
809
|
+
*
|
|
810
|
+
* Idempotent / coalesced two ways: concurrent `serviceWake`s for the same
|
|
811
|
+
* strand share one in-flight operation ({@link serviceWakePromises}), and the
|
|
812
|
+
* underlying resume coalesces with a racing push-wake via
|
|
813
|
+
* {@link HibernationManager}'s wake coalescing — one runtime build, one window,
|
|
814
|
+
* one re-hibernate decision. Returns `{ serviced: false }` (never throws) when
|
|
815
|
+
* the node is not running or the strand is unknown, and surfaces a resume
|
|
816
|
+
* failure as `{ serviced: true, hadActivity: false }` after re-hibernating.
|
|
817
|
+
*
|
|
818
|
+
* @param strandId - the strand a push said has pending activity.
|
|
819
|
+
* @param opts.windowMs - override the live-window duration (defaults to the
|
|
820
|
+
* configured `checkInWindowMs` / {@link DEFAULT_CHECKIN_WINDOW_MS}).
|
|
821
|
+
*/
|
|
822
|
+
serviceWake(strandId: string, opts?: {
|
|
823
|
+
windowMs?: number;
|
|
824
|
+
}): Promise<ServiceWakeResult>;
|
|
825
|
+
/** Body of {@link serviceWake}; serialised per-strand by its coalescing guard. */
|
|
826
|
+
private runServiceWake;
|
|
113
827
|
/**
|
|
114
828
|
* Get the control network node (for advanced use)
|
|
115
829
|
*/
|
|
@@ -133,6 +847,44 @@ export declare class CadreNode implements SAppIdLookup {
|
|
|
133
847
|
* @param authorityPrivateKey - The authority's private key (base64url encoded)
|
|
134
848
|
*/
|
|
135
849
|
initializeSeedBootstrap(authorityPrivateKey: string): void;
|
|
850
|
+
/**
|
|
851
|
+
* Push the multiaddrs that future invites should advertise. Pass `null` to
|
|
852
|
+
* revert to the libp2p-reported addresses (the default). The host calls this
|
|
853
|
+
* at spawn and on every NAT change.
|
|
854
|
+
*/
|
|
855
|
+
setInviteAddresses(addresses: string[] | null): void;
|
|
856
|
+
/**
|
|
857
|
+
* Resolve the addresses to embed in invites. Prefers pushed addresses, then
|
|
858
|
+
* any config-supplied resolver, then the libp2p-observed multiaddrs.
|
|
859
|
+
*/
|
|
860
|
+
private resolveInviteAddresses;
|
|
861
|
+
/**
|
|
862
|
+
* Enumerate the cadre's `CadrePeer` membership.
|
|
863
|
+
*/
|
|
864
|
+
listMembers(): Promise<Array<{
|
|
865
|
+
peerId: string;
|
|
866
|
+
multiaddr: string | null;
|
|
867
|
+
}>>;
|
|
868
|
+
/**
|
|
869
|
+
* Probe whether a given peer is a `CadrePeer` member.
|
|
870
|
+
*/
|
|
871
|
+
isMember(peerId: string): Promise<boolean>;
|
|
872
|
+
/**
|
|
873
|
+
* Push-wake a hibernating cadre peer over the control network.
|
|
874
|
+
*
|
|
875
|
+
* Resolves the target's signed control-network address from its `CadrePeer`
|
|
876
|
+
* record (via {@link resolvePeerAddrs}, signaling/relay first — so a NAT'd peer
|
|
877
|
+
* is reachable through its circuit-relay address), dials `WAKE_PROTOCOL`, sends
|
|
878
|
+
* the {@link WakeRequest}, and returns the peer's {@link WakeAck}. The receiver
|
|
879
|
+
* gates the request on cadre membership and only resumes a strand it already
|
|
880
|
+
* participates in.
|
|
881
|
+
*
|
|
882
|
+
* @param targetPeerId - The hibernating cadre peer to wake.
|
|
883
|
+
* @param strandId - The strand the caller knows has pending activity.
|
|
884
|
+
* @param reason - Optional cause hint, e.g. `"activity"` or `"manual"`.
|
|
885
|
+
* @throws if the node is not started or the target has no dialable address.
|
|
886
|
+
*/
|
|
887
|
+
pushWake(targetPeerId: string, strandId: string, reason?: string): Promise<WakeAck>;
|
|
136
888
|
/**
|
|
137
889
|
* Enable the seed listener for receiving seeds via the /sereus/seed/1.0.0 protocol.
|
|
138
890
|
* This is for drone nodes that need to receive seeds without being an authority.
|
|
@@ -165,9 +917,16 @@ export declare class CadreNode implements SAppIdLookup {
|
|
|
165
917
|
createSeed(): Promise<ControlNetworkSeed>;
|
|
166
918
|
/**
|
|
167
919
|
* Apply a seed to populate the peer cache and enable connections.
|
|
168
|
-
*
|
|
169
|
-
|
|
170
|
-
|
|
920
|
+
*
|
|
921
|
+
* Validates the seed signature, then evaluates a trust anchor for the signer
|
|
922
|
+
* key (see `SeedTrustPolicy`). An enrollment caller can pass a per-seed
|
|
923
|
+
* `trustPolicy` override — e.g. a `pinnedKeyTrustPolicy` built from a
|
|
924
|
+
* `CadreInvite.authorityKeys` — so a cold-start node can accept its first
|
|
925
|
+
* seed without reconfiguring the service.
|
|
926
|
+
*/
|
|
927
|
+
applySeed(seed: ControlNetworkSeed, options?: {
|
|
928
|
+
trustPolicy?: SeedTrustPolicy;
|
|
929
|
+
}): Promise<ApplySeedResult>;
|
|
171
930
|
/**
|
|
172
931
|
* Deliver a seed directly to a peer via the /sereus/seed/1.0.0 protocol.
|
|
173
932
|
*/
|