@serfab/cadre-core 0.12.0 → 0.13.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 (86) hide show
  1. package/README.md +3 -2
  2. package/dist/cadre-node.d.ts +328 -25
  3. package/dist/cadre-node.js +760 -59
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-database.d.ts +19 -0
  6. package/dist/control-database.js +51 -9
  7. package/dist/control-database.js.map +1 -1
  8. package/dist/control-schema.d.ts +1 -1
  9. package/dist/control-schema.js +30 -2
  10. package/dist/control-schema.js.map +1 -1
  11. package/dist/enrolled-machine-store-file.d.ts +13 -0
  12. package/dist/enrolled-machine-store-file.js +41 -0
  13. package/dist/enrolled-machine-store-file.js.map +1 -0
  14. package/dist/enrolled-machine-store.d.ts +81 -0
  15. package/dist/enrolled-machine-store.js +225 -0
  16. package/dist/enrolled-machine-store.js.map +1 -0
  17. package/dist/file-durable-slot.js +5 -3
  18. package/dist/file-durable-slot.js.map +1 -1
  19. package/dist/index.d.ts +5 -3
  20. package/dist/index.js +23 -5
  21. package/dist/index.js.map +1 -1
  22. package/dist/membership-connection-gater.d.ts +15 -1
  23. package/dist/membership-connection-gater.js +9 -3
  24. package/dist/membership-connection-gater.js.map +1 -1
  25. package/dist/node-local-snapshot.d.ts +6 -0
  26. package/dist/node-local-snapshot.js +7 -1
  27. package/dist/node-local-snapshot.js.map +1 -1
  28. package/dist/{strand-backfill.d.ts → peer-join-backfill.d.ts} +49 -20
  29. package/dist/{strand-backfill.js → peer-join-backfill.js} +133 -52
  30. package/dist/peer-join-backfill.js.map +1 -0
  31. package/dist/relay-addrs.d.ts +73 -0
  32. package/dist/relay-addrs.js +195 -0
  33. package/dist/relay-addrs.js.map +1 -1
  34. package/dist/strand-database.d.ts +12 -0
  35. package/dist/strand-database.js +16 -0
  36. package/dist/strand-database.js.map +1 -1
  37. package/dist/strand-formation-manager.d.ts +12 -0
  38. package/dist/strand-formation-manager.js +10 -3
  39. package/dist/strand-formation-manager.js.map +1 -1
  40. package/dist/strand-formation-protocol.d.ts +76 -2
  41. package/dist/strand-formation-protocol.js +78 -2
  42. package/dist/strand-formation-protocol.js.map +1 -1
  43. package/dist/strand-instance-manager.d.ts +147 -14
  44. package/dist/strand-instance-manager.js +225 -45
  45. package/dist/strand-instance-manager.js.map +1 -1
  46. package/dist/strand-membership-writer.d.ts +12 -0
  47. package/dist/strand-membership-writer.js +23 -1
  48. package/dist/strand-membership-writer.js.map +1 -1
  49. package/dist/strand-network-config.d.ts +84 -0
  50. package/dist/strand-network-config.js +136 -0
  51. package/dist/strand-network-config.js.map +1 -0
  52. package/dist/strand-revocation-enforcer.d.ts +392 -0
  53. package/dist/strand-revocation-enforcer.js +533 -0
  54. package/dist/strand-revocation-enforcer.js.map +1 -0
  55. package/dist/strand-solicitation.d.ts +7 -0
  56. package/dist/strand-solicitation.js +8 -2
  57. package/dist/strand-solicitation.js.map +1 -1
  58. package/dist/strand-watcher.js +6 -1
  59. package/dist/strand-watcher.js.map +1 -1
  60. package/dist/types.d.ts +210 -16
  61. package/dist/types.js +7 -1
  62. package/dist/types.js.map +1 -1
  63. package/package.json +16 -8
  64. package/src/cadre-node.ts +6353 -5603
  65. package/src/control-database.ts +53 -9
  66. package/src/control-schema.ts +30 -2
  67. package/src/enrolled-machine-store-file.ts +43 -0
  68. package/src/enrolled-machine-store.ts +280 -0
  69. package/src/file-durable-slot.ts +5 -3
  70. package/src/index.ts +52 -10
  71. package/src/membership-connection-gater.ts +9 -3
  72. package/src/node-local-snapshot.ts +13 -1
  73. package/src/peer-addr-book.ts +251 -250
  74. package/src/{strand-backfill.ts → peer-join-backfill.ts} +478 -389
  75. package/src/relay-addrs.ts +218 -0
  76. package/src/strand-database.ts +17 -0
  77. package/src/strand-formation-manager.ts +22 -3
  78. package/src/strand-formation-protocol.ts +808 -692
  79. package/src/strand-instance-manager.ts +317 -54
  80. package/src/strand-membership-writer.ts +23 -1
  81. package/src/strand-network-config.ts +172 -0
  82. package/src/strand-revocation-enforcer.ts +653 -0
  83. package/src/strand-solicitation.ts +484 -471
  84. package/src/strand-watcher.ts +319 -314
  85. package/src/types.ts +1554 -1354
  86. package/dist/strand-backfill.js.map +0 -1
@@ -1,692 +1,808 @@
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 } from '@multiformats/multiaddr';
23
- import type { Libp2p } from '@libp2p/interface';
24
- import type { StrandFormationDisclosure } from './types.js';
25
- import { type ControlStream, writeFrame, 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 './seed-bootstrap.js';
32
-
33
- const log = debug('sereus:cadre:formation-proto');
34
-
35
- /** Protocol id for the native formation transport (parallel to `/sereus/seed/1.0.0`). */
36
- export const FORMATION_PROTOCOL = '/sereus/formation/1.0.0';
37
-
38
- /**
39
- * Rejection reason for an invitation that cannot be redeemed at all — unknown, expired, or
40
- * fully spent. Shared with `StrandFormationManager`, which reports an
41
- * `InvitationExhaustedError` (an invite spent out from under a redemption already in flight)
42
- * with this SAME wording on purpose: a joiner that lost the race must be indistinguishable
43
- * from a non-racing latecomer, so the two sites must never drift apart.
44
- */
45
- export const INVALID_TOKEN_REASON = 'Invalid token';
46
-
47
- /** Maximum formation message size (1MB). */
48
- const MAX_FORMATION_MSG_SIZE = 1024 * 1024;
49
-
50
- /** Default whole-session timeout (ms). */
51
- const DEFAULT_SESSION_TIMEOUT_MS = 30_000;
52
- /** Default per-step (single read/write) timeout (ms). */
53
- const DEFAULT_STEP_TIMEOUT_MS = 5_000;
54
- /**
55
- * Default provisioning budget (ms) — distinct from {@link DEFAULT_STEP_TIMEOUT_MS} because
56
- * `provisionStrand` is real work (DB writes, and an outbound approval-hook HTTP call when
57
- * the invite carries a `ValidationUrl`), not a bare wire read/write.
58
- *
59
- * Ordering is deliberate — each layer must be able to fail and report before the layer above
60
- * it gives up:
61
- *
62
- * approval hook (10 s, `formation-approval.ts`)
63
- * < responder provisioning (12 s)
64
- * < initiator await-response (15 s)
65
- * < session (30 s)
66
- *
67
- * The 3 s margin between responder provisioning and initiator await-response is the wire
68
- * latency budget for the result frame to travel back.
69
- *
70
- * The last {@link PROVISION_SETTLE_GRACE_MS} of this budget is a settle grace, so the default
71
- * WORK budget (12 s − 2 s = 10 s) EQUALS the hook's own 10 s: a dead hook races 'Formation
72
- * approval unavailable, retry' against 'Formation provisioning timed out'. Both are retryable
73
- * and both leave the invite unspent, so the race is benign.
74
- */
75
- const DEFAULT_PROVISION_TIMEOUT_MS = 12_000;
76
- /**
77
- * Settle grace (ms), carved OUT of `provisionTimeoutMs` — never added on top, so the budget
78
- * ladder above is untouched. The listener aborts the provisioning hook when the work budget
79
- * ({@link splitProvisionBudget}) expires, then waits up to this grace for the work to settle
80
- * anyway: once the `FormationUsage` insert has been issued nothing can un-spend it (the table
81
- * is append-only), so a provisioning that lands late is ADOPTED and reported as a real
82
- * approval rather than lying "timed out" over a spent invite. A hook that observes the
83
- * abort before writing leaves the invite unspent.
84
- */
85
- const PROVISION_SETTLE_GRACE_MS = 2_000;
86
- /**
87
- * Wire-latency margin (ms) added to the responder's provisioning budget to get the
88
- * initiator's await-response budget — the travel time for the result frame to come back
89
- * after the responder finishes (see {@link DEFAULT_PROVISION_TIMEOUT_MS}).
90
- * `StrandFormationManager` reuses this constant so a CONFIGURED budget preserves the same
91
- * margin the defaults do, instead of applying the same number to both sides and racing the
92
- * initiator's own timeout against the responder's clean rejection reply. The responder's
93
- * clamp ({@link provisionCeilingMs}) holds the same margin back, so the ordering survives a
94
- * budget large enough that BOTH roles get clamped.
95
- *
96
- * NOTE: 3 s is a fixed assumption about how long the result frame takes to travel back. If
97
- * formation ever runs over paths where that frame can take longer (a slow circuit relay, a
98
- * congested mobile link), the margin is too thin and the initiator's timeout races the
99
- * responder's reply again — raise it, or derive it from an observed round-trip.
100
- */
101
- export const PROVISION_RESPONSE_TRAVEL_MARGIN_MS = 3_000;
102
- /** Default initiator await-response budget (ms); see {@link DEFAULT_PROVISION_TIMEOUT_MS}. */
103
- const DEFAULT_INITIATOR_PROVISION_TIMEOUT_MS = DEFAULT_PROVISION_TIMEOUT_MS + PROVISION_RESPONSE_TRAVEL_MARGIN_MS;
104
- /**
105
- * Default cap on concurrent inbound formation sessions.
106
- * NOTE: a longer provisioning budget holds a session's slot longer, so a slow hook can
107
- * exhaust this cap and make the listener reject fresh joiners with 'Too many concurrent
108
- * formation sessions'. Fine at the current default; revisit if `provisionTimeoutMs` is
109
- * raised well above its default or this cap is lowered.
110
- */
111
- const DEFAULT_MAX_CONCURRENT_SESSIONS = 100;
112
-
113
- // ── Roles ────────────────────────────────────────────────────────────────────
114
-
115
- export type FormationParty = 'initiator' | 'responder';
116
-
117
- // ── Wire messages (length-prefixed JSON frames) ──────────────────────────────
118
-
119
- export interface FormationStrandInfo {
120
- strandId: string;
121
- createdBy: FormationParty;
122
- }
123
-
124
- export interface FormationDbConnectionInfo {
125
- endpoint: string;
126
- credentialsRef: string;
127
- }
128
-
129
- export interface FormationProvisionResult {
130
- strand: FormationStrandInfo;
131
- /**
132
- * The strand's membership key (closed-strand read-gating secret), delivered to a
133
- * validated invitee for provision-then-record formation. Disclosed only AFTER token
134
- * + disclosure validation, exactly like the responder identity/cadre — a rejected or
135
- * already-used token discloses neither identity nor key. Absent for open strands.
136
- */
137
- memberPrivateKey?: string;
138
- dbConnectionInfo: FormationDbConnectionInfo;
139
- }
140
-
141
- /**
142
- * Outcome of the responder's provisioning hook.
143
- *
144
- * Distinct from a bare {@link FormationProvisionResult} so the hook can REJECT a
145
- * formation AFTER token + disclosure validation — e.g. a bound invite naming a host
146
- * strand this responder has not yet converged on, or a concurrent-redemption collision.
147
- * Without this channel such cases threw inside provisioning, the stream closed with no
148
- * result frame, and the initiator saw a read-error/timeout instead of a clean
149
- * `approved: false`. A rejection still discloses NO responder identity/cadre.
150
- */
151
- export type ResponderProvisionOutcome =
152
- | { approved: true; result: FormationProvisionResult }
153
- | { approved: false; reason: string };
154
-
155
- /** Initiator → Responder: carries the real token + disclosure + initiator cadre. */
156
- export interface FormationContactMessage {
157
- /** The real invitation token. */
158
- token: string;
159
- /** Initiator's member key (peer id) — human-facing identity in logs and `FormStrandResult.memberKey`. */
160
- partyId: string;
161
- /**
162
- * Initiator's base64url ed25519 public key — the key behind `partyId`, written to
163
- * `FormationUsage.PeerKey` and covered by BOTH signed digests.
164
- */
165
- peerKey: string;
166
- /** Joiner-minted single-use nonce for THIS redemption; both signed digests cover it. */
167
- usageStampId: string;
168
- /**
169
- * The joiner's signature over the `'consent'` digest (see `formationConsentMessage`
170
- * in control-database.ts) — proof the named peer agreed to this redemption.
171
- */
172
- peerSignature: string;
173
- /** The real disclosure, carried verbatim. */
174
- disclosure: StrandFormationDisclosure;
175
- /** Initiator's real multiaddrs. */
176
- cadrePeerAddrs: string[];
177
- }
178
-
179
- /** Responder → Initiator: responder identity/cadre disclosed only after validation. */
180
- export interface FormationResultMessage {
181
- approved: boolean;
182
- /** Present iff `approved === false`. */
183
- reason?: string;
184
- /** Responder's real party id (disclosed only after validation). */
185
- partyId?: string;
186
- /** Responder's real multiaddrs (omitted on rejection). */
187
- cadrePeerAddrs?: string[];
188
- /** The provisioned strand/db result (always present on approval). */
189
- provisionResult?: FormationProvisionResult;
190
- }
191
-
192
- // ── Stream framing helpers ───────────────────────────────────────────────────
193
-
194
- /**
195
- * Reads length-prefixed JSON frames from a libp2p stream one frame at a time.
196
- *
197
- * Unlike seed delivery (which reads a stream to EOF then parses once), formation
198
- * is request/response on a single live stream, so reading must stop at each frame
199
- * boundary. The reader buffers across chunk boundaries and retains any overflow
200
- * (a following frame coalesced into the same chunk) for the next read.
201
- */
202
- class FrameReader {
203
- private readonly iterator: AsyncIterator<Uint8Array>;
204
- private readonly maxLength: number;
205
- private buffer = new Uint8Array(0);
206
-
207
- constructor(stream: AsyncIterable<Uint8Array>, maxLength = MAX_FORMATION_MSG_SIZE) {
208
- this.iterator = stream[Symbol.asyncIterator]();
209
- this.maxLength = maxLength;
210
- }
211
-
212
- private append(chunk: Uint8Array): void {
213
- const next = new Uint8Array(this.buffer.length + chunk.length);
214
- next.set(this.buffer, 0);
215
- next.set(chunk, this.buffer.length);
216
- this.buffer = next;
217
- }
218
-
219
- /** Pull chunks until the buffer holds ≥ `need` bytes; false if the stream ended first. */
220
- private async fill(need: number): Promise<boolean> {
221
- while (this.buffer.length < need) {
222
- const { value, done } = await this.iterator.next();
223
- if (done) return false;
224
- const bytes = value instanceof Uint8Array
225
- ? value
226
- : (value as { subarray(): Uint8Array }).subarray();
227
- this.append(bytes);
228
- }
229
- return true;
230
- }
231
-
232
- async read<T>(): Promise<T> {
233
- if (!(await this.fill(4))) {
234
- throw new Error('Formation stream closed before length prefix');
235
- }
236
- const length = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength).getUint32(0, false);
237
- if (length > this.maxLength) {
238
- throw new Error(`Formation frame declares length ${length} exceeding max ${this.maxLength}`);
239
- }
240
- if (!(await this.fill(4 + length))) {
241
- throw new Error(`Formation frame declares length ${length} but stream ended early`);
242
- }
243
- const json = new TextDecoder().decode(this.buffer.subarray(4, 4 + length));
244
- this.buffer = this.buffer.subarray(4 + length);
245
- return JSON.parse(json) as T;
246
- }
247
- }
248
-
249
- // ── Result validation ────────────────────────────────────────────────────────
250
-
251
- /** Matches the placeholder cadre addrs (`cadre-a-1.local`, …) of the removed strand-proto transport. */
252
- const PLACEHOLDER_CADRE_ADDR = /^cadre-[ab]-\d+\.local$/;
253
-
254
- /**
255
- * Structural check on a `responderCreates` result: the responder must have approved,
256
- * disclosed a non-empty real identity + cadre (not the legacy `cadre-*.local`
257
- * placeholders), and returned a strand vouched for by the responder party with a real id.
258
- *
259
- * `createdBy: 'responder'` means "the responder party vouches for / returns this strand."
260
- * Under provision-then-record that strand was minted owner-signed earlier (not created
261
- * in-session), but it is still the responder party returning its own strand, so the marker
262
- * — and this structural validator — stay unchanged.
263
- *
264
- * The behavioral floor for the initiator: a responder that returns an arbitrary/empty
265
- * `strandId` or omits its disclosed identity is rejected, not silently accepted.
266
- */
267
- export function isValidResponderCreatesResult(response: FormationResultMessage): boolean {
268
- if (!response.approved) return false;
269
- if (!response.partyId) return false;
270
- const addrs = response.cadrePeerAddrs;
271
- if (!addrs || addrs.length === 0) return false;
272
- if (addrs.some((a) => PLACEHOLDER_CADRE_ADDR.test(a))) return false;
273
- const provision = response.provisionResult;
274
- if (!provision?.strand?.strandId) return false;
275
- if (provision.strand.createdBy !== 'responder') return false;
276
- return true;
277
- }
278
-
279
- /**
280
- * Ceiling for a resolved provisioning budget.
281
- *
282
- * The session budget also has to cover the wire step that PRECEDES provisioning (the
283
- * responder's contact read, the initiator's dial-connect), so a whole step is held back
284
- * rather than triggering only on a literal overrun.
285
- *
286
- * `reserveMs` is the EXTRA room only the responder holds back, so its own budget still
287
- * lands strictly before the initiator's larger await-response budget even when both are
288
- * clamped — without it, any configured budget at or above `sessionTimeoutMs -
289
- * stepTimeoutMs` clamps both roles onto the same number and the responder's clean
290
- * rejection races the initiator's timeout again. Capped at half the remaining room (like
291
- * {@link splitProvisionBudget}) so a small session config still spends most of it working.
292
- */
293
- function provisionCeilingMs(sessionTimeoutMs: number, stepTimeoutMs: number, reserveMs: number): number {
294
- const roomMs = sessionTimeoutMs - stepTimeoutMs;
295
- return Math.max(1, roomMs - Math.min(reserveMs, Math.floor(roomMs / 2)));
296
- }
297
-
298
- /**
299
- * Resolve a caller-supplied provisioning budget: `0`/negative means "unset" (use
300
- * `defaultMs`). If the result would let provisioning outlive the session — no result
301
- * frame is ever sent, exactly the failure this budget exists to prevent — clamp it to
302
- * {@link provisionCeilingMs} and log a warning.
303
- */
304
- function resolveProvisionTimeoutMs(
305
- configured: number | undefined,
306
- defaultMs: number,
307
- sessionTimeoutMs: number,
308
- stepTimeoutMs: number,
309
- role: string,
310
- reserveMs = 0
311
- ): number {
312
- const requested = configured && configured > 0 ? configured : defaultMs;
313
- const ceilingMs = provisionCeilingMs(sessionTimeoutMs, stepTimeoutMs, reserveMs);
314
- if (requested >= ceilingMs) {
315
- log(
316
- '%s provisionTimeoutMs %dms leaves no room under sessionTimeoutMs %dms (step %dms, reserve %dms); clamping to %dms',
317
- role, requested, sessionTimeoutMs, stepTimeoutMs, reserveMs, ceilingMs
318
- );
319
- return ceilingMs;
320
- }
321
- return requested;
322
- }
323
-
324
- /**
325
- * Split a resolved provisioning budget into the WORK budget and the trailing settle grace.
326
- *
327
- * The grace is carved OUT of the budget (see {@link PROVISION_SETTLE_GRACE_MS}), and capped at
328
- * half of it so a small configured budget still spends at least half its time doing work.
329
- */
330
- function splitProvisionBudget(provisionTimeoutMs: number): { workMs: number; graceMs: number } {
331
- const graceMs = Math.min(PROVISION_SETTLE_GRACE_MS, Math.floor(provisionTimeoutMs / 2));
332
- return { workMs: provisionTimeoutMs - graceMs, graceMs };
333
- }
334
-
335
- // ── Responder (listener) ─────────────────────────────────────────────────────
336
-
337
- export interface FormationListenerOptions {
338
- /** Validate the invitation token; returns whether it is valid. */
339
- validateToken(token: string): Promise<{ valid: boolean }>;
340
- /** Validate the initiator's disclosure with the REAL token + disclosure. */
341
- validateDisclosure(token: string, disclosure: StrandFormationDisclosure): Promise<boolean>;
342
- /**
343
- * Provision (or, for provision-then-record, resolve + record consent against) the
344
- * strand (`responderCreates`) for the given initiator. The WHOLE contact message is
345
- * threaded in: the hook needs the REAL token to map the bound host strand, and the
346
- * joiner's `peerKey`/`usageStampId`/`peerSignature` to write the consent columns.
347
- *
348
- * Returns a {@link ResponderProvisionOutcome}: the hook may REJECT post-validation
349
- * (e.g. an unconverged host strand) and the listener turns that into a clean,
350
- * non-disclosing `approved: false` reply rather than dropping the result frame.
351
- *
352
- * `signal` is aborted when the listener's work budget expires: a hook that observes it
353
- * BEFORE writing abandons the redemption and leaves the invite unspent. Optional so
354
- * signal-unaware hooks (tests, mocks) stay assignable.
355
- */
356
- provisionStrand(contact: FormationContactMessage, signal?: AbortSignal): Promise<ResponderProvisionOutcome>;
357
- /** Responder identity, disclosed only AFTER token + disclosure validation passes. */
358
- getResponderIdentity(): { partyId: string; cadrePeerAddrs: string[] };
359
- sessionTimeoutMs?: number;
360
- stepTimeoutMs?: number;
361
- /**
362
- * Budget for the `provisionStrand` hook call — distinct from `stepTimeoutMs` because
363
- * provisioning is real work, not a bare wire read/write. Default 12 s; `0`/unset uses
364
- * the default; a value that would outlive the session is clamped ({@link
365
- * provisionCeilingMs}). See {@link DEFAULT_PROVISION_TIMEOUT_MS} for the full ordering
366
- * rationale.
367
- */
368
- provisionTimeoutMs?: number;
369
- maxConcurrentSessions?: number;
370
- }
371
-
372
- /**
373
- * Responder side of the native formation protocol. Registers a libp2p handler and
374
- * drives each inbound stream through token + disclosure validation, provisioning,
375
- * and result delivery — enforcing the cadre-disclosure timing rule (responder cadre
376
- * is revealed only after validation; rejections disclose nothing).
377
- */
378
- export class FormationListener {
379
- private readonly options: FormationListenerOptions;
380
- private readonly sessionTimeoutMs: number;
381
- private readonly stepTimeoutMs: number;
382
- private readonly provisionWorkMs: number;
383
- private readonly provisionGraceMs: number;
384
- private readonly maxConcurrentSessions: number;
385
- private readonly registered = new Set<Libp2p>();
386
- private activeSessions = 0;
387
- private sessionCounter = 0;
388
-
389
- constructor(options: FormationListenerOptions) {
390
- this.options = options;
391
- this.sessionTimeoutMs = options.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;
392
- this.stepTimeoutMs = options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS;
393
- const split = splitProvisionBudget(resolveProvisionTimeoutMs(
394
- options.provisionTimeoutMs, DEFAULT_PROVISION_TIMEOUT_MS,
395
- this.sessionTimeoutMs, this.stepTimeoutMs, 'FormationListener',
396
- PROVISION_RESPONSE_TRAVEL_MARGIN_MS
397
- ));
398
- this.provisionWorkMs = split.workMs;
399
- this.provisionGraceMs = split.graceMs;
400
- this.maxConcurrentSessions = options.maxConcurrentSessions ?? DEFAULT_MAX_CONCURRENT_SESSIONS;
401
- }
402
-
403
- /** Number of in-flight inbound sessions. */
404
- get activeCount(): number {
405
- return this.activeSessions;
406
- }
407
-
408
- register(node: Libp2p, protocolId: string = FORMATION_PROTOCOL): void {
409
- if (this.registered.has(node)) {
410
- log('node already registered');
411
- return;
412
- }
413
- void node.handle(protocolId, async (rawStream: unknown, _connection: unknown) => {
414
- await this.handleStream(rawStream as ControlStream);
415
- });
416
- this.registered.add(node);
417
- log('formation listener registered (%s)', protocolId);
418
- }
419
-
420
- unregister(node: Libp2p, protocolId: string = FORMATION_PROTOCOL): void {
421
- if (!this.registered.has(node)) return;
422
- void node.unhandle(protocolId);
423
- this.registered.delete(node);
424
- log('formation listener unregistered (%s)', protocolId);
425
- }
426
-
427
- private async handleStream(stream: ControlStream): Promise<void> {
428
- if (this.activeSessions >= this.maxConcurrentSessions) {
429
- const rejection: FormationResultMessage = { approved: false, reason: 'Too many concurrent formation sessions' };
430
- try { writeFrame(stream, rejection); } catch { /* best effort */ }
431
- try { await stream.close(); } catch { /* ignore */ }
432
- return;
433
- }
434
- const id = ++this.sessionCounter;
435
- this.activeSessions++;
436
- try {
437
- await withTimeout(this.sessionTimeoutMs, `Formation session#${id}`, () => this.runSession(id, stream));
438
- } catch (err) {
439
- log('formation session #%d failed: %o', id, err);
440
- } finally {
441
- this.activeSessions--;
442
- try { await stream.close(); } catch { /* ignore */ }
443
- }
444
- }
445
-
446
- /**
447
- * Run the provisioning hook under its WORK budget — the configured provisioning budget minus
448
- * the trailing settle grace ({@link splitProvisionBudget}, {@link PROVISION_SETTLE_GRACE_MS}).
449
- *
450
- * When the work budget expires the hook's signal is aborted, then
451
- * {@link settleWithinGrace} waits out the grace for the aborted work to settle anyway.
452
- * Returns `undefined` for "timed out" — which the caller turns into a retryable rejection
453
- * frame — and rethrows every other failure so it reaches the internal-error path.
454
- *
455
- * Deliberately not `withDeadline`: that exposes neither the timed-out flag nor the signal
456
- * outside its `op`, and both are needed here.
457
- */
458
- private async provision(id: number, contact: FormationContactMessage): Promise<ResponderProvisionOutcome | undefined> {
459
- const controller = new AbortController();
460
- let timedOut = false;
461
- const pending = this.options.provisionStrand(contact, controller.signal);
462
- try {
463
- return await withTimeout(
464
- this.provisionWorkMs,
465
- `Formation provisioning#${id}`,
466
- () => pending,
467
- () => { timedOut = true; controller.abort(); }
468
- );
469
- } catch (err) {
470
- if (!timedOut) throw err;
471
- log(
472
- 'formation session #%d provisioning work budget expired after %dms; aborted, settling up to %dms',
473
- id, this.provisionWorkMs, this.provisionGraceMs
474
- );
475
- return await this.settleWithinGrace(id, pending);
476
- }
477
- }
478
-
479
- /**
480
- * Wait out the settle grace for an ABORTED provisioning, adopting a late success.
481
- *
482
- * A hook that observed the abort before issuing its `FormationUsage` insert rejects (with
483
- * `FormationAbortedError`) and leaves the invite unspent → reported as a timeout. A hook
484
- * that had already written cannot be un-written (the table is append-only), so if it lands
485
- * inside the grace its outcome is ADOPTED — the joiner is told the truth (approved, or the
486
- * hook's own rejection reason) rather than "timed out" over a spent invite.
487
- *
488
- * NOTE: one window stays open — a work budget that expires after the `FormationUsage`
489
- * insert was issued AND a commit that outlasts the grace. The joiner is told 'timed out'
490
- * while its one-time invite is in fact spent, and since every retry mints a fresh keypair
491
- * no recovery path can match it. Nothing can un-spend an append-only row, so the late-settle
492
- * logging below is the observability for it; widen the grace only if it is seen in the wild.
493
- */
494
- private async settleWithinGrace(
495
- id: number,
496
- pending: Promise<ResponderProvisionOutcome>
497
- ): Promise<ResponderProvisionOutcome | undefined> {
498
- let stillPending = false;
499
- try {
500
- const outcome = await withTimeout(
501
- this.provisionGraceMs,
502
- `Formation settle#${id}`,
503
- () => pending,
504
- () => { stillPending = true; }
505
- );
506
- log('formation session #%d provisioning settled within its grace: approved=%s — adopting', id, outcome.approved);
507
- return outcome;
508
- } catch (err) {
509
- if (!stillPending) {
510
- log('formation session #%d provisioning failed after its abort: %o', id, err);
511
- return undefined;
512
- }
513
- log('formation session #%d provisioning still pending after its %dms grace', id, this.provisionGraceMs);
514
- // Log how it eventually settled so a late failure is not swallowed by the two
515
- // abandoned `withTimeout` calls.
516
- void pending.then(
517
- (late) => log('formation session #%d provisioning settled after its grace: approved=%s', id, late.approved),
518
- (err2) => log('formation session #%d provisioning failed after its grace: %o', id, err2)
519
- );
520
- return undefined;
521
- }
522
- }
523
-
524
- /**
525
- * Joiner-consent pre-check — the legibility twin of the schema's
526
- * `FormationUsage.PeerConsented` CHECK, exactly as `verifyFormationApproval` is for the
527
- * approver's vouch. The database constraint stays the authority; this turns a bad consent
528
- * into a clean 'Invalid joiner consent' rejection instead of an opaque CHECK failure at
529
- * commit. Runs BEFORE token/disclosure validation: it is the cheapest check (pure local
530
- * crypto, no DB read) and a rejection discloses nothing.
531
- *
532
- * Also pins `partyId` to `peerKey`: an ed25519 peer id is an identity multihash of the
533
- * very key, and this is the ONLY layer that can check the match — SQL cannot unwrap a
534
- * multihash, and `partyId` itself is never stored.
535
- */
536
- private isJoinerConsentValid(id: number, contact: FormationContactMessage): boolean {
537
- try {
538
- requireEd25519PublicKeyB64(contact.peerKey, 'joiner peer key');
539
- } catch {
540
- // Deliberately not rethrown or echoed: the helper's error message embeds the whole
541
- // rejected value, and this one arrived from a remote peer (the cap-the-echo case its
542
- // own NOTE warns about). Log without the raw value instead.
543
- log('formation session #%d: joiner peer key is not a base64url ed25519 public key', id);
544
- return false;
545
- }
546
- const embedded = ed25519PublicKeyB64FromPeerId(contact.partyId);
547
- if (!embedded || embedded !== contact.peerKey) {
548
- log('formation session #%d: partyId does not embed the presented peer key', id);
549
- return false;
550
- }
551
- const consentOk = verifyFormationConsent({
552
- token: contact.token,
553
- usageStampId: contact.usageStampId,
554
- peerKey: contact.peerKey,
555
- disclosure: canonicalJson(contact.disclosure),
556
- peerSig: contact.peerSignature
557
- });
558
- if (!consentOk) {
559
- log('formation session #%d: joiner consent signature failed verification', id);
560
- return false;
561
- }
562
- return true;
563
- }
564
-
565
- private async runSession(id: number, stream: ControlStream): Promise<void> {
566
- // Track whether ANY frame has been written so the catch below can convert an
567
- // unexpected internal error into a non-disclosing rejection ONLY when nothing has
568
- // gone out yet. This closes the "stream closed with no result frame" class of bug.
569
- let wroteFrame = false;
570
- const send = (msg: FormationResultMessage): void => {
571
- writeFrame(stream, msg);
572
- wroteFrame = true;
573
- };
574
-
575
- try {
576
- const reader = new FrameReader(stream);
577
- const contact = await withTimeout(this.stepTimeoutMs, `Formation await-contact#${id}`, () => reader.read<FormationContactMessage>());
578
- log('formation session #%d contact: token=%s party=%s', id, contact.token, contact.partyId);
579
-
580
- if (!this.isJoinerConsentValid(id, contact)) {
581
- send({ approved: false, reason: 'Invalid joiner consent' });
582
- return;
583
- }
584
-
585
- const tokenResult = await this.options.validateToken(contact.token);
586
- if (!tokenResult.valid) {
587
- send({ approved: false, reason: INVALID_TOKEN_REASON });
588
- return;
589
- }
590
-
591
- const disclosureOk = await this.options.validateDisclosure(contact.token, contact.disclosure);
592
- if (!disclosureOk) {
593
- send({ approved: false, reason: 'Invalid disclosure' });
594
- return;
595
- }
596
-
597
- const outcome = await this.provision(id, contact);
598
- if (!outcome) {
599
- // Reported as its own retryable reason rather than falling through to the generic
600
- // catch below, which would report the misleading 'Internal formation error'.
601
- send({ approved: false, reason: 'Formation provisioning timed out' });
602
- return;
603
- }
604
- if (!outcome.approved) {
605
- // A post-validation rejection still discloses NEITHER identity NOR cadre,
606
- // exactly like the token/disclosure rejections above.
607
- send({ approved: false, reason: outcome.reason });
608
- return;
609
- }
610
- // Validation + provisioning passed → safe to disclose responder identity/cadre.
611
- const identity = this.options.getResponderIdentity();
612
- send({
613
- approved: true,
614
- partyId: identity.partyId,
615
- cadrePeerAddrs: identity.cadrePeerAddrs,
616
- provisionResult: outcome.result
617
- });
618
- } catch (err) {
619
- // Defense-in-depth: if an unexpected internal error escapes BEFORE any frame was
620
- // written (e.g. a future provisionStrand-hook bug), convert it into a non-disclosing
621
- // protocol rejection so the initiator sees a clean error instead of a read-error/
622
- // timeout. If a frame was already sent, leave the stream as-is and let handleStream
623
- // log + close. Re-throw either way so the failure is still recorded — this is a
624
- // deliberate, logged conversion, not silent.
625
- if (!wroteFrame) {
626
- const internalError: FormationResultMessage = { approved: false, reason: 'Internal formation error' };
627
- try { writeFrame(stream, internalError); } catch { /* stream already broken */ }
628
- }
629
- throw err;
630
- }
631
- }
632
- }
633
-
634
- // ── Initiator (dialer) ───────────────────────────────────────────────────────
635
-
636
- export interface FormationDialOptions {
637
- /** The contact message to send (real token, partyId, disclosure, initiator cadre). */
638
- contact: FormationContactMessage;
639
- /** Responder multiaddrs to dial. */
640
- responderAddrs: string[];
641
- /** Validate the responder's result; a false return aborts the formation. */
642
- validateResponse(response: FormationResultMessage): Promise<boolean>;
643
- sessionTimeoutMs?: number;
644
- stepTimeoutMs?: number;
645
- /**
646
- * Budget for the `await-response` read only (the responder's provisioning + reply travel
647
- * time) — `dial-connect` keeps using `stepTimeoutMs`. Default 15 s; `0`/unset uses the
648
- * default. See {@link DEFAULT_PROVISION_TIMEOUT_MS} for the full ordering rationale.
649
- */
650
- provisionTimeoutMs?: number;
651
- protocolId?: string;
652
- }
653
-
654
- /**
655
- * Initiator side of the native formation protocol. Dials the responder, sends the
656
- * contact (carrying the real disclosure/token/cadre), validates the responder's
657
- * result, and returns the strand the responder provisioned.
658
- */
659
- export async function dialFormation(node: Libp2p, options: FormationDialOptions): Promise<FormationProvisionResult> {
660
- if (options.responderAddrs.length === 0) {
661
- throw new Error('No responder addresses available for formation');
662
- }
663
- const protocolId = options.protocolId ?? FORMATION_PROTOCOL;
664
- const sessionTimeoutMs = options.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;
665
- const stepTimeoutMs = options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS;
666
- const provisionTimeoutMs = resolveProvisionTimeoutMs(
667
- options.provisionTimeoutMs, DEFAULT_INITIATOR_PROVISION_TIMEOUT_MS,
668
- sessionTimeoutMs, stepTimeoutMs, 'dialFormation'
669
- );
670
- const addr = multiaddr(options.responderAddrs[0]);
671
-
672
- return withTimeout(sessionTimeoutMs, 'Formation dial', async () => {
673
- const rawStream = await withTimeout(stepTimeoutMs, 'Formation dial-connect', async () => node.dialProtocol(addr, protocolId));
674
- const stream = rawStream as unknown as ControlStream;
675
- try {
676
- const reader = new FrameReader(stream);
677
- writeFrame(stream, options.contact);
678
-
679
- const response = await withTimeout(provisionTimeoutMs, 'Formation await-response', () => reader.read<FormationResultMessage>());
680
- if (!response.approved) {
681
- throw new Error(`Formation rejected: ${response.reason ?? 'no reason provided'}`);
682
- }
683
- const ok = await options.validateResponse(response);
684
- if (!ok) throw new Error('Responder result failed validation');
685
-
686
- if (!response.provisionResult) throw new Error('Missing provision result for responderCreates mode');
687
- return response.provisionResult;
688
- } finally {
689
- try { await stream.close(); } catch { /* ignore */ }
690
- }
691
- });
692
- }
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 } from '@multiformats/multiaddr';
23
+ import type { Libp2p } from '@libp2p/interface';
24
+ import type { StrandFormationDisclosure } from './types.js';
25
+ import { type ControlStream, writeFrame, 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 './seed-bootstrap.js';
32
+
33
+ const log = debug('sereus:cadre:formation-proto');
34
+
35
+ /** Protocol id for the native formation transport (parallel to `/sereus/seed/1.0.0`). */
36
+ export const FORMATION_PROTOCOL = '/sereus/formation/1.0.0';
37
+
38
+ /**
39
+ * Rejection reason for an invitation that cannot be redeemed at all — unknown, expired, or
40
+ * fully spent. Shared with `StrandFormationManager`, which reports an
41
+ * `InvitationExhaustedError` (an invite spent out from under a redemption already in flight)
42
+ * with this SAME wording on purpose: a joiner that lost the race must be indistinguishable
43
+ * from a non-racing latecomer, so the two sites must never drift apart.
44
+ */
45
+ export const INVALID_TOKEN_REASON = 'Invalid token';
46
+
47
+ /** Maximum formation message size (1MB). */
48
+ const MAX_FORMATION_MSG_SIZE = 1024 * 1024;
49
+
50
+ /** Default whole-session timeout (ms). */
51
+ const DEFAULT_SESSION_TIMEOUT_MS = 30_000;
52
+ /** Default per-step (single read/write) timeout (ms). */
53
+ const DEFAULT_STEP_TIMEOUT_MS = 5_000;
54
+ /**
55
+ * Default provisioning budget (ms) — distinct from {@link DEFAULT_STEP_TIMEOUT_MS} because
56
+ * `provisionStrand` is real work (DB writes, and an outbound approval-hook HTTP call when
57
+ * the invite carries a `ValidationUrl`), not a bare wire read/write.
58
+ *
59
+ * Ordering is deliberate — each layer must be able to fail and report before the layer above
60
+ * it gives up:
61
+ *
62
+ * approval hook (10 s, `formation-approval.ts`)
63
+ * < responder provisioning (12 s)
64
+ * < initiator await-response (15 s)
65
+ * < session (30 s)
66
+ *
67
+ * The 3 s margin between responder provisioning and initiator await-response is the wire
68
+ * latency budget for the result frame to travel back.
69
+ *
70
+ * The last {@link PROVISION_SETTLE_GRACE_MS} of this budget is a settle grace, so the default
71
+ * WORK budget (12 s − 2 s = 10 s) EQUALS the hook's own 10 s: a dead hook races 'Formation
72
+ * approval unavailable, retry' against 'Formation provisioning timed out'. Both are retryable
73
+ * and both leave the invite unspent, so the race is benign.
74
+ */
75
+ const DEFAULT_PROVISION_TIMEOUT_MS = 12_000;
76
+ /**
77
+ * Settle grace (ms), carved OUT of `provisionTimeoutMs` — never added on top, so the budget
78
+ * ladder above is untouched. The listener aborts the provisioning hook when the work budget
79
+ * ({@link splitProvisionBudget}) expires, then waits up to this grace for the work to settle
80
+ * anyway: once the `FormationUsage` insert has been issued nothing can un-spend it (the table
81
+ * is append-only), so a provisioning that lands late is ADOPTED and reported as a real
82
+ * approval rather than lying "timed out" over a spent invite. A hook that observes the
83
+ * abort before writing leaves the invite unspent.
84
+ */
85
+ const PROVISION_SETTLE_GRACE_MS = 2_000;
86
+ /**
87
+ * Wire-latency margin (ms) added to the responder's provisioning budget to get the
88
+ * initiator's await-response budget — the travel time for the result frame to come back
89
+ * after the responder finishes (see {@link DEFAULT_PROVISION_TIMEOUT_MS}).
90
+ * `StrandFormationManager` reuses this constant so a CONFIGURED budget preserves the same
91
+ * margin the defaults do, instead of applying the same number to both sides and racing the
92
+ * initiator's own timeout against the responder's clean rejection reply. The responder's
93
+ * clamp ({@link provisionCeilingMs}) holds the same margin back, so the ordering survives a
94
+ * budget large enough that BOTH roles get clamped.
95
+ *
96
+ * NOTE: 3 s is a fixed assumption about how long the result frame takes to travel back. If
97
+ * formation ever runs over paths where that frame can take longer (a slow circuit relay, a
98
+ * congested mobile link), the margin is too thin and the initiator's timeout races the
99
+ * responder's reply again — raise it, or derive it from an observed round-trip.
100
+ */
101
+ export const PROVISION_RESPONSE_TRAVEL_MARGIN_MS = 3_000;
102
+ /** Default initiator await-response budget (ms); see {@link DEFAULT_PROVISION_TIMEOUT_MS}. */
103
+ const DEFAULT_INITIATOR_PROVISION_TIMEOUT_MS = DEFAULT_PROVISION_TIMEOUT_MS + PROVISION_RESPONSE_TRAVEL_MARGIN_MS;
104
+ /**
105
+ * Default cap on concurrent inbound formation sessions.
106
+ * NOTE: a longer provisioning budget holds a session's slot longer, so a slow hook can
107
+ * exhaust this cap and make the listener reject fresh joiners with 'Too many concurrent
108
+ * formation sessions'. Fine at the current default; revisit if `provisionTimeoutMs` is
109
+ * raised well above its default or this cap is lowered.
110
+ */
111
+ const DEFAULT_MAX_CONCURRENT_SESSIONS = 100;
112
+
113
+ /**
114
+ * Cap on the strand-network addresses a formation result carries
115
+ * ({@link FormationResultMessage.strandAddrs}). A node's own strand multiaddrs are a
116
+ * handful of entries (one per listen transport, plus a circuit-relay reservation), so
117
+ * 16 is generous for the honest case while keeping the result frame bounded against a
118
+ * peer that would pad it — either direction, since both sides run the list through
119
+ * {@link sanitizeStrandAddrs}. Exported because the same bound has to hold on the
120
+ * initiator's stored copy: `CadreNode` accumulates across repeat formations against one
121
+ * strand, so it caps the accumulation rather than only each arriving list.
122
+ */
123
+ export const MAX_STRAND_ADDRS = 16;
124
+
125
+ // ── Roles ────────────────────────────────────────────────────────────────────
126
+
127
+ export type FormationParty = 'initiator' | 'responder';
128
+
129
+ // ── Wire messages (length-prefixed JSON frames) ──────────────────────────────
130
+
131
+ export interface FormationStrandInfo {
132
+ strandId: string;
133
+ createdBy: FormationParty;
134
+ }
135
+
136
+ export interface FormationDbConnectionInfo {
137
+ endpoint: string;
138
+ credentialsRef: string;
139
+ }
140
+
141
+ export interface FormationProvisionResult {
142
+ strand: FormationStrandInfo;
143
+ /**
144
+ * The strand's membership key (closed-strand read-gating secret), delivered to a
145
+ * validated invitee for provision-then-record formation. Disclosed only AFTER token
146
+ * + disclosure validation, exactly like the responder identity/cadre — a rejected or
147
+ * already-used token discloses neither identity nor key. Absent for open strands.
148
+ */
149
+ memberPrivateKey?: string;
150
+ dbConnectionInfo: FormationDbConnectionInfo;
151
+ }
152
+
153
+ /**
154
+ * Outcome of the responder's provisioning hook.
155
+ *
156
+ * Distinct from a bare {@link FormationProvisionResult} so the hook can REJECT a
157
+ * formation AFTER token + disclosure validation — e.g. a bound invite naming a host
158
+ * strand this responder has not yet converged on, or a concurrent-redemption collision.
159
+ * Without this channel such cases threw inside provisioning, the stream closed with no
160
+ * result frame, and the initiator saw a read-error/timeout instead of a clean
161
+ * `approved: false`. A rejection still discloses NO responder identity/cadre.
162
+ */
163
+ export type ResponderProvisionOutcome =
164
+ | { approved: true; result: FormationProvisionResult }
165
+ | { approved: false; reason: string };
166
+
167
+ /** Initiator → Responder: carries the real token + disclosure + initiator cadre. */
168
+ export interface FormationContactMessage {
169
+ /** The real invitation token. */
170
+ token: string;
171
+ /** Initiator's member key (peer id) — human-facing identity in logs and `FormStrandResult.memberKey`. */
172
+ partyId: string;
173
+ /**
174
+ * Initiator's base64url ed25519 public key — the key behind `partyId`, written to
175
+ * `FormationUsage.PeerKey` and covered by BOTH signed digests.
176
+ */
177
+ peerKey: string;
178
+ /** Joiner-minted single-use nonce for THIS redemption; both signed digests cover it. */
179
+ usageStampId: string;
180
+ /**
181
+ * The joiner's signature over the `'consent'` digest (see `formationConsentMessage`
182
+ * in control-database.ts) — proof the named peer agreed to this redemption.
183
+ */
184
+ peerSignature: string;
185
+ /** The real disclosure, carried verbatim. */
186
+ disclosure: StrandFormationDisclosure;
187
+ /** Initiator's real multiaddrs. */
188
+ cadrePeerAddrs: string[];
189
+ }
190
+
191
+ /** Responder → Initiator: responder identity/cadre disclosed only after validation. */
192
+ export interface FormationResultMessage {
193
+ approved: boolean;
194
+ /** Present iff `approved === false`. */
195
+ reason?: string;
196
+ /** Responder's real party id (disclosed only after validation). */
197
+ partyId?: string;
198
+ /** Responder's real multiaddrs (omitted on rejection). */
199
+ cadrePeerAddrs?: string[];
200
+ /**
201
+ * The responder's live STRAND-network multiaddrs for the provisioned strand — the
202
+ * initiator's only cross-party discovery seed, since the strand-addr RPC that resolves
203
+ * a sibling's strand addrs is membership-gated and answers own-party callers only.
204
+ *
205
+ * Disclosed on the same terms as `partyId`/`cadrePeerAddrs`: only after token +
206
+ * disclosure validation AND an approving provisioning outcome; a rejection carries
207
+ * none. Signaling-first, each entry ending in `/p2p/<responder strand transport
208
+ * peerId>` so the initiator can attribute it. OMITTED when the responder holds no live
209
+ * strand node for the provisioned strand (the responder-provisions path mints a strand
210
+ * that has not launched yet) — an absent or empty list is legal and means "no
211
+ * cross-party seed", never a protocol error.
212
+ */
213
+ strandAddrs?: string[];
214
+ /** The provisioned strand/db result (always present on approval). */
215
+ provisionResult?: FormationProvisionResult;
216
+ }
217
+
218
+ /**
219
+ * Normalize a strand-address list arriving from — or heading to — the wire: keep only
220
+ * parsable multiaddr strings, drop duplicates, and cap at {@link MAX_STRAND_ADDRS}.
221
+ * Order is preserved, so the responder's signaling-first ordering survives.
222
+ *
223
+ * Applied on BOTH sides on purpose. The responder bounds what it sends; the initiator
224
+ * bounds what it stores, because a peer is free to ignore the cap. A malformed entry is
225
+ * SKIPPED rather than fatal — these are runtime-discovered addresses (same posture as
226
+ * `extractCircuitRelayTargets` in `delegate-admission.ts`), and one bad entry must not
227
+ * cost a formation that has otherwise succeeded.
228
+ */
229
+ export function sanitizeStrandAddrs(addrs: unknown): string[] {
230
+ if (!Array.isArray(addrs)) return [];
231
+ const out: string[] = [];
232
+ const seen = new Set<string>();
233
+ for (const entry of addrs) {
234
+ if (out.length >= MAX_STRAND_ADDRS) break;
235
+ if (typeof entry !== 'string' || entry.length === 0) {
236
+ log('strandAddrs: skipping non-string entry %o', entry);
237
+ continue;
238
+ }
239
+ if (seen.has(entry)) continue;
240
+ try {
241
+ multiaddr(entry);
242
+ } catch (error) {
243
+ // Deliberately not echoing the raw value at error level: it arrived from a remote
244
+ // peer. The log line below is the observability for a responder announcing junk.
245
+ log('strandAddrs: skipping unparsable entry: %o', error);
246
+ continue;
247
+ }
248
+ seen.add(entry);
249
+ out.push(entry);
250
+ }
251
+ return out;
252
+ }
253
+
254
+ // ── Stream framing helpers ───────────────────────────────────────────────────
255
+
256
+ /**
257
+ * Reads length-prefixed JSON frames from a libp2p stream one frame at a time.
258
+ *
259
+ * Unlike seed delivery (which reads a stream to EOF then parses once), formation
260
+ * is request/response on a single live stream, so reading must stop at each frame
261
+ * boundary. The reader buffers across chunk boundaries and retains any overflow
262
+ * (a following frame coalesced into the same chunk) for the next read.
263
+ */
264
+ class FrameReader {
265
+ private readonly iterator: AsyncIterator<Uint8Array>;
266
+ private readonly maxLength: number;
267
+ private buffer = new Uint8Array(0);
268
+
269
+ constructor(stream: AsyncIterable<Uint8Array>, maxLength = MAX_FORMATION_MSG_SIZE) {
270
+ this.iterator = stream[Symbol.asyncIterator]();
271
+ this.maxLength = maxLength;
272
+ }
273
+
274
+ private append(chunk: Uint8Array): void {
275
+ const next = new Uint8Array(this.buffer.length + chunk.length);
276
+ next.set(this.buffer, 0);
277
+ next.set(chunk, this.buffer.length);
278
+ this.buffer = next;
279
+ }
280
+
281
+ /** Pull chunks until the buffer holds ≥ `need` bytes; false if the stream ended first. */
282
+ private async fill(need: number): Promise<boolean> {
283
+ while (this.buffer.length < need) {
284
+ const { value, done } = await this.iterator.next();
285
+ if (done) return false;
286
+ const bytes = value instanceof Uint8Array
287
+ ? value
288
+ : (value as { subarray(): Uint8Array }).subarray();
289
+ this.append(bytes);
290
+ }
291
+ return true;
292
+ }
293
+
294
+ async read<T>(): Promise<T> {
295
+ if (!(await this.fill(4))) {
296
+ throw new Error('Formation stream closed before length prefix');
297
+ }
298
+ const length = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength).getUint32(0, false);
299
+ if (length > this.maxLength) {
300
+ throw new Error(`Formation frame declares length ${length} exceeding max ${this.maxLength}`);
301
+ }
302
+ if (!(await this.fill(4 + length))) {
303
+ throw new Error(`Formation frame declares length ${length} but stream ended early`);
304
+ }
305
+ const json = new TextDecoder().decode(this.buffer.subarray(4, 4 + length));
306
+ this.buffer = this.buffer.subarray(4 + length);
307
+ return JSON.parse(json) as T;
308
+ }
309
+ }
310
+
311
+ // ── Result validation ────────────────────────────────────────────────────────
312
+
313
+ /** Matches the placeholder cadre addrs (`cadre-a-1.local`, …) of the removed strand-proto transport. */
314
+ const PLACEHOLDER_CADRE_ADDR = /^cadre-[ab]-\d+\.local$/;
315
+
316
+ /**
317
+ * Structural check on a `responderCreates` result: the responder must have approved,
318
+ * disclosed a non-empty real identity + cadre (not the legacy `cadre-*.local`
319
+ * placeholders), and returned a strand vouched for by the responder party with a real id.
320
+ *
321
+ * `createdBy: 'responder'` means "the responder party vouches for / returns this strand."
322
+ * Under provision-then-record that strand was minted owner-signed earlier (not created
323
+ * in-session), but it is still the responder party returning its own strand, so the marker
324
+ * — and this structural validator — stay unchanged.
325
+ *
326
+ * The behavioral floor for the initiator: a responder that returns an arbitrary/empty
327
+ * `strandId` or omits its disclosed identity is rejected, not silently accepted.
328
+ */
329
+ export function isValidResponderCreatesResult(response: FormationResultMessage): boolean {
330
+ if (!response.approved) return false;
331
+ if (!response.partyId) return false;
332
+ const addrs = response.cadrePeerAddrs;
333
+ if (!addrs || addrs.length === 0) return false;
334
+ if (addrs.some((a) => PLACEHOLDER_CADRE_ADDR.test(a))) return false;
335
+ const provision = response.provisionResult;
336
+ if (!provision?.strand?.strandId) return false;
337
+ if (provision.strand.createdBy !== 'responder') return false;
338
+ return true;
339
+ }
340
+
341
+ /**
342
+ * Ceiling for a resolved provisioning budget.
343
+ *
344
+ * The session budget also has to cover the wire step that PRECEDES provisioning (the
345
+ * responder's contact read, the initiator's dial-connect), so a whole step is held back
346
+ * rather than triggering only on a literal overrun.
347
+ *
348
+ * `reserveMs` is the EXTRA room only the responder holds back, so its own budget still
349
+ * lands strictly before the initiator's larger await-response budget even when both are
350
+ * clamped — without it, any configured budget at or above `sessionTimeoutMs -
351
+ * stepTimeoutMs` clamps both roles onto the same number and the responder's clean
352
+ * rejection races the initiator's timeout again. Capped at half the remaining room (like
353
+ * {@link splitProvisionBudget}) so a small session config still spends most of it working.
354
+ */
355
+ function provisionCeilingMs(sessionTimeoutMs: number, stepTimeoutMs: number, reserveMs: number): number {
356
+ const roomMs = sessionTimeoutMs - stepTimeoutMs;
357
+ return Math.max(1, roomMs - Math.min(reserveMs, Math.floor(roomMs / 2)));
358
+ }
359
+
360
+ /**
361
+ * Resolve a caller-supplied provisioning budget: `0`/negative means "unset" (use
362
+ * `defaultMs`). If the result would let provisioning outlive the session — no result
363
+ * frame is ever sent, exactly the failure this budget exists to prevent — clamp it to
364
+ * {@link provisionCeilingMs} and log a warning.
365
+ */
366
+ function resolveProvisionTimeoutMs(
367
+ configured: number | undefined,
368
+ defaultMs: number,
369
+ sessionTimeoutMs: number,
370
+ stepTimeoutMs: number,
371
+ role: string,
372
+ reserveMs = 0
373
+ ): number {
374
+ const requested = configured && configured > 0 ? configured : defaultMs;
375
+ const ceilingMs = provisionCeilingMs(sessionTimeoutMs, stepTimeoutMs, reserveMs);
376
+ if (requested >= ceilingMs) {
377
+ log(
378
+ '%s provisionTimeoutMs %dms leaves no room under sessionTimeoutMs %dms (step %dms, reserve %dms); clamping to %dms',
379
+ role, requested, sessionTimeoutMs, stepTimeoutMs, reserveMs, ceilingMs
380
+ );
381
+ return ceilingMs;
382
+ }
383
+ return requested;
384
+ }
385
+
386
+ /**
387
+ * Split a resolved provisioning budget into the WORK budget and the trailing settle grace.
388
+ *
389
+ * The grace is carved OUT of the budget (see {@link PROVISION_SETTLE_GRACE_MS}), and capped at
390
+ * half of it so a small configured budget still spends at least half its time doing work.
391
+ */
392
+ function splitProvisionBudget(provisionTimeoutMs: number): { workMs: number; graceMs: number } {
393
+ const graceMs = Math.min(PROVISION_SETTLE_GRACE_MS, Math.floor(provisionTimeoutMs / 2));
394
+ return { workMs: provisionTimeoutMs - graceMs, graceMs };
395
+ }
396
+
397
+ // ── Responder (listener) ─────────────────────────────────────────────────────
398
+
399
+ export interface FormationListenerOptions {
400
+ /** Validate the invitation token; returns whether it is valid. */
401
+ validateToken(token: string): Promise<{ valid: boolean }>;
402
+ /** Validate the initiator's disclosure with the REAL token + disclosure. */
403
+ validateDisclosure(token: string, disclosure: StrandFormationDisclosure): Promise<boolean>;
404
+ /**
405
+ * Provision (or, for provision-then-record, resolve + record consent against) the
406
+ * strand (`responderCreates`) for the given initiator. The WHOLE contact message is
407
+ * threaded in: the hook needs the REAL token to map the bound host strand, and the
408
+ * joiner's `peerKey`/`usageStampId`/`peerSignature` to write the consent columns.
409
+ *
410
+ * Returns a {@link ResponderProvisionOutcome}: the hook may REJECT post-validation
411
+ * (e.g. an unconverged host strand) and the listener turns that into a clean,
412
+ * non-disclosing `approved: false` reply rather than dropping the result frame.
413
+ *
414
+ * `signal` is aborted when the listener's work budget expires: a hook that observes it
415
+ * BEFORE writing abandons the redemption and leaves the invite unspent. Optional so
416
+ * signal-unaware hooks (tests, mocks) stay assignable.
417
+ */
418
+ provisionStrand(contact: FormationContactMessage, signal?: AbortSignal): Promise<ResponderProvisionOutcome>;
419
+ /** Responder identity, disclosed only AFTER token + disclosure validation passes. */
420
+ getResponderIdentity(): { partyId: string; cadrePeerAddrs: string[] };
421
+ /**
422
+ * This node's live STRAND-network multiaddrs for a provisioned strand, read on the
423
+ * approval path only (same disclosure timing as {@link getResponderIdentity}) and
424
+ * carried back as {@link FormationResultMessage.strandAddrs}.
425
+ *
426
+ * Optional, and an empty answer is legal: the strand may not be running here yet (the
427
+ * responder-provisions path mints it during this very session). The listener cannot
428
+ * reach the strand runtime itself, so this is the seam `CadreNode` wires to its own
429
+ * per-strand address lookup.
430
+ */
431
+ resolveStrandAddrs?(strandId: string): string[];
432
+ sessionTimeoutMs?: number;
433
+ stepTimeoutMs?: number;
434
+ /**
435
+ * Budget for the `provisionStrand` hook call — distinct from `stepTimeoutMs` because
436
+ * provisioning is real work, not a bare wire read/write. Default 12 s; `0`/unset uses
437
+ * the default; a value that would outlive the session is clamped ({@link
438
+ * provisionCeilingMs}). See {@link DEFAULT_PROVISION_TIMEOUT_MS} for the full ordering
439
+ * rationale.
440
+ */
441
+ provisionTimeoutMs?: number;
442
+ maxConcurrentSessions?: number;
443
+ }
444
+
445
+ /**
446
+ * Responder side of the native formation protocol. Registers a libp2p handler and
447
+ * drives each inbound stream through token + disclosure validation, provisioning,
448
+ * and result delivery — enforcing the cadre-disclosure timing rule (responder cadre
449
+ * is revealed only after validation; rejections disclose nothing).
450
+ */
451
+ export class FormationListener {
452
+ private readonly options: FormationListenerOptions;
453
+ private readonly sessionTimeoutMs: number;
454
+ private readonly stepTimeoutMs: number;
455
+ private readonly provisionWorkMs: number;
456
+ private readonly provisionGraceMs: number;
457
+ private readonly maxConcurrentSessions: number;
458
+ private readonly registered = new Set<Libp2p>();
459
+ private activeSessions = 0;
460
+ private sessionCounter = 0;
461
+
462
+ constructor(options: FormationListenerOptions) {
463
+ this.options = options;
464
+ this.sessionTimeoutMs = options.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;
465
+ this.stepTimeoutMs = options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS;
466
+ const split = splitProvisionBudget(resolveProvisionTimeoutMs(
467
+ options.provisionTimeoutMs, DEFAULT_PROVISION_TIMEOUT_MS,
468
+ this.sessionTimeoutMs, this.stepTimeoutMs, 'FormationListener',
469
+ PROVISION_RESPONSE_TRAVEL_MARGIN_MS
470
+ ));
471
+ this.provisionWorkMs = split.workMs;
472
+ this.provisionGraceMs = split.graceMs;
473
+ this.maxConcurrentSessions = options.maxConcurrentSessions ?? DEFAULT_MAX_CONCURRENT_SESSIONS;
474
+ }
475
+
476
+ /** Number of in-flight inbound sessions. */
477
+ get activeCount(): number {
478
+ return this.activeSessions;
479
+ }
480
+
481
+ register(node: Libp2p, protocolId: string = FORMATION_PROTOCOL): void {
482
+ if (this.registered.has(node)) {
483
+ log('node already registered');
484
+ return;
485
+ }
486
+ void node.handle(protocolId, async (rawStream: unknown, _connection: unknown) => {
487
+ await this.handleStream(rawStream as ControlStream);
488
+ });
489
+ this.registered.add(node);
490
+ log('formation listener registered (%s)', protocolId);
491
+ }
492
+
493
+ unregister(node: Libp2p, protocolId: string = FORMATION_PROTOCOL): void {
494
+ if (!this.registered.has(node)) return;
495
+ void node.unhandle(protocolId);
496
+ this.registered.delete(node);
497
+ log('formation listener unregistered (%s)', protocolId);
498
+ }
499
+
500
+ private async handleStream(stream: ControlStream): Promise<void> {
501
+ if (this.activeSessions >= this.maxConcurrentSessions) {
502
+ const rejection: FormationResultMessage = { approved: false, reason: 'Too many concurrent formation sessions' };
503
+ try { writeFrame(stream, rejection); } catch { /* best effort */ }
504
+ try { await stream.close(); } catch { /* ignore */ }
505
+ return;
506
+ }
507
+ const id = ++this.sessionCounter;
508
+ this.activeSessions++;
509
+ try {
510
+ await withTimeout(this.sessionTimeoutMs, `Formation session#${id}`, () => this.runSession(id, stream));
511
+ } catch (err) {
512
+ log('formation session #%d failed: %o', id, err);
513
+ } finally {
514
+ this.activeSessions--;
515
+ try { await stream.close(); } catch { /* ignore */ }
516
+ }
517
+ }
518
+
519
+ /**
520
+ * Run the provisioning hook under its WORK budget — the configured provisioning budget minus
521
+ * the trailing settle grace ({@link splitProvisionBudget}, {@link PROVISION_SETTLE_GRACE_MS}).
522
+ *
523
+ * When the work budget expires the hook's signal is aborted, then
524
+ * {@link settleWithinGrace} waits out the grace for the aborted work to settle anyway.
525
+ * Returns `undefined` for "timed out" — which the caller turns into a retryable rejection
526
+ * frame — and rethrows every other failure so it reaches the internal-error path.
527
+ *
528
+ * Deliberately not `withDeadline`: that exposes neither the timed-out flag nor the signal
529
+ * outside its `op`, and both are needed here.
530
+ */
531
+ private async provision(id: number, contact: FormationContactMessage): Promise<ResponderProvisionOutcome | undefined> {
532
+ const controller = new AbortController();
533
+ let timedOut = false;
534
+ const pending = this.options.provisionStrand(contact, controller.signal);
535
+ try {
536
+ return await withTimeout(
537
+ this.provisionWorkMs,
538
+ `Formation provisioning#${id}`,
539
+ () => pending,
540
+ () => { timedOut = true; controller.abort(); }
541
+ );
542
+ } catch (err) {
543
+ if (!timedOut) throw err;
544
+ log(
545
+ 'formation session #%d provisioning work budget expired after %dms; aborted, settling up to %dms',
546
+ id, this.provisionWorkMs, this.provisionGraceMs
547
+ );
548
+ return await this.settleWithinGrace(id, pending);
549
+ }
550
+ }
551
+
552
+ /**
553
+ * Wait out the settle grace for an ABORTED provisioning, adopting a late success.
554
+ *
555
+ * A hook that observed the abort before issuing its `FormationUsage` insert rejects (with
556
+ * `FormationAbortedError`) and leaves the invite unspent → reported as a timeout. A hook
557
+ * that had already written cannot be un-written (the table is append-only), so if it lands
558
+ * inside the grace its outcome is ADOPTED — the joiner is told the truth (approved, or the
559
+ * hook's own rejection reason) rather than "timed out" over a spent invite.
560
+ *
561
+ * NOTE: one window stays open — a work budget that expires after the `FormationUsage`
562
+ * insert was issued AND a commit that outlasts the grace. The joiner is told 'timed out'
563
+ * while its one-time invite is in fact spent, and since every retry mints a fresh keypair
564
+ * no recovery path can match it. Nothing can un-spend an append-only row, so the late-settle
565
+ * logging below is the observability for it; widen the grace only if it is seen in the wild.
566
+ */
567
+ private async settleWithinGrace(
568
+ id: number,
569
+ pending: Promise<ResponderProvisionOutcome>
570
+ ): Promise<ResponderProvisionOutcome | undefined> {
571
+ let stillPending = false;
572
+ try {
573
+ const outcome = await withTimeout(
574
+ this.provisionGraceMs,
575
+ `Formation settle#${id}`,
576
+ () => pending,
577
+ () => { stillPending = true; }
578
+ );
579
+ log('formation session #%d provisioning settled within its grace: approved=%s — adopting', id, outcome.approved);
580
+ return outcome;
581
+ } catch (err) {
582
+ if (!stillPending) {
583
+ log('formation session #%d provisioning failed after its abort: %o', id, err);
584
+ return undefined;
585
+ }
586
+ log('formation session #%d provisioning still pending after its %dms grace', id, this.provisionGraceMs);
587
+ // Log how it eventually settled so a late failure is not swallowed by the two
588
+ // abandoned `withTimeout` calls.
589
+ void pending.then(
590
+ (late) => log('formation session #%d provisioning settled after its grace: approved=%s', id, late.approved),
591
+ (err2) => log('formation session #%d provisioning failed after its grace: %o', id, err2)
592
+ );
593
+ return undefined;
594
+ }
595
+ }
596
+
597
+ /**
598
+ * Joiner-consent pre-check — the legibility twin of the schema's
599
+ * `FormationUsage.PeerConsented` CHECK, exactly as `verifyFormationApproval` is for the
600
+ * approver's vouch. The database constraint stays the authority; this turns a bad consent
601
+ * into a clean 'Invalid joiner consent' rejection instead of an opaque CHECK failure at
602
+ * commit. Runs BEFORE token/disclosure validation: it is the cheapest check (pure local
603
+ * crypto, no DB read) and a rejection discloses nothing.
604
+ *
605
+ * Also pins `partyId` to `peerKey`: an ed25519 peer id is an identity multihash of the
606
+ * very key, and this is the ONLY layer that can check the match — SQL cannot unwrap a
607
+ * multihash, and `partyId` itself is never stored.
608
+ */
609
+ private isJoinerConsentValid(id: number, contact: FormationContactMessage): boolean {
610
+ try {
611
+ requireEd25519PublicKeyB64(contact.peerKey, 'joiner peer key');
612
+ } catch {
613
+ // Deliberately not rethrown or echoed: the helper's error message embeds the whole
614
+ // rejected value, and this one arrived from a remote peer (the cap-the-echo case its
615
+ // own NOTE warns about). Log without the raw value instead.
616
+ log('formation session #%d: joiner peer key is not a base64url ed25519 public key', id);
617
+ return false;
618
+ }
619
+ const embedded = ed25519PublicKeyB64FromPeerId(contact.partyId);
620
+ if (!embedded || embedded !== contact.peerKey) {
621
+ log('formation session #%d: partyId does not embed the presented peer key', id);
622
+ return false;
623
+ }
624
+ const consentOk = verifyFormationConsent({
625
+ token: contact.token,
626
+ usageStampId: contact.usageStampId,
627
+ peerKey: contact.peerKey,
628
+ disclosure: canonicalJson(contact.disclosure),
629
+ peerSig: contact.peerSignature
630
+ });
631
+ if (!consentOk) {
632
+ log('formation session #%d: joiner consent signature failed verification', id);
633
+ return false;
634
+ }
635
+ return true;
636
+ }
637
+
638
+ /**
639
+ * The strand addresses to disclose for an APPROVED provisioning, sanitized and capped.
640
+ *
641
+ * Never throws: a hook that fails (a strand runtime torn down mid-session) costs the
642
+ * joiner its cross-party seed, not the formation it has already earned — the seed is
643
+ * an optimization, the consent row is the commitment.
644
+ */
645
+ private strandAddrsFor(id: number, strandId: string): string[] {
646
+ if (!this.options.resolveStrandAddrs) return [];
647
+ try {
648
+ return sanitizeStrandAddrs(this.options.resolveStrandAddrs(strandId));
649
+ } catch (err) {
650
+ log('formation session #%d: strand-addr lookup for %s failed (continuing): %o', id, strandId, err);
651
+ return [];
652
+ }
653
+ }
654
+
655
+ private async runSession(id: number, stream: ControlStream): Promise<void> {
656
+ // Track whether ANY frame has been written so the catch below can convert an
657
+ // unexpected internal error into a non-disclosing rejection ONLY when nothing has
658
+ // gone out yet. This closes the "stream closed with no result frame" class of bug.
659
+ let wroteFrame = false;
660
+ const send = (msg: FormationResultMessage): void => {
661
+ writeFrame(stream, msg);
662
+ wroteFrame = true;
663
+ };
664
+
665
+ try {
666
+ const reader = new FrameReader(stream);
667
+ const contact = await withTimeout(this.stepTimeoutMs, `Formation await-contact#${id}`, () => reader.read<FormationContactMessage>());
668
+ log('formation session #%d contact: token=%s party=%s', id, contact.token, contact.partyId);
669
+
670
+ if (!this.isJoinerConsentValid(id, contact)) {
671
+ send({ approved: false, reason: 'Invalid joiner consent' });
672
+ return;
673
+ }
674
+
675
+ const tokenResult = await this.options.validateToken(contact.token);
676
+ if (!tokenResult.valid) {
677
+ send({ approved: false, reason: INVALID_TOKEN_REASON });
678
+ return;
679
+ }
680
+
681
+ const disclosureOk = await this.options.validateDisclosure(contact.token, contact.disclosure);
682
+ if (!disclosureOk) {
683
+ send({ approved: false, reason: 'Invalid disclosure' });
684
+ return;
685
+ }
686
+
687
+ const outcome = await this.provision(id, contact);
688
+ if (!outcome) {
689
+ // Reported as its own retryable reason rather than falling through to the generic
690
+ // catch below, which would report the misleading 'Internal formation error'.
691
+ send({ approved: false, reason: 'Formation provisioning timed out' });
692
+ return;
693
+ }
694
+ if (!outcome.approved) {
695
+ // A post-validation rejection still discloses NEITHER identity NOR cadre,
696
+ // exactly like the token/disclosure rejections above.
697
+ send({ approved: false, 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: FormationResultMessage = { approved: false, 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
+ /** Responder multiaddrs to dial. */
735
+ responderAddrs: string[];
736
+ /** Validate the responder's result; a false return aborts the formation. */
737
+ validateResponse(response: FormationResultMessage): Promise<boolean>;
738
+ sessionTimeoutMs?: number;
739
+ stepTimeoutMs?: number;
740
+ /**
741
+ * Budget for the `await-response` read only (the responder's provisioning + reply travel
742
+ * time) — `dial-connect` keeps using `stepTimeoutMs`. Default 15 s; `0`/unset uses the
743
+ * default. See {@link DEFAULT_PROVISION_TIMEOUT_MS} for the full ordering rationale.
744
+ */
745
+ provisionTimeoutMs?: number;
746
+ protocolId?: string;
747
+ }
748
+
749
+ /**
750
+ * What one successful formation dial yields the initiator.
751
+ *
752
+ * The provisioned strand travels in {@link FormationProvisionResult}, but the responder's
753
+ * strand-network addresses are NOT part of that structure — they are a disclosure of the
754
+ * responder's live runtime, alongside `partyId`/`cadrePeerAddrs`, not a property of the
755
+ * strand row. Returning them beside the provision result keeps that separation while
756
+ * still handing the caller the one thing it needs to seed a cross-party mesh.
757
+ *
758
+ * `strandAddrs` is always an array and is frequently EMPTY — see
759
+ * {@link FormationResultMessage.strandAddrs}.
760
+ */
761
+ export interface FormationDialResult {
762
+ provision: FormationProvisionResult;
763
+ /** Sanitized + capped ({@link sanitizeStrandAddrs}); `[]` when the responder sent none. */
764
+ strandAddrs: string[];
765
+ }
766
+
767
+ /**
768
+ * Initiator side of the native formation protocol. Dials the responder, sends the
769
+ * contact (carrying the real disclosure/token/cadre), validates the responder's
770
+ * result, and returns the strand the responder provisioned plus the responder's
771
+ * strand-network addresses (see {@link FormationDialResult}).
772
+ */
773
+ export async function dialFormation(node: Libp2p, options: FormationDialOptions): Promise<FormationDialResult> {
774
+ if (options.responderAddrs.length === 0) {
775
+ throw new Error('No responder addresses available for formation');
776
+ }
777
+ const protocolId = options.protocolId ?? FORMATION_PROTOCOL;
778
+ const sessionTimeoutMs = options.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;
779
+ const stepTimeoutMs = options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS;
780
+ const provisionTimeoutMs = resolveProvisionTimeoutMs(
781
+ options.provisionTimeoutMs, DEFAULT_INITIATOR_PROVISION_TIMEOUT_MS,
782
+ sessionTimeoutMs, stepTimeoutMs, 'dialFormation'
783
+ );
784
+ const addr = multiaddr(options.responderAddrs[0]);
785
+
786
+ return withTimeout(sessionTimeoutMs, 'Formation dial', async () => {
787
+ const rawStream = await withTimeout(stepTimeoutMs, 'Formation dial-connect', async () => node.dialProtocol(addr, protocolId));
788
+ const stream = rawStream as unknown as ControlStream;
789
+ try {
790
+ const reader = new FrameReader(stream);
791
+ writeFrame(stream, options.contact);
792
+
793
+ const response = await withTimeout(provisionTimeoutMs, 'Formation await-response', () => reader.read<FormationResultMessage>());
794
+ if (!response.approved) {
795
+ throw new Error(`Formation rejected: ${response.reason ?? 'no reason provided'}`);
796
+ }
797
+ const ok = await options.validateResponse(response);
798
+ if (!ok) throw new Error('Responder result failed validation');
799
+
800
+ if (!response.provisionResult) throw new Error('Missing provision result for responderCreates mode');
801
+ // Sanitized HERE — the wire boundary — so nothing above this call ever handles an
802
+ // unvalidated, unbounded address list from a remote peer.
803
+ return { provision: response.provisionResult, strandAddrs: sanitizeStrandAddrs(response.strandAddrs) };
804
+ } finally {
805
+ try { await stream.close(); } catch { /* ignore */ }
806
+ }
807
+ });
808
+ }