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