@serfab/cadre-core 0.7.1 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +9 -8
  2. package/dist/authority-key.d.ts +41 -0
  3. package/dist/authority-key.js +52 -0
  4. package/dist/authority-key.js.map +1 -0
  5. package/dist/cadre-node.d.ts +770 -11
  6. package/dist/cadre-node.js +1900 -88
  7. package/dist/cadre-node.js.map +1 -1
  8. package/dist/canonical-datetime.d.ts +33 -0
  9. package/dist/canonical-datetime.js +38 -0
  10. package/dist/canonical-datetime.js.map +1 -0
  11. package/dist/canonical-json.d.ts +12 -0
  12. package/dist/canonical-json.js +33 -0
  13. package/dist/canonical-json.js.map +1 -0
  14. package/dist/control-cohort.d.ts +63 -0
  15. package/dist/control-cohort.js +80 -0
  16. package/dist/control-cohort.js.map +1 -0
  17. package/dist/control-database.d.ts +259 -5
  18. package/dist/control-database.js +541 -128
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +89 -0
  21. package/dist/control-formation-recorder.js +139 -0
  22. package/dist/control-formation-recorder.js.map +1 -0
  23. package/dist/control-schema.d.ts +12 -0
  24. package/dist/control-schema.js +199 -0
  25. package/dist/control-schema.js.map +1 -0
  26. package/dist/control-stream.d.ts +54 -0
  27. package/dist/control-stream.js +104 -0
  28. package/dist/control-stream.js.map +1 -0
  29. package/dist/device-token.d.ts +50 -0
  30. package/dist/device-token.js +66 -0
  31. package/dist/device-token.js.map +1 -0
  32. package/dist/diagnostics/connection-path.d.ts +118 -0
  33. package/dist/diagnostics/connection-path.js +204 -0
  34. package/dist/diagnostics/connection-path.js.map +1 -0
  35. package/dist/diagnostics/webrtc-turn-tracker.d.ts +50 -0
  36. package/dist/diagnostics/webrtc-turn-tracker.js +196 -0
  37. package/dist/diagnostics/webrtc-turn-tracker.js.map +1 -0
  38. package/dist/hibernation-manager.d.ts +79 -0
  39. package/dist/hibernation-manager.js +173 -23
  40. package/dist/hibernation-manager.js.map +1 -1
  41. package/dist/index.d.ts +25 -4
  42. package/dist/index.js +59 -4
  43. package/dist/index.js.map +1 -1
  44. package/dist/key-store-file.d.ts +52 -0
  45. package/dist/key-store-file.js +194 -0
  46. package/dist/key-store-file.js.map +1 -0
  47. package/dist/key-store.d.ts +75 -0
  48. package/dist/key-store.js +66 -0
  49. package/dist/key-store.js.map +1 -0
  50. package/dist/peer-authorization.d.ts +26 -0
  51. package/dist/peer-authorization.js +40 -0
  52. package/dist/peer-authorization.js.map +1 -0
  53. package/dist/peer-record.d.ts +89 -0
  54. package/dist/peer-record.js +117 -0
  55. package/dist/peer-record.js.map +1 -0
  56. package/dist/push-credentials.d.ts +34 -0
  57. package/dist/push-credentials.js +81 -0
  58. package/dist/push-credentials.js.map +1 -0
  59. package/dist/push-fanout.d.ts +137 -0
  60. package/dist/push-fanout.js +197 -0
  61. package/dist/push-fanout.js.map +1 -0
  62. package/dist/push-notifier-apns.d.ts +53 -0
  63. package/dist/push-notifier-apns.js +195 -0
  64. package/dist/push-notifier-apns.js.map +1 -0
  65. package/dist/push-notifier-fcm.d.ts +38 -0
  66. package/dist/push-notifier-fcm.js +183 -0
  67. package/dist/push-notifier-fcm.js.map +1 -0
  68. package/dist/push-notifier-shared.d.ts +18 -0
  69. package/dist/push-notifier-shared.js +25 -0
  70. package/dist/push-notifier-shared.js.map +1 -0
  71. package/dist/push-notifier.d.ts +71 -0
  72. package/dist/push-notifier.js +50 -0
  73. package/dist/push-notifier.js.map +1 -0
  74. package/dist/schema-verification.d.ts +11 -2
  75. package/dist/schema-verification.js +15 -4
  76. package/dist/schema-verification.js.map +1 -1
  77. package/dist/seed-bootstrap.d.ts +197 -9
  78. package/dist/seed-bootstrap.js +396 -137
  79. package/dist/seed-bootstrap.js.map +1 -1
  80. package/dist/seed-trust-policy.d.ts +63 -0
  81. package/dist/seed-trust-policy.js +56 -0
  82. package/dist/seed-trust-policy.js.map +1 -0
  83. package/dist/strand-addr-protocol.d.ts +132 -0
  84. package/dist/strand-addr-protocol.js +313 -0
  85. package/dist/strand-addr-protocol.js.map +1 -0
  86. package/dist/strand-cohort.d.ts +54 -0
  87. package/dist/strand-cohort.js +38 -0
  88. package/dist/strand-cohort.js.map +1 -0
  89. package/dist/strand-database.d.ts +54 -6
  90. package/dist/strand-database.js +88 -100
  91. package/dist/strand-database.js.map +1 -1
  92. package/dist/strand-formation-manager.d.ts +79 -19
  93. package/dist/strand-formation-manager.js +196 -104
  94. package/dist/strand-formation-manager.js.map +1 -1
  95. package/dist/strand-formation-protocol.d.ts +162 -0
  96. package/dist/strand-formation-protocol.js +279 -0
  97. package/dist/strand-formation-protocol.js.map +1 -0
  98. package/dist/strand-instance-manager.d.ts +73 -4
  99. package/dist/strand-instance-manager.js +167 -41
  100. package/dist/strand-instance-manager.js.map +1 -1
  101. package/dist/strand-member-key.d.ts +29 -0
  102. package/dist/strand-member-key.js +38 -0
  103. package/dist/strand-member-key.js.map +1 -0
  104. package/dist/strand-member-registry.d.ts +98 -0
  105. package/dist/strand-member-registry.js +129 -0
  106. package/dist/strand-member-registry.js.map +1 -0
  107. package/dist/strand-membership-writer.d.ts +361 -0
  108. package/dist/strand-membership-writer.js +449 -0
  109. package/dist/strand-membership-writer.js.map +1 -0
  110. package/dist/strand-solicitation.d.ts +77 -2
  111. package/dist/strand-solicitation.js +25 -4
  112. package/dist/strand-solicitation.js.map +1 -1
  113. package/dist/strand-wake-payload.d.ts +30 -0
  114. package/dist/strand-wake-payload.js +20 -0
  115. package/dist/strand-wake-payload.js.map +1 -0
  116. package/dist/strand-wake-protocol.d.ts +114 -0
  117. package/dist/strand-wake-protocol.js +257 -0
  118. package/dist/strand-wake-protocol.js.map +1 -0
  119. package/dist/strand-watcher.d.ts +6 -2
  120. package/dist/strand-watcher.js +57 -17
  121. package/dist/strand-watcher.js.map +1 -1
  122. package/dist/types.d.ts +406 -23
  123. package/dist/types.js +22 -5
  124. package/dist/types.js.map +1 -1
  125. package/package.json +14 -8
  126. package/src/authority-key.ts +68 -0
  127. package/src/cadre-node.ts +2937 -948
  128. package/src/canonical-datetime.ts +39 -0
  129. package/src/canonical-json.ts +30 -0
  130. package/src/control-cohort.ts +103 -0
  131. package/src/control-database.ts +931 -383
  132. package/src/control-formation-recorder.ts +151 -0
  133. package/src/control-schema.ts +198 -0
  134. package/src/control-stream.ts +128 -0
  135. package/src/device-token.ts +89 -0
  136. package/src/diagnostics/connection-path.ts +277 -0
  137. package/src/diagnostics/webrtc-turn-tracker.ts +222 -0
  138. package/src/hibernation-manager.ts +197 -28
  139. package/src/index.ts +273 -79
  140. package/src/key-store-file.ts +203 -0
  141. package/src/key-store.ts +99 -0
  142. package/src/peer-authorization.ts +53 -0
  143. package/src/peer-record.ts +146 -0
  144. package/src/push-credentials.ts +84 -0
  145. package/src/push-fanout.ts +272 -0
  146. package/src/push-notifier-apns.ts +243 -0
  147. package/src/push-notifier-fcm.ts +221 -0
  148. package/src/push-notifier-shared.ts +28 -0
  149. package/src/push-notifier.ts +93 -0
  150. package/src/schema-verification.ts +18 -4
  151. package/src/seed-bootstrap.ts +464 -188
  152. package/src/seed-trust-policy.ts +107 -0
  153. package/src/strand-addr-protocol.ts +410 -0
  154. package/src/strand-cohort.ts +77 -0
  155. package/src/strand-database.ts +113 -141
  156. package/src/strand-formation-manager.ts +233 -142
  157. package/src/strand-formation-protocol.ts +391 -0
  158. package/src/strand-instance-manager.ts +207 -56
  159. package/src/strand-member-key.ts +39 -0
  160. package/src/strand-member-registry.ts +177 -0
  161. package/src/strand-membership-writer.ts +640 -0
  162. package/src/strand-solicitation.ts +93 -4
  163. package/src/strand-wake-payload.ts +32 -0
  164. package/src/strand-wake-protocol.ts +331 -0
  165. package/src/strand-watcher.ts +61 -17
  166. package/src/types.ts +1012 -582
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Trust-anchor policy for control-network seeds.
3
+ *
4
+ * A seed carries an ed25519 signature over its body and the `signerKey` that
5
+ * produced it. Verifying that signature only proves the seed is internally
6
+ * consistent — it does NOT prove the signer is an authority, because both the
7
+ * signer key and the seed's own `isAuthority` peer flags are attacker-supplied.
8
+ * The trust decision must therefore rest on an anchor that does not come from
9
+ * the seed body:
10
+ *
11
+ * 1. DB-anchored — keys already in the receiver's `CadreControl.AuthorityKey`
12
+ * table (steady state: the node is enrolled / has synced control state).
13
+ * 2. Pinned out-of-band — keys handed to the node from outside the seed
14
+ * (carried by a `CadreInvite.authorityKeys`, or pinned by an operator).
15
+ * 3. TOFU (opt-in) — an explicit confirmation callback invoked on first sight
16
+ * of an unknown signer key. Interactive hosts only; off by default.
17
+ *
18
+ * Secure default (`dbAnchoredTrustPolicy`): a cold-start node with an empty
19
+ * `AuthorityKey` table and no pinned keys rejects the seed — a seed can no
20
+ * longer vouch for its own signer.
21
+ */
22
+ export interface SeedTrustContext {
23
+ /** Party the seed claims to belong to. */
24
+ partyId: string;
25
+ /** ed25519 base64url signer key — already signature-verified by `applySeed`. */
26
+ signerKey: string;
27
+ /**
28
+ * The receiver's known authority keys, sourced from its `AuthorityKey`
29
+ * table — NOT from the seed. Empty for a cold-start node.
30
+ */
31
+ knownAuthorityKeys: ReadonlySet<string>;
32
+ }
33
+
34
+ export interface SeedTrustDecision {
35
+ /** Whether the signer key is trusted. */
36
+ trusted: boolean;
37
+ /** Human-readable reason, surfaced as the seed-apply error when not trusted. */
38
+ reason?: string;
39
+ }
40
+
41
+ /**
42
+ * Decides whether a signature-verified seed's signer key should be trusted.
43
+ * May be synchronous (DB/pinned anchors) or asynchronous (TOFU confirmation).
44
+ */
45
+ export interface SeedTrustPolicy {
46
+ evaluate(ctx: SeedTrustContext): Promise<SeedTrustDecision> | SeedTrustDecision;
47
+ }
48
+
49
+ /**
50
+ * Default policy: trust only keys already present in the receiver's
51
+ * `AuthorityKey` table. A cold-start node (empty table) rejects every seed.
52
+ */
53
+ export function dbAnchoredTrustPolicy(): SeedTrustPolicy {
54
+ return {
55
+ evaluate({ signerKey, knownAuthorityKeys }) {
56
+ if (knownAuthorityKeys.has(signerKey)) {
57
+ return { trusted: true };
58
+ }
59
+ return {
60
+ trusted: false,
61
+ reason: 'Signer key is not a known authority (DB-anchored trust policy)',
62
+ };
63
+ },
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Cold-start policy: trust keys in the receiver's `AuthorityKey` table plus a
69
+ * set pinned out-of-band (typically `CadreInvite.authorityKeys` or operator
70
+ * config). Lets an unenrolled invitee accept its first seed without the seed
71
+ * vouching for itself.
72
+ */
73
+ export function pinnedKeyTrustPolicy(pinned: Iterable<string>): SeedTrustPolicy {
74
+ const pinnedSet = new Set(pinned);
75
+ return {
76
+ evaluate({ signerKey, knownAuthorityKeys }) {
77
+ if (knownAuthorityKeys.has(signerKey) || pinnedSet.has(signerKey)) {
78
+ return { trusted: true };
79
+ }
80
+ return {
81
+ trusted: false,
82
+ reason: 'Signer key is neither a known nor a pinned authority (pinned-key trust policy)',
83
+ };
84
+ },
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Opt-in interactive policy: trust keys already in the `AuthorityKey` table,
90
+ * and on an unknown key invoke `confirm` (e.g. a trust-circle UI prompt). The
91
+ * key is trusted iff `confirm` resolves true. Not enabled by default.
92
+ */
93
+ export function tofuTrustPolicy(
94
+ confirm: (ctx: SeedTrustContext) => Promise<boolean>
95
+ ): SeedTrustPolicy {
96
+ return {
97
+ async evaluate(ctx) {
98
+ if (ctx.knownAuthorityKeys.has(ctx.signerKey)) {
99
+ return { trusted: true };
100
+ }
101
+ const accepted = await confirm(ctx);
102
+ return accepted
103
+ ? { trusted: true }
104
+ : { trusted: false, reason: 'TOFU confirmation declined for unknown signer key' };
105
+ },
106
+ };
107
+ }
@@ -0,0 +1,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>`) 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
+ }
@@ -0,0 +1,77 @@
1
+ import type { StrandMode } from './types.js';
2
+
3
+ /**
4
+ * A single CadrePeer membership row, as returned by
5
+ * `ControlDatabase.queryCadrePeers()`.
6
+ */
7
+ export interface CohortPeerRow {
8
+ peerId: string;
9
+ /** Comma-joined list of multiaddr strings; `''` when no addrs were recorded. */
10
+ multiaddr: string | null;
11
+ }
12
+
13
+ /**
14
+ * Cohort-derived discovery seed for a strand's libp2p node. `bootstrapNodes`
15
+ * here are **strand-network** addresses resolved on demand from co-cadre
16
+ * siblings (see `collectStrandAddrs` / `STRAND_ADDR_PROTOCOL`), NOT the control
17
+ * addresses stored in `CadrePeer.Multiaddr`.
18
+ */
19
+ export interface CohortSeed {
20
+ /** Dialable strand-network multiaddr strings for cohort peers other than self (deduplicated). */
21
+ bootstrapNodes: string[];
22
+ /** True when at least one CadrePeer row other than self exists (even if it has no resolvable strand addr). */
23
+ hasOtherPeers: boolean;
24
+ }
25
+
26
+ /**
27
+ * Membership-only view of a strand's cohort, derived from the control network's
28
+ * CadrePeer rows. The bootstrap addresses themselves are resolved separately
29
+ * (over the strand-addr RPC) from these peerIds, never from the rows' addr field.
30
+ */
31
+ export interface CohortMembers {
32
+ /** PeerIds of cohort members other than self — the strand-addr RPC fan-out targets (deduplicated, in row order). */
33
+ otherPeerIds: string[];
34
+ /** True when at least one CadrePeer row other than self exists (even if it has no resolvable strand addr). */
35
+ hasOtherPeers: boolean;
36
+ }
37
+
38
+ /**
39
+ * Derive the membership view of a strand's cohort from the control network's
40
+ * CadrePeer rows: the peerIds of members other than `selfPeerId` (the strand-addr
41
+ * RPC fan-out targets) and whether any other member exists at all.
42
+ *
43
+ * Deliberately does NOT read `CadrePeer.Multiaddr` — that field carries each
44
+ * node's *control*-network address, which must not seed the *strand* mesh
45
+ * (dialing it reaches the remote's control instance, not its strand instance).
46
+ * The strand-network bootstrap addresses are resolved on demand over the control
47
+ * mesh from these peerIds. `hasOtherPeers` reflects membership presence, NOT
48
+ * dialability, so a cohort whose strand addrs are not yet resolvable still
49
+ * selects `networked` mode.
50
+ */
51
+ export function deriveCohortMembers(peers: CohortPeerRow[], selfPeerId?: string): CohortMembers {
52
+ const otherPeerIds: string[] = [];
53
+ const seen = new Set<string>();
54
+
55
+ for (const peer of peers) {
56
+ if (selfPeerId !== undefined && peer.peerId === selfPeerId) {
57
+ continue;
58
+ }
59
+ if (seen.has(peer.peerId)) {
60
+ continue;
61
+ }
62
+ seen.add(peer.peerId);
63
+ otherPeerIds.push(peer.peerId);
64
+ }
65
+
66
+ return { otherPeerIds, hasOtherPeers: otherPeerIds.length > 0 };
67
+ }
68
+
69
+ /**
70
+ * Choose the strand mode. An explicit mode (from `addStrand`) always wins. When
71
+ * omitted (the `handleStrandAdded` discovery path, or an `addStrand` caller that
72
+ * leaves it unset), infer: `bootstrap` for a solo/first node (no other peers),
73
+ * `networked` once the cohort has other members.
74
+ */
75
+ export function selectStrandMode(explicitMode: StrandMode | undefined, hasOtherPeers: boolean): StrandMode {
76
+ return explicitMode ?? (hasOtherPeers ? 'networked' : 'bootstrap');
77
+ }