@serfab/cadre-core 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/README.md +255 -253
  2. package/dist/bootstrap-peer-store-file.d.ts +13 -0
  3. package/dist/bootstrap-peer-store-file.js +42 -0
  4. package/dist/bootstrap-peer-store-file.js.map +1 -0
  5. package/dist/bootstrap-peer-store.d.ts +73 -0
  6. package/dist/bootstrap-peer-store.js +128 -0
  7. package/dist/bootstrap-peer-store.js.map +1 -0
  8. package/dist/cadre-node.d.ts +1121 -81
  9. package/dist/cadre-node.js +2276 -262
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/control-authorization.d.ts +93 -0
  12. package/dist/control-authorization.js +57 -0
  13. package/dist/control-authorization.js.map +1 -0
  14. package/dist/control-cohort.d.ts +26 -0
  15. package/dist/control-cohort.js +26 -0
  16. package/dist/control-cohort.js.map +1 -1
  17. package/dist/control-database.d.ts +959 -54
  18. package/dist/control-database.js +1421 -148
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +90 -10
  21. package/dist/control-formation-recorder.js +130 -14
  22. package/dist/control-formation-recorder.js.map +1 -1
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +651 -72
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-stream.d.ts +38 -4
  27. package/dist/control-stream.js +70 -4
  28. package/dist/control-stream.js.map +1 -1
  29. package/dist/control-write-retry.d.ts +161 -0
  30. package/dist/control-write-retry.js +412 -0
  31. package/dist/control-write-retry.js.map +1 -0
  32. package/dist/delegate-admission.d.ts +134 -0
  33. package/dist/delegate-admission.js +244 -0
  34. package/dist/delegate-admission.js.map +1 -0
  35. package/dist/device-token.d.ts +11 -11
  36. package/dist/device-token.js +14 -13
  37. package/dist/device-token.js.map +1 -1
  38. package/dist/ed25519-key.d.ts +26 -0
  39. package/dist/ed25519-key.js +56 -1
  40. package/dist/ed25519-key.js.map +1 -1
  41. package/dist/file-durable-slot.d.ts +20 -0
  42. package/dist/file-durable-slot.js +53 -0
  43. package/dist/file-durable-slot.js.map +1 -0
  44. package/dist/formation-approval.d.ts +157 -0
  45. package/dist/formation-approval.js +375 -0
  46. package/dist/formation-approval.js.map +1 -0
  47. package/dist/fs-atomic.d.ts +38 -0
  48. package/dist/fs-atomic.js +97 -0
  49. package/dist/fs-atomic.js.map +1 -0
  50. package/dist/identity-key.d.ts +49 -0
  51. package/dist/identity-key.js +81 -0
  52. package/dist/identity-key.js.map +1 -0
  53. package/dist/index.d.ts +17 -7
  54. package/dist/index.js +40 -6
  55. package/dist/index.js.map +1 -1
  56. package/dist/key-store-file.d.ts +2 -24
  57. package/dist/key-store-file.js +10 -77
  58. package/dist/key-store-file.js.map +1 -1
  59. package/dist/membership-connection-gater.d.ts +146 -0
  60. package/dist/membership-connection-gater.js +180 -0
  61. package/dist/membership-connection-gater.js.map +1 -0
  62. package/dist/node-local-snapshot.d.ts +109 -0
  63. package/dist/node-local-snapshot.js +182 -0
  64. package/dist/node-local-snapshot.js.map +1 -0
  65. package/dist/peer-addr-book.d.ts +92 -0
  66. package/dist/peer-addr-book.js +220 -0
  67. package/dist/peer-addr-book.js.map +1 -0
  68. package/dist/peer-authorization.d.ts +135 -18
  69. package/dist/peer-authorization.js +152 -21
  70. package/dist/peer-authorization.js.map +1 -1
  71. package/dist/peer-record.d.ts +21 -8
  72. package/dist/peer-record.js +26 -10
  73. package/dist/peer-record.js.map +1 -1
  74. package/dist/relay-addrs.d.ts +45 -0
  75. package/dist/relay-addrs.js +103 -0
  76. package/dist/relay-addrs.js.map +1 -0
  77. package/dist/relay-reservation.d.ts +266 -0
  78. package/dist/relay-reservation.js +613 -0
  79. package/dist/relay-reservation.js.map +1 -0
  80. package/dist/seed-bootstrap.d.ts +228 -56
  81. package/dist/seed-bootstrap.js +340 -198
  82. package/dist/seed-bootstrap.js.map +1 -1
  83. package/dist/seed-trust-policy.d.ts +47 -21
  84. package/dist/seed-trust-policy.js +24 -15
  85. package/dist/seed-trust-policy.js.map +1 -1
  86. package/dist/strand-addr-protocol.d.ts +42 -13
  87. package/dist/strand-addr-protocol.js +58 -52
  88. package/dist/strand-addr-protocol.js.map +1 -1
  89. package/dist/strand-backfill.d.ts +109 -0
  90. package/dist/strand-backfill.js +279 -0
  91. package/dist/strand-backfill.js.map +1 -0
  92. package/dist/strand-cohort.d.ts +4 -37
  93. package/dist/strand-cohort.js +4 -15
  94. package/dist/strand-cohort.js.map +1 -1
  95. package/dist/strand-database.d.ts +11 -16
  96. package/dist/strand-database.js +19 -7
  97. package/dist/strand-database.js.map +1 -1
  98. package/dist/strand-formation-manager.d.ts +36 -7
  99. package/dist/strand-formation-manager.js +115 -15
  100. package/dist/strand-formation-manager.js.map +1 -1
  101. package/dist/strand-formation-protocol.d.ts +103 -4
  102. package/dist/strand-formation-protocol.js +232 -4
  103. package/dist/strand-formation-protocol.js.map +1 -1
  104. package/dist/strand-instance-manager.d.ts +88 -19
  105. package/dist/strand-instance-manager.js +178 -34
  106. package/dist/strand-instance-manager.js.map +1 -1
  107. package/dist/strand-member-registry.d.ts +5 -5
  108. package/dist/strand-member-registry.js +18 -10
  109. package/dist/strand-member-registry.js.map +1 -1
  110. package/dist/strand-membership-writer.d.ts +484 -88
  111. package/dist/strand-membership-writer.js +751 -128
  112. package/dist/strand-membership-writer.js.map +1 -1
  113. package/dist/strand-solicitation.d.ts +99 -33
  114. package/dist/strand-solicitation.js +100 -52
  115. package/dist/strand-solicitation.js.map +1 -1
  116. package/dist/strand-transport-key.d.ts +40 -0
  117. package/dist/strand-transport-key.js +56 -0
  118. package/dist/strand-transport-key.js.map +1 -0
  119. package/dist/strand-wake-protocol.d.ts +9 -7
  120. package/dist/strand-wake-protocol.js +22 -46
  121. package/dist/strand-wake-protocol.js.map +1 -1
  122. package/dist/strand-watcher.d.ts +17 -2
  123. package/dist/strand-watcher.js +47 -3
  124. package/dist/strand-watcher.js.map +1 -1
  125. package/dist/trusted-owner-store-file.d.ts +12 -0
  126. package/dist/trusted-owner-store-file.js +39 -0
  127. package/dist/trusted-owner-store-file.js.map +1 -0
  128. package/dist/trusted-owner-store.d.ts +64 -0
  129. package/dist/trusted-owner-store.js +126 -0
  130. package/dist/trusted-owner-store.js.map +1 -0
  131. package/dist/types.d.ts +307 -44
  132. package/dist/types.js +13 -0
  133. package/dist/types.js.map +1 -1
  134. package/package.json +20 -8
  135. package/src/arachnode-stub.ts +159 -159
  136. package/src/bootstrap-peer-store-file.ts +44 -0
  137. package/src/bootstrap-peer-store.ts +172 -0
  138. package/src/cadre-node.ts +5158 -2981
  139. package/src/canonical-json.ts +30 -30
  140. package/src/control-authorization.ts +114 -0
  141. package/src/control-cohort.ts +130 -103
  142. package/src/control-database.ts +2406 -948
  143. package/src/control-formation-recorder.ts +305 -151
  144. package/src/control-schema.ts +651 -72
  145. package/src/control-stream.ts +205 -128
  146. package/src/control-write-retry.ts +483 -0
  147. package/src/delegate-admission.ts +302 -0
  148. package/src/device-token.ts +94 -89
  149. package/src/diagnostics/connection-path.ts +277 -277
  150. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  151. package/src/ed25519-key.ts +66 -1
  152. package/src/enrollment.ts +199 -199
  153. package/src/file-durable-slot.ts +61 -0
  154. package/src/formation-approval.ts +604 -0
  155. package/src/fs-atomic.ts +107 -0
  156. package/src/hibernation-manager.ts +437 -437
  157. package/src/identity-key.ts +109 -0
  158. package/src/index.ts +137 -5
  159. package/src/key-store-file.ts +132 -203
  160. package/src/key-store.ts +99 -99
  161. package/src/membership-connection-gater.ts +204 -0
  162. package/src/node-local-snapshot.ts +260 -0
  163. package/src/peer-addr-book.ts +250 -0
  164. package/src/peer-authorization.ts +259 -81
  165. package/src/peer-record.ts +164 -146
  166. package/src/push-credentials.ts +84 -84
  167. package/src/push-node.ts +64 -64
  168. package/src/push-notifier-apns.ts +247 -247
  169. package/src/push-notifier-fcm.ts +220 -220
  170. package/src/push-notifier-shared.ts +28 -28
  171. package/src/push-notifier.ts +52 -52
  172. package/src/relay-addrs.ts +111 -0
  173. package/src/relay-reservation.ts +823 -0
  174. package/src/seed-bootstrap.ts +409 -209
  175. package/src/seed-trust-policy.ts +140 -107
  176. package/src/strand-addr-protocol.ts +441 -410
  177. package/src/strand-backfill.ts +366 -0
  178. package/src/strand-cohort.ts +38 -77
  179. package/src/strand-database.ts +202 -204
  180. package/src/strand-formation-manager.ts +491 -368
  181. package/src/strand-formation-protocol.ts +692 -391
  182. package/src/strand-instance-manager.ts +201 -46
  183. package/src/strand-member-key.ts +39 -39
  184. package/src/strand-member-registry.ts +182 -177
  185. package/src/strand-membership-writer.ts +938 -146
  186. package/src/strand-solicitation.ts +472 -407
  187. package/src/strand-transport-key.ts +58 -0
  188. package/src/strand-wake-payload.ts +32 -32
  189. package/src/strand-wake-protocol.ts +314 -331
  190. package/src/strand-watcher.ts +314 -251
  191. package/src/trusted-owner-store-file.ts +41 -0
  192. package/src/trusted-owner-store.ts +171 -0
  193. package/src/types.ts +1309 -1032
@@ -1,331 +1,314 @@
1
- /**
2
- * Control-network push-wake transport.
3
- *
4
- * Lets a same-cadre peer — typically an always-on server that participates in a
5
- * strand and sees new activity — signal a hibernating cadre peer to bring that
6
- * strand online, pull pending activity, and re-hibernate. Push-wake travels the
7
- * **control network** (the per-party network connecting this party's own cadre
8
- * nodes), which is the only network a hibernating peer keeps connected.
9
- *
10
- * Modeled directly on `seed-bootstrap.ts`: a dedicated libp2p protocol id,
11
- * 4-byte big-endian length-prefixed JSON frames, `node.handle` for the receiver,
12
- * `node.dialProtocol` for the sender, and the shared `ControlStream` primitives
13
- * from `control-stream.ts`. The exchange is a single request → single ack on one
14
- * stream (like seed delivery), so each side reads to EOF (under a read timeout)
15
- * and decodes one frame via the shared {@link decodeLengthPrefixedFrame} guard.
16
- *
17
- * **Authorization (v1):** the control network already restricts membership —
18
- * only this party's cadre peers connect (schema-gated `CadrePeer`). A wake is
19
- * low-risk: it only causes the receiver to spend resources coming online for a
20
- * strand it already participates in. So the receiver verifies the remote peer is
21
- * a `CadrePeer` member (via the injected `isMember` gate) and requires no
22
- * signature beyond control-network membership. A richer per-request signature is
23
- * deliberately out of scope for v1.
24
- */
25
-
26
- import debug from 'debug';
27
- import type { Libp2p, Connection } from '@libp2p/interface';
28
- import type { Multiaddr } from '@multiformats/multiaddr';
29
- import type { StrandInstance, WakeRequest, WakeAck } from './types.js';
30
- import { decodeLengthPrefixedFrame } from './seed-bootstrap.js';
31
- import { type ControlStream, writeFrame, withTimeout, readStreamToEnd } from './control-stream.js';
32
-
33
- const log = debug('sereus:cadre:strand-wake');
34
-
35
- /** Protocol id for control-network push-wake (parallel to `/sereus/seed/1.0.0`). */
36
- export const WAKE_PROTOCOL = '/sereus/strand-wake/1.0.0';
37
-
38
- /**
39
- * Maximum wake frame size. Wake messages are tiny (a strand id + short reason),
40
- * so this is a defensive cap — far below the 1MB seed ceiling — that bounds the
41
- * bytes a peer can make the receiver buffer per stream.
42
- */
43
- const MAX_WAKE_SIZE = 64 * 1024;
44
-
45
- /** Default time to wait for the ack before abandoning a wake dial (ms). */
46
- const DEFAULT_WAKE_TIMEOUT_MS = 10_000;
47
-
48
- /** Default time the receiver waits for an inbound wake frame before aborting (ms). */
49
- const DEFAULT_WAKE_READ_TIMEOUT_MS = 10_000;
50
-
51
- /** Default cap on concurrent inbound wake streams a single peer can pin open. */
52
- const DEFAULT_MAX_CONCURRENT_WAKES = 100;
53
-
54
- /**
55
- * Read a libp2p stream to EOF and decode the single length-prefixed JSON frame
56
- * it carries. Bounded by `timeoutMs` (a never-half-closing peer is aborted, not
57
- * awaited forever) and capped at {@link MAX_WAKE_SIZE}, reusing the shared
58
- * {@link decodeLengthPrefixedFrame} guard for the prefix/length checks.
59
- */
60
- async function readFrame<T>(stream: ControlStream, timeoutMs: number): Promise<T> {
61
- const data = await readStreamToEnd(stream, { maxBytes: MAX_WAKE_SIZE, timeoutMs, label: 'Wake' });
62
- const body = decodeLengthPrefixedFrame(data, MAX_WAKE_SIZE);
63
- return JSON.parse(new TextDecoder().decode(body)) as T;
64
- }
65
-
66
- /**
67
- * Dependencies the {@link StrandWakeService} receiver needs from its host
68
- * (`CadreNode`), injected so the service is testable without a full node.
69
- */
70
- export interface StrandWakeServiceOptions {
71
- /** Membership gate: is the remote peer a `CadrePeer` member of this cadre? */
72
- isMember(remotePeerId: string): Promise<boolean>;
73
- /** Look up a local strand instance by id (undefined if not participated in). */
74
- getStrand(strandId: string): StrandInstance | undefined;
75
- /**
76
- * Trigger the local wake path for a hibernating/idle strand. Wired to
77
- * `CadreNode.wakeStrand` (→ `HibernationManager` → `resumeStrand`), whose
78
- * resume coalescing prevents a push-wake racing a concurrent check-in.
79
- */
80
- wake(strandId: string): Promise<void>;
81
- /**
82
- * Time to wait for the inbound wake frame before aborting the read (ms).
83
- * Defaults to {@link DEFAULT_WAKE_READ_TIMEOUT_MS}. Bounds a buggy/compromised
84
- * own-cadre node that opens a stream and never half-closes its write end.
85
- */
86
- readTimeoutMs?: number;
87
- /**
88
- * Cap on concurrent inbound wake streams (defaults to
89
- * {@link DEFAULT_MAX_CONCURRENT_WAKES}). Over the cap, a non-accepting ack is
90
- * returned without invoking the wake path.
91
- */
92
- maxConcurrent?: number;
93
- }
94
-
95
- /**
96
- * Receiver side of the push-wake protocol. Registers a `WAKE_PROTOCOL` handler
97
- * on the control node and, for each inbound {@link WakeRequest}, gates on cadre
98
- * membership, then resumes the named strand if it is hibernating/idle and we
99
- * participate in it — replying with a {@link WakeAck}.
100
- */
101
- export class StrandWakeService {
102
- private readonly options: StrandWakeServiceOptions;
103
- private readonly readTimeoutMs: number;
104
- private readonly maxConcurrent: number;
105
- private node: Libp2p | null = null;
106
- /** In-flight inbound wake streams, used to enforce {@link maxConcurrent}. */
107
- private activeStreams = 0;
108
-
109
- constructor(options: StrandWakeServiceOptions) {
110
- this.options = options;
111
- this.readTimeoutMs = options.readTimeoutMs ?? DEFAULT_WAKE_READ_TIMEOUT_MS;
112
- this.maxConcurrent = options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT_WAKES;
113
- }
114
-
115
- /** Number of in-flight inbound wake streams. */
116
- get activeCount(): number {
117
- return this.activeStreams;
118
- }
119
-
120
- /** Register the wake protocol handler on the control node. */
121
- initialize(node: Libp2p): void {
122
- this.node = node;
123
- // `runOnLimitedConnection: true` is REQUIRED for the relay path: a NAT'd
124
- // receiver is reached over a circuit-relay connection, which libp2p marks
125
- // "limited" (the relay caps its data/duration). Without this the receiver
126
- // would refuse the inbound wake stream on exactly the connection the
127
- // protocol is designed to use (see the relay note on `dialWake`).
128
- void node.handle(WAKE_PROTOCOL, async (rawStream: unknown, rawConnection: unknown) => {
129
- const remotePeerId = (rawConnection as Connection).remotePeer.toString();
130
- await this.handleStream(rawStream as ControlStream, remotePeerId);
131
- }, { runOnLimitedConnection: true });
132
- log('StrandWakeService registered handler: %s', WAKE_PROTOCOL);
133
- }
134
-
135
- /** Unregister the handler and release the node reference. */
136
- async shutdown(): Promise<void> {
137
- if (this.node) {
138
- await this.node.unhandle(WAKE_PROTOCOL);
139
- this.node = null;
140
- log('StrandWakeService shutdown');
141
- }
142
- }
143
-
144
- /**
145
- * Read the inbound request, decide + execute the wake, and write the ack.
146
- *
147
- * Three hardening layers, all reported as a non-accepting ack rather than a
148
- * dropped/hung stream: a concurrency cap (over {@link maxConcurrent}, reply
149
- * without touching the wake path), a read timeout (a peer that never
150
- * half-closes is aborted inside {@link readFrame}/`readStreamToEnd`), and the
151
- * existing malformed/oversized-frame guard.
152
- */
153
- private async handleStream(stream: ControlStream, remotePeerId: string): Promise<void> {
154
- log('Incoming wake request from: %s', remotePeerId);
155
-
156
- if (this.activeStreams >= this.maxConcurrent) {
157
- log('Rejecting wake from %s: %d concurrent streams at cap %d', remotePeerId, this.activeStreams, this.maxConcurrent);
158
- const ack: WakeAck = { accepted: false, reason: 'Too many concurrent wake requests' };
159
- try {
160
- writeFrame(stream, ack);
161
- } catch {
162
- // Ignore send errors on the reject path.
163
- }
164
- try {
165
- await stream.close();
166
- } catch {
167
- // Ignore close errors.
168
- }
169
- return;
170
- }
171
-
172
- this.activeStreams++;
173
- try {
174
- const request = await readFrame<WakeRequest>(stream, this.readTimeoutMs);
175
- const ack = await this.processWakeRequest(request, remotePeerId);
176
- writeFrame(stream, ack);
177
- } catch (err) {
178
- log('Error handling wake request from %s: %o', remotePeerId, err);
179
- const ack: WakeAck = {
180
- accepted: false,
181
- reason: err instanceof Error ? err.message : 'Unknown error',
182
- };
183
- try {
184
- writeFrame(stream, ack);
185
- } catch {
186
- // Ignore send errors on the error path.
187
- }
188
- } finally {
189
- this.activeStreams--;
190
- try {
191
- await stream.close();
192
- } catch {
193
- // Ignore close errors.
194
- }
195
- }
196
- }
197
-
198
- /**
199
- * Decide and execute the wake for a decoded request. Exposed (not private) so
200
- * the decision matrix can be unit-tested directly.
201
- *
202
- * - Non-member sender → rejected (`accepted: false`).
203
- * - Unknown / not-participated strand → rejected.
204
- * - Hibernating or idle strand → resumed via the wake path, then `accepted`.
205
- * - Already-live strand → no-op, `accepted` with current status.
206
- */
207
- async processWakeRequest(request: WakeRequest, remotePeerId: string): Promise<WakeAck> {
208
- // Control-network membership is the v1 authorization: only this party's
209
- // cadre peers may ask us to wake.
210
- if (!(await this.options.isMember(remotePeerId))) {
211
- log('Rejecting wake from non-member %s', remotePeerId);
212
- return { accepted: false, reason: 'Sender is not a cadre member' };
213
- }
214
-
215
- const instance = this.options.getStrand(request.strandId);
216
- if (!instance) {
217
- log('Rejecting wake for unknown/unparticipated strand %s', request.strandId);
218
- return { accepted: false, reason: 'Strand not found or not participated in' };
219
- }
220
-
221
- if (instance.status === 'hibernating' || instance.status === 'idle') {
222
- log('Waking strand %s on push from %s (reason=%s)', request.strandId, remotePeerId, request.reason ?? 'unspecified');
223
- await this.options.wake(request.strandId);
224
- } else {
225
- log('Strand %s already %s; push-wake is a no-op', request.strandId, instance.status);
226
- }
227
-
228
- // The wake path mutates the shared instance, so re-read its current status.
229
- return { accepted: true, status: instance.status };
230
- }
231
- }
232
-
233
- /** Options for {@link dialWake}. */
234
- export interface DialWakeOptions {
235
- /** Per-dial timeout in ms (default {@link DEFAULT_WAKE_TIMEOUT_MS}). */
236
- timeoutMs?: number;
237
- /** Override the protocol id (defaults to {@link WAKE_PROTOCOL}). */
238
- protocolId?: string;
239
- }
240
-
241
- /**
242
- * Sender side: dial a target's control-network address(es), send a
243
- * {@link WakeRequest} over `WAKE_PROTOCOL`, and return the peer's {@link WakeAck}.
244
- *
245
- * Tries each candidate address in order (signaling/relay first, as produced by
246
- * `CadreNode.resolvePeerAddrs`) until one dials, so a NAT'd peer is reachable via
247
- * its circuit-relay address. Throws if no address is dialable.
248
- */
249
- export async function dialWake(
250
- node: Libp2p,
251
- addrs: Multiaddr[],
252
- request: WakeRequest,
253
- options: DialWakeOptions = {}
254
- ): Promise<WakeAck> {
255
- if (addrs.length === 0) {
256
- throw new Error('No dialable address for wake target');
257
- }
258
- const protocolId = options.protocolId ?? WAKE_PROTOCOL;
259
- const timeoutMs = options.timeoutMs ?? DEFAULT_WAKE_TIMEOUT_MS;
260
-
261
- let lastError: Error | null = null;
262
- for (const addr of addrs) {
263
- // One controller per attempt: on timeout, `withTimeout`'s `onTimeout` aborts
264
- // it, which aborts the in-flight dialProtocol (via the dial `signal`) and the
265
- // live stream — so neither the connect nor the unbounded ack-read leaks.
266
- const controller = new AbortController();
267
- try {
268
- return await withTimeout(
269
- timeoutMs,
270
- `Wake dial ${addr.toString()}`,
271
- () => sendWake(node, addr, protocolId, request, timeoutMs, controller.signal),
272
- () => controller.abort(),
273
- );
274
- } catch (err) {
275
- lastError = err instanceof Error ? err : new Error(String(err));
276
- log('Wake dial to %s failed: %o', addr.toString(), err);
277
- }
278
- }
279
- throw lastError ?? new Error('Wake dial failed');
280
- }
281
-
282
- /**
283
- * Open one stream, send the request, half-close, and read the ack.
284
- *
285
- * `signal` is the per-attempt abort signal from {@link dialWake}: it is passed to
286
- * `dialProtocol` so a timeout during connect aborts the dial, and once the stream
287
- * is open an abort listener resets the live stream — releasing the otherwise
288
- * unbounded ack-read. `readFrame` still applies `timeoutMs` as a backstop for the
289
- * case where an abort does not propagate (e.g. a stream double whose `abort()` is
290
- * a no-op).
291
- */
292
- async function sendWake(
293
- node: Libp2p,
294
- addr: Multiaddr,
295
- protocolId: string,
296
- request: WakeRequest,
297
- timeoutMs: number,
298
- signal: AbortSignal,
299
- ): Promise<WakeAck> {
300
- // `runOnLimitedConnection: true`: the target may be reachable only over a
301
- // circuit-relay connection (the signaling-first addr), which libp2p marks
302
- // "limited". The wake exchange is a single tiny request→ack well within the
303
- // relay's data/duration cap, so opening it on the limited connection is safe
304
- // and is the whole point of dialing the relay address.
305
- const rawStream = await node.dialProtocol(addr, protocolId, { runOnLimitedConnection: true, signal });
306
- const stream = rawStream as unknown as ControlStream;
307
-
308
- const abortErr = new Error('Wake dial aborted by timeout');
309
- const onAbort = (): void => stream.abort(abortErr);
310
- // If the timeout already fired during connect, release the freshly-opened stream now.
311
- if (signal.aborted) {
312
- onAbort();
313
- throw abortErr;
314
- }
315
- signal.addEventListener('abort', onAbort, { once: true });
316
-
317
- try {
318
- writeFrame(stream, request);
319
- // close() half-closes the write end (EOF) while the read end stays open for
320
- // the ack — the same libp2p 3.x pattern as seed delivery.
321
- await stream.close();
322
- const ack = await readFrame<WakeAck>(stream, timeoutMs);
323
- log('Wake ack from %s: accepted=%s status=%s', addr.toString(), ack.accepted, ack.status ?? '-');
324
- return ack;
325
- } catch (err) {
326
- stream.abort(err instanceof Error ? err : new Error(String(err)));
327
- throw err;
328
- } finally {
329
- signal.removeEventListener('abort', onAbort);
330
- }
331
- }
1
+ /**
2
+ * Control-network push-wake transport.
3
+ *
4
+ * Lets a same-cadre peer — typically an always-on server that participates in a
5
+ * strand and sees new activity — signal a hibernating cadre peer to bring that
6
+ * strand online, pull pending activity, and re-hibernate. Push-wake travels the
7
+ * **control network** (the per-party network connecting this party's own cadre
8
+ * nodes), which is the only network a hibernating peer keeps connected.
9
+ *
10
+ * Modeled directly on `seed-bootstrap.ts`: a dedicated libp2p protocol id,
11
+ * 4-byte big-endian length-prefixed JSON frames, `node.handle` for the receiver,
12
+ * `node.dialProtocol` for the sender, and the shared `ControlStream` primitives
13
+ * from `control-stream.ts`. The exchange is a single request → single ack on one
14
+ * stream (like seed delivery), so each side reads to EOF (under a read timeout)
15
+ * and decodes one frame via the shared {@link decodeLengthPrefixedFrame} guard.
16
+ *
17
+ * **Authorization (v1):** a wake is low-risk — it only causes the receiver to
18
+ * spend resources coming online for a strand it already participates in — so the
19
+ * receiver carries no per-request signature and instead defers entirely to the
20
+ * injected `isMember` predicate. `CadreNode` injects its AUTHORIZED-membership
21
+ * predicate there (`isAuthorizedMember`: the sender's `CadrePeer` row must carry
22
+ * a voucher that verifies against an owner key in the receiver's node-local
23
+ * trusted-owner anchor), so a peer that merely published rows into the replicated
24
+ * control DB is refused. This module stays agnostic: it enforces whatever
25
+ * predicate it is given.
26
+ */
27
+
28
+ import debug from 'debug';
29
+ import type { Libp2p, Connection } from '@libp2p/interface';
30
+ import type { Multiaddr } from '@multiformats/multiaddr';
31
+ import type { StrandInstance, WakeRequest, WakeAck } from './types.js';
32
+ import { decodeLengthPrefixedFrame } from './seed-bootstrap.js';
33
+ import { type ControlStream, writeFrame, withDeadline, exchangeFrame, readStreamToEnd } from './control-stream.js';
34
+
35
+ const log = debug('sereus:cadre:strand-wake');
36
+
37
+ /** Protocol id for control-network push-wake (parallel to `/sereus/seed/1.0.0`). */
38
+ export const WAKE_PROTOCOL = '/sereus/strand-wake/1.0.0';
39
+
40
+ /**
41
+ * Maximum wake frame size. Wake messages are tiny (a strand id + short reason),
42
+ * so this is a defensive cap — far below the 1MB seed ceiling — that bounds the
43
+ * bytes a peer can make the receiver buffer per stream.
44
+ */
45
+ const MAX_WAKE_SIZE = 64 * 1024;
46
+
47
+ /** Default time to wait for the ack before abandoning a wake dial (ms). */
48
+ const DEFAULT_WAKE_TIMEOUT_MS = 10_000;
49
+
50
+ /** Default time the receiver waits for an inbound wake frame before aborting (ms). */
51
+ const DEFAULT_WAKE_READ_TIMEOUT_MS = 10_000;
52
+
53
+ /** Default cap on concurrent inbound wake streams a single peer can pin open. */
54
+ const DEFAULT_MAX_CONCURRENT_WAKES = 100;
55
+
56
+ /**
57
+ * Read a libp2p stream to EOF and decode the single length-prefixed JSON frame
58
+ * it carries. Bounded by `timeoutMs` (a never-half-closing peer is aborted, not
59
+ * awaited forever) and capped at {@link MAX_WAKE_SIZE}, reusing the shared
60
+ * {@link decodeLengthPrefixedFrame} guard for the prefix/length checks.
61
+ */
62
+ async function readFrame<T>(stream: ControlStream, timeoutMs: number): Promise<T> {
63
+ const data = await readStreamToEnd(stream, { maxBytes: MAX_WAKE_SIZE, timeoutMs, label: 'Wake' });
64
+ const body = decodeLengthPrefixedFrame(data, MAX_WAKE_SIZE);
65
+ return JSON.parse(new TextDecoder().decode(body)) as T;
66
+ }
67
+
68
+ /**
69
+ * Dependencies the {@link StrandWakeService} receiver needs from its host
70
+ * (`CadreNode`), injected so the service is testable without a full node.
71
+ */
72
+ export interface StrandWakeServiceOptions {
73
+ /** Membership gate: is the remote peer a `CadrePeer` member of this cadre? */
74
+ isMember(remotePeerId: string): Promise<boolean>;
75
+ /** Look up a local strand instance by id (undefined if not participated in). */
76
+ getStrand(strandId: string): StrandInstance | undefined;
77
+ /**
78
+ * Trigger the local wake path for a hibernating/idle strand. Wired to
79
+ * `CadreNode.wakeStrand` (→ `HibernationManager` → `resumeStrand`), whose
80
+ * resume coalescing prevents a push-wake racing a concurrent check-in.
81
+ */
82
+ wake(strandId: string): Promise<void>;
83
+ /**
84
+ * Time to wait for the inbound wake frame before aborting the read (ms).
85
+ * Defaults to {@link DEFAULT_WAKE_READ_TIMEOUT_MS}. Bounds a buggy/compromised
86
+ * own-cadre node that opens a stream and never half-closes its write end.
87
+ */
88
+ readTimeoutMs?: number;
89
+ /**
90
+ * Cap on concurrent inbound wake streams (defaults to
91
+ * {@link DEFAULT_MAX_CONCURRENT_WAKES}). Over the cap, a non-accepting ack is
92
+ * returned without invoking the wake path.
93
+ */
94
+ maxConcurrent?: number;
95
+ }
96
+
97
+ /**
98
+ * Receiver side of the push-wake protocol. Registers a `WAKE_PROTOCOL` handler
99
+ * on the control node and, for each inbound {@link WakeRequest}, gates on cadre
100
+ * membership, then resumes the named strand if it is hibernating/idle and we
101
+ * participate in it — replying with a {@link WakeAck}.
102
+ */
103
+ export class StrandWakeService {
104
+ private readonly options: StrandWakeServiceOptions;
105
+ private readonly readTimeoutMs: number;
106
+ private readonly maxConcurrent: number;
107
+ private node: Libp2p | null = null;
108
+ /** In-flight inbound wake streams, used to enforce {@link maxConcurrent}. */
109
+ private activeStreams = 0;
110
+
111
+ constructor(options: StrandWakeServiceOptions) {
112
+ this.options = options;
113
+ this.readTimeoutMs = options.readTimeoutMs ?? DEFAULT_WAKE_READ_TIMEOUT_MS;
114
+ this.maxConcurrent = options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT_WAKES;
115
+ }
116
+
117
+ /** Number of in-flight inbound wake streams. */
118
+ get activeCount(): number {
119
+ return this.activeStreams;
120
+ }
121
+
122
+ /** Register the wake protocol handler on the control node. */
123
+ initialize(node: Libp2p): void {
124
+ this.node = node;
125
+ // `runOnLimitedConnection: true` is REQUIRED for the relay path: a NAT'd
126
+ // receiver is reached over a circuit-relay connection, which libp2p marks
127
+ // "limited" (the relay caps its data/duration). Without this the receiver
128
+ // would refuse the inbound wake stream on exactly the connection the
129
+ // protocol is designed to use (see the relay note on `dialWake`).
130
+ void node.handle(WAKE_PROTOCOL, async (rawStream: unknown, rawConnection: unknown) => {
131
+ const remotePeerId = (rawConnection as Connection).remotePeer.toString();
132
+ await this.handleStream(rawStream as ControlStream, remotePeerId);
133
+ }, { runOnLimitedConnection: true });
134
+ log('StrandWakeService registered handler: %s', WAKE_PROTOCOL);
135
+ }
136
+
137
+ /** Unregister the handler and release the node reference. */
138
+ async shutdown(): Promise<void> {
139
+ if (this.node) {
140
+ await this.node.unhandle(WAKE_PROTOCOL);
141
+ this.node = null;
142
+ log('StrandWakeService shutdown');
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Read the inbound request, decide + execute the wake, and write the ack.
148
+ *
149
+ * Three hardening layers, all reported as a non-accepting ack rather than a
150
+ * dropped/hung stream: a concurrency cap (over {@link maxConcurrent}, reply
151
+ * without touching the wake path), a read timeout (a peer that never
152
+ * half-closes is aborted inside {@link readFrame}/`readStreamToEnd`), and the
153
+ * existing malformed/oversized-frame guard.
154
+ */
155
+ private async handleStream(stream: ControlStream, remotePeerId: string): Promise<void> {
156
+ log('Incoming wake request from: %s', remotePeerId);
157
+
158
+ if (this.activeStreams >= this.maxConcurrent) {
159
+ log('Rejecting wake from %s: %d concurrent streams at cap %d', remotePeerId, this.activeStreams, this.maxConcurrent);
160
+ const ack: WakeAck = { accepted: false, reason: 'Too many concurrent wake requests' };
161
+ try {
162
+ writeFrame(stream, ack);
163
+ } catch {
164
+ // Ignore send errors on the reject path.
165
+ }
166
+ try {
167
+ await stream.close();
168
+ } catch {
169
+ // Ignore close errors.
170
+ }
171
+ return;
172
+ }
173
+
174
+ this.activeStreams++;
175
+ try {
176
+ const request = await readFrame<WakeRequest>(stream, this.readTimeoutMs);
177
+ const ack = await this.processWakeRequest(request, remotePeerId);
178
+ writeFrame(stream, ack);
179
+ } catch (err) {
180
+ log('Error handling wake request from %s: %o', remotePeerId, err);
181
+ const ack: WakeAck = {
182
+ accepted: false,
183
+ reason: err instanceof Error ? err.message : 'Unknown error',
184
+ };
185
+ try {
186
+ writeFrame(stream, ack);
187
+ } catch {
188
+ // Ignore send errors on the error path.
189
+ }
190
+ } finally {
191
+ this.activeStreams--;
192
+ try {
193
+ await stream.close();
194
+ } catch {
195
+ // Ignore close errors.
196
+ }
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Decide and execute the wake for a decoded request. Exposed (not private) so
202
+ * the decision matrix can be unit-tested directly.
203
+ *
204
+ * - Non-member sender → rejected (`accepted: false`).
205
+ * - Unknown / not-participated strand → rejected.
206
+ * - Hibernating or idle strand → resumed via the wake path, then `accepted`.
207
+ * - Already-live strand → no-op, `accepted` with current status.
208
+ */
209
+ async processWakeRequest(request: WakeRequest, remotePeerId: string): Promise<WakeAck> {
210
+ // The injected membership predicate is the whole v1 authorization (CadreNode
211
+ // supplies the voucher-anchored one); only a peer it admits may ask us to wake.
212
+ if (!(await this.options.isMember(remotePeerId))) {
213
+ log('Rejecting wake from non-member %s', remotePeerId);
214
+ return { accepted: false, reason: 'Sender is not a cadre member' };
215
+ }
216
+
217
+ const instance = this.options.getStrand(request.strandId);
218
+ if (!instance) {
219
+ log('Rejecting wake for unknown/unparticipated strand %s', request.strandId);
220
+ return { accepted: false, reason: 'Strand not found or not participated in' };
221
+ }
222
+
223
+ if (instance.status === 'hibernating' || instance.status === 'idle') {
224
+ log('Waking strand %s on push from %s (reason=%s)', request.strandId, remotePeerId, request.reason ?? 'unspecified');
225
+ await this.options.wake(request.strandId);
226
+ } else {
227
+ log('Strand %s already %s; push-wake is a no-op', request.strandId, instance.status);
228
+ }
229
+
230
+ // The wake path mutates the shared instance, so re-read its current status.
231
+ return { accepted: true, status: instance.status };
232
+ }
233
+ }
234
+
235
+ /** Options for {@link dialWake}. */
236
+ export interface DialWakeOptions {
237
+ /** Per-dial timeout in ms (default {@link DEFAULT_WAKE_TIMEOUT_MS}). */
238
+ timeoutMs?: number;
239
+ /** Override the protocol id (defaults to {@link WAKE_PROTOCOL}). */
240
+ protocolId?: string;
241
+ }
242
+
243
+ /**
244
+ * Sender side: dial a target's control-network address(es), send a
245
+ * {@link WakeRequest} over `WAKE_PROTOCOL`, and return the peer's {@link WakeAck}.
246
+ *
247
+ * Tries each candidate address in order (signaling/relay first, as produced by
248
+ * `CadreNode.resolvePeerAddrs`) until one dials, so a NAT'd peer is reachable via
249
+ * its circuit-relay address. Throws if no address is dialable.
250
+ */
251
+ export async function dialWake(
252
+ node: Libp2p,
253
+ addrs: Multiaddr[],
254
+ request: WakeRequest,
255
+ options: DialWakeOptions = {}
256
+ ): Promise<WakeAck> {
257
+ if (addrs.length === 0) {
258
+ throw new Error('No dialable address for wake target');
259
+ }
260
+ const protocolId = options.protocolId ?? WAKE_PROTOCOL;
261
+ const timeoutMs = options.timeoutMs ?? DEFAULT_WAKE_TIMEOUT_MS;
262
+
263
+ let lastError: Error | null = null;
264
+ for (const addr of addrs) {
265
+ try {
266
+ // One deadline per attempt: its signal aborts the in-flight dialProtocol and
267
+ // resets the live stream, so neither the connect nor the ack-read leaks.
268
+ return await withDeadline(
269
+ timeoutMs,
270
+ `Wake dial ${addr.toString()}`,
271
+ (signal) => sendWake(node, addr, protocolId, request, timeoutMs, signal),
272
+ );
273
+ } catch (err) {
274
+ lastError = err instanceof Error ? err : new Error(String(err));
275
+ log('Wake dial to %s failed: %o', addr.toString(), err);
276
+ }
277
+ }
278
+ throw lastError ?? new Error('Wake dial failed');
279
+ }
280
+
281
+ /**
282
+ * Open one stream, send the request, half-close, and read the ack.
283
+ *
284
+ * `signal` is the per-attempt deadline from {@link dialWake}: it goes to
285
+ * `dialProtocol` so a timeout during connect aborts the dial, and into
286
+ * {@link exchangeFrame} so a timeout after the stream is open resets it —
287
+ * releasing the otherwise unbounded ack-read.
288
+ */
289
+ async function sendWake(
290
+ node: Libp2p,
291
+ addr: Multiaddr,
292
+ protocolId: string,
293
+ request: WakeRequest,
294
+ timeoutMs: number,
295
+ signal: AbortSignal,
296
+ ): Promise<WakeAck> {
297
+ // `runOnLimitedConnection: true`: the target may be reachable only over a
298
+ // circuit-relay connection (the signaling-first addr), which libp2p marks
299
+ // "limited". The wake exchange is a single tiny request→ack well within the
300
+ // relay's data/duration cap, so opening it on the limited connection is safe
301
+ // and is the whole point of dialing the relay address.
302
+ const rawStream = await node.dialProtocol(addr, protocolId, { runOnLimitedConnection: true, signal });
303
+
304
+ const ack = await exchangeFrame(
305
+ rawStream as unknown as ControlStream,
306
+ signal,
307
+ request,
308
+ (stream) => readFrame<WakeAck>(stream, timeoutMs),
309
+ 'Wake dial aborted by timeout',
310
+ );
311
+
312
+ log('Wake ack from %s: accepted=%s status=%s', addr.toString(), ack.accepted, ack.status ?? '-');
313
+ return ack;
314
+ }