@serfab/cadre-core 0.9.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 (193) hide show
  1. package/README.md +255 -253
  2. package/dist/bootstrap-peer-store-file.d.ts +13 -0
  3. package/dist/bootstrap-peer-store-file.js +42 -0
  4. package/dist/bootstrap-peer-store-file.js.map +1 -0
  5. package/dist/bootstrap-peer-store.d.ts +73 -0
  6. package/dist/bootstrap-peer-store.js +128 -0
  7. package/dist/bootstrap-peer-store.js.map +1 -0
  8. package/dist/cadre-node.d.ts +1121 -81
  9. package/dist/cadre-node.js +2276 -262
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/control-authorization.d.ts +93 -0
  12. package/dist/control-authorization.js +57 -0
  13. package/dist/control-authorization.js.map +1 -0
  14. package/dist/control-cohort.d.ts +26 -0
  15. package/dist/control-cohort.js +26 -0
  16. package/dist/control-cohort.js.map +1 -1
  17. package/dist/control-database.d.ts +959 -54
  18. package/dist/control-database.js +1421 -148
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +90 -10
  21. package/dist/control-formation-recorder.js +130 -14
  22. package/dist/control-formation-recorder.js.map +1 -1
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +651 -72
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-stream.d.ts +38 -4
  27. package/dist/control-stream.js +70 -4
  28. package/dist/control-stream.js.map +1 -1
  29. package/dist/control-write-retry.d.ts +161 -0
  30. package/dist/control-write-retry.js +412 -0
  31. package/dist/control-write-retry.js.map +1 -0
  32. package/dist/delegate-admission.d.ts +134 -0
  33. package/dist/delegate-admission.js +244 -0
  34. package/dist/delegate-admission.js.map +1 -0
  35. package/dist/device-token.d.ts +11 -11
  36. package/dist/device-token.js +14 -13
  37. package/dist/device-token.js.map +1 -1
  38. package/dist/ed25519-key.d.ts +26 -0
  39. package/dist/ed25519-key.js +56 -1
  40. package/dist/ed25519-key.js.map +1 -1
  41. package/dist/file-durable-slot.d.ts +20 -0
  42. package/dist/file-durable-slot.js +53 -0
  43. package/dist/file-durable-slot.js.map +1 -0
  44. package/dist/formation-approval.d.ts +157 -0
  45. package/dist/formation-approval.js +375 -0
  46. package/dist/formation-approval.js.map +1 -0
  47. package/dist/fs-atomic.d.ts +38 -0
  48. package/dist/fs-atomic.js +97 -0
  49. package/dist/fs-atomic.js.map +1 -0
  50. package/dist/identity-key.d.ts +49 -0
  51. package/dist/identity-key.js +81 -0
  52. package/dist/identity-key.js.map +1 -0
  53. package/dist/index.d.ts +17 -7
  54. package/dist/index.js +40 -6
  55. package/dist/index.js.map +1 -1
  56. package/dist/key-store-file.d.ts +2 -24
  57. package/dist/key-store-file.js +10 -77
  58. package/dist/key-store-file.js.map +1 -1
  59. package/dist/membership-connection-gater.d.ts +146 -0
  60. package/dist/membership-connection-gater.js +180 -0
  61. package/dist/membership-connection-gater.js.map +1 -0
  62. package/dist/node-local-snapshot.d.ts +109 -0
  63. package/dist/node-local-snapshot.js +182 -0
  64. package/dist/node-local-snapshot.js.map +1 -0
  65. package/dist/peer-addr-book.d.ts +92 -0
  66. package/dist/peer-addr-book.js +220 -0
  67. package/dist/peer-addr-book.js.map +1 -0
  68. package/dist/peer-authorization.d.ts +135 -18
  69. package/dist/peer-authorization.js +152 -21
  70. package/dist/peer-authorization.js.map +1 -1
  71. package/dist/peer-record.d.ts +21 -8
  72. package/dist/peer-record.js +26 -10
  73. package/dist/peer-record.js.map +1 -1
  74. package/dist/relay-addrs.d.ts +45 -0
  75. package/dist/relay-addrs.js +103 -0
  76. package/dist/relay-addrs.js.map +1 -0
  77. package/dist/relay-reservation.d.ts +266 -0
  78. package/dist/relay-reservation.js +613 -0
  79. package/dist/relay-reservation.js.map +1 -0
  80. package/dist/seed-bootstrap.d.ts +228 -56
  81. package/dist/seed-bootstrap.js +340 -198
  82. package/dist/seed-bootstrap.js.map +1 -1
  83. package/dist/seed-trust-policy.d.ts +47 -21
  84. package/dist/seed-trust-policy.js +24 -15
  85. package/dist/seed-trust-policy.js.map +1 -1
  86. package/dist/strand-addr-protocol.d.ts +42 -13
  87. package/dist/strand-addr-protocol.js +58 -52
  88. package/dist/strand-addr-protocol.js.map +1 -1
  89. package/dist/strand-backfill.d.ts +109 -0
  90. package/dist/strand-backfill.js +279 -0
  91. package/dist/strand-backfill.js.map +1 -0
  92. package/dist/strand-cohort.d.ts +4 -37
  93. package/dist/strand-cohort.js +4 -15
  94. package/dist/strand-cohort.js.map +1 -1
  95. package/dist/strand-database.d.ts +11 -16
  96. package/dist/strand-database.js +19 -7
  97. package/dist/strand-database.js.map +1 -1
  98. package/dist/strand-formation-manager.d.ts +36 -7
  99. package/dist/strand-formation-manager.js +115 -15
  100. package/dist/strand-formation-manager.js.map +1 -1
  101. package/dist/strand-formation-protocol.d.ts +103 -4
  102. package/dist/strand-formation-protocol.js +232 -4
  103. package/dist/strand-formation-protocol.js.map +1 -1
  104. package/dist/strand-instance-manager.d.ts +88 -19
  105. package/dist/strand-instance-manager.js +178 -34
  106. package/dist/strand-instance-manager.js.map +1 -1
  107. package/dist/strand-member-registry.d.ts +5 -5
  108. package/dist/strand-member-registry.js +18 -10
  109. package/dist/strand-member-registry.js.map +1 -1
  110. package/dist/strand-membership-writer.d.ts +484 -88
  111. package/dist/strand-membership-writer.js +751 -128
  112. package/dist/strand-membership-writer.js.map +1 -1
  113. package/dist/strand-solicitation.d.ts +99 -33
  114. package/dist/strand-solicitation.js +100 -52
  115. package/dist/strand-solicitation.js.map +1 -1
  116. package/dist/strand-transport-key.d.ts +40 -0
  117. package/dist/strand-transport-key.js +56 -0
  118. package/dist/strand-transport-key.js.map +1 -0
  119. package/dist/strand-wake-protocol.d.ts +9 -7
  120. package/dist/strand-wake-protocol.js +22 -46
  121. package/dist/strand-wake-protocol.js.map +1 -1
  122. package/dist/strand-watcher.d.ts +17 -2
  123. package/dist/strand-watcher.js +47 -3
  124. package/dist/strand-watcher.js.map +1 -1
  125. package/dist/trusted-owner-store-file.d.ts +12 -0
  126. package/dist/trusted-owner-store-file.js +39 -0
  127. package/dist/trusted-owner-store-file.js.map +1 -0
  128. package/dist/trusted-owner-store.d.ts +64 -0
  129. package/dist/trusted-owner-store.js +126 -0
  130. package/dist/trusted-owner-store.js.map +1 -0
  131. package/dist/types.d.ts +307 -44
  132. package/dist/types.js +13 -0
  133. package/dist/types.js.map +1 -1
  134. package/package.json +20 -8
  135. package/src/arachnode-stub.ts +159 -159
  136. package/src/bootstrap-peer-store-file.ts +44 -0
  137. package/src/bootstrap-peer-store.ts +172 -0
  138. package/src/cadre-node.ts +5158 -2981
  139. package/src/canonical-json.ts +30 -30
  140. package/src/control-authorization.ts +114 -0
  141. package/src/control-cohort.ts +130 -103
  142. package/src/control-database.ts +2406 -948
  143. package/src/control-formation-recorder.ts +305 -151
  144. package/src/control-schema.ts +651 -72
  145. package/src/control-stream.ts +205 -128
  146. package/src/control-write-retry.ts +483 -0
  147. package/src/delegate-admission.ts +302 -0
  148. package/src/device-token.ts +94 -89
  149. package/src/diagnostics/connection-path.ts +277 -277
  150. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  151. package/src/ed25519-key.ts +66 -1
  152. package/src/enrollment.ts +199 -199
  153. package/src/file-durable-slot.ts +61 -0
  154. package/src/formation-approval.ts +604 -0
  155. package/src/fs-atomic.ts +107 -0
  156. package/src/hibernation-manager.ts +437 -437
  157. package/src/identity-key.ts +109 -0
  158. package/src/index.ts +137 -5
  159. package/src/key-store-file.ts +132 -203
  160. package/src/key-store.ts +99 -99
  161. package/src/membership-connection-gater.ts +204 -0
  162. package/src/node-local-snapshot.ts +260 -0
  163. package/src/peer-addr-book.ts +250 -0
  164. package/src/peer-authorization.ts +259 -81
  165. package/src/peer-record.ts +164 -146
  166. package/src/push-credentials.ts +84 -84
  167. package/src/push-node.ts +64 -64
  168. package/src/push-notifier-apns.ts +247 -247
  169. package/src/push-notifier-fcm.ts +220 -220
  170. package/src/push-notifier-shared.ts +28 -28
  171. package/src/push-notifier.ts +52 -52
  172. package/src/relay-addrs.ts +111 -0
  173. package/src/relay-reservation.ts +823 -0
  174. package/src/seed-bootstrap.ts +409 -209
  175. package/src/seed-trust-policy.ts +140 -107
  176. package/src/strand-addr-protocol.ts +441 -410
  177. package/src/strand-backfill.ts +366 -0
  178. package/src/strand-cohort.ts +38 -77
  179. package/src/strand-database.ts +202 -204
  180. package/src/strand-formation-manager.ts +491 -368
  181. package/src/strand-formation-protocol.ts +692 -391
  182. package/src/strand-instance-manager.ts +201 -46
  183. package/src/strand-member-key.ts +39 -39
  184. package/src/strand-member-registry.ts +182 -177
  185. package/src/strand-membership-writer.ts +938 -146
  186. package/src/strand-solicitation.ts +472 -407
  187. package/src/strand-transport-key.ts +58 -0
  188. package/src/strand-wake-payload.ts +32 -32
  189. package/src/strand-wake-protocol.ts +314 -331
  190. package/src/strand-watcher.ts +314 -251
  191. package/src/trusted-owner-store-file.ts +41 -0
  192. package/src/trusted-owner-store.ts +171 -0
  193. package/src/types.ts +1309 -1032
@@ -1,368 +1,491 @@
1
- import debug from 'debug';
2
- import type { Libp2p } from '@libp2p/interface';
3
- import type {
4
- OpenInvitation,
5
- FormStrandResult,
6
- StrandFormationDisclosure
7
- } from './types.js';
8
- import type {
9
- DisclosureValidator,
10
- FormationUsageRecorder,
11
- ResolvedHostStrand,
12
- StrandProvisioner,
13
- FormationResponseValidator
14
- } from './strand-solicitation.js';
15
- import {
16
- FormationListener,
17
- dialFormation,
18
- isValidResponderCreatesResult,
19
- type FormationContactMessage,
20
- type FormationProvisionResult,
21
- type FormationResultMessage,
22
- type ResponderProvisionOutcome
23
- } from './strand-formation-protocol.js';
24
-
25
- const log = debug('sereus:cadre:formation-manager');
26
-
27
- /**
28
- * Configuration for StrandFormationManager
29
- */
30
- export interface StrandFormationManagerConfig {
31
- /** Session timeout in milliseconds */
32
- sessionTimeoutMs?: number;
33
- /** Step timeout in milliseconds */
34
- stepTimeoutMs?: number;
35
- /** Maximum concurrent sessions */
36
- maxConcurrentSessions?: number;
37
- /** Enable debug logging */
38
- enableDebugLogging?: boolean;
39
- /** Protocol ID override */
40
- protocolId?: string;
41
- }
42
-
43
- /**
44
- * Options for creating a StrandFormationManager
45
- */
46
- export interface StrandFormationManagerOptions {
47
- /** Validates disclosures from initiators (responder side) */
48
- disclosureValidator?: DisclosureValidator;
49
- /** Records and validates token usage (responder side) */
50
- formationUsageRecorder?: FormationUsageRecorder;
51
- /** Provisions strands after validation (responder side) */
52
- strandProvisioner?: StrandProvisioner;
53
- /** Validates the responder's result (initiator side); defaults to a structural check */
54
- formationResponseValidator?: FormationResponseValidator;
55
- /** This party's ID for identification */
56
- partyId: string;
57
- /** This party's cadre peer addresses */
58
- cadrePeerAddrs?: string[];
59
- /** Configuration options */
60
- config?: StrandFormationManagerConfig;
61
- }
62
-
63
- /**
64
- * StrandFormationManager drives the native cadre-core formation transport
65
- * (`strand-formation-protocol.ts`) from cadre-core's strand-solicitation interfaces.
66
- *
67
- * Responder side: a {@link FormationListener} wires the inbound protocol to
68
- * {@link FormationUsageRecorder} (token), {@link DisclosureValidator} (identity),
69
- * and {@link StrandProvisioner} (provisioning), disclosing this party's real
70
- * identity + cadre only after validation.
71
- *
72
- * Initiator side: {@link formStrand} dials the responder carrying the real
73
- * disclosure/token/cadre, then validates the responder's result via the
74
- * {@link FormationResponseValidator} (or a built-in structural check).
75
- */
76
- export class StrandFormationManager {
77
- private readonly disclosureValidator?: DisclosureValidator;
78
- private readonly formationUsageRecorder?: FormationUsageRecorder;
79
- private readonly strandProvisioner?: StrandProvisioner;
80
- private readonly formationResponseValidator?: FormationResponseValidator;
81
- private readonly partyId: string;
82
- private readonly cadrePeerAddrs: string[];
83
- private readonly config: StrandFormationManagerConfig;
84
- private readonly listener: FormationListener;
85
- private readonly registeredNodes = new Set<Libp2p>();
86
- private dialerSessions = 0;
87
-
88
- constructor(options: StrandFormationManagerOptions) {
89
- this.disclosureValidator = options.disclosureValidator;
90
- this.formationUsageRecorder = options.formationUsageRecorder;
91
- this.strandProvisioner = options.strandProvisioner;
92
- this.formationResponseValidator = options.formationResponseValidator;
93
- this.partyId = options.partyId;
94
- this.cadrePeerAddrs = options.cadrePeerAddrs ?? [];
95
- this.config = options.config ?? {};
96
-
97
- this.listener = new FormationListener({
98
- validateToken: (token) => this.validateToken(token),
99
- validateDisclosure: (token, disclosure) => this.validateDisclosure(token, disclosure),
100
- provisionStrand: (token, initiatorPartyId, disclosure) =>
101
- this.provisionAsResponder(token, initiatorPartyId, disclosure),
102
- getResponderIdentity: () => ({ partyId: this.partyId, cadrePeerAddrs: this.cadrePeerAddrs }),
103
- sessionTimeoutMs: this.config.sessionTimeoutMs,
104
- stepTimeoutMs: this.config.stepTimeoutMs,
105
- maxConcurrentSessions: this.config.maxConcurrentSessions
106
- });
107
-
108
- log('StrandFormationManager created for party: %s', this.partyId);
109
- }
110
-
111
- /**
112
- * Register this manager as a protocol handler on a libp2p node.
113
- * Call this on the control network node to handle incoming formation requests.
114
- */
115
- registerResponder(node: Libp2p, protocolId?: string): void {
116
- if (this.registeredNodes.has(node)) {
117
- log('Node already registered');
118
- return;
119
- }
120
- this.listener.register(node, protocolId ?? this.config.protocolId);
121
- this.registeredNodes.add(node);
122
- log('Registered as responder on node');
123
- }
124
-
125
- /**
126
- * Unregister the protocol handler from a libp2p node.
127
- */
128
- unregisterResponder(node: Libp2p, protocolId?: string): void {
129
- if (!this.registeredNodes.has(node)) {
130
- return;
131
- }
132
- this.listener.unregister(node, protocolId ?? this.config.protocolId);
133
- this.registeredNodes.delete(node);
134
- log('Unregistered from node');
135
- }
136
-
137
- /**
138
- * Form a strand with a responder via an open invitation (initiator side).
139
- *
140
- * Builds a contact message carrying the real token + disclosure + this party's
141
- * real cadre addresses, dials the responder over the native protocol, and
142
- * validates the responder's result before returning.
143
- */
144
- async formStrand(
145
- invitation: OpenInvitation,
146
- disclosure: StrandFormationDisclosure,
147
- node: Libp2p
148
- ): Promise<FormStrandResult> {
149
- log('Forming strand with invitation token: %s', invitation.token);
150
-
151
- const contact: FormationContactMessage = {
152
- token: invitation.token,
153
- partyId: disclosure.partyId ?? this.partyId,
154
- disclosure,
155
- cadrePeerAddrs: this.cadrePeerAddrs
156
- };
157
-
158
- this.dialerSessions++;
159
- try {
160
- const provision = await dialFormation(node, {
161
- contact,
162
- responderAddrs: invitation.bootstrap,
163
- validateResponse: (response) => this.validateResponse(invitation, disclosure, response),
164
- sessionTimeoutMs: this.config.sessionTimeoutMs,
165
- stepTimeoutMs: this.config.stepTimeoutMs,
166
- protocolId: this.config.protocolId
167
- });
168
-
169
- log('Strand formed: %s', provision.strand.strandId);
170
-
171
- return {
172
- memberKey: contact.partyId,
173
- invitePrivateKey: '',
174
- strandId: provision.strand.strandId,
175
- // The host strand's membership key, delivered through the protocol (provision-then-record).
176
- // Undefined for an open strand. Kept separate from invitePrivateKey (the initiator's
177
- // generated signing key), which is set by the StrandSolicitationService layer.
178
- memberPrivateKey: provision.memberPrivateKey
179
- };
180
- } finally {
181
- this.dialerSessions--;
182
- }
183
- }
184
-
185
- /**
186
- * Get the number of active sessions
187
- */
188
- getActiveSessionCounts(): { listeners: number; dialers: number } {
189
- return { listeners: this.listener.activeCount, dialers: this.dialerSessions };
190
- }
191
-
192
- // ── Responder-side hooks ─────────────────────────────────────────────────────
193
-
194
- private async validateToken(token: string): Promise<{ valid: boolean }> {
195
- if (!this.formationUsageRecorder) {
196
- // No recorder configured — accept all tokens.
197
- return { valid: true };
198
- }
199
-
200
- const tokenCheck = await this.formationUsageRecorder.isTokenValid(token);
201
- if (!tokenCheck.valid) {
202
- log('Token invalid: %s', token);
203
- return { valid: false };
204
- }
205
-
206
- if (await this.formationUsageRecorder.isTokenUsed(token)) {
207
- log('Token already used: %s', token);
208
- return { valid: false };
209
- }
210
-
211
- return { valid: true };
212
- }
213
-
214
- private async validateDisclosure(token: string, disclosure: StrandFormationDisclosure): Promise<boolean> {
215
- if (!this.disclosureValidator) {
216
- // No validator configured — accept all disclosures.
217
- return true;
218
- }
219
- return this.disclosureValidator.validateDisclosure(token, disclosure);
220
- }
221
-
222
- /**
223
- * Responder-side provisioning. Routes on how the invite resolves
224
- * ({@link ResolvedHostStrand}), and can REJECT post-validation by returning a
225
- * {@link ResponderProvisionOutcome} with `approved: false` — `runSession` turns that
226
- * into a clean, non-disclosing reply instead of a dropped result frame.
227
- *
228
- * - **bound** (host strand present): provision-then-record — write the single
229
- * `FormationUsage` consent row against the pre-existing strand (record-only) and
230
- * return it + its membership key (a read-gating secret disclosed only here, behind the
231
- * token + disclosure validation `runSession` already enforced).
232
- * - **missing** (invite names a host strand absent on this responder, e.g. unconverged):
233
- * reject cleanly + retryably, writing NO usage row — recording usage here would fail the
234
- * deferred `StrandExists` CHECK at commit and drop the frame.
235
- * - **unbound** (no binding): the responder-provisions fallback — see {@link provisionUnbound}.
236
- *
237
- * Defense-in-depth: known provisioning/redeem failures (notably the concurrent
238
- * `(Token, UseNumber)` PK collision when two redemptions of one unbound single-use invite
239
- * race) are caught and mapped to a logged, retry-suggesting rejection rather than a thrown
240
- * insert + a silently-closed stream. The LOG-before-reject keeps this a deliberate
241
- * internal-error→protocol-rejection conversion (AGENTS.md: don't eat exceptions silently),
242
- * not control-flow-by-exception.
243
- */
244
- private async provisionAsResponder(
245
- token: string,
246
- initiatorPartyId: string,
247
- _disclosure: StrandFormationDisclosure
248
- ): Promise<ResponderProvisionOutcome> {
249
- const recorder = this.formationUsageRecorder;
250
- const resolved: ResolvedHostStrand = recorder?.resolveStrand
251
- ? await recorder.resolveStrand(token)
252
- : { kind: 'unbound' };
253
-
254
- try {
255
- switch (resolved.kind) {
256
- case 'bound': {
257
- // recorder is guaranteed non-null here: only resolveStrand can yield 'bound'.
258
- await recorder!.recordUsage(token, initiatorPartyId, resolved.strandId);
259
- return this.approve({
260
- strand: { strandId: resolved.strandId, createdBy: 'responder' },
261
- memberPrivateKey: resolved.memberPrivateKey ?? undefined,
262
- dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
263
- });
264
- }
265
- case 'missing': {
266
- log('Host strand %s not yet available on this responder; rejecting token %s', resolved.strandId, token);
267
- return { approved: false, reason: 'Host strand not yet available on this responder' };
268
- }
269
- case 'unbound':
270
- return await this.provisionUnbound(token, initiatorPartyId);
271
- }
272
- } catch (err) {
273
- log('provisionAsResponder failed for token %s: %o', token, err);
274
- return { approved: false, reason: 'Formation conflict, retry' };
275
- }
276
- }
277
-
278
- /**
279
- * Responder-provisions fallback (invite binds no host strand). Precedence:
280
- *
281
- * 1. `recorder.provisionAndRecord` present (a real DB recorder) → atomic create-strand +
282
- * record-consent, so the unbound redemption is single-use just like the bound path.
283
- * Returns the new strand (+ key, null for an open responder-provisioned strand).
284
- * 2. else `strandProvisioner` present → the legacy/mock contract: provision a bare strand,
285
- * NO inline usage write (those callers record usage explicitly via
286
- * `recordFormationComplete`, or assert transport invariants only). Threads the invite's
287
- * REAL `sAppId`.
288
- * 3. else → a structural placeholder (no recorder + no provisioner ⇒ no single-use semantics
289
- * exist to enforce).
290
- *
291
- * Plan tradeoff — option (a) "record usage on the fallback" over (b) "remove the fallback":
292
- * (a) closes the single-use hole with a targeted atomic create+record and leaves the
293
- * `StrandProvisioner` mock-transport tests untouched; (b) would delete the provisioner
294
- * surface and churn ~6 unit + ~6 integration sites for ZERO production benefit (production
295
- * — `cadre-web.ts` / `cadre-phone.ts` — always publishes strand-BOUND invites and treats
296
- * the responder-provisions placeholder as failure). The broader "should this fallback exist
297
- * at all?" question lives in backlog `formation-initiatorcreates-cover-or-remove`.
298
- */
299
- private async provisionUnbound(
300
- token: string,
301
- initiatorPartyId: string
302
- ): Promise<ResponderProvisionOutcome> {
303
- const recorder = this.formationUsageRecorder;
304
- if (recorder?.provisionAndRecord) {
305
- const sAppId = await this.resolveInviteSAppId(token);
306
- const provisioned = await recorder.provisionAndRecord(token, initiatorPartyId, sAppId);
307
- return this.approve({
308
- strand: { strandId: provisioned.strandId, createdBy: 'responder' },
309
- memberPrivateKey: provisioned.memberPrivateKey ?? undefined,
310
- dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
311
- });
312
- }
313
-
314
- if (this.strandProvisioner) {
315
- const sAppId = await this.resolveInviteSAppId(token);
316
- const result = await this.strandProvisioner.provisionStrand(sAppId, initiatorPartyId, this.partyId);
317
- return this.approve({
318
- strand: { strandId: result.strandId, createdBy: 'responder' },
319
- dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
320
- });
321
- }
322
-
323
- // No recorder + no provisioner — a structural placeholder the initiator can still validate.
324
- const strandId = `strand-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
325
- return this.approve({
326
- strand: { strandId, createdBy: 'responder' },
327
- dbConnectionInfo: { endpoint: 'local', credentialsRef: '' }
328
- });
329
- }
330
-
331
- /** Wrap a provision result as an approving {@link ResponderProvisionOutcome}. */
332
- private approve(result: FormationProvisionResult): ResponderProvisionOutcome {
333
- return { approved: true, result };
334
- }
335
-
336
- /**
337
- * The invite's authoritative `sAppId` for the responder-provisions fallback, read back
338
- * from the recorder's `isTokenValid` invitation (the real `FormationInvite.sAppId`).
339
- * Empty string when no recorder is wired or the invitation omits it.
340
- */
341
- private async resolveInviteSAppId(token: string): Promise<string> {
342
- if (!this.formationUsageRecorder) return '';
343
- const check = await this.formationUsageRecorder.isTokenValid(token);
344
- return check.invitation?.sAppId ?? '';
345
- }
346
-
347
- // ── Initiator-side result validation ─────────────────────────────────────────
348
-
349
- private async validateResponse(
350
- invitation: OpenInvitation,
351
- disclosure: StrandFormationDisclosure,
352
- response: FormationResultMessage
353
- ): Promise<boolean> {
354
- if (this.formationResponseValidator) {
355
- return this.formationResponseValidator.validateResponse({ invitation, disclosure, response });
356
- }
357
- return isValidResponderCreatesResult(response);
358
- }
359
- }
360
-
361
- /**
362
- * Create a StrandFormationManager with the given options
363
- */
364
- export function createStrandFormationManager(
365
- options: StrandFormationManagerOptions
366
- ): StrandFormationManager {
367
- return new StrandFormationManager(options);
368
- }
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
+ }