@serfab/cadre-core 0.11.0 → 0.13.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 (121) hide show
  1. package/README.md +3 -2
  2. package/dist/announce-addrs.d.ts +49 -0
  3. package/dist/announce-addrs.js +78 -0
  4. package/dist/announce-addrs.js.map +1 -0
  5. package/dist/cadre-node.d.ts +607 -53
  6. package/dist/cadre-node.js +1268 -157
  7. package/dist/cadre-node.js.map +1 -1
  8. package/dist/control-database.d.ts +174 -23
  9. package/dist/control-database.js +317 -107
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-read-retry.d.ts +103 -0
  12. package/dist/control-read-retry.js +145 -0
  13. package/dist/control-read-retry.js.map +1 -0
  14. package/dist/control-retry.d.ts +101 -0
  15. package/dist/control-retry.js +108 -0
  16. package/dist/control-retry.js.map +1 -0
  17. package/dist/control-schema.d.ts +1 -1
  18. package/dist/control-schema.js +50 -6
  19. package/dist/control-schema.js.map +1 -1
  20. package/dist/control-write-retry.d.ts +59 -35
  21. package/dist/control-write-retry.js +21 -92
  22. package/dist/control-write-retry.js.map +1 -1
  23. package/dist/delegate-admission.d.ts +17 -15
  24. package/dist/delegate-admission.js +17 -15
  25. package/dist/delegate-admission.js.map +1 -1
  26. package/dist/enrolled-machine-store-file.d.ts +13 -0
  27. package/dist/enrolled-machine-store-file.js +41 -0
  28. package/dist/enrolled-machine-store-file.js.map +1 -0
  29. package/dist/enrolled-machine-store.d.ts +81 -0
  30. package/dist/enrolled-machine-store.js +225 -0
  31. package/dist/enrolled-machine-store.js.map +1 -0
  32. package/dist/file-durable-slot.js +5 -3
  33. package/dist/file-durable-slot.js.map +1 -1
  34. package/dist/index.d.ts +10 -6
  35. package/dist/index.js +39 -12
  36. package/dist/index.js.map +1 -1
  37. package/dist/membership-connection-gater.d.ts +226 -26
  38. package/dist/membership-connection-gater.js +316 -30
  39. package/dist/membership-connection-gater.js.map +1 -1
  40. package/dist/node-local-snapshot.d.ts +6 -0
  41. package/dist/node-local-snapshot.js +7 -1
  42. package/dist/node-local-snapshot.js.map +1 -1
  43. package/dist/{strand-backfill.d.ts → peer-join-backfill.d.ts} +49 -20
  44. package/dist/{strand-backfill.js → peer-join-backfill.js} +146 -56
  45. package/dist/peer-join-backfill.js.map +1 -0
  46. package/dist/peer-record.d.ts +26 -0
  47. package/dist/peer-record.js +32 -0
  48. package/dist/peer-record.js.map +1 -1
  49. package/dist/relay-addrs.d.ts +145 -22
  50. package/dist/relay-addrs.js +314 -31
  51. package/dist/relay-addrs.js.map +1 -1
  52. package/dist/relay-reservation.d.ts +20 -15
  53. package/dist/relay-reservation.js +18 -14
  54. package/dist/relay-reservation.js.map +1 -1
  55. package/dist/strand-addr-protocol.js +16 -0
  56. package/dist/strand-addr-protocol.js.map +1 -1
  57. package/dist/strand-database.d.ts +12 -0
  58. package/dist/strand-database.js +16 -0
  59. package/dist/strand-database.js.map +1 -1
  60. package/dist/strand-formation-manager.d.ts +22 -9
  61. package/dist/strand-formation-manager.js +20 -12
  62. package/dist/strand-formation-manager.js.map +1 -1
  63. package/dist/strand-formation-protocol.d.ts +83 -9
  64. package/dist/strand-formation-protocol.js +86 -10
  65. package/dist/strand-formation-protocol.js.map +1 -1
  66. package/dist/strand-instance-manager.d.ts +151 -17
  67. package/dist/strand-instance-manager.js +237 -32
  68. package/dist/strand-instance-manager.js.map +1 -1
  69. package/dist/strand-membership-writer.d.ts +118 -14
  70. package/dist/strand-membership-writer.js +203 -15
  71. package/dist/strand-membership-writer.js.map +1 -1
  72. package/dist/strand-network-config.d.ts +84 -0
  73. package/dist/strand-network-config.js +136 -0
  74. package/dist/strand-network-config.js.map +1 -0
  75. package/dist/strand-revocation-enforcer.d.ts +392 -0
  76. package/dist/strand-revocation-enforcer.js +533 -0
  77. package/dist/strand-revocation-enforcer.js.map +1 -0
  78. package/dist/strand-solicitation.d.ts +10 -3
  79. package/dist/strand-solicitation.js +12 -7
  80. package/dist/strand-solicitation.js.map +1 -1
  81. package/dist/strand-wake-protocol.d.ts +47 -2
  82. package/dist/strand-wake-protocol.js +76 -6
  83. package/dist/strand-wake-protocol.js.map +1 -1
  84. package/dist/strand-watcher.js +6 -1
  85. package/dist/strand-watcher.js.map +1 -1
  86. package/dist/types.d.ts +282 -43
  87. package/dist/types.js +7 -1
  88. package/dist/types.js.map +1 -1
  89. package/package.json +16 -8
  90. package/src/announce-addrs.ts +93 -0
  91. package/src/cadre-node.ts +1366 -171
  92. package/src/control-database.ts +2628 -2406
  93. package/src/control-read-retry.ts +167 -0
  94. package/src/control-retry.ts +190 -0
  95. package/src/control-schema.ts +50 -6
  96. package/src/control-write-retry.ts +30 -130
  97. package/src/delegate-admission.ts +17 -15
  98. package/src/enrolled-machine-store-file.ts +43 -0
  99. package/src/enrolled-machine-store.ts +280 -0
  100. package/src/file-durable-slot.ts +5 -3
  101. package/src/index.ts +477 -407
  102. package/src/membership-connection-gater.ts +539 -204
  103. package/src/node-local-snapshot.ts +13 -1
  104. package/src/peer-addr-book.ts +251 -250
  105. package/src/{strand-backfill.ts → peer-join-backfill.ts} +187 -75
  106. package/src/peer-record.ts +33 -0
  107. package/src/relay-addrs.ts +436 -111
  108. package/src/relay-reservation.ts +828 -823
  109. package/src/strand-addr-protocol.ts +17 -0
  110. package/src/strand-database.ts +17 -0
  111. package/src/strand-formation-manager.ts +511 -491
  112. package/src/strand-formation-protocol.ts +808 -692
  113. package/src/strand-instance-manager.ts +899 -611
  114. package/src/strand-membership-writer.ts +232 -15
  115. package/src/strand-network-config.ts +172 -0
  116. package/src/strand-revocation-enforcer.ts +653 -0
  117. package/src/strand-solicitation.ts +484 -472
  118. package/src/strand-wake-protocol.ts +94 -8
  119. package/src/strand-watcher.ts +319 -314
  120. package/src/types.ts +1554 -1309
  121. package/dist/strand-backfill.js.map +0 -1
@@ -1,111 +1,436 @@
1
- /**
2
- * Translate `network.relayAddrs` — the operator-facing "use these relay servers"
3
- * setting — into the mechanism this repo already has for reserving a circuit-relay
4
- * slot: a `…/p2p/<relayPeerId>/p2p-circuit` entry in the node's listen addrs.
5
- *
6
- * `@libp2p/circuit-relay-v2`'s transport is always present on the Node path
7
- * (`../optimystic/packages/db-p2p/src/libp2p-node.ts` pushes `circuitRelayTransport()`
8
- * unconditionally), and listening on a relay's circuit addr is what makes libp2p dial
9
- * that relay and hold a reservation. Everything downstream of the listen list —
10
- * the reservation itself, `CadreNode.circuitRelayTargets()` picking delegate-announce
11
- * targets, strand nodes inheriting the listen addrs, the `/p2p-circuit`-first address
12
- * publishing in `registerSelf` — then works unchanged.
13
- *
14
- * So `relayAddrs` is a second, friendlier door onto an existing mechanism:
15
- *
16
- * effective listen addrs = listenAddrs ++ relayAddrs.map(a => a + '/p2p-circuit')
17
- *
18
- * NOTE: this is the FAIL-FAST route to a reservation — libp2p's transport manager
19
- * throws when a configured circuit listener cannot listen, so naming a relay that
20
- * is down means the node does not start. The fail-soft route is the bare
21
- * `/p2p-circuit` search listener driven by `relay-reservation.ts`. The two are
22
- * ALTERNATIVES, not layers: configuring `relayAddrs` on a node that already
23
- * reserves via the search listener adds the fatal listener back and the node
24
- * stops booting when its relay is down.
25
- */
26
-
27
- import { multiaddr, type Component } from '@multiformats/multiaddr';
28
- import { circuitRelayTargetOrThrow } from './delegate-admission.js';
29
- import type { NetworkConfig } from './types.js';
30
-
31
- /**
32
- * The direct listener a node keeps when it configures `relayAddrs` but no
33
- * `listenAddrs`. Without this, naming a relay would silently REPLACE the node's
34
- * direct TCP listener with a circuit-only one.
35
- *
36
- * NOTE: mirrors `createLibp2pNode`'s own default listen addr in
37
- * `../optimystic/packages/db-p2p/src/libp2p-node.ts` (`/ip4/0.0.0.0/tcp/<port>`,
38
- * and `CadreNode` passes `port: 0`) — that file is the source of truth. If it
39
- * ever changes its default, this constant has to follow.
40
- */
41
- const DEFAULT_DIRECT_LISTEN_ADDR = '/ip4/0.0.0.0/tcp/0';
42
-
43
- /**
44
- * The circuit-listen multiaddr for each configured relay: `<relayAddr>/p2p-circuit`.
45
- * An entry that already carries `/p2p-circuit` is passed through unchanged.
46
- * Throws on an entry that is unparsable or names no relay peerId — this is
47
- * operator configuration, so a typo must fail loudly at start rather than
48
- * silently costing the node its reachability.
49
- *
50
- * Deliberately unlike `extractCircuitRelayTargets` (`delegate-admission.ts`), which
51
- * SKIPS a bad entry: that one reads addresses discovered at runtime from peers, where
52
- * one bad entry must not be fatal.
53
- */
54
- export function relayCircuitAddrs(relayAddrs: readonly string[]): string[] {
55
- return dedupe(relayAddrs.map(circuitListenAddr));
56
- }
57
-
58
- /**
59
- * The listen multiaddrs a node actually binds: configured `listenAddrs` plus the
60
- * circuit-listen addr of every configured relay, deduplicated, order-stable
61
- * (configured entries first). Returns `undefined` when neither field is set, so
62
- * callers keep omitting `listenAddrs` and inherit db-p2p's default.
63
- */
64
- export function resolveListenAddrs(network: NetworkConfig | undefined): string[] | undefined {
65
- const circuits = relayCircuitAddrs(network?.relayAddrs ?? []);
66
- const listenAddrs = network?.listenAddrs;
67
- if (!listenAddrs && circuits.length === 0) {
68
- return undefined;
69
- }
70
- // An explicitly empty `listenAddrs` (the React Native "cannot listen" case) stays
71
- // empty — but a relay named alongside it still gets its circuit listener, since
72
- // acquiring one is the whole point of configuring a relay.
73
- return dedupe([...(listenAddrs ?? [DEFAULT_DIRECT_LISTEN_ADDR]), ...circuits]);
74
- }
75
-
76
- /**
77
- * One entry of {@link relayCircuitAddrs}: the addr the node listens on for this relay.
78
- *
79
- * NOTE: an entry carrying components AFTER `/p2p-circuit` — a full relayed DIAL addr,
80
- * `…/p2p/<relay>/p2p-circuit/p2p/<someone else>` — is passed through as written and
81
- * would be listened on verbatim. It validates (the relay it names is real), so only an
82
- * operator who pastes a peer's relayed address into `relayAddrs` hits it; if that turns
83
- * out to be a common paste, truncate at the `/p2p-circuit` component here.
84
- */
85
- function circuitListenAddr(relayAddr: string): string {
86
- const alreadyCircuit = parseComponents(relayAddr).some((c) => c.name === 'p2p-circuit');
87
- const listenAddr = alreadyCircuit ? relayAddr : `${relayAddr}/p2p-circuit`;
88
- try {
89
- circuitRelayTargetOrThrow(listenAddr); // validates the relay peerId
90
- } catch (err) {
91
- throw new Error(
92
- `network.relayAddrs entry names no relay peerId (expected <dial addr>/p2p/<relayPeerId>): ${relayAddr}`,
93
- { cause: err }
94
- );
95
- }
96
- return listenAddr;
97
- }
98
-
99
- /** Multiaddr components of `relayAddr`, with the config field named on a parse failure. */
100
- function parseComponents(relayAddr: string): Component[] {
101
- try {
102
- return multiaddr(relayAddr).getComponents();
103
- } catch (err) {
104
- throw new Error(`network.relayAddrs entry is not a valid multiaddr: ${relayAddr}`, { cause: err });
105
- }
106
- }
107
-
108
- /** Exact-string dedupe, first occurrence wins, so the list is stable across restarts. */
109
- function dedupe(addrs: readonly string[]): string[] {
110
- return [...new Set(addrs)];
111
- }
1
+ /**
2
+ * Translate `network.relayAddrs` — the operator-facing "use these relay servers"
3
+ * setting — into the listen entry a node needs before it can hold a circuit-relay
4
+ * slot, and validate the operator's entries while doing it.
5
+ *
6
+ * `@libp2p/circuit-relay-v2`'s listener branches on the SHAPE of the listen addr,
7
+ * and the same `relayAddrs` list resolves to either shape depending on WHO is
8
+ * listening ({@link RelayListenRoute}):
9
+ *
10
+ * | route | listen entry | libp2p behaviour |
11
+ * | -------------- | ------------------------------------------- | --------------------------------------------------------- |
12
+ * | `'configured'` | `<relayAddr>/p2p-circuit`, one per relay | dial that relay from inside `listen()` and reserve, or throw |
13
+ * | `'search'` | a single bare `/p2p-circuit` | register a pending reservation; open no connection |
14
+ *
15
+ * The CONTROL node takes the `'search'` route, and `CadreNode.start()` drives the
16
+ * reservation explicitly (`relay-reservation.ts`) once the control database is up.
17
+ * That ordering is the point: a configured circuit listener dials the relay from
18
+ * inside `libp2p.start()`, so the control database was being built while a sibling
19
+ * relay was already in this node's cohort — and a sibling that has not yet
20
+ * replicated this node's `CadrePeer` row correctly refuses its control-DB streams,
21
+ * which killed `start()` outright. See `cadre-node.ts` → `start()`.
22
+ *
23
+ * STRAND nodes keep the `'configured'` route (`strand-instance-manager.ts`): they
24
+ * inherit the control node's `NetworkConfig`, nothing drives an explicit
25
+ * reservation for them, and their relay connection cannot disturb a control-DB
26
+ * bring-up (a strand node's protocol ids are namespaced `/optimystic/strand-<id>/…`,
27
+ * so the relay is never in its cohort).
28
+ *
29
+ * `network.relayAddrs` is FAIL-FAST for the operator on both routes, just from
30
+ * different places: a malformed entry throws here at config resolution, and on the
31
+ * control node a first reservation attempt that does not land throws out of
32
+ * `start()` (`RelayReservationFailedError`). Naming a relay that is down still
33
+ * means the node does not come up.
34
+ *
35
+ * The bare `/p2p-circuit` search listener cannot open a connection on its own:
36
+ * libp2p fills a pending reservation from `RelayDiscovery`, which nominates a peer
37
+ * only once the relay-hop protocol id is in that peer's peer-store protocol list,
38
+ * and that list is written exclusively by IDENTIFY — which `@optimystic/db-p2p`
39
+ * namespaces per network, so a cadre node and a stock relay never identify each
40
+ * other. See `relay-reservation.ts`'s module doc and `docs/architecture.md`.
41
+ */
42
+
43
+ import { multiaddr, type Component } from '@multiformats/multiaddr';
44
+ import { circuitRelayTargetOrThrow } from './delegate-admission.js';
45
+ import type { NetworkConfig } from './types.js';
46
+ import type { RelayReservationState } from './relay-reservation.js';
47
+
48
+ /**
49
+ * The direct listener a node keeps when it configures `relayAddrs` but no
50
+ * `listenAddrs`. Without this, naming a relay would silently REPLACE the node's
51
+ * direct TCP listener with a circuit-only one.
52
+ *
53
+ * NOTE: mirrors `createLibp2pNode`'s own default listen addr in
54
+ * `../optimystic/packages/db-p2p/src/libp2p-node.ts` (`/ip4/0.0.0.0/tcp/<port>`,
55
+ * and `CadreNode` passes `port: 0`) — that file is the source of truth. If it
56
+ * ever changes its default, this constant has to follow.
57
+ */
58
+ const DEFAULT_DIRECT_LISTEN_ADDR = '/ip4/0.0.0.0/tcp/0';
59
+
60
+ /**
61
+ * libp2p's relay SEARCH listener: registers one pending reservation and dials
62
+ * nothing. One entry covers every configured relay — the pending reservation is
63
+ * per-listener, not per-relay, and `relay-reservation.ts` fills it with whichever
64
+ * relay answers first.
65
+ */
66
+ export const RELAY_SEARCH_LISTEN_ADDR = '/p2p-circuit';
67
+
68
+ /**
69
+ * Which listener shape `network.relayAddrs` resolves to for this caller — see the
70
+ * table in the module doc. Defaults to `'configured'` everywhere except the
71
+ * control node's own libp2p options.
72
+ */
73
+ export type RelayListenRoute = 'configured' | 'search';
74
+
75
+ /**
76
+ * The circuit-listen multiaddr for each configured relay: `<relayAddr>/p2p-circuit`.
77
+ * An entry that already carries `/p2p-circuit` is passed through unchanged.
78
+ * Throws on an entry that is unparsable or names no relay peerId — this is
79
+ * operator configuration, so a typo must fail loudly at start rather than
80
+ * silently costing the node its reachability.
81
+ *
82
+ * Deliberately unlike `extractCircuitRelayTargets` (`delegate-admission.ts`), which
83
+ * SKIPS a bad entry: that one reads addresses discovered at runtime from peers, where
84
+ * one bad entry must not be fatal.
85
+ */
86
+ export function relayCircuitAddrs(relayAddrs: readonly string[]): string[] {
87
+ return dedupe(relayAddrs.map(circuitListenAddr));
88
+ }
89
+
90
+ /**
91
+ * The listen multiaddrs a node actually binds: configured `listenAddrs` plus the
92
+ * relay listen entry `route` calls for, deduplicated, order-stable (configured
93
+ * entries first). Returns `undefined` when neither field is set, so callers keep
94
+ * omitting `listenAddrs` and inherit db-p2p's default.
95
+ *
96
+ * Every `relayAddrs` entry is validated on BOTH routes — the `'search'` route
97
+ * discards the resolved circuit addrs, but an operator typo must fail at config
98
+ * resolution either way.
99
+ */
100
+ export function resolveListenAddrs(
101
+ network: NetworkConfig | undefined,
102
+ route: RelayListenRoute = 'configured'
103
+ ): string[] | undefined {
104
+ const configured = relayCircuitAddrs(network?.relayAddrs ?? []);
105
+ const relayEntries = route === 'search'
106
+ ? (configured.length > 0 ? [RELAY_SEARCH_LISTEN_ADDR] : [])
107
+ : configured;
108
+ const listenAddrs = network?.listenAddrs;
109
+ if (route === 'search') {
110
+ rejectConfiguredCircuitListenAddrs(listenAddrs ?? []);
111
+ }
112
+ if (!listenAddrs && relayEntries.length === 0) {
113
+ return undefined;
114
+ }
115
+ // An explicitly empty `listenAddrs` (the React Native "cannot listen" case) stays
116
+ // empty — but a relay named alongside it still gets its listen entry, since
117
+ // acquiring a slot is the whole point of configuring a relay.
118
+ return dedupe([...(listenAddrs ?? [DEFAULT_DIRECT_LISTEN_ADDR]), ...relayEntries]);
119
+ }
120
+
121
+ /**
122
+ * The transport-derived `createLibp2pNode` options a resolved listen set implies —
123
+ * see {@link resolveTransportOptions}.
124
+ */
125
+ export interface ListenTransportOptions {
126
+ /**
127
+ * Present when some listen entry names WebSocket. Its VALUE is never bound; it is
128
+ * the switch that makes `@optimystic/db-p2p` add `webSockets()` — see
129
+ * {@link WS_TRANSPORT_SWITCH_PORT}.
130
+ */
131
+ wsPort?: number;
132
+ }
133
+
134
+ /**
135
+ * The `wsPort` value passed purely to turn `@optimystic/db-p2p`'s WebSocket transport
136
+ * ON. It is never bound, so it is deliberately `0` rather than a port scraped from a
137
+ * listen entry.
138
+ *
139
+ * WHY it is a switch and not a port: `createLibp2pNode`
140
+ * (`../optimystic/packages/db-p2p/src/libp2p-node.ts`) feeds `wsPort` into BOTH its
141
+ * default transports and its default listen addrs, and `createLibp2pNodeBase`
142
+ * (`libp2p-node-base.ts:490-491`) falls back to those two defaults INDEPENDENTLY:
143
+ *
144
+ * ```ts
145
+ * const listenAddrs = options.listenAddrs ?? defaults.listenAddrs;
146
+ * const transports = options.transports ?? defaults.transports;
147
+ * ```
148
+ *
149
+ * `cadre-core` always supplies explicit `listenAddrs` alongside it, so the synthesized
150
+ * `/ip4/<wsHost>/tcp/<wsPort>/ws` default ADDRESS is discarded while the `webSockets()`
151
+ * transport it added survives. A scraped port would also be a lie whenever a config
152
+ * names several WebSocket addresses on different ports, and the strand path rewrites
153
+ * fixed ports to `0` regardless (`strand-network-config.ts`).
154
+ *
155
+ * NOTE: db-p2p's own doc comment on `wsPort` (`libp2p-node-base.ts:170-172`) says it is
156
+ * "Ignored when `transports`/`listenAddrs` are explicitly provided" — true of the
157
+ * address half, NOT of the transport half, which is the half this depends on. Re-verify
158
+ * empirically rather than trusting that comment: `test/listen-transport-options.spec.ts`
159
+ * boots a real node and asserts a `/ws` multiaddr appears. If db-p2p ever makes the
160
+ * comment true of both halves, it needs an explicit `enableWebSockets` switch and this
161
+ * constant becomes unusable.
162
+ */
163
+ const WS_TRANSPORT_SWITCH_PORT = 0;
164
+
165
+ /**
166
+ * The transport-derived libp2p options `listenAddrs` implies, and the gate that stops a
167
+ * listen address the node has no transport for from being SILENTLY dropped.
168
+ *
169
+ * libp2p's transport manager sorts configured listen addresses by which transport claims
170
+ * them, discards the unclaimed ones, and raises `UnsupportedListenAddressesError` only
171
+ * when EVERY address was discarded. Pair a TCP address with a WebSocket one — which is
172
+ * exactly what the shipped configs do — and the TCP address carries the start while the
173
+ * missing WebSocket listener is never reported. Two halves of `NetworkConfig` that have
174
+ * to agree (`listenAddrs`, and the transports the node will actually have) were never
175
+ * checked against each other; this is that check, and it covers both node kinds because
176
+ * both resolve their listen set through {@link resolveListenAddrs}.
177
+ *
178
+ * The two transport classes are handled differently, on purpose:
179
+ *
180
+ * - **WebSocket is DERIVED.** It is the one non-TCP transport the shipped configs need
181
+ * (the React Native reference app's companion drone; `cadre start --ws-port`), and
182
+ * `@optimystic/db-p2p` already knows how to add it. `cadre-core` grows no dependency
183
+ * and decides no transport policy — it flips db-p2p's own switch
184
+ * ({@link WS_TRANSPORT_SWITCH_PORT}).
185
+ * - **Everything else is REFUSED.** Deriving `/quic-v1`, `/webrtc` or `/webtransport`
186
+ * would mean importing transport packages into every `cadre-core` consumer including
187
+ * the React Native and browser bundles (against the cross-platform rule in
188
+ * `AGENTS.md`) and duplicating policy `libp2p-node.ts` owns. So name the address, name
189
+ * the transport it needs, and refuse to start — matching how `network.relayAddrs` and
190
+ * `network.announceAddrs` already treat an operator typo.
191
+ *
192
+ * Returns `{}` unconditionally when `network.transports` is set: a programmatic embedder
193
+ * supplying transport factories owns the policy, and the factories are opaque — nothing
194
+ * can be inferred from them. That is what keeps the RN phone, the web app, and the
195
+ * integration-test harness unaffected.
196
+ *
197
+ * NOTE: pairing this with {@link resolveListenAddrs} is a CONVENTION, not a structure —
198
+ * a third libp2p-node build site could resolve listen addrs and forget to call this,
199
+ * putting the original bug back on that path. Both existing sites are covered
200
+ * (`cadre-node.ts` → `buildControlNodeOptions`, `strand-network-config.ts` →
201
+ * `strandNodeAddrs`), and they are the only two `createLibp2pNode` callers in this repo
202
+ * that derive their listen set from a `NetworkConfig` — the other callers
203
+ * (`integration-tests/src/harness/test-party.ts`, `quereus-plugin-sereus`'s `connect.ts`
204
+ * and `connect-browser.ts`) pass no `listenAddrs` at all, or pass their own transports
205
+ * with it. If a third CONFIG-derived site appears, fold the two functions into one that
206
+ * returns listen addrs and transport options together, so forgetting becomes impossible
207
+ * rather than merely unlikely.
208
+ *
209
+ * @param listenAddrs the ALREADY-resolved listen set — the output of
210
+ * {@link resolveListenAddrs} after any per-node rewriting — so the check reads what
211
+ * this node will actually bind.
212
+ * @throws {UnbindableListenAddressError} when a listen entry names a transport outside
213
+ * {tcp, ws/wss, p2p-circuit}.
214
+ */
215
+ export function resolveTransportOptions(
216
+ network: NetworkConfig | undefined,
217
+ listenAddrs: readonly string[] | undefined
218
+ ): ListenTransportOptions {
219
+ if (network?.transports) {
220
+ return {};
221
+ }
222
+ const kinds = (listenAddrs ?? []).map((addr) => [addr, listenTransportKind(addr)] as const);
223
+ const unsupported = kinds.filter(([, kind]) => kind === 'unsupported').map(([addr]) => addr);
224
+ if (unsupported.length > 0) {
225
+ throw new UnbindableListenAddressError(unsupported);
226
+ }
227
+ return kinds.some(([, kind]) => kind === 'websockets') ? { wsPort: WS_TRANSPORT_SWITCH_PORT } : {};
228
+ }
229
+
230
+ /**
231
+ * Thrown at config resolution when `network.listenAddrs` names an address none of the
232
+ * default transports can bind. Names each offending address alongside the libp2p
233
+ * transport package it would need — what the operator has without this is a node that
234
+ * starts and silently never listens there.
235
+ */
236
+ export class UnbindableListenAddressError extends Error {
237
+ constructor(readonly listenAddrs: readonly string[]) {
238
+ super(
239
+ 'network.listenAddrs names an address this node has no transport for: ' +
240
+ `${listenAddrs.map((a) => `${a} — ${unbindableReason(a)}`).join('; ')}. ` +
241
+ 'Default transports bind TCP (including /unix/<path>), WebSocket (/ws, /wss) and circuit-relay addresses only. ' +
242
+ 'Either drop the address, or supply the transport programmatically via network.transports.'
243
+ );
244
+ this.name = 'UnbindableListenAddressError';
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Which default transport claims `listenAddr`, or `'unsupported'` when none does.
250
+ *
251
+ * Classification is a multiaddr COMPONENT question, not a string question, so this
252
+ * parses and reads the transport stack — the component names left once the addressing
253
+ * and security layers are dropped. That stack is outermost-LAST
254
+ * (`/ip4/…/tcp/443/tls/ws` → `['tcp', 'ws']`), which is why its terminal entry decides.
255
+ *
256
+ * An unparsable entry is `'ignored'` and passes through untouched, following
257
+ * `isConfiguredCircuitListenAddr` below and `ephemeralPortListenAddr`
258
+ * (`strand-network-config.ts`): libp2p reports a bad listen addr itself, and this check
259
+ * must only ever ADD a denial.
260
+ */
261
+ function listenTransportKind(listenAddr: string): 'tcp' | 'websockets' | 'circuit' | 'ignored' | 'unsupported' {
262
+ let stack: readonly string[];
263
+ try {
264
+ stack = transportStack(listenAddr);
265
+ } catch {
266
+ return 'ignored';
267
+ }
268
+ const outermost = stack.at(-1);
269
+ if (outermost === undefined) {
270
+ // Nothing but addressing components — a bare `/ip4/1.2.3.4`. No transport claims
271
+ // it, so it is dropped by exactly the same silent path this check exists to close.
272
+ return 'unsupported';
273
+ }
274
+ if (outermost === 'p2p-circuit') {
275
+ return 'circuit';
276
+ }
277
+ if (outermost === 'ws' || outermost === 'wss') {
278
+ return 'websockets';
279
+ }
280
+ // Only a BARE tcp or unix stack is TCP. `@libp2p/tcp` binds both — its `listenFilter`
281
+ // accepts an exact TCP match OR a `/unix/<path>` address (a named pipe on Windows) —
282
+ // and nothing layered on top of either, which is why `/tcp/<port>/<anything else>` is
283
+ // NOT waved through merely because a `tcp` component happens to appear.
284
+ return stack.length === 1 && (outermost === 'tcp' || outermost === 'unix') ? 'tcp' : 'unsupported';
285
+ }
286
+
287
+ /**
288
+ * Component names of `listenAddr` with the addressing and security layers removed, so
289
+ * what remains names transports. Host components (`ip4`, `dns4`, …) and the layers that
290
+ * ride inside a transport without being one (`tls`, `sni`, `certhash`, `p2p`) say
291
+ * nothing about which transport has to be configured.
292
+ */
293
+ function transportStack(listenAddr: string): string[] {
294
+ return multiaddr(listenAddr).getComponents()
295
+ .map((component) => component.name)
296
+ .filter((name) => !NON_TRANSPORT_COMPONENTS.has(name));
297
+ }
298
+
299
+ /** Components that address or secure a connection rather than name its transport. */
300
+ const NON_TRANSPORT_COMPONENTS = new Set([
301
+ 'ip4', 'ip6', 'ip6zone', 'dns', 'dns4', 'dns6', 'dnsaddr',
302
+ 'tls', 'sni', 'certhash', 'p2p', 'noise'
303
+ ]);
304
+
305
+ /**
306
+ * Why `listenAddr` cannot be bound, phrased for the operator: the libp2p package that
307
+ * would make it bindable where one is known, and otherwise what is wrong with it.
308
+ *
309
+ * Read OUTERMOST-first (`/udp/…/quic-v1/webtransport` needs `@libp2p/webtransport`,
310
+ * not the `@libp2p/quic` it rides on), matching how `listenTransportKind` decides.
311
+ */
312
+ function unbindableReason(listenAddr: string): string {
313
+ let stack: readonly string[];
314
+ try {
315
+ stack = transportStack(listenAddr);
316
+ } catch {
317
+ return 'not a parsable multiaddr';
318
+ }
319
+ if (stack.length === 0) {
320
+ return 'it names no transport component';
321
+ }
322
+ const pkg = [...stack].reverse().map((name) => TRANSPORT_PACKAGES[name]).find((p) => p !== undefined);
323
+ return pkg === undefined ? 'needs an unrecognized transport' : `needs ${pkg}`;
324
+ }
325
+
326
+ /**
327
+ * The libp2p package each unbindable transport component comes from. Naming the package
328
+ * is the actionable half of the refusal — the operator either drops the address or wires
329
+ * that package in through `network.transports`.
330
+ */
331
+ const TRANSPORT_PACKAGES: Record<string, string> = {
332
+ 'quic': '@libp2p/quic',
333
+ 'quic-v1': '@libp2p/quic',
334
+ 'webtransport': '@libp2p/webtransport',
335
+ 'webrtc': '@libp2p/webrtc',
336
+ 'webrtc-direct': '@libp2p/webrtc'
337
+ };
338
+
339
+ /**
340
+ * Thrown out of `CadreNode.start()` when the boot-path reservation drive for
341
+ * `network.relayAddrs` produces no `/p2p-circuit` address on its FIRST attempt.
342
+ *
343
+ * This is what keeps `network.relayAddrs` fail-fast now that the control node
344
+ * takes the `'search'` route: libp2p's own `UnsupportedListenAddressesError` used
345
+ * to abort start from inside `listen()`, and an operator who names a relay is
346
+ * telling the node it has no other reachability — coming up undialable is worse
347
+ * than not coming up. Names the relays and the reservation's own reason, both of
348
+ * which the libp2p error omitted.
349
+ */
350
+ export class RelayReservationFailedError extends Error {
351
+ constructor(
352
+ readonly relayAddrs: readonly string[],
353
+ readonly state: RelayReservationState
354
+ ) {
355
+ super(
356
+ `network.relayAddrs reservation failed (status: ${state.status}): ` +
357
+ `${state.error ?? 'no /p2p-circuit address appeared'} — relays: ${relayAddrs.join(', ')}`
358
+ );
359
+ this.name = 'RelayReservationFailedError';
360
+ }
361
+ }
362
+
363
+ /**
364
+ * A hand-written `<relay>/p2p-circuit` entry in `network.listenAddrs` is the
365
+ * CONFIGURED listener shape, and it is unusable on the `'search'` route: libp2p
366
+ * dials that relay from inside `listen()`, the bring-up quiet period
367
+ * (`membership-connection-gater.ts`) denies exactly that dial, `listen()` fails, and
368
+ * the transport manager's default `FATAL_ALL` aborts `libp2p.start()`. The operator
369
+ * would see `UnsupportedListenAddressesError` from deep inside bring-up with nothing
370
+ * naming the cause, so name it here instead.
371
+ *
372
+ * `network.relayAddrs` is the exact replacement — same relay, and the reservation is
373
+ * driven after bring-up, which is the whole point of the route.
374
+ */
375
+ function rejectConfiguredCircuitListenAddrs(listenAddrs: readonly string[]): void {
376
+ const configured = listenAddrs.filter(isConfiguredCircuitListenAddr);
377
+ if (configured.length > 0) {
378
+ throw new Error(
379
+ 'network.listenAddrs names a relay directly ' +
380
+ `(${configured.join(', ')}), which a control node cannot listen on: libp2p would ` +
381
+ 'dial that relay during control-database bring-up, when the node accepts no ' +
382
+ 'connections. Move the relay to network.relayAddrs, which reserves after bring-up.'
383
+ );
384
+ }
385
+ }
386
+
387
+ /** `<something>/p2p-circuit` — the configured shape, as opposed to the bare search addr. */
388
+ function isConfiguredCircuitListenAddr(listenAddr: string): boolean {
389
+ if (listenAddr === RELAY_SEARCH_LISTEN_ADDR) {
390
+ return false;
391
+ }
392
+ try {
393
+ return multiaddr(listenAddr).getComponents().some((c) => c.name === 'p2p-circuit');
394
+ } catch {
395
+ // Not our error to raise: libp2p reports an unparsable listen addr itself, and
396
+ // this helper only ever ADDS a denial.
397
+ return false;
398
+ }
399
+ }
400
+
401
+ /**
402
+ * One entry of {@link relayCircuitAddrs}: the addr the node listens on for this relay.
403
+ *
404
+ * NOTE: an entry carrying components AFTER `/p2p-circuit` — a full relayed DIAL addr,
405
+ * `…/p2p/<relay>/p2p-circuit/p2p/<someone else>` — is passed through as written and
406
+ * would be listened on verbatim. It validates (the relay it names is real), so only an
407
+ * operator who pastes a peer's relayed address into `relayAddrs` hits it; if that turns
408
+ * out to be a common paste, truncate at the `/p2p-circuit` component here.
409
+ */
410
+ function circuitListenAddr(relayAddr: string): string {
411
+ const alreadyCircuit = parseComponents(relayAddr).some((c) => c.name === 'p2p-circuit');
412
+ const listenAddr = alreadyCircuit ? relayAddr : `${relayAddr}/p2p-circuit`;
413
+ try {
414
+ circuitRelayTargetOrThrow(listenAddr); // validates the relay peerId
415
+ } catch (err) {
416
+ throw new Error(
417
+ `network.relayAddrs entry names no relay peerId (expected <dial addr>/p2p/<relayPeerId>): ${relayAddr}`,
418
+ { cause: err }
419
+ );
420
+ }
421
+ return listenAddr;
422
+ }
423
+
424
+ /** Multiaddr components of `relayAddr`, with the config field named on a parse failure. */
425
+ function parseComponents(relayAddr: string): Component[] {
426
+ try {
427
+ return multiaddr(relayAddr).getComponents();
428
+ } catch (err) {
429
+ throw new Error(`network.relayAddrs entry is not a valid multiaddr: ${relayAddr}`, { cause: err });
430
+ }
431
+ }
432
+
433
+ /** Exact-string dedupe, first occurrence wins, so the list is stable across restarts. */
434
+ function dedupe(addrs: readonly string[]): string[] {
435
+ return [...new Set(addrs)];
436
+ }