@serfab/cadre-core 1.13.0 → 1.15.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 (230) hide show
  1. package/README.md +293 -274
  2. package/dist/cadre-invite-protocol.d.ts +383 -0
  3. package/dist/cadre-invite-protocol.js +774 -0
  4. package/dist/cadre-invite-protocol.js.map +1 -0
  5. package/dist/cadre-join-request.d.ts +42 -0
  6. package/dist/cadre-join-request.js +144 -0
  7. package/dist/cadre-join-request.js.map +1 -0
  8. package/dist/cadre-node.d.ts +849 -210
  9. package/dist/cadre-node.js +1574 -374
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/claim-proof.d.ts +45 -0
  12. package/dist/claim-proof.js +132 -0
  13. package/dist/claim-proof.js.map +1 -0
  14. package/dist/control-authorization.d.ts +80 -19
  15. package/dist/control-authorization.js +55 -13
  16. package/dist/control-authorization.js.map +1 -1
  17. package/dist/control-cohort.js +1 -1
  18. package/dist/control-cohort.js.map +1 -1
  19. package/dist/control-database.d.ts +605 -108
  20. package/dist/control-database.js +1299 -280
  21. package/dist/control-database.js.map +1 -1
  22. package/dist/control-protocol-guard.d.ts +142 -0
  23. package/dist/control-protocol-guard.js +293 -0
  24. package/dist/control-protocol-guard.js.map +1 -0
  25. package/dist/control-schema.d.ts +1 -1
  26. package/dist/control-schema.js +817 -1067
  27. package/dist/control-schema.js.map +1 -1
  28. package/dist/control-stream.d.ts +4 -0
  29. package/dist/control-stream.js +22 -7
  30. package/dist/control-stream.js.map +1 -1
  31. package/dist/delegate-admission.d.ts +1 -1
  32. package/dist/delegate-admission.js +1 -1
  33. package/dist/device-token.d.ts +11 -9
  34. package/dist/device-token.js +14 -12
  35. package/dist/device-token.js.map +1 -1
  36. package/dist/ed25519-key.d.ts +22 -9
  37. package/dist/ed25519-key.js +47 -10
  38. package/dist/ed25519-key.js.map +1 -1
  39. package/dist/fetch-impl.d.ts +12 -0
  40. package/dist/fetch-impl.js +23 -0
  41. package/dist/fetch-impl.js.map +1 -0
  42. package/dist/file-durable-slot.js +2 -1
  43. package/dist/file-durable-slot.js.map +1 -1
  44. package/dist/file-safe-name.d.ts +25 -0
  45. package/dist/file-safe-name.js +29 -0
  46. package/dist/file-safe-name.js.map +1 -0
  47. package/dist/formation-approval.js +5 -11
  48. package/dist/formation-approval.js.map +1 -1
  49. package/dist/fs-atomic.d.ts +0 -19
  50. package/dist/fs-atomic.js +3 -24
  51. package/dist/fs-atomic.js.map +1 -1
  52. package/dist/index.d.ts +22 -10
  53. package/dist/index.js +54 -11
  54. package/dist/index.js.map +1 -1
  55. package/dist/invitation-bootstrap.d.ts +50 -12
  56. package/dist/invitation-bootstrap.js +76 -13
  57. package/dist/invitation-bootstrap.js.map +1 -1
  58. package/dist/joined-strand-store.d.ts +7 -0
  59. package/dist/joined-strand-store.js +9 -0
  60. package/dist/joined-strand-store.js.map +1 -1
  61. package/dist/key-store-file.js +2 -1
  62. package/dist/key-store-file.js.map +1 -1
  63. package/dist/link-budget.d.ts +25 -33
  64. package/dist/link-budget.js +25 -35
  65. package/dist/link-budget.js.map +1 -1
  66. package/dist/machine-removal.d.ts +78 -0
  67. package/dist/machine-removal.js +166 -0
  68. package/dist/machine-removal.js.map +1 -0
  69. package/dist/membership-connection-gater.d.ts +191 -151
  70. package/dist/membership-connection-gater.js +236 -173
  71. package/dist/membership-connection-gater.js.map +1 -1
  72. package/dist/node-claim-payload.d.ts +74 -0
  73. package/dist/node-claim-payload.js +224 -0
  74. package/dist/node-claim-payload.js.map +1 -0
  75. package/dist/node-default-transports.d.ts +27 -0
  76. package/dist/node-default-transports.js +35 -0
  77. package/dist/node-default-transports.js.map +1 -0
  78. package/dist/node-transports.d.ts +30 -0
  79. package/dist/node-transports.js +40 -0
  80. package/dist/node-transports.js.map +1 -0
  81. package/dist/owner-anchor-sync.d.ts +22 -0
  82. package/dist/owner-anchor-sync.js +143 -0
  83. package/dist/owner-anchor-sync.js.map +1 -0
  84. package/dist/peer-authorization.d.ts +113 -18
  85. package/dist/peer-authorization.js +225 -29
  86. package/dist/peer-authorization.js.map +1 -1
  87. package/dist/peer-dial.d.ts +143 -27
  88. package/dist/peer-dial.js +276 -31
  89. package/dist/peer-dial.js.map +1 -1
  90. package/dist/peer-join-backfill.d.ts +26 -2
  91. package/dist/peer-join-backfill.js +60 -12
  92. package/dist/peer-join-backfill.js.map +1 -1
  93. package/dist/peer-record.d.ts +17 -52
  94. package/dist/peer-record.js +20 -58
  95. package/dist/peer-record.js.map +1 -1
  96. package/dist/pending-join-runner.d.ts +66 -58
  97. package/dist/pending-join-runner.js +136 -145
  98. package/dist/pending-join-runner.js.map +1 -1
  99. package/dist/primary-lan-address.d.ts +8 -0
  100. package/dist/primary-lan-address.js +46 -0
  101. package/dist/primary-lan-address.js.map +1 -0
  102. package/dist/provider/client.d.ts +131 -0
  103. package/dist/provider/client.js +226 -0
  104. package/dist/provider/client.js.map +1 -0
  105. package/dist/provider/descriptor.d.ts +41 -0
  106. package/dist/provider/descriptor.js +103 -0
  107. package/dist/provider/descriptor.js.map +1 -0
  108. package/dist/provider/index.d.ts +9 -0
  109. package/dist/provider/index.js +10 -0
  110. package/dist/provider/index.js.map +1 -0
  111. package/dist/provider/oauth.d.ts +125 -0
  112. package/dist/provider/oauth.js +199 -0
  113. package/dist/provider/oauth.js.map +1 -0
  114. package/dist/provider/rent-node.d.ts +101 -0
  115. package/dist/provider/rent-node.js +220 -0
  116. package/dist/provider/rent-node.js.map +1 -0
  117. package/dist/push-fanout.d.ts +8 -2
  118. package/dist/push-fanout.js +8 -2
  119. package/dist/push-fanout.js.map +1 -1
  120. package/dist/relay-addrs.d.ts +9 -4
  121. package/dist/relay-addrs.js +9 -4
  122. package/dist/relay-addrs.js.map +1 -1
  123. package/dist/relay-reservation.d.ts +51 -16
  124. package/dist/relay-reservation.js +107 -24
  125. package/dist/relay-reservation.js.map +1 -1
  126. package/dist/seed-bootstrap.d.ts +165 -123
  127. package/dist/seed-bootstrap.js +313 -275
  128. package/dist/seed-bootstrap.js.map +1 -1
  129. package/dist/seed-trust-policy.d.ts +98 -37
  130. package/dist/seed-trust-policy.js +188 -2
  131. package/dist/seed-trust-policy.js.map +1 -1
  132. package/dist/strand-addr-protocol.d.ts +24 -26
  133. package/dist/strand-addr-protocol.js +19 -26
  134. package/dist/strand-addr-protocol.js.map +1 -1
  135. package/dist/strand-commit-durability.d.ts +54 -0
  136. package/dist/strand-commit-durability.js +74 -0
  137. package/dist/strand-commit-durability.js.map +1 -0
  138. package/dist/strand-database.d.ts +23 -8
  139. package/dist/strand-database.js +41 -13
  140. package/dist/strand-database.js.map +1 -1
  141. package/dist/strand-first-sync-gate.d.ts +7 -1
  142. package/dist/strand-first-sync-gate.js +7 -1
  143. package/dist/strand-first-sync-gate.js.map +1 -1
  144. package/dist/strand-formation-protocol.js +5 -2
  145. package/dist/strand-formation-protocol.js.map +1 -1
  146. package/dist/strand-fret-addrs.d.ts +19 -1
  147. package/dist/strand-fret-addrs.js +27 -9
  148. package/dist/strand-fret-addrs.js.map +1 -1
  149. package/dist/strand-instance-manager.d.ts +81 -19
  150. package/dist/strand-instance-manager.js +216 -105
  151. package/dist/strand-instance-manager.js.map +1 -1
  152. package/dist/strand-move.d.ts +124 -0
  153. package/dist/strand-move.js +438 -0
  154. package/dist/strand-move.js.map +1 -0
  155. package/dist/strand-network-config.js +7 -6
  156. package/dist/strand-network-config.js.map +1 -1
  157. package/dist/strand-peer-redial.d.ts +113 -0
  158. package/dist/strand-peer-redial.js +236 -0
  159. package/dist/strand-peer-redial.js.map +1 -0
  160. package/dist/strand-revocation-enforcer.d.ts +11 -11
  161. package/dist/strand-revocation-enforcer.js +11 -11
  162. package/dist/strand-wake-protocol.d.ts +13 -16
  163. package/dist/strand-wake-protocol.js +23 -27
  164. package/dist/strand-wake-protocol.js.map +1 -1
  165. package/dist/trusted-owner-store.d.ts +35 -5
  166. package/dist/trusted-owner-store.js +50 -8
  167. package/dist/trusted-owner-store.js.map +1 -1
  168. package/dist/types.d.ts +512 -89
  169. package/dist/types.js +10 -0
  170. package/dist/types.js.map +1 -1
  171. package/package.json +19 -10
  172. package/src/cadre-invite-protocol.ts +1052 -0
  173. package/src/cadre-join-request.ts +167 -0
  174. package/src/cadre-node.ts +1703 -386
  175. package/src/claim-proof.ts +147 -0
  176. package/src/control-authorization.ts +203 -117
  177. package/src/control-cohort.ts +1 -1
  178. package/src/control-database.ts +4663 -3453
  179. package/src/control-protocol-guard.ts +348 -0
  180. package/src/control-schema.ts +828 -1078
  181. package/src/control-stream.ts +26 -7
  182. package/src/delegate-admission.ts +1 -1
  183. package/src/device-token.ts +14 -10
  184. package/src/ed25519-key.ts +47 -10
  185. package/src/fetch-impl.ts +23 -0
  186. package/src/file-durable-slot.ts +64 -63
  187. package/src/file-safe-name.ts +32 -0
  188. package/src/formation-approval.ts +604 -610
  189. package/src/fs-atomic.ts +92 -117
  190. package/src/index.ts +789 -648
  191. package/src/invitation-bootstrap.ts +91 -13
  192. package/src/joined-strand-store.ts +508 -498
  193. package/src/key-store-file.ts +142 -141
  194. package/src/link-budget.ts +25 -36
  195. package/src/machine-removal.ts +216 -0
  196. package/src/membership-connection-gater.ts +259 -191
  197. package/src/node-claim-payload.ts +259 -0
  198. package/src/node-default-transports.ts +38 -0
  199. package/src/node-transports.ts +49 -0
  200. package/src/owner-anchor-sync.ts +171 -0
  201. package/src/peer-authorization.ts +258 -29
  202. package/src/peer-dial.ts +604 -315
  203. package/src/peer-join-backfill.ts +62 -11
  204. package/src/peer-record.ts +159 -197
  205. package/src/pending-join-runner.ts +729 -735
  206. package/src/primary-lan-address.ts +47 -0
  207. package/src/provider/client.ts +326 -0
  208. package/src/provider/descriptor.ts +129 -0
  209. package/src/provider/index.ts +59 -0
  210. package/src/provider/oauth.ts +285 -0
  211. package/src/provider/rent-node.ts +275 -0
  212. package/src/push-fanout.ts +8 -2
  213. package/src/relay-addrs.ts +9 -4
  214. package/src/relay-reservation.ts +1211 -1121
  215. package/src/seed-bootstrap.ts +1502 -1448
  216. package/src/seed-trust-policy.ts +353 -140
  217. package/src/strand-addr-protocol.ts +26 -35
  218. package/src/strand-commit-durability.ts +116 -0
  219. package/src/strand-database.ts +46 -14
  220. package/src/strand-first-sync-gate.ts +7 -1
  221. package/src/strand-formation-protocol.ts +1039 -1036
  222. package/src/strand-fret-addrs.ts +179 -145
  223. package/src/strand-instance-manager.ts +2026 -1883
  224. package/src/strand-move.ts +585 -0
  225. package/src/strand-network-config.ts +7 -6
  226. package/src/strand-peer-redial.ts +307 -0
  227. package/src/strand-revocation-enforcer.ts +11 -11
  228. package/src/strand-wake-protocol.ts +23 -30
  229. package/src/trusted-owner-store.ts +242 -171
  230. package/src/types.ts +2687 -2242
@@ -0,0 +1,307 @@
1
+ /**
2
+ * A running strand node redialing the strand's other members itself, when it holds a
3
+ * connection to none of them, with the dial budget the host's declared link gives a
4
+ * relayed connection.
5
+ *
6
+ * Why. Below cadre-core the only thing that redials a strand peer is FRET's maintenance:
7
+ * its pings and neighbour announcements open the connection themselves (`dial: true`) under
8
+ * a fixed 2 000 ms limit on the whole call (`MAINTENANCE_RPC_TIMEOUT_MS` in `p2p-fret`'s
9
+ * `fret-service.ts`). Opening a relayed connection takes longer than that on a slow link:
10
+ * about 9 s on a 20 ms per-frame cap with a 70%-busy event loop
11
+ * (`joiner-first-commit-over-slow-relay`, whose slow-restart arm reproduces this), where
12
+ * {@link relayedDialBudgetMs} allows 21.5 s at the default declaration. Each such redial is
13
+ * cut off part-way through the handshake, from both sides, for as long as the link stays that
14
+ * slow. And after a restart nothing else dials a strand peer: a cross-party strand's launch
15
+ * seed is empty, and cadre-core's address passes only fill the address book. Two phones that
16
+ * restarted then never reconnect, and a write either made alone never reaches the other.
17
+ *
18
+ * What it does. One loop per strand runtime, started in `StrandInstanceManager`'s runtime
19
+ * build and stopped with the runtime (stop, quiesce, failed build), so a hibernating strand
20
+ * never dials. Each look at the node:
21
+ * - a member connected: nothing to do; look again in {@link STRAND_REDIAL_CHECK_MS}, or as
22
+ * soon as a peer disconnects.
23
+ * - no member connected and none known: likewise nothing (a founder alone, a storage replica
24
+ * before anyone arrives).
25
+ * - no member connected and some known: dial every known member at once
26
+ * ({@link dialPeerAddrs}, direct addresses before relayed ones), each address with the
27
+ * relayed-dial budget. A round that connects to one goes back to watching; one that does
28
+ * not waits a backoff starting at that budget and doubling to
29
+ * {@link STRAND_REDIAL_MAX_BACKOFF_MS}.
30
+ *
31
+ * Who is known: every peer the node's FRET table holds a verified signed address record for
32
+ * (`strand-fret-addrs.ts`), plus the launch seed (sibling strand addresses and a formation's
33
+ * carried addresses). Who counts as connected: a peer FRET labels `'member'` (it has seen it
34
+ * speak this strand's protocols), or a seed peer. Neither ever includes a configured relay, a
35
+ * peer FRET labels `'foreign'`, or a peer the revocation gate refuses. The relay matters most:
36
+ * the strand node is connected to it throughout and FRET files it with a record like any
37
+ * peer, so counting it would leave this loop idle exactly when it is needed.
38
+ *
39
+ * NOTE: this compensates for FRET's 2 000 ms maintenance dial limit, which cannot open a
40
+ * relayed connection on a slow link (upstream half:
41
+ * `blocked/fret-maintenance-ping-dial-budget-below-a-relayed-dial`). If FRET's maintenance
42
+ * dial ever takes a limit derived from the declared link, this loop becomes a backstop and
43
+ * may be deleted, as `peer-join-backfill.ts` says of itself.
44
+ */
45
+
46
+ import debug from 'debug';
47
+ import type { Multiaddr } from '@multiformats/multiaddr';
48
+ import { relayedDialBudgetMs } from './link-budget.js';
49
+ import { CONTROL_COHORT_DIAL_ADDRESS_ATTEMPTS, SelfRelayOnlyError, dialPeerAddrs, type AddrDialer, type PeerDialBudget } from './peer-dial.js';
50
+ import { groupAddrsByPeerId } from './peer-addr-book.js';
51
+ import { strandFretMembership, strandFretPeerAddrs, type FretAddrHost, type FretMembership } from './strand-fret-addrs.js';
52
+ import { defaultTimeoutScheduler, type TimeoutScheduler } from './timeout-scheduler.js';
53
+
54
+ const log = debug('sereus:cadre:strand-redial');
55
+
56
+ /**
57
+ * Gap between looks while a member is connected or none is known. While a member is
58
+ * connected a look reads FRET's labels and the connection list and checks no signature
59
+ * ({@link strandFretMembership}); a disconnect also triggers a look at once.
60
+ */
61
+ export const STRAND_REDIAL_CHECK_MS = 5_000;
62
+
63
+ /**
64
+ * Ceiling on the wait between failed rounds. A member that is gone for good is dialed this
65
+ * often for as long as FRET keeps its record (up to 14 days after it was last confirmed).
66
+ */
67
+ export const STRAND_REDIAL_MAX_BACKOFF_MS = 5 * 60_000;
68
+
69
+ /** The loop's dial budget and cadence. */
70
+ export interface StrandRedialTimings {
71
+ /** Limit on one address's dial, and on one member's addresses together. */
72
+ budget: PeerDialBudget;
73
+ /** Wait after the first failed round; doubled after each further one. */
74
+ minBackoffMs: number;
75
+ /** Ceiling the backoff doubles up to. */
76
+ maxBackoffMs: number;
77
+ /** Gap between looks while nothing needs dialing. */
78
+ checkMs: number;
79
+ }
80
+
81
+ /**
82
+ * The timings at a declared link round trip: {@link relayedDialBudgetMs} per address, the
83
+ * same whole-budget count per member as the control cohort's dials (dead direct addresses
84
+ * a record lists ahead of the relayed one that works), and a first backoff of one per-address
85
+ * budget.
86
+ */
87
+ export function strandRedialTimings(linkRoundTripMs?: number): StrandRedialTimings {
88
+ const perAddressMs = relayedDialBudgetMs(linkRoundTripMs);
89
+ return {
90
+ budget: { perAddressMs, totalMs: CONTROL_COHORT_DIAL_ADDRESS_ATTEMPTS * perAddressMs },
91
+ minBackoffMs: perAddressMs,
92
+ maxBackoffMs: STRAND_REDIAL_MAX_BACKOFF_MS,
93
+ checkMs: STRAND_REDIAL_CHECK_MS
94
+ };
95
+ }
96
+
97
+ /** The slice of a strand's libp2p node the loop uses. Structurally satisfied by db-p2p's node. */
98
+ export interface RedialNode extends AddrDialer {
99
+ services?: FretAddrHost['services'];
100
+ getConnections(): ReadonlyArray<{ remotePeer: { toString(): string } }>;
101
+ addEventListener(type: 'peer:disconnect', listener: () => void): void;
102
+ removeEventListener(type: 'peer:disconnect', listener: () => void): void;
103
+ }
104
+
105
+ export interface StrandRedialDeps {
106
+ /** Names the strand in logs. */
107
+ label: string;
108
+ node: RedialNode;
109
+ /**
110
+ * The launch seed: multiaddr strings, each naming its peer in a trailing `/p2p/`.
111
+ *
112
+ * NOTE: read once, at runtime build. Addresses a re-formation carries while the strand runs
113
+ * reach the peerStore (`recordFormationStrandAddrs`) but not this loop until the runtime is
114
+ * rebuilt; if a re-formed strand is seen not reconnecting until relaunch, read the seed per round.
115
+ */
116
+ seed: readonly string[];
117
+ /** Peer ids never dialed nor counted as members: the relays the node reserves on. */
118
+ excluded: ReadonlySet<string>;
119
+ /** The revocation gate's current verdict, asked of peers and of this node itself; absent for an open strand. */
120
+ isRevoked?: (peerId: string) => boolean;
121
+ /** Omit for real (unref'd) timers. */
122
+ scheduler?: TimeoutScheduler;
123
+ }
124
+
125
+ /** A running redial loop; its only imperative is {@link stop}. */
126
+ export interface StrandPeerRedial {
127
+ /** Idempotent. No look or round starts after it; dials in flight run out on their own deadlines, and their result is discarded. */
128
+ stop(): void;
129
+ }
130
+
131
+ /** How a look ended: nothing needed dialing or a round connected (`'watch'`), or a round reached no member (`'retry'`). */
132
+ type LookOutcome = 'watch' | 'retry';
133
+
134
+ /** Start the loop; its first look runs at once. */
135
+ export function superviseStrandPeerRedial(deps: StrandRedialDeps, timings: StrandRedialTimings): StrandPeerRedial {
136
+ return new StrandPeerRedialLoop(deps, timings);
137
+ }
138
+
139
+ class StrandPeerRedialLoop implements StrandPeerRedial {
140
+ private readonly scheduler: TimeoutScheduler;
141
+ private readonly seed: Map<string, Multiaddr[]>;
142
+ private readonly selfId: string;
143
+ private backoffMs: number;
144
+ private timer: unknown = null;
145
+ /**
146
+ * Whether the pending wait is a plain gap between looks, which a disconnect cuts short. A
147
+ * backoff after a failed round is not cut short, or a flapping relay connection would turn
148
+ * the backoff into a dial on every flap; and while a look or round runs there is no wait.
149
+ */
150
+ private watching = false;
151
+ private stopped = false;
152
+ private readonly onDisconnect = (): void => {
153
+ if (this.watching && !this.stopped) {
154
+ this.cancelTimer();
155
+ void this.tick();
156
+ }
157
+ };
158
+
159
+ constructor(private readonly deps: StrandRedialDeps, private readonly timings: StrandRedialTimings) {
160
+ this.scheduler = deps.scheduler ?? defaultTimeoutScheduler;
161
+ this.seed = groupAddrsByPeerId([...deps.seed]);
162
+ this.selfId = deps.node.peerId.toString();
163
+ this.backoffMs = timings.minBackoffMs;
164
+ deps.node.addEventListener('peer:disconnect', this.onDisconnect);
165
+ void this.tick();
166
+ }
167
+
168
+ stop(): void {
169
+ if (this.stopped) {
170
+ return;
171
+ }
172
+ this.stopped = true;
173
+ this.cancelTimer();
174
+ this.deps.node.removeEventListener('peer:disconnect', this.onDisconnect);
175
+ }
176
+
177
+ private async tick(): Promise<void> {
178
+ if (this.stopped) {
179
+ return;
180
+ }
181
+ this.watching = false;
182
+ let outcome: LookOutcome = 'watch';
183
+ try {
184
+ outcome = await this.lookAndDial();
185
+ } catch (error) {
186
+ // A node torn down under the look throws from its table export or connection list.
187
+ log('strand %s: redial look failed (looking again in %dms): %o', this.deps.label, this.timings.checkMs, error);
188
+ }
189
+ if (this.stopped) {
190
+ return;
191
+ }
192
+ this.watching = outcome === 'watch';
193
+ const waitMs = outcome === 'watch' ? this.resetBackoff() : this.nextBackoff();
194
+ this.timer = this.scheduler.setTimeout(() => {
195
+ this.timer = null;
196
+ void this.tick();
197
+ }, waitMs);
198
+ }
199
+
200
+ /**
201
+ * One look, and a round of dials when it finds no member connected but some known. A node
202
+ * whose own party was removed dials nobody: the strand keeps running for the session, but a
203
+ * removed party must not keep dialing the strand's peers (`CadreNode.forgetRevokedJoin`).
204
+ */
205
+ private async lookAndDial(): Promise<LookOutcome> {
206
+ if (this.deps.isRevoked?.(this.selfId) === true) {
207
+ return 'watch';
208
+ }
209
+ const membership = strandFretMembership(this.deps.node);
210
+ if (this.memberConnected(membership)) {
211
+ return 'watch';
212
+ }
213
+ const known = await this.knownMembers(membership);
214
+ if (known.size === 0 || this.stopped) {
215
+ return 'watch';
216
+ }
217
+ log('strand %s: no member connected; dialing %d known member(s)', this.deps.label, known.size);
218
+ if (await this.dialAny(known)) {
219
+ log('strand %s: reconnected to a member', this.deps.label);
220
+ return 'watch';
221
+ }
222
+ log('strand %s: no known member answered; next round in %dms', this.deps.label, this.backoffMs);
223
+ return 'retry';
224
+ }
225
+
226
+ /** The gap between looks, with the backoff started over. */
227
+ private resetBackoff(): number {
228
+ this.backoffMs = this.timings.minBackoffMs;
229
+ return this.timings.checkMs;
230
+ }
231
+
232
+ /**
233
+ * The wait after a round that reached no member, doubling the next one up to the cap.
234
+ *
235
+ * NOTE: a round whose dials failed within milliseconds (a relay connection that is still
236
+ * closing, the member's relay reservation not back yet) waits as long as one whose dials ran
237
+ * out their budget. In `joiner-first-commit-over-slow-relay`'s third arm that first wait is what
238
+ * leaves the joiner writable with no member connected. If reconnecting within seconds of a cut
239
+ * ever matters, retry a round that failed that fast after a short delay instead.
240
+ *
241
+ * NOTE: one such fast failure is `ConnectionClosedError: The connection muxer is "closed"`. A
242
+ * relay that aborts its connection to this node cannot tell it so (`@libp2p/websockets`'
243
+ * listener resets with close code 1006, which the `ws` package refuses to send;
244
+ * `blocked/report-libp2p-websockets-buffered-amount`, second arm), so this node keeps a dead
245
+ * relay connection until its own monitor drops it, up to 65 s, and every relayed dial reuses
246
+ * it. If rounds keep failing that way, close a relay connection whose muxer is closed before
247
+ * the next round instead of waiting it out.
248
+ */
249
+ private nextBackoff(): number {
250
+ const waitMs = this.backoffMs;
251
+ this.backoffMs = Math.min(waitMs * 2, this.timings.maxBackoffMs);
252
+ return waitMs;
253
+ }
254
+
255
+ private eligible(peerId: string): boolean {
256
+ return peerId !== this.selfId && !this.deps.excluded.has(peerId) && this.deps.isRevoked?.(peerId) !== true;
257
+ }
258
+
259
+ /** Whether an open connection reaches a peer FRET has seen speak this strand's protocols, or a seed peer. */
260
+ private memberConnected(membership: ReadonlyMap<string, FretMembership>): boolean {
261
+ return this.deps.node.getConnections().some((connection) => {
262
+ const peerId = connection.remotePeer.toString();
263
+ return this.eligible(peerId) && (membership.get(peerId) === 'member' || this.seed.has(peerId));
264
+ });
265
+ }
266
+
267
+ /** The members to dial, each with its candidate addresses: verified FRET records first, then the seed's. */
268
+ private async knownMembers(membership: ReadonlyMap<string, FretMembership>): Promise<Map<string, Multiaddr[]>> {
269
+ const { peers } = await strandFretPeerAddrs(this.deps.node);
270
+ const known = new Map<string, Multiaddr[]>();
271
+ for (const [peerId, addrs] of [...peers, ...this.seed]) {
272
+ if (!this.eligible(peerId) || membership.get(peerId) === 'foreign') {
273
+ continue;
274
+ }
275
+ known.set(peerId, unionAddrs(known.get(peerId) ?? [], addrs));
276
+ }
277
+ return known;
278
+ }
279
+
280
+ /** Dial every member in `known` at once; resolves to whether any connected. */
281
+ private async dialAny(known: ReadonlyMap<string, Multiaddr[]>): Promise<boolean> {
282
+ const members = [...known];
283
+ const outcomes = await Promise.allSettled(members.map(([peerId, addrs]) =>
284
+ dialPeerAddrs(this.deps.node, peerId, addrs, this.timings.budget, `strand ${this.deps.label} redial of ${peerId}`)
285
+ ));
286
+ outcomes.forEach((outcome, i) => {
287
+ if (outcome.status === 'rejected') {
288
+ const reason = outcome.reason instanceof SelfRelayOnlyError ? 'reachable only by relaying through this node' : outcome.reason;
289
+ log('strand %s: redial of %s failed: %o', this.deps.label, members[i][0], reason);
290
+ }
291
+ });
292
+ return outcomes.some((outcome) => outcome.status === 'fulfilled');
293
+ }
294
+
295
+ private cancelTimer(): void {
296
+ if (this.timer !== null) {
297
+ this.scheduler.clearTimeout(this.timer);
298
+ this.timer = null;
299
+ }
300
+ }
301
+ }
302
+
303
+ /** `primary` then the entries of `extra` it lacks, compared as strings. */
304
+ function unionAddrs(primary: readonly Multiaddr[], extra: readonly Multiaddr[]): Multiaddr[] {
305
+ const seen = new Set(primary.map((addr) => addr.toString()));
306
+ return [...primary, ...extra.filter((addr) => !seen.has(addr.toString()))];
307
+ }
@@ -83,23 +83,23 @@
83
83
  *
84
84
  * ## What transfers from the control gater (`membership-connection-gater.ts`)
85
85
  *
86
- * Transfers: the two-layer shape (fail-closed per-stream gate as PRIMARY, an
87
- * opportunistic connection-level deny on top), the synchronous in-memory
86
+ * Transfers: the two-layer shape (fail-closed per-stream gate as PRIMARY, a
87
+ * connection-level layer on top), the synchronous in-memory
88
88
  * snapshot judged by the stream gate (a live DB read inside a gate deadlocks —
89
89
  * the same argument as the control node's `authorizeInboundControlStream`), the
90
90
  * fail-open-on-error/timeout posture for the connection hooks
91
91
  * (`decideWithinDeadline`, reused as-is), and the "compose over the caller's
92
92
  * gater, every base hook preserved" mechanics.
93
93
  *
94
- * Does NOT transfer — the relay-reservation seam (`'admit-for-relay'` + the
95
- * unauthorized budget). That machinery exists because the control gate denies on
96
- * ABSENCE of placement, where a member whose row is in flight is
97
- * indistinguishable from an outsider and a wrong reservation deny is
98
- * unrecoverable. This gate denies on POSITIVE revocation evidence, so a
99
- * reservation deny is never that kind of wrong answer; the one stale-wrong case
100
- * (a missed re-add) heals via replication as above. `denyInboundRelayReservation`
101
- * here is therefore a plain "deny iff revoked" — no budget, no admit-for-relay
102
- * verdict, no reserve deadline.
94
+ * Does NOT transfer — provisional admission and the relay-reservation seam
95
+ * (`'admit-provisionally'`, its deadline, the unauthorized budget). That
96
+ * machinery exists because the control gate judges on ABSENCE of placement,
97
+ * where a member whose row is in flight, or a device whose invitation row has
98
+ * not arrived, is indistinguishable from an outsider, and a wrong reservation
99
+ * deny is unrecoverable. This gate denies on POSITIVE revocation evidence, so a
100
+ * deny is never that kind of wrong answer; the one stale-wrong case (a missed
101
+ * re-add) heals via replication as above. Every hook here is therefore a plain
102
+ * "deny iff revoked" — no budget, no provisional verdict, no deadline.
103
103
  *
104
104
  * Does NOT transfer — the bring-up quiet period. A strand node's DB bring-up
105
105
  * NEEDS its cross-party cohort connections; this enforcer simply starts with an
@@ -16,13 +16,12 @@
16
16
  *
17
17
  * **Authorization (v1):** a wake is low-risk — it only causes the receiver to
18
18
  * spend resources coming online for a strand it already participates in — so the
19
- * receiver carries no per-request signature and instead defers entirely to the
20
- * injected `isMember` predicate. `CadreNode` injects its AUTHORIZED-membership
21
- * predicate there (`isAuthorizedMember`: the sender's `CadrePeer` row must carry
22
- * a voucher that verifies against an owner key in the receiver's node-local
23
- * trusted-owner anchor), so a peer that merely published rows into the replicated
24
- * control DB is refused. This module stays agnostic: it enforces whatever
25
- * predicate it is given.
19
+ * request carries no signature. Membership is checked before this handler runs, by
20
+ * the control node's protocol guard (`control-protocol-guard.ts`, the `members`
21
+ * class: `CadreNode.isAuthorizedMember`, under which the sender's `CadrePeer` row
22
+ * must carry a voucher that verifies against an owner key in the receiver's
23
+ * node-local trusted-owner anchor), so a peer that merely published rows into the
24
+ * replicated control DB gets its stream reset and never reaches this module.
26
25
  */
27
26
 
28
27
  import debug from 'debug';
@@ -31,7 +30,7 @@ import type { Multiaddr } from '@multiformats/multiaddr';
31
30
  import type { StrandInstance, WakeRequest, WakeAck } from './types.js';
32
31
  import { decodeLengthPrefixedFrame } from './seed-bootstrap.js';
33
32
  import { type ControlStream, exchangeFrame, readStreamToEnd, replyAndClose } from './control-stream.js';
34
- import { tryAddrsInTurn } from './peer-dial.js';
33
+ import { dialAddr, tryAddrsInTurn } from './peer-dial.js';
35
34
  import { relayedRequestBudgetMs } from './link-budget.js';
36
35
 
37
36
  const log = debug('sereus:cadre:strand-wake');
@@ -55,8 +54,8 @@ const MAX_WAKE_SIZE = 64 * 1024;
55
54
  * It holds only link work because the receiver acks as soon as it has DECIDED, before the
56
55
  * wake itself runs ({@link StrandWakeService.processWakeRequest}).
57
56
  *
58
- * NOTE: the receiver's membership check (two live control reads) runs inside this deadline and
59
- * is not counted. In steady state those reads touch only held blocks and do not consult the
57
+ * NOTE: the receiver's membership check (two live control reads, in its protocol guard) runs
58
+ * inside this deadline and is not counted. In steady state those reads touch only held blocks and do not consult the
60
59
  * cohort. If a wake or address request is seen timing out while the receiver's membership read
61
60
  * is consulting, count one membership decision in this deadline or answer the check from the
62
61
  * materialized authorized-peer snapshot. See docs/cadre-consistency.md → "Deadlines Over
@@ -122,8 +121,6 @@ async function readFrame<T>(stream: ControlStream, timeoutMs: number): Promise<T
122
121
  * (`CadreNode`), injected so the service is testable without a full node.
123
122
  */
124
123
  export interface StrandWakeServiceOptions {
125
- /** Membership gate: is the remote peer a `CadrePeer` member of this cadre? */
126
- isMember(remotePeerId: string): Promise<boolean>;
127
124
  /** Look up a local strand instance by id (undefined if not participated in). */
128
125
  getStrand(strandId: string): StrandInstance | undefined;
129
126
  /**
@@ -157,9 +154,10 @@ export interface StrandWakeServiceOptions {
157
154
 
158
155
  /**
159
156
  * Receiver side of the push-wake protocol. Registers a `WAKE_PROTOCOL` handler
160
- * on the control node and, for each inbound {@link WakeRequest}, gates on cadre
161
- * membership, replies with a {@link WakeAck}, and starts resuming the named
162
- * strand if it is hibernating/idle and we participate in it.
157
+ * on the control node and, for each inbound {@link WakeRequest} (from a peer the
158
+ * protocol guard has already admitted as an authorized member), replies with a
159
+ * {@link WakeAck} and starts resuming the named strand if it is hibernating/idle
160
+ * and we participate in it.
163
161
  */
164
162
  export class StrandWakeService {
165
163
  private readonly options: StrandWakeServiceOptions;
@@ -249,8 +247,7 @@ export class StrandWakeService {
249
247
  * Decide the wake for a decoded request and start it. Exposed (not private) so
250
248
  * the decision matrix can be unit-tested directly.
251
249
  *
252
- * - Non-member sender → rejected (`accepted: false`).
253
- * - Unknown / not-participated strand → rejected.
250
+ * - Unknown / not-participated strand → rejected (`accepted: false`).
254
251
  * - Hibernating or idle strand → `accepted` with that status, and a wake started.
255
252
  * - Already-live strand → no-op, `accepted` with current status.
256
253
  *
@@ -260,13 +257,6 @@ export class StrandWakeService {
260
257
  * sender's attempt deadline, coupling that deadline to this node's own budgets.
261
258
  */
262
259
  async processWakeRequest(request: WakeRequest, remotePeerId: string): Promise<WakeAck> {
263
- // The injected membership predicate is the whole v1 authorization (CadreNode
264
- // supplies the voucher-anchored one); only a peer it admits may ask us to wake.
265
- if (!(await this.options.isMember(remotePeerId))) {
266
- log('Rejecting wake from non-member %s', remotePeerId);
267
- return { accepted: false, reason: 'Sender is not a cadre member' };
268
- }
269
-
270
260
  const instance = this.options.getStrand(request.strandId);
271
261
  if (!instance) {
272
262
  log('Rejecting wake for unknown/unparticipated strand %s', request.strandId);
@@ -366,12 +356,14 @@ export async function dialWake(
366
356
  }
367
357
 
368
358
  /**
369
- * Open one stream, send the request, half-close, and read the ack.
359
+ * Dial one address, open one stream, send the request, half-close, and read the ack.
360
+ *
361
+ * The address is dialed outside libp2p's dial queue (`dialAddr`), so another dial of
362
+ * the target in flight cannot capture this attempt; an open connection is still reused.
370
363
  *
371
- * `signal` is the per-attempt deadline from {@link dialWake}: it goes to
372
- * `dialProtocol` so a timeout during connect aborts the dial, and into
373
- * {@link exchangeFrame} so a timeout after the stream is open resets it —
374
- * releasing the otherwise unbounded ack-read.
364
+ * `signal` is the per-attempt deadline from {@link dialWake}: it goes to the dial so a
365
+ * timeout during connect aborts it, and into {@link exchangeFrame} so a timeout after
366
+ * the stream is open resets it — releasing the otherwise unbounded ack-read.
375
367
  */
376
368
  async function sendWake(
377
369
  node: Libp2p,
@@ -381,12 +373,13 @@ async function sendWake(
381
373
  timeoutMs: number,
382
374
  signal: AbortSignal,
383
375
  ): Promise<WakeAck> {
376
+ const connection = await dialAddr(node, addr, signal, 'Wake dial');
384
377
  // `runOnLimitedConnection: true`: the target may be reachable only over a
385
378
  // circuit-relay connection (the signaling-first addr), which libp2p marks
386
379
  // "limited". The wake exchange is a single tiny request→ack well within the
387
380
  // relay's data/duration cap, so opening it on the limited connection is safe
388
381
  // and is the whole point of dialing the relay address.
389
- const rawStream = await node.dialProtocol(addr, protocolId, { runOnLimitedConnection: true, signal });
382
+ const rawStream = await connection.newStream(protocolId, { runOnLimitedConnection: true, signal });
390
383
 
391
384
  const ack = await exchangeFrame(
392
385
  rawStream as unknown as ControlStream,