@serfab/cadre-core 0.10.0 → 0.11.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 (105) hide show
  1. package/README.md +255 -255
  2. package/dist/cadre-node.d.ts +203 -28
  3. package/dist/cadre-node.js +445 -84
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-cohort.d.ts +26 -0
  6. package/dist/control-cohort.js +26 -0
  7. package/dist/control-cohort.js.map +1 -1
  8. package/dist/control-database.d.ts +82 -117
  9. package/dist/control-database.js +217 -295
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-formation-recorder.d.ts +8 -7
  12. package/dist/control-formation-recorder.js +8 -7
  13. package/dist/control-formation-recorder.js.map +1 -1
  14. package/dist/control-schema.d.ts +1 -1
  15. package/dist/control-schema.js +789 -774
  16. package/dist/control-schema.js.map +1 -1
  17. package/dist/control-write-retry.d.ts +15 -5
  18. package/dist/control-write-retry.js +19 -18
  19. package/dist/control-write-retry.js.map +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/peer-addr-book.d.ts +92 -0
  24. package/dist/peer-addr-book.js +220 -0
  25. package/dist/peer-addr-book.js.map +1 -0
  26. package/dist/seed-bootstrap.d.ts +7 -0
  27. package/dist/seed-bootstrap.js +15 -13
  28. package/dist/seed-bootstrap.js.map +1 -1
  29. package/dist/strand-cohort.d.ts +4 -37
  30. package/dist/strand-cohort.js +4 -15
  31. package/dist/strand-cohort.js.map +1 -1
  32. package/dist/strand-database.d.ts +11 -16
  33. package/dist/strand-database.js +19 -7
  34. package/dist/strand-database.js.map +1 -1
  35. package/dist/strand-formation-manager.d.ts +8 -8
  36. package/dist/strand-formation-manager.js +15 -18
  37. package/dist/strand-formation-manager.js.map +1 -1
  38. package/dist/strand-instance-manager.d.ts +52 -21
  39. package/dist/strand-instance-manager.js +100 -34
  40. package/dist/strand-instance-manager.js.map +1 -1
  41. package/dist/strand-membership-writer.d.ts +6 -4
  42. package/dist/strand-membership-writer.js +38 -36
  43. package/dist/strand-membership-writer.js.map +1 -1
  44. package/dist/types.d.ts +39 -31
  45. package/dist/types.js.map +1 -1
  46. package/package.json +8 -7
  47. package/src/arachnode-stub.ts +159 -159
  48. package/src/bootstrap-peer-store-file.ts +44 -44
  49. package/src/bootstrap-peer-store.ts +172 -172
  50. package/src/cadre-node.ts +5158 -4771
  51. package/src/canonical-json.ts +30 -30
  52. package/src/control-authorization.ts +114 -114
  53. package/src/control-cohort.ts +130 -103
  54. package/src/control-database.ts +2406 -2506
  55. package/src/control-formation-recorder.ts +305 -304
  56. package/src/control-schema.ts +801 -786
  57. package/src/control-stream.ts +205 -205
  58. package/src/control-write-retry.ts +483 -473
  59. package/src/delegate-admission.ts +302 -302
  60. package/src/device-token.ts +94 -94
  61. package/src/diagnostics/connection-path.ts +277 -277
  62. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  63. package/src/ed25519-key.ts +134 -134
  64. package/src/enrollment.ts +199 -199
  65. package/src/file-durable-slot.ts +61 -61
  66. package/src/formation-approval.ts +604 -604
  67. package/src/fs-atomic.ts +107 -107
  68. package/src/hibernation-manager.ts +437 -437
  69. package/src/identity-key.ts +109 -109
  70. package/src/index.ts +1 -0
  71. package/src/key-store-file.ts +132 -132
  72. package/src/key-store.ts +99 -99
  73. package/src/membership-connection-gater.ts +204 -204
  74. package/src/node-local-snapshot.ts +260 -260
  75. package/src/peer-addr-book.ts +250 -0
  76. package/src/peer-authorization.ts +259 -259
  77. package/src/peer-record.ts +164 -164
  78. package/src/push-credentials.ts +84 -84
  79. package/src/push-node.ts +64 -64
  80. package/src/push-notifier-apns.ts +247 -247
  81. package/src/push-notifier-fcm.ts +220 -220
  82. package/src/push-notifier-shared.ts +28 -28
  83. package/src/push-notifier.ts +52 -52
  84. package/src/relay-addrs.ts +111 -111
  85. package/src/relay-reservation.ts +823 -823
  86. package/src/seed-bootstrap.ts +15 -15
  87. package/src/seed-trust-policy.ts +140 -140
  88. package/src/strand-addr-protocol.ts +441 -441
  89. package/src/strand-backfill.ts +366 -366
  90. package/src/strand-cohort.ts +38 -77
  91. package/src/strand-database.ts +202 -204
  92. package/src/strand-formation-manager.ts +491 -494
  93. package/src/strand-formation-protocol.ts +692 -692
  94. package/src/strand-instance-manager.ts +108 -50
  95. package/src/strand-member-key.ts +39 -39
  96. package/src/strand-member-registry.ts +182 -182
  97. package/src/strand-membership-writer.ts +1432 -1430
  98. package/src/strand-solicitation.ts +472 -472
  99. package/src/strand-transport-key.ts +58 -58
  100. package/src/strand-wake-payload.ts +32 -32
  101. package/src/strand-wake-protocol.ts +314 -314
  102. package/src/strand-watcher.ts +314 -314
  103. package/src/trusted-owner-store-file.ts +41 -41
  104. package/src/trusted-owner-store.ts +171 -171
  105. package/src/types.ts +1309 -1303
@@ -1,494 +1,491 @@
1
- import debug from 'debug';
2
- import { fromString as uint8ArrayFromString } from 'uint8arrays';
3
- import type { Libp2p } from '@libp2p/interface';
4
- import type {
5
- OpenInvitation,
6
- FormStrandResult,
7
- StrandFormationDisclosure
8
- } from './types.js';
9
- import {
10
- FormationApprovalError,
11
- type FormationApprovalFailure
12
- } from './formation-approval.js';
13
- // control-database does not import this manager, so this import introduces no cycle.
14
- import { FormationAbortedError, InvitationExhaustedError } from './control-database.js';
15
- import { canonicalJson } from './canonical-json.js';
16
- import type {
17
- DisclosureValidator,
18
- FormationUsageRecorder,
19
- ResolvedHostStrand,
20
- StrandProvisioner,
21
- FormationResponseValidator
22
- } from './strand-solicitation.js';
23
- import {
24
- FormationListener,
25
- INVALID_TOKEN_REASON,
26
- PROVISION_RESPONSE_TRAVEL_MARGIN_MS,
27
- dialFormation,
28
- isValidResponderCreatesResult,
29
- type FormationContactMessage,
30
- type FormationProvisionResult,
31
- type FormationResultMessage,
32
- type ResponderProvisionOutcome
33
- } from './strand-formation-protocol.js';
34
-
35
- const log = debug('sereus:cadre:formation-manager');
36
-
37
- /**
38
- * Largest serialized disclosure a responder will accept (8 KiB). The disclosure is
39
- * attacker-influenced text destined for a replicated table (`FormationUsage.Disclosure`)
40
- * and for the approval hook's signed digest — the cap bounds both, and is enforced BEFORE
41
- * any database read or hook contact so an oversized blob costs nothing downstream.
42
- */
43
- const MAX_DISCLOSURE_BYTES = 8 * 1024;
44
-
45
- /**
46
- * Rejection reason a would-be joiner is told for each approval-failure category
47
- * (see {@link FormationApprovalFailure}). Distinct per category on purpose: mapping any
48
- * of these onto the generic 'Formation conflict, retry' would tell an operator to retry
49
- * what retrying can never fix (e.g. a non-enrolled validation key).
50
- */
51
- const APPROVAL_REJECTION_REASONS: Record<FormationApprovalFailure, string> = {
52
- refused: 'Formation approval refused',
53
- unavailable: 'Formation approval unavailable, retry',
54
- malformed: 'Formation approval invalid',
55
- unenrolled: 'Formation approval key is not enrolled',
56
- misconfigured: 'Formation approval misconfigured'
57
- };
58
-
59
- /**
60
- * Configuration for StrandFormationManager
61
- */
62
- export interface StrandFormationManagerConfig {
63
- /** Session timeout in milliseconds */
64
- sessionTimeoutMs?: number;
65
- /** Step timeout in milliseconds */
66
- stepTimeoutMs?: number;
67
- /**
68
- * Provisioning budget in milliseconds for the RESPONDER's `provisionStrand` hook call.
69
- * The initiator's `await-response` wait is derived automatically from this value plus
70
- * `PROVISION_RESPONSE_TRAVEL_MARGIN_MS` (`strand-formation-protocol.ts`) — never set
71
- * directly — so the ordering documented there (approval hook < responder provisioning <
72
- * initiator await-response < session) cannot collapse when this is configured.
73
- */
74
- provisionTimeoutMs?: number;
75
- /** Maximum concurrent sessions */
76
- maxConcurrentSessions?: number;
77
- /** Enable debug logging */
78
- enableDebugLogging?: boolean;
79
- /** Protocol ID override */
80
- protocolId?: string;
81
- }
82
-
83
- /**
84
- * Options for creating a StrandFormationManager
85
- */
86
- export interface StrandFormationManagerOptions {
87
- /** Validates disclosures from initiators (responder side) */
88
- disclosureValidator?: DisclosureValidator;
89
- /** Records and validates token usage (responder side) */
90
- formationUsageRecorder?: FormationUsageRecorder;
91
- /** Provisions strands after validation (responder side) */
92
- strandProvisioner?: StrandProvisioner;
93
- /** Validates the responder's result (initiator side); defaults to a structural check */
94
- formationResponseValidator?: FormationResponseValidator;
95
- /** This party's ID for identification */
96
- partyId: string;
97
- /** This party's cadre peer addresses */
98
- cadrePeerAddrs?: string[];
99
- /** Configuration options */
100
- config?: StrandFormationManagerConfig;
101
- }
102
-
103
- /**
104
- * StrandFormationManager drives the native cadre-core formation transport
105
- * (`strand-formation-protocol.ts`) from cadre-core's strand-solicitation interfaces.
106
- *
107
- * Responder side: a {@link FormationListener} wires the inbound protocol to
108
- * {@link FormationUsageRecorder} (token), {@link DisclosureValidator} (identity),
109
- * and {@link StrandProvisioner} (provisioning), disclosing this party's real
110
- * identity + cadre only after validation.
111
- *
112
- * Initiator side: {@link formStrand} dials the responder carrying the real
113
- * disclosure/token/cadre, then validates the responder's result via the
114
- * {@link FormationResponseValidator} (or a built-in structural check).
115
- */
116
- export class StrandFormationManager {
117
- private readonly disclosureValidator?: DisclosureValidator;
118
- private readonly formationUsageRecorder?: FormationUsageRecorder;
119
- private readonly strandProvisioner?: StrandProvisioner;
120
- private readonly formationResponseValidator?: FormationResponseValidator;
121
- private readonly partyId: string;
122
- private readonly cadrePeerAddrs: string[];
123
- private readonly config: StrandFormationManagerConfig;
124
- private readonly listener: FormationListener;
125
- private readonly registeredNodes = new Set<Libp2p>();
126
- private dialerSessions = 0;
127
-
128
- constructor(options: StrandFormationManagerOptions) {
129
- this.disclosureValidator = options.disclosureValidator;
130
- this.formationUsageRecorder = options.formationUsageRecorder;
131
- this.strandProvisioner = options.strandProvisioner;
132
- this.formationResponseValidator = options.formationResponseValidator;
133
- this.partyId = options.partyId;
134
- this.cadrePeerAddrs = options.cadrePeerAddrs ?? [];
135
- this.config = options.config ?? {};
136
-
137
- this.listener = new FormationListener({
138
- validateToken: (token) => this.validateToken(token),
139
- validateDisclosure: (token, disclosure) => this.validateDisclosure(token, disclosure),
140
- provisionStrand: (contact, signal) =>
141
- this.provisionAsResponder(contact, signal),
142
- getResponderIdentity: () => ({ partyId: this.partyId, cadrePeerAddrs: this.cadrePeerAddrs }),
143
- sessionTimeoutMs: this.config.sessionTimeoutMs,
144
- stepTimeoutMs: this.config.stepTimeoutMs,
145
- provisionTimeoutMs: this.config.provisionTimeoutMs,
146
- maxConcurrentSessions: this.config.maxConcurrentSessions
147
- });
148
-
149
- log('StrandFormationManager created for party: %s', this.partyId);
150
- }
151
-
152
- /**
153
- * Register this manager as a protocol handler on a libp2p node.
154
- * Call this on the control network node to handle incoming formation requests.
155
- */
156
- registerResponder(node: Libp2p, protocolId?: string): void {
157
- if (this.registeredNodes.has(node)) {
158
- log('Node already registered');
159
- return;
160
- }
161
- this.listener.register(node, protocolId ?? this.config.protocolId);
162
- this.registeredNodes.add(node);
163
- log('Registered as responder on node');
164
- }
165
-
166
- /**
167
- * Unregister the protocol handler from a libp2p node.
168
- */
169
- unregisterResponder(node: Libp2p, protocolId?: string): void {
170
- if (!this.registeredNodes.has(node)) {
171
- return;
172
- }
173
- this.listener.unregister(node, protocolId ?? this.config.protocolId);
174
- this.registeredNodes.delete(node);
175
- log('Unregistered from node');
176
- }
177
-
178
- /**
179
- * Form a strand with a responder via an open invitation (initiator side).
180
- *
181
- * Builds a contact message carrying the real token + disclosure + this party's
182
- * real cadre addresses + the joiner's consent (minted and signed by the
183
- * solicitation layer — this manager only places it on the contact), dials the
184
- * responder over the native protocol, and validates the responder's result
185
- * before returning.
186
- */
187
- async formStrand(
188
- invitation: OpenInvitation,
189
- disclosure: StrandFormationDisclosure,
190
- consent: { peerKey: string; usageStampId: string; peerSignature: string },
191
- node: Libp2p
192
- ): Promise<FormStrandResult> {
193
- log('Forming strand with invitation token: %s', invitation.token);
194
-
195
- const contact: FormationContactMessage = {
196
- token: invitation.token,
197
- partyId: disclosure.partyId ?? this.partyId,
198
- peerKey: consent.peerKey,
199
- usageStampId: consent.usageStampId,
200
- peerSignature: consent.peerSignature,
201
- disclosure,
202
- cadrePeerAddrs: this.cadrePeerAddrs
203
- };
204
-
205
- this.dialerSessions++;
206
- try {
207
- const provision = await dialFormation(node, {
208
- contact,
209
- responderAddrs: invitation.bootstrap,
210
- validateResponse: (response) => this.validateResponse(invitation, disclosure, response),
211
- sessionTimeoutMs: this.config.sessionTimeoutMs,
212
- stepTimeoutMs: this.config.stepTimeoutMs,
213
- provisionTimeoutMs: this.initiatorProvisionTimeoutMs(),
214
- protocolId: this.config.protocolId
215
- });
216
-
217
- log('Strand formed: %s', provision.strand.strandId);
218
-
219
- return {
220
- memberKey: contact.partyId,
221
- invitePrivateKey: '',
222
- strandId: provision.strand.strandId,
223
- // The host strand's membership key, delivered through the protocol (provision-then-record).
224
- // Undefined for an open strand. Kept separate from invitePrivateKey (the initiator's
225
- // generated signing key), which is set by the StrandSolicitationService layer.
226
- memberPrivateKey: provision.memberPrivateKey
227
- };
228
- } finally {
229
- this.dialerSessions--;
230
- }
231
- }
232
-
233
- /**
234
- * Get the number of active sessions
235
- */
236
- getActiveSessionCounts(): { listeners: number; dialers: number } {
237
- return { listeners: this.listener.activeCount, dialers: this.dialerSessions };
238
- }
239
-
240
- /**
241
- * Derive the initiator's await-response budget from the configured RESPONDER budget —
242
- * never the same number (see `StrandFormationManagerConfig.provisionTimeoutMs`). Mirrors
243
- * `resolveProvisionTimeoutMs`'s own "`0`/negative means unset" rule so an unset config
244
- * still lets both sides fall back to their own independent defaults; must NOT hardcode
245
- * `DEFAULT_PROVISION_TIMEOUT_MS` here, or the per-role clamping downstream is defeated.
246
- * A value too large for the session is clamped per role, and the responder's ceiling holds
247
- * the same margin back, so the ordering survives there too.
248
- */
249
- private initiatorProvisionTimeoutMs(): number | undefined {
250
- const host = this.config.provisionTimeoutMs;
251
- return host && host > 0 ? host + PROVISION_RESPONSE_TRAVEL_MARGIN_MS : undefined;
252
- }
253
-
254
- // ── Responder-side hooks ─────────────────────────────────────────────────────
255
-
256
- private async validateToken(token: string): Promise<{ valid: boolean }> {
257
- if (!this.formationUsageRecorder) {
258
- // No recorder configured — accept all tokens.
259
- return { valid: true };
260
- }
261
-
262
- const tokenCheck = await this.formationUsageRecorder.isTokenValid(token);
263
- if (!tokenCheck.valid) {
264
- log('Token invalid: %s', token);
265
- return { valid: false };
266
- }
267
-
268
- if (await this.formationUsageRecorder.isTokenUsed(token)) {
269
- log('Token already used: %s', token);
270
- return { valid: false };
271
- }
272
-
273
- return { valid: true };
274
- }
275
-
276
- private async validateDisclosure(token: string, disclosure: StrandFormationDisclosure): Promise<boolean> {
277
- if (!this.disclosureValidator) {
278
- // No validator configured — accept all disclosures.
279
- return true;
280
- }
281
- return this.disclosureValidator.validateDisclosure(token, disclosure);
282
- }
283
-
284
- /**
285
- * Responder-side provisioning. Routes on how the invite resolves
286
- * ({@link ResolvedHostStrand}), and can REJECT post-validation by returning a
287
- * {@link ResponderProvisionOutcome} with `approved: false` — `runSession` turns that
288
- * into a clean, non-disclosing reply instead of a dropped result frame.
289
- *
290
- * - **bound** (host strand present): provision-then-record — write the single
291
- * `FormationUsage` consent row against the pre-existing strand (record-only) and
292
- * return it + its membership key (a read-gating secret disclosed only here, behind the
293
- * token + disclosure validation `runSession` already enforced).
294
- * - **missing** (invite names a host strand absent on this responder, e.g. unconverged):
295
- * reject cleanly + retryably, writing NO usage row — recording usage here would fail the
296
- * deferred `StrandExists` CHECK at commit and drop the frame.
297
- * - **unbound** (no binding): the responder-provisions fallback — see {@link provisionUnbound}.
298
- *
299
- * Defense-in-depth: known provisioning/redeem failures are caught and mapped to a logged
300
- * protocol rejection rather than a thrown insert + a silently-closed stream. The mapping is
301
- * per-failure, NOT blanket retry-suggesting: an exhausted invitation
302
- * ({@link InvitationExhaustedError}, raised by `ControlDatabase` whenever a redemption's use
303
- * number is past the invite's seat budget — including a first attempt racing another
304
- * redemption of the same token on this node, not only a retry) is reported as `'Invalid
305
- * token'`, because retrying it can never succeed. The
306
- * `(Token, UseNumber)` PK collision that concurrent redemptions of one invite used to
307
- * surface here is now retried a layer down and no longer reaches this method. The
308
- * LOG-before-reject keeps this a deliberate internal-error→protocol-rejection conversion
309
- * (AGENTS.md: don't eat exceptions silently), not control-flow-by-exception.
310
- */
311
- private async provisionAsResponder(
312
- contact: FormationContactMessage,
313
- signal?: AbortSignal
314
- ): Promise<ResponderProvisionOutcome> {
315
- const token = contact.token;
316
- // CANONICALLY serialized — both sides derive the identical string: this is the exact
317
- // text the joiner signed (consent), the approver signs (vouch), and the recorder writes
318
- // to `FormationUsage.Disclosure` — a re-serialization anywhere below would break the
319
- // signature-over-stored-bytes invariant.
320
- const disclosureText = canonicalJson(contact.disclosure);
321
- if (uint8ArrayFromString(disclosureText, 'utf8').byteLength > MAX_DISCLOSURE_BYTES) {
322
- log('Disclosure over %d bytes; rejecting token %s', MAX_DISCLOSURE_BYTES, token);
323
- return { approved: false, reason: 'Disclosure too large' };
324
- }
325
-
326
- const recorder = this.formationUsageRecorder;
327
- const resolved: ResolvedHostStrand = recorder?.resolveStrand
328
- ? await recorder.resolveStrand(token)
329
- : { kind: 'unbound' };
330
-
331
- try {
332
- switch (resolved.kind) {
333
- case 'bound': {
334
- // recorder is guaranteed non-null here: only resolveStrand can yield 'bound'.
335
- await recorder!.recordUsage({
336
- token,
337
- peerKey: contact.peerKey,
338
- peerSignature: contact.peerSignature,
339
- usageStampId: contact.usageStampId,
340
- strandId: resolved.strandId,
341
- disclosure: disclosureText,
342
- signal
343
- });
344
- return this.approve({
345
- strand: { strandId: resolved.strandId, createdBy: 'responder' },
346
- memberPrivateKey: resolved.memberPrivateKey ?? undefined,
347
- dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
348
- });
349
- }
350
- case 'missing': {
351
- log('Host strand %s not yet available on this responder; rejecting token %s', resolved.strandId, token);
352
- return { approved: false, reason: 'Host strand not yet available on this responder' };
353
- }
354
- case 'unbound':
355
- return await this.provisionUnbound(contact, disclosureText, signal);
356
- }
357
- } catch (err) {
358
- if (err instanceof FormationAbortedError) {
359
- // The listener's timeout path owns the reply for an abandoned provisioning; mapping
360
- // this onto 'Formation conflict, retry' would misreport it as a conflict.
361
- throw err;
362
- }
363
- if (err instanceof FormationApprovalError) {
364
- log('approval failed (%s) for token %s: %o', err.failure, token, err);
365
- return { approved: false, reason: APPROVAL_REJECTION_REASONS[err.failure] };
366
- }
367
- if (err instanceof InvitationExhaustedError) {
368
- // Shares `INVALID_TOKEN_REASON` with the up-front `validateToken` rejection so the loser
369
- // of the race that exposed the spent invite — same-node, first attempt, or a retry that
370
- // ran out — sees exactly what a non-racing latecomer sees. No wire-visible distinction between "invalid" and "exhausted" — the
371
- // operator signal lives in this log line instead.
372
- // NOTE: if a joining client ever has to tell "never valid" from "used up" WITHOUT node
373
- // logs, that is a new protocol reason string, not a local change here.
374
- log(
375
- 'invitation exhausted for token %s: use #%d past limit of %d',
376
- err.token,
377
- err.useNumber,
378
- err.totalUses
379
- );
380
- return { approved: false, reason: INVALID_TOKEN_REASON };
381
- }
382
- // An approval obtained before landing here is RETRIED, not discarded: the database
383
- // layer re-presents the same approver sign-off under a fresh use number when it loses
384
- // one to a writer its local write queue does not serialize — another node of the cadre,
385
- // another `Database` handle over the same store (see
386
- // `ControlDatabase.withUseNumberRetry`). Reaching this catch-all means either that retry
387
- // ran out (surfaced above as `InvitationExhaustedError`) or the failure was never
388
- // retryable to begin with.
389
- log('provisionAsResponder failed for token %s: %o', token, err);
390
- return { approved: false, reason: 'Formation conflict, retry' };
391
- }
392
- }
393
-
394
- /**
395
- * Responder-provisions fallback (invite binds no host strand). Precedence:
396
- *
397
- * 1. `recorder.provisionAndRecord` present (a real DB recorder) → atomic create-strand +
398
- * record-consent, so the unbound redemption is single-use just like the bound path.
399
- * Returns the new strand (+ key, null for an open responder-provisioned strand).
400
- * 2. else `strandProvisioner` present → the legacy/mock contract: provision a bare strand,
401
- * NO inline usage write (those callers record usage explicitly via
402
- * `recordFormationComplete`, or assert transport invariants only). Threads the invite's
403
- * REAL `sAppId`.
404
- * 3. else → a structural placeholder (no recorder + no provisioner ⇒ no single-use semantics
405
- * exist to enforce).
406
- *
407
- * Plan tradeoff — option (a) "record usage on the fallback" over (b) "remove the fallback":
408
- * (a) closes the single-use hole with a targeted atomic create+record and leaves the
409
- * `StrandProvisioner` mock-transport tests untouched; (b) would delete the provisioner
410
- * surface and churn ~6 unit + ~6 integration sites for ZERO production benefit (production
411
- * — `cadre-web.ts` / `cadre-phone.ts` — always publishes strand-BOUND invites and treats
412
- * the responder-provisions placeholder as failure). The broader "should this fallback exist
413
- * at all?" question lives in backlog `formation-initiatorcreates-cover-or-remove`.
414
- */
415
- private async provisionUnbound(
416
- contact: FormationContactMessage,
417
- disclosureText: string,
418
- signal?: AbortSignal
419
- ): Promise<ResponderProvisionOutcome> {
420
- const token = contact.token;
421
- const recorder = this.formationUsageRecorder;
422
- if (recorder?.provisionAndRecord) {
423
- const sAppId = await this.resolveInviteSAppId(token);
424
- const provisioned = await recorder.provisionAndRecord({
425
- token,
426
- peerKey: contact.peerKey,
427
- peerSignature: contact.peerSignature,
428
- usageStampId: contact.usageStampId,
429
- sAppId,
430
- disclosure: disclosureText,
431
- signal
432
- });
433
- return this.approve({
434
- strand: { strandId: provisioned.strandId, createdBy: 'responder' },
435
- memberPrivateKey: provisioned.memberPrivateKey ?? undefined,
436
- dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
437
- });
438
- }
439
-
440
- if (this.strandProvisioner) {
441
- const sAppId = await this.resolveInviteSAppId(token);
442
- const result = await this.strandProvisioner.provisionStrand(sAppId, contact.partyId, this.partyId);
443
- return this.approve({
444
- strand: { strandId: result.strandId, createdBy: 'responder' },
445
- dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
446
- });
447
- }
448
-
449
- // No recorder + no provisioner — a structural placeholder the initiator can still validate.
450
- const strandId = `strand-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
451
- return this.approve({
452
- strand: { strandId, createdBy: 'responder' },
453
- dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
454
- });
455
- }
456
-
457
- /** Wrap a provision result as an approving {@link ResponderProvisionOutcome}. */
458
- private approve(result: FormationProvisionResult): ResponderProvisionOutcome {
459
- return { approved: true, result };
460
- }
461
-
462
- /**
463
- * The invite's authoritative `sAppId` for the responder-provisions fallback, read back
464
- * from the recorder's `isTokenValid` invitation (the real `FormationInvite.sAppId`).
465
- * Empty string when no recorder is wired or the invitation omits it.
466
- */
467
- private async resolveInviteSAppId(token: string): Promise<string> {
468
- if (!this.formationUsageRecorder) return '';
469
- const check = await this.formationUsageRecorder.isTokenValid(token);
470
- return check.invitation?.sAppId ?? '';
471
- }
472
-
473
- // ── Initiator-side result validation ─────────────────────────────────────────
474
-
475
- private async validateResponse(
476
- invitation: OpenInvitation,
477
- disclosure: StrandFormationDisclosure,
478
- response: FormationResultMessage
479
- ): Promise<boolean> {
480
- if (this.formationResponseValidator) {
481
- return this.formationResponseValidator.validateResponse({ invitation, disclosure, response });
482
- }
483
- return isValidResponderCreatesResult(response);
484
- }
485
- }
486
-
487
- /**
488
- * Create a StrandFormationManager with the given options
489
- */
490
- export function createStrandFormationManager(
491
- options: StrandFormationManagerOptions
492
- ): StrandFormationManager {
493
- return new StrandFormationManager(options);
494
- }
1
+ import debug from 'debug';
2
+ import { fromString as uint8ArrayFromString } from 'uint8arrays';
3
+ import type { Libp2p } from '@libp2p/interface';
4
+ import type {
5
+ OpenInvitation,
6
+ FormStrandResult,
7
+ StrandFormationDisclosure
8
+ } from './types.js';
9
+ import {
10
+ FormationApprovalError,
11
+ type FormationApprovalFailure
12
+ } from './formation-approval.js';
13
+ // control-database does not import this manager, so this import introduces no cycle.
14
+ import { FormationAbortedError, InvitationExhaustedError } from './control-database.js';
15
+ import { canonicalJson } from './canonical-json.js';
16
+ import type {
17
+ DisclosureValidator,
18
+ FormationUsageRecorder,
19
+ ResolvedHostStrand,
20
+ StrandProvisioner,
21
+ FormationResponseValidator
22
+ } from './strand-solicitation.js';
23
+ import {
24
+ FormationListener,
25
+ INVALID_TOKEN_REASON,
26
+ PROVISION_RESPONSE_TRAVEL_MARGIN_MS,
27
+ dialFormation,
28
+ isValidResponderCreatesResult,
29
+ type FormationContactMessage,
30
+ type FormationProvisionResult,
31
+ type FormationResultMessage,
32
+ type ResponderProvisionOutcome
33
+ } from './strand-formation-protocol.js';
34
+
35
+ const log = debug('sereus:cadre:formation-manager');
36
+
37
+ /**
38
+ * Largest serialized disclosure a responder will accept (8 KiB). The disclosure is
39
+ * attacker-influenced text destined for a replicated table (`FormationUsage.Disclosure`)
40
+ * and for the approval hook's signed digest — the cap bounds both, and is enforced BEFORE
41
+ * any database read or hook contact so an oversized blob costs nothing downstream.
42
+ */
43
+ const MAX_DISCLOSURE_BYTES = 8 * 1024;
44
+
45
+ /**
46
+ * Rejection reason a would-be joiner is told for each approval-failure category
47
+ * (see {@link FormationApprovalFailure}). Distinct per category on purpose: mapping any
48
+ * of these onto the generic 'Formation conflict, retry' would tell an operator to retry
49
+ * what retrying can never fix (e.g. a non-enrolled validation key).
50
+ */
51
+ const APPROVAL_REJECTION_REASONS: Record<FormationApprovalFailure, string> = {
52
+ refused: 'Formation approval refused',
53
+ unavailable: 'Formation approval unavailable, retry',
54
+ malformed: 'Formation approval invalid',
55
+ unenrolled: 'Formation approval key is not enrolled',
56
+ misconfigured: 'Formation approval misconfigured'
57
+ };
58
+
59
+ /**
60
+ * Configuration for StrandFormationManager
61
+ */
62
+ export interface StrandFormationManagerConfig {
63
+ /** Session timeout in milliseconds */
64
+ sessionTimeoutMs?: number;
65
+ /** Step timeout in milliseconds */
66
+ stepTimeoutMs?: number;
67
+ /**
68
+ * Provisioning budget in milliseconds for the RESPONDER's `provisionStrand` hook call.
69
+ * The initiator's `await-response` wait is derived automatically from this value plus
70
+ * `PROVISION_RESPONSE_TRAVEL_MARGIN_MS` (`strand-formation-protocol.ts`) — never set
71
+ * directly — so the ordering documented there (approval hook < responder provisioning <
72
+ * initiator await-response < session) cannot collapse when this is configured.
73
+ */
74
+ provisionTimeoutMs?: number;
75
+ /** Maximum concurrent sessions */
76
+ maxConcurrentSessions?: number;
77
+ /** Enable debug logging */
78
+ enableDebugLogging?: boolean;
79
+ /** Protocol ID override */
80
+ protocolId?: string;
81
+ }
82
+
83
+ /**
84
+ * Options for creating a StrandFormationManager
85
+ */
86
+ export interface StrandFormationManagerOptions {
87
+ /** Validates disclosures from initiators (responder side) */
88
+ disclosureValidator?: DisclosureValidator;
89
+ /** Records and validates token usage (responder side) */
90
+ formationUsageRecorder?: FormationUsageRecorder;
91
+ /** Provisions strands after validation (responder side) */
92
+ strandProvisioner?: StrandProvisioner;
93
+ /** Validates the responder's result (initiator side); defaults to a structural check */
94
+ formationResponseValidator?: FormationResponseValidator;
95
+ /** This party's ID for identification */
96
+ partyId: string;
97
+ /** This party's cadre peer addresses */
98
+ cadrePeerAddrs?: string[];
99
+ /** Configuration options */
100
+ config?: StrandFormationManagerConfig;
101
+ }
102
+
103
+ /**
104
+ * StrandFormationManager drives the native cadre-core formation transport
105
+ * (`strand-formation-protocol.ts`) from cadre-core's strand-solicitation interfaces.
106
+ *
107
+ * Responder side: a {@link FormationListener} wires the inbound protocol to
108
+ * {@link FormationUsageRecorder} (token), {@link DisclosureValidator} (identity),
109
+ * and {@link StrandProvisioner} (provisioning), disclosing this party's real
110
+ * identity + cadre only after validation.
111
+ *
112
+ * Initiator side: {@link formStrand} dials the responder carrying the real
113
+ * disclosure/token/cadre, then validates the responder's result via the
114
+ * {@link FormationResponseValidator} (or a built-in structural check).
115
+ */
116
+ export class StrandFormationManager {
117
+ private readonly disclosureValidator?: DisclosureValidator;
118
+ private readonly formationUsageRecorder?: FormationUsageRecorder;
119
+ private readonly strandProvisioner?: StrandProvisioner;
120
+ private readonly formationResponseValidator?: FormationResponseValidator;
121
+ private readonly partyId: string;
122
+ private readonly cadrePeerAddrs: string[];
123
+ private readonly config: StrandFormationManagerConfig;
124
+ private readonly listener: FormationListener;
125
+ private readonly registeredNodes = new Set<Libp2p>();
126
+ private dialerSessions = 0;
127
+
128
+ constructor(options: StrandFormationManagerOptions) {
129
+ this.disclosureValidator = options.disclosureValidator;
130
+ this.formationUsageRecorder = options.formationUsageRecorder;
131
+ this.strandProvisioner = options.strandProvisioner;
132
+ this.formationResponseValidator = options.formationResponseValidator;
133
+ this.partyId = options.partyId;
134
+ this.cadrePeerAddrs = options.cadrePeerAddrs ?? [];
135
+ this.config = options.config ?? {};
136
+
137
+ this.listener = new FormationListener({
138
+ validateToken: (token) => this.validateToken(token),
139
+ validateDisclosure: (token, disclosure) => this.validateDisclosure(token, disclosure),
140
+ provisionStrand: (contact, signal) =>
141
+ this.provisionAsResponder(contact, signal),
142
+ getResponderIdentity: () => ({ partyId: this.partyId, cadrePeerAddrs: this.cadrePeerAddrs }),
143
+ sessionTimeoutMs: this.config.sessionTimeoutMs,
144
+ stepTimeoutMs: this.config.stepTimeoutMs,
145
+ provisionTimeoutMs: this.config.provisionTimeoutMs,
146
+ maxConcurrentSessions: this.config.maxConcurrentSessions
147
+ });
148
+
149
+ log('StrandFormationManager created for party: %s', this.partyId);
150
+ }
151
+
152
+ /**
153
+ * Register this manager as a protocol handler on a libp2p node.
154
+ * Call this on the control network node to handle incoming formation requests.
155
+ */
156
+ registerResponder(node: Libp2p, protocolId?: string): void {
157
+ if (this.registeredNodes.has(node)) {
158
+ log('Node already registered');
159
+ return;
160
+ }
161
+ this.listener.register(node, protocolId ?? this.config.protocolId);
162
+ this.registeredNodes.add(node);
163
+ log('Registered as responder on node');
164
+ }
165
+
166
+ /**
167
+ * Unregister the protocol handler from a libp2p node.
168
+ */
169
+ unregisterResponder(node: Libp2p, protocolId?: string): void {
170
+ if (!this.registeredNodes.has(node)) {
171
+ return;
172
+ }
173
+ this.listener.unregister(node, protocolId ?? this.config.protocolId);
174
+ this.registeredNodes.delete(node);
175
+ log('Unregistered from node');
176
+ }
177
+
178
+ /**
179
+ * Form a strand with a responder via an open invitation (initiator side).
180
+ *
181
+ * Builds a contact message carrying the real token + disclosure + this party's
182
+ * real cadre addresses + the joiner's consent (minted and signed by the
183
+ * solicitation layer — this manager only places it on the contact), dials the
184
+ * responder over the native protocol, and validates the responder's result
185
+ * before returning.
186
+ */
187
+ async formStrand(
188
+ invitation: OpenInvitation,
189
+ disclosure: StrandFormationDisclosure,
190
+ consent: { peerKey: string; usageStampId: string; peerSignature: string },
191
+ node: Libp2p
192
+ ): Promise<FormStrandResult> {
193
+ log('Forming strand with invitation token: %s', invitation.token);
194
+
195
+ const contact: FormationContactMessage = {
196
+ token: invitation.token,
197
+ partyId: disclosure.partyId ?? this.partyId,
198
+ peerKey: consent.peerKey,
199
+ usageStampId: consent.usageStampId,
200
+ peerSignature: consent.peerSignature,
201
+ disclosure,
202
+ cadrePeerAddrs: this.cadrePeerAddrs
203
+ };
204
+
205
+ this.dialerSessions++;
206
+ try {
207
+ const provision = await dialFormation(node, {
208
+ contact,
209
+ responderAddrs: invitation.bootstrap,
210
+ validateResponse: (response) => this.validateResponse(invitation, disclosure, response),
211
+ sessionTimeoutMs: this.config.sessionTimeoutMs,
212
+ stepTimeoutMs: this.config.stepTimeoutMs,
213
+ provisionTimeoutMs: this.initiatorProvisionTimeoutMs(),
214
+ protocolId: this.config.protocolId
215
+ });
216
+
217
+ log('Strand formed: %s', provision.strand.strandId);
218
+
219
+ return {
220
+ memberKey: contact.partyId,
221
+ invitePrivateKey: '',
222
+ strandId: provision.strand.strandId,
223
+ // The host strand's membership key, delivered through the protocol (provision-then-record).
224
+ // Undefined for an open strand. Kept separate from invitePrivateKey (the initiator's
225
+ // generated signing key), which is set by the StrandSolicitationService layer.
226
+ memberPrivateKey: provision.memberPrivateKey
227
+ };
228
+ } finally {
229
+ this.dialerSessions--;
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Get the number of active sessions
235
+ */
236
+ getActiveSessionCounts(): { listeners: number; dialers: number } {
237
+ return { listeners: this.listener.activeCount, dialers: this.dialerSessions };
238
+ }
239
+
240
+ /**
241
+ * Derive the initiator's await-response budget from the configured RESPONDER budget —
242
+ * never the same number (see `StrandFormationManagerConfig.provisionTimeoutMs`). Mirrors
243
+ * `resolveProvisionTimeoutMs`'s own "`0`/negative means unset" rule so an unset config
244
+ * still lets both sides fall back to their own independent defaults; must NOT hardcode
245
+ * `DEFAULT_PROVISION_TIMEOUT_MS` here, or the per-role clamping downstream is defeated.
246
+ * A value too large for the session is clamped per role, and the responder's ceiling holds
247
+ * the same margin back, so the ordering survives there too.
248
+ */
249
+ private initiatorProvisionTimeoutMs(): number | undefined {
250
+ const host = this.config.provisionTimeoutMs;
251
+ return host && host > 0 ? host + PROVISION_RESPONSE_TRAVEL_MARGIN_MS : undefined;
252
+ }
253
+
254
+ // ── Responder-side hooks ─────────────────────────────────────────────────────
255
+
256
+ private async validateToken(token: string): Promise<{ valid: boolean }> {
257
+ if (!this.formationUsageRecorder) {
258
+ // No recorder configured — accept all tokens.
259
+ return { valid: true };
260
+ }
261
+
262
+ const tokenCheck = await this.formationUsageRecorder.isTokenValid(token);
263
+ if (!tokenCheck.valid) {
264
+ log('Token invalid: %s', token);
265
+ return { valid: false };
266
+ }
267
+
268
+ if (await this.formationUsageRecorder.isTokenUsed(token)) {
269
+ log('Token already used: %s', token);
270
+ return { valid: false };
271
+ }
272
+
273
+ return { valid: true };
274
+ }
275
+
276
+ private async validateDisclosure(token: string, disclosure: StrandFormationDisclosure): Promise<boolean> {
277
+ if (!this.disclosureValidator) {
278
+ // No validator configured — accept all disclosures.
279
+ return true;
280
+ }
281
+ return this.disclosureValidator.validateDisclosure(token, disclosure);
282
+ }
283
+
284
+ /**
285
+ * Responder-side provisioning. Routes on how the invite resolves
286
+ * ({@link ResolvedHostStrand}), and can REJECT post-validation by returning a
287
+ * {@link ResponderProvisionOutcome} with `approved: false` — `runSession` turns that
288
+ * into a clean, non-disclosing reply instead of a dropped result frame.
289
+ *
290
+ * - **bound** (host strand present): provision-then-record — write the single
291
+ * `FormationUsage` consent row against the pre-existing strand (record-only) and
292
+ * return it + its membership key (a read-gating secret disclosed only here, behind the
293
+ * token + disclosure validation `runSession` already enforced).
294
+ * - **missing** (invite names a host strand absent on this responder, e.g. unconverged):
295
+ * reject cleanly + retryably, writing NO usage row — recording usage here would fail the
296
+ * deferred `StrandExists` CHECK at commit and drop the frame.
297
+ * - **unbound** (no binding): the responder-provisions fallback — see {@link provisionUnbound}.
298
+ *
299
+ * Defense-in-depth: known provisioning/redeem failures are caught and mapped to a logged
300
+ * protocol rejection rather than a thrown insert + a silently-closed stream. The mapping is
301
+ * per-failure, NOT blanket retry-suggesting: an exhausted invitation
302
+ * ({@link InvitationExhaustedError}, raised by `ControlDatabase` when the count of recorded
303
+ * uses has reached the invite's seat budget — which is how the loser of a same-node race
304
+ * surfaces, the local write queue having serialized the two writes) is reported as
305
+ * `'Invalid token'`, because retrying it can never succeed. Concurrent redemptions never
306
+ * contend for a shared row key — each writes under its own `UsageStampId` — so there is no
307
+ * key collision to surface here at all. The LOG-before-reject keeps this a deliberate
308
+ * internal-error→protocol-rejection conversion (AGENTS.md: don't eat exceptions silently),
309
+ * not control-flow-by-exception.
310
+ */
311
+ private async provisionAsResponder(
312
+ contact: FormationContactMessage,
313
+ signal?: AbortSignal
314
+ ): Promise<ResponderProvisionOutcome> {
315
+ const token = contact.token;
316
+ // CANONICALLY serialized — both sides derive the identical string: this is the exact
317
+ // text the joiner signed (consent), the approver signs (vouch), and the recorder writes
318
+ // to `FormationUsage.Disclosure` — a re-serialization anywhere below would break the
319
+ // signature-over-stored-bytes invariant.
320
+ const disclosureText = canonicalJson(contact.disclosure);
321
+ if (uint8ArrayFromString(disclosureText, 'utf8').byteLength > MAX_DISCLOSURE_BYTES) {
322
+ log('Disclosure over %d bytes; rejecting token %s', MAX_DISCLOSURE_BYTES, token);
323
+ return { approved: false, reason: 'Disclosure too large' };
324
+ }
325
+
326
+ const recorder = this.formationUsageRecorder;
327
+ const resolved: ResolvedHostStrand = recorder?.resolveStrand
328
+ ? await recorder.resolveStrand(token)
329
+ : { kind: 'unbound' };
330
+
331
+ try {
332
+ switch (resolved.kind) {
333
+ case 'bound': {
334
+ // recorder is guaranteed non-null here: only resolveStrand can yield 'bound'.
335
+ await recorder!.recordUsage({
336
+ token,
337
+ peerKey: contact.peerKey,
338
+ peerSignature: contact.peerSignature,
339
+ usageStampId: contact.usageStampId,
340
+ strandId: resolved.strandId,
341
+ disclosure: disclosureText,
342
+ signal
343
+ });
344
+ return this.approve({
345
+ strand: { strandId: resolved.strandId, createdBy: 'responder' },
346
+ memberPrivateKey: resolved.memberPrivateKey ?? undefined,
347
+ dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
348
+ });
349
+ }
350
+ case 'missing': {
351
+ log('Host strand %s not yet available on this responder; rejecting token %s', resolved.strandId, token);
352
+ return { approved: false, reason: 'Host strand not yet available on this responder' };
353
+ }
354
+ case 'unbound':
355
+ return await this.provisionUnbound(contact, disclosureText, signal);
356
+ }
357
+ } catch (err) {
358
+ if (err instanceof FormationAbortedError) {
359
+ // The listener's timeout path owns the reply for an abandoned provisioning; mapping
360
+ // this onto 'Formation conflict, retry' would misreport it as a conflict.
361
+ throw err;
362
+ }
363
+ if (err instanceof FormationApprovalError) {
364
+ log('approval failed (%s) for token %s: %o', err.failure, token, err);
365
+ return { approved: false, reason: APPROVAL_REJECTION_REASONS[err.failure] };
366
+ }
367
+ if (err instanceof InvitationExhaustedError) {
368
+ // Shares `INVALID_TOKEN_REASON` with the up-front `validateToken` rejection so the loser
369
+ // of the race that exposed the spent invite sees exactly what a non-racing latecomer
370
+ // sees. No wire-visible distinction between "invalid" and "exhausted" — the
371
+ // operator signal lives in this log line instead.
372
+ // NOTE: if a joining client ever has to tell "never valid" from "used up" WITHOUT node
373
+ // logs, that is a new protocol reason string, not a local change here.
374
+ log(
375
+ 'invitation exhausted for token %s: %d of %d use(s) already recorded',
376
+ err.token,
377
+ err.usesRecorded,
378
+ err.totalUses
379
+ );
380
+ return { approved: false, reason: INVALID_TOKEN_REASON };
381
+ }
382
+ // An approval is never discarded to a lost key race: each redemption writes under its
383
+ // own `UsageStampId`, so no other writer can take its row key. Reaching this catch-all
384
+ // means the failure was never retryable at the database layer to begin with (or the
385
+ // transient-cluster retry inside `ControlDatabase.lockedWithRetry` ran out).
386
+ log('provisionAsResponder failed for token %s: %o', token, err);
387
+ return { approved: false, reason: 'Formation conflict, retry' };
388
+ }
389
+ }
390
+
391
+ /**
392
+ * Responder-provisions fallback (invite binds no host strand). Precedence:
393
+ *
394
+ * 1. `recorder.provisionAndRecord` present (a real DB recorder) → atomic create-strand +
395
+ * record-consent, so the unbound redemption is single-use just like the bound path.
396
+ * Returns the new strand (+ key, null for an open responder-provisioned strand).
397
+ * 2. else `strandProvisioner` present → the legacy/mock contract: provision a bare strand,
398
+ * NO inline usage write (those callers record usage explicitly via
399
+ * `recordFormationComplete`, or assert transport invariants only). Threads the invite's
400
+ * REAL `sAppId`.
401
+ * 3. else → a structural placeholder (no recorder + no provisioner ⇒ no single-use semantics
402
+ * exist to enforce).
403
+ *
404
+ * Plan tradeoff — option (a) "record usage on the fallback" over (b) "remove the fallback":
405
+ * (a) closes the single-use hole with a targeted atomic create+record and leaves the
406
+ * `StrandProvisioner` mock-transport tests untouched; (b) would delete the provisioner
407
+ * surface and churn ~6 unit + ~6 integration sites for ZERO production benefit (production
408
+ * — `cadre-web.ts` / `cadre-phone.ts` — always publishes strand-BOUND invites and treats
409
+ * the responder-provisions placeholder as failure). The broader "should this fallback exist
410
+ * at all?" question lives in backlog `formation-initiatorcreates-cover-or-remove`.
411
+ */
412
+ private async provisionUnbound(
413
+ contact: FormationContactMessage,
414
+ disclosureText: string,
415
+ signal?: AbortSignal
416
+ ): Promise<ResponderProvisionOutcome> {
417
+ const token = contact.token;
418
+ const recorder = this.formationUsageRecorder;
419
+ if (recorder?.provisionAndRecord) {
420
+ const sAppId = await this.resolveInviteSAppId(token);
421
+ const provisioned = await recorder.provisionAndRecord({
422
+ token,
423
+ peerKey: contact.peerKey,
424
+ peerSignature: contact.peerSignature,
425
+ usageStampId: contact.usageStampId,
426
+ sAppId,
427
+ disclosure: disclosureText,
428
+ signal
429
+ });
430
+ return this.approve({
431
+ strand: { strandId: provisioned.strandId, createdBy: 'responder' },
432
+ memberPrivateKey: provisioned.memberPrivateKey ?? undefined,
433
+ dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
434
+ });
435
+ }
436
+
437
+ if (this.strandProvisioner) {
438
+ const sAppId = await this.resolveInviteSAppId(token);
439
+ const result = await this.strandProvisioner.provisionStrand(sAppId, contact.partyId, this.partyId);
440
+ return this.approve({
441
+ strand: { strandId: result.strandId, createdBy: 'responder' },
442
+ dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
443
+ });
444
+ }
445
+
446
+ // No recorder + no provisioner — a structural placeholder the initiator can still validate.
447
+ const strandId = `strand-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
448
+ return this.approve({
449
+ strand: { strandId, createdBy: 'responder' },
450
+ dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
451
+ });
452
+ }
453
+
454
+ /** Wrap a provision result as an approving {@link ResponderProvisionOutcome}. */
455
+ private approve(result: FormationProvisionResult): ResponderProvisionOutcome {
456
+ return { approved: true, result };
457
+ }
458
+
459
+ /**
460
+ * The invite's authoritative `sAppId` for the responder-provisions fallback, read back
461
+ * from the recorder's `isTokenValid` invitation (the real `FormationInvite.sAppId`).
462
+ * Empty string when no recorder is wired or the invitation omits it.
463
+ */
464
+ private async resolveInviteSAppId(token: string): Promise<string> {
465
+ if (!this.formationUsageRecorder) return '';
466
+ const check = await this.formationUsageRecorder.isTokenValid(token);
467
+ return check.invitation?.sAppId ?? '';
468
+ }
469
+
470
+ // ── Initiator-side result validation ─────────────────────────────────────────
471
+
472
+ private async validateResponse(
473
+ invitation: OpenInvitation,
474
+ disclosure: StrandFormationDisclosure,
475
+ response: FormationResultMessage
476
+ ): Promise<boolean> {
477
+ if (this.formationResponseValidator) {
478
+ return this.formationResponseValidator.validateResponse({ invitation, disclosure, response });
479
+ }
480
+ return isValidResponderCreatesResult(response);
481
+ }
482
+ }
483
+
484
+ /**
485
+ * Create a StrandFormationManager with the given options
486
+ */
487
+ export function createStrandFormationManager(
488
+ options: StrandFormationManagerOptions
489
+ ): StrandFormationManager {
490
+ return new StrandFormationManager(options);
491
+ }