@serfab/cadre-core 1.23.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 (313) 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 +145 -44
  8. package/dist/cadre-node.js +239 -79
  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 +2 -2
  82. package/dist/node-claim-payload.d.ts +15 -7
  83. package/dist/node-claim-payload.js +25 -9
  84. package/dist/node-claim-payload.js.map +1 -1
  85. package/dist/node-class.d.ts +36 -0
  86. package/dist/node-class.js +26 -0
  87. package/dist/node-class.js.map +1 -0
  88. package/dist/node-default-transports.d.ts +50 -3
  89. package/dist/node-default-transports.js +48 -3
  90. package/dist/node-default-transports.js.map +1 -1
  91. package/dist/node-roles.d.ts +118 -0
  92. package/dist/node-roles.js +142 -0
  93. package/dist/node-roles.js.map +1 -0
  94. package/dist/node-transports.d.ts +6 -2
  95. package/dist/node-transports.js +39 -7
  96. package/dist/node-transports.js.map +1 -1
  97. package/dist/owner-anchor-sync.js +1 -1
  98. package/dist/owner-key-export.js +1 -1
  99. package/dist/owner-key-flows.d.ts +1 -1
  100. package/dist/owner-key-store.js +1 -1
  101. package/dist/owner-signer.js +1 -1
  102. package/dist/peer-authorization.d.ts +3 -1
  103. package/dist/peer-authorization.js +3 -1
  104. package/dist/peer-authorization.js.map +1 -1
  105. package/dist/peer-dial.d.ts +74 -10
  106. package/dist/peer-dial.js +89 -17
  107. package/dist/peer-dial.js.map +1 -1
  108. package/dist/peer-join-backfill.js +4 -4
  109. package/dist/peer-join-backfill.js.map +1 -1
  110. package/dist/peer-record.d.ts +34 -9
  111. package/dist/peer-record.js +66 -13
  112. package/dist/peer-record.js.map +1 -1
  113. package/dist/pending-join-runner.d.ts +1 -1
  114. package/dist/pending-join-runner.js +1 -1
  115. package/dist/provider/client.d.ts +6 -5
  116. package/dist/provider/client.js +3 -3
  117. package/dist/provider/client.js.map +1 -1
  118. package/dist/provider/descriptor.d.ts +1 -1
  119. package/dist/provider/descriptor.js +1 -1
  120. package/dist/provider/oauth.d.ts +1 -1
  121. package/dist/provider/oauth.js +1 -1
  122. package/dist/provider/rent-node.d.ts +4 -3
  123. package/dist/provider/rent-node.js +3 -3
  124. package/dist/provider/rent-node.js.map +1 -1
  125. package/dist/relay-addrs.d.ts +62 -7
  126. package/dist/relay-addrs.js +74 -11
  127. package/dist/relay-addrs.js.map +1 -1
  128. package/dist/relay-reservation.d.ts +1 -1
  129. package/dist/relay-reservation.js +1 -1
  130. package/dist/relay-server.d.ts +6 -5
  131. package/dist/relay-server.js +5 -5
  132. package/dist/relay-server.js.map +1 -1
  133. package/dist/schema-verification.d.ts +13 -10
  134. package/dist/schema-verification.js +32 -24
  135. package/dist/schema-verification.js.map +1 -1
  136. package/dist/sealed-party-key.js +1 -1
  137. package/dist/seed-bootstrap.d.ts +4 -3
  138. package/dist/seed-bootstrap.js +6 -7
  139. package/dist/seed-bootstrap.js.map +1 -1
  140. package/dist/strand-addr-protocol.d.ts +8 -6
  141. package/dist/strand-addr-protocol.js +12 -10
  142. package/dist/strand-addr-protocol.js.map +1 -1
  143. package/dist/strand-app-schema-report.d.ts +16 -2
  144. package/dist/strand-app-schema-report.js +15 -0
  145. package/dist/strand-app-schema-report.js.map +1 -1
  146. package/dist/strand-cohort.d.ts +1 -4
  147. package/dist/strand-cohort.js.map +1 -1
  148. package/dist/strand-commit-durability.d.ts +1 -1
  149. package/dist/strand-database.d.ts +13 -6
  150. package/dist/strand-database.js +17 -9
  151. package/dist/strand-database.js.map +1 -1
  152. package/dist/strand-first-sync-gate.d.ts +3 -2
  153. package/dist/strand-first-sync-gate.js +3 -2
  154. package/dist/strand-first-sync-gate.js.map +1 -1
  155. package/dist/strand-formation-deadlines.d.ts +2 -2
  156. package/dist/strand-formation-deadlines.js +2 -2
  157. package/dist/strand-formation-protocol.d.ts +1 -1
  158. package/dist/strand-formation-protocol.js +51 -16
  159. package/dist/strand-formation-protocol.js.map +1 -1
  160. package/dist/strand-instance-manager.d.ts +67 -33
  161. package/dist/strand-instance-manager.js +164 -55
  162. package/dist/strand-instance-manager.js.map +1 -1
  163. package/dist/strand-membership-reconciler.d.ts +8 -3
  164. package/dist/strand-membership-reconciler.js +8 -3
  165. package/dist/strand-membership-reconciler.js.map +1 -1
  166. package/dist/strand-membership-writer.d.ts +2 -2
  167. package/dist/strand-membership-writer.js +41 -39
  168. package/dist/strand-membership-writer.js.map +1 -1
  169. package/dist/strand-move.js +1 -1
  170. package/dist/strand-network-config.d.ts +15 -5
  171. package/dist/strand-network-config.js +7 -6
  172. package/dist/strand-network-config.js.map +1 -1
  173. package/dist/strand-party-key-rotation.d.ts +7 -3
  174. package/dist/strand-party-key-rotation.js +7 -3
  175. package/dist/strand-party-key-rotation.js.map +1 -1
  176. package/dist/strand-party-machines.d.ts +19 -8
  177. package/dist/strand-party-machines.js +26 -11
  178. package/dist/strand-party-machines.js.map +1 -1
  179. package/dist/strand-party-peers.d.ts +36 -14
  180. package/dist/strand-party-peers.js +24 -15
  181. package/dist/strand-party-peers.js.map +1 -1
  182. package/dist/strand-peer-redial.d.ts +1 -1
  183. package/dist/strand-peer-redial.js +1 -1
  184. package/dist/strand-reactivity.d.ts +20 -17
  185. package/dist/strand-reactivity.js +31 -18
  186. package/dist/strand-reactivity.js.map +1 -1
  187. package/dist/strand-revocation-enforcer.d.ts +3 -3
  188. package/dist/strand-revocation-enforcer.js +3 -3
  189. package/dist/strand-wake-protocol.d.ts +19 -7
  190. package/dist/strand-wake-protocol.js +22 -10
  191. package/dist/strand-wake-protocol.js.map +1 -1
  192. package/dist/strand-watcher.d.ts +1 -1
  193. package/dist/strand-watcher.js +1 -1
  194. package/dist/table-change-watch.js +1 -1
  195. package/dist/types.d.ts +116 -55
  196. package/dist/types.js.map +1 -1
  197. package/dist/webrtc-upgrade.d.ts +254 -0
  198. package/dist/webrtc-upgrade.js +355 -0
  199. package/dist/webrtc-upgrade.js.map +1 -0
  200. package/package.json +9 -9
  201. package/src/announce-addrs.ts +93 -93
  202. package/src/arachnode-stub.ts +18 -10
  203. package/src/bootstrap-peer-store-file.ts +44 -44
  204. package/src/bootstrap-peer-store.ts +214 -214
  205. package/src/cadre-invite-protocol.ts +741 -740
  206. package/src/cadre-node.ts +12462 -12280
  207. package/src/claim-proof.ts +147 -147
  208. package/src/control-authorization.ts +290 -276
  209. package/src/control-cohort.ts +223 -204
  210. package/src/control-database.ts +72 -28
  211. package/src/control-formation-recorder.ts +359 -359
  212. package/src/control-protocol-guard.ts +370 -366
  213. package/src/control-read-retry.ts +222 -180
  214. package/src/control-retry.ts +36 -4
  215. package/src/control-schema-version.ts +301 -301
  216. package/src/control-schema.ts +1108 -1087
  217. package/src/control-write-retry.ts +639 -669
  218. package/src/delegate-admission.ts +351 -351
  219. package/src/describe-thrown.ts +60 -60
  220. package/src/ed25519-key.ts +185 -185
  221. package/src/edge-node/config.ts +13 -10
  222. package/src/edge-node/dissolve.ts +252 -252
  223. package/src/edge-node/edge-join.ts +320 -320
  224. package/src/edge-node/edge-node.ts +1095 -1095
  225. package/src/edge-node/index.ts +60 -59
  226. package/src/edge-node/join-credential.ts +16 -16
  227. package/src/edge-node/lazy-raw-storage.ts +194 -178
  228. package/src/edge-node/listen-addrs.ts +26 -0
  229. package/src/edge-node/node-local.ts +84 -84
  230. package/src/edge-node/options.ts +195 -195
  231. package/src/edge-node/owner-grant.ts +63 -63
  232. package/src/edge-node/platform.ts +5 -4
  233. package/src/edge-node/strand-move.ts +266 -266
  234. package/src/edge-node/strands.ts +27 -12
  235. package/src/enrolled-machine-store-file.ts +43 -43
  236. package/src/enrolled-machine-store.ts +280 -280
  237. package/src/fetch-impl.ts +23 -23
  238. package/src/file-durable-slot.ts +64 -64
  239. package/src/file-safe-name.ts +32 -32
  240. package/src/formation-approval.ts +604 -604
  241. package/src/formation-token.ts +63 -63
  242. package/src/fs-atomic.ts +92 -92
  243. package/src/index.ts +987 -957
  244. package/src/invitation-bootstrap.ts +152 -118
  245. package/src/joined-strand-store.ts +553 -553
  246. package/src/key-store-file.ts +142 -142
  247. package/src/link-budget.ts +61 -5
  248. package/src/machine-removal.ts +211 -210
  249. package/src/member-redemption.ts +643 -643
  250. package/src/membership-connection-gater.ts +650 -650
  251. package/src/membership-view.ts +147 -147
  252. package/src/node-claim-payload.ts +34 -12
  253. package/src/node-class.ts +47 -0
  254. package/src/node-default-transports.ts +65 -3
  255. package/src/node-roles.ts +220 -0
  256. package/src/node-transports.ts +86 -49
  257. package/src/owner-anchor-sync.ts +172 -172
  258. package/src/owner-grant-protocol.ts +547 -547
  259. package/src/owner-key-export.ts +348 -348
  260. package/src/owner-key-flows.ts +109 -109
  261. package/src/owner-key-store.ts +1 -1
  262. package/src/owner-keys.ts +179 -179
  263. package/src/owner-signer.ts +92 -92
  264. package/src/peer-addr-book.ts +252 -252
  265. package/src/peer-authorization.ts +584 -582
  266. package/src/peer-dial.ts +698 -605
  267. package/src/peer-join-backfill.ts +961 -961
  268. package/src/peer-record.ts +71 -16
  269. package/src/pending-join-runner.ts +798 -798
  270. package/src/primary-lan-address.ts +47 -47
  271. package/src/provider/client.ts +327 -326
  272. package/src/provider/descriptor.ts +129 -129
  273. package/src/provider/index.ts +59 -59
  274. package/src/provider/oauth.ts +285 -285
  275. package/src/provider/rent-node.ts +276 -275
  276. package/src/relay-addrs.ts +90 -12
  277. package/src/relay-reservation.ts +1 -1
  278. package/src/relay-server.ts +99 -98
  279. package/src/schema-verification.ts +38 -23
  280. package/src/sealed-party-key.ts +190 -190
  281. package/src/seed-bootstrap.ts +8 -11
  282. package/src/seed-trust-policy.ts +353 -353
  283. package/src/self-address-update.ts +19 -19
  284. package/src/strand-addr-protocol.ts +17 -14
  285. package/src/strand-app-schema-report.ts +147 -122
  286. package/src/strand-cohort.ts +1 -5
  287. package/src/strand-commit-durability.ts +165 -165
  288. package/src/strand-database.ts +522 -510
  289. package/src/strand-first-sync-gate.ts +3 -2
  290. package/src/strand-formation-deadlines.ts +227 -227
  291. package/src/strand-formation-manager.ts +731 -731
  292. package/src/strand-formation-protocol.ts +1174 -1138
  293. package/src/strand-fret-addrs.ts +179 -179
  294. package/src/strand-instance-manager.ts +188 -63
  295. package/src/strand-membership-reconciler.ts +1315 -1310
  296. package/src/strand-membership-writer.ts +2152 -2150
  297. package/src/strand-move.ts +1 -1
  298. package/src/strand-network-config.ts +16 -6
  299. package/src/strand-offline.ts +178 -178
  300. package/src/strand-party-key-rotation.ts +440 -436
  301. package/src/strand-party-machines.ts +308 -293
  302. package/src/strand-party-peers.ts +151 -129
  303. package/src/strand-peer-redial.ts +1 -1
  304. package/src/strand-reactivity.ts +36 -19
  305. package/src/strand-revocation-enforcer.ts +758 -758
  306. package/src/strand-wake-protocol.ts +406 -394
  307. package/src/strand-watcher.ts +1 -1
  308. package/src/table-change-watch.ts +285 -285
  309. package/src/timed-step.ts +28 -28
  310. package/src/timeout-scheduler.ts +29 -29
  311. package/src/trusted-owner-store.ts +242 -242
  312. package/src/types.ts +3182 -3121
  313. package/src/webrtc-upgrade.ts +439 -0
@@ -1,1138 +1,1174 @@
1
- /**
2
- * Native cadre-core strand-formation transport.
3
- *
4
- * Mirrors the `seed-bootstrap.ts` protocol service: a dedicated
5
- * libp2p protocol id, length-prefixed JSON frames, and small single-purpose
6
- * session helpers. It replaces the removed `@serfab/strand-proto` package's transport,
7
- * carrying the caller's REAL invitation token + disclosure and BOTH parties'
8
- * real cadre peer addresses end-to-end (no `{ partyId: sessionId }` / `cadre-*.local`
9
- * placeholders), and validating the responder's result on the initiator side.
10
- *
11
- * Provisioning flow (`responderCreates`, 2 messages): the responder provisions (or, for
12
- * provision-then-record, resolves + records consent against) the strand and returns the
13
- * result on approval.
14
- *
15
- * Cadre-disclosure timing: the responder reveals its own party id + cadre addresses
16
- * — and, for a closed strand returned via provision-then-record, that strand's
17
- * membership key — ONLY after the token and disclosure validate; a rejection
18
- * discloses none of them.
19
- */
20
-
21
- import debug from 'debug';
22
- import { multiaddr, type Multiaddr } from '@multiformats/multiaddr';
23
- import type { Connection, Libp2p } from '@libp2p/interface';
24
- import type { StrandFormationDisclosure, StrandMembershipInvite } from './types.js';
25
- import { type ControlStream, writeFrame, withDeadline, withTimeout } from './control-stream.js';
26
- import { canonicalJson } from './canonical-json.js';
27
- import { requireEd25519PublicKeyB64 } from './ed25519-key.js';
28
- import { verifyFormationConsent } from './peer-authorization.js';
29
- // seed-bootstrap imports neither this protocol nor the manager/solicitation layers,
30
- // so this import introduces no cycle.
31
- import { ed25519PublicKeyB64FromPeerId } from './ed25519-key.js';
32
- import { trailingPeerId } from './peer-dial.js';
33
- import {
34
- formationDeadlines,
35
- resolveProvisionTimeoutMs,
36
- responderClampReserveMs,
37
- splitProvisionBudget
38
- } from './strand-formation-deadlines.js';
39
- import {
40
- FormationRejectedError,
41
- FormationUnreachableError,
42
- type FormationRejectionCode
43
- } from './strand-formation-rejection.js';
44
- import type { FormationTokenCheck, FormationTokenRead } from './formation-token.js';
45
- import { describeThrown, toError } from './describe-thrown.js';
46
-
47
- const log = debug('sereus:cadre:formation-proto');
48
-
49
- /** Protocol id for the native formation transport (parallel to `/sereus/seed/1.0.0`). */
50
- export const FORMATION_PROTOCOL = '/sereus/formation/1.0.0';
51
-
52
- /**
53
- * Rejection reason for an invitation that cannot be redeemed — unknown here
54
- * (`'token-unknown'`), or expired or fully spent (`'token-spent'`); the code tells them
55
- * apart. Shared with `StrandFormationManager`, which reports an `InvitationExhaustedError`
56
- * (an invite spent out from under a redemption already in flight) with this SAME wording and
57
- * code on purpose: a joiner that lost the race must be indistinguishable from a non-racing
58
- * latecomer, so the two sites must never drift apart.
59
- */
60
- export const INVALID_TOKEN_REASON = 'Invalid token';
61
-
62
- /** Maximum formation message size (1MB). */
63
- const MAX_FORMATION_MSG_SIZE = 1024 * 1024;
64
-
65
- /**
66
- * Default cap on concurrent inbound formation sessions.
67
- *
68
- * NOTE: a session holds its slot for its whole provisioning budget, 171 s at the default
69
- * declared link ({@link formationDeadlines}), so a slow hook or commit holds slots for
70
- * minutes. Only a caller holding a valid token AND a valid consent signature reaches
71
- * provisioning — a stranger is cut at the contact wait (7 s at the default) or at the first
72
- * validation read — so the exposure is one invitee opening many sessions with one token. If
73
- * invitation tokens are ever published where untrusted parties can read them, cap in-flight
74
- * sessions per token rather than lowering this.
75
- */
76
- const DEFAULT_MAX_CONCURRENT_SESSIONS = 100;
77
-
78
- /**
79
- * Cap on the strand-network addresses a formation result carries
80
- * ({@link FormationResultMessage.strandAddrs}). A node's own strand multiaddrs are a
81
- * handful of entries (one per listen transport, plus a circuit-relay reservation), so
82
- * 16 is generous for the honest case while keeping the result frame bounded against a
83
- * peer that would pad it — either direction, since both sides run the list through
84
- * {@link sanitizeStrandAddrs}. The initiator's kept copy is one arriving list, replaced by
85
- * the next formation against the same strand, so the same bound holds there.
86
- */
87
- const MAX_STRAND_ADDRS = 16;
88
-
89
- // ── Roles ────────────────────────────────────────────────────────────────────
90
-
91
- export type FormationParty = 'initiator' | 'responder';
92
-
93
- // ── Wire messages (length-prefixed JSON frames) ──────────────────────────────
94
-
95
- export interface FormationStrandInfo {
96
- strandId: string;
97
- createdBy: FormationParty;
98
- }
99
-
100
- export interface FormationDbConnectionInfo {
101
- endpoint: string;
102
- credentialsRef: string;
103
- }
104
-
105
- export interface FormationProvisionResult {
106
- strand: FormationStrandInfo;
107
- /**
108
- * The strand's membership key (closed-strand read-gating secret), delivered to a
109
- * validated invitee for provision-then-record formation. Disclosed only AFTER token
110
- * + disclosure validation, exactly like the responder identity/cadre — a rejected or
111
- * already-used token discloses neither identity nor key. Absent for open strands.
112
- */
113
- memberPrivateKey?: string;
114
- /**
115
- * The joiner's single-use membership invitation into the (closed, bound) host
116
- * strand — issued by the responder's live strand runtime against `Strand.Invite`
117
- * just before the consent row was recorded. Same disclosure timing as
118
- * {@link memberPrivateKey}: present only on an approved result, absent for open
119
- * strands and the responder-provisions path. Bounded and shape-checked on the
120
- * initiator side ({@link isWellFormedMembershipInvite}) — a hostile responder's
121
- * malformed field fails validation rather than crashing the initiator.
122
- */
123
- membershipInvite?: StrandMembershipInvite;
124
- dbConnectionInfo: FormationDbConnectionInfo;
125
- }
126
-
127
- /**
128
- * Outcome of the responder's provisioning hook.
129
- *
130
- * Distinct from a bare {@link FormationProvisionResult} so the hook can REJECT a
131
- * formation AFTER token + disclosure validation — e.g. a bound invite naming a host
132
- * strand this responder has not yet converged on, or a concurrent-redemption collision.
133
- * Without this channel such cases threw inside provisioning, the stream closed with no
134
- * result frame, and the initiator saw a read-error/timeout instead of a clean
135
- * `approved: false`. A rejection still discloses NO responder identity/cadre.
136
- */
137
- export type ResponderProvisionOutcome =
138
- | { approved: true; result: FormationProvisionResult }
139
- | FormationRejection;
140
-
141
- /**
142
- * A refusal as the responder sends it: never without a code. Carries nothing else — no
143
- * identity, addresses or keys — so a rejection discloses nothing about the responder.
144
- */
145
- export interface FormationRejection {
146
- approved: false;
147
- code: FormationRejectionCode;
148
- /** Human-facing text for logs; joiners branch on `code`. */
149
- reason: string;
150
- }
151
-
152
-
153
- /** Initiator → Responder: carries the real token + disclosure + initiator cadre. */
154
- export interface FormationContactMessage {
155
- /** The real invitation token. */
156
- token: string;
157
- /** Initiator's member key (peer id) — human-facing identity in logs and `FormStrandResult.memberKey`. */
158
- partyId: string;
159
- /**
160
- * Initiator's base64url ed25519 public key — the key behind `partyId`, written to
161
- * `FormationUsage.PeerKey` and covered by BOTH signed digests.
162
- */
163
- peerKey: string;
164
- /** Joiner-minted single-use nonce for THIS redemption; both signed digests cover it. */
165
- usageStampId: string;
166
- /**
167
- * The joiner's signature over the `'consent'` digest (see `formationConsentMessage`
168
- * in control-database.ts) — proof the named peer agreed to this redemption.
169
- */
170
- peerSignature: string;
171
- /** The real disclosure, carried verbatim. */
172
- disclosure: StrandFormationDisclosure;
173
- /** Initiator's real multiaddrs. */
174
- cadrePeerAddrs: string[];
175
- }
176
-
177
- /** Responder → Initiator: responder identity/cadre disclosed only after validation. */
178
- export interface FormationResultMessage {
179
- approved: boolean;
180
- /**
181
- * Why the responder refused; present iff `approved === false`. Optional on this wire type
182
- * only because a frame from another version may omit it — the responder always sends one
183
- * ({@link FormationRejection}), and the joiner reads a missing one as `'unrecognized'`.
184
- */
185
- code?: FormationRejectionCode;
186
- /** Human-facing text; present iff `approved === false`. */
187
- reason?: string;
188
- /** Responder's real party id (disclosed only after validation). */
189
- partyId?: string;
190
- /** Responder's real multiaddrs (omitted on rejection). */
191
- cadrePeerAddrs?: string[];
192
- /**
193
- * The responder's live STRAND-network multiaddrs for the provisioned strand — the
194
- * initiator's only cross-party discovery seed, since the strand-addr RPC that resolves
195
- * a sibling's strand addrs is membership-gated and answers own-party callers only.
196
- *
197
- * Disclosed on the same terms as `partyId`/`cadrePeerAddrs`: only after token +
198
- * disclosure validation AND an approving provisioning outcome; a rejection carries
199
- * none. Signaling-first, each entry ending in `/p2p/<responder strand transport
200
- * peerId>` so the initiator can attribute it. OMITTED when the responder holds no live
201
- * strand node for the provisioned strand (the responder-provisions path mints a strand
202
- * that has not launched yet) — an absent or empty list is legal and means "no
203
- * cross-party seed", never a protocol error.
204
- */
205
- strandAddrs?: string[];
206
- /** The provisioned strand/db result (always present on approval). */
207
- provisionResult?: FormationProvisionResult;
208
- }
209
-
210
- /** An approving result frame as the responder builds it. */
211
- type ApprovedResultMessage = FormationResultMessage & { approved: true };
212
-
213
- /**
214
- * Normalize a strand-address list arriving from — or heading to — the wire: keep only
215
- * parsable multiaddr strings, drop duplicates, and cap at {@link MAX_STRAND_ADDRS}.
216
- * Order is preserved, so the responder's signaling-first ordering survives.
217
- *
218
- * Applied on BOTH sides on purpose. The responder bounds what it sends; the initiator
219
- * bounds what it stores, because a peer is free to ignore the cap. A malformed entry is
220
- * SKIPPED rather than fatal — these are runtime-discovered addresses (same posture as
221
- * `extractCircuitRelayTargets` in `delegate-admission.ts`), and one bad entry must not
222
- * cost a formation that has otherwise succeeded.
223
- */
224
- export function sanitizeStrandAddrs(addrs: unknown): string[] {
225
- if (!Array.isArray(addrs)) return [];
226
- const out: string[] = [];
227
- const seen = new Set<string>();
228
- for (const entry of addrs) {
229
- if (out.length >= MAX_STRAND_ADDRS) break;
230
- if (typeof entry !== 'string' || entry.length === 0) {
231
- log('strandAddrs: skipping non-string entry %o', entry);
232
- continue;
233
- }
234
- if (seen.has(entry)) continue;
235
- try {
236
- multiaddr(entry);
237
- } catch (error) {
238
- // Deliberately not echoing the raw value at error level: it arrived from a remote
239
- // peer. The log line below is the observability for a responder announcing junk.
240
- log('strandAddrs: skipping unparsable entry: %o', error);
241
- continue;
242
- }
243
- seen.add(entry);
244
- out.push(entry);
245
- }
246
- return out;
247
- }
248
-
249
- // ── Stream framing helpers ───────────────────────────────────────────────────
250
-
251
- /**
252
- * Reads length-prefixed JSON frames from a libp2p stream one frame at a time.
253
- *
254
- * Unlike seed delivery (which reads a stream to EOF then parses once), formation
255
- * is request/response on a single live stream, so reading must stop at each frame
256
- * boundary. The reader buffers across chunk boundaries and retains any overflow
257
- * (a following frame coalesced into the same chunk) for the next read.
258
- */
259
- class FrameReader {
260
- private readonly iterator: AsyncIterator<Uint8Array>;
261
- private readonly maxLength: number;
262
- private buffer = new Uint8Array(0);
263
-
264
- constructor(stream: AsyncIterable<Uint8Array>, maxLength = MAX_FORMATION_MSG_SIZE) {
265
- this.iterator = stream[Symbol.asyncIterator]();
266
- this.maxLength = maxLength;
267
- }
268
-
269
- private append(chunk: Uint8Array): void {
270
- const next = new Uint8Array(this.buffer.length + chunk.length);
271
- next.set(this.buffer, 0);
272
- next.set(chunk, this.buffer.length);
273
- this.buffer = next;
274
- }
275
-
276
- /** Pull chunks until the buffer holds ≥ `need` bytes; false if the stream ended first. */
277
- private async fill(need: number): Promise<boolean> {
278
- while (this.buffer.length < need) {
279
- const { value, done } = await this.iterator.next();
280
- if (done) return false;
281
- const bytes = value instanceof Uint8Array
282
- ? value
283
- : (value as { subarray(): Uint8Array }).subarray();
284
- this.append(bytes);
285
- }
286
- return true;
287
- }
288
-
289
- async read<T>(): Promise<T> {
290
- if (!(await this.fill(4))) {
291
- throw new Error('Formation stream closed before length prefix');
292
- }
293
- const length = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength).getUint32(0, false);
294
- if (length > this.maxLength) {
295
- throw new Error(`Formation frame declares length ${length} exceeding max ${this.maxLength}`);
296
- }
297
- if (!(await this.fill(4 + length))) {
298
- throw new Error(`Formation frame declares length ${length} but stream ended early`);
299
- }
300
- const json = new TextDecoder().decode(this.buffer.subarray(4, 4 + length));
301
- this.buffer = this.buffer.subarray(4 + length);
302
- return JSON.parse(json) as T;
303
- }
304
- }
305
-
306
- // ── Result validation ────────────────────────────────────────────────────────
307
-
308
- /** Matches the placeholder cadre addrs (`cadre-a-1.local`, …) of the removed strand-proto transport. */
309
- const PLACEHOLDER_CADRE_ADDR = /^cadre-[ab]-\d+\.local$/;
310
-
311
- /**
312
- * Both halves of a {@link StrandMembershipInvite} are base64url ed25519 key encodings —
313
- * 43 chars for 32 bytes. The bound is deliberately loose (a future encoding change must
314
- * not silently strand joiners) while still capping what a hostile responder can make the
315
- * initiator retain.
316
- */
317
- const MAX_MEMBERSHIP_INVITE_KEY_LENGTH = 256;
318
- const BASE64URL_KEY = /^[A-Za-z0-9_-]+$/;
319
-
320
- /**
321
- * Is `value` a well-formed {@link StrandMembershipInvite} — exactly two bounded
322
- * base64url strings? The initiator-side shape check for the one attacker-influenced
323
- * OBJECT the formation result carries (`strandAddrs` gets the equivalent treatment in
324
- * {@link sanitizeStrandAddrs}): a malformed field from a hostile responder must fail
325
- * validation, never crash the initiator or be carried into the joiner's invite cache.
326
- * `undefined` is NOT well-formed — absence is legal on the result and callers gate on
327
- * presence first.
328
- */
329
- export function isWellFormedMembershipInvite(value: unknown): value is StrandMembershipInvite {
330
- if (typeof value !== 'object' || value === null) return false;
331
- const { inviteKey, invitePrivateKey } = value as Record<string, unknown>;
332
- const wellFormedKey = (key: unknown): boolean =>
333
- typeof key === 'string' && key.length > 0 && key.length <= MAX_MEMBERSHIP_INVITE_KEY_LENGTH && BASE64URL_KEY.test(key);
334
- return wellFormedKey(inviteKey) && wellFormedKey(invitePrivateKey);
335
- }
336
-
337
- /**
338
- * Structural check on a `responderCreates` result: the responder must have approved,
339
- * disclosed a non-empty real identity + cadre (not the legacy `cadre-*.local`
340
- * placeholders), and returned a strand vouched for by the responder party with a real id.
341
- *
342
- * `createdBy: 'responder'` means "the responder party vouches for / returns this strand."
343
- * Under provision-then-record that strand was minted owner-signed earlier (not created
344
- * in-session), but it is still the responder party returning its own strand, so the marker
345
- * — and this structural validator — stay unchanged.
346
- *
347
- * The behavioral floor for the initiator: a responder that returns an arbitrary/empty
348
- * `strandId` or omits its disclosed identity is rejected, not silently accepted.
349
- */
350
- export function isValidResponderCreatesResult(response: FormationResultMessage): boolean {
351
- if (!response.approved) return false;
352
- if (!response.partyId) return false;
353
- const addrs = response.cadrePeerAddrs;
354
- if (!addrs || addrs.length === 0) return false;
355
- if (addrs.some((a) => PLACEHOLDER_CADRE_ADDR.test(a))) return false;
356
- const provision = response.provisionResult;
357
- if (!provision?.strand?.strandId) return false;
358
- if (provision.strand.createdBy !== 'responder') return false;
359
- // Optional, but when present it must be well-formed: a malformed invitation is a
360
- // membership the joiner can never redeem, so reject the result rather than accept a
361
- // formation that would leave a half-member.
362
- if (provision.membershipInvite !== undefined && !isWellFormedMembershipInvite(provision.membershipInvite)) {
363
- return false;
364
- }
365
- return true;
366
- }
367
-
368
- // ── Responder (listener) ─────────────────────────────────────────────────────
369
-
370
- export interface FormationListenerOptions {
371
- /** Validate the invitation token; an invalid one says whether it is unknown here or spent. */
372
- validateToken(token: string): Promise<FormationTokenCheck>;
373
- /** Validate the initiator's disclosure with the REAL token + disclosure. */
374
- validateDisclosure(token: string, disclosure: StrandFormationDisclosure): Promise<boolean>;
375
- /**
376
- * Provision (or, for provision-then-record, resolve + record consent against) the
377
- * strand (`responderCreates`) for the given initiator. The WHOLE contact message is
378
- * threaded in: the hook needs the REAL token to map the bound host strand, and the
379
- * joiner's `peerKey`/`usageStampId`/`peerSignature` to write the consent columns.
380
- *
381
- * Returns a {@link ResponderProvisionOutcome}: the hook may REJECT post-validation
382
- * (e.g. an unconverged host strand) and the listener turns that into a clean,
383
- * non-disclosing `approved: false` reply rather than dropping the result frame.
384
- *
385
- * `signal` is aborted when the listener's work budget expires: a hook that observes it
386
- * BEFORE writing abandons the redemption and leaves the invite unspent. Optional so
387
- * signal-unaware hooks (tests, mocks) stay assignable.
388
- *
389
- * `read` is the token as {@link validateToken} read it for this session, so the hook acts on
390
- * that read instead of reading the invite again; absent when the token check read nothing.
391
- */
392
- provisionStrand(
393
- contact: FormationContactMessage,
394
- signal?: AbortSignal,
395
- read?: FormationTokenRead
396
- ): Promise<ResponderProvisionOutcome>;
397
- /** Responder identity, disclosed only AFTER token + disclosure validation passes. */
398
- getResponderIdentity(): { partyId: string; cadrePeerAddrs: string[] };
399
- /**
400
- * This node's live STRAND-network multiaddrs for a provisioned strand, read on the
401
- * approval path only (same disclosure timing as {@link getResponderIdentity}) and
402
- * carried back as {@link FormationResultMessage.strandAddrs}.
403
- *
404
- * Optional, and an empty answer is legal: the strand may not be running here yet (the
405
- * responder-provisions path mints it during this very session). The listener cannot
406
- * reach the strand runtime itself, so this is the seam `CadreNode` wires to its own
407
- * per-strand address lookup.
408
- */
409
- resolveStrandAddrs?(strandId: string): string[];
410
- /**
411
- * This machine's declared link round trip (`NetworkConfig.linkRoundTripMs`), from which
412
- * every deadline below takes its default ({@link formationDeadlines}). The default
413
- * declaration when omitted.
414
- */
415
- linkRoundTripMs?: number;
416
- /** Whole-session budget; default `sessionMs` of the derived ladder. */
417
- sessionTimeoutMs?: number;
418
- /** Budget for the contact-frame read; default `awaitContactMs` of the derived ladder. */
419
- stepTimeoutMs?: number;
420
- /**
421
- * Budget for the `provisionStrand` hook call, work plus settle grace — distinct from
422
- * `stepTimeoutMs` because provisioning is real work, not a bare wire read. Default
423
- * `provisionWorkMs + provisionGraceMs` of the derived ladder (171 s at the default
424
- * declaration); `0`/unset uses the default; a value that would outlive the session is
425
- * clamped ({@link resolveProvisionTimeoutMs}). See {@link formationDeadlines} for the ordering.
426
- */
427
- provisionTimeoutMs?: number;
428
- maxConcurrentSessions?: number;
429
- }
430
-
431
- /**
432
- * Responder side of the native formation protocol. Registers a libp2p handler and
433
- * drives each inbound stream through token + disclosure validation, provisioning,
434
- * and result delivery — enforcing the cadre-disclosure timing rule (responder cadre
435
- * is revealed only after validation; rejections disclose nothing).
436
- */
437
- export class FormationListener {
438
- private readonly options: FormationListenerOptions;
439
- private readonly sessionTimeoutMs: number;
440
- private readonly awaitContactMs: number;
441
- private readonly provisionWorkMs: number;
442
- private readonly provisionGraceMs: number;
443
- private readonly maxConcurrentSessions: number;
444
- private readonly registered = new Set<Libp2p>();
445
- private activeSessions = 0;
446
- private sessionCounter = 0;
447
-
448
- constructor(options: FormationListenerOptions) {
449
- this.options = options;
450
- const deadlines = formationDeadlines(options.linkRoundTripMs);
451
- this.sessionTimeoutMs = options.sessionTimeoutMs ?? deadlines.sessionMs;
452
- this.awaitContactMs = options.stepTimeoutMs ?? deadlines.awaitContactMs;
453
- const split = splitProvisionBudget(resolveProvisionTimeoutMs(
454
- options.provisionTimeoutMs, deadlines.provisionWorkMs + deadlines.provisionGraceMs,
455
- this.sessionTimeoutMs, this.awaitContactMs + deadlines.validationMs, 'FormationListener',
456
- responderClampReserveMs(deadlines, this.awaitContactMs)
457
- ), deadlines.provisionGraceMs);
458
- this.provisionWorkMs = split.workMs;
459
- this.provisionGraceMs = split.graceMs;
460
- this.maxConcurrentSessions = options.maxConcurrentSessions ?? DEFAULT_MAX_CONCURRENT_SESSIONS;
461
- }
462
-
463
- /** Number of in-flight inbound sessions. */
464
- get activeCount(): number {
465
- return this.activeSessions;
466
- }
467
-
468
- /** Register the formation handler on `node`. Rejects when libp2p refuses the registration. */
469
- async register(node: Libp2p, protocolId: string = FORMATION_PROTOCOL): Promise<void> {
470
- if (this.registered.has(node)) {
471
- log('node already registered');
472
- return;
473
- }
474
- await node.handle(protocolId, async (rawStream: unknown, _connection: unknown) => {
475
- await this.handleStream(rawStream as ControlStream);
476
- });
477
- this.registered.add(node);
478
- log('formation listener registered (%s)', protocolId);
479
- }
480
-
481
- async unregister(node: Libp2p, protocolId: string = FORMATION_PROTOCOL): Promise<void> {
482
- if (!this.registered.has(node)) return;
483
- await node.unhandle(protocolId);
484
- this.registered.delete(node);
485
- log('formation listener unregistered (%s)', protocolId);
486
- }
487
-
488
- private async handleStream(stream: ControlStream): Promise<void> {
489
- if (this.activeSessions >= this.maxConcurrentSessions) {
490
- const rejection: FormationRejection = { approved: false, code: 'busy', reason: 'Too many concurrent formation sessions' };
491
- try { writeFrame(stream, rejection); } catch { /* best effort */ }
492
- try { await stream.close(); } catch { /* ignore */ }
493
- return;
494
- }
495
- const id = ++this.sessionCounter;
496
- this.activeSessions++;
497
- try {
498
- await withTimeout(this.sessionTimeoutMs, `Formation session#${id}`, () => this.runSession(id, stream));
499
- } catch (err) {
500
- log('formation session #%d failed: %o', id, err);
501
- } finally {
502
- this.activeSessions--;
503
- try { await stream.close(); } catch { /* ignore */ }
504
- }
505
- }
506
-
507
- /**
508
- * Run the provisioning hook under its WORK budget — the provisioning budget minus the
509
- * trailing settle grace ({@link splitProvisionBudget}).
510
- *
511
- * When the work budget expires the hook's signal is aborted, then
512
- * {@link settleWithinGrace} waits out the grace for the aborted work to settle anyway.
513
- * Returns `undefined` for "timed out" — which the caller turns into a retryable rejection
514
- * frame — and rethrows every other failure so it reaches the internal-error path.
515
- *
516
- * Deliberately not `withDeadline`: that exposes neither the timed-out flag nor the signal
517
- * outside its `op`, and both are needed here.
518
- */
519
- private async provision(
520
- id: number,
521
- contact: FormationContactMessage,
522
- read: FormationTokenRead | undefined
523
- ): Promise<ResponderProvisionOutcome | undefined> {
524
- const controller = new AbortController();
525
- let timedOut = false;
526
- const pending = this.options.provisionStrand(contact, controller.signal, read);
527
- try {
528
- return await withTimeout(
529
- this.provisionWorkMs,
530
- `Formation provisioning#${id}`,
531
- () => pending,
532
- () => { timedOut = true; controller.abort(); }
533
- );
534
- } catch (err) {
535
- if (!timedOut) throw err;
536
- log(
537
- 'formation session #%d provisioning work budget expired after %dms; aborted, settling up to %dms',
538
- id, this.provisionWorkMs, this.provisionGraceMs
539
- );
540
- return await this.settleWithinGrace(id, pending);
541
- }
542
- }
543
-
544
- /**
545
- * Wait out the settle grace for an ABORTED provisioning, adopting a late success.
546
- *
547
- * A hook that observed the abort before issuing its `FormationUsage` insert rejects (with
548
- * `FormationAbortedError`) and leaves the invite unspent → reported as a timeout. A hook
549
- * that had already written cannot be un-written (the table is append-only), so if it lands
550
- * inside the grace its outcome is ADOPTED — the joiner is told the truth (approved, or the
551
- * hook's own rejection reason) rather than "timed out" over a spent invite.
552
- *
553
- * The grace is derived to contain one seat read plus one commit at the declared link
554
- * ({@link formationDeadlines}), which is exactly what runs after the insert attempt passes
555
- * its abort check, so at that link the late outcome lands inside it.
556
- *
557
- * NOTE: a commit that outlasts even the derived grace (a link slower than declared, a
558
- * configured `provisionTimeoutMs` whose half-cap shrank the grace, or a commit phase that
559
- * re-picks an unanswering coordinator, which Optimystic lets run to its transaction budget,
560
- * 170 s at the default declared link) still tells the joiner
561
- * 'timed out' while its one-time invite is in fact spent, and since every retry mints a
562
- * fresh keypair no recovery path can match it. Nothing can un-spend an append-only row, so
563
- * the late-settle logging below is the observability for it; if it is seen in the wild,
564
- * raise the declared link rather than this grace.
565
- */
566
- private async settleWithinGrace(
567
- id: number,
568
- pending: Promise<ResponderProvisionOutcome>
569
- ): Promise<ResponderProvisionOutcome | undefined> {
570
- let stillPending = false;
571
- try {
572
- const outcome = await withTimeout(
573
- this.provisionGraceMs,
574
- `Formation settle#${id}`,
575
- () => pending,
576
- () => { stillPending = true; }
577
- );
578
- log('formation session #%d provisioning settled within its grace: approved=%s — adopting', id, outcome.approved);
579
- return outcome;
580
- } catch (err) {
581
- if (!stillPending) {
582
- log('formation session #%d provisioning failed after its abort: %o', id, err);
583
- return undefined;
584
- }
585
- log('formation session #%d provisioning still pending after its %dms grace', id, this.provisionGraceMs);
586
- // Log how it eventually settled so a late failure is not swallowed by the two
587
- // abandoned `withTimeout` calls.
588
- void pending.then(
589
- (late) => log('formation session #%d provisioning settled after its grace: approved=%s', id, late.approved),
590
- (err2) => log('formation session #%d provisioning failed after its grace: %o', id, err2)
591
- );
592
- return undefined;
593
- }
594
- }
595
-
596
- /**
597
- * Joiner-consent pre-check — the legibility twin of the schema's
598
- * `FormationUsage.PeerConsented` CHECK, exactly as `verifyFormationApproval` is for the
599
- * approver's vouch. The database constraint stays the authority; this turns a bad consent
600
- * into a clean 'Invalid joiner consent' rejection instead of an opaque CHECK failure at
601
- * commit. Runs BEFORE token/disclosure validation: it is the cheapest check (pure local
602
- * crypto, no DB read) and a rejection discloses nothing.
603
- *
604
- * Also pins `partyId` to `peerKey`: an ed25519 peer id is an identity multihash of the
605
- * very key, and this is the ONLY layer that can check the match — SQL cannot unwrap a
606
- * multihash, and `partyId` itself is never stored.
607
- */
608
- private isJoinerConsentValid(id: number, contact: FormationContactMessage): boolean {
609
- try {
610
- requireEd25519PublicKeyB64(contact.peerKey, 'joiner peer key');
611
- } catch {
612
- // Deliberately not rethrown or echoed: the helper's error message embeds the whole
613
- // rejected value, and this one arrived from a remote peer (the cap-the-echo case its
614
- // own NOTE warns about). Log without the raw value instead.
615
- log('formation session #%d: joiner peer key is not a base64url ed25519 public key', id);
616
- return false;
617
- }
618
- const embedded = ed25519PublicKeyB64FromPeerId(contact.partyId);
619
- if (!embedded || embedded !== contact.peerKey) {
620
- log('formation session #%d: partyId does not embed the presented peer key', id);
621
- return false;
622
- }
623
- const consentOk = verifyFormationConsent({
624
- token: contact.token,
625
- usageStampId: contact.usageStampId,
626
- peerKey: contact.peerKey,
627
- disclosure: canonicalJson(contact.disclosure),
628
- peerSig: contact.peerSignature
629
- });
630
- if (!consentOk) {
631
- log('formation session #%d: joiner consent signature failed verification', id);
632
- return false;
633
- }
634
- return true;
635
- }
636
-
637
- /**
638
- * The strand addresses to disclose for an APPROVED provisioning, sanitized and capped.
639
- *
640
- * Never throws: a hook that fails (a strand runtime torn down mid-session) costs the
641
- * joiner its cross-party seed, not the formation it has already earned — the seed is
642
- * an optimization, the consent row is the commitment.
643
- */
644
- private strandAddrsFor(id: number, strandId: string): string[] {
645
- if (!this.options.resolveStrandAddrs) return [];
646
- try {
647
- return sanitizeStrandAddrs(this.options.resolveStrandAddrs(strandId));
648
- } catch (err) {
649
- log('formation session #%d: strand-addr lookup for %s failed (continuing): %o', id, strandId, err);
650
- return [];
651
- }
652
- }
653
-
654
- private async runSession(id: number, stream: ControlStream): Promise<void> {
655
- // Track whether ANY frame has been written so the catch below can convert an
656
- // unexpected internal error into a non-disclosing rejection ONLY when nothing has
657
- // gone out yet. This closes the "stream closed with no result frame" class of bug.
658
- let wroteFrame = false;
659
- const send = (msg: FormationRejection | ApprovedResultMessage): void => {
660
- writeFrame(stream, msg);
661
- wroteFrame = true;
662
- };
663
-
664
- try {
665
- const reader = new FrameReader(stream);
666
- const contact = await withTimeout(this.awaitContactMs, `Formation await-contact#${id}`, () => reader.read<FormationContactMessage>());
667
- log('formation session #%d contact: token=%s party=%s', id, contact.token, contact.partyId);
668
-
669
- if (!this.isJoinerConsentValid(id, contact)) {
670
- send({ approved: false, code: 'consent-invalid', reason: 'Invalid joiner consent' });
671
- return;
672
- }
673
-
674
- const tokenResult = await this.options.validateToken(contact.token);
675
- if (!tokenResult.valid) {
676
- send({ approved: false, code: tokenResult.code, reason: INVALID_TOKEN_REASON });
677
- return;
678
- }
679
-
680
- const disclosureOk = await this.options.validateDisclosure(contact.token, contact.disclosure);
681
- if (!disclosureOk) {
682
- send({ approved: false, code: 'disclosure-invalid', reason: 'Invalid disclosure' });
683
- return;
684
- }
685
-
686
- const outcome = await this.provision(id, contact, tokenResult.read);
687
- if (!outcome) {
688
- // Reported as its own retryable reason rather than falling through to the generic
689
- // catch below, which would report the misleading 'Internal formation error'.
690
- send({ approved: false, code: 'provisioning-timeout', reason: 'Formation provisioning timed out' });
691
- return;
692
- }
693
- if (!outcome.approved) {
694
- // A post-validation rejection still discloses NEITHER identity NOR cadre, exactly
695
- // like the token/disclosure rejections above — copied field by field so nothing else
696
- // a hook put on its outcome reaches the wire.
697
- send({ approved: false, code: outcome.code, reason: outcome.reason });
698
- return;
699
- }
700
- // Validation + provisioning passed → safe to disclose responder identity/cadre.
701
- const identity = this.options.getResponderIdentity();
702
- const strandAddrs = this.strandAddrsFor(id, outcome.result.strand.strandId);
703
- send({
704
- approved: true,
705
- partyId: identity.partyId,
706
- cadrePeerAddrs: identity.cadrePeerAddrs,
707
- // Omitted rather than sent empty: an absent field and an empty list mean the same
708
- // thing to the initiator, and omitting keeps every rejection-parity assertion a
709
- // plain `toBeUndefined()`.
710
- ...(strandAddrs.length > 0 ? { strandAddrs } : {}),
711
- provisionResult: outcome.result
712
- });
713
- } catch (err) {
714
- // Defense-in-depth: if an unexpected internal error escapes BEFORE any frame was
715
- // written (e.g. a future provisionStrand-hook bug), convert it into a non-disclosing
716
- // protocol rejection so the initiator sees a clean error instead of a read-error/
717
- // timeout. If a frame was already sent, leave the stream as-is and let handleStream
718
- // log + close. Re-throw either way so the failure is still recorded — this is a
719
- // deliberate, logged conversion, not silent.
720
- if (!wroteFrame) {
721
- const internalError: FormationRejection = { approved: false, code: 'internal', reason: 'Internal formation error' };
722
- try { writeFrame(stream, internalError); } catch { /* stream already broken */ }
723
- }
724
- throw err;
725
- }
726
- }
727
- }
728
-
729
- // ── Initiator (dialer) ───────────────────────────────────────────────────────
730
-
731
- export interface FormationDialOptions {
732
- /** The contact message to send (real token, partyId, disclosure, initiator cadre). */
733
- contact: FormationContactMessage;
734
- /**
735
- * Responder multiaddrs to dial, normally the invitation's bootstrap list. Every entry that
736
- * parses is tried, in the order libp2p's default address sorter picks (loopback last, then
737
- * public before private, then circuit after direct), until one connects, all under one
738
- * dial-connect budget (`dialTimeoutMs`); an entry that does not parse is skipped.
739
- *
740
- * {@link dialFormation} dials ONE machine, so every entry must name the same trailing peer
741
- * id (or none). An invitation names several machines of the inviting party; hand it to
742
- * {@link dialFormationByMachine}, which splits the list by trailing peer id, drops entries
743
- * that name no peer, and runs one {@link dialFormation} session per machine, in the order
744
- * each machine first appears. Each session keeps its own deadline ladder, so a machine that
745
- * cannot be dialled costs one `dialTimeoutMs` and one that accepts the contact and then
746
- * stalls costs up to one `sessionTimeoutMs`; `CadreNode.createOpenInvitation` names at most
747
- * four machines.
748
- */
749
- responderAddrs: string[];
750
- /** Validate the responder's result; a false return aborts the formation. */
751
- validateResponse(response: FormationResultMessage): Promise<boolean>;
752
- /**
753
- * This machine's declared link round trip (`NetworkConfig.linkRoundTripMs`), from which
754
- * every deadline below takes its default ({@link formationDeadlines}). The default
755
- * declaration when omitted.
756
- */
757
- linkRoundTripMs?: number;
758
- /** Whole-session budget; default `sessionMs` of the derived ladder. */
759
- sessionTimeoutMs?: number;
760
- /**
761
- * Budget for `dial-connect`: opening the connection, through a relay if need be, and
762
- * negotiating the formation protocol. Default `dialMs` of the derived ladder.
763
- */
764
- dialTimeoutMs?: number;
765
- /**
766
- * Budget for the `await-response` read only (the responder's provisioning plus the reply's
767
- * travel time). Default `initiatorAwaitResponseMs` of the derived ladder; `0`/unset uses
768
- * the default; a value that would outlive the session is clamped. See
769
- * {@link formationDeadlines} for the ordering.
770
- */
771
- provisionTimeoutMs?: number;
772
- protocolId?: string;
773
- }
774
-
775
- /**
776
- * What one successful formation dial yields the initiator.
777
- *
778
- * The provisioned strand travels in {@link FormationProvisionResult}, but the responder's
779
- * strand-network addresses are NOT part of that structure — they are a disclosure of the
780
- * responder's live runtime, alongside `partyId`/`cadrePeerAddrs`, not a property of the
781
- * strand row. Returning them beside the provision result keeps that separation while
782
- * still handing the caller the one thing it needs to seed a cross-party mesh.
783
- *
784
- * `strandAddrs` is always an array and is frequently EMPTY — see
785
- * {@link FormationResultMessage.strandAddrs}.
786
- */
787
- export interface FormationDialResult {
788
- provision: FormationProvisionResult;
789
- /** Sanitized + capped ({@link sanitizeStrandAddrs}); `[]` when the responder sent none. */
790
- strandAddrs: string[];
791
- }
792
-
793
- /** The formation stream and the connection it runs on. */
794
- interface FormationChannel {
795
- stream: ControlStream;
796
- connection: Connection;
797
- }
798
-
799
- /**
800
- * Connections a formation dial opened, each with the number of formation exchanges still using
801
- * it; the entry is dropped when the last one finishes and closes the connection
802
- * ({@link releaseFormationConnection}). A connection the node already held when its dial started
803
- * is never entered, so formation never closes someone else's connection.
804
- *
805
- * Counted per connection rather than per dial: two formations to one responder machine at once
806
- * (two pending joins on invitations from one inviter) share the connection libp2p's dial queue
807
- * opened for the first, and the first to finish must leave it to the second.
808
- */
809
- const formationConnectionUsers = new WeakMap<Connection, number>();
810
-
811
- /**
812
- * Open the formation stream under the dial deadline, cancelling the dial when it expires.
813
- *
814
- * The deadline's signal goes into the dial and the stream negotiation, so an expired dial is
815
- * abandoned by libp2p rather than left running. A dial that settles in the same tick the
816
- * deadline fires loses the race to the timeout rejection and would leave its stream open with
817
- * nobody to close it, so a channel that arrives after the signal aborted is reset here, and its
818
- * connection released — the same treatment `exchangeFrame` (`control-stream.ts`) gives a stream
819
- * dialed past its deadline. A late rejection is the abort itself, or reaches the caller through
820
- * the awaited copy, so the handler below only stops it being reported as unhandled.
821
- *
822
- * NOTE: libp2p tries `addrs` one after another, and they all share this one dial budget. Its
823
- * per-address limit (`addressDialTimeout`: ten link round trips plus two admission decisions, as
824
- * `optimysticDialLimits` states it) is longer than `dialTimeoutMs` (`formationDeadlines().dialMs`:
825
- * five round trips plus one decision) at every declaration, so it never cuts off an address
826
- * inside this dial. An address that hangs without answering (a black-holed relay host) uses the
827
- * whole budget, and the join moves on to the party's next machine
828
- * ({@link dialFormationByMachine}) rather than to this machine's next address; an address that is
829
- * refused fails fast and still hands over to the next. A budget per address here would overrun
830
- * the session or shrink the await-response budget ({@link formationDeadlines}). If joins through a
831
- * hung first address are seen in practice, give each address a sub-budget or dial them in parallel.
832
- * The same dial can also be joined to another dial of the responder in flight (the queue keys
833
- * jobs by peer id — see `peer-dial.ts` → `dialAddr`), which then holds this one on that job's
834
- * address; the remedy, when that is seen, is the same per-address dial.
835
- */
836
- function openFormationStream(node: Libp2p, addrs: Multiaddr[], protocolId: string, dialTimeoutMs: number): Promise<FormationChannel> {
837
- return withDeadline(dialTimeoutMs, 'Formation dial-connect', async (signal) => {
838
- const pending = dialFormationChannel(node, addrs, protocolId, signal);
839
- void pending.then(
840
- (channel) => {
841
- if (signal.aborted) abandonLateChannel(channel);
842
- },
843
- () => { /* surfaced through the awaited copy, or the abort itself */ }
844
- );
845
- try {
846
- return await pending;
847
- } catch (error) {
848
- throw describeAllAddressesFailed(error);
849
- }
850
- });
851
- }
852
-
853
- /**
854
- * Dial the responder machine, then open the formation stream on the connection. The ids of the
855
- * node's connections are read before the dial: a connection not among them was opened by this
856
- * dial (or by another formation dial it was joined to), and is closed when formation is done
857
- * with it. A stream that cannot be opened releases the connection at once.
858
- *
859
- * NOTE: a dial of the responder that something other than formation started, and this dial was
860
- * joined to, also counts as opened by formation and is closed afterwards. Nothing else dials an
861
- * inviter's control node before formation does; if something starts to, tell the two apart by
862
- * the connection's own opening time rather than by this snapshot.
863
- */
864
- async function dialFormationChannel(node: Libp2p, addrs: Multiaddr[], protocolId: string, signal: AbortSignal): Promise<FormationChannel> {
865
- const heldBefore = new Set(node.getConnections().map((connection) => connection.id));
866
- const connection = await node.dial(addrs, { signal });
867
- useFormationConnection(connection, heldBefore.has(connection.id));
868
- try {
869
- signal.throwIfAborted();
870
- const stream = await connection.newStream(protocolId, { signal });
871
- return { stream: stream as unknown as ControlStream, connection };
872
- } catch (error) {
873
- void releaseFormationConnection(connection);
874
- throw error;
875
- }
876
- }
877
-
878
- function abandonLateChannel({ stream, connection }: FormationChannel): void {
879
- stream.abort(new Error('Formation dial-connect resolved after its deadline'));
880
- void releaseFormationConnection(connection);
881
- }
882
-
883
- /**
884
- * Count one more formation exchange on `connection` when a formation dial opened it — this one
885
- * (`heldBefore` false) or an earlier one still using it.
886
- */
887
- function useFormationConnection(connection: Connection, heldBefore: boolean): void {
888
- const users = formationConnectionUsers.get(connection);
889
- if (users !== undefined) formationConnectionUsers.set(connection, users + 1);
890
- else if (!heldBefore) formationConnectionUsers.set(connection, 1);
891
- }
892
-
893
- /**
894
- * End one formation exchange's use of `connection`, closing it when a formation dial opened it
895
- * and no other exchange still uses it. Never throws.
896
- *
897
- * Only the joiner closes: it opened the connection, so it is the side that knows the connection
898
- * did not exist before. The joiner's and the inviter's control nodes run on different FRET
899
- * networks, so a connection left open after formation carries nothing but FRET pings that fail,
900
- * until FRET has been refused three times and leaves that peer alone (p2p-fret 1.2.1). FRET can
901
- * still redial the other control node on its own while it re-probes a peer it has seen
902
- * (`complete/fret-maintenance-probes-peers-off-its-ring`).
903
- *
904
- * The close is graceful, so the responder's side can finish its own stream close; a close that
905
- * fails or overruns libp2p's close timeout is logged and the connection aborted, as libp2p's own
906
- * `hangUp` does. When the responder is a machine of the joiner's own party the connection
907
- * normally pre-exists (the cadre mesh) and is left alone; if this dial opened it, it is closed,
908
- * and the mesh re-dials that sibling as after any dropped connection.
909
- */
910
- async function releaseFormationConnection(connection: Connection): Promise<void> {
911
- const users = formationConnectionUsers.get(connection);
912
- if (users === undefined) return;
913
- if (users > 1) {
914
- formationConnectionUsers.set(connection, users - 1);
915
- return;
916
- }
917
- formationConnectionUsers.delete(connection);
918
- try {
919
- await connection.close();
920
- } catch (error) {
921
- log('closing the formation connection to %s failed; aborting it: %o', connection.remotePeer.toString(), error);
922
- connection.abort(toError(error));
923
- }
924
- }
925
-
926
- const NO_RESPONDER_ADDRS = 'No responder addresses available for formation';
927
-
928
- /**
929
- * Parse the responder addresses, skipping any entry that does not parse: the list comes from
930
- * a stranger's invitation, and one bad entry must not fail an otherwise good list. Entries
931
- * naming different peers are left for libp2p to refuse; {@link dialFormationByMachine} hands
932
- * this one machine's addresses at a time.
933
- */
934
- function parseResponderAddrs(addrs: string[]): Multiaddr[] {
935
- const parsed: Multiaddr[] = [];
936
- for (const addr of addrs) {
937
- const ma = parseResponderAddr(addr);
938
- if (ma) parsed.push(ma);
939
- }
940
- if (parsed.length === 0) {
941
- throw new FormationUnreachableError(NO_RESPONDER_ADDRS);
942
- }
943
- return parsed;
944
- }
945
-
946
- function parseResponderAddr(addr: string): Multiaddr | null {
947
- try {
948
- return multiaddr(addr);
949
- } catch (error) {
950
- log('responderAddrs: skipping unparsable entry: %o', error);
951
- return null;
952
- }
953
- }
954
-
955
- /** One machine of the inviting party, and the invitation's addresses for it. */
956
- interface ResponderMachine {
957
- peerId: string;
958
- addrs: string[];
959
- }
960
-
961
- /**
962
- * Split the responder addresses by the machine each reaches (its trailing peer id), keeping
963
- * the order in which each machine first appears. An entry that does not parse, or names no
964
- * peer, is dropped: every address an inviter mints (`getMultiaddrs()`, `resolvePeerAddrs`)
965
- * names its machine, and libp2p refuses one dial that mixes named and unnamed addresses.
966
- */
967
- function groupResponderAddrsByMachine(addrs: string[]): ResponderMachine[] {
968
- const machines = new Map<string, string[]>();
969
- for (const addr of addrs) {
970
- const ma = parseResponderAddr(addr);
971
- if (!ma) continue;
972
- const peerId = trailingPeerId(ma);
973
- if (!peerId) {
974
- log('responderAddrs: skipping %s — it names no machine', addr);
975
- continue;
976
- }
977
- const group = machines.get(peerId);
978
- if (group) group.push(addr);
979
- else machines.set(peerId, [addr]);
980
- }
981
- return [...machines].map(([peerId, group]) => ({ peerId, addrs: group }));
982
- }
983
-
984
- /**
985
- * Worth asking the next machine of the inviting party: it could not be reached, or it answered
986
- * with a refusal a sibling may not repeat (the invitation not replicated to it yet, the host
987
- * strand not running there, …). A final refusal is the party's answer, not one machine's.
988
- */
989
- function shouldTryNextMachine(error: unknown): error is FormationUnreachableError | FormationRejectedError {
990
- return error instanceof FormationUnreachableError || (error instanceof FormationRejectedError && error.retryable);
991
- }
992
-
993
- /**
994
- * Every machine failed without a refusal. A single machine's error already names each address
995
- * it tried, so it is thrown as is; several are restated as one error naming each machine.
996
- */
997
- function noMachineReached(failures: Array<{ peerId: string; error: FormationUnreachableError }>): FormationUnreachableError {
998
- if (failures.length === 1) return failures[0].error;
999
- const errors = failures.map((failure) => failure.error);
1000
- return new FormationUnreachableError(
1001
- `Formation could not reach any of the inviter's ${failures.length} machines: ` +
1002
- failures.map((failure) => `${failure.peerId}: ${failure.error.message}`).join('; '),
1003
- { cause: new AggregateError(errors, 'Every inviting machine was unreachable') }
1004
- );
1005
- }
1006
-
1007
- /**
1008
- * libp2p reports a dial in which every address failed as `AggregateError('All multiaddr dials
1009
- * failed')`, which names none of them; restate it with each address's own error, which names
1010
- * its host and port. A dial that tried only one address already surfaces that address's own
1011
- * error, so anything else passes through unchanged.
1012
- */
1013
- function describeAllAddressesFailed(error: unknown): unknown {
1014
- if (!(error instanceof AggregateError)) return error;
1015
- const reasons = error.errors.map(describeThrown);
1016
- return new FormationUnreachableError(
1017
- `Formation could not reach the inviter at any of the ${reasons.length} addresses tried: ${reasons.join('; ')}`,
1018
- { cause: error }
1019
- );
1020
- }
1021
-
1022
- /** Report a failure that came before any answer as {@link FormationUnreachableError}, keeping its message. */
1023
- function asUnreachable(error: unknown): FormationUnreachableError {
1024
- if (error instanceof FormationUnreachableError) return error;
1025
- return new FormationUnreachableError(describeThrown(error), { cause: error });
1026
- }
1027
-
1028
- /**
1029
- * Open the formation stream, send the contact, and read back the one result frame, closing
1030
- * the stream either way. Nothing here has an answer from the responder yet, so the caller
1031
- * reports any failure as {@link FormationUnreachableError} — a frame too large or not JSON
1032
- * included, since it is not an answer either.
1033
- */
1034
- async function exchangeContact(
1035
- node: Libp2p,
1036
- addrs: Multiaddr[],
1037
- contact: FormationContactMessage,
1038
- budgets: { protocolId: string; dialTimeoutMs: number; awaitResponseMs: number }
1039
- ): Promise<FormationResultMessage> {
1040
- const { stream, connection } = await openFormationStream(node, addrs, budgets.protocolId, budgets.dialTimeoutMs);
1041
- try {
1042
- const reader = new FrameReader(stream);
1043
- writeFrame(stream, contact);
1044
- return await withTimeout(budgets.awaitResponseMs, 'Formation await-response', () => reader.read<FormationResultMessage>());
1045
- } finally {
1046
- try { await stream.close(); } catch { /* ignore */ }
1047
- void releaseFormationConnection(connection);
1048
- }
1049
- }
1050
-
1051
- /**
1052
- * Turn the responder's answer into the dial's result. A refusal throws
1053
- * {@link FormationRejectedError}; an approval that fails validation throws a plain `Error`,
1054
- * since that is a misbehaving responder rather than a refusal.
1055
- */
1056
- async function acceptResult(
1057
- response: FormationResultMessage,
1058
- validateResponse: FormationDialOptions['validateResponse']
1059
- ): Promise<FormationDialResult> {
1060
- if (!response.approved) {
1061
- throw new FormationRejectedError(response.code, response.reason);
1062
- }
1063
- if (!(await validateResponse(response))) throw new Error('Responder result failed validation');
1064
-
1065
- if (!response.provisionResult) throw new Error('Missing provision result for responderCreates mode');
1066
- // Sanitized HERE — the wire boundary — so nothing above this call ever handles an
1067
- // unvalidated, unbounded address list from a remote peer.
1068
- return { provision: response.provisionResult, strandAddrs: sanitizeStrandAddrs(response.strandAddrs) };
1069
- }
1070
-
1071
- /**
1072
- * Initiator side of the native formation protocol. Dials the responder, sends the
1073
- * contact (carrying the real disclosure/token/cadre), validates the responder's
1074
- * result, and returns the strand the responder provisioned plus the responder's
1075
- * strand-network addresses (see {@link FormationDialResult}).
1076
- *
1077
- * Throws {@link FormationUnreachableError} for every failure before a result frame is read
1078
- * (including the session deadline passing first), {@link FormationRejectedError} when the
1079
- * responder refuses, and a plain `Error` for an approval that fails validation.
1080
- */
1081
- export async function dialFormation(node: Libp2p, options: FormationDialOptions): Promise<FormationDialResult> {
1082
- const addrs = parseResponderAddrs(options.responderAddrs);
1083
- const protocolId = options.protocolId ?? FORMATION_PROTOCOL;
1084
- const deadlines = formationDeadlines(options.linkRoundTripMs);
1085
- const sessionTimeoutMs = options.sessionTimeoutMs ?? deadlines.sessionMs;
1086
- const dialTimeoutMs = options.dialTimeoutMs ?? deadlines.dialMs;
1087
- const awaitResponseMs = resolveProvisionTimeoutMs(
1088
- options.provisionTimeoutMs, deadlines.initiatorAwaitResponseMs,
1089
- sessionTimeoutMs, dialTimeoutMs, 'dialFormation'
1090
- );
1091
-
1092
- let answered = false;
1093
- try {
1094
- return await withTimeout(sessionTimeoutMs, 'Formation dial', async () => {
1095
- const response = await exchangeContact(node, addrs, options.contact, { protocolId, dialTimeoutMs, awaitResponseMs });
1096
- answered = true;
1097
- return await acceptResult(response, options.validateResponse);
1098
- });
1099
- } catch (error) {
1100
- throw answered ? error : asUnreachable(error);
1101
- }
1102
- }
1103
-
1104
- /**
1105
- * Initiator side for a whole invitation: one {@link dialFormation} session per machine of the
1106
- * inviting party the bootstrap list names (see {@link FormationDialOptions.responderAddrs}), in
1107
- * order, until one approves.
1108
- *
1109
- * A machine that cannot be reached, or that refuses retryably, hands over to the next. A final
1110
- * refusal, or an approval that fails validation, is thrown at once: another machine of the
1111
- * same party would answer the same, and an approval may already have spent the invitation.
1112
- * With no machine left, throws the last retryable refusal when any machine answered (the party
1113
- * is reachable but not ready, which says more than "unreachable"), otherwise one
1114
- * {@link FormationUnreachableError} naming each machine's failure.
1115
- *
1116
- * Every session sends the SAME contact. `FormationUsage` is keyed by the contact's
1117
- * `usageStampId`, so at most one machine of the inviting party can record this redemption,
1118
- * even when one the joiner gave up on was still committing it.
1119
- */
1120
- export async function dialFormationByMachine(node: Libp2p, options: FormationDialOptions): Promise<FormationDialResult> {
1121
- const machines = groupResponderAddrsByMachine(options.responderAddrs);
1122
- if (machines.length === 0) {
1123
- throw new FormationUnreachableError(NO_RESPONDER_ADDRS);
1124
- }
1125
- const unreached: Array<{ peerId: string; error: FormationUnreachableError }> = [];
1126
- let refusal: FormationRejectedError | undefined;
1127
- for (const machine of machines) {
1128
- try {
1129
- return await dialFormation(node, { ...options, responderAddrs: machine.addrs });
1130
- } catch (error) {
1131
- if (!shouldTryNextMachine(error)) throw error;
1132
- log('formation via %s failed (%s), trying the next inviting machine', machine.peerId, error.message);
1133
- if (error instanceof FormationRejectedError) refusal = error;
1134
- else unreached.push({ peerId: machine.peerId, error });
1135
- }
1136
- }
1137
- throw refusal ?? noMachineReached(unreached);
1138
- }
1
+ /**
2
+ * Native cadre-core strand-formation transport.
3
+ *
4
+ * Mirrors the `seed-bootstrap.ts` protocol service: a dedicated
5
+ * libp2p protocol id, length-prefixed JSON frames, and small single-purpose
6
+ * session helpers. It replaces the removed `@serfab/strand-proto` package's transport,
7
+ * carrying the caller's REAL invitation token + disclosure and BOTH parties'
8
+ * real cadre peer addresses end-to-end (no `{ partyId: sessionId }` / `cadre-*.local`
9
+ * placeholders), and validating the responder's result on the initiator side.
10
+ *
11
+ * Provisioning flow (`responderCreates`, 2 messages): the responder provisions (or, for
12
+ * provision-then-record, resolves + records consent against) the strand and returns the
13
+ * result on approval.
14
+ *
15
+ * Cadre-disclosure timing: the responder reveals its own party id + cadre addresses
16
+ * — and, for a closed strand returned via provision-then-record, that strand's
17
+ * membership key — ONLY after the token and disclosure validate; a rejection
18
+ * discloses none of them.
19
+ */
20
+
21
+ import debug from 'debug';
22
+ import { multiaddr, type Multiaddr } from '@multiformats/multiaddr';
23
+ import type { Connection, Libp2p } from '@libp2p/interface';
24
+ import type { StrandFormationDisclosure, StrandMembershipInvite } from './types.js';
25
+ import { type ControlStream, writeFrame, withDeadline, withTimeout } from './control-stream.js';
26
+ import { canonicalJson } from './canonical-json.js';
27
+ import { requireEd25519PublicKeyB64 } from './ed25519-key.js';
28
+ import { verifyFormationConsent } from './peer-authorization.js';
29
+ // seed-bootstrap imports neither this protocol nor the manager/solicitation layers,
30
+ // so this import introduces no cycle.
31
+ import { ed25519PublicKeyB64FromPeerId } from './ed25519-key.js';
32
+ import { addrKind, trailingPeerId } from './peer-dial.js';
33
+ import {
34
+ formationDeadlines,
35
+ resolveProvisionTimeoutMs,
36
+ responderClampReserveMs,
37
+ splitProvisionBudget
38
+ } from './strand-formation-deadlines.js';
39
+ import {
40
+ FormationRejectedError,
41
+ FormationUnreachableError,
42
+ type FormationRejectionCode
43
+ } from './strand-formation-rejection.js';
44
+ import type { FormationTokenCheck, FormationTokenRead } from './formation-token.js';
45
+ import { describeThrown, toError } from './describe-thrown.js';
46
+
47
+ const log = debug('sereus:cadre:formation-proto');
48
+
49
+ /** Protocol id for the native formation transport (parallel to `/sereus/seed/1.0.0`). */
50
+ export const FORMATION_PROTOCOL = '/sereus/formation/1.0.0';
51
+
52
+ /**
53
+ * Rejection reason for an invitation that cannot be redeemed — unknown here
54
+ * (`'token-unknown'`), or expired or fully spent (`'token-spent'`); the code tells them
55
+ * apart. Shared with `StrandFormationManager`, which reports an `InvitationExhaustedError`
56
+ * (an invite spent out from under a redemption already in flight) with this SAME wording and
57
+ * code on purpose: a joiner that lost the race must be indistinguishable from a non-racing
58
+ * latecomer, so the two sites must never drift apart.
59
+ */
60
+ export const INVALID_TOKEN_REASON = 'Invalid token';
61
+
62
+ /** Maximum formation message size (1MB). */
63
+ const MAX_FORMATION_MSG_SIZE = 1024 * 1024;
64
+
65
+ /**
66
+ * Default cap on concurrent inbound formation sessions.
67
+ *
68
+ * NOTE: a session holds its slot for its whole provisioning budget, 171 s at the default
69
+ * declared link ({@link formationDeadlines}), so a slow hook or commit holds slots for
70
+ * minutes. Only a caller holding a valid token AND a valid consent signature reaches
71
+ * provisioning — a stranger is cut at the contact wait (7 s at the default) or at the first
72
+ * validation read — so the exposure is one invitee opening many sessions with one token. If
73
+ * invitation tokens are ever published where untrusted parties can read them, cap in-flight
74
+ * sessions per token rather than lowering this.
75
+ */
76
+ const DEFAULT_MAX_CONCURRENT_SESSIONS = 100;
77
+
78
+ /**
79
+ * Cap on the strand-network addresses a formation result carries
80
+ * ({@link FormationResultMessage.strandAddrs}). A node's own strand multiaddrs are a
81
+ * handful of entries (one per listen transport, plus a circuit-relay reservation), so
82
+ * 16 is generous for the honest case while keeping the result frame bounded against a
83
+ * peer that would pad it — either direction, since both sides run the list through
84
+ * {@link sanitizeStrandAddrs}. The initiator's kept copy is one arriving list, replaced by
85
+ * the next formation against the same strand, so the same bound holds there.
86
+ */
87
+ const MAX_STRAND_ADDRS = 16;
88
+
89
+ // ── Roles ────────────────────────────────────────────────────────────────────
90
+
91
+ export type FormationParty = 'initiator' | 'responder';
92
+
93
+ // ── Wire messages (length-prefixed JSON frames) ──────────────────────────────
94
+
95
+ export interface FormationStrandInfo {
96
+ strandId: string;
97
+ createdBy: FormationParty;
98
+ }
99
+
100
+ export interface FormationDbConnectionInfo {
101
+ endpoint: string;
102
+ credentialsRef: string;
103
+ }
104
+
105
+ export interface FormationProvisionResult {
106
+ strand: FormationStrandInfo;
107
+ /**
108
+ * The strand's membership key (closed-strand read-gating secret), delivered to a
109
+ * validated invitee for provision-then-record formation. Disclosed only AFTER token
110
+ * + disclosure validation, exactly like the responder identity/cadre — a rejected or
111
+ * already-used token discloses neither identity nor key. Absent for open strands.
112
+ */
113
+ memberPrivateKey?: string;
114
+ /**
115
+ * The joiner's single-use membership invitation into the (closed, bound) host
116
+ * strand — issued by the responder's live strand runtime against `Strand.Invite`
117
+ * just before the consent row was recorded. Same disclosure timing as
118
+ * {@link memberPrivateKey}: present only on an approved result, absent for open
119
+ * strands and the responder-provisions path. Bounded and shape-checked on the
120
+ * initiator side ({@link isWellFormedMembershipInvite}) — a hostile responder's
121
+ * malformed field fails validation rather than crashing the initiator.
122
+ */
123
+ membershipInvite?: StrandMembershipInvite;
124
+ dbConnectionInfo: FormationDbConnectionInfo;
125
+ }
126
+
127
+ /**
128
+ * Outcome of the responder's provisioning hook.
129
+ *
130
+ * Distinct from a bare {@link FormationProvisionResult} so the hook can REJECT a
131
+ * formation AFTER token + disclosure validation — e.g. a bound invite naming a host
132
+ * strand this responder has not yet converged on, or a concurrent-redemption collision.
133
+ * Without this channel such cases threw inside provisioning, the stream closed with no
134
+ * result frame, and the initiator saw a read-error/timeout instead of a clean
135
+ * `approved: false`. A rejection still discloses NO responder identity/cadre.
136
+ */
137
+ export type ResponderProvisionOutcome =
138
+ | { approved: true; result: FormationProvisionResult }
139
+ | FormationRejection;
140
+
141
+ /**
142
+ * A refusal as the responder sends it: never without a code. Carries nothing else — no
143
+ * identity, addresses or keys — so a rejection discloses nothing about the responder.
144
+ */
145
+ export interface FormationRejection {
146
+ approved: false;
147
+ code: FormationRejectionCode;
148
+ /** Human-facing text for logs; joiners branch on `code`. */
149
+ reason: string;
150
+ }
151
+
152
+
153
+ /** Initiator → Responder: carries the real token + disclosure + initiator cadre. */
154
+ export interface FormationContactMessage {
155
+ /** The real invitation token. */
156
+ token: string;
157
+ /** Initiator's member key (peer id) — human-facing identity in logs and `FormStrandResult.memberKey`. */
158
+ partyId: string;
159
+ /**
160
+ * Initiator's base64url ed25519 public key — the key behind `partyId`, written to
161
+ * `FormationUsage.PeerKey` and covered by BOTH signed digests.
162
+ */
163
+ peerKey: string;
164
+ /** Joiner-minted single-use nonce for THIS redemption; both signed digests cover it. */
165
+ usageStampId: string;
166
+ /**
167
+ * The joiner's signature over the `'consent'` digest (see `formationConsentMessage`
168
+ * in control-database.ts) — proof the named peer agreed to this redemption.
169
+ */
170
+ peerSignature: string;
171
+ /** The real disclosure, carried verbatim. */
172
+ disclosure: StrandFormationDisclosure;
173
+ /** Initiator's real multiaddrs. */
174
+ cadrePeerAddrs: string[];
175
+ }
176
+
177
+ /** Responder → Initiator: responder identity/cadre disclosed only after validation. */
178
+ export interface FormationResultMessage {
179
+ approved: boolean;
180
+ /**
181
+ * Why the responder refused; present iff `approved === false`. Optional on this wire type
182
+ * only because a frame from another version may omit it — the responder always sends one
183
+ * ({@link FormationRejection}), and the joiner reads a missing one as `'unrecognized'`.
184
+ */
185
+ code?: FormationRejectionCode;
186
+ /** Human-facing text; present iff `approved === false`. */
187
+ reason?: string;
188
+ /** Responder's real party id (disclosed only after validation). */
189
+ partyId?: string;
190
+ /** Responder's real multiaddrs (omitted on rejection). */
191
+ cadrePeerAddrs?: string[];
192
+ /**
193
+ * The responder's live STRAND-network multiaddrs for the provisioned strand — the
194
+ * initiator's only cross-party discovery seed, since the strand-addr RPC that resolves
195
+ * a sibling's strand addrs is membership-gated and answers own-party callers only.
196
+ *
197
+ * Disclosed on the same terms as `partyId`/`cadrePeerAddrs`: only after token +
198
+ * disclosure validation AND an approving provisioning outcome; a rejection carries
199
+ * none. Signaling-first, each entry ending in `/p2p/<responder strand transport
200
+ * peerId>` so the initiator can attribute it. OMITTED when the responder holds no live
201
+ * strand node for the provisioned strand (the responder-provisions path mints a strand
202
+ * that has not launched yet) — an absent or empty list is legal and means "no
203
+ * cross-party seed", never a protocol error.
204
+ */
205
+ strandAddrs?: string[];
206
+ /** The provisioned strand/db result (always present on approval). */
207
+ provisionResult?: FormationProvisionResult;
208
+ }
209
+
210
+ /** An approving result frame as the responder builds it. */
211
+ type ApprovedResultMessage = FormationResultMessage & { approved: true };
212
+
213
+ /**
214
+ * Normalize a strand-address list arriving from — or heading to — the wire: keep only
215
+ * parsable multiaddr strings, drop duplicates, and cap at {@link MAX_STRAND_ADDRS}.
216
+ * Order is preserved, so the responder's relayed-first ordering survives.
217
+ *
218
+ * Applied on BOTH sides on purpose. The responder bounds what it sends; the initiator
219
+ * bounds what it stores, because a peer is free to ignore the cap. A malformed entry is
220
+ * SKIPPED rather than fatal — these are runtime-discovered addresses (same posture as
221
+ * `extractCircuitRelayTargets` in `delegate-admission.ts`), and one bad entry must not
222
+ * cost a formation that has otherwise succeeded.
223
+ */
224
+ export function sanitizeStrandAddrs(addrs: unknown): string[] {
225
+ if (!Array.isArray(addrs)) return [];
226
+ const out: string[] = [];
227
+ const seen = new Set<string>();
228
+ for (const entry of addrs) {
229
+ if (out.length >= MAX_STRAND_ADDRS) break;
230
+ if (typeof entry !== 'string' || entry.length === 0) {
231
+ log('strandAddrs: skipping non-string entry %o', entry);
232
+ continue;
233
+ }
234
+ if (seen.has(entry)) continue;
235
+ try {
236
+ multiaddr(entry);
237
+ } catch (error) {
238
+ // Deliberately not echoing the raw value at error level: it arrived from a remote
239
+ // peer. The log line below is the observability for a responder announcing junk.
240
+ log('strandAddrs: skipping unparsable entry: %o', error);
241
+ continue;
242
+ }
243
+ seen.add(entry);
244
+ out.push(entry);
245
+ }
246
+ return out;
247
+ }
248
+
249
+ // ── Stream framing helpers ───────────────────────────────────────────────────
250
+
251
+ /**
252
+ * Reads length-prefixed JSON frames from a libp2p stream one frame at a time.
253
+ *
254
+ * Unlike seed delivery (which reads a stream to EOF then parses once), formation
255
+ * is request/response on a single live stream, so reading must stop at each frame
256
+ * boundary. The reader buffers across chunk boundaries and retains any overflow
257
+ * (a following frame coalesced into the same chunk) for the next read.
258
+ */
259
+ class FrameReader {
260
+ private readonly iterator: AsyncIterator<Uint8Array>;
261
+ private readonly maxLength: number;
262
+ private buffer = new Uint8Array(0);
263
+
264
+ constructor(stream: AsyncIterable<Uint8Array>, maxLength = MAX_FORMATION_MSG_SIZE) {
265
+ this.iterator = stream[Symbol.asyncIterator]();
266
+ this.maxLength = maxLength;
267
+ }
268
+
269
+ private append(chunk: Uint8Array): void {
270
+ const next = new Uint8Array(this.buffer.length + chunk.length);
271
+ next.set(this.buffer, 0);
272
+ next.set(chunk, this.buffer.length);
273
+ this.buffer = next;
274
+ }
275
+
276
+ /** Pull chunks until the buffer holds ≥ `need` bytes; false if the stream ended first. */
277
+ private async fill(need: number): Promise<boolean> {
278
+ while (this.buffer.length < need) {
279
+ const { value, done } = await this.iterator.next();
280
+ if (done) return false;
281
+ const bytes = value instanceof Uint8Array
282
+ ? value
283
+ : (value as { subarray(): Uint8Array }).subarray();
284
+ this.append(bytes);
285
+ }
286
+ return true;
287
+ }
288
+
289
+ async read<T>(): Promise<T> {
290
+ if (!(await this.fill(4))) {
291
+ throw new Error('Formation stream closed before length prefix');
292
+ }
293
+ const length = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength).getUint32(0, false);
294
+ if (length > this.maxLength) {
295
+ throw new Error(`Formation frame declares length ${length} exceeding max ${this.maxLength}`);
296
+ }
297
+ if (!(await this.fill(4 + length))) {
298
+ throw new Error(`Formation frame declares length ${length} but stream ended early`);
299
+ }
300
+ const json = new TextDecoder().decode(this.buffer.subarray(4, 4 + length));
301
+ this.buffer = this.buffer.subarray(4 + length);
302
+ return JSON.parse(json) as T;
303
+ }
304
+ }
305
+
306
+ // ── Result validation ────────────────────────────────────────────────────────
307
+
308
+ /** Matches the placeholder cadre addrs (`cadre-a-1.local`, …) of the removed strand-proto transport. */
309
+ const PLACEHOLDER_CADRE_ADDR = /^cadre-[ab]-\d+\.local$/;
310
+
311
+ /**
312
+ * Both halves of a {@link StrandMembershipInvite} are base64url ed25519 key encodings —
313
+ * 43 chars for 32 bytes. The bound is deliberately loose (a future encoding change must
314
+ * not silently strand joiners) while still capping what a hostile responder can make the
315
+ * initiator retain.
316
+ */
317
+ const MAX_MEMBERSHIP_INVITE_KEY_LENGTH = 256;
318
+ const BASE64URL_KEY = /^[A-Za-z0-9_-]+$/;
319
+
320
+ /**
321
+ * Is `value` a well-formed {@link StrandMembershipInvite} — exactly two bounded
322
+ * base64url strings? The initiator-side shape check for the one attacker-influenced
323
+ * OBJECT the formation result carries (`strandAddrs` gets the equivalent treatment in
324
+ * {@link sanitizeStrandAddrs}): a malformed field from a hostile responder must fail
325
+ * validation, never crash the initiator or be carried into the joiner's invite cache.
326
+ * `undefined` is NOT well-formed — absence is legal on the result and callers gate on
327
+ * presence first.
328
+ */
329
+ export function isWellFormedMembershipInvite(value: unknown): value is StrandMembershipInvite {
330
+ if (typeof value !== 'object' || value === null) return false;
331
+ const { inviteKey, invitePrivateKey } = value as Record<string, unknown>;
332
+ const wellFormedKey = (key: unknown): boolean =>
333
+ typeof key === 'string' && key.length > 0 && key.length <= MAX_MEMBERSHIP_INVITE_KEY_LENGTH && BASE64URL_KEY.test(key);
334
+ return wellFormedKey(inviteKey) && wellFormedKey(invitePrivateKey);
335
+ }
336
+
337
+ /**
338
+ * Structural check on a `responderCreates` result: the responder must have approved,
339
+ * disclosed a non-empty real identity + cadre (not the legacy `cadre-*.local`
340
+ * placeholders), and returned a strand vouched for by the responder party with a real id.
341
+ *
342
+ * `createdBy: 'responder'` means "the responder party vouches for / returns this strand."
343
+ * Under provision-then-record that strand was minted owner-signed earlier (not created
344
+ * in-session), but it is still the responder party returning its own strand, so the marker
345
+ * — and this structural validator — stay unchanged.
346
+ *
347
+ * The behavioral floor for the initiator: a responder that returns an arbitrary/empty
348
+ * `strandId` or omits its disclosed identity is rejected, not silently accepted.
349
+ */
350
+ export function isValidResponderCreatesResult(response: FormationResultMessage): boolean {
351
+ if (!response.approved) return false;
352
+ if (!response.partyId) return false;
353
+ const addrs = response.cadrePeerAddrs;
354
+ if (!addrs || addrs.length === 0) return false;
355
+ if (addrs.some((a) => PLACEHOLDER_CADRE_ADDR.test(a))) return false;
356
+ const provision = response.provisionResult;
357
+ if (!provision?.strand?.strandId) return false;
358
+ if (provision.strand.createdBy !== 'responder') return false;
359
+ // Optional, but when present it must be well-formed: a malformed invitation is a
360
+ // membership the joiner can never redeem, so reject the result rather than accept a
361
+ // formation that would leave a half-member.
362
+ if (provision.membershipInvite !== undefined && !isWellFormedMembershipInvite(provision.membershipInvite)) {
363
+ return false;
364
+ }
365
+ return true;
366
+ }
367
+
368
+ // ── Responder (listener) ─────────────────────────────────────────────────────
369
+
370
+ export interface FormationListenerOptions {
371
+ /** Validate the invitation token; an invalid one says whether it is unknown here or spent. */
372
+ validateToken(token: string): Promise<FormationTokenCheck>;
373
+ /** Validate the initiator's disclosure with the REAL token + disclosure. */
374
+ validateDisclosure(token: string, disclosure: StrandFormationDisclosure): Promise<boolean>;
375
+ /**
376
+ * Provision (or, for provision-then-record, resolve + record consent against) the
377
+ * strand (`responderCreates`) for the given initiator. The WHOLE contact message is
378
+ * threaded in: the hook needs the REAL token to map the bound host strand, and the
379
+ * joiner's `peerKey`/`usageStampId`/`peerSignature` to write the consent columns.
380
+ *
381
+ * Returns a {@link ResponderProvisionOutcome}: the hook may REJECT post-validation
382
+ * (e.g. an unconverged host strand) and the listener turns that into a clean,
383
+ * non-disclosing `approved: false` reply rather than dropping the result frame.
384
+ *
385
+ * `signal` is aborted when the listener's work budget expires: a hook that observes it
386
+ * BEFORE writing abandons the redemption and leaves the invite unspent. Optional so
387
+ * signal-unaware hooks (tests, mocks) stay assignable.
388
+ *
389
+ * `read` is the token as {@link validateToken} read it for this session, so the hook acts on
390
+ * that read instead of reading the invite again; absent when the token check read nothing.
391
+ */
392
+ provisionStrand(
393
+ contact: FormationContactMessage,
394
+ signal?: AbortSignal,
395
+ read?: FormationTokenRead
396
+ ): Promise<ResponderProvisionOutcome>;
397
+ /** Responder identity, disclosed only AFTER token + disclosure validation passes. */
398
+ getResponderIdentity(): { partyId: string; cadrePeerAddrs: string[] };
399
+ /**
400
+ * This node's live STRAND-network multiaddrs for a provisioned strand, read on the
401
+ * approval path only (same disclosure timing as {@link getResponderIdentity}) and
402
+ * carried back as {@link FormationResultMessage.strandAddrs}.
403
+ *
404
+ * Optional, and an empty answer is legal: the strand may not be running here yet (the
405
+ * responder-provisions path mints it during this very session). The listener cannot
406
+ * reach the strand runtime itself, so this is the seam `CadreNode` wires to its own
407
+ * per-strand address lookup.
408
+ */
409
+ resolveStrandAddrs?(strandId: string): string[];
410
+ /**
411
+ * This machine's declared link round trip (`NetworkConfig.linkRoundTripMs`), from which
412
+ * every deadline below takes its default ({@link formationDeadlines}). The default
413
+ * declaration when omitted.
414
+ */
415
+ linkRoundTripMs?: number;
416
+ /** Whole-session budget; default `sessionMs` of the derived ladder. */
417
+ sessionTimeoutMs?: number;
418
+ /** Budget for the contact-frame read; default `awaitContactMs` of the derived ladder. */
419
+ stepTimeoutMs?: number;
420
+ /**
421
+ * Budget for the `provisionStrand` hook call, work plus settle grace — distinct from
422
+ * `stepTimeoutMs` because provisioning is real work, not a bare wire read. Default
423
+ * `provisionWorkMs + provisionGraceMs` of the derived ladder (171 s at the default
424
+ * declaration); `0`/unset uses the default; a value that would outlive the session is
425
+ * clamped ({@link resolveProvisionTimeoutMs}). See {@link formationDeadlines} for the ordering.
426
+ */
427
+ provisionTimeoutMs?: number;
428
+ maxConcurrentSessions?: number;
429
+ }
430
+
431
+ /**
432
+ * Responder side of the native formation protocol. Registers a libp2p handler and
433
+ * drives each inbound stream through token + disclosure validation, provisioning,
434
+ * and result delivery — enforcing the cadre-disclosure timing rule (responder cadre
435
+ * is revealed only after validation; rejections disclose nothing).
436
+ */
437
+ export class FormationListener {
438
+ private readonly options: FormationListenerOptions;
439
+ private readonly sessionTimeoutMs: number;
440
+ private readonly awaitContactMs: number;
441
+ private readonly provisionWorkMs: number;
442
+ private readonly provisionGraceMs: number;
443
+ private readonly maxConcurrentSessions: number;
444
+ private readonly registered = new Set<Libp2p>();
445
+ private activeSessions = 0;
446
+ private sessionCounter = 0;
447
+
448
+ constructor(options: FormationListenerOptions) {
449
+ this.options = options;
450
+ const deadlines = formationDeadlines(options.linkRoundTripMs);
451
+ this.sessionTimeoutMs = options.sessionTimeoutMs ?? deadlines.sessionMs;
452
+ this.awaitContactMs = options.stepTimeoutMs ?? deadlines.awaitContactMs;
453
+ const split = splitProvisionBudget(resolveProvisionTimeoutMs(
454
+ options.provisionTimeoutMs, deadlines.provisionWorkMs + deadlines.provisionGraceMs,
455
+ this.sessionTimeoutMs, this.awaitContactMs + deadlines.validationMs, 'FormationListener',
456
+ responderClampReserveMs(deadlines, this.awaitContactMs)
457
+ ), deadlines.provisionGraceMs);
458
+ this.provisionWorkMs = split.workMs;
459
+ this.provisionGraceMs = split.graceMs;
460
+ this.maxConcurrentSessions = options.maxConcurrentSessions ?? DEFAULT_MAX_CONCURRENT_SESSIONS;
461
+ }
462
+
463
+ /** Number of in-flight inbound sessions. */
464
+ get activeCount(): number {
465
+ return this.activeSessions;
466
+ }
467
+
468
+ /** Register the formation handler on `node`. Rejects when libp2p refuses the registration. */
469
+ async register(node: Libp2p, protocolId: string = FORMATION_PROTOCOL): Promise<void> {
470
+ if (this.registered.has(node)) {
471
+ log('node already registered');
472
+ return;
473
+ }
474
+ await node.handle(protocolId, async (rawStream: unknown, _connection: unknown) => {
475
+ await this.handleStream(rawStream as ControlStream);
476
+ });
477
+ this.registered.add(node);
478
+ log('formation listener registered (%s)', protocolId);
479
+ }
480
+
481
+ async unregister(node: Libp2p, protocolId: string = FORMATION_PROTOCOL): Promise<void> {
482
+ if (!this.registered.has(node)) return;
483
+ await node.unhandle(protocolId);
484
+ this.registered.delete(node);
485
+ log('formation listener unregistered (%s)', protocolId);
486
+ }
487
+
488
+ private async handleStream(stream: ControlStream): Promise<void> {
489
+ if (this.activeSessions >= this.maxConcurrentSessions) {
490
+ const rejection: FormationRejection = { approved: false, code: 'busy', reason: 'Too many concurrent formation sessions' };
491
+ try { writeFrame(stream, rejection); } catch { /* best effort */ }
492
+ try { await stream.close(); } catch { /* ignore */ }
493
+ return;
494
+ }
495
+ const id = ++this.sessionCounter;
496
+ this.activeSessions++;
497
+ try {
498
+ await withTimeout(this.sessionTimeoutMs, `Formation session#${id}`, () => this.runSession(id, stream));
499
+ } catch (err) {
500
+ log('formation session #%d failed: %o', id, err);
501
+ } finally {
502
+ this.activeSessions--;
503
+ try { await stream.close(); } catch { /* ignore */ }
504
+ }
505
+ }
506
+
507
+ /**
508
+ * Run the provisioning hook under its WORK budget — the provisioning budget minus the
509
+ * trailing settle grace ({@link splitProvisionBudget}).
510
+ *
511
+ * When the work budget expires the hook's signal is aborted, then
512
+ * {@link settleWithinGrace} waits out the grace for the aborted work to settle anyway.
513
+ * Returns `undefined` for "timed out" — which the caller turns into a retryable rejection
514
+ * frame — and rethrows every other failure so it reaches the internal-error path.
515
+ *
516
+ * Deliberately not `withDeadline`: that exposes neither the timed-out flag nor the signal
517
+ * outside its `op`, and both are needed here.
518
+ */
519
+ private async provision(
520
+ id: number,
521
+ contact: FormationContactMessage,
522
+ read: FormationTokenRead | undefined
523
+ ): Promise<ResponderProvisionOutcome | undefined> {
524
+ const controller = new AbortController();
525
+ let timedOut = false;
526
+ const pending = this.options.provisionStrand(contact, controller.signal, read);
527
+ try {
528
+ return await withTimeout(
529
+ this.provisionWorkMs,
530
+ `Formation provisioning#${id}`,
531
+ () => pending,
532
+ () => { timedOut = true; controller.abort(); }
533
+ );
534
+ } catch (err) {
535
+ if (!timedOut) throw err;
536
+ log(
537
+ 'formation session #%d provisioning work budget expired after %dms; aborted, settling up to %dms',
538
+ id, this.provisionWorkMs, this.provisionGraceMs
539
+ );
540
+ return await this.settleWithinGrace(id, pending);
541
+ }
542
+ }
543
+
544
+ /**
545
+ * Wait out the settle grace for an ABORTED provisioning, adopting a late success.
546
+ *
547
+ * A hook that observed the abort before issuing its `FormationUsage` insert rejects (with
548
+ * `FormationAbortedError`) and leaves the invite unspent → reported as a timeout. A hook
549
+ * that had already written cannot be un-written (the table is append-only), so if it lands
550
+ * inside the grace its outcome is ADOPTED — the joiner is told the truth (approved, or the
551
+ * hook's own rejection reason) rather than "timed out" over a spent invite.
552
+ *
553
+ * The grace is derived to contain one seat read plus one commit at the declared link
554
+ * ({@link formationDeadlines}), which is exactly what runs after the insert attempt passes
555
+ * its abort check, so at that link the late outcome lands inside it.
556
+ *
557
+ * NOTE: a commit that outlasts even the derived grace (a link slower than declared, a
558
+ * configured `provisionTimeoutMs` whose half-cap shrank the grace, or a commit phase that
559
+ * re-picks an unanswering coordinator, which Optimystic lets run to its transaction budget,
560
+ * 170 s at the default declared link) still tells the joiner
561
+ * 'timed out' while its one-time invite is in fact spent, and since every retry mints a
562
+ * fresh keypair no recovery path can match it. Nothing can un-spend an append-only row, so
563
+ * the late-settle logging below is the observability for it; if it is seen in the wild,
564
+ * raise the declared link rather than this grace.
565
+ */
566
+ private async settleWithinGrace(
567
+ id: number,
568
+ pending: Promise<ResponderProvisionOutcome>
569
+ ): Promise<ResponderProvisionOutcome | undefined> {
570
+ let stillPending = false;
571
+ try {
572
+ const outcome = await withTimeout(
573
+ this.provisionGraceMs,
574
+ `Formation settle#${id}`,
575
+ () => pending,
576
+ () => { stillPending = true; }
577
+ );
578
+ log('formation session #%d provisioning settled within its grace: approved=%s — adopting', id, outcome.approved);
579
+ return outcome;
580
+ } catch (err) {
581
+ if (!stillPending) {
582
+ log('formation session #%d provisioning failed after its abort: %o', id, err);
583
+ return undefined;
584
+ }
585
+ log('formation session #%d provisioning still pending after its %dms grace', id, this.provisionGraceMs);
586
+ // Log how it eventually settled so a late failure is not swallowed by the two
587
+ // abandoned `withTimeout` calls.
588
+ void pending.then(
589
+ (late) => log('formation session #%d provisioning settled after its grace: approved=%s', id, late.approved),
590
+ (err2) => log('formation session #%d provisioning failed after its grace: %o', id, err2)
591
+ );
592
+ return undefined;
593
+ }
594
+ }
595
+
596
+ /**
597
+ * Joiner-consent pre-check — the legibility twin of the schema's
598
+ * `FormationUsage.PeerConsented` CHECK, exactly as `verifyFormationApproval` is for the
599
+ * approver's vouch. The database constraint stays the authority; this turns a bad consent
600
+ * into a clean 'Invalid joiner consent' rejection instead of an opaque CHECK failure at
601
+ * commit. Runs BEFORE token/disclosure validation: it is the cheapest check (pure local
602
+ * crypto, no DB read) and a rejection discloses nothing.
603
+ *
604
+ * Also pins `partyId` to `peerKey`: an ed25519 peer id is an identity multihash of the
605
+ * very key, and this is the ONLY layer that can check the match — SQL cannot unwrap a
606
+ * multihash, and `partyId` itself is never stored.
607
+ */
608
+ private isJoinerConsentValid(id: number, contact: FormationContactMessage): boolean {
609
+ try {
610
+ requireEd25519PublicKeyB64(contact.peerKey, 'joiner peer key');
611
+ } catch {
612
+ // Deliberately not rethrown or echoed: the helper's error message embeds the whole
613
+ // rejected value, and this one arrived from a remote peer (the cap-the-echo case its
614
+ // own NOTE warns about). Log without the raw value instead.
615
+ log('formation session #%d: joiner peer key is not a base64url ed25519 public key', id);
616
+ return false;
617
+ }
618
+ const embedded = ed25519PublicKeyB64FromPeerId(contact.partyId);
619
+ if (!embedded || embedded !== contact.peerKey) {
620
+ log('formation session #%d: partyId does not embed the presented peer key', id);
621
+ return false;
622
+ }
623
+ const consentOk = verifyFormationConsent({
624
+ token: contact.token,
625
+ usageStampId: contact.usageStampId,
626
+ peerKey: contact.peerKey,
627
+ disclosure: canonicalJson(contact.disclosure),
628
+ peerSig: contact.peerSignature
629
+ });
630
+ if (!consentOk) {
631
+ log('formation session #%d: joiner consent signature failed verification', id);
632
+ return false;
633
+ }
634
+ return true;
635
+ }
636
+
637
+ /**
638
+ * The strand addresses to disclose for an APPROVED provisioning, sanitized and capped.
639
+ *
640
+ * Never throws: a hook that fails (a strand runtime torn down mid-session) costs the
641
+ * joiner its cross-party seed, not the formation it has already earned — the seed is
642
+ * an optimization, the consent row is the commitment.
643
+ */
644
+ private strandAddrsFor(id: number, strandId: string): string[] {
645
+ if (!this.options.resolveStrandAddrs) return [];
646
+ try {
647
+ return sanitizeStrandAddrs(this.options.resolveStrandAddrs(strandId));
648
+ } catch (err) {
649
+ log('formation session #%d: strand-addr lookup for %s failed (continuing): %o', id, strandId, err);
650
+ return [];
651
+ }
652
+ }
653
+
654
+ private async runSession(id: number, stream: ControlStream): Promise<void> {
655
+ // Track whether ANY frame has been written so the catch below can convert an
656
+ // unexpected internal error into a non-disclosing rejection ONLY when nothing has
657
+ // gone out yet. This closes the "stream closed with no result frame" class of bug.
658
+ let wroteFrame = false;
659
+ const send = (msg: FormationRejection | ApprovedResultMessage): void => {
660
+ writeFrame(stream, msg);
661
+ wroteFrame = true;
662
+ };
663
+
664
+ try {
665
+ const reader = new FrameReader(stream);
666
+ const contact = await withTimeout(this.awaitContactMs, `Formation await-contact#${id}`, () => reader.read<FormationContactMessage>());
667
+ log('formation session #%d contact: token=%s party=%s', id, contact.token, contact.partyId);
668
+
669
+ if (!this.isJoinerConsentValid(id, contact)) {
670
+ send({ approved: false, code: 'consent-invalid', reason: 'Invalid joiner consent' });
671
+ return;
672
+ }
673
+
674
+ const tokenResult = await this.options.validateToken(contact.token);
675
+ if (!tokenResult.valid) {
676
+ send({ approved: false, code: tokenResult.code, reason: INVALID_TOKEN_REASON });
677
+ return;
678
+ }
679
+
680
+ const disclosureOk = await this.options.validateDisclosure(contact.token, contact.disclosure);
681
+ if (!disclosureOk) {
682
+ send({ approved: false, code: 'disclosure-invalid', reason: 'Invalid disclosure' });
683
+ return;
684
+ }
685
+
686
+ const outcome = await this.provision(id, contact, tokenResult.read);
687
+ if (!outcome) {
688
+ // Reported as its own retryable reason rather than falling through to the generic
689
+ // catch below, which would report the misleading 'Internal formation error'.
690
+ send({ approved: false, code: 'provisioning-timeout', reason: 'Formation provisioning timed out' });
691
+ return;
692
+ }
693
+ if (!outcome.approved) {
694
+ // A post-validation rejection still discloses NEITHER identity NOR cadre, exactly
695
+ // like the token/disclosure rejections above — copied field by field so nothing else
696
+ // a hook put on its outcome reaches the wire.
697
+ send({ approved: false, code: outcome.code, reason: outcome.reason });
698
+ return;
699
+ }
700
+ // Validation + provisioning passed → safe to disclose responder identity/cadre.
701
+ const identity = this.options.getResponderIdentity();
702
+ const strandAddrs = this.strandAddrsFor(id, outcome.result.strand.strandId);
703
+ send({
704
+ approved: true,
705
+ partyId: identity.partyId,
706
+ cadrePeerAddrs: identity.cadrePeerAddrs,
707
+ // Omitted rather than sent empty: an absent field and an empty list mean the same
708
+ // thing to the initiator, and omitting keeps every rejection-parity assertion a
709
+ // plain `toBeUndefined()`.
710
+ ...(strandAddrs.length > 0 ? { strandAddrs } : {}),
711
+ provisionResult: outcome.result
712
+ });
713
+ } catch (err) {
714
+ // Defense-in-depth: if an unexpected internal error escapes BEFORE any frame was
715
+ // written (e.g. a future provisionStrand-hook bug), convert it into a non-disclosing
716
+ // protocol rejection so the initiator sees a clean error instead of a read-error/
717
+ // timeout. If a frame was already sent, leave the stream as-is and let handleStream
718
+ // log + close. Re-throw either way so the failure is still recorded — this is a
719
+ // deliberate, logged conversion, not silent.
720
+ if (!wroteFrame) {
721
+ const internalError: FormationRejection = { approved: false, code: 'internal', reason: 'Internal formation error' };
722
+ try { writeFrame(stream, internalError); } catch { /* stream already broken */ }
723
+ }
724
+ throw err;
725
+ }
726
+ }
727
+ }
728
+
729
+ // ── Initiator (dialer) ───────────────────────────────────────────────────────
730
+
731
+ export interface FormationDialOptions {
732
+ /** The contact message to send (real token, partyId, disclosure, initiator cadre). */
733
+ contact: FormationContactMessage;
734
+ /**
735
+ * Responder multiaddrs to dial, normally the invitation's bootstrap list. Every entry that
736
+ * parses is tried, in the order libp2p's default address sorter picks (loopback last, then
737
+ * public before private, then circuit after direct), until one connects, all under one
738
+ * dial-connect budget (`dialTimeoutMs`); an entry that does not parse is skipped.
739
+ *
740
+ * {@link dialFormation} dials ONE machine, so every entry must name the same trailing peer
741
+ * id (or none). An invitation names several machines of the inviting party; hand it to
742
+ * {@link dialFormationByMachine}, which splits the list by trailing peer id, drops entries
743
+ * that name no peer, and runs one {@link dialFormation} session per machine, in the order
744
+ * each machine first appears. Each session keeps its own deadline ladder, so a machine that
745
+ * cannot be dialled costs one `dialTimeoutMs` and one that accepts the contact and then
746
+ * stalls costs up to one `sessionTimeoutMs`; `CadreNode.createOpenInvitation` names at most
747
+ * four machines.
748
+ */
749
+ responderAddrs: string[];
750
+ /** Validate the responder's result; a false return aborts the formation. */
751
+ validateResponse(response: FormationResultMessage): Promise<boolean>;
752
+ /**
753
+ * This machine's declared link round trip (`NetworkConfig.linkRoundTripMs`), from which
754
+ * every deadline below takes its default ({@link formationDeadlines}). The default
755
+ * declaration when omitted.
756
+ */
757
+ linkRoundTripMs?: number;
758
+ /** Whole-session budget; default `sessionMs` of the derived ladder. */
759
+ sessionTimeoutMs?: number;
760
+ /**
761
+ * Budget for `dial-connect`: opening the connection, through a relay if need be, and
762
+ * negotiating the formation protocol. Default `dialMs` of the derived ladder.
763
+ */
764
+ dialTimeoutMs?: number;
765
+ /**
766
+ * Budget for the `await-response` read only (the responder's provisioning plus the reply's
767
+ * travel time). Default `initiatorAwaitResponseMs` of the derived ladder; `0`/unset uses
768
+ * the default; a value that would outlive the session is clamped. See
769
+ * {@link formationDeadlines} for the ordering.
770
+ */
771
+ provisionTimeoutMs?: number;
772
+ protocolId?: string;
773
+ }
774
+
775
+ /**
776
+ * What one successful formation dial yields the initiator.
777
+ *
778
+ * The provisioned strand travels in {@link FormationProvisionResult}, but the responder's
779
+ * strand-network addresses are NOT part of that structure — they are a disclosure of the
780
+ * responder's live runtime, alongside `partyId`/`cadrePeerAddrs`, not a property of the
781
+ * strand row. Returning them beside the provision result keeps that separation while
782
+ * still handing the caller the one thing it needs to seed a cross-party mesh.
783
+ *
784
+ * `strandAddrs` is always an array and is frequently EMPTY — see
785
+ * {@link FormationResultMessage.strandAddrs}.
786
+ */
787
+ export interface FormationDialResult {
788
+ provision: FormationProvisionResult;
789
+ /** Sanitized + capped ({@link sanitizeStrandAddrs}); `[]` when the responder sent none. */
790
+ strandAddrs: string[];
791
+ }
792
+
793
+ /** The formation stream and the connection it runs on. */
794
+ interface FormationChannel {
795
+ stream: ControlStream;
796
+ connection: Connection;
797
+ }
798
+
799
+ /**
800
+ * Connections a formation dial opened, each with the number of formation exchanges still using
801
+ * it; the entry is dropped when the last one finishes and closes the connection
802
+ * ({@link releaseFormationConnection}). A connection the node already held when its dial started
803
+ * is never entered, so formation never closes someone else's connection.
804
+ *
805
+ * Counted per connection rather than per dial: two formations to one responder machine at once
806
+ * (two pending joins on invitations from one inviter) share the connection libp2p's dial queue
807
+ * opened for the first, and the first to finish must leave it to the second.
808
+ */
809
+ const formationConnectionUsers = new WeakMap<Connection, number>();
810
+
811
+ /**
812
+ * Open the formation stream under the dial deadline, cancelling the dial when it expires.
813
+ *
814
+ * The deadline's signal goes into the dial and the stream negotiation, so an expired dial is
815
+ * abandoned by libp2p rather than left running. A dial that settles in the same tick the
816
+ * deadline fires loses the race to the timeout rejection and would leave its stream open with
817
+ * nobody to close it, so a channel that arrives after the signal aborted is reset here, and its
818
+ * connection released — the same treatment `exchangeFrame` (`control-stream.ts`) gives a stream
819
+ * dialed past its deadline. A late rejection is the abort itself, or reaches the caller through
820
+ * the awaited copy, so the handler below only stops it being reported as unhandled.
821
+ *
822
+ * NOTE: libp2p tries `addrs` one after another, and they all share this one dial budget — so
823
+ * ONE address that hangs without answering costs the whole budget, and the join moves on to the
824
+ * party's next machine ({@link dialFormationByMachine}) rather than to this machine's next
825
+ * address. (Its per-address limit, `addressDialTimeout` — ten link round trips plus two
826
+ * admission decisions, as `optimysticDialLimits` states it — is longer than `dialTimeoutMs`
827
+ * (`formationDeadlines().dialMs`: five round trips plus one decision) at every declaration, so
828
+ * it never cuts an address off inside this dial. An address that is REFUSED fails fast and
829
+ * hands over to the next one normally.)
830
+ *
831
+ * The WebRTC case of that is handled: {@link withoutWebrtcAddrs} drops an address whose
832
+ * connection waits on ICE before the list gets here. What is NOT handled is a black-holed relay
833
+ * host — a relayed address whose relay accepts the TCP connection and then answers nothing. Such
834
+ * an address still takes the whole budget and the join never reaches this machine's other
835
+ * relays. A budget per address here would overrun the session or shrink the await-response
836
+ * budget ({@link formationDeadlines}), so the remedy, if that is seen in practice, is to dial the
837
+ * addresses in parallel or give each its own sub-budget carved out of this one. The same dial
838
+ * can also be joined to another dial of the responder in flight (the queue keys jobs by peer id
839
+ * — see `peer-dial.ts` → `dialAddr`), which then holds this one on that job's address; same
840
+ * remedy.
841
+ */
842
+ function openFormationStream(node: Libp2p, addrs: Multiaddr[], protocolId: string, dialTimeoutMs: number): Promise<FormationChannel> {
843
+ return withDeadline(dialTimeoutMs, 'Formation dial-connect', async (signal) => {
844
+ const pending = dialFormationChannel(node, addrs, protocolId, signal);
845
+ void pending.then(
846
+ (channel) => {
847
+ if (signal.aborted) abandonLateChannel(channel);
848
+ },
849
+ () => { /* surfaced through the awaited copy, or the abort itself */ }
850
+ );
851
+ try {
852
+ return await pending;
853
+ } catch (error) {
854
+ throw describeAllAddressesFailed(error);
855
+ }
856
+ });
857
+ }
858
+
859
+ /**
860
+ * Dial the responder machine, then open the formation stream on the connection. The ids of the
861
+ * node's connections are read before the dial: a connection not among them was opened by this
862
+ * dial (or by another formation dial it was joined to), and is closed when formation is done
863
+ * with it. A stream that cannot be opened releases the connection at once.
864
+ *
865
+ * NOTE: a dial of the responder that something other than formation started, and this dial was
866
+ * joined to, also counts as opened by formation and is closed afterwards. Nothing else dials an
867
+ * inviter's control node before formation does; if something starts to, tell the two apart by
868
+ * the connection's own opening time rather than by this snapshot.
869
+ */
870
+ async function dialFormationChannel(node: Libp2p, addrs: Multiaddr[], protocolId: string, signal: AbortSignal): Promise<FormationChannel> {
871
+ const heldBefore = new Set(node.getConnections().map((connection) => connection.id));
872
+ const connection = await node.dial(withoutWebrtcAddrs(addrs), { signal });
873
+ useFormationConnection(connection, heldBefore.has(connection.id));
874
+ try {
875
+ signal.throwIfAborted();
876
+ const stream = await connection.newStream(protocolId, { signal });
877
+ return { stream: stream as unknown as ControlStream, connection };
878
+ } catch (error) {
879
+ void releaseFormationConnection(connection);
880
+ throw error;
881
+ }
882
+ }
883
+
884
+ /**
885
+ * `addrs` without the ones that need a WebRTC session after the relay hop (`peer-dial.ts` →
886
+ * {@link addrKind}), unless they are all there is.
887
+ *
888
+ * Formation needs ONE stream and somebody is waiting on it, so it dials relayed
889
+ * (`docs/network/relay.md` → "Direct connections over WebRTC"); the bulk strand traffic is what
890
+ * a direct connection is worth having for, and the strand nodes negotiate that separately. A
891
+ * responder that listens on `/webrtc` publishes two addresses per relay — the plain relayed one
892
+ * and a WebRTC one signalled through the same relay — and where ICE cannot connect between the
893
+ * two networks the WebRTC one answers nothing for about 23 s, longer than the whole dial budget
894
+ * (gotchoices/sereus#61).
895
+ *
896
+ * The addresses are FILTERED rather than reordered because libp2p re-sorts whatever list it is
897
+ * given (`defaultAddressSorter`), and its `circuitRelayAddressesLast` recognises only an exact
898
+ * `Circuit` match — so it would put the WebRTC address back in front of the relayed one.
899
+ *
900
+ * A responder whose every address is a WebRTC one keeps them: filtering would leave nothing to
901
+ * dial, and an ICE path that does exist (two machines on one network) still forms the strand.
902
+ */
903
+ function withoutWebrtcAddrs(addrs: Multiaddr[]): Multiaddr[] {
904
+ const dialable = addrs.filter((addr) => addrKind(addr) !== 'webrtc');
905
+ if (dialable.length === 0) {
906
+ return addrs;
907
+ }
908
+ if (dialable.length < addrs.length) {
909
+ log('formation dial: leaving out %d WebRTC address(es); a relayed address is what the join waits on', addrs.length - dialable.length);
910
+ }
911
+ return dialable;
912
+ }
913
+
914
+ function abandonLateChannel({ stream, connection }: FormationChannel): void {
915
+ stream.abort(new Error('Formation dial-connect resolved after its deadline'));
916
+ void releaseFormationConnection(connection);
917
+ }
918
+
919
+ /**
920
+ * Count one more formation exchange on `connection` when a formation dial opened it — this one
921
+ * (`heldBefore` false) or an earlier one still using it.
922
+ */
923
+ function useFormationConnection(connection: Connection, heldBefore: boolean): void {
924
+ const users = formationConnectionUsers.get(connection);
925
+ if (users !== undefined) formationConnectionUsers.set(connection, users + 1);
926
+ else if (!heldBefore) formationConnectionUsers.set(connection, 1);
927
+ }
928
+
929
+ /**
930
+ * End one formation exchange's use of `connection`, closing it when a formation dial opened it
931
+ * and no other exchange still uses it. Never throws.
932
+ *
933
+ * Only the joiner closes: it opened the connection, so it is the side that knows the connection
934
+ * did not exist before. The joiner's and the inviter's control nodes run on different FRET
935
+ * networks, so a connection left open after formation carries nothing but FRET pings that fail,
936
+ * until FRET has been refused three times and leaves that peer alone (p2p-fret 1.2.1). FRET can
937
+ * still redial the other control node on its own while it re-probes a peer it has seen
938
+ * (`complete/fret-maintenance-probes-peers-off-its-ring`).
939
+ *
940
+ * The close is graceful, so the responder's side can finish its own stream close; a close that
941
+ * fails or overruns libp2p's close timeout is logged and the connection aborted, as libp2p's own
942
+ * `hangUp` does. When the responder is a machine of the joiner's own party the connection
943
+ * normally pre-exists (the cadre mesh) and is left alone; if this dial opened it, it is closed,
944
+ * and the mesh re-dials that sibling as after any dropped connection.
945
+ */
946
+ async function releaseFormationConnection(connection: Connection): Promise<void> {
947
+ const users = formationConnectionUsers.get(connection);
948
+ if (users === undefined) return;
949
+ if (users > 1) {
950
+ formationConnectionUsers.set(connection, users - 1);
951
+ return;
952
+ }
953
+ formationConnectionUsers.delete(connection);
954
+ try {
955
+ await connection.close();
956
+ } catch (error) {
957
+ log('closing the formation connection to %s failed; aborting it: %o', connection.remotePeer.toString(), error);
958
+ connection.abort(toError(error));
959
+ }
960
+ }
961
+
962
+ const NO_RESPONDER_ADDRS = 'No responder addresses available for formation';
963
+
964
+ /**
965
+ * Parse the responder addresses, skipping any entry that does not parse: the list comes from
966
+ * a stranger's invitation, and one bad entry must not fail an otherwise good list. Entries
967
+ * naming different peers are left for libp2p to refuse; {@link dialFormationByMachine} hands
968
+ * this one machine's addresses at a time.
969
+ */
970
+ function parseResponderAddrs(addrs: string[]): Multiaddr[] {
971
+ const parsed: Multiaddr[] = [];
972
+ for (const addr of addrs) {
973
+ const ma = parseResponderAddr(addr);
974
+ if (ma) parsed.push(ma);
975
+ }
976
+ if (parsed.length === 0) {
977
+ throw new FormationUnreachableError(NO_RESPONDER_ADDRS);
978
+ }
979
+ return parsed;
980
+ }
981
+
982
+ function parseResponderAddr(addr: string): Multiaddr | null {
983
+ try {
984
+ return multiaddr(addr);
985
+ } catch (error) {
986
+ log('responderAddrs: skipping unparsable entry: %o', error);
987
+ return null;
988
+ }
989
+ }
990
+
991
+ /** One machine of the inviting party, and the invitation's addresses for it. */
992
+ interface ResponderMachine {
993
+ peerId: string;
994
+ addrs: string[];
995
+ }
996
+
997
+ /**
998
+ * Split the responder addresses by the machine each reaches (its trailing peer id), keeping
999
+ * the order in which each machine first appears. An entry that does not parse, or names no
1000
+ * peer, is dropped: every address an inviter mints (`getMultiaddrs()`, `resolvePeerAddrs`)
1001
+ * names its machine, and libp2p refuses one dial that mixes named and unnamed addresses.
1002
+ */
1003
+ function groupResponderAddrsByMachine(addrs: string[]): ResponderMachine[] {
1004
+ const machines = new Map<string, string[]>();
1005
+ for (const addr of addrs) {
1006
+ const ma = parseResponderAddr(addr);
1007
+ if (!ma) continue;
1008
+ const peerId = trailingPeerId(ma);
1009
+ if (!peerId) {
1010
+ log('responderAddrs: skipping %s — it names no machine', addr);
1011
+ continue;
1012
+ }
1013
+ const group = machines.get(peerId);
1014
+ if (group) group.push(addr);
1015
+ else machines.set(peerId, [addr]);
1016
+ }
1017
+ return [...machines].map(([peerId, group]) => ({ peerId, addrs: group }));
1018
+ }
1019
+
1020
+ /**
1021
+ * Worth asking the next machine of the inviting party: it could not be reached, or it answered
1022
+ * with a refusal a sibling may not repeat (the invitation not replicated to it yet, the host
1023
+ * strand not running there, …). A final refusal is the party's answer, not one machine's.
1024
+ */
1025
+ function shouldTryNextMachine(error: unknown): error is FormationUnreachableError | FormationRejectedError {
1026
+ return error instanceof FormationUnreachableError || (error instanceof FormationRejectedError && error.retryable);
1027
+ }
1028
+
1029
+ /**
1030
+ * Every machine failed without a refusal. A single machine's error already names each address
1031
+ * it tried, so it is thrown as is; several are restated as one error naming each machine.
1032
+ */
1033
+ function noMachineReached(failures: Array<{ peerId: string; error: FormationUnreachableError }>): FormationUnreachableError {
1034
+ if (failures.length === 1) return failures[0].error;
1035
+ const errors = failures.map((failure) => failure.error);
1036
+ return new FormationUnreachableError(
1037
+ `Formation could not reach any of the inviter's ${failures.length} machines: ` +
1038
+ failures.map((failure) => `${failure.peerId}: ${failure.error.message}`).join('; '),
1039
+ { cause: new AggregateError(errors, 'Every inviting machine was unreachable') }
1040
+ );
1041
+ }
1042
+
1043
+ /**
1044
+ * libp2p reports a dial in which every address failed as `AggregateError('All multiaddr dials
1045
+ * failed')`, which names none of them; restate it with each address's own error, which names
1046
+ * its host and port. A dial that tried only one address already surfaces that address's own
1047
+ * error, so anything else passes through unchanged.
1048
+ */
1049
+ function describeAllAddressesFailed(error: unknown): unknown {
1050
+ if (!(error instanceof AggregateError)) return error;
1051
+ const reasons = error.errors.map(describeThrown);
1052
+ return new FormationUnreachableError(
1053
+ `Formation could not reach the inviter at any of the ${reasons.length} addresses tried: ${reasons.join('; ')}`,
1054
+ { cause: error }
1055
+ );
1056
+ }
1057
+
1058
+ /** Report a failure that came before any answer as {@link FormationUnreachableError}, keeping its message. */
1059
+ function asUnreachable(error: unknown): FormationUnreachableError {
1060
+ if (error instanceof FormationUnreachableError) return error;
1061
+ return new FormationUnreachableError(describeThrown(error), { cause: error });
1062
+ }
1063
+
1064
+ /**
1065
+ * Open the formation stream, send the contact, and read back the one result frame, closing
1066
+ * the stream either way. Nothing here has an answer from the responder yet, so the caller
1067
+ * reports any failure as {@link FormationUnreachableError} — a frame too large or not JSON
1068
+ * included, since it is not an answer either.
1069
+ */
1070
+ async function exchangeContact(
1071
+ node: Libp2p,
1072
+ addrs: Multiaddr[],
1073
+ contact: FormationContactMessage,
1074
+ budgets: { protocolId: string; dialTimeoutMs: number; awaitResponseMs: number }
1075
+ ): Promise<FormationResultMessage> {
1076
+ const { stream, connection } = await openFormationStream(node, addrs, budgets.protocolId, budgets.dialTimeoutMs);
1077
+ try {
1078
+ const reader = new FrameReader(stream);
1079
+ writeFrame(stream, contact);
1080
+ return await withTimeout(budgets.awaitResponseMs, 'Formation await-response', () => reader.read<FormationResultMessage>());
1081
+ } finally {
1082
+ try { await stream.close(); } catch { /* ignore */ }
1083
+ void releaseFormationConnection(connection);
1084
+ }
1085
+ }
1086
+
1087
+ /**
1088
+ * Turn the responder's answer into the dial's result. A refusal throws
1089
+ * {@link FormationRejectedError}; an approval that fails validation throws a plain `Error`,
1090
+ * since that is a misbehaving responder rather than a refusal.
1091
+ */
1092
+ async function acceptResult(
1093
+ response: FormationResultMessage,
1094
+ validateResponse: FormationDialOptions['validateResponse']
1095
+ ): Promise<FormationDialResult> {
1096
+ if (!response.approved) {
1097
+ throw new FormationRejectedError(response.code, response.reason);
1098
+ }
1099
+ if (!(await validateResponse(response))) throw new Error('Responder result failed validation');
1100
+
1101
+ if (!response.provisionResult) throw new Error('Missing provision result for responderCreates mode');
1102
+ // Sanitized HERE — the wire boundary — so nothing above this call ever handles an
1103
+ // unvalidated, unbounded address list from a remote peer.
1104
+ return { provision: response.provisionResult, strandAddrs: sanitizeStrandAddrs(response.strandAddrs) };
1105
+ }
1106
+
1107
+ /**
1108
+ * Initiator side of the native formation protocol. Dials the responder, sends the
1109
+ * contact (carrying the real disclosure/token/cadre), validates the responder's
1110
+ * result, and returns the strand the responder provisioned plus the responder's
1111
+ * strand-network addresses (see {@link FormationDialResult}).
1112
+ *
1113
+ * Throws {@link FormationUnreachableError} for every failure before a result frame is read
1114
+ * (including the session deadline passing first), {@link FormationRejectedError} when the
1115
+ * responder refuses, and a plain `Error` for an approval that fails validation.
1116
+ */
1117
+ export async function dialFormation(node: Libp2p, options: FormationDialOptions): Promise<FormationDialResult> {
1118
+ const addrs = parseResponderAddrs(options.responderAddrs);
1119
+ const protocolId = options.protocolId ?? FORMATION_PROTOCOL;
1120
+ const deadlines = formationDeadlines(options.linkRoundTripMs);
1121
+ const sessionTimeoutMs = options.sessionTimeoutMs ?? deadlines.sessionMs;
1122
+ const dialTimeoutMs = options.dialTimeoutMs ?? deadlines.dialMs;
1123
+ const awaitResponseMs = resolveProvisionTimeoutMs(
1124
+ options.provisionTimeoutMs, deadlines.initiatorAwaitResponseMs,
1125
+ sessionTimeoutMs, dialTimeoutMs, 'dialFormation'
1126
+ );
1127
+
1128
+ let answered = false;
1129
+ try {
1130
+ return await withTimeout(sessionTimeoutMs, 'Formation dial', async () => {
1131
+ const response = await exchangeContact(node, addrs, options.contact, { protocolId, dialTimeoutMs, awaitResponseMs });
1132
+ answered = true;
1133
+ return await acceptResult(response, options.validateResponse);
1134
+ });
1135
+ } catch (error) {
1136
+ throw answered ? error : asUnreachable(error);
1137
+ }
1138
+ }
1139
+
1140
+ /**
1141
+ * Initiator side for a whole invitation: one {@link dialFormation} session per machine of the
1142
+ * inviting party the bootstrap list names (see {@link FormationDialOptions.responderAddrs}), in
1143
+ * order, until one approves.
1144
+ *
1145
+ * A machine that cannot be reached, or that refuses retryably, hands over to the next. A final
1146
+ * refusal, or an approval that fails validation, is thrown at once: another machine of the
1147
+ * same party would answer the same, and an approval may already have spent the invitation.
1148
+ * With no machine left, throws the last retryable refusal when any machine answered (the party
1149
+ * is reachable but not ready, which says more than "unreachable"), otherwise one
1150
+ * {@link FormationUnreachableError} naming each machine's failure.
1151
+ *
1152
+ * Every session sends the SAME contact. `FormationUsage` is keyed by the contact's
1153
+ * `usageStampId`, so at most one machine of the inviting party can record this redemption,
1154
+ * even when one the joiner gave up on was still committing it.
1155
+ */
1156
+ export async function dialFormationByMachine(node: Libp2p, options: FormationDialOptions): Promise<FormationDialResult> {
1157
+ const machines = groupResponderAddrsByMachine(options.responderAddrs);
1158
+ if (machines.length === 0) {
1159
+ throw new FormationUnreachableError(NO_RESPONDER_ADDRS);
1160
+ }
1161
+ const unreached: Array<{ peerId: string; error: FormationUnreachableError }> = [];
1162
+ let refusal: FormationRejectedError | undefined;
1163
+ for (const machine of machines) {
1164
+ try {
1165
+ return await dialFormation(node, { ...options, responderAddrs: machine.addrs });
1166
+ } catch (error) {
1167
+ if (!shouldTryNextMachine(error)) throw error;
1168
+ log('formation via %s failed (%s), trying the next inviting machine', machine.peerId, error.message);
1169
+ if (error instanceof FormationRejectedError) refusal = error;
1170
+ else unreached.push({ peerId: machine.peerId, error });
1171
+ }
1172
+ }
1173
+ throw refusal ?? noMachineReached(unreached);
1174
+ }