@serfab/cadre-core 1.6.0 → 1.8.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 (179) hide show
  1. package/README.md +8 -6
  2. package/dist/cadre-node.d.ts +548 -137
  3. package/dist/cadre-node.js +1208 -383
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-authorization.d.ts +2 -2
  6. package/dist/control-authorization.js +1 -0
  7. package/dist/control-authorization.js.map +1 -1
  8. package/dist/control-cohort.d.ts +6 -0
  9. package/dist/control-cohort.js +6 -0
  10. package/dist/control-cohort.js.map +1 -1
  11. package/dist/control-database.d.ts +46 -8
  12. package/dist/control-database.js +97 -18
  13. package/dist/control-database.js.map +1 -1
  14. package/dist/control-formation-recorder.d.ts +37 -14
  15. package/dist/control-formation-recorder.js +60 -10
  16. package/dist/control-formation-recorder.js.map +1 -1
  17. package/dist/control-read-retry.d.ts +13 -12
  18. package/dist/control-read-retry.js +14 -12
  19. package/dist/control-read-retry.js.map +1 -1
  20. package/dist/control-schema.d.ts +1 -1
  21. package/dist/control-schema.js +67 -5
  22. package/dist/control-schema.js.map +1 -1
  23. package/dist/control-stream.d.ts +9 -1
  24. package/dist/control-stream.js +24 -1
  25. package/dist/control-stream.js.map +1 -1
  26. package/dist/control-write-retry.d.ts +12 -2
  27. package/dist/control-write-retry.js +13 -2
  28. package/dist/control-write-retry.js.map +1 -1
  29. package/dist/delegate-admission.d.ts +11 -8
  30. package/dist/delegate-admission.js +19 -11
  31. package/dist/delegate-admission.js.map +1 -1
  32. package/dist/diagnostics/connection-path.d.ts +0 -7
  33. package/dist/diagnostics/connection-path.js +0 -7
  34. package/dist/diagnostics/connection-path.js.map +1 -1
  35. package/dist/formation-approval.d.ts +7 -0
  36. package/dist/formation-approval.js +9 -3
  37. package/dist/formation-approval.js.map +1 -1
  38. package/dist/fs-atomic.d.ts +11 -2
  39. package/dist/fs-atomic.js +13 -3
  40. package/dist/fs-atomic.js.map +1 -1
  41. package/dist/hibernation-manager.d.ts +111 -8
  42. package/dist/hibernation-manager.js +234 -49
  43. package/dist/hibernation-manager.js.map +1 -1
  44. package/dist/index.d.ts +13 -6
  45. package/dist/index.js +27 -5
  46. package/dist/index.js.map +1 -1
  47. package/dist/joined-strand-store.d.ts +177 -0
  48. package/dist/joined-strand-store.js +431 -0
  49. package/dist/joined-strand-store.js.map +1 -0
  50. package/dist/key-store-file.js +14 -5
  51. package/dist/key-store-file.js.map +1 -1
  52. package/dist/key-store.d.ts +6 -0
  53. package/dist/key-store.js.map +1 -1
  54. package/dist/link-budget.d.ts +367 -69
  55. package/dist/link-budget.js +375 -72
  56. package/dist/link-budget.js.map +1 -1
  57. package/dist/membership-connection-gater.d.ts +30 -43
  58. package/dist/membership-connection-gater.js +31 -42
  59. package/dist/membership-connection-gater.js.map +1 -1
  60. package/dist/node-local-snapshot.d.ts +5 -4
  61. package/dist/node-local-snapshot.js +6 -3
  62. package/dist/node-local-snapshot.js.map +1 -1
  63. package/dist/peer-dial.d.ts +24 -4
  64. package/dist/peer-dial.js +74 -5
  65. package/dist/peer-dial.js.map +1 -1
  66. package/dist/peer-join-backfill.d.ts +35 -15
  67. package/dist/peer-join-backfill.js +115 -55
  68. package/dist/peer-join-backfill.js.map +1 -1
  69. package/dist/push-fanout.d.ts +6 -0
  70. package/dist/push-fanout.js +6 -0
  71. package/dist/push-fanout.js.map +1 -1
  72. package/dist/relay-reservation.d.ts +3 -1
  73. package/dist/relay-reservation.js +3 -1
  74. package/dist/relay-reservation.js.map +1 -1
  75. package/dist/relay-server.d.ts +79 -0
  76. package/dist/relay-server.js +74 -0
  77. package/dist/relay-server.js.map +1 -0
  78. package/dist/seed-bootstrap.d.ts +57 -4
  79. package/dist/seed-bootstrap.js +107 -83
  80. package/dist/seed-bootstrap.js.map +1 -1
  81. package/dist/storage-scope.d.ts +33 -17
  82. package/dist/storage-scope.js +44 -23
  83. package/dist/storage-scope.js.map +1 -1
  84. package/dist/strand-addr-protocol.d.ts +58 -21
  85. package/dist/strand-addr-protocol.js +133 -85
  86. package/dist/strand-addr-protocol.js.map +1 -1
  87. package/dist/strand-database.d.ts +20 -2
  88. package/dist/strand-database.js +42 -5
  89. package/dist/strand-database.js.map +1 -1
  90. package/dist/strand-first-sync-gate.d.ts +59 -21
  91. package/dist/strand-first-sync-gate.js +58 -19
  92. package/dist/strand-first-sync-gate.js.map +1 -1
  93. package/dist/strand-formation-deadlines.d.ts +151 -0
  94. package/dist/strand-formation-deadlines.js +171 -0
  95. package/dist/strand-formation-deadlines.js.map +1 -0
  96. package/dist/strand-formation-manager.d.ts +63 -30
  97. package/dist/strand-formation-manager.js +67 -41
  98. package/dist/strand-formation-manager.js.map +1 -1
  99. package/dist/strand-formation-protocol.d.ts +45 -35
  100. package/dist/strand-formation-protocol.js +59 -122
  101. package/dist/strand-formation-protocol.js.map +1 -1
  102. package/dist/strand-instance-manager.d.ts +152 -6
  103. package/dist/strand-instance-manager.js +331 -42
  104. package/dist/strand-instance-manager.js.map +1 -1
  105. package/dist/strand-membership-writer.d.ts +6 -0
  106. package/dist/strand-membership-writer.js +11 -0
  107. package/dist/strand-membership-writer.js.map +1 -1
  108. package/dist/strand-peer-book-file.d.ts +12 -0
  109. package/dist/strand-peer-book-file.js +37 -0
  110. package/dist/strand-peer-book-file.js.map +1 -0
  111. package/dist/strand-peer-book-protocol.d.ts +168 -0
  112. package/dist/strand-peer-book-protocol.js +356 -0
  113. package/dist/strand-peer-book-protocol.js.map +1 -0
  114. package/dist/strand-peer-book-swap.d.ts +104 -0
  115. package/dist/strand-peer-book-swap.js +284 -0
  116. package/dist/strand-peer-book-swap.js.map +1 -0
  117. package/dist/strand-peer-book.d.ts +159 -0
  118. package/dist/strand-peer-book.js +361 -0
  119. package/dist/strand-peer-book.js.map +1 -0
  120. package/dist/strand-peer-observer.d.ts +88 -0
  121. package/dist/strand-peer-observer.js +180 -0
  122. package/dist/strand-peer-observer.js.map +1 -0
  123. package/dist/strand-revocation-enforcer.js +2 -1
  124. package/dist/strand-revocation-enforcer.js.map +1 -1
  125. package/dist/strand-solicitation.d.ts +36 -20
  126. package/dist/strand-solicitation.js +4 -4
  127. package/dist/strand-solicitation.js.map +1 -1
  128. package/dist/strand-wake-protocol.d.ts +80 -23
  129. package/dist/strand-wake-protocol.js +89 -64
  130. package/dist/strand-wake-protocol.js.map +1 -1
  131. package/dist/types.d.ts +181 -33
  132. package/dist/types.js +4 -3
  133. package/dist/types.js.map +1 -1
  134. package/package.json +11 -7
  135. package/src/cadre-node.ts +1316 -398
  136. package/src/control-authorization.ts +2 -1
  137. package/src/control-cohort.ts +6 -0
  138. package/src/control-database.ts +122 -18
  139. package/src/control-formation-recorder.ts +354 -305
  140. package/src/control-read-retry.ts +14 -12
  141. package/src/control-schema.ts +67 -5
  142. package/src/control-stream.ts +25 -1
  143. package/src/control-write-retry.ts +13 -2
  144. package/src/delegate-admission.ts +23 -13
  145. package/src/diagnostics/connection-path.ts +0 -7
  146. package/src/formation-approval.ts +610 -604
  147. package/src/fs-atomic.ts +14 -4
  148. package/src/hibernation-manager.ts +638 -437
  149. package/src/index.ts +91 -6
  150. package/src/joined-strand-store.ts +498 -0
  151. package/src/key-store-file.ts +14 -5
  152. package/src/key-store.ts +6 -0
  153. package/src/link-budget.ts +393 -74
  154. package/src/membership-connection-gater.ts +31 -45
  155. package/src/node-local-snapshot.ts +293 -289
  156. package/src/peer-dial.ts +81 -7
  157. package/src/peer-join-backfill.ts +120 -57
  158. package/src/push-fanout.ts +6 -0
  159. package/src/relay-reservation.ts +3 -1
  160. package/src/relay-server.ts +98 -0
  161. package/src/seed-bootstrap.ts +133 -91
  162. package/src/storage-scope.ts +44 -23
  163. package/src/strand-addr-protocol.ts +547 -458
  164. package/src/strand-database.ts +287 -242
  165. package/src/strand-first-sync-gate.ts +58 -19
  166. package/src/strand-formation-deadlines.ts +227 -0
  167. package/src/strand-formation-manager.ts +700 -647
  168. package/src/strand-formation-protocol.ts +103 -150
  169. package/src/strand-instance-manager.ts +387 -45
  170. package/src/strand-membership-writer.ts +12 -0
  171. package/src/strand-peer-book-file.ts +39 -0
  172. package/src/strand-peer-book-protocol.ts +466 -0
  173. package/src/strand-peer-book-swap.ts +338 -0
  174. package/src/strand-peer-book.ts +475 -0
  175. package/src/strand-peer-observer.ts +235 -0
  176. package/src/strand-revocation-enforcer.ts +2 -1
  177. package/src/strand-solicitation.ts +519 -500
  178. package/src/strand-wake-protocol.ts +401 -355
  179. package/src/types.ts +185 -33
@@ -1,647 +1,700 @@
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
- StrandMembershipInvite
9
- } from './types.js';
10
- import {
11
- FormationApprovalError,
12
- type FormationApprovalFailure
13
- } from './formation-approval.js';
14
- // control-database does not import this manager, so this import introduces no cycle.
15
- import { FormationAbortedError, InvitationExhaustedError } from './control-database.js';
16
- import { PreSplitStrandIdentityError } from './strand-membership-writer.js';
17
- import { mintPlaceholderStrandId } from './strand-id.js';
18
- import { canonicalJson } from './canonical-json.js';
19
- import type {
20
- DisclosureValidator,
21
- FormationUsageRecorder,
22
- ResolvedHostStrand,
23
- StrandProvisioner,
24
- FormationResponseValidator
25
- } from './strand-solicitation.js';
26
- import {
27
- FormationListener,
28
- INVALID_TOKEN_REASON,
29
- PROVISION_RESPONSE_TRAVEL_MARGIN_MS,
30
- dialFormation,
31
- isValidResponderCreatesResult,
32
- isWellFormedMembershipInvite,
33
- type FormationContactMessage,
34
- type FormationProvisionResult,
35
- type FormationResultMessage,
36
- type ResponderProvisionOutcome
37
- } from './strand-formation-protocol.js';
38
-
39
- const log = debug('sereus:cadre:formation-manager');
40
-
41
- /**
42
- * Largest serialized disclosure a responder will accept (8 KiB). The disclosure is
43
- * attacker-influenced text destined for a replicated table (`FormationUsage.Disclosure`)
44
- * and for the approval hook's signed digest — the cap bounds both, and is enforced BEFORE
45
- * any database read or hook contact so an oversized blob costs nothing downstream.
46
- */
47
- const MAX_DISCLOSURE_BYTES = 8 * 1024;
48
-
49
- /**
50
- * How long a formation-issued strand membership invitation stays redeemable (7 days).
51
- * The responder's {@link StrandFormationManagerOptions.issueMembershipInvite} hook stamps
52
- * `now + this` as the `Strand.Invite.Expiration`. Long enough for a slow joiner to bring
53
- * its strand node up and redeem; short enough that a lost formation result does not leave
54
- * a live bearer credential in the strand forever. An expired invitation rolls the
55
- * redemption back cleanly (the schema's `NotExpired` gate) — the joiner's recovery is a
56
- * fresh formation, which issues a fresh invitation.
57
- */
58
- export const MEMBERSHIP_INVITE_TTL_MS = 7 * 24 * 3600_000;
59
-
60
- /**
61
- * Rejection reason for a bound CLOSED-strand redemption whose responder could not issue
62
- * the joiner's membership invitation — the host strand runtime not live on this
63
- * responder, no party identity key yet, or the strand DB refusing the `Strand.Invite`
64
- * write. Retryable on purpose, and rejected BEFORE the consent row is recorded, so the
65
- * formation token stays unspent: approving without an invitation would admit a joiner
66
- * that looks joined but can never become a member, and a responder not running the
67
- * strand cannot serve the joiner's sync anyway. The one permanent failure,
68
- * a pre-split host strand, gets {@link HOST_STRAND_MUST_BE_RECREATED_REASON} instead.
69
- */
70
- export const MEMBERSHIP_INVITE_UNAVAILABLE_REASON = 'Strand membership invitation unavailable, retry';
71
-
72
- /**
73
- * Rejection reason for a bound CLOSED-strand redemption whose host strand was founded
74
- * before the per-party identity split: the responder's founder launch refused it
75
- * (`PreSplitStrandIdentityError`), so no invitation can ever be issued into it. Not
76
- * retryable — the host must recreate the strand and issue a fresh invitation. Like
77
- * {@link MEMBERSHIP_INVITE_UNAVAILABLE_REASON}, rejected before consent is recorded, so
78
- * the formation token stays unspent.
79
- */
80
- export const HOST_STRAND_MUST_BE_RECREATED_REASON = 'Host strand must be recreated';
81
-
82
- /**
83
- * Rejection reason a would-be joiner is told for each approval-failure category
84
- * (see {@link FormationApprovalFailure}). Distinct per category on purpose: mapping any
85
- * of these onto the generic 'Formation conflict, retry' would tell an operator to retry
86
- * what retrying can never fix (e.g. a non-enrolled validation key).
87
- */
88
- const APPROVAL_REJECTION_REASONS: Record<FormationApprovalFailure, string> = {
89
- refused: 'Formation approval refused',
90
- unavailable: 'Formation approval unavailable, retry',
91
- malformed: 'Formation approval invalid',
92
- unenrolled: 'Formation approval key is not enrolled',
93
- misconfigured: 'Formation approval misconfigured'
94
- };
95
-
96
- /**
97
- * Configuration for StrandFormationManager
98
- */
99
- export interface StrandFormationManagerConfig {
100
- /** Session timeout in milliseconds */
101
- sessionTimeoutMs?: number;
102
- /** Step timeout in milliseconds */
103
- stepTimeoutMs?: number;
104
- /**
105
- * Provisioning budget in milliseconds for the RESPONDER's `provisionStrand` hook call.
106
- * The initiator's `await-response` wait is derived automatically from this value plus
107
- * `PROVISION_RESPONSE_TRAVEL_MARGIN_MS` (`strand-formation-protocol.ts`) — never set
108
- * directly — so the ordering documented there (approval hook < responder provisioning <
109
- * initiator await-response < session) cannot collapse when this is configured.
110
- */
111
- provisionTimeoutMs?: number;
112
- /** Maximum concurrent sessions */
113
- maxConcurrentSessions?: number;
114
- /** Enable debug logging */
115
- enableDebugLogging?: boolean;
116
- /** Protocol ID override */
117
- protocolId?: string;
118
- }
119
-
120
- /**
121
- * Options for creating a StrandFormationManager
122
- */
123
- export interface StrandFormationManagerOptions {
124
- /** Validates disclosures from initiators (responder side) */
125
- disclosureValidator?: DisclosureValidator;
126
- /** Records and validates token usage (responder side) */
127
- formationUsageRecorder?: FormationUsageRecorder;
128
- /** Provisions strands after validation (responder side) */
129
- strandProvisioner?: StrandProvisioner;
130
- /** Validates the responder's result (initiator side); defaults to a structural check */
131
- formationResponseValidator?: FormationResponseValidator;
132
- /** This party's ID for identification */
133
- partyId: string;
134
- /** This party's cadre peer addresses */
135
- cadrePeerAddrs?: string[];
136
- /**
137
- * This node's live STRAND-network multiaddrs for a strand it is running (responder
138
- * side). Wired by `CadreNode` to its own per-strand address lookup; the manager has no
139
- * route to the strand runtime itself.
140
- *
141
- * A hook, not a `config` knob, so it sits with the other responder-side seams
142
- * (`strandProvisioner`, `formationUsageRecorder`) rather than among the timeouts. Left
143
- * unwired — every mock/transport test — the responder simply discloses no strand
144
- * addresses and cross-party joiners fall back to an empty seed.
145
- */
146
- resolveStrandAddrs?: (strandId: string) => string[];
147
- /**
148
- * Issue a single-use `Strand.Invite` against the live host strand a BOUND redemption
149
- * resolved to (responder side) — the seam that gets the JOINER its own membership.
150
- * Like {@link resolveStrandAddrs}, the formation layer cannot reach the strand
151
- * runtime itself, so `CadreNode` wires this to its own running-instance +
152
- * `StrandPartyKey` lookup.
153
- *
154
- * Contract: return the issued invitation for a CLOSED host strand; return `null`
155
- * for an open one (no members, nothing to invite into); THROW when a closed strand's
156
- * invitation cannot be issued (runtime not live, no party key, strand DB write
157
- * rejected) — the manager then rejects the whole redemption with
158
- * {@link MEMBERSHIP_INVITE_UNAVAILABLE_REASON} BEFORE recording consent, so the
159
- * formation token stays unspent and the joiner can retry. Throw a
160
- * `PreSplitStrandIdentityError` for a host strand that can never issue one; that maps
161
- * to the non-retryable {@link HOST_STRAND_MUST_BE_RECREATED_REASON}.
162
- *
163
- * Left unwired — mock/transport tests — the bound path approves with no invitation,
164
- * mirroring the unwired {@link resolveStrandAddrs} posture. Production
165
- * (`CadreNode.initializeStrandSolicitation`) always wires it.
166
- */
167
- issueMembershipInvite?: (strandId: string) => Promise<StrandMembershipInvite | null>;
168
- /** Configuration options */
169
- config?: StrandFormationManagerConfig;
170
- }
171
-
172
- /**
173
- * StrandFormationManager drives the native cadre-core formation transport
174
- * (`strand-formation-protocol.ts`) from cadre-core's strand-solicitation interfaces.
175
- *
176
- * Responder side: a {@link FormationListener} wires the inbound protocol to
177
- * {@link FormationUsageRecorder} (token), {@link DisclosureValidator} (identity),
178
- * and {@link StrandProvisioner} (provisioning), disclosing this party's real
179
- * identity + cadre only after validation.
180
- *
181
- * Initiator side: {@link formStrand} dials the responder carrying the real
182
- * disclosure/token/cadre, then validates the responder's result via the
183
- * {@link FormationResponseValidator} (or a built-in structural check).
184
- */
185
- export class StrandFormationManager {
186
- private readonly disclosureValidator?: DisclosureValidator;
187
- private readonly formationUsageRecorder?: FormationUsageRecorder;
188
- private readonly strandProvisioner?: StrandProvisioner;
189
- private readonly formationResponseValidator?: FormationResponseValidator;
190
- private readonly partyId: string;
191
- private readonly cadrePeerAddrs: string[];
192
- private readonly resolveStrandAddrs?: (strandId: string) => string[];
193
- private readonly issueMembershipInvite?: (strandId: string) => Promise<StrandMembershipInvite | null>;
194
- private readonly config: StrandFormationManagerConfig;
195
- private readonly listener: FormationListener;
196
- private readonly registeredNodes = new Set<Libp2p>();
197
- private dialerSessions = 0;
198
-
199
- constructor(options: StrandFormationManagerOptions) {
200
- this.disclosureValidator = options.disclosureValidator;
201
- this.formationUsageRecorder = options.formationUsageRecorder;
202
- this.strandProvisioner = options.strandProvisioner;
203
- this.formationResponseValidator = options.formationResponseValidator;
204
- this.partyId = options.partyId;
205
- this.cadrePeerAddrs = options.cadrePeerAddrs ?? [];
206
- this.resolveStrandAddrs = options.resolveStrandAddrs;
207
- this.issueMembershipInvite = options.issueMembershipInvite;
208
- this.config = options.config ?? {};
209
-
210
- this.listener = new FormationListener({
211
- validateToken: (token) => this.validateToken(token),
212
- validateDisclosure: (token, disclosure) => this.validateDisclosure(token, disclosure),
213
- provisionStrand: (contact, signal) =>
214
- this.provisionAsResponder(contact, signal),
215
- getResponderIdentity: () => ({ partyId: this.partyId, cadrePeerAddrs: this.cadrePeerAddrs }),
216
- // Forwarded only when wired, so `FormationListenerOptions.resolveStrandAddrs`
217
- // stays genuinely absent (and the listener short-circuits) for an unwired manager.
218
- ...(this.resolveStrandAddrs && { resolveStrandAddrs: this.resolveStrandAddrs }),
219
- sessionTimeoutMs: this.config.sessionTimeoutMs,
220
- stepTimeoutMs: this.config.stepTimeoutMs,
221
- provisionTimeoutMs: this.config.provisionTimeoutMs,
222
- maxConcurrentSessions: this.config.maxConcurrentSessions
223
- });
224
-
225
- log('StrandFormationManager created for party: %s', this.partyId);
226
- }
227
-
228
- /**
229
- * Register this manager as a protocol handler on a libp2p node.
230
- * Call this on the control network node to handle incoming formation requests.
231
- */
232
- registerResponder(node: Libp2p, protocolId?: string): void {
233
- if (this.registeredNodes.has(node)) {
234
- log('Node already registered');
235
- return;
236
- }
237
- this.listener.register(node, protocolId ?? this.config.protocolId);
238
- this.registeredNodes.add(node);
239
- log('Registered as responder on node');
240
- }
241
-
242
- /**
243
- * Unregister the protocol handler from a libp2p node.
244
- */
245
- unregisterResponder(node: Libp2p, protocolId?: string): void {
246
- if (!this.registeredNodes.has(node)) {
247
- return;
248
- }
249
- this.listener.unregister(node, protocolId ?? this.config.protocolId);
250
- this.registeredNodes.delete(node);
251
- log('Unregistered from node');
252
- }
253
-
254
- /**
255
- * Form a strand with a responder via an open invitation (initiator side).
256
- *
257
- * Builds a contact message carrying the real token + disclosure + this party's
258
- * real cadre addresses + the joiner's consent (minted and signed by the
259
- * solicitation layer — this manager only places it on the contact), dials the
260
- * responder over the native protocol, and validates the responder's result
261
- * before returning.
262
- */
263
- async formStrand(
264
- invitation: OpenInvitation,
265
- disclosure: StrandFormationDisclosure,
266
- consent: { peerKey: string; usageStampId: string; peerSignature: string },
267
- node: Libp2p
268
- ): Promise<FormStrandResult> {
269
- log('Forming strand with invitation token: %s', invitation.token);
270
-
271
- const contact: FormationContactMessage = {
272
- token: invitation.token,
273
- partyId: disclosure.partyId ?? this.partyId,
274
- peerKey: consent.peerKey,
275
- usageStampId: consent.usageStampId,
276
- peerSignature: consent.peerSignature,
277
- disclosure,
278
- cadrePeerAddrs: this.cadrePeerAddrs
279
- };
280
-
281
- this.dialerSessions++;
282
- try {
283
- const dialed = await dialFormation(node, {
284
- contact,
285
- responderAddrs: invitation.bootstrap,
286
- validateResponse: (response) => this.validateResponse(invitation, disclosure, response),
287
- sessionTimeoutMs: this.config.sessionTimeoutMs,
288
- stepTimeoutMs: this.config.stepTimeoutMs,
289
- provisionTimeoutMs: this.initiatorProvisionTimeoutMs(),
290
- protocolId: this.config.protocolId
291
- });
292
-
293
- const provision = dialed.provision;
294
- log('Strand formed: %s (%d cross-party strand addr(s))', provision.strand.strandId, dialed.strandAddrs.length);
295
-
296
- return {
297
- memberKey: contact.partyId,
298
- invitePrivateKey: '',
299
- strandId: provision.strand.strandId,
300
- // The host strand's membership key, delivered through the protocol (provision-then-record).
301
- // Undefined for an open strand. Kept separate from invitePrivateKey (the initiator's
302
- // generated signing key), which is set by the StrandSolicitationService layer.
303
- memberPrivateKey: provision.memberPrivateKey,
304
- // Carried only when well-formed. The DEFAULT response validator already rejects
305
- // a malformed one; this re-check keeps a custom validator that skips the shape
306
- // check from feeding a hostile responder's object into the joiner's invite cache.
307
- membershipInvite: this.membershipInviteFrom(provision),
308
- // Possibly empty — the responder may hold no live strand node yet.
309
- strandAddrs: dialed.strandAddrs
310
- };
311
- } finally {
312
- this.dialerSessions--;
313
- }
314
- }
315
-
316
- /**
317
- * Get the number of active sessions
318
- */
319
- getActiveSessionCounts(): { listeners: number; dialers: number } {
320
- return { listeners: this.listener.activeCount, dialers: this.dialerSessions };
321
- }
322
-
323
- /**
324
- * The provision result's membership invitation, iff well-formed — a malformed one
325
- * (possible only past a custom {@link FormationResponseValidator} that skipped the
326
- * structural check) is dropped with a log rather than cached: it could never redeem
327
- * anyway, and carrying an unbounded hostile object outlives the session.
328
- */
329
- private membershipInviteFrom(provision: FormationProvisionResult): StrandMembershipInvite | undefined {
330
- if (provision.membershipInvite === undefined) {
331
- return undefined;
332
- }
333
- if (!isWellFormedMembershipInvite(provision.membershipInvite)) {
334
- log('formStrand: dropping malformed membershipInvite from responder for strand %s', provision.strand.strandId);
335
- return undefined;
336
- }
337
- return { inviteKey: provision.membershipInvite.inviteKey, invitePrivateKey: provision.membershipInvite.invitePrivateKey };
338
- }
339
-
340
- /**
341
- * Derive the initiator's await-response budget from the configured RESPONDER budget —
342
- * never the same number (see `StrandFormationManagerConfig.provisionTimeoutMs`). Mirrors
343
- * `resolveProvisionTimeoutMs`'s own "`0`/negative means unset" rule so an unset config
344
- * still lets both sides fall back to their own independent defaults; must NOT hardcode
345
- * `DEFAULT_PROVISION_TIMEOUT_MS` here, or the per-role clamping downstream is defeated.
346
- * A value too large for the session is clamped per role, and the responder's ceiling holds
347
- * the same margin back, so the ordering survives there too.
348
- */
349
- private initiatorProvisionTimeoutMs(): number | undefined {
350
- const host = this.config.provisionTimeoutMs;
351
- return host && host > 0 ? host + PROVISION_RESPONSE_TRAVEL_MARGIN_MS : undefined;
352
- }
353
-
354
- // ── Responder-side hooks ─────────────────────────────────────────────────────
355
-
356
- private async validateToken(token: string): Promise<{ valid: boolean }> {
357
- if (!this.formationUsageRecorder) {
358
- // No recorder configured — accept all tokens.
359
- return { valid: true };
360
- }
361
-
362
- const tokenCheck = await this.formationUsageRecorder.isTokenValid(token);
363
- if (!tokenCheck.valid) {
364
- log('Token invalid: %s', token);
365
- return { valid: false };
366
- }
367
-
368
- if (await this.formationUsageRecorder.isTokenUsed(token)) {
369
- log('Token already used: %s', token);
370
- return { valid: false };
371
- }
372
-
373
- return { valid: true };
374
- }
375
-
376
- private async validateDisclosure(token: string, disclosure: StrandFormationDisclosure): Promise<boolean> {
377
- if (!this.disclosureValidator) {
378
- // No validator configured — accept all disclosures.
379
- return true;
380
- }
381
- return this.disclosureValidator.validateDisclosure(token, disclosure);
382
- }
383
-
384
- /**
385
- * Responder-side provisioning. Routes on how the invite resolves
386
- * ({@link ResolvedHostStrand}), and can REJECT post-validation by returning a
387
- * {@link ResponderProvisionOutcome} with `approved: false` — `runSession` turns that
388
- * into a clean, non-disclosing reply instead of a dropped result frame.
389
- *
390
- * - **bound** (host strand present): provision-then-record — first issue the joiner's
391
- * single-use strand membership invitation via the wired `issueMembershipInvite` seam
392
- * ({@link issueBoundMembershipInvite}; a closed strand whose invitation cannot be
393
- * issued rejects retryably HERE, before any consent row spends the token), then write
394
- * the single `FormationUsage` consent row against the pre-existing strand
395
- * (record-only) and return it + its membership key + the invitation (all read-gating
396
- * secrets disclosed only here, behind the token + disclosure validation `runSession`
397
- * already enforced).
398
- * - **missing** (invite names a host strand absent on this responder, e.g. unconverged):
399
- * reject cleanly + retryably, writing NO usage row — recording usage here would fail the
400
- * deferred `StrandExists` CHECK at commit and drop the frame.
401
- * - **unbound** (no binding): the responder-provisions fallback — see {@link provisionUnbound}.
402
- *
403
- * Defense-in-depth: known provisioning/redeem failures are caught and mapped to a logged
404
- * protocol rejection rather than a thrown insert + a silently-closed stream. The mapping is
405
- * per-failure, NOT blanket retry-suggesting: an exhausted invitation
406
- * ({@link InvitationExhaustedError}, raised by `ControlDatabase` when the count of recorded
407
- * uses has reached the invite's seat budget — which is how the loser of a same-node race
408
- * surfaces, the local write queue having serialized the two writes) is reported as
409
- * `'Invalid token'`, because retrying it can never succeed. Concurrent redemptions never
410
- * contend for a shared row key — each writes under its own `UsageStampId` — so there is no
411
- * key collision to surface here at all. The LOG-before-reject keeps this a deliberate
412
- * internal-error→protocol-rejection conversion (AGENTS.md: don't eat exceptions silently),
413
- * not control-flow-by-exception.
414
- */
415
- private async provisionAsResponder(
416
- contact: FormationContactMessage,
417
- signal?: AbortSignal
418
- ): Promise<ResponderProvisionOutcome> {
419
- const token = contact.token;
420
- // CANONICALLY serialized — both sides derive the identical string: this is the exact
421
- // text the joiner signed (consent), the approver signs (vouch), and the recorder writes
422
- // to `FormationUsage.Disclosure` — a re-serialization anywhere below would break the
423
- // signature-over-stored-bytes invariant.
424
- const disclosureText = canonicalJson(contact.disclosure);
425
- if (uint8ArrayFromString(disclosureText, 'utf8').byteLength > MAX_DISCLOSURE_BYTES) {
426
- log('Disclosure over %d bytes; rejecting token %s', MAX_DISCLOSURE_BYTES, token);
427
- return { approved: false, reason: 'Disclosure too large' };
428
- }
429
-
430
- const recorder = this.formationUsageRecorder;
431
- const resolved: ResolvedHostStrand = recorder?.resolveStrand
432
- ? await recorder.resolveStrand(token)
433
- : { kind: 'unbound' };
434
-
435
- try {
436
- switch (resolved.kind) {
437
- case 'bound': {
438
- // Issued BEFORE the consent row is recorded, so an issue failure rejects with
439
- // the formation token still unspent (retryable). The inverse window — invite
440
- // issued, then recordUsage fails/aborts — orphans a live `Strand.Invite` no
441
- // joiner ever received; bounded deliberately by its expiry
442
- // ({@link MEMBERSHIP_INVITE_TTL_MS}) rather than compensated, since nothing
443
- // here can atomically un-issue a strand-DB row.
444
- const issued = await this.issueBoundMembershipInvite(token, resolved.strandId);
445
- if (!issued.ok) {
446
- return { approved: false, reason: issued.reason };
447
- }
448
- // recorder is guaranteed non-null here: only resolveStrand can yield 'bound'.
449
- await recorder!.recordUsage({
450
- token,
451
- peerKey: contact.peerKey,
452
- peerSignature: contact.peerSignature,
453
- usageStampId: contact.usageStampId,
454
- strandId: resolved.strandId,
455
- disclosure: disclosureText,
456
- signal
457
- });
458
- return this.approve({
459
- strand: { strandId: resolved.strandId, createdBy: 'responder' },
460
- memberPrivateKey: resolved.memberPrivateKey ?? undefined,
461
- // Omitted (not sent undefined-valued) so rejection-parity and open-strand
462
- // assertions stay plain `toBeUndefined()` on the parsed frame.
463
- ...(issued.invite ? { membershipInvite: issued.invite } : {}),
464
- dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
465
- });
466
- }
467
- case 'missing': {
468
- log('Host strand %s not yet available on this responder; rejecting token %s', resolved.strandId, token);
469
- return { approved: false, reason: 'Host strand not yet available on this responder' };
470
- }
471
- case 'unbound':
472
- return await this.provisionUnbound(contact, disclosureText, signal);
473
- }
474
- } catch (err) {
475
- if (err instanceof FormationAbortedError) {
476
- // The listener's timeout path owns the reply for an abandoned provisioning; mapping
477
- // this onto 'Formation conflict, retry' would misreport it as a conflict.
478
- throw err;
479
- }
480
- if (err instanceof FormationApprovalError) {
481
- log('approval failed (%s) for token %s: %o', err.failure, token, err);
482
- return { approved: false, reason: APPROVAL_REJECTION_REASONS[err.failure] };
483
- }
484
- if (err instanceof InvitationExhaustedError) {
485
- // Shares `INVALID_TOKEN_REASON` with the up-front `validateToken` rejection so the loser
486
- // of the race that exposed the spent invite sees exactly what a non-racing latecomer
487
- // sees. No wire-visible distinction between "invalid" and "exhausted" — the
488
- // operator signal lives in this log line instead.
489
- // NOTE: if a joining client ever has to tell "never valid" from "used up" WITHOUT node
490
- // logs, that is a new protocol reason string, not a local change here.
491
- log(
492
- 'invitation exhausted for token %s: %d of %d use(s) already recorded',
493
- err.token,
494
- err.usesRecorded,
495
- err.totalUses
496
- );
497
- return { approved: false, reason: INVALID_TOKEN_REASON };
498
- }
499
- // An approval is never discarded to a lost key race: each redemption writes under its
500
- // own `UsageStampId`, so no other writer can take its row key. Reaching this catch-all
501
- // means the failure was never retryable at the database layer to begin with (or the
502
- // transient-cluster retry inside `ControlDatabase.lockedWithRetry` ran out).
503
- log('provisionAsResponder failed for token %s: %o', token, err);
504
- return { approved: false, reason: 'Formation conflict, retry' };
505
- }
506
- }
507
-
508
- /**
509
- * Issue the joiner's membership invitation for a BOUND redemption via the wired
510
- * {@link StrandFormationManagerOptions.issueMembershipInvite} seam.
511
- *
512
- * - Hook unwired (mock/transport tests): approve with no invitation, the same posture
513
- * as an unwired `resolveStrandAddrs`.
514
- * - Hook returns an invitation (closed host strand): carry it on the approval.
515
- * - Hook returns `null` (open host strand): approve with no invitation.
516
- * - Hook throws (runtime not live, no party key, strand-DB write rejected): report
517
- * `ok: false` with {@link MEMBERSHIP_INVITE_UNAVAILABLE_REASON} — the caller rejects
518
- * BEFORE any consent row is written, so the formation token stays unspent.
519
- * - Hook throws `PreSplitStrandIdentityError` (the host strand was founded before the
520
- * per-party identity split and can never issue one): same, but with the
521
- * non-retryable {@link HOST_STRAND_MUST_BE_RECREATED_REASON}.
522
- *
523
- * The LOG-before-reject keeps both a deliberate internal-error→protocol-rejection
524
- * conversion, same as the catch-all in {@link provisionAsResponder}.
525
- */
526
- private async issueBoundMembershipInvite(
527
- token: string,
528
- strandId: string
529
- ): Promise<{ ok: true; invite?: StrandMembershipInvite } | { ok: false; reason: string }> {
530
- if (!this.issueMembershipInvite) {
531
- return { ok: true };
532
- }
533
- try {
534
- const invite = await this.issueMembershipInvite(strandId);
535
- return { ok: true, invite: invite ?? undefined };
536
- } catch (err) {
537
- if (err instanceof PreSplitStrandIdentityError) {
538
- log('host strand %s is pre-split (token %s); rejecting — it must be recreated: %o', strandId, token, err);
539
- return { ok: false, reason: HOST_STRAND_MUST_BE_RECREATED_REASON };
540
- }
541
- log('membership-invite issue for strand %s failed (token %s); rejecting retryably: %o', strandId, token, err);
542
- return { ok: false, reason: MEMBERSHIP_INVITE_UNAVAILABLE_REASON };
543
- }
544
- }
545
-
546
- /**
547
- * Responder-provisions fallback (invite binds no host strand). Precedence:
548
- *
549
- * 1. `recorder.provisionAndRecord` present (a real DB recorder) → atomic create-strand +
550
- * record-consent, so the unbound redemption is single-use just like the bound path.
551
- * Returns the new strand (+ key, null for an open responder-provisioned strand).
552
- * 2. else `strandProvisioner` present → the mock/transport-test contract: provision a bare
553
- * strand, NO inline usage write (those callers record usage explicitly via
554
- * `recordFormationComplete`, or assert transport invariants only). Threads the invite's
555
- * REAL `sAppId`.
556
- * 3. else → a structural placeholder (no recorder + no provisioner ⇒ no single-use semantics
557
- * exist to enforce).
558
- *
559
- * NOTE: accepted tradeoff — the plan chose (a) "record usage on the fallback" over (b)
560
- * "remove the fallback", so arm 2 (`strandProvisioner`, no recorder) is kept. (a) closes the
561
- * single-use hole with a targeted atomic create+record and leaves the `StrandProvisioner`
562
- * mock-transport tests untouched; (b) would delete the provisioner surface and churn ~6 unit
563
- * + ~6 integration sites for ZERO production benefit (production — `cadre-web.ts` /
564
- * `cadre-phone.ts` — always publishes strand-BOUND invites and treats the
565
- * responder-provisions placeholder as failure). Revisit if production starts publishing
566
- * unbound invites, or the mock-transport tests go away.
567
- */
568
- private async provisionUnbound(
569
- contact: FormationContactMessage,
570
- disclosureText: string,
571
- signal?: AbortSignal
572
- ): Promise<ResponderProvisionOutcome> {
573
- const token = contact.token;
574
- const recorder = this.formationUsageRecorder;
575
- if (recorder?.provisionAndRecord) {
576
- const sAppId = await this.resolveInviteSAppId(token);
577
- const provisioned = await recorder.provisionAndRecord({
578
- token,
579
- peerKey: contact.peerKey,
580
- peerSignature: contact.peerSignature,
581
- usageStampId: contact.usageStampId,
582
- sAppId,
583
- disclosure: disclosureText,
584
- signal
585
- });
586
- return this.approve({
587
- strand: { strandId: provisioned.strandId, createdBy: 'responder' },
588
- memberPrivateKey: provisioned.memberPrivateKey ?? undefined,
589
- dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
590
- });
591
- }
592
-
593
- if (this.strandProvisioner) {
594
- const sAppId = await this.resolveInviteSAppId(token);
595
- const result = await this.strandProvisioner.provisionStrand(sAppId, contact.partyId, this.partyId);
596
- return this.approve({
597
- strand: { strandId: result.strandId, createdBy: 'responder' },
598
- dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
599
- });
600
- }
601
-
602
- // No recorder + no provisioner — a structural placeholder the initiator can still validate.
603
- const strandId = mintPlaceholderStrandId();
604
- return this.approve({
605
- strand: { strandId, createdBy: 'responder' },
606
- dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
607
- });
608
- }
609
-
610
- /** Wrap a provision result as an approving {@link ResponderProvisionOutcome}. */
611
- private approve(result: FormationProvisionResult): ResponderProvisionOutcome {
612
- return { approved: true, result };
613
- }
614
-
615
- /**
616
- * The invite's authoritative `sAppId` for the responder-provisions fallback, read back
617
- * from the recorder's `isTokenValid` invitation (the real `FormationInvite.sAppId`).
618
- * Empty string when no recorder is wired or the invitation omits it.
619
- */
620
- private async resolveInviteSAppId(token: string): Promise<string> {
621
- if (!this.formationUsageRecorder) return '';
622
- const check = await this.formationUsageRecorder.isTokenValid(token);
623
- return check.invitation?.sAppId ?? '';
624
- }
625
-
626
- // ── Initiator-side result validation ─────────────────────────────────────────
627
-
628
- private async validateResponse(
629
- invitation: OpenInvitation,
630
- disclosure: StrandFormationDisclosure,
631
- response: FormationResultMessage
632
- ): Promise<boolean> {
633
- if (this.formationResponseValidator) {
634
- return this.formationResponseValidator.validateResponse({ invitation, disclosure, response });
635
- }
636
- return isValidResponderCreatesResult(response);
637
- }
638
- }
639
-
640
- /**
641
- * Create a StrandFormationManager with the given options
642
- */
643
- export function createStrandFormationManager(
644
- options: StrandFormationManagerOptions
645
- ): StrandFormationManager {
646
- return new StrandFormationManager(options);
647
- }
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
+ StrandMembershipInvite
9
+ } from './types.js';
10
+ import {
11
+ FormationApprovalError,
12
+ type FormationApprovalFailure
13
+ } from './formation-approval.js';
14
+ // control-database does not import this manager, so this import introduces no cycle.
15
+ import { FormationAbortedError, InvitationExhaustedError } from './control-database.js';
16
+ import { PreSplitStrandIdentityError } from './strand-membership-writer.js';
17
+ import { mintPlaceholderStrandId } from './strand-id.js';
18
+ import { canonicalJson } from './canonical-json.js';
19
+ import type {
20
+ AuthorizedFormationUsage,
21
+ DisclosureValidator,
22
+ FormationUsageParams,
23
+ FormationUsageRecorder,
24
+ ResolvedHostStrand,
25
+ StrandProvisioner,
26
+ FormationResponseValidator
27
+ } from './strand-solicitation.js';
28
+ import {
29
+ FormationListener,
30
+ INVALID_TOKEN_REASON,
31
+ dialFormation,
32
+ isValidResponderCreatesResult,
33
+ isWellFormedMembershipInvite,
34
+ type FormationContactMessage,
35
+ type FormationProvisionResult,
36
+ type FormationResultMessage,
37
+ type ResponderProvisionOutcome
38
+ } from './strand-formation-protocol.js';
39
+ import { formationDeadlines } from './strand-formation-deadlines.js';
40
+
41
+ const log = debug('sereus:cadre:formation-manager');
42
+
43
+ /**
44
+ * Largest serialized disclosure a responder will accept (8 KiB). The disclosure is
45
+ * attacker-influenced text destined for a replicated table (`FormationUsage.Disclosure`)
46
+ * and for the approval hook's signed digest — the cap bounds both, and is enforced BEFORE
47
+ * any database read or hook contact so an oversized blob costs nothing downstream.
48
+ */
49
+ const MAX_DISCLOSURE_BYTES = 8 * 1024;
50
+
51
+ /**
52
+ * How long a formation-issued strand membership invitation stays redeemable (7 days).
53
+ * The responder's {@link StrandFormationManagerOptions.issueMembershipInvite} hook stamps
54
+ * `now + this` as the `Strand.Invite.Expiration`. Long enough for a slow joiner to bring
55
+ * its strand node up and redeem; short enough that a lost formation result does not leave
56
+ * a live bearer credential in the strand forever. An expired invitation rolls the
57
+ * redemption back cleanly (the schema's `NotExpired` gate) — the joiner's recovery is a
58
+ * fresh formation, which issues a fresh invitation.
59
+ */
60
+ export const MEMBERSHIP_INVITE_TTL_MS = 7 * 24 * 3600_000;
61
+
62
+ /**
63
+ * Rejection reason for a bound CLOSED-strand redemption whose responder could not issue
64
+ * the joiner's membership invitation — the host strand runtime not live on this
65
+ * responder (never launched, mid-start, or a hibernating one that did not wake within the
66
+ * provisioning budget; a hibernating runtime is woken, not refused), no party identity key
67
+ * yet, or the strand DB refusing the `Strand.Invite` write. Retryable on purpose, and
68
+ * rejected BEFORE the consent row is recorded, so the formation token stays unspent:
69
+ * approving without an invitation would admit a joiner that looks joined but can never
70
+ * become a member, and a responder not running the strand cannot serve the joiner's sync
71
+ * anyway. The one permanent failure, a pre-split host strand, gets
72
+ * {@link HOST_STRAND_MUST_BE_RECREATED_REASON} instead.
73
+ */
74
+ export const MEMBERSHIP_INVITE_UNAVAILABLE_REASON = 'Strand membership invitation unavailable, retry';
75
+
76
+ /**
77
+ * Rejection reason for a bound CLOSED-strand redemption whose host strand was founded
78
+ * before the per-party identity split: the responder's founder launch refused it
79
+ * (`PreSplitStrandIdentityError`), so no invitation can ever be issued into it. Not
80
+ * retryable — the host must recreate the strand and issue a fresh invitation. Like
81
+ * {@link MEMBERSHIP_INVITE_UNAVAILABLE_REASON}, rejected before consent is recorded, so
82
+ * the formation token stays unspent.
83
+ */
84
+ export const HOST_STRAND_MUST_BE_RECREATED_REASON = 'Host strand must be recreated';
85
+
86
+ /**
87
+ * Rejection reason a would-be joiner is told for each approval-failure category
88
+ * (see {@link FormationApprovalFailure}). Distinct per category on purpose: mapping any
89
+ * of these onto the generic 'Formation conflict, retry' would tell an operator to retry
90
+ * what retrying can never fix (e.g. a non-enrolled validation key).
91
+ */
92
+ const APPROVAL_REJECTION_REASONS: Record<FormationApprovalFailure, string> = {
93
+ refused: 'Formation approval refused',
94
+ unavailable: 'Formation approval unavailable, retry',
95
+ malformed: 'Formation approval invalid',
96
+ unenrolled: 'Formation approval key is not enrolled',
97
+ misconfigured: 'Formation approval misconfigured'
98
+ };
99
+
100
+ /**
101
+ * Responder-side seam that issues a bound joiner's membership invitation — see
102
+ * {@link StrandFormationManagerOptions.issueMembershipInvite} for the contract. `signal`
103
+ * is the responder's provisioning budget: the issuer stops waiting (and throws) once it
104
+ * aborts.
105
+ */
106
+ export type MembershipInviteIssuer = (strandId: string, signal?: AbortSignal) => Promise<StrandMembershipInvite | null>;
107
+
108
+ /**
109
+ * Configuration for StrandFormationManager
110
+ */
111
+ export interface StrandFormationManagerConfig {
112
+ /**
113
+ * This machine's declared link round trip (`NetworkConfig.linkRoundTripMs`), from which
114
+ * every formation deadline is derived (`formationDeadlines` in
115
+ * `strand-formation-deadlines.ts`). `CadreNode` fills it from its network config; the
116
+ * fields below override single rungs of that ladder.
117
+ */
118
+ linkRoundTripMs?: number;
119
+ /** Whole-session budget, both roles, in milliseconds. */
120
+ sessionTimeoutMs?: number;
121
+ /** The responder's contact-frame read, in milliseconds. */
122
+ stepTimeoutMs?: number;
123
+ /** The initiator's dial-connect (open the connection, negotiate the protocol), in milliseconds. */
124
+ dialTimeoutMs?: number;
125
+ /**
126
+ * Provisioning budget in milliseconds for the RESPONDER's `provisionStrand` hook call.
127
+ * The initiator's `await-response` wait is derived automatically from this value plus the
128
+ * travel margin of the derived ladder (`responseTravelMarginMs`) — never set directly — so
129
+ * the ordering documented there (approval hook < responder provisioning < initiator
130
+ * await-response < session) cannot collapse when this is configured.
131
+ */
132
+ provisionTimeoutMs?: number;
133
+ /** Maximum concurrent sessions */
134
+ maxConcurrentSessions?: number;
135
+ /** Enable debug logging */
136
+ enableDebugLogging?: boolean;
137
+ /** Protocol ID override */
138
+ protocolId?: string;
139
+ }
140
+
141
+ /**
142
+ * Options for creating a StrandFormationManager
143
+ */
144
+ export interface StrandFormationManagerOptions {
145
+ /** Validates disclosures from initiators (responder side) */
146
+ disclosureValidator?: DisclosureValidator;
147
+ /** Records and validates token usage (responder side) */
148
+ formationUsageRecorder?: FormationUsageRecorder;
149
+ /** Provisions strands after validation (responder side) */
150
+ strandProvisioner?: StrandProvisioner;
151
+ /** Validates the responder's result (initiator side); defaults to a structural check */
152
+ formationResponseValidator?: FormationResponseValidator;
153
+ /** This party's ID for identification */
154
+ partyId: string;
155
+ /** This party's cadre peer addresses */
156
+ cadrePeerAddrs?: string[];
157
+ /**
158
+ * This node's live STRAND-network multiaddrs for a strand it is running (responder
159
+ * side). Wired by `CadreNode` to its own per-strand address lookup; the manager has no
160
+ * route to the strand runtime itself.
161
+ *
162
+ * A hook, not a `config` knob, so it sits with the other responder-side seams
163
+ * (`strandProvisioner`, `formationUsageRecorder`) rather than among the timeouts. Left
164
+ * unwired — every mock/transport test — the responder simply discloses no strand
165
+ * addresses and cross-party joiners fall back to an empty seed.
166
+ */
167
+ resolveStrandAddrs?: (strandId: string) => string[];
168
+ /**
169
+ * Issue a single-use `Strand.Invite` against the live host strand a BOUND redemption
170
+ * resolved to (responder side) — the seam that gets the JOINER its own membership.
171
+ * Like {@link resolveStrandAddrs}, the formation layer cannot reach the strand
172
+ * runtime itself, so `CadreNode` wires this to its own running-instance +
173
+ * `StrandPartyKey` lookup.
174
+ *
175
+ * Contract: return the issued invitation for a CLOSED host strand; return `null`
176
+ * for an open one (no members, nothing to invite into); THROW when a closed strand's
177
+ * invitation cannot be issued (runtime not live, no party key, strand DB write
178
+ * rejected) — the manager then rejects the whole redemption with
179
+ * {@link MEMBERSHIP_INVITE_UNAVAILABLE_REASON} BEFORE recording consent, so the
180
+ * formation token stays unspent and the joiner can retry. Throw a
181
+ * `PreSplitStrandIdentityError` for a host strand that can never issue one; that maps
182
+ * to the non-retryable {@link HOST_STRAND_MUST_BE_RECREATED_REASON}.
183
+ *
184
+ * A hibernating host runtime is not a reason to throw: the issuer wakes it first,
185
+ * bounded by `signal` (the responder's provisioning budget), and throws only when the
186
+ * wake does not finish in time or fails.
187
+ *
188
+ * Left unwired — mock/transport tests — the bound path approves with no invitation,
189
+ * mirroring the unwired {@link resolveStrandAddrs} posture. Production
190
+ * (`CadreNode.initializeStrandSolicitation`) always wires it.
191
+ */
192
+ issueMembershipInvite?: MembershipInviteIssuer;
193
+ /** Configuration options */
194
+ config?: StrandFormationManagerConfig;
195
+ }
196
+
197
+ /**
198
+ * StrandFormationManager drives the native cadre-core formation transport
199
+ * (`strand-formation-protocol.ts`) from cadre-core's strand-solicitation interfaces.
200
+ *
201
+ * Responder side: a {@link FormationListener} wires the inbound protocol to
202
+ * {@link FormationUsageRecorder} (token), {@link DisclosureValidator} (identity),
203
+ * and {@link StrandProvisioner} (provisioning), disclosing this party's real
204
+ * identity + cadre only after validation.
205
+ *
206
+ * Initiator side: {@link formStrand} dials the responder carrying the real
207
+ * disclosure/token/cadre, then validates the responder's result via the
208
+ * {@link FormationResponseValidator} (or a built-in structural check).
209
+ */
210
+ export class StrandFormationManager {
211
+ private readonly disclosureValidator?: DisclosureValidator;
212
+ private readonly formationUsageRecorder?: FormationUsageRecorder;
213
+ private readonly strandProvisioner?: StrandProvisioner;
214
+ private readonly formationResponseValidator?: FormationResponseValidator;
215
+ private readonly partyId: string;
216
+ private readonly cadrePeerAddrs: string[];
217
+ private readonly resolveStrandAddrs?: (strandId: string) => string[];
218
+ private readonly issueMembershipInvite?: MembershipInviteIssuer;
219
+ private readonly config: StrandFormationManagerConfig;
220
+ private readonly listener: FormationListener;
221
+ private readonly registeredNodes = new Set<Libp2p>();
222
+ private dialerSessions = 0;
223
+
224
+ constructor(options: StrandFormationManagerOptions) {
225
+ this.disclosureValidator = options.disclosureValidator;
226
+ this.formationUsageRecorder = options.formationUsageRecorder;
227
+ this.strandProvisioner = options.strandProvisioner;
228
+ this.formationResponseValidator = options.formationResponseValidator;
229
+ this.partyId = options.partyId;
230
+ this.cadrePeerAddrs = options.cadrePeerAddrs ?? [];
231
+ this.resolveStrandAddrs = options.resolveStrandAddrs;
232
+ this.issueMembershipInvite = options.issueMembershipInvite;
233
+ this.config = options.config ?? {};
234
+
235
+ this.listener = new FormationListener({
236
+ validateToken: (token) => this.validateToken(token),
237
+ validateDisclosure: (token, disclosure) => this.validateDisclosure(token, disclosure),
238
+ provisionStrand: (contact, signal) =>
239
+ this.provisionAsResponder(contact, signal),
240
+ getResponderIdentity: () => ({ partyId: this.partyId, cadrePeerAddrs: this.cadrePeerAddrs }),
241
+ // Forwarded only when wired, so `FormationListenerOptions.resolveStrandAddrs`
242
+ // stays genuinely absent (and the listener short-circuits) for an unwired manager.
243
+ ...(this.resolveStrandAddrs && { resolveStrandAddrs: this.resolveStrandAddrs }),
244
+ linkRoundTripMs: this.config.linkRoundTripMs,
245
+ sessionTimeoutMs: this.config.sessionTimeoutMs,
246
+ stepTimeoutMs: this.config.stepTimeoutMs,
247
+ provisionTimeoutMs: this.config.provisionTimeoutMs,
248
+ maxConcurrentSessions: this.config.maxConcurrentSessions
249
+ });
250
+
251
+ log('StrandFormationManager created for party: %s', this.partyId);
252
+ }
253
+
254
+ /**
255
+ * Register this manager as a protocol handler on a libp2p node.
256
+ * Call this on the control network node to handle incoming formation requests.
257
+ */
258
+ async registerResponder(node: Libp2p, protocolId?: string): Promise<void> {
259
+ if (this.registeredNodes.has(node)) {
260
+ log('Node already registered');
261
+ return;
262
+ }
263
+ await this.listener.register(node, protocolId ?? this.config.protocolId);
264
+ this.registeredNodes.add(node);
265
+ log('Registered as responder on node');
266
+ }
267
+
268
+ /**
269
+ * Unregister the protocol handler from a libp2p node.
270
+ */
271
+ async unregisterResponder(node: Libp2p, protocolId?: string): Promise<void> {
272
+ if (!this.registeredNodes.has(node)) {
273
+ return;
274
+ }
275
+ await this.listener.unregister(node, protocolId ?? this.config.protocolId);
276
+ this.registeredNodes.delete(node);
277
+ log('Unregistered from node');
278
+ }
279
+
280
+ /**
281
+ * Form a strand with a responder via an open invitation (initiator side).
282
+ *
283
+ * Builds a contact message carrying the real token + disclosure + this party's
284
+ * real cadre addresses + the joiner's consent (minted and signed by the
285
+ * solicitation layer — this manager only places it on the contact), dials the
286
+ * responder over the native protocol, and validates the responder's result
287
+ * before returning.
288
+ */
289
+ async formStrand(
290
+ invitation: OpenInvitation,
291
+ disclosure: StrandFormationDisclosure,
292
+ consent: { peerKey: string; usageStampId: string; peerSignature: string },
293
+ node: Libp2p
294
+ ): Promise<FormStrandResult> {
295
+ log('Forming strand with invitation token: %s', invitation.token);
296
+
297
+ const contact: FormationContactMessage = {
298
+ token: invitation.token,
299
+ partyId: disclosure.partyId ?? this.partyId,
300
+ peerKey: consent.peerKey,
301
+ usageStampId: consent.usageStampId,
302
+ peerSignature: consent.peerSignature,
303
+ disclosure,
304
+ cadrePeerAddrs: this.cadrePeerAddrs
305
+ };
306
+
307
+ this.dialerSessions++;
308
+ try {
309
+ const dialed = await dialFormation(node, {
310
+ contact,
311
+ responderAddrs: invitation.bootstrap,
312
+ validateResponse: (response) => this.validateResponse(invitation, disclosure, response),
313
+ linkRoundTripMs: this.config.linkRoundTripMs,
314
+ sessionTimeoutMs: this.config.sessionTimeoutMs,
315
+ dialTimeoutMs: this.config.dialTimeoutMs,
316
+ provisionTimeoutMs: this.initiatorProvisionTimeoutMs(),
317
+ protocolId: this.config.protocolId
318
+ });
319
+
320
+ const provision = dialed.provision;
321
+ log('Strand formed: %s (%d cross-party strand addr(s))', provision.strand.strandId, dialed.strandAddrs.length);
322
+
323
+ return {
324
+ memberKey: contact.partyId,
325
+ invitePrivateKey: '',
326
+ strandId: provision.strand.strandId,
327
+ // The host strand's membership key, delivered through the protocol (provision-then-record).
328
+ // Undefined for an open strand. Kept separate from invitePrivateKey (the initiator's
329
+ // generated signing key), which is set by the StrandSolicitationService layer.
330
+ memberPrivateKey: provision.memberPrivateKey,
331
+ // Carried only when well-formed. The DEFAULT response validator already rejects
332
+ // a malformed one; this re-check keeps a custom validator that skips the shape
333
+ // check from feeding a hostile responder's object into the joiner's invite cache.
334
+ membershipInvite: this.membershipInviteFrom(provision),
335
+ // Possibly empty — the responder may hold no live strand node yet.
336
+ strandAddrs: dialed.strandAddrs
337
+ };
338
+ } finally {
339
+ this.dialerSessions--;
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Get the number of active sessions
345
+ */
346
+ getActiveSessionCounts(): { listeners: number; dialers: number } {
347
+ return { listeners: this.listener.activeCount, dialers: this.dialerSessions };
348
+ }
349
+
350
+ /**
351
+ * The provision result's membership invitation, iff well-formed — a malformed one
352
+ * (possible only past a custom {@link FormationResponseValidator} that skipped the
353
+ * structural check) is dropped with a log rather than cached: it could never redeem
354
+ * anyway, and carrying an unbounded hostile object outlives the session.
355
+ */
356
+ private membershipInviteFrom(provision: FormationProvisionResult): StrandMembershipInvite | undefined {
357
+ if (provision.membershipInvite === undefined) {
358
+ return undefined;
359
+ }
360
+ if (!isWellFormedMembershipInvite(provision.membershipInvite)) {
361
+ log('formStrand: dropping malformed membershipInvite from responder for strand %s', provision.strand.strandId);
362
+ return undefined;
363
+ }
364
+ return { inviteKey: provision.membershipInvite.inviteKey, invitePrivateKey: provision.membershipInvite.invitePrivateKey };
365
+ }
366
+
367
+ /**
368
+ * Derive the initiator's await-response budget from the configured RESPONDER budget —
369
+ * never the same number (see `StrandFormationManagerConfig.provisionTimeoutMs`): the
370
+ * configured value plus the travel margin the ladder derives at this machine's link.
371
+ * Mirrors `resolveProvisionTimeoutMs`'s own "`0`/negative means unset" rule so an unset
372
+ * config still lets both sides fall back to their own derived defaults; must NOT
373
+ * reproduce the derived default here, or the per-role clamping downstream is defeated.
374
+ * A value too large for the session is clamped per role, and the responder's ceiling holds
375
+ * the margin back, so the ordering survives there too.
376
+ */
377
+ private initiatorProvisionTimeoutMs(): number | undefined {
378
+ const host = this.config.provisionTimeoutMs;
379
+ return host && host > 0
380
+ ? host + formationDeadlines(this.config.linkRoundTripMs).responseTravelMarginMs
381
+ : undefined;
382
+ }
383
+
384
+ // ── Responder-side hooks ─────────────────────────────────────────────────────
385
+
386
+ private async validateToken(token: string): Promise<{ valid: boolean }> {
387
+ if (!this.formationUsageRecorder) {
388
+ // No recorder configured — accept all tokens.
389
+ return { valid: true };
390
+ }
391
+
392
+ const tokenCheck = await this.formationUsageRecorder.isTokenValid(token);
393
+ if (!tokenCheck.valid) {
394
+ log('Token invalid: %s', token);
395
+ return { valid: false };
396
+ }
397
+
398
+ if (await this.formationUsageRecorder.isTokenUsed(token)) {
399
+ log('Token already used: %s', token);
400
+ return { valid: false };
401
+ }
402
+
403
+ return { valid: true };
404
+ }
405
+
406
+ private async validateDisclosure(token: string, disclosure: StrandFormationDisclosure): Promise<boolean> {
407
+ if (!this.disclosureValidator) {
408
+ // No validator configured — accept all disclosures.
409
+ return true;
410
+ }
411
+ return this.disclosureValidator.validateDisclosure(token, disclosure);
412
+ }
413
+
414
+ /**
415
+ * Responder-side provisioning. Routes on how the invite resolves
416
+ * ({@link ResolvedHostStrand}), and can REJECT post-validation by returning a
417
+ * {@link ResponderProvisionOutcome} with `approved: false` — `runSession` turns that
418
+ * into a clean, non-disclosing reply instead of a dropped result frame.
419
+ *
420
+ * - **bound** (host strand present): provision-then-record, in three steps —
421
+ * (1) authorize ({@link authorizeBoundUsage}: the outside approval when the invite
422
+ * demands one, and a seat pre-check), so a refused join writes nothing into the host
423
+ * strand; (2) issue the joiner's single-use strand membership invitation via the wired
424
+ * `issueMembershipInvite` seam ({@link issueBoundMembershipInvite}; a closed strand whose
425
+ * invitation cannot be issued rejects retryably HERE, before any consent row spends the
426
+ * token); (3) write the single `FormationUsage` consent row against the pre-existing
427
+ * strand (record-only) and return it + its membership key + the invitation (all
428
+ * read-gating secrets disclosed only here, behind the token + disclosure validation
429
+ * `runSession` already enforced).
430
+ * - **missing** (invite names a host strand absent on this responder, e.g. unconverged):
431
+ * reject cleanly + retryably, writing NO usage row — recording usage here would fail the
432
+ * deferred `StrandExists` CHECK at commit and drop the frame.
433
+ * - **unbound** (no binding): the responder-provisions fallback — see {@link provisionUnbound}.
434
+ *
435
+ * Defense-in-depth: known provisioning/redeem failures are caught and mapped to a logged
436
+ * protocol rejection rather than a thrown insert + a silently-closed stream. The mapping is
437
+ * per-failure, NOT blanket retry-suggesting: an exhausted invitation
438
+ * ({@link InvitationExhaustedError}, raised by `ControlDatabase` when the count of recorded
439
+ * uses has reached the invite's seat budget — which is how the loser of a same-node race
440
+ * surfaces, the local write queue having serialized the two writes) is reported as
441
+ * `'Invalid token'`, because retrying it can never succeed. Concurrent redemptions never
442
+ * contend for a shared row key — each writes under its own `UsageStampId` — so there is no
443
+ * key collision to surface here at all. The LOG-before-reject keeps this a deliberate
444
+ * internal-error→protocol-rejection conversion (AGENTS.md: don't eat exceptions silently),
445
+ * not control-flow-by-exception.
446
+ */
447
+ private async provisionAsResponder(
448
+ contact: FormationContactMessage,
449
+ signal?: AbortSignal
450
+ ): Promise<ResponderProvisionOutcome> {
451
+ const token = contact.token;
452
+ // CANONICALLY serialized — both sides derive the identical string: this is the exact
453
+ // text the joiner signed (consent), the approver signs (vouch), and the recorder writes
454
+ // to `FormationUsage.Disclosure` — a re-serialization anywhere below would break the
455
+ // signature-over-stored-bytes invariant.
456
+ const disclosureText = canonicalJson(contact.disclosure);
457
+ if (uint8ArrayFromString(disclosureText, 'utf8').byteLength > MAX_DISCLOSURE_BYTES) {
458
+ log('Disclosure over %d bytes; rejecting token %s', MAX_DISCLOSURE_BYTES, token);
459
+ return { approved: false, reason: 'Disclosure too large' };
460
+ }
461
+
462
+ const recorder = this.formationUsageRecorder;
463
+ const resolved: ResolvedHostStrand = recorder?.resolveStrand
464
+ ? await recorder.resolveStrand(token)
465
+ : { kind: 'unbound' };
466
+
467
+ try {
468
+ switch (resolved.kind) {
469
+ case 'bound': {
470
+ // recorder is guaranteed non-null here: only resolveStrand can yield 'bound'.
471
+ const authorized = await this.authorizeBoundUsage(recorder!, {
472
+ token,
473
+ peerKey: contact.peerKey,
474
+ peerSignature: contact.peerSignature,
475
+ usageStampId: contact.usageStampId,
476
+ strandId: resolved.strandId,
477
+ disclosure: disclosureText,
478
+ signal
479
+ });
480
+ // Issued only once authorized (a refused join writes nothing into the strand) and
481
+ // BEFORE consent is recorded (an issue failure leaves the token unspent, retryable).
482
+ // The remaining window — invite issued, then record() fails or aborts (a write that
483
+ // exhausted its retries, an abort, or the same-node seat race noted at
484
+ // `ControlFormationUsageRecorder.assertSeatFree`) — orphans a
485
+ // live `Strand.Invite` no joiner ever received; bounded deliberately by its expiry
486
+ // ({@link MEMBERSHIP_INVITE_TTL_MS}) rather than compensated, since nothing
487
+ // here can atomically un-issue a strand-DB row.
488
+ const issued = await this.issueBoundMembershipInvite(token, resolved.strandId, signal);
489
+ if (!issued.ok) {
490
+ return { approved: false, reason: issued.reason };
491
+ }
492
+ await authorized.record();
493
+ return this.approve({
494
+ strand: { strandId: resolved.strandId, createdBy: 'responder' },
495
+ memberPrivateKey: resolved.memberPrivateKey ?? undefined,
496
+ // Omitted (not sent undefined-valued) so rejection-parity and open-strand
497
+ // assertions stay plain `toBeUndefined()` on the parsed frame.
498
+ ...(issued.invite ? { membershipInvite: issued.invite } : {}),
499
+ dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
500
+ });
501
+ }
502
+ case 'missing': {
503
+ log('Host strand %s not yet available on this responder; rejecting token %s', resolved.strandId, token);
504
+ return { approved: false, reason: 'Host strand not yet available on this responder' };
505
+ }
506
+ case 'unbound':
507
+ return await this.provisionUnbound(contact, disclosureText, signal);
508
+ }
509
+ } catch (err) {
510
+ if (err instanceof FormationAbortedError) {
511
+ // The listener's timeout path owns the reply for an abandoned provisioning; mapping
512
+ // this onto 'Formation conflict, retry' would misreport it as a conflict.
513
+ throw err;
514
+ }
515
+ if (err instanceof FormationApprovalError) {
516
+ log('approval failed (%s) for token %s: %o', err.failure, token, err);
517
+ return { approved: false, reason: APPROVAL_REJECTION_REASONS[err.failure] };
518
+ }
519
+ if (err instanceof InvitationExhaustedError) {
520
+ // Shares `INVALID_TOKEN_REASON` with the up-front `validateToken` rejection so the loser
521
+ // of the race that exposed the spent invite sees exactly what a non-racing latecomer
522
+ // sees. No wire-visible distinction between "invalid" and "exhausted" — the
523
+ // operator signal lives in this log line instead.
524
+ // NOTE: if a joining client ever has to tell "never valid" from "used up" WITHOUT node
525
+ // logs, that is a new protocol reason string, not a local change here.
526
+ log(
527
+ 'invitation exhausted for token %s: %d of %d use(s) already recorded',
528
+ err.token,
529
+ err.usesRecorded,
530
+ err.totalUses
531
+ );
532
+ return { approved: false, reason: INVALID_TOKEN_REASON };
533
+ }
534
+ // An approval is never discarded to a lost key race: each redemption writes under its
535
+ // own `UsageStampId`, so no other writer can take its row key. Reaching this catch-all
536
+ // means the failure was never retryable at the database layer to begin with (or the
537
+ // transient-cluster retry inside `ControlDatabase.lockedWithRetry` ran out).
538
+ log('provisionAsResponder failed for token %s: %o', token, err);
539
+ return { approved: false, reason: 'Formation conflict, retry' };
540
+ }
541
+ }
542
+
543
+ /**
544
+ * Authorize a BOUND redemption without writing it, through the recorder's optional
545
+ * {@link FormationUsageRecorder.authorizeUsage}. A recorder without it has nothing to ask up
546
+ * front, so its handle defers everything to `recordUsage`.
547
+ */
548
+ private async authorizeBoundUsage(
549
+ recorder: FormationUsageRecorder,
550
+ params: FormationUsageParams
551
+ ): Promise<AuthorizedFormationUsage> {
552
+ if (recorder.authorizeUsage) {
553
+ return await recorder.authorizeUsage(params);
554
+ }
555
+ return { record: () => recorder.recordUsage(params) };
556
+ }
557
+
558
+ /**
559
+ * Issue the joiner's membership invitation for a BOUND redemption via the wired
560
+ * {@link StrandFormationManagerOptions.issueMembershipInvite} seam. Runs after the
561
+ * redemption is authorized ({@link authorizeBoundUsage}) and before consent is recorded.
562
+ *
563
+ * - Hook unwired (mock/transport tests): approve with no invitation, the same posture
564
+ * as an unwired `resolveStrandAddrs`.
565
+ * - Hook returns an invitation (closed host strand): carry it on the approval.
566
+ * - Hook returns `null` (open host strand): approve with no invitation.
567
+ * - Hook throws (runtime not live — including a hibernating one whose wake outran
568
+ * `signal` — no party key, strand-DB write rejected): report
569
+ * `ok: false` with {@link MEMBERSHIP_INVITE_UNAVAILABLE_REASON} — the caller rejects
570
+ * BEFORE any consent row is written, so the formation token stays unspent.
571
+ * - Hook throws `PreSplitStrandIdentityError` (the host strand was founded before the
572
+ * per-party identity split and can never issue one): same, but with the
573
+ * non-retryable {@link HOST_STRAND_MUST_BE_RECREATED_REASON}.
574
+ *
575
+ * The LOG-before-reject keeps both a deliberate internal-error→protocol-rejection
576
+ * conversion, same as the catch-all in {@link provisionAsResponder}.
577
+ */
578
+ private async issueBoundMembershipInvite(
579
+ token: string,
580
+ strandId: string,
581
+ signal?: AbortSignal
582
+ ): Promise<{ ok: true; invite?: StrandMembershipInvite } | { ok: false; reason: string }> {
583
+ if (!this.issueMembershipInvite) {
584
+ return { ok: true };
585
+ }
586
+ try {
587
+ const invite = await this.issueMembershipInvite(strandId, signal);
588
+ return { ok: true, invite: invite ?? undefined };
589
+ } catch (err) {
590
+ if (err instanceof PreSplitStrandIdentityError) {
591
+ log('host strand %s is pre-split (token %s); rejecting — it must be recreated: %o', strandId, token, err);
592
+ return { ok: false, reason: HOST_STRAND_MUST_BE_RECREATED_REASON };
593
+ }
594
+ log('membership-invite issue for strand %s failed (token %s); rejecting retryably: %o', strandId, token, err);
595
+ return { ok: false, reason: MEMBERSHIP_INVITE_UNAVAILABLE_REASON };
596
+ }
597
+ }
598
+
599
+ /**
600
+ * Responder-provisions fallback (invite binds no host strand). Precedence:
601
+ *
602
+ * 1. `recorder.provisionAndRecord` present (a real DB recorder) → atomic create-strand +
603
+ * record-consent, so the unbound redemption is single-use just like the bound path.
604
+ * Returns the new strand (+ key, null for an open responder-provisioned strand).
605
+ * 2. else `strandProvisioner` present → the mock/transport-test contract: provision a bare
606
+ * strand, NO inline usage write (those callers record usage explicitly via
607
+ * `recordFormationComplete`, or assert transport invariants only). Threads the invite's
608
+ * REAL `sAppId`.
609
+ * 3. else → a structural placeholder (no recorder + no provisioner ⇒ no single-use semantics
610
+ * exist to enforce).
611
+ *
612
+ * NOTE: accepted tradeoff — the plan chose (a) "record usage on the fallback" over (b)
613
+ * "remove the fallback", so arm 2 (`strandProvisioner`, no recorder) is kept. (a) closes the
614
+ * single-use hole with a targeted atomic create+record and leaves the `StrandProvisioner`
615
+ * mock-transport tests untouched; (b) would delete the provisioner surface and churn ~6 unit
616
+ * + ~6 integration sites for ZERO production benefit (production — `cadre-web.ts` /
617
+ * `cadre-phone.ts` — always publishes strand-BOUND invites and treats the
618
+ * responder-provisions placeholder as failure). Revisit if production starts publishing
619
+ * unbound invites, or the mock-transport tests go away.
620
+ */
621
+ private async provisionUnbound(
622
+ contact: FormationContactMessage,
623
+ disclosureText: string,
624
+ signal?: AbortSignal
625
+ ): Promise<ResponderProvisionOutcome> {
626
+ const token = contact.token;
627
+ const recorder = this.formationUsageRecorder;
628
+ if (recorder?.provisionAndRecord) {
629
+ const sAppId = await this.resolveInviteSAppId(token);
630
+ const provisioned = await recorder.provisionAndRecord({
631
+ token,
632
+ peerKey: contact.peerKey,
633
+ peerSignature: contact.peerSignature,
634
+ usageStampId: contact.usageStampId,
635
+ sAppId,
636
+ disclosure: disclosureText,
637
+ signal
638
+ });
639
+ return this.approve({
640
+ strand: { strandId: provisioned.strandId, createdBy: 'responder' },
641
+ memberPrivateKey: provisioned.memberPrivateKey ?? undefined,
642
+ dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
643
+ });
644
+ }
645
+
646
+ if (this.strandProvisioner) {
647
+ const sAppId = await this.resolveInviteSAppId(token);
648
+ const result = await this.strandProvisioner.provisionStrand(sAppId, contact.partyId, this.partyId);
649
+ return this.approve({
650
+ strand: { strandId: result.strandId, createdBy: 'responder' },
651
+ dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
652
+ });
653
+ }
654
+
655
+ // No recorder + no provisioner — a structural placeholder the initiator can still validate.
656
+ const strandId = mintPlaceholderStrandId();
657
+ return this.approve({
658
+ strand: { strandId, createdBy: 'responder' },
659
+ dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
660
+ });
661
+ }
662
+
663
+ /** Wrap a provision result as an approving {@link ResponderProvisionOutcome}. */
664
+ private approve(result: FormationProvisionResult): ResponderProvisionOutcome {
665
+ return { approved: true, result };
666
+ }
667
+
668
+ /**
669
+ * The invite's authoritative `sAppId` for the responder-provisions fallback, read back
670
+ * from the recorder's `isTokenValid` invitation (the real `FormationInvite.sAppId`).
671
+ * Empty string when no recorder is wired or the invitation omits it.
672
+ */
673
+ private async resolveInviteSAppId(token: string): Promise<string> {
674
+ if (!this.formationUsageRecorder) return '';
675
+ const check = await this.formationUsageRecorder.isTokenValid(token);
676
+ return check.invitation?.sAppId ?? '';
677
+ }
678
+
679
+ // ── Initiator-side result validation ─────────────────────────────────────────
680
+
681
+ private async validateResponse(
682
+ invitation: OpenInvitation,
683
+ disclosure: StrandFormationDisclosure,
684
+ response: FormationResultMessage
685
+ ): Promise<boolean> {
686
+ if (this.formationResponseValidator) {
687
+ return this.formationResponseValidator.validateResponse({ invitation, disclosure, response });
688
+ }
689
+ return isValidResponderCreatesResult(response);
690
+ }
691
+ }
692
+
693
+ /**
694
+ * Create a StrandFormationManager with the given options
695
+ */
696
+ export function createStrandFormationManager(
697
+ options: StrandFormationManagerOptions
698
+ ): StrandFormationManager {
699
+ return new StrandFormationManager(options);
700
+ }