@serfab/cadre-core 1.13.0 → 1.14.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 (120) hide show
  1. package/dist/cadre-invite-protocol.d.ts +348 -0
  2. package/dist/cadre-invite-protocol.js +605 -0
  3. package/dist/cadre-invite-protocol.js.map +1 -0
  4. package/dist/cadre-node.d.ts +523 -180
  5. package/dist/cadre-node.js +921 -293
  6. package/dist/cadre-node.js.map +1 -1
  7. package/dist/claim-proof.d.ts +45 -0
  8. package/dist/claim-proof.js +132 -0
  9. package/dist/claim-proof.js.map +1 -0
  10. package/dist/control-authorization.d.ts +80 -19
  11. package/dist/control-authorization.js +55 -13
  12. package/dist/control-authorization.js.map +1 -1
  13. package/dist/control-cohort.js +1 -1
  14. package/dist/control-cohort.js.map +1 -1
  15. package/dist/control-database.d.ts +514 -97
  16. package/dist/control-database.js +1033 -195
  17. package/dist/control-database.js.map +1 -1
  18. package/dist/control-protocol-guard.d.ts +142 -0
  19. package/dist/control-protocol-guard.js +293 -0
  20. package/dist/control-protocol-guard.js.map +1 -0
  21. package/dist/control-schema.d.ts +1 -1
  22. package/dist/control-schema.js +801 -1067
  23. package/dist/control-schema.js.map +1 -1
  24. package/dist/control-stream.d.ts +4 -0
  25. package/dist/control-stream.js +22 -7
  26. package/dist/control-stream.js.map +1 -1
  27. package/dist/delegate-admission.d.ts +1 -1
  28. package/dist/delegate-admission.js +1 -1
  29. package/dist/device-token.d.ts +11 -9
  30. package/dist/device-token.js +14 -12
  31. package/dist/device-token.js.map +1 -1
  32. package/dist/ed25519-key.d.ts +15 -0
  33. package/dist/ed25519-key.js +28 -1
  34. package/dist/ed25519-key.js.map +1 -1
  35. package/dist/index.d.ts +14 -9
  36. package/dist/index.js +27 -9
  37. package/dist/index.js.map +1 -1
  38. package/dist/link-budget.d.ts +16 -29
  39. package/dist/link-budget.js +16 -31
  40. package/dist/link-budget.js.map +1 -1
  41. package/dist/membership-connection-gater.d.ts +190 -151
  42. package/dist/membership-connection-gater.js +235 -173
  43. package/dist/membership-connection-gater.js.map +1 -1
  44. package/dist/node-claim-payload.d.ts +19 -0
  45. package/dist/node-claim-payload.js +120 -0
  46. package/dist/node-claim-payload.js.map +1 -0
  47. package/dist/owner-anchor-sync.d.ts +22 -0
  48. package/dist/owner-anchor-sync.js +143 -0
  49. package/dist/owner-anchor-sync.js.map +1 -0
  50. package/dist/peer-authorization.d.ts +113 -18
  51. package/dist/peer-authorization.js +225 -29
  52. package/dist/peer-authorization.js.map +1 -1
  53. package/dist/peer-dial.d.ts +19 -0
  54. package/dist/peer-dial.js +22 -1
  55. package/dist/peer-dial.js.map +1 -1
  56. package/dist/peer-join-backfill.d.ts +26 -2
  57. package/dist/peer-join-backfill.js +54 -12
  58. package/dist/peer-join-backfill.js.map +1 -1
  59. package/dist/peer-record.d.ts +13 -9
  60. package/dist/peer-record.js +16 -12
  61. package/dist/peer-record.js.map +1 -1
  62. package/dist/pending-join-runner.d.ts +66 -58
  63. package/dist/pending-join-runner.js +136 -145
  64. package/dist/pending-join-runner.js.map +1 -1
  65. package/dist/push-fanout.d.ts +8 -2
  66. package/dist/push-fanout.js +8 -2
  67. package/dist/push-fanout.js.map +1 -1
  68. package/dist/seed-bootstrap.d.ts +147 -122
  69. package/dist/seed-bootstrap.js +284 -269
  70. package/dist/seed-bootstrap.js.map +1 -1
  71. package/dist/seed-trust-policy.d.ts +98 -37
  72. package/dist/seed-trust-policy.js +188 -2
  73. package/dist/seed-trust-policy.js.map +1 -1
  74. package/dist/strand-addr-protocol.d.ts +24 -26
  75. package/dist/strand-addr-protocol.js +19 -26
  76. package/dist/strand-addr-protocol.js.map +1 -1
  77. package/dist/strand-formation-protocol.js +1 -1
  78. package/dist/strand-formation-protocol.js.map +1 -1
  79. package/dist/strand-revocation-enforcer.d.ts +11 -11
  80. package/dist/strand-revocation-enforcer.js +11 -11
  81. package/dist/strand-wake-protocol.d.ts +13 -16
  82. package/dist/strand-wake-protocol.js +13 -20
  83. package/dist/strand-wake-protocol.js.map +1 -1
  84. package/dist/trusted-owner-store.d.ts +35 -5
  85. package/dist/trusted-owner-store.js +50 -8
  86. package/dist/trusted-owner-store.js.map +1 -1
  87. package/dist/types.d.ts +302 -87
  88. package/dist/types.js.map +1 -1
  89. package/package.json +8 -7
  90. package/src/cadre-invite-protocol.ts +864 -0
  91. package/src/cadre-node.ts +9381 -8686
  92. package/src/claim-proof.ts +147 -0
  93. package/src/control-authorization.ts +203 -117
  94. package/src/control-cohort.ts +1 -1
  95. package/src/control-database.ts +1216 -218
  96. package/src/control-protocol-guard.ts +348 -0
  97. package/src/control-schema.ts +812 -1078
  98. package/src/control-stream.ts +26 -7
  99. package/src/delegate-admission.ts +1 -1
  100. package/src/device-token.ts +14 -10
  101. package/src/ed25519-key.ts +28 -1
  102. package/src/index.ts +84 -10
  103. package/src/link-budget.ts +16 -32
  104. package/src/membership-connection-gater.ts +637 -570
  105. package/src/node-claim-payload.ts +125 -0
  106. package/src/owner-anchor-sync.ts +171 -0
  107. package/src/peer-authorization.ts +258 -29
  108. package/src/peer-dial.ts +22 -1
  109. package/src/peer-join-backfill.ts +56 -11
  110. package/src/peer-record.ts +16 -11
  111. package/src/pending-join-runner.ts +729 -735
  112. package/src/push-fanout.ts +8 -2
  113. package/src/seed-bootstrap.ts +344 -321
  114. package/src/seed-trust-policy.ts +353 -140
  115. package/src/strand-addr-protocol.ts +26 -35
  116. package/src/strand-formation-protocol.ts +1 -1
  117. package/src/strand-revocation-enforcer.ts +11 -11
  118. package/src/strand-wake-protocol.ts +13 -23
  119. package/src/trusted-owner-store.ts +242 -171
  120. package/src/types.ts +2471 -2242
@@ -1,570 +1,637 @@
1
- /**
2
- * Control-network inbound admission gates (defense-in-depth): the
3
- * encrypted-connection checkpoint and the circuit-relay reservation checkpoint.
4
- *
5
- * Layer 2 of the membership enforcement chain: the PRIMARY gates are per-stream
6
- * — every sensitive sereus control protocol rejects a peer that fails the
7
- * voucher-anchored membership check (wake and strand-addr via
8
- * `CadreNode.isAuthorizedMember`; the Optimystic control-DB protocols via the
9
- * materialized-snapshot gate `CadreNode.authorizeInboundControlStream`), and
10
- * the replicated rows an outsider *can* still write are disbelieved at read
11
- * time. This module adds the opportunistic connection-level layer on top: a
12
- * peer this node can positively determine is NOT authorized is refused at the
13
- * encrypted-connection checkpoint, before any protocol negotiation, so a
14
- * known-nothing outsider is never even in the conversation — EXCEPT on a node
15
- * that runs the circuit-relay server, where the refusal moves to the
16
- * relay-reservation checkpoint instead (see "The relay-reservation seam").
17
- *
18
- * ## The stranger allowlist (the ONE place it is defined)
19
- *
20
- * A libp2p connection gater decides per CONNECTION, before protocols are
21
- * negotiated, so "allow seed, deny repo" cannot be expressed here — instead the
22
- * policy admits a connection whenever a legitimate stranger interaction could be
23
- * riding it, and the per-stream gates take over. The complete set of protocols a
24
- * NOT-yet-authorized peer may legitimately speak on a control node is:
25
- *
26
- * - `/sereus/seed/1.0.0` ({@link SEED_PROTOCOL}) — enrollment seed delivery.
27
- * An owner dials a brand-new node to seed it (the new node has no members
28
- * yet, so its gate is inert), and an invited phone dials the owner before it
29
- * is authorized (admitted via the enrollment window `CadreNode.createInvite`
30
- * opens). The handler's own trust decision is the anchored seed-trust policy.
31
- * - `/sereus/formation/1.0.0` ({@link FORMATION_PROTOCOL}) — cross-party
32
- * strand formation via open invitations. Stranger-facing BY DESIGN: the
33
- * initiator is another party, and its token is only checkable inside the
34
- * protocol. The exemption is therefore keyed on EXPECTATION of a stranger,
35
- * not capability to serve one: stranger denial is suspended only while this
36
- * node has at least one UNEXPIRED, NOT-FULLY-CONSUMED open invitation
37
- * outstanding (`StrandSolicitationService.hasOutstandingInvitation` — the
38
- * tokens this process minted or published, plus any still-redeemable
39
- * `FormationInvite` row the usage recorder can see). Registering the
40
- * responder does NOT suspend it, so every node — each registers one at
41
- * `CadreNode.start` — keeps a live gate. The
42
- * handler's own trust decision remains the per-token check, which is
43
- * strictly finer than this one: a peer admitted here can still be rejected
44
- * in-protocol for a bogus or spent token.
45
- *
46
- * There is one further connection-level carve-out, which is NOT a protocol
47
- * exemption and needs no stranger window:
48
- *
49
- * - **Announced delegate peers** (`delegate-admission.ts`). A member's strand
50
- * node runs as a separate libp2p identity whose peerId no sibling can
51
- * recompute. Before starting a strand node, a member's control node
52
- * announces that peerId over the already-authenticated strand-addr RPC, and
53
- * the receiver holds a short-lived grant for it
54
- * (`CadreNode.grantDelegateAdmission`). The grant admits the CONNECTION,
55
- * admits the peer's RESERVATION at the seam below (without spending the
56
- * unauthorized budget), and nothing else — it is deliberately invisible to
57
- * the per-stream gate, so a delegate still gets refused on every
58
- * members-only protocol.
59
- *
60
- * ## The relay-reservation seam
61
- *
62
- * A circuit-relay reservation is established by the reserving peer DIALING the
63
- * relay, so at the relay it is an inbound connection — and killing that
64
- * connection kills the reservation. For a genuine member whose `CadrePeer` row
65
- * has not yet replicated to this node, a connection-level deny here is NOT
66
- * self-healing the way a data connection's is: an outbound reconcile dial
67
- * re-establishes a data link, but no outbound dial can grant the REMOTE peer a
68
- * reservation, and a relay-only peer has no address of its own to dial back —
69
- * the reservation IS its address. Boot ordering makes the window ordinary (a
70
- * node's circuit listener runs inside `libp2p.start()`, before its own row
71
- * could have replicated anywhere), and a stalled replication makes it
72
- * unbounded. So the relay would be answering a RELAY question ("may this peer
73
- * use my forwarding capacity?") with a MEMBERSHIP answer, at a checkpoint where
74
- * a wrong answer is unrecoverable.
75
- *
76
- * On a node whose relay server is enabled the two questions are separated:
77
- *
78
- * - The policy returns `'admit-for-relay'` instead of `'deny'`, and the
79
- * connection is ADMITTED. The fail-closed per-stream gates still refuse such
80
- * a peer every members-only protocol, so it gains identify/ping and the
81
- * relay hop protocol, nothing else.
82
- * - The reservation itself is decided at libp2p's
83
- * `denyInboundRelayReservation` hook (the circuit-relay server consults it
84
- * per RESERVE request): the policy admits members, delegates and configured
85
- * infra outright, and admits peers it cannot place only within a bounded
86
- * budget ({@link UnauthorizedReservationBudget}) — a member whose row is in
87
- * flight always finds a slot under any sane cap, while outsiders cannot
88
- * annex the party's relay capacity. COUNT and lifetime are the only bounds
89
- * on such a peer: a party-run relay forwards without libp2p's per-connection
90
- * data and duration limit by default (`relay-server.ts`), so what a granted
91
- * slot carries is not capped.
92
- * - An `'admit-for-relay'` connection that is NOT reserving is dropped: it has
93
- * {@link RELAY_ADMISSION_RESERVE_DEADLINE_MS} to get a reservation ADMITTED
94
- * at that hook, after which the gate CLOSES the underlying connection so
95
- * both ends let go of the socket. The guarantee above thus weakens on
96
- * relay-enabled nodes from "never in the conversation" to "in it briefly,
97
- * and can speak nothing".
98
- *
99
- * The deadline clears on reservation ADMISSION, not on the reservation's own
100
- * success: this gate cannot observe the server-side `reserve()` outcome, so a
101
- * peer whose admitted reservation is then refused for server capacity keeps its
102
- * connection until either side closes it — bounded and mute, so harmless.
103
- *
104
- * Everything else a control node handles — the Optimystic control-DB protocols
105
- * (`/optimystic/control-<party>/{repo,cluster,sync,block-transfer}/…`), wake
106
- * (`/sereus/strand-wake/1.0.0`), and strand-addr (`/sereus/strand-addr/1.0.0`)
107
- * — is members-only, and every one of them enforces that per-stream. Wake and
108
- * strand-addr check `isAuthorizedMember` inside their handlers; the four
109
- * control-DB protocols are gated by the fail-closed
110
- * `CadreNode.authorizeInboundControlStream` (wired as libp2p's
111
- * `authorizeInboundStream` upstream hook), which judges each inbound stream
112
- * against the MATERIALIZED authorized-peer snapshot — synchronous and
113
- * in-memory, because a live DB read from inside the gate would deadlock into
114
- * mutual denial. The two layers complement, not duplicate: this connection
115
- * gate is fail-open over a live DB read (deny only on positive proof of an
116
- * outsider), the stream gate is fail-closed over the snapshot and has NO
117
- * stranger carve-outs — an enrollment window admits a stranger's connection
118
- * for seed delivery, yet its repo streams are still refused.
119
- *
120
- * ## The bring-up quiet period
121
- *
122
- * One state is decided BEFORE any of the above, and is not about the remote peer
123
- * at all: while this node's control-database bring-up is in flight
124
- * (`InboundAdmissionPolicy.bringUpInFlight`), the gate denies BOTH directions —
125
- * `denyDialPeer` and `denyInboundEncryptedConnection` — and then opens.
126
- *
127
- * The invariant it protects is "`ControlDatabase.initialize()` runs while this
128
- * node holds ZERO control connections". Building that database is a long chain
129
- * of cohort-consulting block probes, and every connected same-party sibling is in
130
- * the cohort those probes consult. A sibling that has not yet replicated this
131
- * node's `CadrePeer` row correctly refuses them at its own fail-closed per-stream
132
- * gate, so ONE connection in this window turns bring-up into
133
- * `BlockUnavailableError` and `start()` rejects. Retrying cannot converge: the
134
- * condition that would clear the refusal is this node's own row reaching the
135
- * sibling, and writing that row needs the database the retry is building. So the
136
- * only fix is to not be in the conversation yet — which is what this window is.
137
- *
138
- * The ordering is arranged so nothing SHOULD open a connection here anyway:
139
- * `network.relayAddrs` resolves to a listener that dials nothing and reserves
140
- * after bring-up (`relay-addrs.ts`), `controlNetwork.bootstrapNodes` is dialed
141
- * after bring-up (`CadreNode.dialControlBootstrapPeers`), and the control-cohort
142
- * reconcile pass is scheduled post-start. This window is what makes that a property
143
- * rather than an accident of ordering — the live cases it catches are peers the node
144
- * remembers from a previous run, which the connection manager auto-dials, and
145
- * inbound dials.
146
- *
147
- * A denial here costs a retry, not a partition: libp2p's connection manager
148
- * re-dials on its auto-dial cadence, the reservation supervisor re-drives, and a
149
- * denied inbound peer reconnects. The window opens on bring-up FAILURE too (via
150
- * `CadreNode.cleanup`), so teardown is never gated.
151
- *
152
- * ## Fail-open, deliberately
153
- *
154
- * Outside that window this layer only ever denies on a POSITIVE determination of
155
- * "unauthorized outsider while no stranger path is open". Any error, missing
156
- * dependency, or ambiguous state admits the connection (and the reservation) and
157
- * defers to the fail-closed stream gates — a DB hiccup must not partition a
158
- * legitimate cadre.
159
- */
160
-
161
- import debug from 'debug';
162
- import type { ConnectionGater, PeerId, MultiaddrConnection } from '@libp2p/interface';
163
- import { SEED_PROTOCOL } from './seed-bootstrap.js';
164
- import { FORMATION_PROTOCOL } from './strand-formation-protocol.js';
165
- import { withDeadline } from './control-stream.js';
166
- import { PARTY_RELAY_RESERVATION_TTL_MS } from './relay-server.js';
167
- import { ADMISSION_DECISION_TIMEOUT_MS, relayAdmissionReserveDeadlineMs } from './link-budget.js';
168
-
169
- const log = debug('sereus:cadre:connection-gater');
170
-
171
- /**
172
- * The protocols a not-yet-authorized peer may legitimately speak on a control
173
- * node (see the module doc above for why each is open and where its own trust
174
- * decision lives). Exported as the single reference point so the allowlist
175
- * cannot silently drift across modules.
176
- */
177
- export const STRANGER_OPEN_PROTOCOLS: readonly string[] = [SEED_PROTOCOL, FORMATION_PROTOCOL];
178
-
179
- /**
180
- * How long `CadreNode.createInvite` holds the inbound gate open for strangers
181
- * when the invite carries no explicit expiry: the invitee must dial in before
182
- * it is authorized, and an expiry-less invite gives the gate no bound of its
183
- * own. Redeeming after this window still works once the owner re-mints (or the
184
- * caller re-opens the window via `CadreNode.openEnrollmentWindow`).
185
- */
186
- export const DEFAULT_ENROLLMENT_WINDOW_MS = 30 * 60 * 1000;
187
-
188
- /**
189
- * How long an `'admit-for-relay'` connection may exist without a relay
190
- * reservation being ADMITTED at the `denyInboundRelayReservation` hook, after
191
- * which the gate closes the underlying connection. A reserving client asks for
192
- * its slot immediately after the connection upgrades (`relay-reservation.ts`
193
- * dials and requests in one drive; a strand node's configured circuit listener
194
- * does the same from inside its own `listen()`), so a connection idle past this
195
- * deadline is not reserving.
196
- *
197
- * Derived from the link ({@link relayAdmissionReserveDeadlineMs}): one link round trip for the
198
- * request to arrive plus one admission decision on it. This is the value at the default
199
- * declaration; `CadreNode` passes the one derived from the relay's OWN declaration, because the
200
- * relay is the machine that decides.
201
- */
202
- export const RELAY_ADMISSION_RESERVE_DEADLINE_MS = relayAdmissionReserveDeadlineMs();
203
-
204
- /**
205
- * Bound on the graceful close of an expired relay-only connection. It exists
206
- * because `AbstractMultiaddrConnection.close()` awaits an `idle`/`drain` event
207
- * when the connection still has unsent bytes, and that wait has no timeout of
208
- * its own — an unsignalled one never ends. This gate writes nothing to a
209
- * stranger, so the wait is not reachable today; the bound is here so a timer
210
- * callback can never hold an unending await.
211
- *
212
- * Applied through {@link withDeadline}, not `AbortSignal.timeout`: the latter is
213
- * not reliably present on React Native/Hermes, which loads this same module.
214
- */
215
- // eslint-disable-next-line no-restricted-syntax -- link-independent: bounds a local connection close inside a timer callback, and expiry aborts the connection instead
216
- export const RELAY_ADMISSION_CLOSE_TIMEOUT_MS = 2_000;
217
-
218
- /**
219
- * Default cap on concurrent relay reservations held by peers the membership
220
- * check could not place (see {@link UnauthorizedReservationBudget}). Small on
221
- * purpose: it exists for the handful of genuine members whose rows are still
222
- * in flight, not as public relay capacity. Overridable per node via
223
- * `network.unauthorizedRelayReservationCap` (0 refuses every unauthorized
224
- * reservation — the strict pre-seam posture).
225
- *
226
- * NOTE: this cap shares the relay server's own reservation store, whose
227
- * party-run default size is `PARTY_RELAY_MAX_RESERVATIONS` (128,
228
- * `relay-server.ts`); unplaced peers may therefore occupy up to this many of
229
- * those slots, and the rest are what members and delegates compete for. The two
230
- * are kept apart by hand — if this is raised, or an embedder shrinks the store
231
- * through `network.relayServerInit.reservations.maxReservations`, keep this one
232
- * well under the store's, or a fleet of unplaceable peers can crowd genuine
233
- * members out of the server's own store (which the gate cannot override).
234
- */
235
- export const MAX_UNAUTHORIZED_RELAY_RESERVATIONS = 8;
236
-
237
- /**
238
- * The connection-level outcome of the admission policy:
239
- * - `'admit'` — a peer with a legitimate claim on the connection (member,
240
- * delegate, infra, open stranger window, or any fail-open state).
241
- * - `'deny'` — positively an outsider, and this node runs no relay server, so
242
- * the connection can carry nothing legitimate.
243
- * - `'admit-for-relay'` — positively an outsider (or an unreplicated member —
244
- * indistinguishable), but this node runs the relay server: admit the
245
- * connection so a reservation can be asked for, decide at the reservation
246
- * seam, and drop the connection if no reservation is admitted in time.
247
- */
248
- export type InboundConnectionVerdict = 'admit' | 'deny' | 'admit-for-relay';
249
-
250
- /**
251
- * The admission decisions the gate defers to — implemented by
252
- * `CadreNode.admitInboundControlConnection` /
253
- * `CadreNode.admitControlRelayReservation` (enrollment windows, anchor state,
254
- * bootstrap infra, delegate grants, the authorized-member set, the
255
- * unauthorized-reservation budget). Kept injectable so the gater's
256
- * composition/fail-open behavior is unit-testable without a full node.
257
- */
258
- export interface InboundAdmissionPolicy {
259
- /** Verdict on an inbound encrypted connection from this peer. */
260
- admitInbound(remotePeerId: string): Promise<InboundConnectionVerdict> | InboundConnectionVerdict;
261
- /** Should this peer be granted a circuit-relay reservation slot? */
262
- admitRelayReservation(remotePeerId: string): Promise<boolean> | boolean;
263
- /**
264
- * True while this node's control-database bring-up is in flight — the
265
- * {@link createMembershipConnectionGater} quiet period (see the module doc).
266
- * Peer-independent, unlike the two decisions above, and SYNCHRONOUS: it is
267
- * read on the outbound-dial path, where an await would be a new stall.
268
- *
269
- * Optional — a policy that omits it is never quiet, which is the right default
270
- * for every caller that is not a booting `CadreNode`.
271
- */
272
- bringUpInFlight?(): boolean;
273
- }
274
-
275
- /**
276
- * Bounded budget of concurrent relay reservations for peers the membership
277
- * check could not place. `tryAdmit` is the whole surface: an already-admitted
278
- * peer refreshes its entry (a reservation refresh never double-counts), a new
279
- * peer takes a free slot or is refused. Entries expire after `ttlMs`, which
280
- * `CadreNode` passes as the relay server's own resolved `reservationTtl`
281
- * (`relay-server.ts`): the server holds an unrefreshed reservation exactly that
282
- * long, and a live reserver re-requests (re-hitting the admission hook,
283
- * refreshing its entry) well before expiry — so the live entry count tracks the
284
- * server's own occupancy without this module reaching into the server's
285
- * reservation store. Injectable `now` keeps expiry testable without fake
286
- * timers. Authorized members and delegates are never run through this — the
287
- * policy admits them before consulting the budget, and `release`s the slot such
288
- * a peer took while it was still unplaceable, so the boot-ordering window a
289
- * member passes through costs the budget nothing once its row lands.
290
- */
291
- export class UnauthorizedReservationBudget {
292
- private readonly admitted = new Map<string, number>();
293
-
294
- constructor(
295
- /** Most peers admitted at once — `network.unauthorizedRelayReservationCap`, resolved. */
296
- readonly cap: number = MAX_UNAUTHORIZED_RELAY_RESERVATIONS,
297
- private readonly ttlMs: number = PARTY_RELAY_RESERVATION_TTL_MS
298
- ) {}
299
-
300
- /** Number of live (unexpired at last prune) entries — test/diagnostic surface. */
301
- get size(): number {
302
- return this.admitted.size;
303
- }
304
-
305
- /** Admit (or refresh) `remotePeerId` if a slot is free; false when the cap is spent. */
306
- tryAdmit(remotePeerId: string, now: number = Date.now()): boolean {
307
- this.prune(now);
308
- if (!this.admitted.has(remotePeerId) && this.admitted.size >= this.cap) {
309
- log('Unauthorized-reservation budget spent (%d/%d) — refusing %s', this.admitted.size, this.cap, remotePeerId);
310
- return false;
311
- }
312
- this.admitted.set(remotePeerId, now + this.ttlMs);
313
- return true;
314
- }
315
-
316
- /**
317
- * Give back the slot `remotePeerId` holds, if any — called when the peer has
318
- * become admissible on its own merits (its membership row replicated, or a
319
- * delegate grant landed), so the slot it took during the boot-ordering window
320
- * does not stay spent for the remaining TTL on a peer that no longer needs it.
321
- */
322
- release(remotePeerId: string): void {
323
- this.admitted.delete(remotePeerId);
324
- }
325
-
326
- private prune(now: number): void {
327
- for (const [peerId, expiresAt] of this.admitted) {
328
- if (expiresAt <= now) {
329
- this.admitted.delete(peerId);
330
- }
331
- }
332
- }
333
- }
334
-
335
- /**
336
- * Build the control node's connection gater: the caller-supplied gater (if any)
337
- * with membership admission composed onto `denyInboundEncryptedConnection` —
338
- * the earliest checkpoint where the remote's authenticated PeerId is known —
339
- * and reservation admission composed onto `denyInboundRelayReservation` — the
340
- * hook the circuit-relay server consults per RESERVE request (inert on a node
341
- * whose relay server is off; libp2p never calls it there).
342
- *
343
- * `denyDialPeer` is composed too, but ONLY for the bring-up quiet period (see
344
- * the module doc): outside that window outbound dials are never gated by
345
- * membership — this node decides for itself who to talk to.
346
- *
347
- * Composition semantics: every hook of `base` is preserved as-is; on the three
348
- * composed hooks a deny from EITHER the base gater or the admission policy
349
- * denies. A policy error — or a decision slower than `decisionTimeoutMs` —
350
- * takes the fail-open outcome (connection admitted / reservation admitted, see
351
- * module doc); the base gater's verdict is still honored first.
352
- *
353
- * An `'admit-for-relay'` verdict admits the connection and arms a
354
- * `reserveDeadlineMs` timer against it; the timer is disarmed when a
355
- * reservation for that peer is ADMITTED at the reservation hook, and closes the
356
- * underlying `MultiaddrConnection` when it fires first.
357
- *
358
- * NOTE: `base` is spread, so a gater passed as a CLASS INSTANCE would lose its
359
- * prototype methods; every caller in this repo (and libp2p's own default)
360
- * supplies a plain object. If a class-based gater ever shows up, delegate
361
- * per-hook instead of spreading.
362
- *
363
- * Deny timing, as observed by the denied dialer: noise negotiates the muxer in
364
- * the security handshake's early data, so the DIALER's upgrade may complete
365
- * (its `dial()` resolves) before this receiver-side hook runs. The deny then
366
- * aborts the receiver's upgrade — the receiver never registers the connection
367
- * and never creates its muxer, so no protocol can ever be negotiated — and the
368
- * dialer sees its "open" connection close moments later.
369
- *
370
- * Control node only: strand cohort nodes legitimately connect cross-party
371
- * peers, so cadre membership never gates them. An OPEN strand's node receives
372
- * the raw configured gater unchanged; a CLOSED strand's node composes its own
373
- * revoked-peer denial onto it instead — a deny-list on positive revocation
374
- * evidence, not this module's membership admission — see
375
- * `strand-revocation-enforcer.ts`.
376
- */
377
- export function createMembershipConnectionGater(
378
- policy: InboundAdmissionPolicy,
379
- base?: ConnectionGater,
380
- decisionTimeoutMs: number = ADMISSION_DECISION_TIMEOUT_MS,
381
- reserveDeadlineMs: number = RELAY_ADMISSION_RESERVE_DEADLINE_MS
382
- ): ConnectionGater {
383
- const pendingReservations = new PendingReserveDeadlines(reserveDeadlineMs);
384
- const quiet = (): boolean => policy.bringUpInFlight?.() ?? false;
385
- return {
386
- ...base,
387
- denyDialPeer: async (peerId: PeerId): Promise<boolean> => {
388
- if (await base?.denyDialPeer?.(peerId)) {
389
- return true;
390
- }
391
- if (quiet()) {
392
- log('Control-database bring-up in flight — refusing the outbound dial to %s', peerId.toString());
393
- return true;
394
- }
395
- return false;
396
- },
397
- denyInboundEncryptedConnection: async (peerId: PeerId, maConn: MultiaddrConnection): Promise<boolean> => {
398
- if (await base?.denyInboundEncryptedConnection?.(peerId, maConn)) {
399
- return true;
400
- }
401
- if (quiet()) {
402
- log('Control-database bring-up in flight — refusing the inbound connection from %s', peerId.toString());
403
- return true;
404
- }
405
- const remotePeerId = peerId.toString();
406
- let verdict: InboundConnectionVerdict;
407
- try {
408
- verdict = await decideWithinDeadline(
409
- () => policy.admitInbound(remotePeerId), 'admit', decisionTimeoutMs, `admitInbound(${remotePeerId})`
410
- );
411
- } catch (error) {
412
- log('admitInbound threw for %s — admitting (fail-open; stream gates decide): %o', remotePeerId, error);
413
- return false;
414
- }
415
- if (verdict === 'admit-for-relay') {
416
- pendingReservations.arm(remotePeerId, maConn);
417
- return false;
418
- }
419
- return verdict === 'deny';
420
- },
421
- denyInboundRelayReservation: async (peerId: PeerId): Promise<boolean> => {
422
- if (await base?.denyInboundRelayReservation?.(peerId)) {
423
- return true;
424
- }
425
- const remotePeerId = peerId.toString();
426
- let admitted: boolean;
427
- try {
428
- admitted = await decideWithinDeadline(
429
- () => policy.admitRelayReservation(remotePeerId), true, decisionTimeoutMs, `admitRelayReservation(${remotePeerId})`
430
- );
431
- } catch (error) {
432
- log('admitRelayReservation threw for %s — admitting (fail-open): %o', remotePeerId, error);
433
- admitted = true;
434
- }
435
- if (admitted) {
436
- pendingReservations.disarm(remotePeerId);
437
- }
438
- return !admitted;
439
- }
440
- };
441
- }
442
-
443
- /**
444
- * Run one admission decision under `timeoutMs`, resolving to `fallback` (the
445
- * fail-open outcome) if it has not settled in time — see
446
- * {@link ADMISSION_DECISION_TIMEOUT_MS} for why an unbounded await is not safe
447
- * on the connection hook. The timer is always cleared so a decided call never
448
- * holds the event loop open. Exported for the strand revoked-peer gate
449
- * (`strand-revocation-enforcer.ts`), which bounds its connection hooks with the
450
- * same fail-open contract.
451
- */
452
- export async function decideWithinDeadline<T>(
453
- decide: () => Promise<T> | T,
454
- fallback: T,
455
- timeoutMs: number,
456
- what: string
457
- ): Promise<T> {
458
- let timer: ReturnType<typeof setTimeout> | undefined;
459
- try {
460
- return await Promise.race([
461
- Promise.resolve().then(decide),
462
- new Promise<T>((resolve) => {
463
- timer = setTimeout(() => {
464
- log('%s exceeded %dms — taking the fail-open outcome (stream gates decide)', what, timeoutMs);
465
- resolve(fallback);
466
- }, timeoutMs);
467
- })
468
- ]);
469
- } finally {
470
- clearTimeout(timer);
471
- }
472
- }
473
-
474
- /** One armed not-reserving deadline: the connection it will close, and its timer. */
475
- interface PendingReserveDeadline {
476
- maConn: MultiaddrConnection;
477
- timer: ReturnType<typeof setTimeout>;
478
- }
479
-
480
- /**
481
- * The not-reserving deadlines for `'admit-for-relay'` connections, keyed by
482
- * remote peerId (a Set per peer — one peer can hold several in-flight
483
- * connections). `arm` starts a timer that closes the connection; `disarm`
484
- * (called when a reservation for that peer is admitted) cancels every pending
485
- * timer for the peer. Timers are unref'd so an armed deadline never holds a
486
- * process open, and a timer that fires against an already-closed connection is
487
- * a no-op (`close()` returns at once on any status but `open`).
488
- *
489
- * Disarming is final for the connections it cancelled: a peer that reserved
490
- * once and then lets its reservation lapse keeps a mute connection (the
491
- * fail-closed stream gates refuse it every members-only protocol) until either
492
- * side closes it. Bounded — only a peer the reservation policy already admitted
493
- * can reach that state, so unplaceable peers are bounded by the budget cap.
494
- */
495
- class PendingReserveDeadlines {
496
- private readonly byPeer = new Map<string, Set<PendingReserveDeadline>>();
497
-
498
- constructor(private readonly deadlineMs: number) {}
499
-
500
- arm(remotePeerId: string, maConn: MultiaddrConnection): void {
501
- const entry: PendingReserveDeadline = {
502
- maConn,
503
- timer: setTimeout(() => this.expire(remotePeerId, entry), this.deadlineMs)
504
- };
505
- (entry.timer as { unref?: () => void }).unref?.();
506
- let entries = this.byPeer.get(remotePeerId);
507
- if (!entries) {
508
- entries = new Set();
509
- this.byPeer.set(remotePeerId, entries);
510
- }
511
- entries.add(entry);
512
- log('Admitted %s for relay only — dropping the connection unless a reservation is admitted within %dms', remotePeerId, this.deadlineMs);
513
- }
514
-
515
- disarm(remotePeerId: string): void {
516
- const entries = this.byPeer.get(remotePeerId);
517
- if (!entries) {
518
- return;
519
- }
520
- this.byPeer.delete(remotePeerId);
521
- for (const entry of entries) {
522
- clearTimeout(entry.timer);
523
- }
524
- }
525
-
526
- private expire(remotePeerId: string, entry: PendingReserveDeadline): void {
527
- const entries = this.byPeer.get(remotePeerId);
528
- entries?.delete(entry);
529
- if (entries?.size === 0) {
530
- this.byPeer.delete(remotePeerId);
531
- }
532
- log('Relay-only admission expired for %s — no reservation admitted within %dms, closing the connection', remotePeerId, this.deadlineMs);
533
- void this.drop(remotePeerId, entry.maConn);
534
- }
535
-
536
- /**
537
- * End an expired relay-only connection: a bounded graceful close, with
538
- * `abort()` only as the escalation. The order cannot be reversed — `abort()`
539
- * marks the connection `aborted`, and `close()` returns immediately on any
540
- * status that is not `open`, so aborting first would make the close a silent
541
- * no-op. Closing a connection the peer already dropped returns at once
542
- * without throwing, so the fallback stays unreached in the ordinary case.
543
- */
544
- private async drop(remotePeerId: string, maConn: MultiaddrConnection): Promise<void> {
545
- try {
546
- await withDeadline(
547
- RELAY_ADMISSION_CLOSE_TIMEOUT_MS,
548
- `relay-only close for ${remotePeerId}`,
549
- (signal) => maConn.close({ signal })
550
- );
551
- return;
552
- } catch (error) {
553
- log('Closing the expired relay-only connection from %s failed — aborting: %o', remotePeerId, error);
554
- }
555
- // NOTE: this fallback cannot actually free a WebSocket. `@libp2p/websockets`'
556
- // `sendReset()` calls `websocket.close(1006)`, and 1006 is a reserved code
557
- // RFC 6455 forbids an endpoint from sending, so `ws` throws and
558
- // `AbstractMessageStream.abort()` swallows it — the local end flips to
559
- // `aborted` while the socket stays up. Measured against
560
- // @libp2p/websockets@10.1.3 (see tickets/blocked/report-libp2p-websockets-abort-close-code.md).
561
- // `MultiaddrConnection` exposes no way down to the raw socket, so this is as
562
- // far as this layer can go. Revisit — drop the fallback, or go back to a
563
- // plain `abort()` — once that transport sends a legal reset code.
564
- try {
565
- maConn.abort(new Error(`relay-only admission expired: no relay reservation admitted within ${this.deadlineMs}ms`));
566
- } catch (error) {
567
- log('Aborting the expired relay-only connection from %s threw: %o', remotePeerId, error);
568
- }
569
- }
570
- }
1
+ /**
2
+ * Control-network inbound admission gates: the encrypted-connection checkpoint
3
+ * and the circuit-relay reservation checkpoint.
4
+ *
5
+ * The fail-closed layer of the membership enforcement chain is per-stream: the
6
+ * control node's protocol guard (`control-protocol-guard.ts`) refuses a peer that
7
+ * is not an authorized member on every protocol not declared open to strangers,
8
+ * before its handler runs, and the replicated rows an outsider *can* still write
9
+ * are disbelieved at read time. This module is NOT a stranger boundary on an
10
+ * enrolled node — outside the bring-up quiet period it admits every inbound
11
+ * connection. Its jobs are:
12
+ *
13
+ * - the bring-up quiet period (below), the one state in which it denies;
14
+ * - deciding which admitted peers carry a deadline: a peer the policy cannot
15
+ * place is admitted PROVISIONALLY, and its connection is closed at the
16
+ * deadline unless the policy admits it by then (see "Provisional admission");
17
+ * - handing circuit-relay reservations to the reservation policy (see "The
18
+ * relay-reservation seam").
19
+ *
20
+ * Why a stranger's connection is admitted at all: the gate sees only a peer id,
21
+ * after the encrypted handshake and before any protocol, so it cannot tell an
22
+ * outsider from a device carrying a cadre invitation this node has not received
23
+ * yet, or from a sibling whose membership row is still replicating. Refusing
24
+ * would fail those at the connection; admitting costs a mute connection for a
25
+ * bounded time, because the protocol guard refuses it every members-only protocol.
26
+ *
27
+ * ## Admitted outright
28
+ *
29
+ * A peer the policy CAN place gets no deadline. Besides members, configured
30
+ * infrastructure and an un-enrolled node's whole world (empty anchor or empty
31
+ * authorized set), that covers the stranger windows: states in which this node
32
+ * expects a stranger on one of the `stranger-open` protocols declared in
33
+ * `controlProtocolClasses` (`control-protocol-guard.ts`):
34
+ *
35
+ * - `/sereus/seed/1.0.0` — enrollment seed delivery.
36
+ * An owner dials a brand-new node to seed it (the new node has no members
37
+ * yet, so it admits everyone outright). The handler's own trust decision is the
38
+ * anchored seed-trust policy — or, on a node started with a claim secret
39
+ * (`CadreNodeConfig.claim`), the claim-secret policy. Such a node is the one
40
+ * stranger-facing state that is NOT "admit the connection and let the
41
+ * per-stream gates sort it out": while it waits to be claimed
42
+ * (`CadreNode.isAwaitingClaim`) its connection is admitted, because the claim
43
+ * seed has to ride one, but its control-DB streams and relay reservations are
44
+ * refused ahead of every admission below, the empty-anchor one included. An
45
+ * unclaimed node has no siblings to replicate from, and one on a public
46
+ * address must not relay for anyone. The claim anchors the owner, after which
47
+ * the ordinary rules apply.
48
+ * - `/sereus/formation/1.0.0` — cross-party
49
+ * strand formation via open invitations. Stranger-facing BY DESIGN: the
50
+ * initiator is another party, and its token is only checkable inside the
51
+ * protocol. The window is keyed on EXPECTATION of a stranger, not capability
52
+ * to serve one: it is open only while this node has at least one UNEXPIRED,
53
+ * NOT-FULLY-CONSUMED open invitation outstanding
54
+ * (`StrandSolicitationService.hasOutstandingInvitation` — the tokens this
55
+ * process minted or published, plus any still-redeemable `FormationInvite`
56
+ * row the usage recorder can see). Registering the responder does NOT open
57
+ * it, so on every node — each registers one at `CadreNode.start` — a stranger
58
+ * with no invitation in play stays on the provisional deadline. The
59
+ * handler's own trust decision remains the per-token check, which is
60
+ * strictly finer than this one: a peer admitted here can still be rejected
61
+ * in-protocol for a bogus or spent token.
62
+ * - `/sereus/cadre-invite/1.0.0` — redemption
63
+ * of a cadre invitation at any member machine. Stranger-facing BY DESIGN:
64
+ * the device is not a member until the redemption writes its row, and its
65
+ * proof of possession (a signature with the invitation's private key) is
66
+ * only checkable inside the protocol. Keyed on expectation, as formation's
67
+ * is: open only while this node holds at least one LIVE `CadreInvite` row
68
+ * (`ControlDatabase.hasLiveCadreInvite`: not withdrawn, unexpired, uses left,
69
+ * issuer still an owner). A member that has not yet received the device's
70
+ * row by replication admits the device provisionally instead, seats the row
71
+ * from the invitation bundle during the redemption, and so admits it at the
72
+ * deadline's re-check.
73
+ *
74
+ * There is one further connection-level carve-out, which is NOT a protocol
75
+ * window:
76
+ *
77
+ * - **Announced delegate peers** (`delegate-admission.ts`). A member's strand
78
+ * node runs as a separate libp2p identity whose peerId no sibling can
79
+ * recompute. Before starting a strand node, a member's control node
80
+ * announces that peerId over the already-authenticated strand-addr RPC, and
81
+ * the receiver holds a short-lived grant for it
82
+ * (`CadreNode.grantDelegateAdmission`). The grant admits the CONNECTION
83
+ * outright, admits the peer's RESERVATION at the seam below (without
84
+ * spending the unauthorized budget), and nothing else — it is deliberately
85
+ * invisible to the protocol guard, so a delegate still gets refused on every
86
+ * members-only protocol.
87
+ *
88
+ * ## Provisional admission
89
+ *
90
+ * A peer the policy cannot place (`'admit-provisionally'`) gets its connection
91
+ * and a deadline — {@link PROVISIONAL_ADMISSION_DEADLINE_MS} at the default
92
+ * declaration; `CadreNode` passes the one derived from its OWN declared link,
93
+ * because the member is the machine that decides. At the deadline the gate asks
94
+ * the policy again:
95
+ *
96
+ * - `'admit'` — the peer has since become a member, holds a delegate grant, or
97
+ * this node now holds a live invitation (a redeeming device's row was
98
+ * seated): the connection stays, and nothing is re-armed;
99
+ * - `'admit-provisionally'` — the connection is closed (a bounded graceful
100
+ * close, with an abort only as the escalation);
101
+ * - the question throws or outlasts the decision deadline — the connection
102
+ * stays (see "Fail-open, deliberately").
103
+ *
104
+ * A connection that is already gone by then costs no question. One peer may hold
105
+ * several provisional connections; each deadline re-asks on its own.
106
+ *
107
+ * NOTE: the gate does not stop a provisionally admitted stranger from being
108
+ * counted into this node's FRET ring and control-database cohort by opening or
109
+ * advertising the party's protocols — FRET and Optimystic decide that from the
110
+ * protocols libp2p records the peer as serving. Ticket
111
+ * `stranger-joins-the-control-cohort-by-advertising-protocols` (blocked).
112
+ *
113
+ * ## The relay-reservation seam
114
+ *
115
+ * A circuit-relay reservation is established by the reserving peer DIALING the
116
+ * relay, so at the relay it rides an inbound connection — and closing that
117
+ * connection kills the reservation. For a genuine member whose `CadrePeer` row
118
+ * has not yet replicated to this node that would NOT be self-healing the way a
119
+ * data connection's close is: an outbound reconcile dial re-establishes a data
120
+ * link, but no outbound dial can grant the REMOTE peer a reservation, and a
121
+ * relay-only peer has no address of its own to dial back — the reservation IS
122
+ * its address. Boot ordering makes the window ordinary (a node reserves at the
123
+ * end of its own `start()`, before its row could have replicated anywhere), and
124
+ * a stalled replication makes it unbounded. So the reservation is decided on its
125
+ * own terms, not by the connection's:
126
+ *
127
+ * - It is decided at libp2p's `denyInboundRelayReservation` hook (the
128
+ * circuit-relay server consults it per RESERVE request): the policy admits
129
+ * members, delegates and configured infra outright, and admits peers it
130
+ * cannot place only within a bounded budget
131
+ * ({@link UnauthorizedReservationBudget}) — a member whose row is in flight
132
+ * always finds a slot under any sane cap, while outsiders cannot annex the
133
+ * party's relay capacity. COUNT and lifetime are the only bounds on such a
134
+ * peer: a party-run relay forwards without libp2p's per-connection data and
135
+ * duration limit by default (`relay-server.ts`), so what a granted slot
136
+ * carries is not capped.
137
+ * - An ADMITTED reservation disarms every provisional deadline the peer holds
138
+ * here, so its connection outlives the deadline even while the peer is still
139
+ * unplaced. A refused one disarms nothing.
140
+ *
141
+ * The deadline clears on reservation ADMISSION, not on the reservation's own
142
+ * success: this gate cannot observe the server-side `reserve()` outcome, so a
143
+ * peer whose admitted reservation is then refused for server capacity keeps its
144
+ * connection until either side closes it — bounded and mute, so harmless.
145
+ *
146
+ * Everything else a control node serves is either libp2p plumbing open to any
147
+ * connection (identify, ping, hole punching, AutoNAT, the relay protocols) or
148
+ * members-only — wake, strand-addr, the Optimystic control-DB protocols and FRET —
149
+ * and the fail-closed layer for all of it is the protocol guard
150
+ * (`control-protocol-guard.ts`), one seam that wraps every handler at dispatch,
151
+ * with a protocol nobody classed treated as members-only. The two layers
152
+ * complement, not duplicate: this connection gate is fail-open over a live DB
153
+ * read and decides only how long a connection lasts, the protocol guard is
154
+ * fail-closed and has NO stranger carve-outs — a live invitation admits a
155
+ * stranger's connection outright for redemption, yet its repo and FRET streams
156
+ * are still refused.
157
+ *
158
+ * ## The bring-up quiet period
159
+ *
160
+ * One state is decided BEFORE any of the above, and is not about the remote peer
161
+ * at all: while this node's control-database bring-up is in flight
162
+ * (`InboundAdmissionPolicy.bringUpInFlight`), the gate denies BOTH directions —
163
+ * `denyDialPeer` and `denyInboundEncryptedConnection` — and then opens.
164
+ *
165
+ * The invariant it protects is "`ControlDatabase.initialize()` runs while this
166
+ * node holds ZERO control connections". Building that database is a long chain
167
+ * of cohort-consulting block probes, and every connected same-party sibling is in
168
+ * the cohort those probes consult. A sibling that has not yet replicated this
169
+ * node's `CadrePeer` row correctly refuses them at its own fail-closed per-stream
170
+ * gate, so ONE connection in this window turns bring-up into
171
+ * `BlockUnavailableError` and `start()` rejects. Retrying cannot converge: the
172
+ * condition that would clear the refusal is this node's own row reaching the
173
+ * sibling, and writing that row needs the database the retry is building. So the
174
+ * only fix is to not be in the conversation yet — which is what this window is.
175
+ *
176
+ * The ordering is arranged so nothing SHOULD open a connection here anyway:
177
+ * `network.relayAddrs` resolves to a listener that dials nothing and reserves
178
+ * after bring-up (`relay-addrs.ts`), `controlNetwork.bootstrapNodes` is dialed
179
+ * after bring-up (`CadreNode.dialControlBootstrapPeers`), and the control-cohort
180
+ * reconcile pass is scheduled post-start. This window is what makes that a property
181
+ * rather than an accident of ordering — the live cases it catches are peers the node
182
+ * remembers from a previous run, which the connection manager auto-dials, and
183
+ * inbound dials.
184
+ *
185
+ * A denial here costs a retry, not a partition: libp2p's connection manager
186
+ * re-dials on its auto-dial cadence, the reservation supervisor re-drives, and a
187
+ * denied inbound peer reconnects. The window opens on bring-up FAILURE too (via
188
+ * `CadreNode.cleanup`), so teardown is never gated.
189
+ *
190
+ * ## Fail-open, deliberately
191
+ *
192
+ * Outside that window this layer never denies, and it closes a provisional
193
+ * connection only on a positive answer that the peer is still unplaced. Any
194
+ * error, missing dependency, timeout or ambiguous state admits the connection
195
+ * outright (and the reservation), or keeps a provisional connection at its
196
+ * deadline, and defers to the fail-closed stream gates — a DB hiccup must not
197
+ * partition a legitimate cadre.
198
+ */
199
+
200
+ import debug from 'debug';
201
+ import type { ConnectionGater, PeerId, MultiaddrConnection } from '@libp2p/interface';
202
+ import { withDeadline } from './control-stream.js';
203
+ import { PARTY_RELAY_RESERVATION_TTL_MS } from './relay-server.js';
204
+ import { ADMISSION_DECISION_TIMEOUT_MS, relayedRequestBudgetMs } from './link-budget.js';
205
+
206
+ const log = debug('sereus:cadre:connection-gater');
207
+
208
+ /**
209
+ * How long a provisionally admitted connection lasts before the gate re-asks the
210
+ * policy and closes it unless the peer is admissible by then (see the module
211
+ * doc's "Provisional admission").
212
+ *
213
+ * {@link relayedRequestBudgetMs}: 28 500 ms at the default declaration. The
214
+ * longest exchange a stranger legitimately starts on a fresh connection is a
215
+ * cadre invitation redemption, and the device abandons each member address after
216
+ * that same budget of its own declared link (`redeemAtMembers`): it covers the
217
+ * dial, the request, the member's catch-up push, the seat and the redemption. So
218
+ * a member never cuts an exchange the device is still waiting on, and a
219
+ * reservation request lands well inside it. This is the value at the default
220
+ * declaration; `CadreNode` passes the one derived from its OWN declaration.
221
+ *
222
+ * NOTE: accepted tradeoff — any stranger can hold a mute connection to any
223
+ * enrolled member for this long, weighed against letting a device redeem an
224
+ * invitation at a member that has not yet received its row (maintainer,
225
+ * 2026-10-07, plan `cadre-invite-redeemable-before-the-row-replicates`). It can
226
+ * open only stranger-open and transport streams (the protocol guard), and
227
+ * libp2p's connection-manager limits bound how many it holds. Revisit if stranger
228
+ * connections show up as load on a member.
229
+ */
230
+ export const PROVISIONAL_ADMISSION_DEADLINE_MS = relayedRequestBudgetMs();
231
+
232
+ /**
233
+ * Bound on the graceful close of an expired provisional connection. It exists
234
+ * because `AbstractMultiaddrConnection.close()` awaits an `idle`/`drain` event
235
+ * when the connection still has unsent bytes, and that wait has no timeout of
236
+ * its own — an unsignalled one never ends. This gate writes nothing to a
237
+ * stranger, so the wait is not reachable from here; the bound is here so a timer
238
+ * callback can never hold an unending await.
239
+ *
240
+ * Applied through {@link withDeadline}, not `AbortSignal.timeout`: the latter is
241
+ * not reliably present on React Native/Hermes, which loads this same module.
242
+ */
243
+ // eslint-disable-next-line no-restricted-syntax -- link-independent: bounds a local connection close inside a timer callback, and expiry aborts the connection instead
244
+ export const PROVISIONAL_ADMISSION_CLOSE_TIMEOUT_MS = 2_000;
245
+
246
+ /**
247
+ * Default cap on concurrent relay reservations held by peers the membership
248
+ * check could not place (see {@link UnauthorizedReservationBudget}). Small on
249
+ * purpose: it exists for the handful of genuine members whose rows are still
250
+ * in flight, not as public relay capacity. Overridable per node via
251
+ * `network.unauthorizedRelayReservationCap` (0 refuses every unauthorized
252
+ * reservation — the strict pre-seam posture).
253
+ *
254
+ * NOTE: this cap shares the relay server's own reservation store, whose
255
+ * party-run default size is `PARTY_RELAY_MAX_RESERVATIONS` (128,
256
+ * `relay-server.ts`); unplaced peers may therefore occupy up to this many of
257
+ * those slots, and the rest are what members and delegates compete for. The two
258
+ * are kept apart by hand — if this is raised, or an embedder shrinks the store
259
+ * through `network.relayServerInit.reservations.maxReservations`, keep this one
260
+ * well under the store's, or a fleet of unplaceable peers can crowd genuine
261
+ * members out of the server's own store (which the gate cannot override).
262
+ */
263
+ export const MAX_UNAUTHORIZED_RELAY_RESERVATIONS = 8;
264
+
265
+ /**
266
+ * The connection-level outcome of the admission policy:
267
+ * - `'admit'` — a peer with a legitimate claim on the connection (member,
268
+ * delegate, infra, open stranger window, or any fail-open state); no deadline.
269
+ * - `'admit-provisionally'` — a peer the policy cannot place (an outsider, a
270
+ * device whose invitation row this node does not hold yet, or a member whose
271
+ * row is still replicating — indistinguishable here): admit the connection,
272
+ * and at the deadline ask again and close it unless the answer is `'admit'`.
273
+ *
274
+ * There is no deny: the gate's only denial is the bring-up quiet period, which
275
+ * is not a judgement of the peer.
276
+ */
277
+ export type InboundConnectionVerdict = 'admit' | 'admit-provisionally';
278
+
279
+ /**
280
+ * The admission decisions the gate defers to — implemented by
281
+ * `CadreNode.admitInboundControlConnection` /
282
+ * `CadreNode.admitControlRelayReservation` (enrollment windows, anchor state,
283
+ * bootstrap infra, delegate grants, the authorized-member set, the
284
+ * unauthorized-reservation budget). Kept injectable so the gater's
285
+ * composition/fail-open behavior is unit-testable without a full node.
286
+ */
287
+ export interface InboundAdmissionPolicy {
288
+ /**
289
+ * Verdict on an inbound encrypted connection from this peer. Asked again at a
290
+ * provisional connection's deadline, so it must answer from current state.
291
+ */
292
+ admitInbound(remotePeerId: string): Promise<InboundConnectionVerdict> | InboundConnectionVerdict;
293
+ /** Should this peer be granted a circuit-relay reservation slot? */
294
+ admitRelayReservation(remotePeerId: string): Promise<boolean> | boolean;
295
+ /**
296
+ * True while this node's control-database bring-up is in flight — the
297
+ * {@link createMembershipConnectionGater} quiet period (see the module doc).
298
+ * Peer-independent, unlike the two decisions above, and SYNCHRONOUS: it is
299
+ * read on the outbound-dial path, where an await would be a new stall.
300
+ *
301
+ * Optional — a policy that omits it is never quiet, which is the right default
302
+ * for every caller that is not a booting `CadreNode`.
303
+ */
304
+ bringUpInFlight?(): boolean;
305
+ }
306
+
307
+ /**
308
+ * Bounded budget of concurrent relay reservations for peers the membership
309
+ * check could not place. `tryAdmit` is the whole surface: an already-admitted
310
+ * peer refreshes its entry (a reservation refresh never double-counts), a new
311
+ * peer takes a free slot or is refused. Entries expire after `ttlMs`, which
312
+ * `CadreNode` passes as the relay server's own resolved `reservationTtl`
313
+ * (`relay-server.ts`): the server holds an unrefreshed reservation exactly that
314
+ * long, and a live reserver re-requests (re-hitting the admission hook,
315
+ * refreshing its entry) well before expiry — so the live entry count tracks the
316
+ * server's own occupancy without this module reaching into the server's
317
+ * reservation store. Injectable `now` keeps expiry testable without fake
318
+ * timers. Authorized members and delegates are never run through this — the
319
+ * policy admits them before consulting the budget, and `release`s the slot such
320
+ * a peer took while it was still unplaceable, so the boot-ordering window a
321
+ * member passes through costs the budget nothing once its row lands.
322
+ */
323
+ export class UnauthorizedReservationBudget {
324
+ private readonly admitted = new Map<string, number>();
325
+
326
+ constructor(
327
+ /** Most peers admitted at once — `network.unauthorizedRelayReservationCap`, resolved. */
328
+ readonly cap: number = MAX_UNAUTHORIZED_RELAY_RESERVATIONS,
329
+ private readonly ttlMs: number = PARTY_RELAY_RESERVATION_TTL_MS
330
+ ) {}
331
+
332
+ /** Number of live (unexpired at last prune) entries — test/diagnostic surface. */
333
+ get size(): number {
334
+ return this.admitted.size;
335
+ }
336
+
337
+ /** Admit (or refresh) `remotePeerId` if a slot is free; false when the cap is spent. */
338
+ tryAdmit(remotePeerId: string, now: number = Date.now()): boolean {
339
+ this.prune(now);
340
+ if (!this.admitted.has(remotePeerId) && this.admitted.size >= this.cap) {
341
+ log('Unauthorized-reservation budget spent (%d/%d) — refusing %s', this.admitted.size, this.cap, remotePeerId);
342
+ return false;
343
+ }
344
+ this.admitted.set(remotePeerId, now + this.ttlMs);
345
+ return true;
346
+ }
347
+
348
+ /**
349
+ * Give back the slot `remotePeerId` holds, if any — called when the peer has
350
+ * become admissible on its own merits (its membership row replicated, or a
351
+ * delegate grant landed), so the slot it took during the boot-ordering window
352
+ * does not stay spent for the remaining TTL on a peer that no longer needs it.
353
+ */
354
+ release(remotePeerId: string): void {
355
+ this.admitted.delete(remotePeerId);
356
+ }
357
+
358
+ private prune(now: number): void {
359
+ for (const [peerId, expiresAt] of this.admitted) {
360
+ if (expiresAt <= now) {
361
+ this.admitted.delete(peerId);
362
+ }
363
+ }
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Build the control node's connection gater: the caller-supplied gater (if any)
369
+ * with membership admission composed onto `denyInboundEncryptedConnection` —
370
+ * the earliest checkpoint where the remote's authenticated PeerId is known —
371
+ * and reservation admission composed onto `denyInboundRelayReservation` — the
372
+ * hook the circuit-relay server consults per RESERVE request (inert on a node
373
+ * whose relay server is off; libp2p never calls it there).
374
+ *
375
+ * `denyDialPeer` is composed too, but ONLY for the bring-up quiet period (see
376
+ * the module doc): outside that window outbound dials are never gated by
377
+ * membership — this node decides for itself who to talk to.
378
+ *
379
+ * Composition semantics: every hook of `base` is preserved as-is; on the three
380
+ * composed hooks a deny from the base gater denies, and so does the quiet
381
+ * period. The admission policy never denies a connection. A policy error — or a
382
+ * decision slower than `decisionTimeoutMs` — takes the fail-open outcome
383
+ * (connection admitted outright / reservation admitted, see module doc); the
384
+ * base gater's verdict is still honored first.
385
+ *
386
+ * An `'admit-provisionally'` verdict admits the connection and arms a
387
+ * `provisionalDeadlineMs` timer against it. When the timer fires the policy is
388
+ * asked again, and the underlying `MultiaddrConnection` is closed unless it now
389
+ * answers `'admit'`; a reservation for that peer ADMITTED at the reservation
390
+ * hook disarms the timer first.
391
+ *
392
+ * NOTE: `base` is spread, so a gater passed as a CLASS INSTANCE would lose its
393
+ * prototype methods; every caller in this repo (and libp2p's own default)
394
+ * supplies a plain object. If a class-based gater ever shows up, delegate
395
+ * per-hook instead of spreading.
396
+ *
397
+ * Deny timing, as observed by the denied dialer (a quiet-period or base-gater
398
+ * deny): noise negotiates the muxer in the security handshake's early data, so
399
+ * the DIALER's upgrade may complete (its `dial()` resolves) before this
400
+ * receiver-side hook runs. The deny then aborts the receiver's upgrade — the
401
+ * receiver never registers the connection and never creates its muxer, so no
402
+ * protocol can ever be negotiated — and the dialer sees its "open" connection
403
+ * close moments later.
404
+ *
405
+ * Control node only: strand cohort nodes legitimately connect cross-party
406
+ * peers, so cadre membership never gates them. An OPEN strand's node receives
407
+ * the raw configured gater unchanged; a CLOSED strand's node composes its own
408
+ * revoked-peer denial onto it instead — a deny-list on positive revocation
409
+ * evidence, not this module's membership admission — see
410
+ * `strand-revocation-enforcer.ts`.
411
+ */
412
+ export function createMembershipConnectionGater(
413
+ policy: InboundAdmissionPolicy,
414
+ base?: ConnectionGater,
415
+ decisionTimeoutMs: number = ADMISSION_DECISION_TIMEOUT_MS,
416
+ provisionalDeadlineMs: number = PROVISIONAL_ADMISSION_DEADLINE_MS
417
+ ): ConnectionGater {
418
+ const decideInbound = (remotePeerId: string): Promise<InboundConnectionVerdict> => decideWithinDeadline(
419
+ () => policy.admitInbound(remotePeerId), 'admit', decisionTimeoutMs, `admitInbound(${remotePeerId})`
420
+ );
421
+ const provisional = new ProvisionalAdmissions(provisionalDeadlineMs, decideInbound);
422
+ const quiet = (): boolean => policy.bringUpInFlight?.() ?? false;
423
+ return {
424
+ ...base,
425
+ denyDialPeer: async (peerId: PeerId): Promise<boolean> => {
426
+ if (await base?.denyDialPeer?.(peerId)) {
427
+ return true;
428
+ }
429
+ if (quiet()) {
430
+ log('Control-database bring-up in flight — refusing the outbound dial to %s', peerId.toString());
431
+ return true;
432
+ }
433
+ return false;
434
+ },
435
+ denyInboundEncryptedConnection: async (peerId: PeerId, maConn: MultiaddrConnection): Promise<boolean> => {
436
+ if (await base?.denyInboundEncryptedConnection?.(peerId, maConn)) {
437
+ return true;
438
+ }
439
+ if (quiet()) {
440
+ log('Control-database bring-up in flight — refusing the inbound connection from %s', peerId.toString());
441
+ return true;
442
+ }
443
+ const remotePeerId = peerId.toString();
444
+ let verdict: InboundConnectionVerdict;
445
+ try {
446
+ verdict = await decideInbound(remotePeerId);
447
+ } catch (error) {
448
+ log('admitInbound threw for %s — admitting (fail-open; stream gates decide): %o', remotePeerId, error);
449
+ return false;
450
+ }
451
+ if (verdict === 'admit-provisionally') {
452
+ provisional.arm(remotePeerId, maConn);
453
+ }
454
+ return false;
455
+ },
456
+ denyInboundRelayReservation: async (peerId: PeerId): Promise<boolean> => {
457
+ if (await base?.denyInboundRelayReservation?.(peerId)) {
458
+ return true;
459
+ }
460
+ const remotePeerId = peerId.toString();
461
+ let admitted: boolean;
462
+ try {
463
+ admitted = await decideWithinDeadline(
464
+ () => policy.admitRelayReservation(remotePeerId), true, decisionTimeoutMs, `admitRelayReservation(${remotePeerId})`
465
+ );
466
+ } catch (error) {
467
+ log('admitRelayReservation threw for %s — admitting (fail-open): %o', remotePeerId, error);
468
+ admitted = true;
469
+ }
470
+ if (admitted) {
471
+ provisional.disarm(remotePeerId);
472
+ }
473
+ return !admitted;
474
+ }
475
+ };
476
+ }
477
+
478
+ /**
479
+ * Run one admission decision under `timeoutMs`, resolving to `fallback` (the
480
+ * fail-open outcome) if it has not settled in time — see
481
+ * {@link ADMISSION_DECISION_TIMEOUT_MS} for why an unbounded await is not safe
482
+ * on the connection hook. The timer is always cleared so a decided call never
483
+ * holds the event loop open. Exported for the strand revoked-peer gate
484
+ * (`strand-revocation-enforcer.ts`), which bounds its connection hooks with the
485
+ * same fail-open contract.
486
+ */
487
+ export async function decideWithinDeadline<T>(
488
+ decide: () => Promise<T> | T,
489
+ fallback: T,
490
+ timeoutMs: number,
491
+ what: string
492
+ ): Promise<T> {
493
+ let timer: ReturnType<typeof setTimeout> | undefined;
494
+ try {
495
+ return await Promise.race([
496
+ Promise.resolve().then(decide),
497
+ new Promise<T>((resolve) => {
498
+ timer = setTimeout(() => {
499
+ log('%s exceeded %dms — taking the fail-open outcome (stream gates decide)', what, timeoutMs);
500
+ resolve(fallback);
501
+ }, timeoutMs);
502
+ })
503
+ ]);
504
+ } finally {
505
+ clearTimeout(timer);
506
+ }
507
+ }
508
+
509
+ /** One armed provisional deadline: the connection it may close, and its timer. */
510
+ interface ProvisionalAdmission {
511
+ maConn: MultiaddrConnection;
512
+ timer: ReturnType<typeof setTimeout>;
513
+ }
514
+
515
+ /**
516
+ * The deadlines of `'admit-provisionally'` connections, keyed by remote peerId
517
+ * (a Set per peer — one peer can hold several in-flight connections). `arm`
518
+ * starts a timer that re-asks the policy and closes the connection unless it now
519
+ * admits; `disarm` (called when a reservation for that peer is admitted) cancels
520
+ * every pending deadline for the peer, one whose question is already out
521
+ * included. Timers are unref'd so an armed deadline never holds a process open.
522
+ *
523
+ * Disarming is final for the connections it cancelled: a peer that reserved
524
+ * once and then lets its reservation lapse keeps a mute connection (the
525
+ * fail-closed stream gates refuse it every members-only protocol) until either
526
+ * side closes it. Bounded — only a peer the reservation policy already admitted
527
+ * can reach that state, so unplaceable peers are bounded by the budget cap.
528
+ */
529
+ class ProvisionalAdmissions {
530
+ private readonly byPeer = new Map<string, Set<ProvisionalAdmission>>();
531
+
532
+ constructor(
533
+ private readonly deadlineMs: number,
534
+ private readonly decide: (remotePeerId: string) => Promise<InboundConnectionVerdict>
535
+ ) {}
536
+
537
+ arm(remotePeerId: string, maConn: MultiaddrConnection): void {
538
+ const entry: ProvisionalAdmission = {
539
+ maConn,
540
+ timer: setTimeout(() => void this.expire(remotePeerId, entry), this.deadlineMs)
541
+ };
542
+ (entry.timer as { unref?: () => void }).unref?.();
543
+ let entries = this.byPeer.get(remotePeerId);
544
+ if (!entries) {
545
+ entries = new Set();
546
+ this.byPeer.set(remotePeerId, entries);
547
+ }
548
+ entries.add(entry);
549
+ log('Admitted %s provisionally — closing the connection in %dms unless it is admissible by then', remotePeerId, this.deadlineMs);
550
+ }
551
+
552
+ disarm(remotePeerId: string): void {
553
+ const entries = this.byPeer.get(remotePeerId);
554
+ if (!entries) {
555
+ return;
556
+ }
557
+ this.byPeer.delete(remotePeerId);
558
+ for (const entry of entries) {
559
+ clearTimeout(entry.timer);
560
+ }
561
+ }
562
+
563
+ private async expire(remotePeerId: string, entry: ProvisionalAdmission): Promise<void> {
564
+ if (entry.maConn.status !== 'open') {
565
+ this.release(remotePeerId, entry);
566
+ return;
567
+ }
568
+ const verdict = await this.recheck(remotePeerId);
569
+ // False when a reservation admitted while the question was out disarmed this deadline.
570
+ if (!this.release(remotePeerId, entry)) {
571
+ return;
572
+ }
573
+ if (verdict === 'admit') {
574
+ log('%s is admissible at its provisional deadline — keeping the connection', remotePeerId);
575
+ return;
576
+ }
577
+ log('Provisional admission expired for %s — still unplaced after %dms, closing the connection', remotePeerId, this.deadlineMs);
578
+ await this.drop(remotePeerId, entry.maConn);
579
+ }
580
+
581
+ /** The policy's answer at the deadline; a throw keeps the connection (fail-open). */
582
+ private async recheck(remotePeerId: string): Promise<InboundConnectionVerdict> {
583
+ try {
584
+ return await this.decide(remotePeerId);
585
+ } catch (error) {
586
+ log('admitInbound threw for %s at its provisional deadline — keeping the connection (fail-open): %o', remotePeerId, error);
587
+ return 'admit';
588
+ }
589
+ }
590
+
591
+ /** Forget `entry`; false when a `disarm` already took it. */
592
+ private release(remotePeerId: string, entry: ProvisionalAdmission): boolean {
593
+ const entries = this.byPeer.get(remotePeerId);
594
+ if (!entries?.delete(entry)) {
595
+ return false;
596
+ }
597
+ if (entries.size === 0) {
598
+ this.byPeer.delete(remotePeerId);
599
+ }
600
+ return true;
601
+ }
602
+
603
+ /**
604
+ * End an expired provisional connection: a bounded graceful close, with
605
+ * `abort()` only as the escalation. The order cannot be reversed — `abort()`
606
+ * marks the connection `aborted`, and `close()` returns immediately on any
607
+ * status that is not `open`, so aborting first would make the close a silent
608
+ * no-op. Closing a connection the peer already dropped returns at once
609
+ * without throwing, so the fallback stays unreached in the ordinary case.
610
+ */
611
+ private async drop(remotePeerId: string, maConn: MultiaddrConnection): Promise<void> {
612
+ try {
613
+ await withDeadline(
614
+ PROVISIONAL_ADMISSION_CLOSE_TIMEOUT_MS,
615
+ `provisional close for ${remotePeerId}`,
616
+ (signal) => maConn.close({ signal })
617
+ );
618
+ return;
619
+ } catch (error) {
620
+ log('Closing the expired provisional connection from %s failed — aborting: %o', remotePeerId, error);
621
+ }
622
+ // NOTE: this fallback cannot actually free a WebSocket. `@libp2p/websockets`'
623
+ // `sendReset()` calls `websocket.close(1006)`, and 1006 is a reserved code
624
+ // RFC 6455 forbids an endpoint from sending, so `ws` throws and
625
+ // `AbstractMessageStream.abort()` swallows it — the local end flips to
626
+ // `aborted` while the socket stays up. Measured against
627
+ // @libp2p/websockets@10.1.3 (see tickets/blocked/report-libp2p-websockets-abort-close-code.md).
628
+ // `MultiaddrConnection` exposes no way down to the raw socket, so this is as
629
+ // far as this layer can go. Revisit — drop the fallback, or go back to a
630
+ // plain `abort()` — once that transport sends a legal reset code.
631
+ try {
632
+ maConn.abort(new Error(`provisional admission expired: still unplaced after ${this.deadlineMs}ms`));
633
+ } catch (error) {
634
+ log('Aborting the expired provisional connection from %s threw: %o', remotePeerId, error);
635
+ }
636
+ }
637
+ }