@serfab/cadre-core 0.10.0 → 0.12.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 (145) hide show
  1. package/README.md +255 -255
  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 +484 -58
  6. package/dist/cadre-node.js +953 -182
  7. package/dist/cadre-node.js.map +1 -1
  8. package/dist/control-cohort.d.ts +26 -0
  9. package/dist/control-cohort.js +26 -0
  10. package/dist/control-cohort.js.map +1 -1
  11. package/dist/control-database.d.ts +222 -125
  12. package/dist/control-database.js +356 -266
  13. package/dist/control-database.js.map +1 -1
  14. package/dist/control-formation-recorder.d.ts +8 -7
  15. package/dist/control-formation-recorder.js +8 -7
  16. package/dist/control-formation-recorder.js.map +1 -1
  17. package/dist/control-read-retry.d.ts +103 -0
  18. package/dist/control-read-retry.js +145 -0
  19. package/dist/control-read-retry.js.map +1 -0
  20. package/dist/control-retry.d.ts +101 -0
  21. package/dist/control-retry.js +108 -0
  22. package/dist/control-retry.js.map +1 -0
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +805 -774
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-write-retry.d.ts +65 -31
  27. package/dist/control-write-retry.js +33 -103
  28. package/dist/control-write-retry.js.map +1 -1
  29. package/dist/delegate-admission.d.ts +17 -15
  30. package/dist/delegate-admission.js +17 -15
  31. package/dist/delegate-admission.js.map +1 -1
  32. package/dist/index.d.ts +7 -5
  33. package/dist/index.js +18 -9
  34. package/dist/index.js.map +1 -1
  35. package/dist/membership-connection-gater.d.ts +211 -25
  36. package/dist/membership-connection-gater.js +309 -29
  37. package/dist/membership-connection-gater.js.map +1 -1
  38. package/dist/peer-addr-book.d.ts +92 -0
  39. package/dist/peer-addr-book.js +220 -0
  40. package/dist/peer-addr-book.js.map +1 -0
  41. package/dist/peer-record.d.ts +26 -0
  42. package/dist/peer-record.js +32 -0
  43. package/dist/peer-record.js.map +1 -1
  44. package/dist/relay-addrs.d.ts +76 -26
  45. package/dist/relay-addrs.js +115 -27
  46. package/dist/relay-addrs.js.map +1 -1
  47. package/dist/relay-reservation.d.ts +20 -15
  48. package/dist/relay-reservation.js +18 -14
  49. package/dist/relay-reservation.js.map +1 -1
  50. package/dist/seed-bootstrap.d.ts +7 -0
  51. package/dist/seed-bootstrap.js +15 -13
  52. package/dist/seed-bootstrap.js.map +1 -1
  53. package/dist/strand-addr-protocol.js +16 -0
  54. package/dist/strand-addr-protocol.js.map +1 -1
  55. package/dist/strand-backfill.js +13 -4
  56. package/dist/strand-backfill.js.map +1 -1
  57. package/dist/strand-cohort.d.ts +4 -37
  58. package/dist/strand-cohort.js +4 -15
  59. package/dist/strand-cohort.js.map +1 -1
  60. package/dist/strand-database.d.ts +11 -16
  61. package/dist/strand-database.js +19 -7
  62. package/dist/strand-database.js.map +1 -1
  63. package/dist/strand-formation-manager.d.ts +18 -17
  64. package/dist/strand-formation-manager.js +25 -27
  65. package/dist/strand-formation-manager.js.map +1 -1
  66. package/dist/strand-formation-protocol.d.ts +7 -7
  67. package/dist/strand-formation-protocol.js +8 -8
  68. package/dist/strand-formation-protocol.js.map +1 -1
  69. package/dist/strand-instance-manager.d.ts +53 -21
  70. package/dist/strand-instance-manager.js +128 -37
  71. package/dist/strand-instance-manager.js.map +1 -1
  72. package/dist/strand-membership-writer.d.ts +113 -19
  73. package/dist/strand-membership-writer.js +219 -51
  74. package/dist/strand-membership-writer.js.map +1 -1
  75. package/dist/strand-solicitation.d.ts +3 -3
  76. package/dist/strand-solicitation.js +4 -5
  77. package/dist/strand-solicitation.js.map +1 -1
  78. package/dist/strand-wake-protocol.d.ts +47 -2
  79. package/dist/strand-wake-protocol.js +76 -6
  80. package/dist/strand-wake-protocol.js.map +1 -1
  81. package/dist/types.d.ts +107 -54
  82. package/dist/types.js.map +1 -1
  83. package/package.json +8 -7
  84. package/src/announce-addrs.ts +93 -0
  85. package/src/arachnode-stub.ts +159 -159
  86. package/src/bootstrap-peer-store-file.ts +44 -44
  87. package/src/bootstrap-peer-store.ts +172 -172
  88. package/src/cadre-node.ts +1026 -194
  89. package/src/canonical-json.ts +30 -30
  90. package/src/control-authorization.ts +114 -114
  91. package/src/control-cohort.ts +130 -103
  92. package/src/control-database.ts +376 -298
  93. package/src/control-formation-recorder.ts +305 -304
  94. package/src/control-read-retry.ts +167 -0
  95. package/src/control-retry.ts +190 -0
  96. package/src/control-schema.ts +817 -786
  97. package/src/control-stream.ts +205 -205
  98. package/src/control-write-retry.ts +383 -473
  99. package/src/delegate-admission.ts +304 -302
  100. package/src/device-token.ts +94 -94
  101. package/src/diagnostics/connection-path.ts +277 -277
  102. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  103. package/src/ed25519-key.ts +134 -134
  104. package/src/enrollment.ts +199 -199
  105. package/src/file-durable-slot.ts +61 -61
  106. package/src/formation-approval.ts +604 -604
  107. package/src/fs-atomic.ts +107 -107
  108. package/src/hibernation-manager.ts +437 -437
  109. package/src/identity-key.ts +109 -109
  110. package/src/index.ts +435 -406
  111. package/src/key-store-file.ts +132 -132
  112. package/src/key-store.ts +99 -99
  113. package/src/membership-connection-gater.ts +368 -39
  114. package/src/node-local-snapshot.ts +260 -260
  115. package/src/peer-addr-book.ts +250 -0
  116. package/src/peer-authorization.ts +259 -259
  117. package/src/peer-record.ts +197 -164
  118. package/src/push-credentials.ts +84 -84
  119. package/src/push-node.ts +64 -64
  120. package/src/push-notifier-apns.ts +247 -247
  121. package/src/push-notifier-fcm.ts +220 -220
  122. package/src/push-notifier-shared.ts +28 -28
  123. package/src/push-notifier.ts +52 -52
  124. package/src/relay-addrs.ts +134 -27
  125. package/src/relay-reservation.ts +22 -17
  126. package/src/seed-bootstrap.ts +15 -15
  127. package/src/seed-trust-policy.ts +140 -140
  128. package/src/strand-addr-protocol.ts +458 -441
  129. package/src/strand-backfill.ts +28 -5
  130. package/src/strand-cohort.ts +38 -77
  131. package/src/strand-database.ts +202 -204
  132. package/src/strand-formation-manager.ts +26 -28
  133. package/src/strand-formation-protocol.ts +692 -692
  134. package/src/strand-instance-manager.ts +636 -553
  135. package/src/strand-member-key.ts +39 -39
  136. package/src/strand-member-registry.ts +182 -182
  137. package/src/strand-membership-writer.ts +1627 -1430
  138. package/src/strand-solicitation.ts +471 -472
  139. package/src/strand-transport-key.ts +58 -58
  140. package/src/strand-wake-payload.ts +32 -32
  141. package/src/strand-wake-protocol.ts +400 -314
  142. package/src/strand-watcher.ts +314 -314
  143. package/src/trusted-owner-store-file.ts +41 -41
  144. package/src/trusted-owner-store.ts +171 -171
  145. package/src/types.ts +1354 -1303
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Control-network inbound connection gate (defense-in-depth).
2
+ * Control-network inbound admission gates (defense-in-depth): the
3
+ * encrypted-connection checkpoint and the circuit-relay reservation checkpoint.
3
4
  *
4
5
  * Layer 2 of the membership enforcement chain: the PRIMARY gates are per-stream
5
6
  * — every sensitive sereus control protocol rejects a peer that fails the
@@ -10,7 +11,9 @@
10
11
  * time. This module adds the opportunistic connection-level layer on top: a
11
12
  * peer this node can positively determine is NOT authorized is refused at the
12
13
  * encrypted-connection checkpoint, before any protocol negotiation, so a
13
- * known-nothing outsider is never even in the conversation.
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").
14
17
  *
15
18
  * ## The stranger allowlist (the ONE place it is defined)
16
19
  *
@@ -45,14 +48,54 @@
45
48
  *
46
49
  * - **Announced delegate peers** (`delegate-admission.ts`). A member's strand
47
50
  * node runs as a separate libp2p identity whose peerId no sibling can
48
- * recompute, so a relay-running control node would deny its circuit-relay
49
- * reservation. Before starting a strand node, a member's control node
51
+ * recompute. Before starting a strand node, a member's control node
50
52
  * announces that peerId over the already-authenticated strand-addr RPC, and
51
53
  * the receiver holds a short-lived grant for it
52
- * (`CadreNode.grantDelegateAdmission`). The grant admits the CONNECTION and
53
- * nothing else — a reservation needs no stream — and is deliberately
54
- * invisible to the per-stream gate below, so a delegate still gets refused
55
- * on every members-only protocol.
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.
89
+ * - An `'admit-for-relay'` connection that is NOT reserving is dropped: it has
90
+ * {@link RELAY_ADMISSION_RESERVE_DEADLINE_MS} to get a reservation ADMITTED
91
+ * at that hook, after which the underlying connection is aborted. The
92
+ * guarantee above thus weakens on relay-enabled nodes from "never in the
93
+ * conversation" to "in it briefly, and can speak nothing".
94
+ *
95
+ * The deadline clears on reservation ADMISSION, not on the reservation's own
96
+ * success: this gate cannot observe the server-side `reserve()` outcome, so a
97
+ * peer whose admitted reservation is then refused for server capacity keeps its
98
+ * connection until either side closes it — bounded and mute, so harmless.
56
99
  *
57
100
  * Everything else a control node handles — the Optimystic control-DB protocols
58
101
  * (`/optimystic/control-<party>/{repo,cluster,sync,block-transfer}/…`), wake
@@ -70,12 +113,45 @@
70
113
  * stranger carve-outs — an enrollment window admits a stranger's connection
71
114
  * for seed delivery, yet its repo streams are still refused.
72
115
  *
116
+ * ## The bring-up quiet period
117
+ *
118
+ * One state is decided BEFORE any of the above, and is not about the remote peer
119
+ * at all: while this node's control-database bring-up is in flight
120
+ * (`InboundAdmissionPolicy.bringUpInFlight`), the gate denies BOTH directions —
121
+ * `denyDialPeer` and `denyInboundEncryptedConnection` — and then opens.
122
+ *
123
+ * The invariant it protects is "`ControlDatabase.initialize()` runs while this
124
+ * node holds ZERO control connections". Building that database is a long chain
125
+ * of cohort-consulting block probes, and every connected same-party sibling is in
126
+ * the cohort those probes consult. A sibling that has not yet replicated this
127
+ * node's `CadrePeer` row correctly refuses them at its own fail-closed per-stream
128
+ * gate, so ONE connection in this window turns bring-up into
129
+ * `BlockUnavailableError` and `start()` rejects. Retrying cannot converge: the
130
+ * condition that would clear the refusal is this node's own row reaching the
131
+ * sibling, and writing that row needs the database the retry is building. So the
132
+ * only fix is to not be in the conversation yet — which is what this window is.
133
+ *
134
+ * The ordering is arranged so nothing SHOULD open a connection here anyway:
135
+ * `network.relayAddrs` resolves to a listener that dials nothing and reserves
136
+ * after bring-up (`relay-addrs.ts`), and the control-cohort reconcile pass is
137
+ * scheduled post-start. This window is what makes that a property rather than an
138
+ * accident of ordering — the live case it actually catches is
139
+ * `controlNetwork.bootstrapNodes`, where `@libp2p/bootstrap` emits its discovery
140
+ * events ~1 s after `libp2p.start()` and the connection manager auto-dials from
141
+ * there, which is a race bring-up wins only while raw-storage latency stays low.
142
+ *
143
+ * A denial here costs a retry, not a partition: libp2p's connection manager
144
+ * re-dials on its auto-dial cadence, the reservation supervisor re-drives, and a
145
+ * denied inbound peer reconnects. The window opens on bring-up FAILURE too (via
146
+ * `CadreNode.cleanup`), so teardown is never gated.
147
+ *
73
148
  * ## Fail-open, deliberately
74
149
  *
75
- * This layer only ever denies on a POSITIVE determination of "unauthorized
76
- * outsider while no stranger path is open". Any error, missing dependency, or
77
- * ambiguous state admits the connection and defers to the fail-closed stream
78
- * gates — a DB hiccup must not partition a legitimate cadre.
150
+ * Outside that window this layer only ever denies on a POSITIVE determination of
151
+ * "unauthorized outsider while no stranger path is open". Any error, missing
152
+ * dependency, or ambiguous state admits the connection (and the reservation) and
153
+ * defers to the fail-closed stream gates — a DB hiccup must not partition a
154
+ * legitimate cadre.
79
155
  */
80
156
 
81
157
  import debug from 'debug';
@@ -103,7 +179,8 @@ export const STRANGER_OPEN_PROTOCOLS: readonly string[] = [SEED_PROTOCOL, FORMAT
103
179
  export const DEFAULT_ENROLLMENT_WINDOW_MS = 30 * 60 * 1000;
104
180
 
105
181
  /**
106
- * Deadline for one admission decision, after which the connection is ADMITTED.
182
+ * Deadline for one admission decision, after which the fail-open outcome is
183
+ * used (connection admitted / reservation admitted).
107
184
  *
108
185
  * libp2p awaits `denyInboundEncryptedConnection` inside the inbound upgrade
109
186
  * WITHOUT racing its inbound-upgrade timeout signal (unlike the pre-encryption
@@ -118,26 +195,164 @@ export const DEFAULT_ENROLLMENT_WINDOW_MS = 30 * 60 * 1000;
118
195
  export const ADMISSION_DECISION_TIMEOUT_MS = 2_000;
119
196
 
120
197
  /**
121
- * The admission decision the gate defers to — implemented by
122
- * `CadreNode.admitInboundControlConnection` (enrollment windows, anchor state,
123
- * bootstrap infra, the authorized-member set). Kept injectable so the gater's
198
+ * How long an `'admit-for-relay'` connection may exist without a relay
199
+ * reservation being ADMITTED at the `denyInboundRelayReservation` hook, after
200
+ * which the gate aborts the underlying connection. A reserving client asks for
201
+ * its slot immediately after the connection upgrades (`relay-reservation.ts`
202
+ * dials and requests in one drive; a strand node's configured circuit listener
203
+ * does the same from inside its own `listen()`), so a connection idle past this
204
+ * deadline is not reserving.
205
+ */
206
+ export const RELAY_ADMISSION_RESERVE_DEADLINE_MS = 5_000;
207
+
208
+ /**
209
+ * Default cap on concurrent relay reservations held by peers the membership
210
+ * check could not place (see {@link UnauthorizedReservationBudget}). Small on
211
+ * purpose: it exists for the handful of genuine members whose rows are still
212
+ * in flight, not as public relay capacity. Overridable per node via
213
+ * `network.unauthorizedRelayReservationCap` (0 refuses every unauthorized
214
+ * reservation — the strict pre-seam posture).
215
+ *
216
+ * NOTE: this cap shares the relay server's own reservation store, whose default
217
+ * size is 15 (`@libp2p/circuit-relay-v2`'s `DEFAULT_MAX_RESERVATION_STORE_SIZE`);
218
+ * unplaced peers may therefore occupy up to this many of those slots, and the
219
+ * rest are what members and delegates compete for. This module cannot read the
220
+ * server's size, so the two are kept apart by hand — if either is raised, keep
221
+ * this one well under the store's, or a fleet of unplaceable peers can crowd
222
+ * genuine members out of the server's own store (which the gate cannot override).
223
+ */
224
+ export const MAX_UNAUTHORIZED_RELAY_RESERVATIONS = 8;
225
+
226
+ /**
227
+ * How long one {@link UnauthorizedReservationBudget} entry occupies a slot
228
+ * without a refresh. Mirrors the relay server's own default reservation TTL
229
+ * (`@libp2p/circuit-relay-v2`'s `DEFAULT_MAX_RESERVATION_TTL`, 2 h): the server
230
+ * holds an unrefreshed reservation exactly that long, and a live reserver
231
+ * re-requests (re-hitting the admission hook, refreshing its entry) well before
232
+ * expiry — so the live entry count tracks the server's own occupancy without
233
+ * this module reaching into the server's reservation store.
234
+ *
235
+ * NOTE: a mirror, not a live coupling — if the relay server is ever configured
236
+ * with a non-default `reservationTtl` (db-p2p's `relayServerInit`), update this
237
+ * constant alongside it or the budget's occupancy drifts from the server's.
238
+ */
239
+ export const UNAUTHORIZED_RESERVATION_TTL_MS = 2 * 60 * 60 * 1000;
240
+
241
+ /**
242
+ * The connection-level outcome of the admission policy:
243
+ * - `'admit'` — a peer with a legitimate claim on the connection (member,
244
+ * delegate, infra, open stranger window, or any fail-open state).
245
+ * - `'deny'` — positively an outsider, and this node runs no relay server, so
246
+ * the connection can carry nothing legitimate.
247
+ * - `'admit-for-relay'` — positively an outsider (or an unreplicated member —
248
+ * indistinguishable), but this node runs the relay server: admit the
249
+ * connection so a reservation can be asked for, decide at the reservation
250
+ * seam, and drop the connection if no reservation is admitted in time.
251
+ */
252
+ export type InboundConnectionVerdict = 'admit' | 'deny' | 'admit-for-relay';
253
+
254
+ /**
255
+ * The admission decisions the gate defers to — implemented by
256
+ * `CadreNode.admitInboundControlConnection` /
257
+ * `CadreNode.admitControlRelayReservation` (enrollment windows, anchor state,
258
+ * bootstrap infra, delegate grants, the authorized-member set, the
259
+ * unauthorized-reservation budget). Kept injectable so the gater's
124
260
  * composition/fail-open behavior is unit-testable without a full node.
125
261
  */
126
262
  export interface InboundAdmissionPolicy {
127
- /** Should an inbound encrypted connection from this peer be admitted? */
128
- admitInbound(remotePeerId: string): Promise<boolean> | boolean;
263
+ /** Verdict on an inbound encrypted connection from this peer. */
264
+ admitInbound(remotePeerId: string): Promise<InboundConnectionVerdict> | InboundConnectionVerdict;
265
+ /** Should this peer be granted a circuit-relay reservation slot? */
266
+ admitRelayReservation(remotePeerId: string): Promise<boolean> | boolean;
267
+ /**
268
+ * True while this node's control-database bring-up is in flight — the
269
+ * {@link createMembershipConnectionGater} quiet period (see the module doc).
270
+ * Peer-independent, unlike the two decisions above, and SYNCHRONOUS: it is
271
+ * read on the outbound-dial path, where an await would be a new stall.
272
+ *
273
+ * Optional — a policy that omits it is never quiet, which is the right default
274
+ * for every caller that is not a booting `CadreNode`.
275
+ */
276
+ bringUpInFlight?(): boolean;
277
+ }
278
+
279
+ /**
280
+ * Bounded budget of concurrent relay reservations for peers the membership
281
+ * check could not place. `tryAdmit` is the whole surface: an already-admitted
282
+ * peer refreshes its entry (a reservation refresh never double-counts), a new
283
+ * peer takes a free slot or is refused. Entries expire after `ttlMs` (see
284
+ * {@link UNAUTHORIZED_RESERVATION_TTL_MS} for why that mirrors the relay
285
+ * server's own hold). 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
+ private readonly cap: number = MAX_UNAUTHORIZED_RELAY_RESERVATIONS,
296
+ private readonly ttlMs: number = UNAUTHORIZED_RESERVATION_TTL_MS
297
+ ) {}
298
+
299
+ /** Number of live (unexpired at last prune) entries — test/diagnostic surface. */
300
+ get size(): number {
301
+ return this.admitted.size;
302
+ }
303
+
304
+ /** Admit (or refresh) `remotePeerId` if a slot is free; false when the cap is spent. */
305
+ tryAdmit(remotePeerId: string, now: number = Date.now()): boolean {
306
+ this.prune(now);
307
+ if (!this.admitted.has(remotePeerId) && this.admitted.size >= this.cap) {
308
+ log('Unauthorized-reservation budget spent (%d/%d) — refusing %s', this.admitted.size, this.cap, remotePeerId);
309
+ return false;
310
+ }
311
+ this.admitted.set(remotePeerId, now + this.ttlMs);
312
+ return true;
313
+ }
314
+
315
+ /**
316
+ * Give back the slot `remotePeerId` holds, if any — called when the peer has
317
+ * become admissible on its own merits (its membership row replicated, or a
318
+ * delegate grant landed), so the slot it took during the boot-ordering window
319
+ * does not stay spent for the remaining TTL on a peer that no longer needs it.
320
+ */
321
+ release(remotePeerId: string): void {
322
+ this.admitted.delete(remotePeerId);
323
+ }
324
+
325
+ private prune(now: number): void {
326
+ for (const [peerId, expiresAt] of this.admitted) {
327
+ if (expiresAt <= now) {
328
+ this.admitted.delete(peerId);
329
+ }
330
+ }
331
+ }
129
332
  }
130
333
 
131
334
  /**
132
335
  * Build the control node's connection gater: the caller-supplied gater (if any)
133
336
  * with membership admission composed onto `denyInboundEncryptedConnection` —
134
- * the earliest checkpoint where the remote's authenticated PeerId is known.
337
+ * the earliest checkpoint where the remote's authenticated PeerId is known —
338
+ * and reservation admission composed onto `denyInboundRelayReservation` — the
339
+ * hook the circuit-relay server consults per RESERVE request (inert on a node
340
+ * whose relay server is off; libp2p never calls it there).
341
+ *
342
+ * `denyDialPeer` is composed too, but ONLY for the bring-up quiet period (see
343
+ * the module doc): outside that window outbound dials are never gated by
344
+ * membership — this node decides for itself who to talk to.
345
+ *
346
+ * Composition semantics: every hook of `base` is preserved as-is; on the three
347
+ * composed hooks a deny from EITHER the base gater or the admission policy
348
+ * denies. A policy error — or a decision slower than `decisionTimeoutMs` —
349
+ * takes the fail-open outcome (connection admitted / reservation admitted, see
350
+ * module doc); the base gater's verdict is still honored first.
135
351
  *
136
- * Composition semantics: every hook of `base` is preserved as-is; on the
137
- * inbound-encrypted hook a deny from EITHER the base gater or the admission
138
- * policy denies. A policy error — or a decision slower than
139
- * `decisionTimeoutMs` — admits (fail-open, see module doc); the base gater's
140
- * verdict is still honored first.
352
+ * An `'admit-for-relay'` verdict admits the connection and arms a
353
+ * `reserveDeadlineMs` timer against it; the timer is disarmed when a
354
+ * reservation for that peer is ADMITTED at the reservation hook, and aborts the
355
+ * underlying `MultiaddrConnection` when it fires first.
141
356
  *
142
357
  * NOTE: `base` is spread, so a gater passed as a CLASS INSTANCE would lose its
143
358
  * prototype methods; every caller in this repo (and libp2p's own default)
@@ -157,44 +372,90 @@ export interface InboundAdmissionPolicy {
157
372
  export function createMembershipConnectionGater(
158
373
  policy: InboundAdmissionPolicy,
159
374
  base?: ConnectionGater,
160
- decisionTimeoutMs: number = ADMISSION_DECISION_TIMEOUT_MS
375
+ decisionTimeoutMs: number = ADMISSION_DECISION_TIMEOUT_MS,
376
+ reserveDeadlineMs: number = RELAY_ADMISSION_RESERVE_DEADLINE_MS
161
377
  ): ConnectionGater {
378
+ const pendingReservations = new PendingReserveDeadlines(reserveDeadlineMs);
379
+ const quiet = (): boolean => policy.bringUpInFlight?.() ?? false;
162
380
  return {
163
381
  ...base,
382
+ denyDialPeer: async (peerId: PeerId): Promise<boolean> => {
383
+ if (await base?.denyDialPeer?.(peerId)) {
384
+ return true;
385
+ }
386
+ if (quiet()) {
387
+ log('Control-database bring-up in flight — refusing the outbound dial to %s', peerId.toString());
388
+ return true;
389
+ }
390
+ return false;
391
+ },
164
392
  denyInboundEncryptedConnection: async (peerId: PeerId, maConn: MultiaddrConnection): Promise<boolean> => {
165
393
  if (await base?.denyInboundEncryptedConnection?.(peerId, maConn)) {
166
394
  return true;
167
395
  }
396
+ if (quiet()) {
397
+ log('Control-database bring-up in flight — refusing the inbound connection from %s', peerId.toString());
398
+ return true;
399
+ }
168
400
  const remotePeerId = peerId.toString();
401
+ let verdict: InboundConnectionVerdict;
169
402
  try {
170
- return !(await admitWithinDeadline(policy, remotePeerId, decisionTimeoutMs));
403
+ verdict = await decideWithinDeadline(
404
+ () => policy.admitInbound(remotePeerId), 'admit', decisionTimeoutMs, `admitInbound(${remotePeerId})`
405
+ );
171
406
  } catch (error) {
172
407
  log('admitInbound threw for %s — admitting (fail-open; stream gates decide): %o', remotePeerId, error);
173
408
  return false;
174
409
  }
410
+ if (verdict === 'admit-for-relay') {
411
+ pendingReservations.arm(remotePeerId, maConn);
412
+ return false;
413
+ }
414
+ return verdict === 'deny';
415
+ },
416
+ denyInboundRelayReservation: async (peerId: PeerId): Promise<boolean> => {
417
+ if (await base?.denyInboundRelayReservation?.(peerId)) {
418
+ return true;
419
+ }
420
+ const remotePeerId = peerId.toString();
421
+ let admitted: boolean;
422
+ try {
423
+ admitted = await decideWithinDeadline(
424
+ () => policy.admitRelayReservation(remotePeerId), true, decisionTimeoutMs, `admitRelayReservation(${remotePeerId})`
425
+ );
426
+ } catch (error) {
427
+ log('admitRelayReservation threw for %s — admitting (fail-open): %o', remotePeerId, error);
428
+ admitted = true;
429
+ }
430
+ if (admitted) {
431
+ pendingReservations.disarm(remotePeerId);
432
+ }
433
+ return !admitted;
175
434
  }
176
435
  };
177
436
  }
178
437
 
179
438
  /**
180
- * Run the admission decision under {@link ADMISSION_DECISION_TIMEOUT_MS},
181
- * resolving to "admit" if it has not settled in time (see that constant for why
182
- * an unbounded await is not safe here). The timer is always cleared so a decided
183
- * connection never holds the event loop open.
439
+ * Run one admission decision under `timeoutMs`, resolving to `fallback` (the
440
+ * fail-open outcome) if it has not settled in time — see
441
+ * {@link ADMISSION_DECISION_TIMEOUT_MS} for why an unbounded await is not safe
442
+ * on the connection hook. The timer is always cleared so a decided call never
443
+ * holds the event loop open.
184
444
  */
185
- async function admitWithinDeadline(
186
- policy: InboundAdmissionPolicy,
187
- remotePeerId: string,
188
- timeoutMs: number
189
- ): Promise<boolean> {
445
+ async function decideWithinDeadline<T>(
446
+ decide: () => Promise<T> | T,
447
+ fallback: T,
448
+ timeoutMs: number,
449
+ what: string
450
+ ): Promise<T> {
190
451
  let timer: ReturnType<typeof setTimeout> | undefined;
191
452
  try {
192
453
  return await Promise.race([
193
- Promise.resolve(policy.admitInbound(remotePeerId)),
194
- new Promise<boolean>((resolve) => {
454
+ Promise.resolve().then(decide),
455
+ new Promise<T>((resolve) => {
195
456
  timer = setTimeout(() => {
196
- log('admitInbound exceeded %dms for %s — admitting (fail-open; stream gates decide)', timeoutMs, remotePeerId);
197
- resolve(true);
457
+ log('%s exceeded %dms — taking the fail-open outcome (stream gates decide)', what, timeoutMs);
458
+ resolve(fallback);
198
459
  }, timeoutMs);
199
460
  })
200
461
  ]);
@@ -202,3 +463,71 @@ async function admitWithinDeadline(
202
463
  clearTimeout(timer);
203
464
  }
204
465
  }
466
+
467
+ /** One armed not-reserving deadline: the connection it will abort, and its timer. */
468
+ interface PendingReserveDeadline {
469
+ maConn: MultiaddrConnection;
470
+ timer: ReturnType<typeof setTimeout>;
471
+ }
472
+
473
+ /**
474
+ * The not-reserving deadlines for `'admit-for-relay'` connections, keyed by
475
+ * remote peerId (a Set per peer — one peer can hold several in-flight
476
+ * connections). `arm` starts a timer that aborts the connection; `disarm`
477
+ * (called when a reservation for that peer is admitted) cancels every pending
478
+ * timer for the peer. Timers are unref'd so an armed deadline never holds a
479
+ * process open, and a timer that fires against an already-closed connection is
480
+ * a swallowed no-op.
481
+ *
482
+ * Disarming is final for the connections it cancelled: a peer that reserved
483
+ * once and then lets its reservation lapse keeps a mute connection (the
484
+ * fail-closed stream gates refuse it every members-only protocol) until either
485
+ * side closes it. Bounded — only a peer the reservation policy already admitted
486
+ * can reach that state, so unplaceable peers are bounded by the budget cap.
487
+ */
488
+ class PendingReserveDeadlines {
489
+ private readonly byPeer = new Map<string, Set<PendingReserveDeadline>>();
490
+
491
+ constructor(private readonly deadlineMs: number) {}
492
+
493
+ arm(remotePeerId: string, maConn: MultiaddrConnection): void {
494
+ const entry: PendingReserveDeadline = {
495
+ maConn,
496
+ timer: setTimeout(() => this.expire(remotePeerId, entry), this.deadlineMs)
497
+ };
498
+ (entry.timer as { unref?: () => void }).unref?.();
499
+ let entries = this.byPeer.get(remotePeerId);
500
+ if (!entries) {
501
+ entries = new Set();
502
+ this.byPeer.set(remotePeerId, entries);
503
+ }
504
+ entries.add(entry);
505
+ log('Admitted %s for relay only — dropping the connection unless a reservation is admitted within %dms', remotePeerId, this.deadlineMs);
506
+ }
507
+
508
+ disarm(remotePeerId: string): void {
509
+ const entries = this.byPeer.get(remotePeerId);
510
+ if (!entries) {
511
+ return;
512
+ }
513
+ this.byPeer.delete(remotePeerId);
514
+ for (const entry of entries) {
515
+ clearTimeout(entry.timer);
516
+ }
517
+ }
518
+
519
+ private expire(remotePeerId: string, entry: PendingReserveDeadline): void {
520
+ const entries = this.byPeer.get(remotePeerId);
521
+ entries?.delete(entry);
522
+ if (entries?.size === 0) {
523
+ this.byPeer.delete(remotePeerId);
524
+ }
525
+ log('Relay-only admission expired for %s — no reservation admitted within %dms, aborting the connection', remotePeerId, this.deadlineMs);
526
+ try {
527
+ entry.maConn.abort(new Error(`relay-only admission expired: no relay reservation admitted within ${this.deadlineMs}ms`));
528
+ } catch (error) {
529
+ // Aborting a connection that already closed on its own is not a failure.
530
+ log('Aborting the expired relay-only connection from %s threw: %o', remotePeerId, error);
531
+ }
532
+ }
533
+ }