@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,366 +1,370 @@
1
- /**
2
- * The per-stream protocol guard on the control node: ONE declaration of what a peer must be to
3
- * open a stream on each protocol the control node serves ({@link controlProtocolClasses}), and
4
- * ONE place that enforces it for every handler, whoever registered it — Sereus, Optimystic,
5
- * FRET or libp2p ({@link installControlProtocolGuard}).
6
- *
7
- * It is the fail-closed layer behind the fail-open connection gate
8
- * (`membership-connection-gater.ts`). That gate decides per CONNECTION and must admit strangers
9
- * in several windows (an open formation invitation, a live cadre invitation, relay-only
10
- * admission on a node running the relay server, a delegate grant); this guard is what keeps a
11
- * stranger on such a connection to the protocols declared open to it. A handler therefore never
12
- * checks membership itself, and a handler added later cannot open a hole by forgetting to: a
13
- * protocol missing from the table is guarded as members-only (see "Unclassified protocols").
14
- *
15
- * ## The classes
16
- *
17
- * - `stranger-open` — seed delivery, strand formation, cadre-invitation redemption, owner-grant
18
- * redemption. Any peer; each handler makes its own trust decision in-protocol (a seed
19
- * signature against the anchored trust policy, a formation token, an invitation's or a
20
- * grant's possession proof).
21
- * - `transport` — libp2p plumbing (identify, ping, hole punching, AutoNAT, the circuit-relay
22
- * stop and hop protocols, WebRTC signaling). Every connection runs these, the redeeming
23
- * device's own included: refusing identify would make that device treat the member as
24
- * off-network. What they expose is the node's listen and observed addresses, its protocol
25
- * list (whose `/optimystic/control-<partyId>` prefix names the party id, which an invitation
26
- * bundle already carries) and its public key. AutoNAT v1 (`@libp2p/autonat` 3.0.28) dials
27
- * back only public addresses on the requester's own observed host, and refuses a request made
28
- * on another peer's behalf, so it cannot be pointed at a third machine. Relay reservations
29
- * are decided separately, at the connection gate's reservation hook.
30
- * - `members` — wake and strand-addr. Authorized members by the voucher-anchored LIVE read
31
- * (`CadreNode.isAuthorizedMember`), the check those handlers made themselves before this
32
- * guard existed, so moving it here changes nobody's admission. That matters most for
33
- * strand-addr's delegate grant, which hands out connection and relay admission. The live read
34
- * also has no window during `start()` where it admits everyone, which the snapshot does.
35
- * - `members-snapshot` — the four Optimystic control-database protocols and the five FRET
36
- * protocols. Authorized members by the in-memory snapshot
37
- * (`CadreNode.authorizeInboundControlStream`). These serve the reads a live membership check
38
- * would itself make, so a live read from inside their guard would deadlock two machines into
39
- * refusing each other; the snapshot is synchronous and reads nothing.
40
- *
41
- * ## Mechanism: the registrar's handler lookup
42
- *
43
- * libp2p dispatches every inbound stream through `components.registrar.getHandler(protocol)`
44
- * (`libp2p/dist/src/connection.js`, `onIncomingStream`). The guard replaces `getHandler` on the
45
- * control node's registrar instance with one that returns the registered record with its
46
- * handler wrapped for the protocol's class. A handler registered at any time, before or after
47
- * the guard, is therefore guarded at dispatch, with no sweep over registrations and no race
48
- * against a late one (the seed listener, a replaced formation handler).
49
- *
50
- * The record's `options` object is passed through unchanged: libp2p also reads it through
51
- * `getHandler` for stream limits (`findIncomingStreamLimit`, `findOutgoingStreamLimit`) and for
52
- * `runOnLimitedConnection`.
53
- *
54
- * NOTE: a libp2p that stopped dispatching through `getHandler` would leave this guard installed
55
- * and inert, and the class-completeness spec would still pass. Only the stranger probe in
56
- * `control-stream-authz.integration.ts` (step 5) observes dispatch, so run it on every libp2p
57
- * upgrade.
58
- *
59
- * libp2p's own stream middleware (`libp2p.use`) is NOT used. In libp2p 3.3.11 `onIncomingStream`
60
- * pushes the handler call onto the very array `registrar.getMiddleware` returns, so every inbound
61
- * stream appends another handler call to the stored chain and outbound streams then run those
62
- * too (read from the source, not run). Revisit if a libp2p upgrade stops mutating that array.
63
- *
64
- * ## Denial
65
- *
66
- * A refused stream is aborted with {@link ControlStreamRefusedError} before its handler runs, so
67
- * nothing is decoded and nothing goes on the wire: telling a stranger "you are not a member"
68
- * would confirm membership state to it. The refusal is logged on this node with peer, protocol
69
- * and reason. The live read fails closed: a false result, a throw and a read slower than
70
- * {@link ControlProtocolGuardOptions.liveDecisionTimeoutMs} all refuse.
71
- *
72
- * ## Unclassified protocols
73
- *
74
- * A protocol missing from the table is guarded as `members-snapshot`, with one `console.warn` per
75
- * protocol: it works for members and refuses strangers until someone classes it.
76
- * `control-protocol-guard.spec.ts` starts a node with every conditional protocol on and fails
77
- * when any protocol it serves is unclassified, so an upgrade that adds one fails CI.
78
- */
79
-
80
- import debug from 'debug';
81
- import type { Connection, Libp2p, Stream, StreamHandler, StreamHandlerRecord } from '@libp2p/interface';
82
- import { SEED_PROTOCOL } from './seed-bootstrap.js';
83
- import { FORMATION_PROTOCOL } from './strand-formation-protocol.js';
84
- import { CADRE_INVITE_PROTOCOL } from './cadre-invite-protocol.js';
85
- import { OWNER_GRANT_PROTOCOL } from './owner-grant-protocol.js';
86
- import { WAKE_PROTOCOL } from './strand-wake-protocol.js';
87
- import { STRAND_ADDR_PROTOCOL } from './strand-addr-protocol.js';
88
- import { withTimeout } from './control-stream.js';
89
- import { describeThrown } from './describe-thrown.js';
90
-
91
- const log = debug('sereus:cadre:control-protocol-guard');
92
-
93
- /** What a peer must be to open a stream on a control-node protocol (see the module doc). */
94
- export type ControlProtocolClass =
95
- /** Any peer. The handler makes its own trust decision in-protocol (seed, formation, cadre-invite, owner-grant). */
96
- | 'stranger-open'
97
- /** libp2p plumbing that a stranger's connection needs or that carries no party data. */
98
- | 'transport'
99
- /** Authorized members by the voucher-anchored live read (`isAuthorizedMember`). For Sereus application protocols. */
100
- | 'members'
101
- /** Authorized members by the in-memory snapshot (`authorizeInboundControlStream`). For anything a control-database read itself depends on. */
102
- | 'members-snapshot';
103
-
104
- /** The class a protocol missing from {@link controlProtocolClasses} is guarded as. */
105
- export const UNCLASSIFIED_PROTOCOL_CLASS: ControlProtocolClass = 'members-snapshot';
106
-
107
- /** Stable error code carried by {@link ControlStreamRefusedError}. */
108
- export const CONTROL_STREAM_REFUSED_CODE = 'ERR_CONTROL_STREAM_REFUSED';
109
-
110
- /**
111
- * The reason a control-node stream was aborted by the guard, so this node's logs can tell a
112
- * refusal from a transport fault. The remote only ever sees the stream reset.
113
- */
114
- export class ControlStreamRefusedError extends Error {
115
- readonly code = CONTROL_STREAM_REFUSED_CODE;
116
-
117
- constructor(remotePeerId: string, protocol: string, reason: string) {
118
- super(`control stream refused: peer=${remotePeerId} protocol=${protocol} reason=${reason}`);
119
- this.name = 'ControlStreamRefusedError';
120
- }
121
- }
122
-
123
- /**
124
- * The control libp2p node's Optimystic network name. `db-p2p` namespaces the node's protocol ids
125
- * as `/optimystic/<networkName>/...`, so this is the one binding every control-network derivation
126
- * starts from: the node options, the block-transfer prefix the control backfill dials, and the
127
- * class table below.
128
- *
129
- * NOTE: the party id goes in UNENCODED here, unlike in `controlStorageScope`. Safe today because a
130
- * party id is locally configured rather than replicated in, and both ends of a connection derive
131
- * this string identically: an odd party id yields an odd but consistent protocol id, not a
132
- * mismatch or an escaped name. If a party id ever arrives from the network, encode it here as the
133
- * storage scope key already does.
134
- */
135
- export function controlNetworkName(partyId: string): string {
136
- return `control-${partyId}`;
137
- }
138
-
139
- /** The control database's two storage protocols, `repo` and `cluster`. */
140
- function controlDatabaseProtocols(partyId: string): readonly string[] {
141
- const prefix = `/optimystic/${controlNetworkName(partyId)}`;
142
- return [`${prefix}/repo/1.0.0`, `${prefix}/cluster/1.0.0`];
143
- }
144
-
145
- /**
146
- * Whether a peer whose protocol list is `protocols` serves the control database. Optimystic
147
- * counts a peer into a control block's cohort by the same test (`servesThisNetwork` in db-p2p's
148
- * `libp2p-key-network.ts`), before its membership check.
149
- */
150
- export function servesControlDatabase(partyId: string, protocols: readonly string[]): boolean {
151
- return controlDatabaseProtocols(partyId).some((protocol) => protocols.includes(protocol));
152
- }
153
-
154
- /**
155
- * The class of every protocol a control node serves, by exact protocol id: the single
156
- * declaration the guard enforces. See the module doc for what each class admits and why each
157
- * protocol is in it.
158
- */
159
- export function controlProtocolClasses(partyId: string): ReadonlyMap<string, ControlProtocolClass> {
160
- const prefix = `/optimystic/${controlNetworkName(partyId)}`;
161
- const fret = `${prefix}/fret/1.0.0`;
162
- return new Map<string, ControlProtocolClass>([
163
- [SEED_PROTOCOL, 'stranger-open'],
164
- [FORMATION_PROTOCOL, 'stranger-open'],
165
- [CADRE_INVITE_PROTOCOL, 'stranger-open'],
166
- [OWNER_GRANT_PROTOCOL, 'stranger-open'],
167
-
168
- [WAKE_PROTOCOL, 'members'],
169
- [STRAND_ADDR_PROTOCOL, 'members'],
170
-
171
- ...controlDatabaseProtocols(partyId).map((protocol): [string, ControlProtocolClass] => [protocol, 'members-snapshot']),
172
- [`${prefix}/db-p2p/sync/1.0.0`, 'members-snapshot'],
173
- [`${prefix}/db-p2p/block-transfer/1.0.0`, 'members-snapshot'],
174
- [`${fret}/neighbors`, 'members-snapshot'],
175
- [`${fret}/neighbors/announce`, 'members-snapshot'],
176
- [`${fret}/maybeAct`, 'members-snapshot'],
177
- [`${fret}/leave`, 'members-snapshot'],
178
- [`${fret}/ping`, 'members-snapshot'],
179
-
180
- [`${prefix}/id/1.0.0`, 'transport'],
181
- [`${prefix}/id/push/1.0.0`, 'transport'],
182
- ['/ipfs/ping/1.0.0', 'transport'],
183
- ['/libp2p/dcutr', 'transport'],
184
- ['/libp2p/autonat/1.0.0', 'transport'],
185
- ['/libp2p/circuit/relay/0.2.0/stop', 'transport'],
186
- // Registered only while the relay server runs (the storage profile's default).
187
- ['/libp2p/circuit/relay/0.2.0/hop', 'transport'],
188
- // Registered only when an embedder's `network.transports` includes WebRTC.
189
- ['/webrtc-signaling/0.0.1', 'transport'],
190
- ]);
191
- }
192
-
193
- /** What {@link installControlProtocolGuard} needs from its host (`CadreNode`). */
194
- export interface ControlProtocolGuardOptions {
195
- /** The party whose control network the node serves; names the `/optimystic/control-<partyId>` protocols. */
196
- partyId: string;
197
- /** The `members` class predicate: `CadreNode.isAuthorizedMember`. Only a literal `true` admits. */
198
- isMemberLive(remotePeerId: string): Promise<boolean>;
199
- /** The `members-snapshot` class predicate: `CadreNode.authorizeInboundControlStream`. Synchronous and in-memory. */
200
- isMemberSnapshot(remotePeerId: string, protocol: string): boolean;
201
- /**
202
- * How long one {@link isMemberLive} read may take before the stream is refused. `CadreNode`
203
- * passes the asker's own attempt deadline at this node's declared link (`relayedRequestBudgetMs`),
204
- * so the guard never cuts off a check the asker would still be waiting for: a shorter cut would
205
- * refuse members whose check completes in time today.
206
- */
207
- liveDecisionTimeoutMs: number;
208
- }
209
-
210
- /** The slice of libp2p's internal registrar the guard replaces. */
211
- interface GuardableRegistrar {
212
- getHandler(protocol: string): StreamHandlerRecord;
213
- }
214
-
215
- function isGuardableRegistrar(value: unknown): value is GuardableRegistrar {
216
- return typeof value === 'object' && value !== null
217
- && typeof (value as { getHandler?: unknown }).getHandler === 'function';
218
- }
219
-
220
- /**
221
- * The control node's registrar, which is not on libp2p's public `Libp2p` type. Throws when the
222
- * shape is absent (a libp2p upgrade that moved it), which fails `CadreNode.start()`: a control
223
- * node without the guard must not run.
224
- */
225
- function controlRegistrar(node: Libp2p): GuardableRegistrar {
226
- let registrar: unknown;
227
- try {
228
- // libp2p's components object is a Proxy that throws for a component it does not hold.
229
- registrar = (node as unknown as { components?: { registrar?: unknown } }).components?.registrar;
230
- } catch (error) {
231
- throw new Error('control-protocol guard: the control node exposes no registrar component; refusing to run unguarded', { cause: error });
232
- }
233
- if (!isGuardableRegistrar(registrar)) {
234
- throw new Error('control-protocol guard: the control node\'s registrar has no getHandler; refusing to run unguarded');
235
- }
236
- return registrar;
237
- }
238
-
239
- /**
240
- * Guard every inbound stream on `node` by its protocol's class (see the module doc). Call once,
241
- * on the control node, before it holds any connection: `CadreNode.start()` calls it right after
242
- * the node is built, inside the bring-up quiet period. Throws when the node's registrar is not
243
- * the shape the guard replaces.
244
- */
245
- export function installControlProtocolGuard(node: Libp2p, options: ControlProtocolGuardOptions): void {
246
- const registrar = controlRegistrar(node);
247
- const guard = new ControlProtocolGuard(options);
248
- const lookup = registrar.getHandler.bind(registrar);
249
- // An unregistered protocol still throws libp2p's own UnhandledProtocolError, from `lookup`.
250
- registrar.getHandler = (protocol: string): StreamHandlerRecord => guard.recordFor(protocol, lookup(protocol));
251
- log('Guarding the control node\'s inbound streams for party %s', options.partyId);
252
- }
253
-
254
- /** The per-node state behind {@link installControlProtocolGuard}. */
255
- class ControlProtocolGuard {
256
- private readonly classes: ReadonlyMap<string, ControlProtocolClass>;
257
- /**
258
- * The guarded copy of each registered record, so the lookups libp2p makes per stream (the
259
- * stream-limit read, then the dispatch) allocate nothing. Keyed on the registrar's own record,
260
- * which a re-registration replaces, so a replaced handler gets a fresh wrapper.
261
- */
262
- private readonly guarded = new WeakMap<StreamHandlerRecord, StreamHandlerRecord>();
263
- private readonly warnedUnclassified = new Set<string>();
264
-
265
- constructor(private readonly options: ControlProtocolGuardOptions) {
266
- this.classes = controlProtocolClasses(options.partyId);
267
- }
268
-
269
- recordFor(protocol: string, record: StreamHandlerRecord): StreamHandlerRecord {
270
- const protocolClass = this.classOf(protocol);
271
- if (protocolClass === 'stranger-open' || protocolClass === 'transport') {
272
- return record;
273
- }
274
- let guarded = this.guarded.get(record);
275
- if (!guarded) {
276
- guarded = { ...record, handler: this.wrap(protocol, protocolClass, record.handler) };
277
- this.guarded.set(record, guarded);
278
- }
279
- return guarded;
280
- }
281
-
282
- private classOf(protocol: string): ControlProtocolClass {
283
- const declared = this.classes.get(protocol);
284
- if (declared) {
285
- return declared;
286
- }
287
- if (!this.warnedUnclassified.has(protocol)) {
288
- this.warnedUnclassified.add(protocol);
289
- console.warn(`Control node serves ${protocol}, which has no class in controlProtocolClasses ` +
290
- `(control-protocol-guard.ts); guarding it as ${UNCLASSIFIED_PROTOCOL_CLASS}, so strangers are refused on it. ` +
291
- 'Declare its class.');
292
- }
293
- return UNCLASSIFIED_PROTOCOL_CLASS;
294
- }
295
-
296
- private wrap(protocol: string, protocolClass: 'members' | 'members-snapshot', handler: StreamHandler): StreamHandler {
297
- if (protocolClass === 'members') {
298
- // NOTE: the handler starts reading only once the live read settles, usually after the
299
- // asker has half-closed, and a plain `for await` over a libp2p 3.3.11 stream never ends
300
- // there (see `collect` in control-stream.ts). Wake and strand-addr read through
301
- // `readStreamToEnd`, which handles it; a handler added to this class must too.
302
- return async (stream: Stream, connection: Connection): Promise<void> => {
303
- const remotePeerId = connection.remotePeer.toString();
304
- const refusal = await this.liveRefusal(remotePeerId);
305
- if (refusal !== undefined) {
306
- refuse(stream, remotePeerId, protocol, refusal);
307
- return;
308
- }
309
- await handler(stream, connection);
310
- };
311
- }
312
- return (stream: Stream, connection: Connection): void | Promise<void> => {
313
- const remotePeerId = connection.remotePeer.toString();
314
- const refusal = this.snapshotRefusal(remotePeerId, protocol);
315
- if (refusal !== undefined) {
316
- refuse(stream, remotePeerId, protocol, refusal);
317
- return;
318
- }
319
- return handler(stream, connection);
320
- };
321
- }
322
-
323
- /**
324
- * Why the live read refuses `remotePeerId`, or undefined when it admits.
325
- *
326
- * NOTE: a stranger's stream now costs one live membership read before it is refused, and the
327
- * handlers' concurrency caps no longer bound those reads; libp2p's per-connection
328
- * `maxInboundStreams` (32 per protocol) does. Fine while that read touches only held blocks.
329
- * If refused strangers ever show up as load, refuse a peer absent from the snapshot before the
330
- * live read.
331
- */
332
- private async liveRefusal(remotePeerId: string): Promise<string | undefined> {
333
- try {
334
- const member = await withTimeout(
335
- this.options.liveDecisionTimeoutMs,
336
- `membership check for ${remotePeerId}`,
337
- () => this.options.isMemberLive(remotePeerId)
338
- );
339
- return member === true ? undefined : 'not an authorized member';
340
- } catch (error) {
341
- return `membership check failed: ${describeThrown(error)}`;
342
- }
343
- }
344
-
345
- /** Why the snapshot refuses `remotePeerId` on `protocol`, or undefined when it admits. */
346
- private snapshotRefusal(remotePeerId: string, protocol: string): string | undefined {
347
- try {
348
- return this.options.isMemberSnapshot(remotePeerId, protocol) === true
349
- ? undefined
350
- : 'not in the authorized-member snapshot';
351
- } catch (error) {
352
- return `snapshot check threw: ${describeThrown(error)}`;
353
- }
354
- }
355
- }
356
-
357
- /** Log a refusal and reset the stream before its handler runs. */
358
- function refuse(stream: Stream, remotePeerId: string, protocol: string, reason: string): void {
359
- log('Refusing %s on %s: %s', remotePeerId, protocol, reason);
360
- try {
361
- stream.abort(new ControlStreamRefusedError(remotePeerId, protocol, reason));
362
- } catch (error) {
363
- // The stream may already be gone; the refusal stands either way.
364
- log('Aborting the refused stream from %s on %s failed: %o', remotePeerId, protocol, error);
365
- }
366
- }
1
+ /**
2
+ * The per-stream protocol guard on the control node: ONE declaration of what a peer must be to
3
+ * open a stream on each protocol the control node serves ({@link controlProtocolClasses}), and
4
+ * ONE place that enforces it for every handler, whoever registered it — Sereus, Optimystic,
5
+ * FRET or libp2p ({@link installControlProtocolGuard}).
6
+ *
7
+ * It is the fail-closed layer behind the fail-open connection gate
8
+ * (`membership-connection-gater.ts`). That gate decides per CONNECTION and must admit strangers
9
+ * in several windows (an open formation invitation, a live cadre invitation, relay-only
10
+ * admission on a node running the relay server, a delegate grant); this guard is what keeps a
11
+ * stranger on such a connection to the protocols declared open to it. A handler therefore never
12
+ * checks membership itself, and a handler added later cannot open a hole by forgetting to: a
13
+ * protocol missing from the table is guarded as members-only (see "Unclassified protocols").
14
+ *
15
+ * ## The classes
16
+ *
17
+ * - `stranger-open` — seed delivery, strand formation, cadre-invitation redemption, owner-grant
18
+ * redemption. Any peer; each handler makes its own trust decision in-protocol (a seed
19
+ * signature against the anchored trust policy, a formation token, an invitation's or a
20
+ * grant's possession proof).
21
+ * - `transport` — libp2p plumbing (identify, ping, hole punching, AutoNAT, the circuit-relay
22
+ * stop and hop protocols, WebRTC signaling). Every connection runs these, the redeeming
23
+ * device's own included: refusing identify would make that device treat the member as
24
+ * off-network. What they expose is the node's listen and observed addresses, its protocol
25
+ * list (whose `/optimystic/control-<partyId>` prefix names the party id, which an invitation
26
+ * bundle already carries) and its public key. AutoNAT v1 (`@libp2p/autonat` 3.0.28) dials
27
+ * back only public addresses on the requester's own observed host, and refuses a request made
28
+ * on another peer's behalf, so it cannot be pointed at a third machine. Relay reservations
29
+ * are decided separately, at the connection gate's reservation hook.
30
+ * - `members` — wake and strand-addr. Authorized members by the voucher-anchored LIVE read
31
+ * (`CadreNode.isAuthorizedMember`), the check those handlers made themselves before this
32
+ * guard existed, so moving it here changes nobody's admission. That matters most for
33
+ * strand-addr's delegate grant, which hands out connection and relay admission. The live read
34
+ * also has no window during `start()` where it admits everyone, which the snapshot does.
35
+ * - `members-snapshot` — the five Optimystic control-database protocols and the five FRET
36
+ * protocols. Authorized members by the in-memory snapshot
37
+ * (`CadreNode.authorizeInboundControlStream`). These serve the reads a live membership check
38
+ * would itself make, so a live read from inside their guard would deadlock two machines into
39
+ * refusing each other; the snapshot is synchronous and reads nothing.
40
+ *
41
+ * ## Mechanism: the registrar's handler lookup
42
+ *
43
+ * libp2p dispatches every inbound stream through `components.registrar.getHandler(protocol)`
44
+ * (`libp2p/dist/src/connection.js`, `onIncomingStream`). The guard replaces `getHandler` on the
45
+ * control node's registrar instance with one that returns the registered record with its
46
+ * handler wrapped for the protocol's class. A handler registered at any time, before or after
47
+ * the guard, is therefore guarded at dispatch, with no sweep over registrations and no race
48
+ * against a late one (the seed listener, a replaced formation handler).
49
+ *
50
+ * The record's `options` object is passed through unchanged: libp2p also reads it through
51
+ * `getHandler` for stream limits (`findIncomingStreamLimit`, `findOutgoingStreamLimit`) and for
52
+ * `runOnLimitedConnection`.
53
+ *
54
+ * NOTE: a libp2p that stopped dispatching through `getHandler` would leave this guard installed
55
+ * and inert, and the class-completeness spec would still pass. Only the stranger probe in
56
+ * `control-stream-authz.integration.ts` (step 5) observes dispatch, so run it on every libp2p
57
+ * upgrade.
58
+ *
59
+ * libp2p's own stream middleware (`libp2p.use`) is NOT used. In libp2p 3.3.11 `onIncomingStream`
60
+ * pushes the handler call onto the very array `registrar.getMiddleware` returns, so every inbound
61
+ * stream appends another handler call to the stored chain and outbound streams then run those
62
+ * too (read from the source, not run). Revisit if a libp2p upgrade stops mutating that array.
63
+ *
64
+ * ## Denial
65
+ *
66
+ * A refused stream is aborted with {@link ControlStreamRefusedError} before its handler runs, so
67
+ * nothing is decoded and nothing goes on the wire: telling a stranger "you are not a member"
68
+ * would confirm membership state to it. The refusal is logged on this node with peer, protocol
69
+ * and reason. The live read fails closed: a false result, a throw and a read slower than
70
+ * {@link ControlProtocolGuardOptions.liveDecisionTimeoutMs} all refuse.
71
+ *
72
+ * ## Unclassified protocols
73
+ *
74
+ * A protocol missing from the table is guarded as `members-snapshot`, with one `console.warn` per
75
+ * protocol: it works for members and refuses strangers until someone classes it.
76
+ * `control-protocol-guard.spec.ts` starts a node with every conditional protocol on and fails
77
+ * when any protocol it serves is unclassified, so an upgrade that adds one fails CI.
78
+ */
79
+
80
+ import debug from 'debug';
81
+ import type { Connection, Libp2p, Stream, StreamHandler, StreamHandlerRecord } from '@libp2p/interface';
82
+ import { SEED_PROTOCOL } from './seed-bootstrap.js';
83
+ import { FORMATION_PROTOCOL } from './strand-formation-protocol.js';
84
+ import { CADRE_INVITE_PROTOCOL } from './cadre-invite-protocol.js';
85
+ import { OWNER_GRANT_PROTOCOL } from './owner-grant-protocol.js';
86
+ import { WAKE_PROTOCOL } from './strand-wake-protocol.js';
87
+ import { STRAND_ADDR_PROTOCOL } from './strand-addr-protocol.js';
88
+ import { WEBRTC_SIGNALING_PROTOCOL } from './webrtc-upgrade.js';
89
+ import { withTimeout } from './control-stream.js';
90
+ import { describeThrown } from './describe-thrown.js';
91
+
92
+ const log = debug('sereus:cadre:control-protocol-guard');
93
+
94
+ /** What a peer must be to open a stream on a control-node protocol (see the module doc). */
95
+ export type ControlProtocolClass =
96
+ /** Any peer. The handler makes its own trust decision in-protocol (seed, formation, cadre-invite, owner-grant). */
97
+ | 'stranger-open'
98
+ /** libp2p plumbing that a stranger's connection needs or that carries no party data. */
99
+ | 'transport'
100
+ /** Authorized members by the voucher-anchored live read (`isAuthorizedMember`). For Sereus application protocols. */
101
+ | 'members'
102
+ /** Authorized members by the in-memory snapshot (`authorizeInboundControlStream`). For anything a control-database read itself depends on. */
103
+ | 'members-snapshot';
104
+
105
+ /** The class a protocol missing from {@link controlProtocolClasses} is guarded as. */
106
+ export const UNCLASSIFIED_PROTOCOL_CLASS: ControlProtocolClass = 'members-snapshot';
107
+
108
+ /** Stable error code carried by {@link ControlStreamRefusedError}. */
109
+ export const CONTROL_STREAM_REFUSED_CODE = 'ERR_CONTROL_STREAM_REFUSED';
110
+
111
+ /**
112
+ * The reason a control-node stream was aborted by the guard, so this node's logs can tell a
113
+ * refusal from a transport fault. The remote only ever sees the stream reset.
114
+ */
115
+ export class ControlStreamRefusedError extends Error {
116
+ readonly code = CONTROL_STREAM_REFUSED_CODE;
117
+
118
+ constructor(remotePeerId: string, protocol: string, reason: string) {
119
+ super(`control stream refused: peer=${remotePeerId} protocol=${protocol} reason=${reason}`);
120
+ this.name = 'ControlStreamRefusedError';
121
+ }
122
+ }
123
+
124
+ /**
125
+ * The control libp2p node's Optimystic network name. `db-p2p` namespaces the node's protocol ids
126
+ * as `/optimystic/<networkName>/...`, so this is the one binding every control-network derivation
127
+ * starts from: the node options, the block-transfer prefix the control backfill dials, and the
128
+ * class table below.
129
+ *
130
+ * NOTE: the party id goes in UNENCODED here, unlike in `controlStorageScope`. Safe today because a
131
+ * party id is locally configured rather than replicated in, and both ends of a connection derive
132
+ * this string identically: an odd party id yields an odd but consistent protocol id, not a
133
+ * mismatch or an escaped name. If a party id ever arrives from the network, encode it here as the
134
+ * storage scope key already does.
135
+ */
136
+ export function controlNetworkName(partyId: string): string {
137
+ return `control-${partyId}`;
138
+ }
139
+
140
+ /** The control database's two storage protocols, `repo` and `cluster`. */
141
+ function controlDatabaseProtocols(partyId: string): readonly string[] {
142
+ const prefix = `/optimystic/${controlNetworkName(partyId)}`;
143
+ return [`${prefix}/repo/1.0.0`, `${prefix}/cluster/1.0.0`];
144
+ }
145
+
146
+ /**
147
+ * Whether a peer whose protocol list is `protocols` serves the control database. Optimystic
148
+ * counts a peer into a control block's cohort by the same test (`servesThisNetwork` in db-p2p's
149
+ * `libp2p-key-network.ts`), before its membership check.
150
+ */
151
+ export function servesControlDatabase(partyId: string, protocols: readonly string[]): boolean {
152
+ return controlDatabaseProtocols(partyId).some((protocol) => protocols.includes(protocol));
153
+ }
154
+
155
+ /**
156
+ * The class of every protocol a control node serves, by exact protocol id: the single
157
+ * declaration the guard enforces. See the module doc for what each class admits and why each
158
+ * protocol is in it.
159
+ */
160
+ export function controlProtocolClasses(partyId: string): ReadonlyMap<string, ControlProtocolClass> {
161
+ const prefix = `/optimystic/${controlNetworkName(partyId)}`;
162
+ const fret = `${prefix}/fret/1.0.0`;
163
+ return new Map<string, ControlProtocolClass>([
164
+ [SEED_PROTOCOL, 'stranger-open'],
165
+ [FORMATION_PROTOCOL, 'stranger-open'],
166
+ [CADRE_INVITE_PROTOCOL, 'stranger-open'],
167
+ [OWNER_GRANT_PROTOCOL, 'stranger-open'],
168
+
169
+ [WAKE_PROTOCOL, 'members'],
170
+ [STRAND_ADDR_PROTOCOL, 'members'],
171
+
172
+ ...controlDatabaseProtocols(partyId).map((protocol): [string, ControlProtocolClass] => [protocol, 'members-snapshot']),
173
+ [`${prefix}/db-p2p/sync/1.0.0`, 'members-snapshot'],
174
+ [`${prefix}/db-p2p/block-transfer/1.0.0`, 'members-snapshot'],
175
+ // Blob pieces (Optimystic 1.29.0). Its announce handler reads committed state to check a
176
+ // reference, so it belongs with the reads a live membership check would itself make.
177
+ [`${prefix}/db-p2p/blob/1.0.0`, 'members-snapshot'],
178
+ [`${fret}/neighbors`, 'members-snapshot'],
179
+ [`${fret}/neighbors/announce`, 'members-snapshot'],
180
+ [`${fret}/maybeAct`, 'members-snapshot'],
181
+ [`${fret}/leave`, 'members-snapshot'],
182
+ [`${fret}/ping`, 'members-snapshot'],
183
+
184
+ [`${prefix}/id/1.0.0`, 'transport'],
185
+ [`${prefix}/id/push/1.0.0`, 'transport'],
186
+ ['/ipfs/ping/1.0.0', 'transport'],
187
+ ['/libp2p/dcutr', 'transport'],
188
+ ['/libp2p/autonat/1.0.0', 'transport'],
189
+ ['/libp2p/circuit/relay/0.2.0/stop', 'transport'],
190
+ // Registered only while the relay server runs (a `'server'` node's default).
191
+ ['/libp2p/circuit/relay/0.2.0/hop', 'transport'],
192
+ // Registered only when an embedder's `network.transports` includes WebRTC.
193
+ [WEBRTC_SIGNALING_PROTOCOL, 'transport'],
194
+ ]);
195
+ }
196
+
197
+ /** What {@link installControlProtocolGuard} needs from its host (`CadreNode`). */
198
+ export interface ControlProtocolGuardOptions {
199
+ /** The party whose control network the node serves; names the `/optimystic/control-<partyId>` protocols. */
200
+ partyId: string;
201
+ /** The `members` class predicate: `CadreNode.isAuthorizedMember`. Only a literal `true` admits. */
202
+ isMemberLive(remotePeerId: string): Promise<boolean>;
203
+ /** The `members-snapshot` class predicate: `CadreNode.authorizeInboundControlStream`. Synchronous and in-memory. */
204
+ isMemberSnapshot(remotePeerId: string, protocol: string): boolean;
205
+ /**
206
+ * How long one {@link isMemberLive} read may take before the stream is refused. `CadreNode`
207
+ * passes the asker's own attempt deadline at this node's declared link (`relayedRequestBudgetMs`),
208
+ * so the guard never cuts off a check the asker would still be waiting for: a shorter cut would
209
+ * refuse members whose check completes in time today.
210
+ */
211
+ liveDecisionTimeoutMs: number;
212
+ }
213
+
214
+ /** The slice of libp2p's internal registrar the guard replaces. */
215
+ interface GuardableRegistrar {
216
+ getHandler(protocol: string): StreamHandlerRecord;
217
+ }
218
+
219
+ function isGuardableRegistrar(value: unknown): value is GuardableRegistrar {
220
+ return typeof value === 'object' && value !== null
221
+ && typeof (value as { getHandler?: unknown }).getHandler === 'function';
222
+ }
223
+
224
+ /**
225
+ * The control node's registrar, which is not on libp2p's public `Libp2p` type. Throws when the
226
+ * shape is absent (a libp2p upgrade that moved it), which fails `CadreNode.start()`: a control
227
+ * node without the guard must not run.
228
+ */
229
+ function controlRegistrar(node: Libp2p): GuardableRegistrar {
230
+ let registrar: unknown;
231
+ try {
232
+ // libp2p's components object is a Proxy that throws for a component it does not hold.
233
+ registrar = (node as unknown as { components?: { registrar?: unknown } }).components?.registrar;
234
+ } catch (error) {
235
+ throw new Error('control-protocol guard: the control node exposes no registrar component; refusing to run unguarded', { cause: error });
236
+ }
237
+ if (!isGuardableRegistrar(registrar)) {
238
+ throw new Error('control-protocol guard: the control node\'s registrar has no getHandler; refusing to run unguarded');
239
+ }
240
+ return registrar;
241
+ }
242
+
243
+ /**
244
+ * Guard every inbound stream on `node` by its protocol's class (see the module doc). Call once,
245
+ * on the control node, before it holds any connection: `CadreNode.start()` calls it right after
246
+ * the node is built, inside the bring-up quiet period. Throws when the node's registrar is not
247
+ * the shape the guard replaces.
248
+ */
249
+ export function installControlProtocolGuard(node: Libp2p, options: ControlProtocolGuardOptions): void {
250
+ const registrar = controlRegistrar(node);
251
+ const guard = new ControlProtocolGuard(options);
252
+ const lookup = registrar.getHandler.bind(registrar);
253
+ // An unregistered protocol still throws libp2p's own UnhandledProtocolError, from `lookup`.
254
+ registrar.getHandler = (protocol: string): StreamHandlerRecord => guard.recordFor(protocol, lookup(protocol));
255
+ log('Guarding the control node\'s inbound streams for party %s', options.partyId);
256
+ }
257
+
258
+ /** The per-node state behind {@link installControlProtocolGuard}. */
259
+ class ControlProtocolGuard {
260
+ private readonly classes: ReadonlyMap<string, ControlProtocolClass>;
261
+ /**
262
+ * The guarded copy of each registered record, so the lookups libp2p makes per stream (the
263
+ * stream-limit read, then the dispatch) allocate nothing. Keyed on the registrar's own record,
264
+ * which a re-registration replaces, so a replaced handler gets a fresh wrapper.
265
+ */
266
+ private readonly guarded = new WeakMap<StreamHandlerRecord, StreamHandlerRecord>();
267
+ private readonly warnedUnclassified = new Set<string>();
268
+
269
+ constructor(private readonly options: ControlProtocolGuardOptions) {
270
+ this.classes = controlProtocolClasses(options.partyId);
271
+ }
272
+
273
+ recordFor(protocol: string, record: StreamHandlerRecord): StreamHandlerRecord {
274
+ const protocolClass = this.classOf(protocol);
275
+ if (protocolClass === 'stranger-open' || protocolClass === 'transport') {
276
+ return record;
277
+ }
278
+ let guarded = this.guarded.get(record);
279
+ if (!guarded) {
280
+ guarded = { ...record, handler: this.wrap(protocol, protocolClass, record.handler) };
281
+ this.guarded.set(record, guarded);
282
+ }
283
+ return guarded;
284
+ }
285
+
286
+ private classOf(protocol: string): ControlProtocolClass {
287
+ const declared = this.classes.get(protocol);
288
+ if (declared) {
289
+ return declared;
290
+ }
291
+ if (!this.warnedUnclassified.has(protocol)) {
292
+ this.warnedUnclassified.add(protocol);
293
+ console.warn(`Control node serves ${protocol}, which has no class in controlProtocolClasses ` +
294
+ `(control-protocol-guard.ts); guarding it as ${UNCLASSIFIED_PROTOCOL_CLASS}, so strangers are refused on it. ` +
295
+ 'Declare its class.');
296
+ }
297
+ return UNCLASSIFIED_PROTOCOL_CLASS;
298
+ }
299
+
300
+ private wrap(protocol: string, protocolClass: 'members' | 'members-snapshot', handler: StreamHandler): StreamHandler {
301
+ if (protocolClass === 'members') {
302
+ // NOTE: the handler starts reading only once the live read settles, usually after the
303
+ // asker has half-closed, and a plain `for await` over a libp2p 3.3.11 stream never ends
304
+ // there (see `collect` in control-stream.ts). Wake and strand-addr read through
305
+ // `readStreamToEnd`, which handles it; a handler added to this class must too.
306
+ return async (stream: Stream, connection: Connection): Promise<void> => {
307
+ const remotePeerId = connection.remotePeer.toString();
308
+ const refusal = await this.liveRefusal(remotePeerId);
309
+ if (refusal !== undefined) {
310
+ refuse(stream, remotePeerId, protocol, refusal);
311
+ return;
312
+ }
313
+ await handler(stream, connection);
314
+ };
315
+ }
316
+ return (stream: Stream, connection: Connection): void | Promise<void> => {
317
+ const remotePeerId = connection.remotePeer.toString();
318
+ const refusal = this.snapshotRefusal(remotePeerId, protocol);
319
+ if (refusal !== undefined) {
320
+ refuse(stream, remotePeerId, protocol, refusal);
321
+ return;
322
+ }
323
+ return handler(stream, connection);
324
+ };
325
+ }
326
+
327
+ /**
328
+ * Why the live read refuses `remotePeerId`, or undefined when it admits.
329
+ *
330
+ * NOTE: a stranger's stream now costs one live membership read before it is refused, and the
331
+ * handlers' concurrency caps no longer bound those reads; libp2p's per-connection
332
+ * `maxInboundStreams` (32 per protocol) does. Fine while that read touches only held blocks.
333
+ * If refused strangers ever show up as load, refuse a peer absent from the snapshot before the
334
+ * live read.
335
+ */
336
+ private async liveRefusal(remotePeerId: string): Promise<string | undefined> {
337
+ try {
338
+ const member = await withTimeout(
339
+ this.options.liveDecisionTimeoutMs,
340
+ `membership check for ${remotePeerId}`,
341
+ () => this.options.isMemberLive(remotePeerId)
342
+ );
343
+ return member === true ? undefined : 'not an authorized member';
344
+ } catch (error) {
345
+ return `membership check failed: ${describeThrown(error)}`;
346
+ }
347
+ }
348
+
349
+ /** Why the snapshot refuses `remotePeerId` on `protocol`, or undefined when it admits. */
350
+ private snapshotRefusal(remotePeerId: string, protocol: string): string | undefined {
351
+ try {
352
+ return this.options.isMemberSnapshot(remotePeerId, protocol) === true
353
+ ? undefined
354
+ : 'not in the authorized-member snapshot';
355
+ } catch (error) {
356
+ return `snapshot check threw: ${describeThrown(error)}`;
357
+ }
358
+ }
359
+ }
360
+
361
+ /** Log a refusal and reset the stream before its handler runs. */
362
+ function refuse(stream: Stream, remotePeerId: string, protocol: string, reason: string): void {
363
+ log('Refusing %s on %s: %s', remotePeerId, protocol, reason);
364
+ try {
365
+ stream.abort(new ControlStreamRefusedError(remotePeerId, protocol, reason));
366
+ } catch (error) {
367
+ // The stream may already be gone; the refusal stands either way.
368
+ log('Aborting the refused stream from %s on %s failed: %o', remotePeerId, protocol, error);
369
+ }
370
+ }