@serfab/cadre-core 0.7.1 → 0.9.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 +11 -10
- package/dist/cadre-node.d.ts +818 -19
- package/dist/cadre-node.js +1952 -99
- package/dist/cadre-node.js.map +1 -1
- package/dist/canonical-datetime.d.ts +33 -0
- package/dist/canonical-datetime.js +38 -0
- package/dist/canonical-datetime.js.map +1 -0
- package/dist/canonical-json.d.ts +12 -0
- package/dist/canonical-json.js +33 -0
- package/dist/canonical-json.js.map +1 -0
- package/dist/control-cohort.d.ts +63 -0
- package/dist/control-cohort.js +80 -0
- package/dist/control-cohort.js.map +1 -0
- package/dist/control-database.d.ts +279 -8
- package/dist/control-database.js +563 -134
- package/dist/control-database.js.map +1 -1
- package/dist/control-formation-recorder.d.ts +89 -0
- package/dist/control-formation-recorder.js +139 -0
- package/dist/control-formation-recorder.js.map +1 -0
- package/dist/control-schema.d.ts +12 -0
- package/dist/control-schema.js +223 -0
- package/dist/control-schema.js.map +1 -0
- package/dist/control-stream.d.ts +54 -0
- package/dist/control-stream.js +104 -0
- package/dist/control-stream.js.map +1 -0
- package/dist/device-token.d.ts +50 -0
- package/dist/device-token.js +66 -0
- package/dist/device-token.js.map +1 -0
- package/dist/diagnostics/connection-path.d.ts +118 -0
- package/dist/diagnostics/connection-path.js +204 -0
- package/dist/diagnostics/connection-path.js.map +1 -0
- package/dist/diagnostics/webrtc-turn-tracker.d.ts +50 -0
- package/dist/diagnostics/webrtc-turn-tracker.js +196 -0
- package/dist/diagnostics/webrtc-turn-tracker.js.map +1 -0
- package/dist/ed25519-key.d.ts +42 -0
- package/dist/ed25519-key.js +51 -0
- package/dist/ed25519-key.js.map +1 -0
- package/dist/hibernation-manager.d.ts +79 -0
- package/dist/hibernation-manager.js +173 -23
- package/dist/hibernation-manager.js.map +1 -1
- package/dist/index.d.ts +25 -4
- package/dist/index.js +59 -4
- package/dist/index.js.map +1 -1
- package/dist/key-store-file.d.ts +52 -0
- package/dist/key-store-file.js +194 -0
- package/dist/key-store-file.js.map +1 -0
- package/dist/key-store.d.ts +75 -0
- package/dist/key-store.js +66 -0
- package/dist/key-store.js.map +1 -0
- package/dist/peer-authorization.d.ts +48 -0
- package/dist/peer-authorization.js +66 -0
- package/dist/peer-authorization.js.map +1 -0
- package/dist/peer-record.d.ts +89 -0
- package/dist/peer-record.js +117 -0
- package/dist/peer-record.js.map +1 -0
- package/dist/push-credentials.d.ts +34 -0
- package/dist/push-credentials.js +81 -0
- package/dist/push-credentials.js.map +1 -0
- package/dist/push-fanout.d.ts +137 -0
- package/dist/push-fanout.js +197 -0
- package/dist/push-fanout.js.map +1 -0
- package/dist/push-node.d.ts +38 -0
- package/dist/push-node.js +48 -0
- package/dist/push-node.js.map +1 -0
- package/dist/push-notifier-apns.d.ts +61 -0
- package/dist/push-notifier-apns.js +199 -0
- package/dist/push-notifier-apns.js.map +1 -0
- package/dist/push-notifier-fcm.d.ts +44 -0
- package/dist/push-notifier-fcm.js +182 -0
- package/dist/push-notifier-fcm.js.map +1 -0
- package/dist/push-notifier-shared.d.ts +18 -0
- package/dist/push-notifier-shared.js +25 -0
- package/dist/push-notifier-shared.js.map +1 -0
- package/dist/push-notifier.d.ts +52 -0
- package/dist/push-notifier.js +22 -0
- package/dist/push-notifier.js.map +1 -0
- package/dist/schema-verification.d.ts +11 -2
- package/dist/schema-verification.js +15 -4
- package/dist/schema-verification.js.map +1 -1
- package/dist/seed-bootstrap.d.ts +228 -21
- package/dist/seed-bootstrap.js +489 -168
- package/dist/seed-bootstrap.js.map +1 -1
- package/dist/seed-trust-policy.d.ts +63 -0
- package/dist/seed-trust-policy.js +56 -0
- package/dist/seed-trust-policy.js.map +1 -0
- package/dist/strand-addr-protocol.d.ts +132 -0
- package/dist/strand-addr-protocol.js +313 -0
- package/dist/strand-addr-protocol.js.map +1 -0
- package/dist/strand-cohort.d.ts +54 -0
- package/dist/strand-cohort.js +38 -0
- package/dist/strand-cohort.js.map +1 -0
- package/dist/strand-database.d.ts +54 -6
- package/dist/strand-database.js +88 -100
- package/dist/strand-database.js.map +1 -1
- package/dist/strand-formation-manager.d.ts +79 -19
- package/dist/strand-formation-manager.js +196 -104
- package/dist/strand-formation-manager.js.map +1 -1
- package/dist/strand-formation-protocol.d.ts +162 -0
- package/dist/strand-formation-protocol.js +279 -0
- package/dist/strand-formation-protocol.js.map +1 -0
- package/dist/strand-instance-manager.d.ts +73 -4
- package/dist/strand-instance-manager.js +167 -41
- package/dist/strand-instance-manager.js.map +1 -1
- package/dist/strand-member-key.d.ts +29 -0
- package/dist/strand-member-key.js +38 -0
- package/dist/strand-member-key.js.map +1 -0
- package/dist/strand-member-registry.d.ts +98 -0
- package/dist/strand-member-registry.js +129 -0
- package/dist/strand-member-registry.js.map +1 -0
- package/dist/strand-membership-writer.d.ts +361 -0
- package/dist/strand-membership-writer.js +449 -0
- package/dist/strand-membership-writer.js.map +1 -0
- package/dist/strand-solicitation.d.ts +77 -2
- package/dist/strand-solicitation.js +25 -4
- package/dist/strand-solicitation.js.map +1 -1
- package/dist/strand-wake-payload.d.ts +30 -0
- package/dist/strand-wake-payload.js +20 -0
- package/dist/strand-wake-payload.js.map +1 -0
- package/dist/strand-wake-protocol.d.ts +114 -0
- package/dist/strand-wake-protocol.js +257 -0
- package/dist/strand-wake-protocol.js.map +1 -0
- package/dist/strand-watcher.d.ts +6 -2
- package/dist/strand-watcher.js +57 -17
- package/dist/strand-watcher.js.map +1 -1
- package/dist/types.d.ts +436 -33
- package/dist/types.js +22 -5
- package/dist/types.js.map +1 -1
- package/package.json +18 -8
- package/src/cadre-node.ts +2981 -948
- package/src/canonical-datetime.ts +39 -0
- package/src/canonical-json.ts +30 -0
- package/src/control-cohort.ts +103 -0
- package/src/control-database.ts +948 -383
- package/src/control-formation-recorder.ts +151 -0
- package/src/control-schema.ts +222 -0
- package/src/control-stream.ts +128 -0
- package/src/device-token.ts +89 -0
- package/src/diagnostics/connection-path.ts +277 -0
- package/src/diagnostics/webrtc-turn-tracker.ts +222 -0
- package/src/ed25519-key.ts +69 -0
- package/src/hibernation-manager.ts +197 -28
- package/src/index.ts +275 -79
- package/src/key-store-file.ts +203 -0
- package/src/key-store.ts +99 -0
- package/src/peer-authorization.ts +81 -0
- package/src/peer-record.ts +146 -0
- package/src/push-credentials.ts +84 -0
- package/src/push-fanout.ts +272 -0
- package/src/push-node.ts +64 -0
- package/src/push-notifier-apns.ts +247 -0
- package/src/push-notifier-fcm.ts +220 -0
- package/src/push-notifier-shared.ts +28 -0
- package/src/push-notifier.ts +52 -0
- package/src/schema-verification.ts +18 -4
- package/src/seed-bootstrap.ts +563 -223
- package/src/seed-trust-policy.ts +107 -0
- package/src/strand-addr-protocol.ts +410 -0
- package/src/strand-cohort.ts +77 -0
- package/src/strand-database.ts +113 -141
- package/src/strand-formation-manager.ts +233 -142
- package/src/strand-formation-protocol.ts +391 -0
- package/src/strand-instance-manager.ts +207 -56
- package/src/strand-member-key.ts +39 -0
- package/src/strand-member-registry.ts +177 -0
- package/src/strand-membership-writer.ts +640 -0
- package/src/strand-solicitation.ts +93 -4
- package/src/strand-wake-payload.ts +32 -0
- package/src/strand-wake-protocol.ts +331 -0
- package/src/strand-watcher.ts +61 -17
- package/src/types.ts +1032 -582
package/src/control-database.ts
CHANGED
|
@@ -1,383 +1,948 @@
|
|
|
1
|
-
import debug from 'debug';
|
|
2
|
-
import { toString as uint8ArrayToString } from 'uint8arrays';
|
|
3
|
-
import { Database, registerPlugin } from '@quereus/quereus';
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
import
|
|
8
|
-
import type {
|
|
9
|
-
import type {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
this.
|
|
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
|
-
this.
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
1
|
+
import debug from 'debug';
|
|
2
|
+
import { toString as uint8ArrayToString } from 'uint8arrays';
|
|
3
|
+
import { Database, registerPlugin } from '@quereus/quereus';
|
|
4
|
+
import type { VTablePluginInfo, FunctionPluginInfo } from '@quereus/quereus';
|
|
5
|
+
import cryptoPlugin from '@optimystic/quereus-plugin-crypto/plugin';
|
|
6
|
+
import optimysticPlugin from '@optimystic/quereus-plugin-optimystic/plugin';
|
|
7
|
+
import { digest, randomBytes } from '@optimystic/quereus-plugin-crypto';
|
|
8
|
+
import type { Libp2p } from '@libp2p/interface';
|
|
9
|
+
import type { IRepo } from '@optimystic/db-core';
|
|
10
|
+
import type { StrandRow, PeerAddressRecord, DeviceTokenRecord, PushPlatform } from './types.js';
|
|
11
|
+
import { CONTROL_SCHEMA } from './control-schema.js';
|
|
12
|
+
import { canonicalDatetime } from './canonical-datetime.js';
|
|
13
|
+
|
|
14
|
+
const log = debug('sereus:cadre:control-db');
|
|
15
|
+
const timing = debug('sereus:cadre:timing');
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Generate a unique stamp ID for transaction authorization.
|
|
19
|
+
* Format: 32 bytes base64url encoded
|
|
20
|
+
* - First 16 bytes: SHA-256 hash of peer ID (for distributed uniqueness)
|
|
21
|
+
* - Last 16 bytes: Random bytes (for collision resistance)
|
|
22
|
+
*/
|
|
23
|
+
export function generateStampId(peerId: string): string {
|
|
24
|
+
// Hash the peer ID and get first 16 bytes (128 bits). A purely local ID
|
|
25
|
+
// generator: never signed/verified against SQL, so the framed single-field
|
|
26
|
+
// digest is fine (the changed framing is not cross-checked anywhere).
|
|
27
|
+
const peerIdHash = digest([peerId], 'sha256', 'bytes') as Uint8Array;
|
|
28
|
+
const peerIdHashPart = peerIdHash.slice(0, 16);
|
|
29
|
+
|
|
30
|
+
// Generate 16 random bytes
|
|
31
|
+
const randomPart = randomBytes(128, 'bytes') as Uint8Array;
|
|
32
|
+
|
|
33
|
+
// Combine peer ID hash and random bytes
|
|
34
|
+
const combined = new Uint8Array(32);
|
|
35
|
+
combined.set(peerIdHashPart, 0);
|
|
36
|
+
combined.set(randomPart, 16);
|
|
37
|
+
|
|
38
|
+
// Convert to base64url
|
|
39
|
+
return uint8ArrayToString(combined, 'base64url');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Parse a stored Quereus `datetime` value into epoch milliseconds.
|
|
44
|
+
*
|
|
45
|
+
* Quereus canonicalises a `datetime` column to a bare UTC `PlainDateTime` string
|
|
46
|
+
* (e.g. `2026-06-04T12:34:56`, no `Z`). JS `Date` reads a timezone-less
|
|
47
|
+
* date-time as LOCAL, so we append `Z` when no offset/zone is present to keep the
|
|
48
|
+
* value anchored to UTC. Numbers (already epoch ms) pass through.
|
|
49
|
+
*/
|
|
50
|
+
function parseStoredDatetimeMs(value: string | number): number {
|
|
51
|
+
if (typeof value === 'number') return value;
|
|
52
|
+
const hasZone = /[zZ]$|[+-]\d\d:?\d\d$/.test(value);
|
|
53
|
+
return new Date(hasZone ? value : `${value}Z`).getTime();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Build the canonical authorization message that owner signatures are bound to.
|
|
58
|
+
*
|
|
59
|
+
* The message is a SINGLE framed SHA-256 digest over the ordered tuple of fields (the
|
|
60
|
+
* crypto plugin's injective multi-field encoding), in a fixed field order, with the
|
|
61
|
+
* single-use StampId as the final field:
|
|
62
|
+
*
|
|
63
|
+
* message = sha256(encodeFields([field_1, field_2, ..., StampId])) // raw digest bytes
|
|
64
|
+
*
|
|
65
|
+
* ed25519 signs these raw digest bytes DIRECTLY (no second hash). The SQL constraints
|
|
66
|
+
* verify the identical bytes with one variadic call
|
|
67
|
+
* (`verify(digest(field_1, ..., StampId), context.Signature, A.Key, 'ed25519')`): SQL
|
|
68
|
+
* `digest(...)` returns the base64url string of the same digest, which `verify`'s default
|
|
69
|
+
* base64url input encoding decodes back to those raw bytes — so signer and verifier
|
|
70
|
+
* operate on the same bytes. Every field is TEXT on both sides (the SQL columns are
|
|
71
|
+
* `cast(... as text)` / `coalesce(...,'')`; the TS args are strings), so the per-field
|
|
72
|
+
* type tags agree. This binds the signature to the row contents (not a bare stamp),
|
|
73
|
+
* closing the captured-stamp replay / privilege-escalation hole. Single source of truth:
|
|
74
|
+
* every signed writer (and every test/harness signer) MUST build the message through this
|
|
75
|
+
* function in the schema's field order, or `verify` will reject the row.
|
|
76
|
+
*/
|
|
77
|
+
export function buildAuthorizationMessage(fields: string[]): Uint8Array {
|
|
78
|
+
return digest([...fields], 'sha256', 'bytes') as Uint8Array;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Minimal interface for the CollectionFactory returned by the optimystic plugin.
|
|
83
|
+
* We only need the methods we actually use.
|
|
84
|
+
*/
|
|
85
|
+
interface CollectionFactory {
|
|
86
|
+
registerLibp2pNode(networkName: string, node: Libp2p, coordinatedRepo: IRepo): void;
|
|
87
|
+
shutdown(): Promise<void>;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Result of registering the optimystic plugin */
|
|
91
|
+
interface OptimysticPluginResult {
|
|
92
|
+
collectionFactory: CollectionFactory;
|
|
93
|
+
vtables: VTablePluginInfo[];
|
|
94
|
+
functions: FunctionPluginInfo[];
|
|
95
|
+
/**
|
|
96
|
+
* Hydrate Quereus's in-memory catalog from persisted optimystic vtab schemas.
|
|
97
|
+
* Must run BEFORE applying CONTROL_SCHEMA on a warm restart so the declarative
|
|
98
|
+
* diff sees the existing tables and skips re-emitting CREATE TABLE / CREATE INDEX
|
|
99
|
+
* for each persisted control object. Idempotent; `{ tables: 0, indexes: 0 }` on a
|
|
100
|
+
* cold/in-memory start. Mirrors the strand path's hydrate-before-apply (see
|
|
101
|
+
* compose-strand.ts).
|
|
102
|
+
*/
|
|
103
|
+
hydrate: (db: Database) => Promise<{ tables: number; indexes: number }>;
|
|
104
|
+
[key: string]: unknown;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Names of the CadreControl tables that {@link ControlDatabase.countRows} can
|
|
109
|
+
* read. Constraining to this union keeps the dynamic `from` clause off the
|
|
110
|
+
* SQL-injection surface and hands callers (e.g. the integration harness's
|
|
111
|
+
* `waitForControlSync`) a typo-proof table argument.
|
|
112
|
+
*/
|
|
113
|
+
export type ControlTable =
|
|
114
|
+
| 'OwnerKey'
|
|
115
|
+
| 'ValidationKey'
|
|
116
|
+
| 'Strand'
|
|
117
|
+
| 'CadrePeer'
|
|
118
|
+
| 'DeviceToken'
|
|
119
|
+
| 'FormationInvite'
|
|
120
|
+
| 'FormationUsage';
|
|
121
|
+
|
|
122
|
+
/** Runtime guard mirroring {@link ControlTable} for the dynamic-`from` count. */
|
|
123
|
+
const CONTROL_TABLES: ReadonlySet<ControlTable> = new Set<ControlTable>([
|
|
124
|
+
'OwnerKey',
|
|
125
|
+
'ValidationKey',
|
|
126
|
+
'Strand',
|
|
127
|
+
'CadrePeer',
|
|
128
|
+
'DeviceToken',
|
|
129
|
+
'FormationInvite',
|
|
130
|
+
'FormationUsage',
|
|
131
|
+
]);
|
|
132
|
+
|
|
133
|
+
export interface ControlDatabaseConfig {
|
|
134
|
+
/** Party ID for the control network */
|
|
135
|
+
partyId: string;
|
|
136
|
+
/**
|
|
137
|
+
* Optional path to the control schema file.
|
|
138
|
+
* If not provided, uses the embedded schema for cross-platform compatibility.
|
|
139
|
+
* Only use this if you need to override the default schema (e.g., for testing).
|
|
140
|
+
*/
|
|
141
|
+
schemaPath?: string;
|
|
142
|
+
/** Libp2p node for the control network (injected) */
|
|
143
|
+
libp2pNode: Libp2p;
|
|
144
|
+
/** Coordinated repo from the libp2p node */
|
|
145
|
+
coordinatedRepo: IRepo;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* ControlDatabase manages the CadreControl schema using Quereus with Optimystic backend.
|
|
150
|
+
* It provides typed query methods for accessing control network data.
|
|
151
|
+
*/
|
|
152
|
+
export class ControlDatabase {
|
|
153
|
+
private db: Database | null = null;
|
|
154
|
+
private collectionFactory: CollectionFactory | null = null;
|
|
155
|
+
private readonly config: ControlDatabaseConfig;
|
|
156
|
+
private initialized = false;
|
|
157
|
+
|
|
158
|
+
constructor(config: ControlDatabaseConfig) {
|
|
159
|
+
this.config = config;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Initialize the database - load schema and register plugins
|
|
164
|
+
*/
|
|
165
|
+
async initialize(): Promise<void> {
|
|
166
|
+
if (this.initialized) {
|
|
167
|
+
log('ControlDatabase already initialized');
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
log('Initializing ControlDatabase for party: %s', this.config.partyId);
|
|
172
|
+
|
|
173
|
+
// Create database instance
|
|
174
|
+
this.db = new Database();
|
|
175
|
+
|
|
176
|
+
// Register crypto plugin (provides digest, sign, verify functions)
|
|
177
|
+
let t0 = performance.now();
|
|
178
|
+
await registerPlugin(this.db, cryptoPlugin);
|
|
179
|
+
timing('[controlDb] cryptoPlugin: %dms', Math.round(performance.now() - t0));
|
|
180
|
+
log('Registered crypto plugin');
|
|
181
|
+
|
|
182
|
+
// Register optimystic plugin with network transactor as default
|
|
183
|
+
t0 = performance.now();
|
|
184
|
+
const networkName = `control-${this.config.partyId}`;
|
|
185
|
+
const pluginResult = optimysticPlugin(this.db, {
|
|
186
|
+
default_transactor: 'network',
|
|
187
|
+
default_key_network: 'libp2p',
|
|
188
|
+
default_network_name: networkName,
|
|
189
|
+
enable_cache: true,
|
|
190
|
+
}) as unknown as OptimysticPluginResult;
|
|
191
|
+
|
|
192
|
+
// Register vtables and functions manually since we need access to collectionFactory
|
|
193
|
+
for (const vtable of pluginResult.vtables) {
|
|
194
|
+
this.db.registerModule(vtable.name, vtable.module, vtable.auxData);
|
|
195
|
+
}
|
|
196
|
+
for (const func of pluginResult.functions) {
|
|
197
|
+
this.db.registerFunction(func.schema);
|
|
198
|
+
}
|
|
199
|
+
timing('[controlDb] optimysticPlugin: %dms', Math.round(performance.now() - t0));
|
|
200
|
+
|
|
201
|
+
this.collectionFactory = pluginResult.collectionFactory;
|
|
202
|
+
|
|
203
|
+
// Inject the libp2p node into the collection factory
|
|
204
|
+
t0 = performance.now();
|
|
205
|
+
this.collectionFactory.registerLibp2pNode(
|
|
206
|
+
networkName,
|
|
207
|
+
this.config.libp2pNode,
|
|
208
|
+
this.config.coordinatedRepo
|
|
209
|
+
);
|
|
210
|
+
timing('[controlDb] registerLibp2pNode: %dms', Math.round(performance.now() - t0));
|
|
211
|
+
log('Registered libp2p node with collection factory');
|
|
212
|
+
|
|
213
|
+
// Network-back the control tables. CONTROL_SCHEMA's `declare schema CadreControl
|
|
214
|
+
// { table ... }` tables carry NO per-table `using optimystic(...)`, so storage is
|
|
215
|
+
// chosen by the database's DEFAULT vtab. Routing the default to optimystic (with
|
|
216
|
+
// the network transactor + this party's control network) is what makes a control
|
|
217
|
+
// write replicate peer-to-peer — exactly what connectToStrand does for strand
|
|
218
|
+
// tables (compose-strand.ts). Without these two calls the tables fall back to
|
|
219
|
+
// Quereus's in-memory vtab and never converge across the cadre.
|
|
220
|
+
this.db.setDefaultVtabName('optimystic');
|
|
221
|
+
this.db.setDefaultVtabArgs({
|
|
222
|
+
networkName,
|
|
223
|
+
transactor: 'network',
|
|
224
|
+
keyNetwork: 'libp2p',
|
|
225
|
+
});
|
|
226
|
+
log('Set default vtab to optimystic (networkName=%s, transactor=network)', networkName);
|
|
227
|
+
|
|
228
|
+
// Hydrate Quereus's catalog from any persisted optimystic vtab schemas BEFORE
|
|
229
|
+
// applying CONTROL_SCHEMA, so a warm restart with persistent storage diffs the
|
|
230
|
+
// control DDL against the already-present tables and re-emits nothing — the same
|
|
231
|
+
// warm-start regression connectToStrand's hydrate-before-apply guards against.
|
|
232
|
+
// No-op on a cold / in-memory start (`{ tables: 0, indexes: 0 }`).
|
|
233
|
+
t0 = performance.now();
|
|
234
|
+
const hydrated = await pluginResult.hydrate(this.db);
|
|
235
|
+
timing('[controlDb] hydrate: %dms (tables=%d, indexes=%d)',
|
|
236
|
+
Math.round(performance.now() - t0), hydrated.tables, hydrated.indexes);
|
|
237
|
+
log('Hydrated control catalog (tables=%d, indexes=%d)', hydrated.tables, hydrated.indexes);
|
|
238
|
+
|
|
239
|
+
// Load and execute the schema
|
|
240
|
+
t0 = performance.now();
|
|
241
|
+
await this.loadSchema();
|
|
242
|
+
timing('[controlDb] loadSchema: %dms', Math.round(performance.now() - t0));
|
|
243
|
+
|
|
244
|
+
this.initialized = true;
|
|
245
|
+
log('ControlDatabase initialized successfully');
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
private async loadSchema(): Promise<void> {
|
|
249
|
+
let schemaContent: string;
|
|
250
|
+
|
|
251
|
+
if (this.config.schemaPath) {
|
|
252
|
+
// Load from file if explicitly provided (for testing or custom schemas)
|
|
253
|
+
// This only works in Node.js environments
|
|
254
|
+
log('Loading schema from file: %s', this.config.schemaPath);
|
|
255
|
+
|
|
256
|
+
// Check if we're in a Node.js environment
|
|
257
|
+
if (typeof process !== 'undefined' && process.versions?.node) {
|
|
258
|
+
try {
|
|
259
|
+
// Use require to conditionally load fs only in Node.js.
|
|
260
|
+
// This won't be bundled by React Native's Metro bundler — a dynamic
|
|
261
|
+
// import() would be statically picked up by Metro, so require is
|
|
262
|
+
// intentional here (cross-platform constraint, not lazy CommonJS).
|
|
263
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
264
|
+
const fs = require('fs/promises');
|
|
265
|
+
schemaContent = await fs.readFile(this.config.schemaPath, 'utf-8');
|
|
266
|
+
} catch (error) {
|
|
267
|
+
throw new Error(
|
|
268
|
+
`Failed to load schema from ${this.config.schemaPath}: ${error instanceof Error ? error.message : String(error)}`,
|
|
269
|
+
{ cause: error }
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
} else {
|
|
273
|
+
throw new Error(
|
|
274
|
+
'Loading schema from file is not supported in React Native. ' +
|
|
275
|
+
'Remove the schemaPath option to use the embedded schema instead.'
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
} else {
|
|
279
|
+
// Use embedded schema for cross-platform compatibility
|
|
280
|
+
log('Using embedded control schema');
|
|
281
|
+
schemaContent = CONTROL_SCHEMA;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
await this.db!.exec(schemaContent);
|
|
285
|
+
log('Schema loaded and executed');
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Query all strands from the control database
|
|
290
|
+
*/
|
|
291
|
+
async queryStrands(): Promise<StrandRow[]> {
|
|
292
|
+
this.ensureInitialized();
|
|
293
|
+
const results: StrandRow[] = [];
|
|
294
|
+
for await (const row of this.db!.eval('select Id, MemberPrivateKey, Type from CadreControl.Strand')) {
|
|
295
|
+
results.push({
|
|
296
|
+
Id: row.Id as string,
|
|
297
|
+
MemberPrivateKey: row.MemberPrivateKey as string | null,
|
|
298
|
+
Type: row.Type as 'o' | 'c',
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
return results;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Read a single strand row by id, or null when absent. Single-row sibling of
|
|
306
|
+
* {@link queryStrands}; the responder uses it to read a host strand's
|
|
307
|
+
* `MemberPrivateKey` (the closed-strand read-gating secret) for delivery to a
|
|
308
|
+
* validated invitee during provision-then-record formation.
|
|
309
|
+
*/
|
|
310
|
+
async queryStrand(strandId: string): Promise<StrandRow | null> {
|
|
311
|
+
this.ensureInitialized();
|
|
312
|
+
for await (const row of this.db!.eval(
|
|
313
|
+
'select Id, MemberPrivateKey, Type from CadreControl.Strand where Id = ?',
|
|
314
|
+
[strandId]
|
|
315
|
+
)) {
|
|
316
|
+
return {
|
|
317
|
+
Id: row.Id as string,
|
|
318
|
+
MemberPrivateKey: row.MemberPrivateKey as string | null,
|
|
319
|
+
Type: row.Type as 'o' | 'c',
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
return null;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Count rows in a CadreControl table as seen by THIS database instance.
|
|
327
|
+
*
|
|
328
|
+
* `table` is validated against {@link CONTROL_TABLES} before it is interpolated
|
|
329
|
+
* into the `from` clause: the names are not user input, but the check keeps the
|
|
330
|
+
* dynamic query off the injection surface and fails loudly on a typo instead of
|
|
331
|
+
* emitting a malformed statement. The count reflects only the rows this node's
|
|
332
|
+
* control DB has converged on — in the integration harness that is the owner
|
|
333
|
+
* node (one ControlDatabase per party), i.e. the authoritative control-network
|
|
334
|
+
* view, not a per-drone convergence guarantee.
|
|
335
|
+
*/
|
|
336
|
+
async countRows(table: ControlTable): Promise<number> {
|
|
337
|
+
this.ensureInitialized();
|
|
338
|
+
if (!CONTROL_TABLES.has(table)) {
|
|
339
|
+
throw new Error(`Unknown CadreControl table: ${table}`);
|
|
340
|
+
}
|
|
341
|
+
for await (const row of this.db!.eval(`select count(1) as Count from CadreControl.${table}`)) {
|
|
342
|
+
return (row.Count as number) ?? 0;
|
|
343
|
+
}
|
|
344
|
+
return 0;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Get the underlying database for advanced queries
|
|
349
|
+
*/
|
|
350
|
+
getDatabase(): Database {
|
|
351
|
+
this.ensureInitialized();
|
|
352
|
+
return this.db!;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Check whether any owner key exists in the control database.
|
|
357
|
+
* Used to decide whether a fresh-party genesis insert is required.
|
|
358
|
+
*/
|
|
359
|
+
async hasOwnerKey(): Promise<boolean> {
|
|
360
|
+
this.ensureInitialized();
|
|
361
|
+
for await (const row of this.db!.eval('select count(1) as Count from CadreControl.OwnerKey')) {
|
|
362
|
+
return (row.Count as number) > 0;
|
|
363
|
+
}
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Idempotent genesis: insert `key` as the founding owner key only when
|
|
369
|
+
* the party has none yet. Returns true if it inserted, false if an owner
|
|
370
|
+
* key already existed (so a repeat `--owner` start is a no-op).
|
|
371
|
+
*/
|
|
372
|
+
async ensureOwnerKey(key: string): Promise<boolean> {
|
|
373
|
+
this.ensureInitialized();
|
|
374
|
+
if (await this.hasOwnerKey()) {
|
|
375
|
+
log('Owner key already present; skipping genesis insert');
|
|
376
|
+
return false;
|
|
377
|
+
}
|
|
378
|
+
await this.insertOwnerKey(key);
|
|
379
|
+
return true;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Collect every owner key (`CadreControl.OwnerKey.Key`) as a set.
|
|
384
|
+
*
|
|
385
|
+
* This is the steady-state trust anchor for seeds: a seed's signer key is
|
|
386
|
+
* trusted only if it is already enrolled here (see `SeedTrustPolicy`). It is
|
|
387
|
+
* also the owner-identity source for `queryPeers`, decoupling owner
|
|
388
|
+
* status from the libp2p transport peer ID.
|
|
389
|
+
*/
|
|
390
|
+
async getOwnerKeys(): Promise<Set<string>> {
|
|
391
|
+
this.ensureInitialized();
|
|
392
|
+
const keys = new Set<string>();
|
|
393
|
+
for await (const row of this.db!.eval('select Key from CadreControl.OwnerKey')) {
|
|
394
|
+
keys.add(row.Key as string);
|
|
395
|
+
}
|
|
396
|
+
return keys;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Enumerate the CadrePeer rows (cadre membership) for admin/membership reads.
|
|
401
|
+
*/
|
|
402
|
+
async queryCadrePeers(): Promise<Array<{ peerId: string; multiaddr: string | null; stampId: string | null; vouchOwner: string | null; vouchSig: string | null }>> {
|
|
403
|
+
this.ensureInitialized();
|
|
404
|
+
const rows: Array<{ peerId: string; multiaddr: string | null; stampId: string | null; vouchOwner: string | null; vouchSig: string | null }> = [];
|
|
405
|
+
for await (const row of this.db!.eval('select PeerId, Multiaddr, StampId, VouchOwner, VouchSig from CadreControl.CadrePeer')) {
|
|
406
|
+
rows.push({
|
|
407
|
+
peerId: row.PeerId as string,
|
|
408
|
+
multiaddr: (row.Multiaddr as string | null) ?? null,
|
|
409
|
+
stampId: (row.StampId as string | null) ?? null,
|
|
410
|
+
vouchOwner: (row.VouchOwner as string | null) ?? null,
|
|
411
|
+
vouchSig: (row.VouchSig as string | null) ?? null,
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
return rows;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Read a single `CadrePeer` row's single-use `StampId` nonce (null when the row
|
|
419
|
+
* does not exist). Used by the owner delete / re-touch paths, which must bind
|
|
420
|
+
* their signature to the row's CURRENT nonce ({@link cadrePeerRemoveDigest} /
|
|
421
|
+
* {@link cadrePeerVoucherDigest}).
|
|
422
|
+
*/
|
|
423
|
+
async queryCadrePeerStampId(peerId: string): Promise<string | null> {
|
|
424
|
+
this.ensureInitialized();
|
|
425
|
+
for await (const row of this.db!.eval('select StampId from CadreControl.CadrePeer where PeerId = ?', [peerId])) {
|
|
426
|
+
return (row.StampId as string | null) ?? null;
|
|
427
|
+
}
|
|
428
|
+
return null;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Read a single peer's address record (the full `CadrePeer` row) by PeerId.
|
|
433
|
+
*
|
|
434
|
+
* Returns null when no row exists. Missing/legacy column values are coalesced
|
|
435
|
+
* to their empty form (`''` key/sig, `[]` addrs, `0` stamp) so the caller's
|
|
436
|
+
* verify/freshness gates uniformly reject an unpublished or malformed row.
|
|
437
|
+
* The split `addrs` re-join to the exact stored `Multiaddr` (split-on-`,` is
|
|
438
|
+
* the inverse of join-on-`,`), so the resolver re-verifies over the same bytes
|
|
439
|
+
* the publisher signed.
|
|
440
|
+
*/
|
|
441
|
+
async queryPeerRecord(peerId: string): Promise<PeerAddressRecord | null> {
|
|
442
|
+
this.ensureInitialized();
|
|
443
|
+
for await (const row of this.db!.eval(
|
|
444
|
+
'select PeerId, PublicKey, Multiaddr, UpdatedAt, Sig from CadreControl.CadrePeer where PeerId = ?',
|
|
445
|
+
[peerId]
|
|
446
|
+
)) {
|
|
447
|
+
const multiaddr = (row.Multiaddr as string | null) ?? '';
|
|
448
|
+
return {
|
|
449
|
+
peerId: row.PeerId as string,
|
|
450
|
+
publicKey: (row.PublicKey as string | null) ?? '',
|
|
451
|
+
addrs: multiaddr.length > 0 ? multiaddr.split(',') : [],
|
|
452
|
+
updatedAt: (row.UpdatedAt as number | null) ?? 0,
|
|
453
|
+
sig: (row.Sig as string | null) ?? '',
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Apply a peer's own self-signed address-record update to an existing row.
|
|
461
|
+
*
|
|
462
|
+
* Authorization is carried entirely by the record: the `Sig` column (verified
|
|
463
|
+
* by the `AuthorizedUpdate` self-branch against the stored `PublicKey`) plus
|
|
464
|
+
* the strictly-increasing `UpdatedAt`. No owner key is involved, so this
|
|
465
|
+
* is the refresh path for any member — owner or drone — once its row
|
|
466
|
+
* exists. `PublicKey` is intentionally not in the SET list (it is immutable on
|
|
467
|
+
* self-update and the constraint enforces `new.PublicKey = old.PublicKey`).
|
|
468
|
+
*/
|
|
469
|
+
async updateSelfPeerRecord(record: PeerAddressRecord): Promise<void> {
|
|
470
|
+
this.ensureInitialized();
|
|
471
|
+
const multiaddr = record.addrs.join(',');
|
|
472
|
+
await this.db!.exec(`
|
|
473
|
+
update CadreControl.CadrePeer
|
|
474
|
+
with context OwnerKey = null, Signature = ?
|
|
475
|
+
set Multiaddr = ?, UpdatedAt = ?, Sig = ?
|
|
476
|
+
where PeerId = ?
|
|
477
|
+
`, [record.sig, multiaddr, record.updatedAt, record.sig, record.peerId]);
|
|
478
|
+
log('Self peer record updated: %s (updatedAt=%d)', record.peerId, record.updatedAt);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Read a single peer's device push token (the full `DeviceToken` row) by PeerId.
|
|
483
|
+
*
|
|
484
|
+
* Returns null when no row exists. Missing/legacy column values are coalesced to
|
|
485
|
+
* their empty form (`''` token/sig, `0` stamp) so the caller's verify/freshness
|
|
486
|
+
* gates uniformly reject an unpublished or malformed row. `platform` is returned
|
|
487
|
+
* verbatim (the resolver validates it against {@link PushPlatform} and re-verifies
|
|
488
|
+
* the self-signature, which covers the platform field).
|
|
489
|
+
*/
|
|
490
|
+
async queryDeviceToken(peerId: string): Promise<DeviceTokenRecord | null> {
|
|
491
|
+
this.ensureInitialized();
|
|
492
|
+
for await (const row of this.db!.eval(
|
|
493
|
+
'select PeerId, Platform, Token, UpdatedAt, Sig from CadreControl.DeviceToken where PeerId = ?',
|
|
494
|
+
[peerId]
|
|
495
|
+
)) {
|
|
496
|
+
return {
|
|
497
|
+
peerId: row.PeerId as string,
|
|
498
|
+
platform: (row.Platform as string ?? '') as PushPlatform,
|
|
499
|
+
token: (row.Token as string | null) ?? '',
|
|
500
|
+
updatedAt: (row.UpdatedAt as number | null) ?? 0,
|
|
501
|
+
sig: (row.Sig as string | null) ?? '',
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
return null;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Apply a peer's own self-signed device-token update to an existing row.
|
|
509
|
+
*
|
|
510
|
+
* Authorization is carried entirely by the record: the `Sig` column (verified by
|
|
511
|
+
* the `DeviceToken.AuthorizedUpdate` self-branch against the stored
|
|
512
|
+
* `CadrePeer.PublicKey`) plus the strictly-increasing `UpdatedAt`. No owner key
|
|
513
|
+
* is involved, so this is the refresh / rotation path for any member once both its
|
|
514
|
+
* `CadrePeer` row (for the PublicKey) and its `DeviceToken` row exist. `PeerId` is
|
|
515
|
+
* intentionally not in the SET list (immutable; the constraint enforces
|
|
516
|
+
* `new.PeerId = old.PeerId`). Mirrors {@link updateSelfPeerRecord}.
|
|
517
|
+
*/
|
|
518
|
+
async updateSelfDeviceToken(record: DeviceTokenRecord): Promise<void> {
|
|
519
|
+
this.ensureInitialized();
|
|
520
|
+
await this.db!.exec(`
|
|
521
|
+
update CadreControl.DeviceToken
|
|
522
|
+
with context OwnerKey = null, Signature = ?
|
|
523
|
+
set Platform = ?, Token = ?, UpdatedAt = ?, Sig = ?
|
|
524
|
+
where PeerId = ?
|
|
525
|
+
`, [record.sig, record.platform, record.token, record.updatedAt, record.sig, record.peerId]);
|
|
526
|
+
log('Self device token updated: %s (platform=%s, updatedAt=%d)', record.peerId, record.platform, record.updatedAt);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* Insert the initial owner key (bootstrap - no existing owners required)
|
|
531
|
+
*/
|
|
532
|
+
async insertOwnerKey(key: string): Promise<void> {
|
|
533
|
+
this.ensureInitialized();
|
|
534
|
+
log('Inserting owner key: %s', key);
|
|
535
|
+
|
|
536
|
+
// Bootstrap is authorized by the schema's `(select count(1) from OwnerKey) <= 1`
|
|
537
|
+
// branch, so no signature is needed. We still persist a fresh, unique StampId in the
|
|
538
|
+
// row's own column to satisfy the not-null/unique anti-replay constraint — the StampId
|
|
539
|
+
// is now a real column value, not the optimystic `StampId()` SQL function.
|
|
540
|
+
const stampId = generateStampId(this.config.libp2pNode.peerId.toString());
|
|
541
|
+
await this.db!.exec(`
|
|
542
|
+
insert into CadreControl.OwnerKey (Key, StampId)
|
|
543
|
+
with context OwnerKey = null, Signature = null
|
|
544
|
+
values (?, ?)
|
|
545
|
+
`, [key, stampId]);
|
|
546
|
+
log('Owner key inserted');
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Insert a strand into the control database using an owner signature.
|
|
551
|
+
*
|
|
552
|
+
* The owner signs the canonical row-bound authorization message (see
|
|
553
|
+
* {@link buildAuthorizationMessage}) — NOT a bare stamp — so the signature is bound to
|
|
554
|
+
* this strand's contents and cannot be transplanted onto an attacker-chosen row. The
|
|
555
|
+
* StampId is persisted as a unique column for single-use anti-replay.
|
|
556
|
+
*
|
|
557
|
+
* @param strandId - Unique identifier for the strand
|
|
558
|
+
* @param type - Strand type: 'o' for open, 'c' for closed
|
|
559
|
+
* @param ownerKey - Public key of the authorizing owner
|
|
560
|
+
* @param signMessage - Function that ed25519-signs the raw message bytes (no pre-hash)
|
|
561
|
+
* with the owner's private key, returning a base64url signature
|
|
562
|
+
* @param memberPrivateKey - Optional private key for membership in closed strands
|
|
563
|
+
*/
|
|
564
|
+
async insertStrand(
|
|
565
|
+
strandId: string,
|
|
566
|
+
type: 'o' | 'c',
|
|
567
|
+
ownerKey: string,
|
|
568
|
+
signMessage: (message: Uint8Array) => string,
|
|
569
|
+
memberPrivateKey?: string
|
|
570
|
+
): Promise<void> {
|
|
571
|
+
this.ensureInitialized();
|
|
572
|
+
log('Inserting strand: %s (type: %s)', strandId, type);
|
|
573
|
+
|
|
574
|
+
// Generate a unique stamp ID using the peer ID for distributed uniqueness
|
|
575
|
+
const peerId = this.config.libp2pNode.peerId.toString();
|
|
576
|
+
const stampId = generateStampId(peerId);
|
|
577
|
+
|
|
578
|
+
// Field order MUST match the schema's Strand `Authorized` verify:
|
|
579
|
+
// Id, Type, MemberPrivateKey ('' when null), StampId.
|
|
580
|
+
const message = buildAuthorizationMessage([strandId, type, memberPrivateKey ?? '', stampId]);
|
|
581
|
+
const signature = signMessage(message);
|
|
582
|
+
|
|
583
|
+
// StampId is a real, unique column (single-use anti-replay), no longer a context value.
|
|
584
|
+
await this.db!.exec(`
|
|
585
|
+
insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId)
|
|
586
|
+
with context OwnerKey = ?, Signature = ?
|
|
587
|
+
values (?, ?, ?, ?)
|
|
588
|
+
`, [ownerKey, signature, strandId, type, memberPrivateKey ?? null, stampId]);
|
|
589
|
+
|
|
590
|
+
log('Strand inserted: %s', strandId);
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* Insert a validation key into the control database using an owner signature.
|
|
595
|
+
*
|
|
596
|
+
* Mirrors {@link insertStrand}: the owner signs the canonical row-bound
|
|
597
|
+
* authorization message over (Key, StampId), and the StampId is persisted as a unique
|
|
598
|
+
* column for single-use anti-replay. A `ValidationKey` authorizes verifying strand
|
|
599
|
+
* formation disclosures.
|
|
600
|
+
*
|
|
601
|
+
* @param key - The validation public key to enroll
|
|
602
|
+
* @param ownerKey - Public key of the authorizing owner
|
|
603
|
+
* @param signMessage - Function that ed25519-signs the raw message bytes (no pre-hash)
|
|
604
|
+
* with the owner's private key, returning a base64url signature
|
|
605
|
+
*/
|
|
606
|
+
async insertValidationKey(
|
|
607
|
+
key: string,
|
|
608
|
+
ownerKey: string,
|
|
609
|
+
signMessage: (message: Uint8Array) => string
|
|
610
|
+
): Promise<void> {
|
|
611
|
+
this.ensureInitialized();
|
|
612
|
+
log('Inserting validation key: %s', key);
|
|
613
|
+
|
|
614
|
+
const peerId = this.config.libp2pNode.peerId.toString();
|
|
615
|
+
const stampId = generateStampId(peerId);
|
|
616
|
+
|
|
617
|
+
// Field order MUST match the schema's ValidationKey `Authorized` verify: Key, StampId.
|
|
618
|
+
const message = buildAuthorizationMessage([key, stampId]);
|
|
619
|
+
const signature = signMessage(message);
|
|
620
|
+
|
|
621
|
+
await this.db!.exec(`
|
|
622
|
+
insert into CadreControl.ValidationKey (Key, StampId)
|
|
623
|
+
with context OwnerKey = ?, Signature = ?
|
|
624
|
+
values (?, ?)
|
|
625
|
+
`, [ownerKey, signature, key, stampId]);
|
|
626
|
+
|
|
627
|
+
log('Validation key inserted: %s', key);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Insert an owner-signed `FormationInvite` (open invitation token).
|
|
632
|
+
*
|
|
633
|
+
* The invite is the on-network record that later authorizes an
|
|
634
|
+
* owner-signature-FREE `Strand` creation: an invited cadre peer redeems it
|
|
635
|
+
* by inserting a matching `FormationUsage` row (see {@link redeemInvitation}),
|
|
636
|
+
* which satisfies the consent branch of `Strand.Authorized`.
|
|
637
|
+
*
|
|
638
|
+
* Like {@link insertStrand}/{@link insertValidationKey}, the owner signs the
|
|
639
|
+
* canonical row-bound authorization message (see {@link buildAuthorizationMessage})
|
|
640
|
+
* over (Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId, StampId) — NOT a
|
|
641
|
+
* bare stamp — so the signature is bound to this invite's contents and cannot be
|
|
642
|
+
* transplanted onto an attacker-chosen row. The StampId is persisted as a unique
|
|
643
|
+
* column for single-use anti-replay. `FormationInvite.AuthorizedAddOrRemove` gates
|
|
644
|
+
* both insert and delete; its `coalesce(new, old)` verify binds the NEW row on
|
|
645
|
+
* insert and the OLD row on delete.
|
|
646
|
+
*
|
|
647
|
+
* `StrandId` binds the invite to a pre-existing host strand (provision-then-record):
|
|
648
|
+
* when set, a responder redeeming this token records a `FormationUsage` against that
|
|
649
|
+
* strand and returns it (see {@link ControlFormationUsageRecorder.resolveStrand}); a
|
|
650
|
+
* null `StrandId` (the default) leaves the legacy responder-provisions path in place.
|
|
651
|
+
* Like ValidationUrl it is a nullable bound field, signed as `''` when absent.
|
|
652
|
+
*
|
|
653
|
+
* The ExpiresAt and TotalUses message fields must byte-match what the (auto-deferred,
|
|
654
|
+
* because it has a subquery) CHECK sees AFTER column coercion: TotalUses becomes a
|
|
655
|
+
* decimal string (`String(totalUses)` ⇔ `cast(new.TotalUses as text)`) and ExpiresAt
|
|
656
|
+
* becomes the engine's canonical `PlainDateTime` string — sourced here from
|
|
657
|
+
* {@link canonicalDatetime} (a `select datetime(?)` round-trip) rather than a hand-rolled
|
|
658
|
+
* ISO formatter, so signer and verifier agree exactly. A null ExpiresAt / TotalUses /
|
|
659
|
+
* ValidationUrl signs as `''`, matching the schema's `coalesce(..., '')`.
|
|
660
|
+
*
|
|
661
|
+
* @param token - Invitation token (the `FormationInvite` primary key)
|
|
662
|
+
* @param sAppId - The sApp a redeemed strand will use
|
|
663
|
+
* @param ownerKey - Public key of the authorizing owner
|
|
664
|
+
* @param signMessage - ed25519-signs the raw message bytes (no pre-hash),
|
|
665
|
+
* returning a base64url signature — the same callback shape {@link insertStrand} uses
|
|
666
|
+
* @param options - Optional `expiresAtMs` (epoch ms), `totalUses`, `validationUrl`,
|
|
667
|
+
* `strandId` (bind to a pre-existing host strand for provision-then-record)
|
|
668
|
+
*/
|
|
669
|
+
async insertFormationInvite(
|
|
670
|
+
token: string,
|
|
671
|
+
sAppId: string,
|
|
672
|
+
ownerKey: string,
|
|
673
|
+
signMessage: (message: Uint8Array) => string,
|
|
674
|
+
options: { expiresAtMs?: number; totalUses?: number; validationUrl?: string; strandId?: string } = {}
|
|
675
|
+
): Promise<void> {
|
|
676
|
+
this.ensureInitialized();
|
|
677
|
+
log('Inserting formation invite: %s', token);
|
|
678
|
+
|
|
679
|
+
const stampId = generateStampId(this.config.libp2pNode.peerId.toString());
|
|
680
|
+
|
|
681
|
+
// Build each bound field exactly as the deferred CHECK sees it post-coercion:
|
|
682
|
+
// - ExpiresAt: engine-canonical datetime string (or '' when absent), sourced from
|
|
683
|
+
// the engine so it byte-matches the column's stored/coerced form.
|
|
684
|
+
// - TotalUses: decimal string via String(...) (⇔ cast(new.TotalUses as text)), '' when absent.
|
|
685
|
+
// - ValidationUrl: the url or '' when absent.
|
|
686
|
+
// - StrandId: the host strand id or '' when absent (text column, no coercion).
|
|
687
|
+
const expiresAtCanonical = options.expiresAtMs == null
|
|
688
|
+
? null
|
|
689
|
+
: await canonicalDatetime(this.db!, options.expiresAtMs);
|
|
690
|
+
const expiresAtField = expiresAtCanonical ?? '';
|
|
691
|
+
const totalUsesField = options.totalUses == null ? '' : String(options.totalUses);
|
|
692
|
+
const validationUrlField = options.validationUrl ?? '';
|
|
693
|
+
const strandIdField = options.strandId ?? '';
|
|
694
|
+
|
|
695
|
+
// Field order MUST match the schema's FormationInvite `AuthorizedAddOrRemove` verify:
|
|
696
|
+
// Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId, StampId.
|
|
697
|
+
const message = buildAuthorizationMessage([
|
|
698
|
+
token, sAppId, expiresAtField, totalUsesField, validationUrlField, strandIdField, stampId,
|
|
699
|
+
]);
|
|
700
|
+
const signature = signMessage(message);
|
|
701
|
+
|
|
702
|
+
// Persist the canonical ExpiresAt string (datetime parse is idempotent on it) so the
|
|
703
|
+
// signed source-of-truth and the stored value are produced once. StampId is a real,
|
|
704
|
+
// unique column (single-use anti-replay), no longer a context value.
|
|
705
|
+
await this.db!.exec(`
|
|
706
|
+
insert into CadreControl.FormationInvite (Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId, StampId)
|
|
707
|
+
with context OwnerKey = ?, Signature = ?
|
|
708
|
+
values (?, ?, ?, ?, ?, ?, ?)
|
|
709
|
+
`, [
|
|
710
|
+
ownerKey, signature,
|
|
711
|
+
token, sAppId,
|
|
712
|
+
expiresAtCanonical,
|
|
713
|
+
options.totalUses ?? null,
|
|
714
|
+
options.validationUrl ?? null,
|
|
715
|
+
options.strandId ?? null,
|
|
716
|
+
stampId,
|
|
717
|
+
]);
|
|
718
|
+
|
|
719
|
+
log('Formation invite inserted: %s', token);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* Redeem a `FormationInvite` by inserting the `Strand` row and a matching
|
|
724
|
+
* `FormationUsage` row **atomically, in one transaction**.
|
|
725
|
+
*
|
|
726
|
+
* The two CHECK constraints are mutually circular under immediate evaluation:
|
|
727
|
+
* `Strand.Authorized`'s consent branch requires the `FormationUsage` row, while
|
|
728
|
+
* `FormationUsage.StrandExists` requires the `Strand` row. Both CHECKs contain
|
|
729
|
+
* subqueries, so Quereus auto-defers them to transaction commit — wrapping both
|
|
730
|
+
* inserts in a single explicit `begin … commit` lets both deferred CHECKs see
|
|
731
|
+
* both rows at commit. The strand is authorised WITHOUT an owner signature
|
|
732
|
+
* (the `FormationUsage` branch of `Strand.Authorized`) but still gets a fresh,
|
|
733
|
+
* unique `StampId` column to satisfy the not-null/unique anti-replay column.
|
|
734
|
+
*
|
|
735
|
+
* `UseNumber` is computed as `max(UseNumber)+1` for the token (the `Monotonic`
|
|
736
|
+
* constraint); callers redeeming concurrently against the same token must
|
|
737
|
+
* serialise, since the next use number is read before the insert.
|
|
738
|
+
*/
|
|
739
|
+
async redeemInvitation(params: {
|
|
740
|
+
token: string;
|
|
741
|
+
strandId: string;
|
|
742
|
+
type?: 'o' | 'c';
|
|
743
|
+
memberPrivateKey?: string;
|
|
744
|
+
disclosure?: string;
|
|
745
|
+
peerId?: string;
|
|
746
|
+
peerSignature?: string;
|
|
747
|
+
nowMs?: number;
|
|
748
|
+
validationKey?: string;
|
|
749
|
+
validationSignature?: string;
|
|
750
|
+
}): Promise<void> {
|
|
751
|
+
this.ensureInitialized();
|
|
752
|
+
const {
|
|
753
|
+
token, strandId, type = 'o',
|
|
754
|
+
memberPrivateKey, disclosure = '',
|
|
755
|
+
peerId, peerSignature,
|
|
756
|
+
nowMs, validationKey, validationSignature,
|
|
757
|
+
} = params;
|
|
758
|
+
log('Redeeming invitation %s -> strand %s', token, strandId);
|
|
759
|
+
|
|
760
|
+
const localPeerId = this.config.libp2pNode.peerId.toString();
|
|
761
|
+
const strandStampId = generateStampId(localPeerId);
|
|
762
|
+
const useNumber = await this.nextUseNumber(token);
|
|
763
|
+
|
|
764
|
+
await this.db!.beginTransaction();
|
|
765
|
+
try {
|
|
766
|
+
// 1. Strand row — authorised by the FormationUsage branch (no owner sig),
|
|
767
|
+
// still carrying a fresh unique StampId for the anti-replay column.
|
|
768
|
+
await this.db!.exec(`
|
|
769
|
+
insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId)
|
|
770
|
+
with context OwnerKey = null, Signature = null
|
|
771
|
+
values (?, ?, ?, ?)
|
|
772
|
+
`, [strandId, type, memberPrivateKey ?? null, strandStampId]);
|
|
773
|
+
|
|
774
|
+
// 2. FormationUsage row — authorised by the matching FormationInvite.
|
|
775
|
+
await this.execFormationUsageInsert({
|
|
776
|
+
token, useNumber, disclosure, strandId,
|
|
777
|
+
peerId: peerId ?? localPeerId, peerSignature: peerSignature ?? null, nowMs: nowMs ?? Date.now(),
|
|
778
|
+
validationKey: validationKey ?? null, validationSignature: validationSignature ?? null,
|
|
779
|
+
});
|
|
780
|
+
|
|
781
|
+
await this.db!.commit();
|
|
782
|
+
log('Redeemed invitation %s -> strand %s (use #%d)', token, strandId, useNumber);
|
|
783
|
+
} catch (error) {
|
|
784
|
+
// A failed commit() already tears down the transaction, so rollback() would
|
|
785
|
+
// throw "No transaction active" and mask the real cause — swallow only that.
|
|
786
|
+
try {
|
|
787
|
+
await this.db!.rollback();
|
|
788
|
+
} catch (rollbackError) {
|
|
789
|
+
log('Rollback after redemption failure was a no-op: %s', rollbackError);
|
|
790
|
+
}
|
|
791
|
+
throw error;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/**
|
|
796
|
+
* Record a `FormationUsage` against an **already-existing** `Strand` (no strand
|
|
797
|
+
* insert). This is the redemption path when the strand was provisioned
|
|
798
|
+
* separately (e.g. owner-signed) and the consent record is added after the
|
|
799
|
+
* fact: the single insert auto-commits, and the deferred `StrandExists` CHECK
|
|
800
|
+
* is satisfied by the pre-existing committed strand row. Returns the assigned
|
|
801
|
+
* `UseNumber`.
|
|
802
|
+
*
|
|
803
|
+
* Use {@link redeemInvitation} instead when the strand must be created by
|
|
804
|
+
* consent atomically with the usage.
|
|
805
|
+
*/
|
|
806
|
+
async recordFormationUsage(params: {
|
|
807
|
+
token: string;
|
|
808
|
+
strandId: string;
|
|
809
|
+
disclosure?: string;
|
|
810
|
+
peerId?: string;
|
|
811
|
+
peerSignature?: string;
|
|
812
|
+
nowMs?: number;
|
|
813
|
+
validationKey?: string;
|
|
814
|
+
validationSignature?: string;
|
|
815
|
+
}): Promise<number> {
|
|
816
|
+
this.ensureInitialized();
|
|
817
|
+
const {
|
|
818
|
+
token, strandId, disclosure = '',
|
|
819
|
+
peerId, peerSignature, nowMs, validationKey, validationSignature,
|
|
820
|
+
} = params;
|
|
821
|
+
|
|
822
|
+
const localPeerId = this.config.libp2pNode.peerId.toString();
|
|
823
|
+
const useNumber = await this.nextUseNumber(token);
|
|
824
|
+
|
|
825
|
+
await this.execFormationUsageInsert({
|
|
826
|
+
token, useNumber, disclosure, strandId,
|
|
827
|
+
peerId: peerId ?? localPeerId, peerSignature: peerSignature ?? null, nowMs: nowMs ?? Date.now(),
|
|
828
|
+
validationKey: validationKey ?? null, validationSignature: validationSignature ?? null,
|
|
829
|
+
});
|
|
830
|
+
|
|
831
|
+
log('Recorded formation usage: token=%s strand=%s (use #%d)', token, strandId, useNumber);
|
|
832
|
+
return useNumber;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/** Parameterised `FormationUsage` insert shared by redeem + record paths. */
|
|
836
|
+
private async execFormationUsageInsert(opts: {
|
|
837
|
+
token: string;
|
|
838
|
+
useNumber: number;
|
|
839
|
+
disclosure: string;
|
|
840
|
+
strandId: string;
|
|
841
|
+
peerId: string;
|
|
842
|
+
peerSignature: string | null;
|
|
843
|
+
nowMs: number;
|
|
844
|
+
validationKey: string | null;
|
|
845
|
+
validationSignature: string | null;
|
|
846
|
+
}): Promise<void> {
|
|
847
|
+
// Derive `context.Now` through the same `canonicalDatetime` transform that
|
|
848
|
+
// produced the stored `ExpiresAt`, so the deferred CHECK's `FI.ExpiresAt >
|
|
849
|
+
// context.Now` compares two byte-identical engine-`datetime` strings. The
|
|
850
|
+
// previous `new Date(nowMs).toISOString()` form differed only by a trailing
|
|
851
|
+
// `.000Z` (the engine `datetime()` separator is `T`, not a space), which never
|
|
852
|
+
// flipped the strict `>` against a second-granular `ExpiresAt` — so this is a
|
|
853
|
+
// robustness/consistency change, matching the strand layer's `consumeInvite`,
|
|
854
|
+
// not a fix for an observable mis-ordering.
|
|
855
|
+
const nowCanonical = await canonicalDatetime(this.db!, opts.nowMs);
|
|
856
|
+
await this.db!.exec(`
|
|
857
|
+
insert into CadreControl.FormationUsage (Token, UseNumber, Disclosure, StrandId)
|
|
858
|
+
with context PeerId = ?, PeerSignature = ?, Now = ?, ValidationKey = ?, ValidationSignature = ?
|
|
859
|
+
values (?, ?, ?, ?)
|
|
860
|
+
`, [
|
|
861
|
+
opts.peerId, opts.peerSignature, nowCanonical,
|
|
862
|
+
opts.validationKey, opts.validationSignature,
|
|
863
|
+
opts.token, opts.useNumber, opts.disclosure, opts.strandId,
|
|
864
|
+
]);
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/**
|
|
868
|
+
* Read a `FormationInvite` row by token, or null when absent. `expiresAtMs` is
|
|
869
|
+
* the parsed epoch-ms of the stored `datetime` (null when the invite never
|
|
870
|
+
* expires); the caller compares it against the wall clock for freshness.
|
|
871
|
+
*/
|
|
872
|
+
async queryFormationInvite(token: string): Promise<{
|
|
873
|
+
token: string;
|
|
874
|
+
sAppId: string;
|
|
875
|
+
expiresAtMs: number | null;
|
|
876
|
+
totalUses: number | null;
|
|
877
|
+
validationUrl: string | null;
|
|
878
|
+
strandId: string | null;
|
|
879
|
+
} | null> {
|
|
880
|
+
this.ensureInitialized();
|
|
881
|
+
for await (const row of this.db!.eval(
|
|
882
|
+
'select Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId from CadreControl.FormationInvite where Token = ?',
|
|
883
|
+
[token]
|
|
884
|
+
)) {
|
|
885
|
+
const expiresAt = row.ExpiresAt as string | number | null;
|
|
886
|
+
const expiresAtMs = expiresAt === null || expiresAt === undefined
|
|
887
|
+
? null
|
|
888
|
+
: parseStoredDatetimeMs(expiresAt);
|
|
889
|
+
return {
|
|
890
|
+
token: row.Token as string,
|
|
891
|
+
sAppId: row.sAppId as string,
|
|
892
|
+
expiresAtMs: expiresAtMs !== null && Number.isNaN(expiresAtMs) ? null : expiresAtMs,
|
|
893
|
+
totalUses: (row.TotalUses as number | null) ?? null,
|
|
894
|
+
validationUrl: (row.ValidationUrl as string | null) ?? null,
|
|
895
|
+
strandId: (row.StrandId as string | null) ?? null,
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
return null;
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
/**
|
|
902
|
+
* Count `FormationUsage` rows recorded against a token (uses consumed so far).
|
|
903
|
+
*/
|
|
904
|
+
async countFormationUsage(token: string): Promise<number> {
|
|
905
|
+
this.ensureInitialized();
|
|
906
|
+
for await (const row of this.db!.eval(
|
|
907
|
+
'select count(1) as Count from CadreControl.FormationUsage where Token = ?',
|
|
908
|
+
[token]
|
|
909
|
+
)) {
|
|
910
|
+
return (row.Count as number) ?? 0;
|
|
911
|
+
}
|
|
912
|
+
return 0;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/** Next `UseNumber` for a token = max(existing)+1, per the `Monotonic` constraint. */
|
|
916
|
+
private async nextUseNumber(token: string): Promise<number> {
|
|
917
|
+
for await (const row of this.db!.eval(
|
|
918
|
+
'select coalesce(max(UseNumber), 0) as MaxUse from CadreControl.FormationUsage where Token = ?',
|
|
919
|
+
[token]
|
|
920
|
+
)) {
|
|
921
|
+
return (row.MaxUse as number) + 1;
|
|
922
|
+
}
|
|
923
|
+
return 1;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/**
|
|
927
|
+
* Close the database and cleanup resources
|
|
928
|
+
*/
|
|
929
|
+
async close(): Promise<void> {
|
|
930
|
+
if (this.collectionFactory) {
|
|
931
|
+
await this.collectionFactory.shutdown();
|
|
932
|
+
this.collectionFactory = null;
|
|
933
|
+
}
|
|
934
|
+
if (this.db) {
|
|
935
|
+
void this.db.close();
|
|
936
|
+
this.db = null;
|
|
937
|
+
}
|
|
938
|
+
this.initialized = false;
|
|
939
|
+
log('ControlDatabase closed');
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
private ensureInitialized(): void {
|
|
943
|
+
if (!this.initialized || !this.db) {
|
|
944
|
+
throw new Error('ControlDatabase not initialized. Call initialize() first.');
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
|