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