@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,410 +1,441 @@
1
- /**
2
- * Control-network strand-address RPC.
3
- *
4
- * A strand runs as its own libp2p node (`strand-<id>`, random port), separate
5
- * from the control node (`control-<partyId>`) even though both share the same
6
- * peerId. To seed a strand's mesh, a node needs a sibling's **strand-network**
7
- * address — but `CadrePeer.Multiaddr` only stores the **control** node's
8
- * addresses. This protocol resolves the strand address on demand: a node asks
9
- * its connected co-cadre siblings "what are your live strand-`X` multiaddrs?" and
10
- * uses the union of their answers as the seed.
11
- *
12
- * Modeled directly on `strand-wake-protocol.ts`: a dedicated libp2p protocol id,
13
- * 4-byte big-endian length-prefixed JSON frames, `node.handle` for the receiver,
14
- * `node.dialProtocol` for the client, and the shared `ControlStream` primitives
15
- * from `control-stream.ts`. The exchange is a single request → single response on
16
- * one stream, so each side reads to EOF (under a read timeout) and decodes one
17
- * frame via the shared {@link decodeLengthPrefixedFrame} guard.
18
- *
19
- * **Authorization (v1):** the control network is single-party — only this party's
20
- * cadre peers connect (schema-gated `CadrePeer`). Like wake, the receiver gates
21
- * on cadre membership (via the injected `isMember`) and requires no further
22
- * signature; a non-member is refused with an empty address list. This is
23
- * defense-in-depth (the control mesh already restricts membership) kept for
24
- * parity with wake. Cross-party strand bootstrap is a different mechanism
25
- * (strand formation / `MemberPeer`) and is out of scope here.
26
- */
27
-
28
- import debug from 'debug';
29
- import type { Libp2p, Connection, PeerId } from '@libp2p/interface';
30
- import type { Multiaddr } from '@multiformats/multiaddr';
31
- import { peerIdFromString } from '@libp2p/peer-id';
32
- import type { StrandAddrRequest, StrandAddrResponse } from './types.js';
33
- import { decodeLengthPrefixedFrame } from './seed-bootstrap.js';
34
- import { orderSignalingFirst } from './peer-record.js';
35
- import { type ControlStream, writeFrame, withTimeout, readStreamToEnd } from './control-stream.js';
36
-
37
- const log = debug('sereus:cadre:strand-addr');
38
-
39
- /** Protocol id for the control-network strand-address RPC (parallel to `/sereus/strand-wake/1.0.0`). */
40
- export const STRAND_ADDR_PROTOCOL = '/sereus/strand-addr/1.0.0';
41
-
42
- /**
43
- * Maximum strand-addr frame size. Responses are tiny (a strand id + a few
44
- * multiaddrs), so this is a defensive cap — far below the 1MB seed ceiling —
45
- * that bounds the bytes a peer can make the receiver buffer per stream.
46
- */
47
- const MAX_ADDR_SIZE = 64 * 1024;
48
-
49
- /** Default time to wait for the response before abandoning a strand-addr dial (ms). */
50
- const DEFAULT_ADDR_TIMEOUT_MS = 10_000;
51
-
52
- /** Default time the receiver waits for an inbound request frame before aborting (ms). */
53
- const DEFAULT_ADDR_READ_TIMEOUT_MS = 10_000;
54
-
55
- /** Default cap on concurrent inbound strand-addr streams a single peer can pin open. */
56
- const DEFAULT_MAX_CONCURRENT_ADDRS = 100;
57
-
58
- /**
59
- * Read a libp2p stream to EOF and decode the single length-prefixed JSON frame
60
- * it carries. Bounded by `timeoutMs` (a never-half-closing peer is aborted, not
61
- * awaited forever) and capped at {@link MAX_ADDR_SIZE}, reusing the shared
62
- * {@link decodeLengthPrefixedFrame} guard for the prefix/length checks.
63
- */
64
- async function readFrame<T>(stream: ControlStream, timeoutMs: number): Promise<T> {
65
- const data = await readStreamToEnd(stream, { maxBytes: MAX_ADDR_SIZE, timeoutMs, label: 'Strand-addr' });
66
- const body = decodeLengthPrefixedFrame(data, MAX_ADDR_SIZE);
67
- return JSON.parse(new TextDecoder().decode(body)) as T;
68
- }
69
-
70
- /** Empty response used on every reject/error path (cap, malformed frame, non-member). */
71
- function emptyResponse(strandId: string): StrandAddrResponse {
72
- return { strandId, multiaddrs: [] };
73
- }
74
-
75
- /**
76
- * Dependencies the {@link StrandAddrService} receiver needs from its host
77
- * (`CadreNode`), injected so the service is testable without a full node.
78
- */
79
- export interface StrandAddrServiceOptions {
80
- /** Membership gate: is the remote peer a `CadrePeer` member of this cadre? */
81
- isMember(remotePeerId: string): Promise<boolean>;
82
- /**
83
- * The local strand instance's dialable strand-network multiaddrs, ordered
84
- * signaling-first. Returns `[]` when the strand is not running / has no live
85
- * node (hibernating, quiescing, or never participated). Kept injectable so the
86
- * decision logic is unit-testable without a full node.
87
- */
88
- getStrandMultiaddrs(strandId: string): string[];
89
- /**
90
- * Time to wait for the inbound request frame before aborting the read (ms).
91
- * Defaults to {@link DEFAULT_ADDR_READ_TIMEOUT_MS}. Bounds a buggy/compromised
92
- * own-cadre node that opens a stream and never half-closes its write end.
93
- */
94
- readTimeoutMs?: number;
95
- /**
96
- * Cap on concurrent inbound strand-addr streams (defaults to
97
- * {@link DEFAULT_MAX_CONCURRENT_ADDRS}). Over the cap, an empty response is
98
- * returned without looking up any strand address.
99
- */
100
- maxConcurrent?: number;
101
- }
102
-
103
- /**
104
- * Receiver side of the strand-address RPC. Registers a `STRAND_ADDR_PROTOCOL`
105
- * handler on the control node and, for each inbound {@link StrandAddrRequest},
106
- * gates on cadre membership, then replies with the local strand instance's live
107
- * multiaddrs (or an empty list when not a member / not running).
108
- */
109
- export class StrandAddrService {
110
- private readonly options: StrandAddrServiceOptions;
111
- private readonly readTimeoutMs: number;
112
- private readonly maxConcurrent: number;
113
- private node: Libp2p | null = null;
114
- /** In-flight inbound strand-addr streams, used to enforce {@link maxConcurrent}. */
115
- private activeStreams = 0;
116
-
117
- constructor(options: StrandAddrServiceOptions) {
118
- this.options = options;
119
- this.readTimeoutMs = options.readTimeoutMs ?? DEFAULT_ADDR_READ_TIMEOUT_MS;
120
- this.maxConcurrent = options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT_ADDRS;
121
- }
122
-
123
- /** Number of in-flight inbound strand-addr streams. */
124
- get activeCount(): number {
125
- return this.activeStreams;
126
- }
127
-
128
- /** Register the strand-addr protocol handler on the control node. */
129
- initialize(node: Libp2p): void {
130
- this.node = node;
131
- // `runOnLimitedConnection: true` is REQUIRED for the relay path: a NAT'd
132
- // sibling is reached over a circuit-relay connection, which libp2p marks
133
- // "limited" (the relay caps its data/duration). Without this the receiver
134
- // would refuse the inbound stream on exactly the connection the protocol is
135
- // designed to use (same reasoning as wake; see the relay note on
136
- // `collectStrandAddrs`).
137
- void node.handle(STRAND_ADDR_PROTOCOL, async (rawStream: unknown, rawConnection: unknown) => {
138
- const remotePeerId = (rawConnection as Connection).remotePeer.toString();
139
- await this.handleStream(rawStream as ControlStream, remotePeerId);
140
- }, { runOnLimitedConnection: true });
141
- log('StrandAddrService registered handler: %s', STRAND_ADDR_PROTOCOL);
142
- }
143
-
144
- /** Unregister the handler and release the node reference. */
145
- async shutdown(): Promise<void> {
146
- if (this.node) {
147
- await this.node.unhandle(STRAND_ADDR_PROTOCOL);
148
- this.node = null;
149
- log('StrandAddrService shutdown');
150
- }
151
- }
152
-
153
- /**
154
- * Read the inbound request, decide the response, and write it back.
155
- *
156
- * Three hardening layers, all reported as an empty {@link StrandAddrResponse}
157
- * rather than a dropped/hung stream: a concurrency cap (over
158
- * {@link maxConcurrent}, reply without looking up any address), a read timeout
159
- * (a peer that never half-closes is aborted inside {@link readFrame}/
160
- * `readStreamToEnd`), and the existing malformed/oversized-frame guard.
161
- */
162
- private async handleStream(stream: ControlStream, remotePeerId: string): Promise<void> {
163
- log('Incoming strand-addr request from: %s', remotePeerId);
164
-
165
- if (this.activeStreams >= this.maxConcurrent) {
166
- log('Rejecting strand-addr from %s: %d concurrent streams at cap %d', remotePeerId, this.activeStreams, this.maxConcurrent);
167
- // The request frame is unread here, so the strand id is unknown — reply
168
- // with an empty list under an empty strand id; the client treats any empty
169
- // response as "no addrs" and skips this sibling.
170
- try {
171
- writeFrame(stream, emptyResponse(''));
172
- } catch {
173
- // Ignore send errors on the reject path.
174
- }
175
- try {
176
- await stream.close();
177
- } catch {
178
- // Ignore close errors.
179
- }
180
- return;
181
- }
182
-
183
- this.activeStreams++;
184
- try {
185
- const request = await readFrame<StrandAddrRequest>(stream, this.readTimeoutMs);
186
- const response = await this.processAddrRequest(request, remotePeerId);
187
- writeFrame(stream, response);
188
- } catch (err) {
189
- log('Error handling strand-addr request from %s: %o', remotePeerId, err);
190
- // Malformed/oversized/timed-out request: strand id is unknown, so reply
191
- // with an empty list under an empty strand id rather than hanging.
192
- try {
193
- writeFrame(stream, emptyResponse(''));
194
- } catch {
195
- // Ignore send errors on the error path.
196
- }
197
- } finally {
198
- this.activeStreams--;
199
- try {
200
- await stream.close();
201
- } catch {
202
- // Ignore close errors.
203
- }
204
- }
205
- }
206
-
207
- /**
208
- * Decide the response for a decoded request. Exposed (not private) so the
209
- * decision matrix can be unit-tested directly (mirrors wake's
210
- * `processWakeRequest`).
211
- *
212
- * - Non-member sender → empty `multiaddrs` (refused).
213
- * - Strand not running locally → empty `multiaddrs` (`getStrandMultiaddrs` → `[]`).
214
- * - Member + running strand → the strand's live, signaling-first multiaddrs.
215
- */
216
- async processAddrRequest(request: StrandAddrRequest, remotePeerId: string): Promise<StrandAddrResponse> {
217
- // Control-network membership is the v1 authorization: only this party's
218
- // cadre peers may ask us for a strand address.
219
- if (!(await this.options.isMember(remotePeerId))) {
220
- log('Refusing strand-addr from non-member %s', remotePeerId);
221
- return emptyResponse(request.strandId);
222
- }
223
-
224
- const multiaddrs = this.options.getStrandMultiaddrs(request.strandId);
225
- log('Strand-addr for %s → %d addr(s)', request.strandId, multiaddrs.length);
226
- return { strandId: request.strandId, multiaddrs };
227
- }
228
- }
229
-
230
- /** A sibling to ask for its strand address. */
231
- export interface StrandAddrPeer {
232
- /** The sibling's control-network peer id (also its strand-node peer id). */
233
- peerId: string;
234
- /**
235
- * Pre-resolved control-network multiaddrs, used as a fallback when no control
236
- * connection is already open. Dialing by {@link peerId} is preferred (it
237
- * reuses an existing connection); these are tried only if that fails.
238
- */
239
- addrs?: Multiaddr[];
240
- }
241
-
242
- /** Options for {@link collectStrandAddrs}. */
243
- export interface CollectStrandAddrsOptions {
244
- /** Per-dial timeout in ms (default {@link DEFAULT_ADDR_TIMEOUT_MS}). */
245
- timeoutMs?: number;
246
- /** Override the protocol id (defaults to {@link STRAND_ADDR_PROTOCOL}). */
247
- protocolId?: string;
248
- }
249
-
250
- /**
251
- * Client side: ask each candidate sibling for its live strand-`strandId`
252
- * multiaddrs and return the **deduplicated union** of every answer, ordered
253
- * signaling-first.
254
- *
255
- * Best-effort per peer: a failed/timed-out/empty sibling is logged and skipped,
256
- * never fatal — an empty union (no sibling online or running the strand) returns
257
- * `[]`, which the caller treats as an acceptable seed that self-heals on the next
258
- * resume/reconcile pass. The local node (`node.peerId`) is excluded so we never
259
- * RPC ourselves or seed with our own strand address.
260
- *
261
- * Dials run concurrently but the union preserves candidate order, so the result
262
- * is deterministic regardless of which sibling answers first.
263
- */
264
- export async function collectStrandAddrs(
265
- node: Libp2p,
266
- peers: StrandAddrPeer[],
267
- strandId: string,
268
- options: CollectStrandAddrsOptions = {}
269
- ): Promise<string[]> {
270
- const selfId = node.peerId.toString();
271
- const request: StrandAddrRequest = { strandId };
272
- const candidates = peers.filter(p => p.peerId !== selfId);
273
-
274
- // Concurrent dials; `dialOneSibling` swallows per-peer failure into `[]`, so
275
- // `Promise.all` never rejects and the result array stays in candidate order.
276
- const perPeer = await Promise.all(
277
- candidates.map(peer => dialOneSibling(node, peer, request, options))
278
- );
279
-
280
- // Deduplicated union in candidate order, then signaling-first for a usable
281
- // dial sequence (relay/`p2p-circuit` ahead of direct addrs).
282
- const seen = new Set<string>();
283
- const union: string[] = [];
284
- for (const addrs of perPeer) {
285
- for (const addr of addrs) {
286
- if (!seen.has(addr)) {
287
- seen.add(addr);
288
- union.push(addr);
289
- }
290
- }
291
- }
292
- return orderSignalingFirst(union);
293
- }
294
-
295
- /**
296
- * Ask one sibling for its strand address, returning its multiaddrs or `[]` on any
297
- * failure. Tries each dial target in order (peerId first to reuse an open control
298
- * connection, then explicit addrs) until one answers; a total failure is logged
299
- * and folded to `[]` so a single dead sibling never aborts the collection.
300
- */
301
- async function dialOneSibling(
302
- node: Libp2p,
303
- peer: StrandAddrPeer,
304
- request: StrandAddrRequest,
305
- options: CollectStrandAddrsOptions
306
- ): Promise<string[]> {
307
- const protocolId = options.protocolId ?? STRAND_ADDR_PROTOCOL;
308
- const timeoutMs = options.timeoutMs ?? DEFAULT_ADDR_TIMEOUT_MS;
309
- const targets = dialTargets(peer);
310
-
311
- if (targets.length === 0) {
312
- log('No dial target for sibling %s', peer.peerId);
313
- return [];
314
- }
315
-
316
- for (const target of targets) {
317
- // One controller per attempt: on timeout, `withTimeout`'s `onTimeout` aborts
318
- // it, which aborts the in-flight dialProtocol (via the dial `signal`) and the
319
- // live stream — so neither the connect nor the unbounded response-read leaks.
320
- const controller = new AbortController();
321
- try {
322
- const response = await withTimeout(
323
- timeoutMs,
324
- `Strand-addr dial ${peer.peerId}`,
325
- () => sendStrandAddr(node, target, protocolId, request, timeoutMs, controller.signal),
326
- () => controller.abort(),
327
- );
328
- return response.multiaddrs;
329
- } catch (err) {
330
- log('Strand-addr dial to %s via %s failed: %o', peer.peerId, describeTarget(target), err);
331
- }
332
- }
333
- return [];
334
- }
335
-
336
- /**
337
- * Dial targets for a sibling, peerId first. Dialing by peerId lets libp2p reuse
338
- * an already-open control connection (the common case — the wiring ticket passes
339
- * connected siblings); the explicit control addrs are a fallback for when no
340
- * connection is open. An unparsable peerId is skipped (rely on addrs).
341
- */
342
- function dialTargets(peer: StrandAddrPeer): Array<PeerId | Multiaddr> {
343
- const targets: Array<PeerId | Multiaddr> = [];
344
- try {
345
- targets.push(peerIdFromString(peer.peerId));
346
- } catch (err) {
347
- log('Unparsable peer id %s, falling back to addrs: %o', peer.peerId, err);
348
- }
349
- if (peer.addrs) {
350
- targets.push(...peer.addrs);
351
- }
352
- return targets;
353
- }
354
-
355
- /** Short label for a dial target (peerId or multiaddr) for logging. */
356
- function describeTarget(target: PeerId | Multiaddr): string {
357
- return target.toString();
358
- }
359
-
360
- /**
361
- * Open one stream to a target, send the request, half-close, and read the
362
- * response.
363
- *
364
- * `signal` is the per-attempt abort signal from {@link dialOneSibling}: it is
365
- * passed to `dialProtocol` so a timeout during connect aborts the dial, and once
366
- * the stream is open an abort listener resets the live stream — releasing the
367
- * otherwise unbounded response-read. `readFrame` still applies `timeoutMs` as a
368
- * backstop for the case where an abort does not propagate (e.g. a stream double
369
- * whose `abort()` is a no-op).
370
- */
371
- async function sendStrandAddr(
372
- node: Libp2p,
373
- target: PeerId | Multiaddr,
374
- protocolId: string,
375
- request: StrandAddrRequest,
376
- timeoutMs: number,
377
- signal: AbortSignal,
378
- ): Promise<StrandAddrResponse> {
379
- // `runOnLimitedConnection: true`: the sibling may be reachable only over a
380
- // circuit-relay connection (the signaling-first addr), which libp2p marks
381
- // "limited". The exchange is a single tiny request→response well within the
382
- // relay's data/duration cap, so opening it on the limited connection is safe
383
- // and is the whole point of dialing over the relay.
384
- const rawStream = await node.dialProtocol(target, protocolId, { runOnLimitedConnection: true, signal });
385
- const stream = rawStream as unknown as ControlStream;
386
-
387
- const abortErr = new Error('Strand-addr dial aborted by timeout');
388
- const onAbort = (): void => stream.abort(abortErr);
389
- // If the timeout already fired during connect, release the freshly-opened stream now.
390
- if (signal.aborted) {
391
- onAbort();
392
- throw abortErr;
393
- }
394
- signal.addEventListener('abort', onAbort, { once: true });
395
-
396
- try {
397
- writeFrame(stream, request);
398
- // close() half-closes the write end (EOF) while the read end stays open for
399
- // the response — the same libp2p 3.x pattern as wake/seed delivery.
400
- await stream.close();
401
- const response = await readFrame<StrandAddrResponse>(stream, timeoutMs);
402
- log('Strand-addr response: %d addr(s) for %s', response.multiaddrs.length, response.strandId);
403
- return response;
404
- } catch (err) {
405
- stream.abort(err instanceof Error ? err : new Error(String(err)));
406
- throw err;
407
- } finally {
408
- signal.removeEventListener('abort', onAbort);
409
- }
410
- }
1
+ /**
2
+ * Control-network strand-address RPC.
3
+ *
4
+ * A strand runs as its own libp2p node (`strand-<id>`, random port), separate
5
+ * from the control node (`control-<partyId>`), with its own transport peerId
6
+ * derived from the cadre identity key (`strand-transport-key.ts`). To seed a
7
+ * strand's mesh, a node needs a sibling's **strand-network** address — but
8
+ * `CadrePeer.Multiaddr` only stores the **control** node's addresses, and a
9
+ * control address now names a different peer entirely, not merely a different
10
+ * port. This protocol resolves the strand address on demand: a node asks its
11
+ * connected co-cadre siblings "what are your live strand-`X` multiaddrs?" and
12
+ * uses the union of their answers as the seed.
13
+ *
14
+ * Modeled directly on `strand-wake-protocol.ts`: a dedicated libp2p protocol id,
15
+ * 4-byte big-endian length-prefixed JSON frames, `node.handle` for the receiver,
16
+ * `node.dialProtocol` for the client, and the shared `ControlStream` primitives
17
+ * from `control-stream.ts`. The exchange is a single request → single response on
18
+ * one stream, so each side reads to EOF (under a read timeout) and decodes one
19
+ * frame via the shared {@link decodeLengthPrefixedFrame} guard.
20
+ *
21
+ * **Authorization (v1):** like wake, the receiver defers entirely to the injected
22
+ * `isMember` predicate and requires no further signature; a peer it rejects gets
23
+ * an empty address list. `CadreNode` injects its AUTHORIZED-membership predicate
24
+ * (`isAuthorizedMember`: voucher on the requester's `CadrePeer` row verified
25
+ * against the node-local trusted-owner anchor), so an outsider that published its
26
+ * own rows into the replicated control DB cannot harvest live strand addresses.
27
+ * Cross-party strand bootstrap is a different mechanism (strand formation /
28
+ * `MemberPeer`) and is out of scope here.
29
+ */
30
+
31
+ import debug from 'debug';
32
+ import type { Libp2p, Connection, PeerId } from '@libp2p/interface';
33
+ import type { Multiaddr } from '@multiformats/multiaddr';
34
+ import { peerIdFromString } from '@libp2p/peer-id';
35
+ import type { StrandAddrRequest, StrandAddrResponse } from './types.js';
36
+ import { decodeLengthPrefixedFrame } from './seed-bootstrap.js';
37
+ import { orderSignalingFirst } from './peer-record.js';
38
+ import { type ControlStream, writeFrame, withDeadline, exchangeFrame, readStreamToEnd } from './control-stream.js';
39
+
40
+ const log = debug('sereus:cadre:strand-addr');
41
+
42
+ /** Protocol id for the control-network strand-address RPC (parallel to `/sereus/strand-wake/1.0.0`). */
43
+ export const STRAND_ADDR_PROTOCOL = '/sereus/strand-addr/1.0.0';
44
+
45
+ /**
46
+ * Maximum strand-addr frame size. Responses are tiny (a strand id + a few
47
+ * multiaddrs), so this is a defensive cap — far below the 1MB seed ceiling —
48
+ * that bounds the bytes a peer can make the receiver buffer per stream.
49
+ */
50
+ const MAX_ADDR_SIZE = 64 * 1024;
51
+
52
+ /** Default time to wait for the response before abandoning a strand-addr dial (ms). */
53
+ const DEFAULT_ADDR_TIMEOUT_MS = 10_000;
54
+
55
+ /** Default time the receiver waits for an inbound request frame before aborting (ms). */
56
+ const DEFAULT_ADDR_READ_TIMEOUT_MS = 10_000;
57
+
58
+ /** Default cap on concurrent inbound strand-addr streams a single peer can pin open. */
59
+ const DEFAULT_MAX_CONCURRENT_ADDRS = 100;
60
+
61
+ /**
62
+ * Read a libp2p stream to EOF and decode the single length-prefixed JSON frame
63
+ * it carries. Bounded by `timeoutMs` (a never-half-closing peer is aborted, not
64
+ * awaited forever) and capped at {@link MAX_ADDR_SIZE}, reusing the shared
65
+ * {@link decodeLengthPrefixedFrame} guard for the prefix/length checks.
66
+ */
67
+ async function readFrame<T>(stream: ControlStream, timeoutMs: number): Promise<T> {
68
+ const data = await readStreamToEnd(stream, { maxBytes: MAX_ADDR_SIZE, timeoutMs, label: 'Strand-addr' });
69
+ const body = decodeLengthPrefixedFrame(data, MAX_ADDR_SIZE);
70
+ return JSON.parse(new TextDecoder().decode(body)) as T;
71
+ }
72
+
73
+ /** Empty response used on every reject/error path (cap, malformed frame, non-member). */
74
+ function emptyResponse(strandId: string): StrandAddrResponse {
75
+ return { strandId, multiaddrs: [] };
76
+ }
77
+
78
+ /**
79
+ * Dependencies the {@link StrandAddrService} receiver needs from its host
80
+ * (`CadreNode`), injected so the service is testable without a full node.
81
+ */
82
+ export interface StrandAddrServiceOptions {
83
+ /** Membership gate: is the remote peer a `CadrePeer` member of this cadre? */
84
+ isMember(remotePeerId: string): Promise<boolean>;
85
+ /**
86
+ * The local strand instance's dialable strand-network multiaddrs, ordered
87
+ * signaling-first. Returns `[]` when the strand is not running / has no live
88
+ * node (hibernating, quiescing, or never participated). Kept injectable so the
89
+ * decision logic is unit-testable without a full node.
90
+ */
91
+ getStrandMultiaddrs(strandId: string): string[];
92
+ /**
93
+ * Called when a member's request carries a `delegatePeerId` — the derived
94
+ * transport peerId its strand-`strandId` node runs as. Invoked only AFTER the
95
+ * `isMember` gate passed, with a validated (parseable, non-self) peerId.
96
+ * `CadreNode` injects its delegate-admission grant recorder so this node's
97
+ * connection gate — and thus its circuit-relay server, when it runs one —
98
+ * admits that peerId (see `delegate-admission.ts`). Optional: absent, an
99
+ * announce is ignored and the address lookup proceeds unchanged.
100
+ */
101
+ onDelegateAnnounce?(announcerPeerId: string, strandId: string, delegatePeerId: string): void;
102
+ /**
103
+ * Time to wait for the inbound request frame before aborting the read (ms).
104
+ * Defaults to {@link DEFAULT_ADDR_READ_TIMEOUT_MS}. Bounds a buggy/compromised
105
+ * own-cadre node that opens a stream and never half-closes its write end.
106
+ */
107
+ readTimeoutMs?: number;
108
+ /**
109
+ * Cap on concurrent inbound strand-addr streams (defaults to
110
+ * {@link DEFAULT_MAX_CONCURRENT_ADDRS}). Over the cap, an empty response is
111
+ * returned without looking up any strand address.
112
+ */
113
+ maxConcurrent?: number;
114
+ }
115
+
116
+ /**
117
+ * Receiver side of the strand-address RPC. Registers a `STRAND_ADDR_PROTOCOL`
118
+ * handler on the control node and, for each inbound {@link StrandAddrRequest},
119
+ * gates on cadre membership, then replies with the local strand instance's live
120
+ * multiaddrs (or an empty list when not a member / not running).
121
+ */
122
+ export class StrandAddrService {
123
+ private readonly options: StrandAddrServiceOptions;
124
+ private readonly readTimeoutMs: number;
125
+ private readonly maxConcurrent: number;
126
+ private node: Libp2p | null = null;
127
+ /** In-flight inbound strand-addr streams, used to enforce {@link maxConcurrent}. */
128
+ private activeStreams = 0;
129
+
130
+ constructor(options: StrandAddrServiceOptions) {
131
+ this.options = options;
132
+ this.readTimeoutMs = options.readTimeoutMs ?? DEFAULT_ADDR_READ_TIMEOUT_MS;
133
+ this.maxConcurrent = options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT_ADDRS;
134
+ }
135
+
136
+ /** Number of in-flight inbound strand-addr streams. */
137
+ get activeCount(): number {
138
+ return this.activeStreams;
139
+ }
140
+
141
+ /** Register the strand-addr protocol handler on the control node. */
142
+ initialize(node: Libp2p): void {
143
+ this.node = node;
144
+ // `runOnLimitedConnection: true` is REQUIRED for the relay path: a NAT'd
145
+ // sibling is reached over a circuit-relay connection, which libp2p marks
146
+ // "limited" (the relay caps its data/duration). Without this the receiver
147
+ // would refuse the inbound stream on exactly the connection the protocol is
148
+ // designed to use (same reasoning as wake; see the relay note on
149
+ // `collectStrandAddrs`).
150
+ void node.handle(STRAND_ADDR_PROTOCOL, async (rawStream: unknown, rawConnection: unknown) => {
151
+ const remotePeerId = (rawConnection as Connection).remotePeer.toString();
152
+ await this.handleStream(rawStream as ControlStream, remotePeerId);
153
+ }, { runOnLimitedConnection: true });
154
+ log('StrandAddrService registered handler: %s', STRAND_ADDR_PROTOCOL);
155
+ }
156
+
157
+ /** Unregister the handler and release the node reference. */
158
+ async shutdown(): Promise<void> {
159
+ if (this.node) {
160
+ await this.node.unhandle(STRAND_ADDR_PROTOCOL);
161
+ this.node = null;
162
+ log('StrandAddrService shutdown');
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Read the inbound request, decide the response, and write it back.
168
+ *
169
+ * Three hardening layers, all reported as an empty {@link StrandAddrResponse}
170
+ * rather than a dropped/hung stream: a concurrency cap (over
171
+ * {@link maxConcurrent}, reply without looking up any address), a read timeout
172
+ * (a peer that never half-closes is aborted inside {@link readFrame}/
173
+ * `readStreamToEnd`), and the existing malformed/oversized-frame guard.
174
+ */
175
+ private async handleStream(stream: ControlStream, remotePeerId: string): Promise<void> {
176
+ log('Incoming strand-addr request from: %s', remotePeerId);
177
+
178
+ if (this.activeStreams >= this.maxConcurrent) {
179
+ log('Rejecting strand-addr from %s: %d concurrent streams at cap %d', remotePeerId, this.activeStreams, this.maxConcurrent);
180
+ // The request frame is unread here, so the strand id is unknown — reply
181
+ // with an empty list under an empty strand id; the client treats any empty
182
+ // response as "no addrs" and skips this sibling.
183
+ try {
184
+ writeFrame(stream, emptyResponse(''));
185
+ } catch {
186
+ // Ignore send errors on the reject path.
187
+ }
188
+ try {
189
+ await stream.close();
190
+ } catch {
191
+ // Ignore close errors.
192
+ }
193
+ return;
194
+ }
195
+
196
+ this.activeStreams++;
197
+ try {
198
+ const request = await readFrame<StrandAddrRequest>(stream, this.readTimeoutMs);
199
+ const response = await this.processAddrRequest(request, remotePeerId);
200
+ writeFrame(stream, response);
201
+ } catch (err) {
202
+ log('Error handling strand-addr request from %s: %o', remotePeerId, err);
203
+ // Malformed/oversized/timed-out request: strand id is unknown, so reply
204
+ // with an empty list under an empty strand id rather than hanging.
205
+ try {
206
+ writeFrame(stream, emptyResponse(''));
207
+ } catch {
208
+ // Ignore send errors on the error path.
209
+ }
210
+ } finally {
211
+ this.activeStreams--;
212
+ try {
213
+ await stream.close();
214
+ } catch {
215
+ // Ignore close errors.
216
+ }
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Decide the response for a decoded request. Exposed (not private) so the
222
+ * decision matrix can be unit-tested directly (mirrors wake's
223
+ * `processWakeRequest`).
224
+ *
225
+ * - Non-member sender → empty `multiaddrs` (refused), no delegate grant.
226
+ * - Member request carrying a `delegatePeerId` → recorded via
227
+ * {@link StrandAddrServiceOptions.onDelegateAnnounce} before the lookup.
228
+ * - Strand not running locally → empty `multiaddrs` (`getStrandMultiaddrs` → `[]`).
229
+ * - Member + running strand → the strand's live, signaling-first multiaddrs.
230
+ */
231
+ async processAddrRequest(request: StrandAddrRequest, remotePeerId: string): Promise<StrandAddrResponse> {
232
+ // Control-network membership is the v1 authorization: only this party's
233
+ // cadre peers may ask us for a strand address (or announce a delegate).
234
+ if (!(await this.options.isMember(remotePeerId))) {
235
+ log('Refusing strand-addr from non-member %s', remotePeerId);
236
+ return emptyResponse(request.strandId);
237
+ }
238
+
239
+ this.recordDelegateAnnounce(request, remotePeerId);
240
+
241
+ const multiaddrs = this.options.getStrandMultiaddrs(request.strandId);
242
+ log('Strand-addr for %s → %d addr(s)', request.strandId, multiaddrs.length);
243
+ return { strandId: request.strandId, multiaddrs };
244
+ }
245
+
246
+ /**
247
+ * Validate and forward a member's delegate announcement. A malformed field
248
+ * (unparsable peerId) and a self-announcement (`delegatePeerId` equal to the
249
+ * announcer's own peerId — a member is admitted directly, never by grant)
250
+ * are logged and dropped; the address lookup proceeds either way.
251
+ */
252
+ private recordDelegateAnnounce(request: StrandAddrRequest, remotePeerId: string): void {
253
+ const { strandId, delegatePeerId } = request;
254
+ if (delegatePeerId === undefined || !this.options.onDelegateAnnounce) {
255
+ return;
256
+ }
257
+ if (delegatePeerId === remotePeerId) {
258
+ log('Ignoring self-announcement from %s (strand %s)', remotePeerId, strandId);
259
+ return;
260
+ }
261
+ try {
262
+ peerIdFromString(delegatePeerId);
263
+ } catch (err) {
264
+ log('Ignoring malformed delegatePeerId %o from %s: %o', delegatePeerId, remotePeerId, err);
265
+ return;
266
+ }
267
+ this.options.onDelegateAnnounce(remotePeerId, strandId, delegatePeerId);
268
+ }
269
+ }
270
+
271
+ /** A sibling to ask for its strand address. */
272
+ export interface StrandAddrPeer {
273
+ /** The sibling's control-network peer id (also its strand-node peer id). */
274
+ peerId: string;
275
+ /**
276
+ * Pre-resolved control-network multiaddrs, used as a fallback when no control
277
+ * connection is already open. Dialing by {@link peerId} is preferred (it
278
+ * reuses an existing connection); these are tried only if that fails.
279
+ */
280
+ addrs?: Multiaddr[];
281
+ }
282
+
283
+ /** Options for {@link collectStrandAddrs}. */
284
+ export interface CollectStrandAddrsOptions {
285
+ /** Per-dial timeout in ms (default {@link DEFAULT_ADDR_TIMEOUT_MS}). */
286
+ timeoutMs?: number;
287
+ /** Override the protocol id (defaults to {@link STRAND_ADDR_PROTOCOL}). */
288
+ protocolId?: string;
289
+ /**
290
+ * The derived transport peerId the caller's own strand-`strandId` node runs
291
+ * (or is about to run) as. Set on every request this collection sends, so
292
+ * each receiver records a delegate admission grant for it — see
293
+ * {@link StrandAddrRequest.delegatePeerId}. Omit for a pure address lookup.
294
+ */
295
+ delegatePeerId?: string;
296
+ }
297
+
298
+ /**
299
+ * Client side: ask each candidate sibling for its live strand-`strandId`
300
+ * multiaddrs and return the **deduplicated union** of every answer, ordered
301
+ * signaling-first.
302
+ *
303
+ * Best-effort per peer: a failed/timed-out/empty sibling is logged and skipped,
304
+ * never fatal — an empty union (no sibling online or running the strand) returns
305
+ * `[]`, which the caller treats as an acceptable seed that self-heals on the next
306
+ * resume/reconcile pass. The local node (`node.peerId`) is excluded so we never
307
+ * RPC ourselves or seed with our own strand address.
308
+ *
309
+ * Dials run concurrently but the union preserves candidate order, so the result
310
+ * is deterministic regardless of which sibling answers first.
311
+ */
312
+ export async function collectStrandAddrs(
313
+ node: Libp2p,
314
+ peers: StrandAddrPeer[],
315
+ strandId: string,
316
+ options: CollectStrandAddrsOptions = {}
317
+ ): Promise<string[]> {
318
+ const selfId = node.peerId.toString();
319
+ const request: StrandAddrRequest = options.delegatePeerId !== undefined
320
+ ? { strandId, delegatePeerId: options.delegatePeerId }
321
+ : { strandId };
322
+ const candidates = peers.filter(p => p.peerId !== selfId);
323
+
324
+ // Concurrent dials; `dialOneSibling` swallows per-peer failure into `[]`, so
325
+ // `Promise.all` never rejects and the result array stays in candidate order.
326
+ const perPeer = await Promise.all(
327
+ candidates.map(peer => dialOneSibling(node, peer, request, options))
328
+ );
329
+
330
+ // Deduplicated union in candidate order, then signaling-first for a usable
331
+ // dial sequence (relay/`p2p-circuit` ahead of direct addrs).
332
+ const seen = new Set<string>();
333
+ const union: string[] = [];
334
+ for (const addrs of perPeer) {
335
+ for (const addr of addrs) {
336
+ if (!seen.has(addr)) {
337
+ seen.add(addr);
338
+ union.push(addr);
339
+ }
340
+ }
341
+ }
342
+ return orderSignalingFirst(union);
343
+ }
344
+
345
+ /**
346
+ * Ask one sibling for its strand address, returning its multiaddrs or `[]` on any
347
+ * failure. Tries each dial target in order (peerId first to reuse an open control
348
+ * connection, then explicit addrs) until one answers; a total failure is logged
349
+ * and folded to `[]` so a single dead sibling never aborts the collection.
350
+ */
351
+ async function dialOneSibling(
352
+ node: Libp2p,
353
+ peer: StrandAddrPeer,
354
+ request: StrandAddrRequest,
355
+ options: CollectStrandAddrsOptions
356
+ ): Promise<string[]> {
357
+ const protocolId = options.protocolId ?? STRAND_ADDR_PROTOCOL;
358
+ const timeoutMs = options.timeoutMs ?? DEFAULT_ADDR_TIMEOUT_MS;
359
+ const targets = dialTargets(peer);
360
+
361
+ if (targets.length === 0) {
362
+ log('No dial target for sibling %s', peer.peerId);
363
+ return [];
364
+ }
365
+
366
+ for (const target of targets) {
367
+ try {
368
+ // One deadline per attempt: its signal aborts the in-flight dialProtocol and
369
+ // resets the live stream, so neither the connect nor the response-read leaks.
370
+ const response = await withDeadline(
371
+ timeoutMs,
372
+ `Strand-addr dial ${peer.peerId}`,
373
+ (signal) => sendStrandAddr(node, target, protocolId, request, timeoutMs, signal),
374
+ );
375
+ return response.multiaddrs;
376
+ } catch (err) {
377
+ log('Strand-addr dial to %s via %s failed: %o', peer.peerId, describeTarget(target), err);
378
+ }
379
+ }
380
+ return [];
381
+ }
382
+
383
+ /**
384
+ * Dial targets for a sibling, peerId first. Dialing by peerId lets libp2p reuse
385
+ * an already-open control connection (the common case — the wiring ticket passes
386
+ * connected siblings); the explicit control addrs are a fallback for when no
387
+ * connection is open. An unparsable peerId is skipped (rely on addrs).
388
+ */
389
+ function dialTargets(peer: StrandAddrPeer): Array<PeerId | Multiaddr> {
390
+ const targets: Array<PeerId | Multiaddr> = [];
391
+ try {
392
+ targets.push(peerIdFromString(peer.peerId));
393
+ } catch (err) {
394
+ log('Unparsable peer id %s, falling back to addrs: %o', peer.peerId, err);
395
+ }
396
+ if (peer.addrs) {
397
+ targets.push(...peer.addrs);
398
+ }
399
+ return targets;
400
+ }
401
+
402
+ /** Short label for a dial target (peerId or multiaddr) for logging. */
403
+ function describeTarget(target: PeerId | Multiaddr): string {
404
+ return target.toString();
405
+ }
406
+
407
+ /**
408
+ * Open one stream to a target, send the request, half-close, and read the
409
+ * response.
410
+ *
411
+ * `signal` is the per-attempt deadline from {@link dialOneSibling}: it goes to
412
+ * `dialProtocol` so a timeout during connect aborts the dial, and into
413
+ * {@link exchangeFrame} so a timeout after the stream is open resets it —
414
+ * releasing the otherwise unbounded response-read.
415
+ */
416
+ async function sendStrandAddr(
417
+ node: Libp2p,
418
+ target: PeerId | Multiaddr,
419
+ protocolId: string,
420
+ request: StrandAddrRequest,
421
+ timeoutMs: number,
422
+ signal: AbortSignal,
423
+ ): Promise<StrandAddrResponse> {
424
+ // `runOnLimitedConnection: true`: the sibling may be reachable only over a
425
+ // circuit-relay connection (the signaling-first addr), which libp2p marks
426
+ // "limited". The exchange is a single tiny request→response well within the
427
+ // relay's data/duration cap, so opening it on the limited connection is safe
428
+ // and is the whole point of dialing over the relay.
429
+ const rawStream = await node.dialProtocol(target, protocolId, { runOnLimitedConnection: true, signal });
430
+
431
+ const response = await exchangeFrame(
432
+ rawStream as unknown as ControlStream,
433
+ signal,
434
+ request,
435
+ (stream) => readFrame<StrandAddrResponse>(stream, timeoutMs),
436
+ 'Strand-addr dial aborted by timeout',
437
+ );
438
+
439
+ log('Strand-addr response: %d addr(s) for %s', response.multiaddrs.length, response.strandId);
440
+ return response;
441
+ }