@serfab/cadre-core 1.2.0 → 1.4.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.
- package/README.md +5 -3
- package/dist/cadre-node.d.ts +32 -19
- package/dist/cadre-node.js +121 -31
- package/dist/cadre-node.js.map +1 -1
- package/dist/control-formation-recorder.d.ts +4 -4
- package/dist/control-formation-recorder.js +6 -6
- package/dist/control-formation-recorder.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +5 -3
- package/dist/index.js.map +1 -1
- package/dist/membership-connection-gater.d.ts +18 -5
- package/dist/membership-connection-gater.js +50 -10
- package/dist/membership-connection-gater.js.map +1 -1
- package/dist/storage-scope.d.ts +50 -12
- package/dist/storage-scope.js +85 -12
- package/dist/storage-scope.js.map +1 -1
- package/dist/strand-formation-manager.js +2 -1
- package/dist/strand-formation-manager.js.map +1 -1
- package/dist/strand-id.d.ts +35 -0
- package/dist/strand-id.js +46 -0
- package/dist/strand-id.js.map +1 -0
- package/dist/strand-instance-manager.js +20 -2
- package/dist/strand-instance-manager.js.map +1 -1
- package/dist/strand-network-config.d.ts +3 -3
- package/dist/strand-network-config.js +3 -3
- package/dist/strand-solicitation.js +2 -1
- package/dist/strand-solicitation.js.map +1 -1
- package/dist/strand-watcher.d.ts +45 -0
- package/dist/strand-watcher.js +74 -13
- package/dist/strand-watcher.js.map +1 -1
- package/dist/types.d.ts +118 -15
- package/dist/types.js +59 -0
- package/dist/types.js.map +1 -1
- package/package.json +7 -7
- package/src/cadre-node.ts +127 -31
- package/src/control-formation-recorder.ts +6 -6
- package/src/index.ts +563 -554
- package/src/membership-connection-gater.ts +56 -11
- package/src/storage-scope.ts +163 -78
- package/src/strand-formation-manager.ts +647 -646
- package/src/strand-id.ts +48 -0
- package/src/strand-instance-manager.ts +21 -2
- package/src/strand-network-config.ts +250 -250
- package/src/strand-solicitation.ts +500 -499
- package/src/strand-watcher.ts +388 -325
- package/src/types.ts +121 -15
|
@@ -1,646 +1,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 {
|
|
18
|
-
import
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
type
|
|
34
|
-
type
|
|
35
|
-
type
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
*
|
|
138
|
-
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
*
|
|
149
|
-
*
|
|
150
|
-
*
|
|
151
|
-
* `
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
*
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
*
|
|
179
|
-
*
|
|
180
|
-
*
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
private readonly
|
|
187
|
-
private readonly
|
|
188
|
-
private readonly
|
|
189
|
-
private readonly
|
|
190
|
-
private readonly
|
|
191
|
-
private readonly
|
|
192
|
-
private readonly
|
|
193
|
-
private readonly
|
|
194
|
-
private readonly
|
|
195
|
-
private readonly
|
|
196
|
-
private
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
this.
|
|
201
|
-
this.
|
|
202
|
-
this.
|
|
203
|
-
this.
|
|
204
|
-
this.
|
|
205
|
-
this.
|
|
206
|
-
this.
|
|
207
|
-
this.
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
//
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
*
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
this.
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
this.
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
*
|
|
256
|
-
*
|
|
257
|
-
*
|
|
258
|
-
*
|
|
259
|
-
*
|
|
260
|
-
*
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
//
|
|
301
|
-
//
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
//
|
|
305
|
-
// check
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
*
|
|
325
|
-
*
|
|
326
|
-
*
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
*
|
|
342
|
-
*
|
|
343
|
-
*
|
|
344
|
-
*
|
|
345
|
-
*
|
|
346
|
-
* the
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
*
|
|
386
|
-
* {@link
|
|
387
|
-
*
|
|
388
|
-
*
|
|
389
|
-
*
|
|
390
|
-
*
|
|
391
|
-
*
|
|
392
|
-
*
|
|
393
|
-
*
|
|
394
|
-
*
|
|
395
|
-
*
|
|
396
|
-
*
|
|
397
|
-
*
|
|
398
|
-
*
|
|
399
|
-
*
|
|
400
|
-
*
|
|
401
|
-
*
|
|
402
|
-
*
|
|
403
|
-
*
|
|
404
|
-
*
|
|
405
|
-
*
|
|
406
|
-
*
|
|
407
|
-
*
|
|
408
|
-
*
|
|
409
|
-
*
|
|
410
|
-
* key
|
|
411
|
-
*
|
|
412
|
-
*
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
//
|
|
421
|
-
//
|
|
422
|
-
//
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
const
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
// the
|
|
439
|
-
//
|
|
440
|
-
//
|
|
441
|
-
//
|
|
442
|
-
//
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
//
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
//
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
//
|
|
486
|
-
//
|
|
487
|
-
//
|
|
488
|
-
//
|
|
489
|
-
//
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
err.
|
|
494
|
-
err.
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
//
|
|
500
|
-
//
|
|
501
|
-
//
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
*
|
|
510
|
-
*
|
|
511
|
-
*
|
|
512
|
-
*
|
|
513
|
-
*
|
|
514
|
-
* - Hook returns
|
|
515
|
-
* - Hook
|
|
516
|
-
*
|
|
517
|
-
*
|
|
518
|
-
*
|
|
519
|
-
*
|
|
520
|
-
*
|
|
521
|
-
*
|
|
522
|
-
*
|
|
523
|
-
*
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
*
|
|
548
|
-
*
|
|
549
|
-
*
|
|
550
|
-
*
|
|
551
|
-
*
|
|
552
|
-
*
|
|
553
|
-
*
|
|
554
|
-
*
|
|
555
|
-
*
|
|
556
|
-
*
|
|
557
|
-
*
|
|
558
|
-
*
|
|
559
|
-
*
|
|
560
|
-
*
|
|
561
|
-
*
|
|
562
|
-
*
|
|
563
|
-
*
|
|
564
|
-
*
|
|
565
|
-
*
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
const
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
const
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
const
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
*
|
|
617
|
-
*
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
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
|
+
}
|