@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,758 +1,758 @@
1
- /**
2
- * Strand revoked-peer enforcement: a per-strand deny gate that refuses the
3
- * network nodes of a REMOVED party, so removal means "we stop talking to you"
4
- * rather than only deleting a row.
5
- *
6
- * ## The deny set is revocation-keyed, never membership-keyed
7
- *
8
- * A strand node maintains a materialized in-memory set of revoked peer ids:
9
- * every `Strand.MemberPeer.PeerId` whose `MemberKey` has no live `Strand.Member`
10
- * row. `MemberPeer.MemberExists` runs on insert, so an orphaned binding can only
11
- * mean "this member existed and was removed" — it is exactly the durable,
12
- * replicated record of a removed party's machines. That holds on the network
13
- * only because every writer commits a party's `Member` row before its
14
- * `MemberPeer` row, as separate commits (the membership reconciler does, and
15
- * `registerMemberPeer` requires an existing member): Optimystic can save a
16
- * multi-collection transaction's tables separately, and remaining members can
17
- * apply them in either order. The one exception is the founder's bootstrap,
18
- * which writes its own `Member` and `MemberPeer` in one transaction; that is
19
- * acceptable because it commits before any other party has joined, so no other
20
- * party's enforcer is reading yet. Everything NOT in the set is admitted.
21
- * Deliberate consequences:
22
- *
23
- * - **Open strands are untouched.** `Member`/`MemberPeer` carry `OnlyClosed`
24
- * checks, so an open strand has no rows and the set is empty — and
25
- * `StrandInstanceManager` additionally skips arming this enforcer entirely for
26
- * `Type !== 'c'`, so an open strand neither subscribes nor reads.
27
- * - **A joining party mid-admission is admitted** (it has no orphaned binding).
28
- * An allowlist ("only peers bound to live members") was considered and
29
- * rejected: a joiner's first membership writes must travel through the very
30
- * cohort an allowlist would close to it — the same mutual-denial trap the
31
- * control network's gater doc describes (`membership-connection-gater.ts`),
32
- * with no enrollment window to carve out. A deny-list on positive evidence
33
- * has no such trap.
34
- * - **Stale-view failure direction: fail-open.** A remaining member that has not
35
- * yet replicated the revocation keeps serving the removed party until the
36
- * tombstoned state arrives — bounded by replication, consistent with
37
- * "revocation is forward-looking". The opposite error (denying a legitimate
38
- * member) is only reachable for a revoked-then-re-admitted party at a node
39
- * that saw the revoke but not the re-add; the re-add gives the member key a
40
- * live `Member` row again, which removes its peers from the deny set as the
41
- * row replicates — self-healing, and the re-adding manager's own node updates
42
- * first, so the heal never depends on talking to the peer being wrongly denied.
43
- * - **Orphaned `MemberPeer` rows are load-bearing**: they ARE the deny record —
44
- * the `Strand.Revocation` tombstone keeps only the stamp, not the peer id — so
45
- * nothing here (or anywhere) tombstones or auto-cleans them at revocation.
46
- * The manager-cleanup path (`removeMemberPeer`'s manager branch) stays as the
47
- * only way to clear a wrongly-registered binding, and clearing an orphan
48
- * forgets the denial (the NOTE at that branch says so).
49
- *
50
- * ## Removal cuts LIVE sessions too — the refresh IS the teardown seam
51
- *
52
- * Refusing NEW connections only half-honors "no longer be answered to or
53
- * communicated with": a long-lived strand connection may never re-dial, so
54
- * without teardown a removed party keeps whatever session it already holds.
55
- * Teardown rides the snapshot refresh itself, which runs when the membership
56
- * tables change (see "When the deny set is refreshed"). `refresh()` is public
57
- * for a caller that wants to await the cut
58
- * (`StrandInstanceManager.refreshRevocationEnforcement` →
59
- * `CadreNode.refreshRevocationEnforcement`): it resolves only after the sweep.
60
- *
61
- * The sweep is driven by MEMBERSHIP in the deny set, never by an
62
- * entered-the-set diff: every refresh hangs up every currently-connected
63
- * revoked peer, so a resume, a crashed refresh, or a connection established
64
- * between two refreshes cannot leave a session standing (a diff would be a
65
- * strict subset of this, so none is kept). A peer with no open connection is
66
- * simply not swept, and a failed `hangUp` is logged, never thrown, and retried
67
- * by a refresh {@link REVOCATION_REFRESH_RETRY_MS} later. `hangUp` closes DIRECT and RELAYED connections alike, and
68
- * on a strand node running the relay server it also drops any reservation the
69
- * revoked peer holds there (a reservation dies with its connection — see the
70
- * relay-seam doc in `membership-connection-gater.ts`).
71
- *
72
- * Teardown is also what stops OUTBOUND traffic. The gate is one-directional —
73
- * `authorizeStream` judges streams the revoked peer opens to US — so nothing
74
- * else prevents this node from pushing over an already-open connection, which
75
- * `PeerJoinBackfill` does for that connection's whole life. Closing the
76
- * connection stops both directions at once, which is why no separate outbound
77
- * gate exists.
78
- *
79
- * If this node's OWN peer id is in the set, it was itself removed (or it left —
80
- * a voluntary departure files the same tombstone). Nothing is torn down for
81
- * that: the other side's gate already refuses us, and every other revoked peer
82
- * is still swept. Instead `onSelfRevoked` fires ONCE per entry into the set
83
- * (re-armed if the party is re-admitted, so a second removal signals again),
84
- * which `CadreNode` surfaces as `strand:revoked` so the embedding app decides
85
- * what to do — this module never stops or leaves a strand on its own.
86
- * Best-effort by nature: a removed party learns only if the tombstone
87
- * replicated to it before the cut.
88
- *
89
- * ## When the deny set is refreshed
90
- *
91
- * Every refresh runs on one table change subscription (`table-change-watch.ts`),
92
- * single-flight, so no two scheduled refreshes overlap:
93
- *
94
- * - **On a change** to `Strand.Member` or `Strand.MemberPeer`. App writes
95
- * (`revokeMember`, `leaveStrand`) commit on the same Quereus `Database` the
96
- * subscription is on, so a local removal is acted on within the coalescing
97
- * window; a replicated one when this node's storage takes it in.
98
- * - **Once at start**, when the strand's database is published.
99
- * - **On a backstop** ({@link DEFAULT_REVOCATION_BACKSTOP_MS} after the last
100
- * refresh settled), for a change that raised no event.
101
- * - **After a failed refresh**, {@link REVOCATION_REFRESH_RETRY_MS} later. The
102
- * first successful read also arms the plugin's bridge for replicated changes
103
- * (the NOTE on `watchTables`), so until one succeeds only local commits wake it.
104
- * - **After each successful refresh on a wide strand** — more distinct bound peer ids than
105
- * the cluster size — {@link REVOCATION_WIDE_STRAND_REFRESH_MS} later, because
106
- * this node may be outside a membership block's cohort and so hear no change.
107
- *
108
- * ## What transfers from the control gater (`membership-connection-gater.ts`)
109
- *
110
- * Transfers: the two-layer shape (fail-closed per-stream gate as PRIMARY, a
111
- * connection-level layer on top), the synchronous in-memory
112
- * snapshot judged by the stream gate (a live DB read inside a gate deadlocks —
113
- * the same argument as the control node's `authorizeInboundControlStream`), the
114
- * fail-open-on-error/timeout posture for the connection hooks
115
- * (`decideWithinDeadline`, reused as-is), and the "compose over the caller's
116
- * gater, every base hook preserved" mechanics.
117
- *
118
- * Does NOT transfer — provisional admission and the relay-reservation seam
119
- * (`'admit-provisionally'`, its deadline, the unauthorized budget). That
120
- * machinery exists because the control gate judges on ABSENCE of placement,
121
- * where a member whose row is in flight, or a device whose invitation row has
122
- * not arrived, is indistinguishable from an outsider, and a wrong reservation
123
- * deny is unrecoverable. This gate denies on POSITIVE revocation evidence, so a
124
- * deny is never that kind of wrong answer; the one stale-wrong case (a missed
125
- * re-add) heals via replication as above. Every hook here is therefore a plain
126
- * "deny iff revoked" — no budget, no provisional verdict, no deadline.
127
- *
128
- * Does NOT transfer — the bring-up quiet period. A strand node's DB bring-up
129
- * NEEDS its cross-party cohort connections; this enforcer simply starts with an
130
- * empty snapshot (admit everything) until its first successful read — the same
131
- * fail-open posture as everywhere else here.
132
- *
133
- * Does NOT transfer — every stranger carve-out (enrollment window, formation
134
- * window, delegate grants). None of those protocols exist on a strand node.
135
- *
136
- * Unlike the control stream gate, no empty-snapshot carve-out is needed: an
137
- * empty deny set means "nothing revoked", which correctly admits everyone — the
138
- * deny-list shape makes the cold-start case and the steady case the same code
139
- * path.
140
- */
141
-
142
- import debug from 'debug';
143
- import type { ConnectionGater, PeerId, MultiaddrConnection } from '@libp2p/interface';
144
- import type { Database } from '@quereus/quereus';
145
- import { decideWithinDeadline } from './membership-connection-gater.js';
146
- import { ADMISSION_DECISION_TIMEOUT_MS } from './link-budget.js';
147
- import { scheduleRuns, type TableChangeWatch, type TableChangeWatchOptions } from './table-change-watch.js';
148
- import type { TimeoutScheduler } from './timeout-scheduler.js';
149
-
150
- const log = debug('sereus:cadre:strand-revocation');
151
-
152
- /**
153
- * Default longest wait between two deny-set refreshes when no membership change
154
- * is heard. Overridable via {@link StrandRevocationEnforcementConfig.backstopMs}.
155
- *
156
- * NOTE: the backstop covers two paths the change subscription does not: a
157
- * machine that was offline when the removal was committed (it normally takes
158
- * the blocks in by join backfill or read repair on reconnect, which raise the
159
- * change too), and any change that reaches storage without an event. The case
160
- * of a node outside a membership block's cohort is covered by
161
- * {@link REVOCATION_WIDE_STRAND_REFRESH_MS}, not by this.
162
- */
163
- export const DEFAULT_REVOCATION_BACKSTOP_MS = 5 * 60_000;
164
-
165
- /**
166
- * How soon a failed refresh is retried. Also how soon a replicated removal is
167
- * heard after a first read that failed, since that read is what arms the
168
- * plugin's replicated-change bridge for the two tables.
169
- */
170
- export const REVOCATION_REFRESH_RETRY_MS = 30_000;
171
-
172
- /**
173
- * How soon a strand with more distinct bound peer ids than its cluster size is
174
- * refreshed again after a successful refresh. On such a strand this node may be
175
- * outside a membership block's cohort, so it takes in no storage event for a
176
- * removal (`docs/architecture.md` → "Table change subscriptions").
177
- */
178
- export const REVOCATION_WIDE_STRAND_REFRESH_MS = 30_000;
179
-
180
- /**
181
- * Embedder tuning for the strand revoked-peer gate, threaded from
182
- * `CadreNodeConfig.strandRevocationEnforcement` to
183
- * `StartStrandConfig.revocationEnforcement` the way the backfill knob is.
184
- */
185
- export interface StrandRevocationEnforcementConfig {
186
- /**
187
- * Default true. False disarms the gate entirely for this node's strands —
188
- * the pre-existing behaviour (a removed party's peers keep being served).
189
- */
190
- enabled?: boolean;
191
- /** Longest wait between two refreshes with no change heard, ms. Default {@link DEFAULT_REVOCATION_BACKSTOP_MS}. */
192
- backstopMs?: number;
193
- /**
194
- * Default true: the enforcer schedules its own refreshes — on a change to
195
- * `Strand.Member` or `Strand.MemberPeer`, after a failed read or hang-up, and
196
- * on a wide strand's follow-up. False schedules none of those, so refreshes
197
- * run only at start, on the backstop, and on `refreshRevocationEnforcement`.
198
- * For test scenarios that need a machine's cuts to be the ones the test drove;
199
- * a production node leaves it on.
200
- */
201
- autoRefresh?: boolean;
202
- }
203
-
204
- /** One `Strand.MemberPeer` row, as the deny-set derivation consumes it. */
205
- export interface StrandMemberPeerBinding {
206
- memberKey: string;
207
- peerId: string;
208
- }
209
-
210
- /** The membership rows one deny-set derivation reads. */
211
- export interface StrandRevocationRows {
212
- /** Every live `Strand.Member.Key`. */
213
- memberKeys: ReadonlySet<string>;
214
- /** Every `Strand.MemberPeer` row (live-membered and orphaned alike). */
215
- bindings: readonly StrandMemberPeerBinding[];
216
- }
217
-
218
- /**
219
- * The minimum of a libp2p node the teardown sweep needs: who WE are, what is
220
- * open, and how to close it. Deliberately not the node itself, so the sweep
221
- * unit-tests against a three-property stub; `Libp2p` (hence
222
- * `Libp2pNodeWithRepo`) satisfies it structurally, which is what
223
- * `StrandInstanceManager` passes.
224
- */
225
- export interface StrandRevocationNetwork {
226
- /** This node's own peer id — how the enforcer recognizes ITSELF in the deny set. */
227
- readonly peerId: PeerId;
228
- /** Every open connection. Only `remotePeer` is read — and reused as the hangUp target. */
229
- getConnections(): readonly { readonly remotePeer: PeerId }[];
230
- /** Close every connection to `peer`: direct, relayed, and any reservation riding one. */
231
- hangUp(peer: PeerId): Promise<void>;
232
- }
233
-
234
- export interface StrandRevocationEnforcerDeps {
235
- /** Log tag naming which strand this enforcer serves (the strand id). */
236
- label: string;
237
- /**
238
- * Read the membership rows the deny set is derived from. Injectable so the
239
- * enforcer unit-tests without a strand database; production wires
240
- * {@link readStrandRevocationRows} over the strand's live DB. A throw or
241
- * rejection KEEPS the previous snapshot (never clears it) — the control
242
- * model, `refreshAuthorizedControlPeers`.
243
- */
244
- readRows: () => Promise<StrandRevocationRows>;
245
- /**
246
- * Handle on the strand's libp2p node for the teardown sweep, read LAZILY on
247
- * every sweep — never captured. It has to be: the enforcer is constructed
248
- * BEFORE the node (the node's options embed the enforcer's predicates), and
249
- * the node is dropped again on quiesce. Omit it, or return undefined, and the
250
- * gate still refuses new connections — only teardown of OPEN ones is skipped.
251
- */
252
- getNetwork?: () => StrandRevocationNetwork | undefined;
253
- /**
254
- * Called ONCE each time this node's own peer id ENTERS the deny set — i.e.
255
- * this node's party was removed from the strand, or left it. Not re-fired
256
- * while it stays there; re-armed if the party is re-admitted, so a second
257
- * removal signals again. Wired by `StrandInstanceManager` through to
258
- * `CadreNode`'s `strand:revoked` event. A resume rebuilds the enforcer, so a
259
- * still-revoked strand also legitimately re-fires once per resume. A throw is
260
- * logged and swallowed — an embedder's handler must not derail the sweep.
261
- */
262
- onSelfRevoked?: () => void;
263
- /**
264
- * Called ONCE each time this node's own peer id LEAVES the deny set after
265
- * {@link onSelfRevoked} reported it there — a manager re-admitted the party, or a
266
- * sibling machine bound this node under the party's current key after a key rotation
267
- * left its only binding orphaned (`strand-membership-reconciler.ts` → "Binding the
268
- * party's other machines"). Not fired by a first refresh that finds this node clear.
269
- * `StrandInstanceManager` wires it to the strand's membership reconciler, which stopped
270
- * on the revocation and restarts here. A throw is logged and swallowed, as for
271
- * {@link onSelfRevoked}.
272
- */
273
- onSelfRestored?: () => void;
274
- /**
275
- * Subscribe `onChange` to changes in `Strand.Member` and `Strand.MemberPeer`
276
- * (`StrandDatabase.watchTables`). Absent, or throwing: refreshes come from
277
- * start, the backstop, retries and wide-strand follow-ups only (unit tests).
278
- */
279
- watchChanges?(onChange: () => Promise<void>, options: TableChangeWatchOptions): TableChangeWatch;
280
- /**
281
- * The strand's cluster size. A snapshot with more distinct bound peer ids than
282
- * this schedules {@link REVOCATION_WIDE_STRAND_REFRESH_MS}; absent, never.
283
- */
284
- cohortBreadth?: number;
285
- /** Timer seam for the watch; omit for real (unref'd) timeouts. */
286
- scheduler?: TimeoutScheduler;
287
- }
288
-
289
- /** Every `Strand.MemberPeer` binding — live-membered and orphaned alike. */
290
- async function scanBindings(db: Database): Promise<StrandMemberPeerBinding[]> {
291
- const bindings: StrandMemberPeerBinding[] = [];
292
- for await (const row of db.eval('select MemberKey, PeerId from Strand.MemberPeer')) {
293
- bindings.push({ memberKey: row.MemberKey as string, peerId: row.PeerId as string });
294
- }
295
- return bindings;
296
- }
297
-
298
- /** Every live `Strand.Member.Key`. */
299
- async function scanMemberKeys(db: Database): Promise<Set<string>> {
300
- const memberKeys = new Set<string>();
301
- for await (const row of db.eval('select Key from Strand.Member')) {
302
- memberKeys.add(row.Key as string);
303
- }
304
- return memberKeys;
305
- }
306
-
307
- /**
308
- * Read the deny-set inputs from a strand database: full-scan
309
- * `Strand.MemberPeer` and `Strand.Member`, to be joined in JavaScript by the
310
- * enforcer. Scan-and-filter, never seek — the composite-PK point-lookup
311
- * unreliability documented at `scanMemberPeers` in `strand-membership-writer.ts`
312
- * applies, so correctness depends only on each scan returning a superset of the
313
- * live rows.
314
- *
315
- * **Scan order is load-bearing, and it is BINDINGS FIRST.** The two scans are
316
- * separate reads with nothing holding them to one snapshot, so a write that
317
- * lands between them is seen by the second scan and not the first. A member
318
- * joins as `Member` row then `MemberPeer` row (`MemberExists` forces that
319
- * order; the module doc says why it holds on the network), so reading `Member`
320
- * first would let a join that commits mid-read produce a binding whose member
321
- * key is absent from the key set — a brand-new member classified as REVOKED,
322
- * the one fail-CLOSED outcome this module exists to avoid. Reading bindings
323
- * first inverts the skew: the new binding is simply not in the older bindings
324
- * snapshot, so the joiner is unclassified and admitted, and a revocation that
325
- * lands mid-read is still seen (the key is missing from the NEWER key scan).
326
- * Every skew window then resolves fail-open, matching the module doc.
327
- *
328
- * NOTE: two whole-table scans per refresh (on each membership change and each
329
- * backstop, per closed strand). Fine at strand scale (a handful of members and bindings); if
330
- * membership churn ever makes these tables large, the fix is a reliable
331
- * filtered read — which needs the networked point-lookup gap closed
332
- * (`debt-composite-pk-point-lookup-unreliable-untracked`) — not a bigger scan.
333
- */
334
- export async function readStrandRevocationRows(db: Database): Promise<StrandRevocationRows> {
335
- const bindings = await scanBindings(db);
336
- const memberKeys = await scanMemberKeys(db);
337
- return { memberKeys, bindings };
338
- }
339
-
340
- /**
341
- * The per-strand revoked-peer deny set and the synchronous predicates over it.
342
- *
343
- * Lifecycle: created in `StrandInstanceManager.buildStrandRuntime` (closed
344
- * strands only), started when `publishDatabase` hands the strand's database to
345
- * the app, stopped and dropped in `releaseRuntime` — so quiesce → resume
346
- * rebuilds it with a fresh snapshot. The snapshot starts EMPTY (admit
347
- * everything) and repopulates on the first successful read; a revoked peer
348
- * therefore gets a short admit window per resume at the connection level.
349
- * Accepted: fail-open posture, and resume is never blocked on a refresh.
350
- */
351
- export class StrandRevocationEnforcer {
352
- /** The materialized deny set — peer ids with an orphaned binding and no live one. */
353
- private revokedPeerIds: ReadonlySet<string> = new Set();
354
- private readonly backstopMs: number;
355
- private readonly autoRefresh: boolean;
356
- /** Tail of the refresh chain — what serializes refreshes (no two reads in flight). */
357
- private refreshTail: Promise<void> = Promise.resolve();
358
- /** Every scheduled refresh runs on it; present between {@link start} and {@link stop}. */
359
- private watch: TableChangeWatch | undefined;
360
- private started = false;
361
- private stopped = false;
362
- /** Latch for the one-shot self-revocation signal — see {@link StrandRevocationEnforcerDeps.onSelfRevoked}. */
363
- private selfRevokedSignaled = false;
364
-
365
- constructor(
366
- private readonly deps: StrandRevocationEnforcerDeps,
367
- config?: StrandRevocationEnforcementConfig
368
- ) {
369
- this.backstopMs = config?.backstopMs ?? DEFAULT_REVOCATION_BACKSTOP_MS;
370
- this.autoRefresh = config?.autoRefresh ?? true;
371
- }
372
-
373
- /** Number of peers currently denied — test/diagnostic surface. */
374
- get revokedCount(): number {
375
- return this.revokedPeerIds.size;
376
- }
377
-
378
- /**
379
- * Subscribe to membership changes and run one refresh at once (not awaited —
380
- * bring-up never blocks on it); the module doc's "When the deny set is
381
- * refreshed" has the full schedule. Call once the strand's database is
382
- * published. A second call, or one after {@link stop}, is a no-op.
383
- */
384
- start(): void {
385
- if (this.started || this.stopped) return;
386
- this.started = true;
387
- this.watch = this.subscribe();
388
- this.watch.trigger(0);
389
- log('[%s] revocation enforcer started (backstop %dms)', this.deps.label, this.backstopMs);
390
- }
391
-
392
- /** Stop scheduling refreshes; a read already in flight completes but its result is discarded. */
393
- stop(): void {
394
- if (this.stopped) return;
395
- this.stopped = true;
396
- this.watch?.dispose();
397
- this.watch = undefined;
398
- log('[%s] revocation enforcer stopped', this.deps.label);
399
- }
400
-
401
- /**
402
- * Refresh the deny set now. Never rejects. Serialized: concurrent calls chain,
403
- * so no two reads overlap, and each explicit call gets a read that STARTS
404
- * after the call (an on-demand refresh after a revocation commit observes that
405
- * commit). A failed or slow read keeps the previous snapshot — never clears it.
406
- */
407
- refresh(): Promise<void> {
408
- const run = this.refreshTail.then(() => this.doRefresh());
409
- this.refreshTail = run;
410
- return run;
411
- }
412
-
413
- /**
414
- * Is `remotePeerId` positively revoked in the current snapshot? Synchronous by
415
- * design — this is judged inside libp2p gates where an await against the DB
416
- * would deadlock (the control stream gate's argument).
417
- */
418
- isRevoked(remotePeerId: string): boolean {
419
- return this.revokedPeerIds.has(remotePeerId);
420
- }
421
-
422
- /**
423
- * The fail-closed PRIMARY layer: the per-stream predicate wired as
424
- * `createLibp2pNode({ authorizeInboundStream })`, gating all four
425
- * `/optimystic/strand-<id>/{repo,cluster,sync,block-transfer}` protocols.
426
- * Also what catches a revoked peer arriving over a RELAYED connection, or
427
- * over a connection admitted before the revocation replicated here.
428
- */
429
- authorizeStream(remotePeerId: string, _protocol: string): boolean {
430
- return !this.isRevoked(remotePeerId);
431
- }
432
-
433
- /**
434
- * The watch every scheduled refresh runs on: the deps' change subscription, or
435
- * a timer-only one when changes are not watched or the subscription throws.
436
- *
437
- * NOTE: a refresh can wake itself once. Its read may start a read-repair sync
438
- * (a held block read more than Optimystic's `readRepairWindowMs`, 10 s, after
439
- * its last check), and that sync's landing raises a change. The follow-up
440
- * refresh runs within the coalescing window plus one read — well inside the
441
- * read-repair window — so it starts no second sync and the chain stops there.
442
- * If idle sync counts on a strand do not fall with this subscription, suspect
443
- * this loop first.
444
- */
445
- private subscribe(): TableChangeWatch {
446
- const onChange = (): Promise<void> => this.refresh();
447
- const options: TableChangeWatchOptions = {
448
- label: `strand-revocation:${this.deps.label}`,
449
- backstopMs: this.backstopMs,
450
- scheduler: this.deps.scheduler,
451
- };
452
- if (this.autoRefresh && this.deps.watchChanges) {
453
- try {
454
- return this.deps.watchChanges(onChange, options);
455
- } catch (error) {
456
- log('[%s] membership change subscription failed — refreshing on the backstop and retries only: %o', this.deps.label, error);
457
- }
458
- }
459
- return scheduleRuns(onChange, options);
460
- }
461
-
462
- /**
463
- * One serialized snapshot rebuild; contains every failure (contract: never rejects).
464
- *
465
- * NOTE: nothing here carries a deadline — a `readRows` or a `hangUp` that never
466
- * settles wedges the refresh chain, which freezes the deny set (the watch runs
467
- * one refresh at a time, and every later `refresh()` chains behind the stuck one).
468
- * Both are bounded in practice (Quereus reads settle; libp2p's connection close
469
- * has its own timeout). If a strand is ever seen with a stale deny set and no
470
- * refresh log line, wrap both awaits in a timeout rather than hunting further.
471
- */
472
- private async doRefresh(): Promise<void> {
473
- if (this.stopped) return;
474
- try {
475
- const rows = await this.deps.readRows();
476
- if (this.stopped) return;
477
- this.revokedPeerIds = deriveRevokedPeerIds(rows);
478
- log('[%s] deny set refreshed: %d revoked peer(s)', this.deps.label, this.revokedPeerIds.size);
479
- this.followUpWideStrand(rows);
480
- // Awaited inside the refresh, so an on-demand refresh() resolves only once
481
- // the cut has been made — that is what makes "revoke, then refresh" an
482
- // immediate teardown for the caller rather than a scheduled one.
483
- await this.tearDownRevoked(this.revokedPeerIds);
484
- } catch (error) {
485
- log('[%s] deny-set refresh failed — keeping previous snapshot: %o', this.deps.label, error);
486
- this.scheduleFollowUp(REVOCATION_REFRESH_RETRY_MS, 'refresh failed');
487
- }
488
- }
489
-
490
- /** Arm one more refresh `delayMs` from now, unless {@link StrandRevocationEnforcementConfig.autoRefresh} is off or the enforcer is not running. */
491
- private scheduleFollowUp(delayMs: number, reason: string): void {
492
- if (!this.autoRefresh || !this.watch) return;
493
- log('[%s] %s — refreshing again in %dms', this.deps.label, reason, delayMs);
494
- this.watch.trigger(delayMs);
495
- }
496
-
497
- /** Schedule {@link REVOCATION_WIDE_STRAND_REFRESH_MS} when `rows` bind more distinct peers than the cluster holds. */
498
- private followUpWideStrand(rows: StrandRevocationRows): void {
499
- const breadth = this.deps.cohortBreadth;
500
- if (breadth === undefined) return;
501
- const boundPeers = new Set(rows.bindings.map((binding) => binding.peerId)).size;
502
- if (boundPeers > breadth) {
503
- this.scheduleFollowUp(REVOCATION_WIDE_STRAND_REFRESH_MS, `${boundPeers} bound peers on a cluster of ${breadth}`);
504
- }
505
- }
506
-
507
- /**
508
- * Close what is already OPEN to the peers of `revoked` — the teardown half of
509
- * enforcement (module doc: "Removal cuts LIVE sessions too"). Never rejects:
510
- * every failure is contained, so the refresh chain survives, and a failed
511
- * `hangUp` schedules a retry.
512
- *
513
- * `revoked` is passed IN rather than read off the field, so the sweep judges
514
- * the exact snapshot its own refresh produced; likewise the connection list is
515
- * enumerated once, before any await, so a peer re-admitted mid-sweep is at
516
- * worst hung up once and reconnects.
517
- *
518
- * NOTE: dropping the revoked peer from the strand's Optimystic cohort needs no
519
- * separate action — machines quiesce strands routinely and the remaining cohort
520
- * keeps committing, so an unreachable cohort peer is already tolerated, and
521
- * `denyDialPeer` makes the exclusion fast (a local refusal, not a dial timeout).
522
- * Two residual facts, both accepted: the removed node keeps every block it had
523
- * already replicated (revocation is forward-looking), and a block whose only
524
- * holders were the removed party's machines can be unavailable to the rest
525
- * until repair.
526
- *
527
- * NOTE: post-removal commit latency is real and MEASURED, not hypothetical. On
528
- * the two-parties-by-two-machines fixture in
529
- * `integration-tests/src/scenarios/strand-removal-cuts-network.integration.ts`
530
- * the remaining cohort's FIRST write after a cut fails repeatedly with
531
- * `BlockUnavailableError: … (peers-unreachable)` before it commits — three or
532
- * four failures, 3.5-4.3 s, over four runs — because the cohort still listed
533
- * the removed party's now unreachable machines and had to downsize to the
534
- * live holders first. It
535
- * recovers on its own, so this is a latency cost, not a defect, and it is
536
- * stated for app authors in `docs/strands.md` → Removing Members. If it ever
537
- * stops recovering — a write that never commits, or `cluster-fetch:no-quorum` —
538
- * that is an upstream (Optimystic) conversation, not a workaround here.
539
- */
540
- private async tearDownRevoked(revoked: ReadonlySet<string>): Promise<void> {
541
- if (this.stopped) {
542
- return;
543
- }
544
- const network = this.resolveNetwork();
545
- if (!network) {
546
- return;
547
- }
548
- const selfPeerId = network.peerId.toString();
549
- // Judged on EVERY pass, including the empty-set one: leaving the set is what
550
- // re-arms the signal (see trackSelfRevoked). Being revoked ourselves tears
551
- // nothing down on our own behalf — the other side's gate already refuses us —
552
- // so the sweep below still runs for every OTHER revoked peer in the pass.
553
- this.trackSelfRevoked(revoked.has(selfPeerId));
554
- if (revoked.size === 0) {
555
- return;
556
- }
557
- for (const peer of connectedRevokedPeers(network, revoked, selfPeerId, this.deps.label)) {
558
- await this.hangUpRevoked(network, peer);
559
- }
560
- }
561
-
562
- /** The lazily-read network handle; an accessor that throws costs this pass only. */
563
- private resolveNetwork(): StrandRevocationNetwork | undefined {
564
- try {
565
- return this.deps.getNetwork?.();
566
- } catch (error) {
567
- log('[%s] network handle unavailable — teardown skipped this pass: %o', this.deps.label, error);
568
- return undefined;
569
- }
570
- }
571
-
572
- /** One hangUp, contained: a stopping node or an already-closed connection is not an error here. */
573
- private async hangUpRevoked(network: StrandRevocationNetwork, peer: PeerId): Promise<void> {
574
- try {
575
- await network.hangUp(peer);
576
- log('[%s] hung up revoked peer %s', this.deps.label, peer.toString());
577
- } catch (error) {
578
- log('[%s] hangUp of revoked peer %s failed: %o', this.deps.label, peer.toString(), error);
579
- this.scheduleFollowUp(REVOCATION_REFRESH_RETRY_MS, 'hangUp failed');
580
- }
581
- }
582
-
583
- /**
584
- * Latch {@link StrandRevocationEnforcerDeps.onSelfRevoked} to the TRANSITION
585
- * into the revoked state: fired once on entry, and re-armed the moment this
586
- * node is out of the set again — a manager can re-admit a party it removed
587
- * (a fresh `Member` row makes the orphaned bindings live again), and a second
588
- * removal has to be reported like the first. Leaving the set after a report is
589
- * the other edge, {@link StrandRevocationEnforcerDeps.onSelfRestored}.
590
- */
591
- private trackSelfRevoked(selfRevoked: boolean): void {
592
- if (selfRevoked === this.selfRevokedSignaled) {
593
- return;
594
- }
595
- this.selfRevokedSignaled = selfRevoked;
596
- if (selfRevoked) {
597
- log('[%s] THIS node is revoked from the strand (removed or left) — signalling', this.deps.label);
598
- this.signalSelf(this.deps.onSelfRevoked, 'onSelfRevoked');
599
- } else {
600
- log('[%s] THIS node is no longer revoked from the strand — signalling', this.deps.label);
601
- this.signalSelf(this.deps.onSelfRestored, 'onSelfRestored');
602
- }
603
- }
604
-
605
- /** Fire one of the self-state handlers; a throw is logged and must not derail the sweep. */
606
- private signalSelf(handler: (() => void) | undefined, name: string): void {
607
- try {
608
- handler?.();
609
- } catch (error) {
610
- log('[%s] %s handler threw: %o', this.deps.label, name, error);
611
- }
612
- }
613
- }
614
-
615
- /**
616
- * The distinct peer ids of `network`'s open connections that are in `revoked`,
617
- * as the `PeerId` objects `hangUp` takes — reusing each connection's own
618
- * `remotePeer` rather than parsing the string back, so no peer-id codec is
619
- * needed here. Self is excluded (a node holds no connection to itself, and
620
- * hanging one up would be nonsense if it did), and a peer connected twice — say
621
- * one direct and one relayed — yields ONE hangUp, which closes both. A throw
622
- * mid-enumeration is logged and keeps whatever was collected before it: a
623
- * partial sweep beats none, and the next refresh re-enumerates anyway.
624
- */
625
- function connectedRevokedPeers(
626
- network: StrandRevocationNetwork,
627
- revoked: ReadonlySet<string>,
628
- selfPeerId: string,
629
- label: string
630
- ): PeerId[] {
631
- const targets = new Map<string, PeerId>();
632
- try {
633
- for (const connection of network.getConnections()) {
634
- const remotePeerId = connection.remotePeer.toString();
635
- if (remotePeerId !== selfPeerId && revoked.has(remotePeerId)) {
636
- targets.set(remotePeerId, connection.remotePeer);
637
- }
638
- }
639
- } catch (error) {
640
- log('[%s] connection enumeration failed — teardown skipped this pass: %o', label, error);
641
- }
642
- return [...targets.values()];
643
- }
644
-
645
- /**
646
- * Derive the deny set: a peer id is revoked iff it has at least one ORPHANED
647
- * binding (a `MemberPeer` row whose member key has no live `Member` row) AND no
648
- * live-membered binding. The second conjunct is what lets a peer id bound to
649
- * TWO member keys — revoked under one, live under the other — keep serving the
650
- * live member: a machine serving a live member must not be cut. Per-binding,
651
- * not per-member, so every machine of a multi-device removed party lands in
652
- * the set.
653
- */
654
- function deriveRevokedPeerIds(rows: StrandRevocationRows): Set<string> {
655
- const orphaned = new Set<string>();
656
- const live = new Set<string>();
657
- for (const binding of rows.bindings) {
658
- (rows.memberKeys.has(binding.memberKey) ? live : orphaned).add(binding.peerId);
659
- }
660
- for (const peerId of live) {
661
- orphaned.delete(peerId);
662
- }
663
- return orphaned;
664
- }
665
-
666
- /** The one capability the gater composition needs from the enforcer. */
667
- export type StrandRevocationJudge = Pick<StrandRevocationEnforcer, 'isRevoked'>;
668
-
669
- /**
670
- * Build a closed strand's connection gater: the caller-supplied gater (if any)
671
- * with revoked-peer denial composed onto three hooks. The opportunistic
672
- * SECONDARY layer — the per-stream gate above is the fail-closed primary.
673
- *
674
- * - `denyInboundEncryptedConnection`: deny iff revoked, so a removed party's
675
- * node is refused before any protocol negotiation.
676
- * - `denyDialPeer`: deny iff revoked — the owner ruling covers "communicated
677
- * with", not just "answered to", and refusing the dial locally is instant,
678
- * which keeps Optimystic from wasting a dial timeout on a peer this node
679
- * will not talk to anyway.
680
- * - `denyInboundRelayReservation`: deny iff revoked — matters when the strand
681
- * node runs the relay server (the storage-profile default), where admitting
682
- * the reservation would let a removed party keep using this node's
683
- * forwarding capacity.
684
- *
685
- * Composition semantics: every hook of `base` is preserved as-is; on the three
686
- * composed hooks a deny from EITHER the base gater or the revocation check
687
- * denies, and an error (or a decision slower than `decisionTimeoutMs`) in
688
- * either is fail-open — the base error admits through to the revocation check,
689
- * a revocation-check error admits outright, and the fail-closed stream gate
690
- * still stands behind both. The deadline is belt-and-braces: the snapshot read
691
- * is synchronous.
692
- *
693
- * NOTE: accepted tradeoff — swallowing a BASE hook's throw diverges from
694
- * `createMembershipConnectionGater`, which lets it propagate to libp2p (a
695
- * fail-closed outcome there). Uniform fail-open was chosen for this module so
696
- * every hook has one failure direction, and it was the shape the plan specified;
697
- * the cost is that an embedder gater which throws is silently admitted here
698
- * while the same gater passed raw to an OPEN strand would refuse. Loud in the
699
- * log either way. Revisit if an embedder ever ships a gater whose throw is a
700
- * meaningful deny, or if the two gaters are unified.
701
- *
702
- * NOTE: `base` is spread, so a gater passed as a CLASS INSTANCE would lose its
703
- * prototype methods — same caveat as `createMembershipConnectionGater`; every
704
- * caller in this repo supplies a plain object (the RN/web permissive gaters,
705
- * e.g. `{ denyDialMultiaddr: () => false }`, keep working unchanged).
706
- */
707
- export function createRevocationConnectionGater(
708
- enforcer: StrandRevocationJudge,
709
- base?: ConnectionGater,
710
- decisionTimeoutMs: number = ADMISSION_DECISION_TIMEOUT_MS
711
- ): ConnectionGater {
712
- /** The base gater's verdict, fail-open: an error or absence is "not denied". */
713
- const baseDenies = async (decide: () => Promise<boolean> | boolean | undefined, hook: string): Promise<boolean> => {
714
- try {
715
- return await decide() === true;
716
- } catch (error) {
717
- log('base gater %s threw — treating as not-denied (fail-open): %o', hook, error);
718
- return false;
719
- }
720
- };
721
- /** The revocation verdict, bounded and fail-open. */
722
- const revokedDenies = async (peerId: PeerId, hook: string): Promise<boolean> => {
723
- const remotePeerId = peerId.toString();
724
- try {
725
- const revoked = await decideWithinDeadline(
726
- () => enforcer.isRevoked(remotePeerId), false, decisionTimeoutMs, `${hook}(${remotePeerId})`
727
- );
728
- if (revoked) {
729
- log('%s: %s is revoked — denying', hook, remotePeerId);
730
- }
731
- return revoked;
732
- } catch (error) {
733
- log('%s revocation check threw for %s — admitting (fail-open; stream gate decides): %o', hook, remotePeerId, error);
734
- return false;
735
- }
736
- };
737
- return {
738
- ...base,
739
- denyDialPeer: async (peerId: PeerId): Promise<boolean> => {
740
- if (await baseDenies(() => base?.denyDialPeer?.(peerId), 'denyDialPeer')) {
741
- return true;
742
- }
743
- return revokedDenies(peerId, 'denyDialPeer');
744
- },
745
- denyInboundEncryptedConnection: async (peerId: PeerId, maConn: MultiaddrConnection): Promise<boolean> => {
746
- if (await baseDenies(() => base?.denyInboundEncryptedConnection?.(peerId, maConn), 'denyInboundEncryptedConnection')) {
747
- return true;
748
- }
749
- return revokedDenies(peerId, 'denyInboundEncryptedConnection');
750
- },
751
- denyInboundRelayReservation: async (peerId: PeerId): Promise<boolean> => {
752
- if (await baseDenies(() => base?.denyInboundRelayReservation?.(peerId), 'denyInboundRelayReservation')) {
753
- return true;
754
- }
755
- return revokedDenies(peerId, 'denyInboundRelayReservation');
756
- }
757
- };
758
- }
1
+ /**
2
+ * Strand revoked-peer enforcement: a per-strand deny gate that refuses the
3
+ * network nodes of a REMOVED party, so removal means "we stop talking to you"
4
+ * rather than only deleting a row.
5
+ *
6
+ * ## The deny set is revocation-keyed, never membership-keyed
7
+ *
8
+ * A strand node maintains a materialized in-memory set of revoked peer ids:
9
+ * every `Strand.MemberPeer.PeerId` whose `MemberKey` has no live `Strand.Member`
10
+ * row. `MemberPeer.MemberExists` runs on insert, so an orphaned binding can only
11
+ * mean "this member existed and was removed" — it is exactly the durable,
12
+ * replicated record of a removed party's machines. That holds on the network
13
+ * only because every writer commits a party's `Member` row before its
14
+ * `MemberPeer` row, as separate commits (the membership reconciler does, and
15
+ * `registerMemberPeer` requires an existing member): Optimystic can save a
16
+ * multi-collection transaction's tables separately, and remaining members can
17
+ * apply them in either order. The one exception is the founder's bootstrap,
18
+ * which writes its own `Member` and `MemberPeer` in one transaction; that is
19
+ * acceptable because it commits before any other party has joined, so no other
20
+ * party's enforcer is reading yet. Everything NOT in the set is admitted.
21
+ * Deliberate consequences:
22
+ *
23
+ * - **Open strands are untouched.** `Member`/`MemberPeer` carry `OnlyClosed`
24
+ * checks, so an open strand has no rows and the set is empty — and
25
+ * `StrandInstanceManager` additionally skips arming this enforcer entirely for
26
+ * `Type !== 'c'`, so an open strand neither subscribes nor reads.
27
+ * - **A joining party mid-admission is admitted** (it has no orphaned binding).
28
+ * An allowlist ("only peers bound to live members") was considered and
29
+ * rejected: a joiner's first membership writes must travel through the very
30
+ * cohort an allowlist would close to it — the same mutual-denial trap the
31
+ * control network's gater doc describes (`membership-connection-gater.ts`),
32
+ * with no enrollment window to carve out. A deny-list on positive evidence
33
+ * has no such trap.
34
+ * - **Stale-view failure direction: fail-open.** A remaining member that has not
35
+ * yet replicated the revocation keeps serving the removed party until the
36
+ * tombstoned state arrives — bounded by replication, consistent with
37
+ * "revocation is forward-looking". The opposite error (denying a legitimate
38
+ * member) is only reachable for a revoked-then-re-admitted party at a node
39
+ * that saw the revoke but not the re-add; the re-add gives the member key a
40
+ * live `Member` row again, which removes its peers from the deny set as the
41
+ * row replicates — self-healing, and the re-adding manager's own node updates
42
+ * first, so the heal never depends on talking to the peer being wrongly denied.
43
+ * - **Orphaned `MemberPeer` rows are load-bearing**: they ARE the deny record —
44
+ * the `Strand.Revocation` tombstone keeps only the stamp, not the peer id — so
45
+ * nothing here (or anywhere) tombstones or auto-cleans them at revocation.
46
+ * The manager-cleanup path (`removeMemberPeer`'s manager branch) stays as the
47
+ * only way to clear a wrongly-registered binding, and clearing an orphan
48
+ * forgets the denial (the NOTE at that branch says so).
49
+ *
50
+ * ## Removal cuts LIVE sessions too — the refresh IS the teardown seam
51
+ *
52
+ * Refusing NEW connections only half-honors "no longer be answered to or
53
+ * communicated with": a long-lived strand connection may never re-dial, so
54
+ * without teardown a removed party keeps whatever session it already holds.
55
+ * Teardown rides the snapshot refresh itself, which runs when the membership
56
+ * tables change (see "When the deny set is refreshed"). `refresh()` is public
57
+ * for a caller that wants to await the cut
58
+ * (`StrandInstanceManager.refreshRevocationEnforcement` →
59
+ * `CadreNode.refreshRevocationEnforcement`): it resolves only after the sweep.
60
+ *
61
+ * The sweep is driven by MEMBERSHIP in the deny set, never by an
62
+ * entered-the-set diff: every refresh hangs up every currently-connected
63
+ * revoked peer, so a resume, a crashed refresh, or a connection established
64
+ * between two refreshes cannot leave a session standing (a diff would be a
65
+ * strict subset of this, so none is kept). A peer with no open connection is
66
+ * simply not swept, and a failed `hangUp` is logged, never thrown, and retried
67
+ * by a refresh {@link REVOCATION_REFRESH_RETRY_MS} later. `hangUp` closes DIRECT and RELAYED connections alike, and
68
+ * on a strand node running the relay server it also drops any reservation the
69
+ * revoked peer holds there (a reservation dies with its connection — see the
70
+ * relay-seam doc in `membership-connection-gater.ts`).
71
+ *
72
+ * Teardown is also what stops OUTBOUND traffic. The gate is one-directional —
73
+ * `authorizeStream` judges streams the revoked peer opens to US — so nothing
74
+ * else prevents this node from pushing over an already-open connection, which
75
+ * `PeerJoinBackfill` does for that connection's whole life. Closing the
76
+ * connection stops both directions at once, which is why no separate outbound
77
+ * gate exists.
78
+ *
79
+ * If this node's OWN peer id is in the set, it was itself removed (or it left —
80
+ * a voluntary departure files the same tombstone). Nothing is torn down for
81
+ * that: the other side's gate already refuses us, and every other revoked peer
82
+ * is still swept. Instead `onSelfRevoked` fires ONCE per entry into the set
83
+ * (re-armed if the party is re-admitted, so a second removal signals again),
84
+ * which `CadreNode` surfaces as `strand:revoked` so the embedding app decides
85
+ * what to do — this module never stops or leaves a strand on its own.
86
+ * Best-effort by nature: a removed party learns only if the tombstone
87
+ * replicated to it before the cut.
88
+ *
89
+ * ## When the deny set is refreshed
90
+ *
91
+ * Every refresh runs on one table change subscription (`table-change-watch.ts`),
92
+ * single-flight, so no two scheduled refreshes overlap:
93
+ *
94
+ * - **On a change** to `Strand.Member` or `Strand.MemberPeer`. App writes
95
+ * (`revokeMember`, `leaveStrand`) commit on the same Quereus `Database` the
96
+ * subscription is on, so a local removal is acted on within the coalescing
97
+ * window; a replicated one when this node's storage takes it in.
98
+ * - **Once at start**, when the strand's database is published.
99
+ * - **On a backstop** ({@link DEFAULT_REVOCATION_BACKSTOP_MS} after the last
100
+ * refresh settled), for a change that raised no event.
101
+ * - **After a failed refresh**, {@link REVOCATION_REFRESH_RETRY_MS} later. The
102
+ * first successful read also arms the plugin's bridge for replicated changes
103
+ * (the NOTE on `watchTables`), so until one succeeds only local commits wake it.
104
+ * - **After each successful refresh on a wide strand** — more distinct bound peer ids than
105
+ * the cluster size — {@link REVOCATION_WIDE_STRAND_REFRESH_MS} later, because
106
+ * this node may be outside a membership block's cohort and so hear no change.
107
+ *
108
+ * ## What transfers from the control gater (`membership-connection-gater.ts`)
109
+ *
110
+ * Transfers: the two-layer shape (fail-closed per-stream gate as PRIMARY, a
111
+ * connection-level layer on top), the synchronous in-memory
112
+ * snapshot judged by the stream gate (a live DB read inside a gate deadlocks —
113
+ * the same argument as the control node's `authorizeInboundControlStream`), the
114
+ * fail-open-on-error/timeout posture for the connection hooks
115
+ * (`decideWithinDeadline`, reused as-is), and the "compose over the caller's
116
+ * gater, every base hook preserved" mechanics.
117
+ *
118
+ * Does NOT transfer — provisional admission and the relay-reservation seam
119
+ * (`'admit-provisionally'`, its deadline, the unauthorized budget). That
120
+ * machinery exists because the control gate judges on ABSENCE of placement,
121
+ * where a member whose row is in flight, or a device whose invitation row has
122
+ * not arrived, is indistinguishable from an outsider, and a wrong reservation
123
+ * deny is unrecoverable. This gate denies on POSITIVE revocation evidence, so a
124
+ * deny is never that kind of wrong answer; the one stale-wrong case (a missed
125
+ * re-add) heals via replication as above. Every hook here is therefore a plain
126
+ * "deny iff revoked" — no budget, no provisional verdict, no deadline.
127
+ *
128
+ * Does NOT transfer — the bring-up quiet period. A strand node's DB bring-up
129
+ * NEEDS its cross-party cohort connections; this enforcer simply starts with an
130
+ * empty snapshot (admit everything) until its first successful read — the same
131
+ * fail-open posture as everywhere else here.
132
+ *
133
+ * Does NOT transfer — every stranger carve-out (enrollment window, formation
134
+ * window, delegate grants). None of those protocols exist on a strand node.
135
+ *
136
+ * Unlike the control stream gate, no empty-snapshot carve-out is needed: an
137
+ * empty deny set means "nothing revoked", which correctly admits everyone — the
138
+ * deny-list shape makes the cold-start case and the steady case the same code
139
+ * path.
140
+ */
141
+
142
+ import debug from 'debug';
143
+ import type { ConnectionGater, PeerId, MultiaddrConnection } from '@libp2p/interface';
144
+ import type { Database } from '@quereus/quereus';
145
+ import { decideWithinDeadline } from './membership-connection-gater.js';
146
+ import { ADMISSION_DECISION_TIMEOUT_MS } from './link-budget.js';
147
+ import { scheduleRuns, type TableChangeWatch, type TableChangeWatchOptions } from './table-change-watch.js';
148
+ import type { TimeoutScheduler } from './timeout-scheduler.js';
149
+
150
+ const log = debug('sereus:cadre:strand-revocation');
151
+
152
+ /**
153
+ * Default longest wait between two deny-set refreshes when no membership change
154
+ * is heard. Overridable via {@link StrandRevocationEnforcementConfig.backstopMs}.
155
+ *
156
+ * NOTE: the backstop covers two paths the change subscription does not: a
157
+ * machine that was offline when the removal was committed (it normally takes
158
+ * the blocks in by join backfill or read repair on reconnect, which raise the
159
+ * change too), and any change that reaches storage without an event. The case
160
+ * of a node outside a membership block's cohort is covered by
161
+ * {@link REVOCATION_WIDE_STRAND_REFRESH_MS}, not by this.
162
+ */
163
+ export const DEFAULT_REVOCATION_BACKSTOP_MS = 5 * 60_000;
164
+
165
+ /**
166
+ * How soon a failed refresh is retried. Also how soon a replicated removal is
167
+ * heard after a first read that failed, since that read is what arms the
168
+ * plugin's replicated-change bridge for the two tables.
169
+ */
170
+ export const REVOCATION_REFRESH_RETRY_MS = 30_000;
171
+
172
+ /**
173
+ * How soon a strand with more distinct bound peer ids than its cluster size is
174
+ * refreshed again after a successful refresh. On such a strand this node may be
175
+ * outside a membership block's cohort, so it takes in no storage event for a
176
+ * removal (`docs/cadre/control-convergence.md` → "Table change subscriptions").
177
+ */
178
+ export const REVOCATION_WIDE_STRAND_REFRESH_MS = 30_000;
179
+
180
+ /**
181
+ * Embedder tuning for the strand revoked-peer gate, threaded from
182
+ * `CadreNodeConfig.strandRevocationEnforcement` to
183
+ * `StartStrandConfig.revocationEnforcement` the way the backfill knob is.
184
+ */
185
+ export interface StrandRevocationEnforcementConfig {
186
+ /**
187
+ * Default true. False disarms the gate entirely for this node's strands —
188
+ * the pre-existing behaviour (a removed party's peers keep being served).
189
+ */
190
+ enabled?: boolean;
191
+ /** Longest wait between two refreshes with no change heard, ms. Default {@link DEFAULT_REVOCATION_BACKSTOP_MS}. */
192
+ backstopMs?: number;
193
+ /**
194
+ * Default true: the enforcer schedules its own refreshes — on a change to
195
+ * `Strand.Member` or `Strand.MemberPeer`, after a failed read or hang-up, and
196
+ * on a wide strand's follow-up. False schedules none of those, so refreshes
197
+ * run only at start, on the backstop, and on `refreshRevocationEnforcement`.
198
+ * For test scenarios that need a machine's cuts to be the ones the test drove;
199
+ * a production node leaves it on.
200
+ */
201
+ autoRefresh?: boolean;
202
+ }
203
+
204
+ /** One `Strand.MemberPeer` row, as the deny-set derivation consumes it. */
205
+ export interface StrandMemberPeerBinding {
206
+ memberKey: string;
207
+ peerId: string;
208
+ }
209
+
210
+ /** The membership rows one deny-set derivation reads. */
211
+ export interface StrandRevocationRows {
212
+ /** Every live `Strand.Member.Key`. */
213
+ memberKeys: ReadonlySet<string>;
214
+ /** Every `Strand.MemberPeer` row (live-membered and orphaned alike). */
215
+ bindings: readonly StrandMemberPeerBinding[];
216
+ }
217
+
218
+ /**
219
+ * The minimum of a libp2p node the teardown sweep needs: who WE are, what is
220
+ * open, and how to close it. Deliberately not the node itself, so the sweep
221
+ * unit-tests against a three-property stub; `Libp2p` (hence
222
+ * `Libp2pNodeWithRepo`) satisfies it structurally, which is what
223
+ * `StrandInstanceManager` passes.
224
+ */
225
+ export interface StrandRevocationNetwork {
226
+ /** This node's own peer id — how the enforcer recognizes ITSELF in the deny set. */
227
+ readonly peerId: PeerId;
228
+ /** Every open connection. Only `remotePeer` is read — and reused as the hangUp target. */
229
+ getConnections(): readonly { readonly remotePeer: PeerId }[];
230
+ /** Close every connection to `peer`: direct, relayed, and any reservation riding one. */
231
+ hangUp(peer: PeerId): Promise<void>;
232
+ }
233
+
234
+ export interface StrandRevocationEnforcerDeps {
235
+ /** Log tag naming which strand this enforcer serves (the strand id). */
236
+ label: string;
237
+ /**
238
+ * Read the membership rows the deny set is derived from. Injectable so the
239
+ * enforcer unit-tests without a strand database; production wires
240
+ * {@link readStrandRevocationRows} over the strand's live DB. A throw or
241
+ * rejection KEEPS the previous snapshot (never clears it) — the control
242
+ * model, `refreshAuthorizedControlPeers`.
243
+ */
244
+ readRows: () => Promise<StrandRevocationRows>;
245
+ /**
246
+ * Handle on the strand's libp2p node for the teardown sweep, read LAZILY on
247
+ * every sweep — never captured. It has to be: the enforcer is constructed
248
+ * BEFORE the node (the node's options embed the enforcer's predicates), and
249
+ * the node is dropped again on quiesce. Omit it, or return undefined, and the
250
+ * gate still refuses new connections — only teardown of OPEN ones is skipped.
251
+ */
252
+ getNetwork?: () => StrandRevocationNetwork | undefined;
253
+ /**
254
+ * Called ONCE each time this node's own peer id ENTERS the deny set — i.e.
255
+ * this node's party was removed from the strand, or left it. Not re-fired
256
+ * while it stays there; re-armed if the party is re-admitted, so a second
257
+ * removal signals again. Wired by `StrandInstanceManager` through to
258
+ * `CadreNode`'s `strand:revoked` event. A resume rebuilds the enforcer, so a
259
+ * still-revoked strand also legitimately re-fires once per resume. A throw is
260
+ * logged and swallowed — an embedder's handler must not derail the sweep.
261
+ */
262
+ onSelfRevoked?: () => void;
263
+ /**
264
+ * Called ONCE each time this node's own peer id LEAVES the deny set after
265
+ * {@link onSelfRevoked} reported it there — a manager re-admitted the party, or a
266
+ * sibling machine bound this node under the party's current key after a key rotation
267
+ * left its only binding orphaned (`strand-membership-reconciler.ts` → "Binding the
268
+ * party's other machines"). Not fired by a first refresh that finds this node clear.
269
+ * `StrandInstanceManager` wires it to the strand's membership reconciler, which stopped
270
+ * on the revocation and restarts here. A throw is logged and swallowed, as for
271
+ * {@link onSelfRevoked}.
272
+ */
273
+ onSelfRestored?: () => void;
274
+ /**
275
+ * Subscribe `onChange` to changes in `Strand.Member` and `Strand.MemberPeer`
276
+ * (`StrandDatabase.watchTables`). Absent, or throwing: refreshes come from
277
+ * start, the backstop, retries and wide-strand follow-ups only (unit tests).
278
+ */
279
+ watchChanges?(onChange: () => Promise<void>, options: TableChangeWatchOptions): TableChangeWatch;
280
+ /**
281
+ * The strand's cluster size. A snapshot with more distinct bound peer ids than
282
+ * this schedules {@link REVOCATION_WIDE_STRAND_REFRESH_MS}; absent, never.
283
+ */
284
+ cohortBreadth?: number;
285
+ /** Timer seam for the watch; omit for real (unref'd) timeouts. */
286
+ scheduler?: TimeoutScheduler;
287
+ }
288
+
289
+ /** Every `Strand.MemberPeer` binding — live-membered and orphaned alike. */
290
+ async function scanBindings(db: Database): Promise<StrandMemberPeerBinding[]> {
291
+ const bindings: StrandMemberPeerBinding[] = [];
292
+ for await (const row of db.eval('select MemberKey, PeerId from Strand.MemberPeer')) {
293
+ bindings.push({ memberKey: row.MemberKey as string, peerId: row.PeerId as string });
294
+ }
295
+ return bindings;
296
+ }
297
+
298
+ /** Every live `Strand.Member.Key`. */
299
+ async function scanMemberKeys(db: Database): Promise<Set<string>> {
300
+ const memberKeys = new Set<string>();
301
+ for await (const row of db.eval('select Key from Strand.Member')) {
302
+ memberKeys.add(row.Key as string);
303
+ }
304
+ return memberKeys;
305
+ }
306
+
307
+ /**
308
+ * Read the deny-set inputs from a strand database: full-scan
309
+ * `Strand.MemberPeer` and `Strand.Member`, to be joined in JavaScript by the
310
+ * enforcer. Scan-and-filter, never seek — the composite-PK point-lookup
311
+ * unreliability documented at `scanMemberPeers` in `strand-membership-writer.ts`
312
+ * applies, so correctness depends only on each scan returning a superset of the
313
+ * live rows.
314
+ *
315
+ * **Scan order is load-bearing, and it is BINDINGS FIRST.** The two scans are
316
+ * separate reads with nothing holding them to one snapshot, so a write that
317
+ * lands between them is seen by the second scan and not the first. A member
318
+ * joins as `Member` row then `MemberPeer` row (`MemberExists` forces that
319
+ * order; the module doc says why it holds on the network), so reading `Member`
320
+ * first would let a join that commits mid-read produce a binding whose member
321
+ * key is absent from the key set — a brand-new member classified as REVOKED,
322
+ * the one fail-CLOSED outcome this module exists to avoid. Reading bindings
323
+ * first inverts the skew: the new binding is simply not in the older bindings
324
+ * snapshot, so the joiner is unclassified and admitted, and a revocation that
325
+ * lands mid-read is still seen (the key is missing from the NEWER key scan).
326
+ * Every skew window then resolves fail-open, matching the module doc.
327
+ *
328
+ * NOTE: two whole-table scans per refresh (on each membership change and each
329
+ * backstop, per closed strand). Fine at strand scale (a handful of members and bindings); if
330
+ * membership churn ever makes these tables large, the fix is a reliable
331
+ * filtered read — which needs the networked point-lookup gap closed
332
+ * (`debt-composite-pk-point-lookup-unreliable-untracked`) — not a bigger scan.
333
+ */
334
+ export async function readStrandRevocationRows(db: Database): Promise<StrandRevocationRows> {
335
+ const bindings = await scanBindings(db);
336
+ const memberKeys = await scanMemberKeys(db);
337
+ return { memberKeys, bindings };
338
+ }
339
+
340
+ /**
341
+ * The per-strand revoked-peer deny set and the synchronous predicates over it.
342
+ *
343
+ * Lifecycle: created in `StrandInstanceManager.buildStrandRuntime` (closed
344
+ * strands only), started when `publishDatabase` hands the strand's database to
345
+ * the app, stopped and dropped in `releaseRuntime` — so quiesce → resume
346
+ * rebuilds it with a fresh snapshot. The snapshot starts EMPTY (admit
347
+ * everything) and repopulates on the first successful read; a revoked peer
348
+ * therefore gets a short admit window per resume at the connection level.
349
+ * Accepted: fail-open posture, and resume is never blocked on a refresh.
350
+ */
351
+ export class StrandRevocationEnforcer {
352
+ /** The materialized deny set — peer ids with an orphaned binding and no live one. */
353
+ private revokedPeerIds: ReadonlySet<string> = new Set();
354
+ private readonly backstopMs: number;
355
+ private readonly autoRefresh: boolean;
356
+ /** Tail of the refresh chain — what serializes refreshes (no two reads in flight). */
357
+ private refreshTail: Promise<void> = Promise.resolve();
358
+ /** Every scheduled refresh runs on it; present between {@link start} and {@link stop}. */
359
+ private watch: TableChangeWatch | undefined;
360
+ private started = false;
361
+ private stopped = false;
362
+ /** Latch for the one-shot self-revocation signal — see {@link StrandRevocationEnforcerDeps.onSelfRevoked}. */
363
+ private selfRevokedSignaled = false;
364
+
365
+ constructor(
366
+ private readonly deps: StrandRevocationEnforcerDeps,
367
+ config?: StrandRevocationEnforcementConfig
368
+ ) {
369
+ this.backstopMs = config?.backstopMs ?? DEFAULT_REVOCATION_BACKSTOP_MS;
370
+ this.autoRefresh = config?.autoRefresh ?? true;
371
+ }
372
+
373
+ /** Number of peers currently denied — test/diagnostic surface. */
374
+ get revokedCount(): number {
375
+ return this.revokedPeerIds.size;
376
+ }
377
+
378
+ /**
379
+ * Subscribe to membership changes and run one refresh at once (not awaited —
380
+ * bring-up never blocks on it); the module doc's "When the deny set is
381
+ * refreshed" has the full schedule. Call once the strand's database is
382
+ * published. A second call, or one after {@link stop}, is a no-op.
383
+ */
384
+ start(): void {
385
+ if (this.started || this.stopped) return;
386
+ this.started = true;
387
+ this.watch = this.subscribe();
388
+ this.watch.trigger(0);
389
+ log('[%s] revocation enforcer started (backstop %dms)', this.deps.label, this.backstopMs);
390
+ }
391
+
392
+ /** Stop scheduling refreshes; a read already in flight completes but its result is discarded. */
393
+ stop(): void {
394
+ if (this.stopped) return;
395
+ this.stopped = true;
396
+ this.watch?.dispose();
397
+ this.watch = undefined;
398
+ log('[%s] revocation enforcer stopped', this.deps.label);
399
+ }
400
+
401
+ /**
402
+ * Refresh the deny set now. Never rejects. Serialized: concurrent calls chain,
403
+ * so no two reads overlap, and each explicit call gets a read that STARTS
404
+ * after the call (an on-demand refresh after a revocation commit observes that
405
+ * commit). A failed or slow read keeps the previous snapshot — never clears it.
406
+ */
407
+ refresh(): Promise<void> {
408
+ const run = this.refreshTail.then(() => this.doRefresh());
409
+ this.refreshTail = run;
410
+ return run;
411
+ }
412
+
413
+ /**
414
+ * Is `remotePeerId` positively revoked in the current snapshot? Synchronous by
415
+ * design — this is judged inside libp2p gates where an await against the DB
416
+ * would deadlock (the control stream gate's argument).
417
+ */
418
+ isRevoked(remotePeerId: string): boolean {
419
+ return this.revokedPeerIds.has(remotePeerId);
420
+ }
421
+
422
+ /**
423
+ * The fail-closed PRIMARY layer: the per-stream predicate wired as
424
+ * `createLibp2pNode({ authorizeInboundStream })`, gating all four
425
+ * `/optimystic/strand-<id>/{repo,cluster,sync,block-transfer}` protocols.
426
+ * Also what catches a revoked peer arriving over a RELAYED connection, or
427
+ * over a connection admitted before the revocation replicated here.
428
+ */
429
+ authorizeStream(remotePeerId: string, _protocol: string): boolean {
430
+ return !this.isRevoked(remotePeerId);
431
+ }
432
+
433
+ /**
434
+ * The watch every scheduled refresh runs on: the deps' change subscription, or
435
+ * a timer-only one when changes are not watched or the subscription throws.
436
+ *
437
+ * NOTE: a refresh can wake itself once. Its read may start a read-repair sync
438
+ * (a held block read more than Optimystic's `readRepairWindowMs`, 10 s, after
439
+ * its last check), and that sync's landing raises a change. The follow-up
440
+ * refresh runs within the coalescing window plus one read — well inside the
441
+ * read-repair window — so it starts no second sync and the chain stops there.
442
+ * If idle sync counts on a strand do not fall with this subscription, suspect
443
+ * this loop first.
444
+ */
445
+ private subscribe(): TableChangeWatch {
446
+ const onChange = (): Promise<void> => this.refresh();
447
+ const options: TableChangeWatchOptions = {
448
+ label: `strand-revocation:${this.deps.label}`,
449
+ backstopMs: this.backstopMs,
450
+ scheduler: this.deps.scheduler,
451
+ };
452
+ if (this.autoRefresh && this.deps.watchChanges) {
453
+ try {
454
+ return this.deps.watchChanges(onChange, options);
455
+ } catch (error) {
456
+ log('[%s] membership change subscription failed — refreshing on the backstop and retries only: %o', this.deps.label, error);
457
+ }
458
+ }
459
+ return scheduleRuns(onChange, options);
460
+ }
461
+
462
+ /**
463
+ * One serialized snapshot rebuild; contains every failure (contract: never rejects).
464
+ *
465
+ * NOTE: nothing here carries a deadline — a `readRows` or a `hangUp` that never
466
+ * settles wedges the refresh chain, which freezes the deny set (the watch runs
467
+ * one refresh at a time, and every later `refresh()` chains behind the stuck one).
468
+ * Both are bounded in practice (Quereus reads settle; libp2p's connection close
469
+ * has its own timeout). If a strand is ever seen with a stale deny set and no
470
+ * refresh log line, wrap both awaits in a timeout rather than hunting further.
471
+ */
472
+ private async doRefresh(): Promise<void> {
473
+ if (this.stopped) return;
474
+ try {
475
+ const rows = await this.deps.readRows();
476
+ if (this.stopped) return;
477
+ this.revokedPeerIds = deriveRevokedPeerIds(rows);
478
+ log('[%s] deny set refreshed: %d revoked peer(s)', this.deps.label, this.revokedPeerIds.size);
479
+ this.followUpWideStrand(rows);
480
+ // Awaited inside the refresh, so an on-demand refresh() resolves only once
481
+ // the cut has been made — that is what makes "revoke, then refresh" an
482
+ // immediate teardown for the caller rather than a scheduled one.
483
+ await this.tearDownRevoked(this.revokedPeerIds);
484
+ } catch (error) {
485
+ log('[%s] deny-set refresh failed — keeping previous snapshot: %o', this.deps.label, error);
486
+ this.scheduleFollowUp(REVOCATION_REFRESH_RETRY_MS, 'refresh failed');
487
+ }
488
+ }
489
+
490
+ /** Arm one more refresh `delayMs` from now, unless {@link StrandRevocationEnforcementConfig.autoRefresh} is off or the enforcer is not running. */
491
+ private scheduleFollowUp(delayMs: number, reason: string): void {
492
+ if (!this.autoRefresh || !this.watch) return;
493
+ log('[%s] %s — refreshing again in %dms', this.deps.label, reason, delayMs);
494
+ this.watch.trigger(delayMs);
495
+ }
496
+
497
+ /** Schedule {@link REVOCATION_WIDE_STRAND_REFRESH_MS} when `rows` bind more distinct peers than the cluster holds. */
498
+ private followUpWideStrand(rows: StrandRevocationRows): void {
499
+ const breadth = this.deps.cohortBreadth;
500
+ if (breadth === undefined) return;
501
+ const boundPeers = new Set(rows.bindings.map((binding) => binding.peerId)).size;
502
+ if (boundPeers > breadth) {
503
+ this.scheduleFollowUp(REVOCATION_WIDE_STRAND_REFRESH_MS, `${boundPeers} bound peers on a cluster of ${breadth}`);
504
+ }
505
+ }
506
+
507
+ /**
508
+ * Close what is already OPEN to the peers of `revoked` — the teardown half of
509
+ * enforcement (module doc: "Removal cuts LIVE sessions too"). Never rejects:
510
+ * every failure is contained, so the refresh chain survives, and a failed
511
+ * `hangUp` schedules a retry.
512
+ *
513
+ * `revoked` is passed IN rather than read off the field, so the sweep judges
514
+ * the exact snapshot its own refresh produced; likewise the connection list is
515
+ * enumerated once, before any await, so a peer re-admitted mid-sweep is at
516
+ * worst hung up once and reconnects.
517
+ *
518
+ * NOTE: dropping the revoked peer from the strand's Optimystic cohort needs no
519
+ * separate action — machines quiesce strands routinely and the remaining cohort
520
+ * keeps committing, so an unreachable cohort peer is already tolerated, and
521
+ * `denyDialPeer` makes the exclusion fast (a local refusal, not a dial timeout).
522
+ * Two residual facts, both accepted: the removed node keeps every block it had
523
+ * already replicated (revocation is forward-looking), and a block whose only
524
+ * holders were the removed party's machines can be unavailable to the rest
525
+ * until repair.
526
+ *
527
+ * NOTE: post-removal commit latency is real and MEASURED, not hypothetical. On
528
+ * the two-parties-by-two-machines fixture in
529
+ * `integration-tests/src/scenarios/strand-removal-cuts-network.integration.ts`
530
+ * the remaining cohort's FIRST write after a cut fails repeatedly with
531
+ * `BlockUnavailableError: … (peers-unreachable)` before it commits — three or
532
+ * four failures, 3.5-4.3 s, over four runs — because the cohort still listed
533
+ * the removed party's now unreachable machines and had to downsize to the
534
+ * live holders first. It
535
+ * recovers on its own, so this is a latency cost, not a defect, and it is
536
+ * stated for app authors in `docs/strands/membership.md` → Removing members. If it ever
537
+ * stops recovering — a write that never commits, or `cluster-fetch:no-quorum` —
538
+ * that is an upstream (Optimystic) conversation, not a workaround here.
539
+ */
540
+ private async tearDownRevoked(revoked: ReadonlySet<string>): Promise<void> {
541
+ if (this.stopped) {
542
+ return;
543
+ }
544
+ const network = this.resolveNetwork();
545
+ if (!network) {
546
+ return;
547
+ }
548
+ const selfPeerId = network.peerId.toString();
549
+ // Judged on EVERY pass, including the empty-set one: leaving the set is what
550
+ // re-arms the signal (see trackSelfRevoked). Being revoked ourselves tears
551
+ // nothing down on our own behalf — the other side's gate already refuses us —
552
+ // so the sweep below still runs for every OTHER revoked peer in the pass.
553
+ this.trackSelfRevoked(revoked.has(selfPeerId));
554
+ if (revoked.size === 0) {
555
+ return;
556
+ }
557
+ for (const peer of connectedRevokedPeers(network, revoked, selfPeerId, this.deps.label)) {
558
+ await this.hangUpRevoked(network, peer);
559
+ }
560
+ }
561
+
562
+ /** The lazily-read network handle; an accessor that throws costs this pass only. */
563
+ private resolveNetwork(): StrandRevocationNetwork | undefined {
564
+ try {
565
+ return this.deps.getNetwork?.();
566
+ } catch (error) {
567
+ log('[%s] network handle unavailable — teardown skipped this pass: %o', this.deps.label, error);
568
+ return undefined;
569
+ }
570
+ }
571
+
572
+ /** One hangUp, contained: a stopping node or an already-closed connection is not an error here. */
573
+ private async hangUpRevoked(network: StrandRevocationNetwork, peer: PeerId): Promise<void> {
574
+ try {
575
+ await network.hangUp(peer);
576
+ log('[%s] hung up revoked peer %s', this.deps.label, peer.toString());
577
+ } catch (error) {
578
+ log('[%s] hangUp of revoked peer %s failed: %o', this.deps.label, peer.toString(), error);
579
+ this.scheduleFollowUp(REVOCATION_REFRESH_RETRY_MS, 'hangUp failed');
580
+ }
581
+ }
582
+
583
+ /**
584
+ * Latch {@link StrandRevocationEnforcerDeps.onSelfRevoked} to the TRANSITION
585
+ * into the revoked state: fired once on entry, and re-armed the moment this
586
+ * node is out of the set again — a manager can re-admit a party it removed
587
+ * (a fresh `Member` row makes the orphaned bindings live again), and a second
588
+ * removal has to be reported like the first. Leaving the set after a report is
589
+ * the other edge, {@link StrandRevocationEnforcerDeps.onSelfRestored}.
590
+ */
591
+ private trackSelfRevoked(selfRevoked: boolean): void {
592
+ if (selfRevoked === this.selfRevokedSignaled) {
593
+ return;
594
+ }
595
+ this.selfRevokedSignaled = selfRevoked;
596
+ if (selfRevoked) {
597
+ log('[%s] THIS node is revoked from the strand (removed or left) — signalling', this.deps.label);
598
+ this.signalSelf(this.deps.onSelfRevoked, 'onSelfRevoked');
599
+ } else {
600
+ log('[%s] THIS node is no longer revoked from the strand — signalling', this.deps.label);
601
+ this.signalSelf(this.deps.onSelfRestored, 'onSelfRestored');
602
+ }
603
+ }
604
+
605
+ /** Fire one of the self-state handlers; a throw is logged and must not derail the sweep. */
606
+ private signalSelf(handler: (() => void) | undefined, name: string): void {
607
+ try {
608
+ handler?.();
609
+ } catch (error) {
610
+ log('[%s] %s handler threw: %o', this.deps.label, name, error);
611
+ }
612
+ }
613
+ }
614
+
615
+ /**
616
+ * The distinct peer ids of `network`'s open connections that are in `revoked`,
617
+ * as the `PeerId` objects `hangUp` takes — reusing each connection's own
618
+ * `remotePeer` rather than parsing the string back, so no peer-id codec is
619
+ * needed here. Self is excluded (a node holds no connection to itself, and
620
+ * hanging one up would be nonsense if it did), and a peer connected twice — say
621
+ * one direct and one relayed — yields ONE hangUp, which closes both. A throw
622
+ * mid-enumeration is logged and keeps whatever was collected before it: a
623
+ * partial sweep beats none, and the next refresh re-enumerates anyway.
624
+ */
625
+ function connectedRevokedPeers(
626
+ network: StrandRevocationNetwork,
627
+ revoked: ReadonlySet<string>,
628
+ selfPeerId: string,
629
+ label: string
630
+ ): PeerId[] {
631
+ const targets = new Map<string, PeerId>();
632
+ try {
633
+ for (const connection of network.getConnections()) {
634
+ const remotePeerId = connection.remotePeer.toString();
635
+ if (remotePeerId !== selfPeerId && revoked.has(remotePeerId)) {
636
+ targets.set(remotePeerId, connection.remotePeer);
637
+ }
638
+ }
639
+ } catch (error) {
640
+ log('[%s] connection enumeration failed — teardown skipped this pass: %o', label, error);
641
+ }
642
+ return [...targets.values()];
643
+ }
644
+
645
+ /**
646
+ * Derive the deny set: a peer id is revoked iff it has at least one ORPHANED
647
+ * binding (a `MemberPeer` row whose member key has no live `Member` row) AND no
648
+ * live-membered binding. The second conjunct is what lets a peer id bound to
649
+ * TWO member keys — revoked under one, live under the other — keep serving the
650
+ * live member: a machine serving a live member must not be cut. Per-binding,
651
+ * not per-member, so every machine of a multi-device removed party lands in
652
+ * the set.
653
+ */
654
+ function deriveRevokedPeerIds(rows: StrandRevocationRows): Set<string> {
655
+ const orphaned = new Set<string>();
656
+ const live = new Set<string>();
657
+ for (const binding of rows.bindings) {
658
+ (rows.memberKeys.has(binding.memberKey) ? live : orphaned).add(binding.peerId);
659
+ }
660
+ for (const peerId of live) {
661
+ orphaned.delete(peerId);
662
+ }
663
+ return orphaned;
664
+ }
665
+
666
+ /** The one capability the gater composition needs from the enforcer. */
667
+ export type StrandRevocationJudge = Pick<StrandRevocationEnforcer, 'isRevoked'>;
668
+
669
+ /**
670
+ * Build a closed strand's connection gater: the caller-supplied gater (if any)
671
+ * with revoked-peer denial composed onto three hooks. The opportunistic
672
+ * SECONDARY layer — the per-stream gate above is the fail-closed primary.
673
+ *
674
+ * - `denyInboundEncryptedConnection`: deny iff revoked, so a removed party's
675
+ * node is refused before any protocol negotiation.
676
+ * - `denyDialPeer`: deny iff revoked — the owner ruling covers "communicated
677
+ * with", not just "answered to", and refusing the dial locally is instant,
678
+ * which keeps Optimystic from wasting a dial timeout on a peer this node
679
+ * will not talk to anyway.
680
+ * - `denyInboundRelayReservation`: deny iff revoked — matters when the strand
681
+ * node runs the relay server (the default on a `'server'` node), where admitting
682
+ * the reservation would let a removed party keep using this node's
683
+ * forwarding capacity.
684
+ *
685
+ * Composition semantics: every hook of `base` is preserved as-is; on the three
686
+ * composed hooks a deny from EITHER the base gater or the revocation check
687
+ * denies, and an error (or a decision slower than `decisionTimeoutMs`) in
688
+ * either is fail-open — the base error admits through to the revocation check,
689
+ * a revocation-check error admits outright, and the fail-closed stream gate
690
+ * still stands behind both. The deadline is belt-and-braces: the snapshot read
691
+ * is synchronous.
692
+ *
693
+ * NOTE: accepted tradeoff — swallowing a BASE hook's throw diverges from
694
+ * `createMembershipConnectionGater`, which lets it propagate to libp2p (a
695
+ * fail-closed outcome there). Uniform fail-open was chosen for this module so
696
+ * every hook has one failure direction, and it was the shape the plan specified;
697
+ * the cost is that an embedder gater which throws is silently admitted here
698
+ * while the same gater passed raw to an OPEN strand would refuse. Loud in the
699
+ * log either way. Revisit if an embedder ever ships a gater whose throw is a
700
+ * meaningful deny, or if the two gaters are unified.
701
+ *
702
+ * NOTE: `base` is spread, so a gater passed as a CLASS INSTANCE would lose its
703
+ * prototype methods — same caveat as `createMembershipConnectionGater`; every
704
+ * caller in this repo supplies a plain object (the RN/web permissive gaters,
705
+ * e.g. `{ denyDialMultiaddr: () => false }`, keep working unchanged).
706
+ */
707
+ export function createRevocationConnectionGater(
708
+ enforcer: StrandRevocationJudge,
709
+ base?: ConnectionGater,
710
+ decisionTimeoutMs: number = ADMISSION_DECISION_TIMEOUT_MS
711
+ ): ConnectionGater {
712
+ /** The base gater's verdict, fail-open: an error or absence is "not denied". */
713
+ const baseDenies = async (decide: () => Promise<boolean> | boolean | undefined, hook: string): Promise<boolean> => {
714
+ try {
715
+ return await decide() === true;
716
+ } catch (error) {
717
+ log('base gater %s threw — treating as not-denied (fail-open): %o', hook, error);
718
+ return false;
719
+ }
720
+ };
721
+ /** The revocation verdict, bounded and fail-open. */
722
+ const revokedDenies = async (peerId: PeerId, hook: string): Promise<boolean> => {
723
+ const remotePeerId = peerId.toString();
724
+ try {
725
+ const revoked = await decideWithinDeadline(
726
+ () => enforcer.isRevoked(remotePeerId), false, decisionTimeoutMs, `${hook}(${remotePeerId})`
727
+ );
728
+ if (revoked) {
729
+ log('%s: %s is revoked — denying', hook, remotePeerId);
730
+ }
731
+ return revoked;
732
+ } catch (error) {
733
+ log('%s revocation check threw for %s — admitting (fail-open; stream gate decides): %o', hook, remotePeerId, error);
734
+ return false;
735
+ }
736
+ };
737
+ return {
738
+ ...base,
739
+ denyDialPeer: async (peerId: PeerId): Promise<boolean> => {
740
+ if (await baseDenies(() => base?.denyDialPeer?.(peerId), 'denyDialPeer')) {
741
+ return true;
742
+ }
743
+ return revokedDenies(peerId, 'denyDialPeer');
744
+ },
745
+ denyInboundEncryptedConnection: async (peerId: PeerId, maConn: MultiaddrConnection): Promise<boolean> => {
746
+ if (await baseDenies(() => base?.denyInboundEncryptedConnection?.(peerId, maConn), 'denyInboundEncryptedConnection')) {
747
+ return true;
748
+ }
749
+ return revokedDenies(peerId, 'denyInboundEncryptedConnection');
750
+ },
751
+ denyInboundRelayReservation: async (peerId: PeerId): Promise<boolean> => {
752
+ if (await baseDenies(() => base?.denyInboundRelayReservation?.(peerId), 'denyInboundRelayReservation')) {
753
+ return true;
754
+ }
755
+ return revokedDenies(peerId, 'denyInboundRelayReservation');
756
+ }
757
+ };
758
+ }