@serfab/cadre-core 0.7.1 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +9 -8
  2. package/dist/authority-key.d.ts +41 -0
  3. package/dist/authority-key.js +52 -0
  4. package/dist/authority-key.js.map +1 -0
  5. package/dist/cadre-node.d.ts +770 -11
  6. package/dist/cadre-node.js +1900 -88
  7. package/dist/cadre-node.js.map +1 -1
  8. package/dist/canonical-datetime.d.ts +33 -0
  9. package/dist/canonical-datetime.js +38 -0
  10. package/dist/canonical-datetime.js.map +1 -0
  11. package/dist/canonical-json.d.ts +12 -0
  12. package/dist/canonical-json.js +33 -0
  13. package/dist/canonical-json.js.map +1 -0
  14. package/dist/control-cohort.d.ts +63 -0
  15. package/dist/control-cohort.js +80 -0
  16. package/dist/control-cohort.js.map +1 -0
  17. package/dist/control-database.d.ts +259 -5
  18. package/dist/control-database.js +541 -128
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +89 -0
  21. package/dist/control-formation-recorder.js +139 -0
  22. package/dist/control-formation-recorder.js.map +1 -0
  23. package/dist/control-schema.d.ts +12 -0
  24. package/dist/control-schema.js +199 -0
  25. package/dist/control-schema.js.map +1 -0
  26. package/dist/control-stream.d.ts +54 -0
  27. package/dist/control-stream.js +104 -0
  28. package/dist/control-stream.js.map +1 -0
  29. package/dist/device-token.d.ts +50 -0
  30. package/dist/device-token.js +66 -0
  31. package/dist/device-token.js.map +1 -0
  32. package/dist/diagnostics/connection-path.d.ts +118 -0
  33. package/dist/diagnostics/connection-path.js +204 -0
  34. package/dist/diagnostics/connection-path.js.map +1 -0
  35. package/dist/diagnostics/webrtc-turn-tracker.d.ts +50 -0
  36. package/dist/diagnostics/webrtc-turn-tracker.js +196 -0
  37. package/dist/diagnostics/webrtc-turn-tracker.js.map +1 -0
  38. package/dist/hibernation-manager.d.ts +79 -0
  39. package/dist/hibernation-manager.js +173 -23
  40. package/dist/hibernation-manager.js.map +1 -1
  41. package/dist/index.d.ts +25 -4
  42. package/dist/index.js +59 -4
  43. package/dist/index.js.map +1 -1
  44. package/dist/key-store-file.d.ts +52 -0
  45. package/dist/key-store-file.js +194 -0
  46. package/dist/key-store-file.js.map +1 -0
  47. package/dist/key-store.d.ts +75 -0
  48. package/dist/key-store.js +66 -0
  49. package/dist/key-store.js.map +1 -0
  50. package/dist/peer-authorization.d.ts +26 -0
  51. package/dist/peer-authorization.js +40 -0
  52. package/dist/peer-authorization.js.map +1 -0
  53. package/dist/peer-record.d.ts +89 -0
  54. package/dist/peer-record.js +117 -0
  55. package/dist/peer-record.js.map +1 -0
  56. package/dist/push-credentials.d.ts +34 -0
  57. package/dist/push-credentials.js +81 -0
  58. package/dist/push-credentials.js.map +1 -0
  59. package/dist/push-fanout.d.ts +137 -0
  60. package/dist/push-fanout.js +197 -0
  61. package/dist/push-fanout.js.map +1 -0
  62. package/dist/push-notifier-apns.d.ts +53 -0
  63. package/dist/push-notifier-apns.js +195 -0
  64. package/dist/push-notifier-apns.js.map +1 -0
  65. package/dist/push-notifier-fcm.d.ts +38 -0
  66. package/dist/push-notifier-fcm.js +183 -0
  67. package/dist/push-notifier-fcm.js.map +1 -0
  68. package/dist/push-notifier-shared.d.ts +18 -0
  69. package/dist/push-notifier-shared.js +25 -0
  70. package/dist/push-notifier-shared.js.map +1 -0
  71. package/dist/push-notifier.d.ts +71 -0
  72. package/dist/push-notifier.js +50 -0
  73. package/dist/push-notifier.js.map +1 -0
  74. package/dist/schema-verification.d.ts +11 -2
  75. package/dist/schema-verification.js +15 -4
  76. package/dist/schema-verification.js.map +1 -1
  77. package/dist/seed-bootstrap.d.ts +197 -9
  78. package/dist/seed-bootstrap.js +396 -137
  79. package/dist/seed-bootstrap.js.map +1 -1
  80. package/dist/seed-trust-policy.d.ts +63 -0
  81. package/dist/seed-trust-policy.js +56 -0
  82. package/dist/seed-trust-policy.js.map +1 -0
  83. package/dist/strand-addr-protocol.d.ts +132 -0
  84. package/dist/strand-addr-protocol.js +313 -0
  85. package/dist/strand-addr-protocol.js.map +1 -0
  86. package/dist/strand-cohort.d.ts +54 -0
  87. package/dist/strand-cohort.js +38 -0
  88. package/dist/strand-cohort.js.map +1 -0
  89. package/dist/strand-database.d.ts +54 -6
  90. package/dist/strand-database.js +88 -100
  91. package/dist/strand-database.js.map +1 -1
  92. package/dist/strand-formation-manager.d.ts +79 -19
  93. package/dist/strand-formation-manager.js +196 -104
  94. package/dist/strand-formation-manager.js.map +1 -1
  95. package/dist/strand-formation-protocol.d.ts +162 -0
  96. package/dist/strand-formation-protocol.js +279 -0
  97. package/dist/strand-formation-protocol.js.map +1 -0
  98. package/dist/strand-instance-manager.d.ts +73 -4
  99. package/dist/strand-instance-manager.js +167 -41
  100. package/dist/strand-instance-manager.js.map +1 -1
  101. package/dist/strand-member-key.d.ts +29 -0
  102. package/dist/strand-member-key.js +38 -0
  103. package/dist/strand-member-key.js.map +1 -0
  104. package/dist/strand-member-registry.d.ts +98 -0
  105. package/dist/strand-member-registry.js +129 -0
  106. package/dist/strand-member-registry.js.map +1 -0
  107. package/dist/strand-membership-writer.d.ts +361 -0
  108. package/dist/strand-membership-writer.js +449 -0
  109. package/dist/strand-membership-writer.js.map +1 -0
  110. package/dist/strand-solicitation.d.ts +77 -2
  111. package/dist/strand-solicitation.js +25 -4
  112. package/dist/strand-solicitation.js.map +1 -1
  113. package/dist/strand-wake-payload.d.ts +30 -0
  114. package/dist/strand-wake-payload.js +20 -0
  115. package/dist/strand-wake-payload.js.map +1 -0
  116. package/dist/strand-wake-protocol.d.ts +114 -0
  117. package/dist/strand-wake-protocol.js +257 -0
  118. package/dist/strand-wake-protocol.js.map +1 -0
  119. package/dist/strand-watcher.d.ts +6 -2
  120. package/dist/strand-watcher.js +57 -17
  121. package/dist/strand-watcher.js.map +1 -1
  122. package/dist/types.d.ts +406 -23
  123. package/dist/types.js +22 -5
  124. package/dist/types.js.map +1 -1
  125. package/package.json +14 -8
  126. package/src/authority-key.ts +68 -0
  127. package/src/cadre-node.ts +2937 -948
  128. package/src/canonical-datetime.ts +39 -0
  129. package/src/canonical-json.ts +30 -0
  130. package/src/control-cohort.ts +103 -0
  131. package/src/control-database.ts +931 -383
  132. package/src/control-formation-recorder.ts +151 -0
  133. package/src/control-schema.ts +198 -0
  134. package/src/control-stream.ts +128 -0
  135. package/src/device-token.ts +89 -0
  136. package/src/diagnostics/connection-path.ts +277 -0
  137. package/src/diagnostics/webrtc-turn-tracker.ts +222 -0
  138. package/src/hibernation-manager.ts +197 -28
  139. package/src/index.ts +273 -79
  140. package/src/key-store-file.ts +203 -0
  141. package/src/key-store.ts +99 -0
  142. package/src/peer-authorization.ts +53 -0
  143. package/src/peer-record.ts +146 -0
  144. package/src/push-credentials.ts +84 -0
  145. package/src/push-fanout.ts +272 -0
  146. package/src/push-notifier-apns.ts +243 -0
  147. package/src/push-notifier-fcm.ts +221 -0
  148. package/src/push-notifier-shared.ts +28 -0
  149. package/src/push-notifier.ts +93 -0
  150. package/src/schema-verification.ts +18 -4
  151. package/src/seed-bootstrap.ts +464 -188
  152. package/src/seed-trust-policy.ts +107 -0
  153. package/src/strand-addr-protocol.ts +410 -0
  154. package/src/strand-cohort.ts +77 -0
  155. package/src/strand-database.ts +113 -141
  156. package/src/strand-formation-manager.ts +233 -142
  157. package/src/strand-formation-protocol.ts +391 -0
  158. package/src/strand-instance-manager.ts +207 -56
  159. package/src/strand-member-key.ts +39 -0
  160. package/src/strand-member-registry.ts +177 -0
  161. package/src/strand-membership-writer.ts +640 -0
  162. package/src/strand-solicitation.ts +93 -4
  163. package/src/strand-wake-payload.ts +32 -0
  164. package/src/strand-wake-protocol.ts +331 -0
  165. package/src/strand-watcher.ts +61 -17
  166. package/src/types.ts +1012 -582
@@ -4,110 +4,10 @@ import { Database, registerPlugin } from '@quereus/quereus';
4
4
  import cryptoPlugin from '@optimystic/quereus-plugin-crypto/plugin';
5
5
  import optimysticPlugin from '@optimystic/quereus-plugin-optimystic/plugin';
6
6
  import { digest, randomBytes } from '@optimystic/quereus-plugin-crypto';
7
+ import { CONTROL_SCHEMA } from './control-schema.js';
8
+ import { canonicalDatetime } from './canonical-datetime.js';
7
9
  const log = debug('sereus:cadre:control-db');
8
10
  const timing = debug('sereus:cadre:timing');
9
- /**
10
- * Embedded control schema for cross-platform compatibility.
11
- * This schema is embedded directly in the code to work in React Native and other
12
- * environments where file system access is not available.
13
- */
14
- const CONTROL_SCHEMA = `-- This manages a Sereus party's cadre, or set of nodes, and their participation in strands (networks)
15
- declare schema CadreControl {
16
- -- A key that can authorize various control changes
17
- table AuthorityKey (
18
- Key text primary key,
19
- constraint Authorized check (
20
- -- Bootstrap: first authority key needs no existing authorization
21
- (select count(1) from AuthorityKey) <= 1
22
-
23
- -- Old authority can authorize by signature and transaction stamp id (not repeatable)
24
- or (old.Key is not null and old.Key = context.AuthorityKey and verify(digest(context.StampId, 'sha256', 'utf8'), context.Signature, old.Key, 'ed25519'))
25
-
26
- -- or other authorities can authorize by signature and transaction stamp id (not repeatable)
27
- or exists (select 1 from AuthorityKey A where A.Key = context.AuthorityKey and verify(digest(context.StampId, 'sha256', 'utf8'), context.Signature, A.Key, 'ed25519'))
28
- )
29
- ) with context (AuthorityKey text null, Signature text null, StampId text);
30
-
31
- -- A key that can validate a strand formation disclosure
32
- table ValidationKey (
33
- Key text primary key,
34
- constraint Authorized check (
35
- -- Authorities can authorize by signature and transaction stamp id (not repeatable)
36
- exists (select 1 from AuthorityKey A where A.Key = context.AuthorityKey and verify(digest(context.StampId, 'sha256', 'utf8'), context.Signature, A.Key, 'ed25519'))
37
- )
38
- ) with context (AuthorityKey text, StampId text, Signature text);
39
-
40
- -- A network of members sharing an sApp database, each contributing peer nodes (their cadre) to the overall cohort
41
- -- Cadre peers should participate in each of these strands
42
- table Strand (
43
- Id text primary key, -- UUID
44
- MemberPrivateKey text null unique, -- Our private key as a member of this strand
45
- Type text, -- Types: 'o' = Open, 'c' = Closed -- Open can still control writes in the sApp, but only Closed controls reads
46
- constraint Authorized check (
47
- -- Authorized by authority signature and transaction stamp id (not repeatable)
48
- exists (select 1 from AuthorityKey A where A.Key = context.AuthorityKey and verify(digest(context.StampId, 'sha256', 'utf8'), context.Signature, A.Key, 'ed25519'))
49
-
50
- -- or authorized by a cadre peer who has received a valid formation invitation
51
- or exists (select 1 from FormationUsage FU where FU.StrandId = new.Id)
52
- ),
53
- -- TODO: constraint to ensure member private key only if closed
54
- ) with context (AuthorityKey text, StampId text, Signature text);
55
-
56
- -- A peer (node) that is part of the cadre
57
- table CadrePeer (
58
- PeerId text primary key,
59
- Multiaddr text,
60
- constraint AuthorizedInsert check on insert, delete (
61
- -- Authorized by an authority key
62
- -- Use utf8 input encoding since peer IDs are base58btc strings, not base64url
63
- exists (select 1 from AuthorityKey A where A.Key = context.AuthorityKey and verify(digest(coalesce(new.PeerId, old.PeerId), 'sha256', 'utf8'), context.Signature, A.Key, 'ed25519'))
64
- ),
65
- constraint AuthorizedUpdate check on update (
66
- -- Peer can change its own multiaddr (using utf8 encoding for both values)
67
- verify(digest(new.PeerId, 'sha256', 'utf8') || digest(new.Multiaddr, 'sha256', 'utf8'), context.Signature, new.PeerId, 'ed25519')
68
- -- or authorized by an authority key
69
- or exists (select 1 from AuthorityKey A where A.Key = context.AuthorityKey and verify(digest(new.PeerId, 'sha256', 'utf8'), context.Signature, A.Key, 'ed25519'))
70
- )
71
- ) with context (AuthorityKey text null, Signature text);
72
-
73
- -- An open invitation to form a strand with this party
74
- table FormationInvite (
75
- Token text primary key, -- Just a random string
76
- sAppId text, -- The app for the strand that will be formed
77
- ExpiresAt datetime null,
78
- TotalUses int null check (TotalUses >= 0),
79
- ValidationUrl text null, -- Web hook - send disclosure, IP address...
80
- constraint AuthorizedAddOrRemove check on insert, delete (
81
- -- Authorized by an authority key to add or remove this invite
82
- exists (select 1 from AuthorityKey A where A.Key = context.AuthorityKey and verify(digest(context.StampId), context.Signature, A.Key))
83
- )
84
- ) with context (AuthorityKey text, StampId text, Signature text);
85
-
86
- table FormationUsage (
87
- Token text,
88
- UseNumber int,
89
- Disclosure text,
90
- StrandId text,
91
- primary key (Token, UseNumber),
92
- constraint InsertOnly check on update, delete (false),
93
- constraint Monotonic check (
94
- new.UseNumber = coalesce((select max(UseNumber) from FormationUsage U where U.Token = new.Token), 0) + 1
95
- ),
96
- constraint Authorized check on insert (
97
- -- Satisfies an invitation
98
- exists (
99
- select 1 from FormationInvite FI
100
- where FI.Token = new.Token
101
- and (FI.TotalUses is null or FI.TotalUses >= new.UseNumber)
102
- and (FI.ExpiresAt is null or FI.ExpiresAt > context.Now)
103
- and (FI.ValidationUrl is null or verify(digest(new.Token, new.Disclosure), context.ValidationSignature, context.ValidationKey))
104
- )
105
- ),
106
- constraint StrandExists check (exists (select 1 from Strand S where S.Id = new.StrandId)),
107
- ) with context (PeerId text, PeerSignature text, Now datetime, ValidationKey text null, ValidationSignature text null);
108
- }
109
-
110
- apply schema CadreControl;`;
111
11
  /**
112
12
  * Generate a unique stamp ID for transaction authorization.
113
13
  * Format: 32 bytes base64url encoded
@@ -115,8 +15,10 @@ apply schema CadreControl;`;
115
15
  * - Last 16 bytes: Random bytes (for collision resistance)
116
16
  */
117
17
  function generateStampId(peerId) {
118
- // Hash the peer ID and get first 16 bytes (128 bits)
119
- const peerIdHash = digest(peerId, 'sha256', 'utf8', 'bytes');
18
+ // Hash the peer ID and get first 16 bytes (128 bits). A purely local ID
19
+ // generator: never signed/verified against SQL, so the framed single-field
20
+ // digest is fine (the changed framing is not cross-checked anywhere).
21
+ const peerIdHash = digest([peerId], 'sha256', 'bytes');
120
22
  const peerIdHashPart = peerIdHash.slice(0, 16);
121
23
  // Generate 16 random bytes
122
24
  const randomPart = randomBytes(128, 'bytes');
@@ -127,6 +29,54 @@ function generateStampId(peerId) {
127
29
  // Convert to base64url
128
30
  return uint8ArrayToString(combined, 'base64url');
129
31
  }
32
+ /**
33
+ * Parse a stored Quereus `datetime` value into epoch milliseconds.
34
+ *
35
+ * Quereus canonicalises a `datetime` column to a bare UTC `PlainDateTime` string
36
+ * (e.g. `2026-06-04T12:34:56`, no `Z`). JS `Date` reads a timezone-less
37
+ * date-time as LOCAL, so we append `Z` when no offset/zone is present to keep the
38
+ * value anchored to UTC. Numbers (already epoch ms) pass through.
39
+ */
40
+ function parseStoredDatetimeMs(value) {
41
+ if (typeof value === 'number')
42
+ return value;
43
+ const hasZone = /[zZ]$|[+-]\d\d:?\d\d$/.test(value);
44
+ return new Date(hasZone ? value : `${value}Z`).getTime();
45
+ }
46
+ /**
47
+ * Build the canonical authorization message that authority signatures are bound to.
48
+ *
49
+ * The message is a SINGLE framed SHA-256 digest over the ordered tuple of fields (the
50
+ * crypto plugin's injective multi-field encoding), in a fixed field order, with the
51
+ * single-use StampId as the final field:
52
+ *
53
+ * message = sha256(encodeFields([field_1, field_2, ..., StampId])) // raw digest bytes
54
+ *
55
+ * ed25519 signs these raw digest bytes DIRECTLY (no second hash). The SQL constraints
56
+ * verify the identical bytes with one variadic call
57
+ * (`verify(digest(field_1, ..., StampId), context.Signature, A.Key, 'ed25519')`): SQL
58
+ * `digest(...)` returns the base64url string of the same digest, which `verify`'s default
59
+ * base64url input encoding decodes back to those raw bytes — so signer and verifier
60
+ * operate on the same bytes. Every field is TEXT on both sides (the SQL columns are
61
+ * `cast(... as text)` / `coalesce(...,'')`; the TS args are strings), so the per-field
62
+ * type tags agree. This binds the signature to the row contents (not a bare stamp),
63
+ * closing the captured-stamp replay / privilege-escalation hole. Single source of truth:
64
+ * every signed writer (and every test/harness signer) MUST build the message through this
65
+ * function in the schema's field order, or `verify` will reject the row.
66
+ */
67
+ export function buildAuthorizationMessage(fields) {
68
+ return digest([...fields], 'sha256', 'bytes');
69
+ }
70
+ /** Runtime guard mirroring {@link ControlTable} for the dynamic-`from` count. */
71
+ const CONTROL_TABLES = new Set([
72
+ 'AuthorityKey',
73
+ 'ValidationKey',
74
+ 'Strand',
75
+ 'CadrePeer',
76
+ 'DeviceToken',
77
+ 'FormationInvite',
78
+ 'FormationUsage',
79
+ ]);
130
80
  /**
131
81
  * ControlDatabase manages the CadreControl schema using Quereus with Optimystic backend.
132
82
  * It provides typed query methods for accessing control network data.
@@ -177,6 +127,29 @@ export class ControlDatabase {
177
127
  this.collectionFactory.registerLibp2pNode(networkName, this.config.libp2pNode, this.config.coordinatedRepo);
178
128
  timing('[controlDb] registerLibp2pNode: %dms', Math.round(performance.now() - t0));
179
129
  log('Registered libp2p node with collection factory');
130
+ // Network-back the control tables. CONTROL_SCHEMA's `declare schema CadreControl
131
+ // { table ... }` tables carry NO per-table `using optimystic(...)`, so storage is
132
+ // chosen by the database's DEFAULT vtab. Routing the default to optimystic (with
133
+ // the network transactor + this party's control network) is what makes a control
134
+ // write replicate peer-to-peer — exactly what connectToStrand does for strand
135
+ // tables (compose-strand.ts). Without these two calls the tables fall back to
136
+ // Quereus's in-memory vtab and never converge across the cadre.
137
+ this.db.setDefaultVtabName('optimystic');
138
+ this.db.setDefaultVtabArgs({
139
+ networkName,
140
+ transactor: 'network',
141
+ keyNetwork: 'libp2p',
142
+ });
143
+ log('Set default vtab to optimystic (networkName=%s, transactor=network)', networkName);
144
+ // Hydrate Quereus's catalog from any persisted optimystic vtab schemas BEFORE
145
+ // applying CONTROL_SCHEMA, so a warm restart with persistent storage diffs the
146
+ // control DDL against the already-present tables and re-emits nothing — the same
147
+ // warm-start regression connectToStrand's hydrate-before-apply guards against.
148
+ // No-op on a cold / in-memory start (`{ tables: 0, indexes: 0 }`).
149
+ t0 = performance.now();
150
+ const hydrated = await pluginResult.hydrate(this.db);
151
+ timing('[controlDb] hydrate: %dms (tables=%d, indexes=%d)', Math.round(performance.now() - t0), hydrated.tables, hydrated.indexes);
152
+ log('Hydrated control catalog (tables=%d, indexes=%d)', hydrated.tables, hydrated.indexes);
180
153
  // Load and execute the schema
181
154
  t0 = performance.now();
182
155
  await this.loadSchema();
@@ -193,13 +166,16 @@ export class ControlDatabase {
193
166
  // Check if we're in a Node.js environment
194
167
  if (typeof process !== 'undefined' && process.versions?.node) {
195
168
  try {
196
- // Use require to conditionally load fs only in Node.js
197
- // This won't be bundled by React Native's Metro bundler
169
+ // Use require to conditionally load fs only in Node.js.
170
+ // This won't be bundled by React Native's Metro bundler — a dynamic
171
+ // import() would be statically picked up by Metro, so require is
172
+ // intentional here (cross-platform constraint, not lazy CommonJS).
173
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
198
174
  const fs = require('fs/promises');
199
175
  schemaContent = await fs.readFile(this.config.schemaPath, 'utf-8');
200
176
  }
201
177
  catch (error) {
202
- throw new Error(`Failed to load schema from ${this.config.schemaPath}: ${error instanceof Error ? error.message : String(error)}`);
178
+ throw new Error(`Failed to load schema from ${this.config.schemaPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
203
179
  }
204
180
  }
205
181
  else {
@@ -230,6 +206,44 @@ export class ControlDatabase {
230
206
  }
231
207
  return results;
232
208
  }
209
+ /**
210
+ * Read a single strand row by id, or null when absent. Single-row sibling of
211
+ * {@link queryStrands}; the responder uses it to read a host strand's
212
+ * `MemberPrivateKey` (the closed-strand read-gating secret) for delivery to a
213
+ * validated invitee during provision-then-record formation.
214
+ */
215
+ async queryStrand(strandId) {
216
+ this.ensureInitialized();
217
+ for await (const row of this.db.eval('select Id, MemberPrivateKey, Type from CadreControl.Strand where Id = ?', [strandId])) {
218
+ return {
219
+ Id: row.Id,
220
+ MemberPrivateKey: row.MemberPrivateKey,
221
+ Type: row.Type,
222
+ };
223
+ }
224
+ return null;
225
+ }
226
+ /**
227
+ * Count rows in a CadreControl table as seen by THIS database instance.
228
+ *
229
+ * `table` is validated against {@link CONTROL_TABLES} before it is interpolated
230
+ * into the `from` clause: the names are not user input, but the check keeps the
231
+ * dynamic query off the injection surface and fails loudly on a typo instead of
232
+ * emitting a malformed statement. The count reflects only the rows this node's
233
+ * control DB has converged on — in the integration harness that is the authority
234
+ * node (one ControlDatabase per party), i.e. the authoritative control-network
235
+ * view, not a per-drone convergence guarantee.
236
+ */
237
+ async countRows(table) {
238
+ this.ensureInitialized();
239
+ if (!CONTROL_TABLES.has(table)) {
240
+ throw new Error(`Unknown CadreControl table: ${table}`);
241
+ }
242
+ for await (const row of this.db.eval(`select count(1) as Count from CadreControl.${table}`)) {
243
+ return row.Count ?? 0;
244
+ }
245
+ return 0;
246
+ }
233
247
  /**
234
248
  * Get the underlying database for advanced queries
235
249
  */
@@ -237,48 +251,447 @@ export class ControlDatabase {
237
251
  this.ensureInitialized();
238
252
  return this.db;
239
253
  }
254
+ /**
255
+ * Check whether any authority key exists in the control database.
256
+ * Used to decide whether a fresh-party genesis insert is required.
257
+ */
258
+ async hasAuthorityKey() {
259
+ this.ensureInitialized();
260
+ for await (const row of this.db.eval('select count(1) as Count from CadreControl.AuthorityKey')) {
261
+ return row.Count > 0;
262
+ }
263
+ return false;
264
+ }
265
+ /**
266
+ * Idempotent genesis: insert `key` as the founding authority key only when
267
+ * the party has none yet. Returns true if it inserted, false if an authority
268
+ * key already existed (so a repeat `--authority` start is a no-op).
269
+ */
270
+ async ensureAuthorityKey(key) {
271
+ this.ensureInitialized();
272
+ if (await this.hasAuthorityKey()) {
273
+ log('Authority key already present; skipping genesis insert');
274
+ return false;
275
+ }
276
+ await this.insertAuthorityKey(key);
277
+ return true;
278
+ }
279
+ /**
280
+ * Collect every authority key (`CadreControl.AuthorityKey.Key`) as a set.
281
+ *
282
+ * This is the steady-state trust anchor for seeds: a seed's signer key is
283
+ * trusted only if it is already enrolled here (see `SeedTrustPolicy`). It is
284
+ * also the authority-identity source for `queryPeers`, decoupling authority
285
+ * status from the libp2p transport peer ID.
286
+ */
287
+ async getAuthorityKeys() {
288
+ this.ensureInitialized();
289
+ const keys = new Set();
290
+ for await (const row of this.db.eval('select Key from CadreControl.AuthorityKey')) {
291
+ keys.add(row.Key);
292
+ }
293
+ return keys;
294
+ }
295
+ /**
296
+ * Enumerate the CadrePeer rows (cadre membership) for admin/membership reads.
297
+ */
298
+ async queryCadrePeers() {
299
+ this.ensureInitialized();
300
+ const rows = [];
301
+ for await (const row of this.db.eval('select PeerId, Multiaddr from CadreControl.CadrePeer')) {
302
+ rows.push({
303
+ peerId: row.PeerId,
304
+ multiaddr: row.Multiaddr ?? null,
305
+ });
306
+ }
307
+ return rows;
308
+ }
309
+ /**
310
+ * Read a single peer's address record (the full `CadrePeer` row) by PeerId.
311
+ *
312
+ * Returns null when no row exists. Missing/legacy column values are coalesced
313
+ * to their empty form (`''` key/sig, `[]` addrs, `0` stamp) so the caller's
314
+ * verify/freshness gates uniformly reject an unpublished or malformed row.
315
+ * The split `addrs` re-join to the exact stored `Multiaddr` (split-on-`,` is
316
+ * the inverse of join-on-`,`), so the resolver re-verifies over the same bytes
317
+ * the publisher signed.
318
+ */
319
+ async queryPeerRecord(peerId) {
320
+ this.ensureInitialized();
321
+ for await (const row of this.db.eval('select PeerId, PublicKey, Multiaddr, UpdatedAt, Sig from CadreControl.CadrePeer where PeerId = ?', [peerId])) {
322
+ const multiaddr = row.Multiaddr ?? '';
323
+ return {
324
+ peerId: row.PeerId,
325
+ publicKey: row.PublicKey ?? '',
326
+ addrs: multiaddr.length > 0 ? multiaddr.split(',') : [],
327
+ updatedAt: row.UpdatedAt ?? 0,
328
+ sig: row.Sig ?? '',
329
+ };
330
+ }
331
+ return null;
332
+ }
333
+ /**
334
+ * Apply a peer's own self-signed address-record update to an existing row.
335
+ *
336
+ * Authorization is carried entirely by the record: the `Sig` column (verified
337
+ * by the `AuthorizedUpdate` self-branch against the stored `PublicKey`) plus
338
+ * the strictly-increasing `UpdatedAt`. No authority key is involved, so this
339
+ * is the refresh path for any member — authority or drone — once its row
340
+ * exists. `PublicKey` is intentionally not in the SET list (it is immutable on
341
+ * self-update and the constraint enforces `new.PublicKey = old.PublicKey`).
342
+ */
343
+ async updateSelfPeerRecord(record) {
344
+ this.ensureInitialized();
345
+ const multiaddr = record.addrs.join(',');
346
+ await this.db.exec(`
347
+ update CadreControl.CadrePeer
348
+ with context AuthorityKey = null, Signature = ?
349
+ set Multiaddr = ?, UpdatedAt = ?, Sig = ?
350
+ where PeerId = ?
351
+ `, [record.sig, multiaddr, record.updatedAt, record.sig, record.peerId]);
352
+ log('Self peer record updated: %s (updatedAt=%d)', record.peerId, record.updatedAt);
353
+ }
354
+ /**
355
+ * Read a single peer's device push token (the full `DeviceToken` row) by PeerId.
356
+ *
357
+ * Returns null when no row exists. Missing/legacy column values are coalesced to
358
+ * their empty form (`''` token/sig, `0` stamp) so the caller's verify/freshness
359
+ * gates uniformly reject an unpublished or malformed row. `platform` is returned
360
+ * verbatim (the resolver validates it against {@link PushPlatform} and re-verifies
361
+ * the self-signature, which covers the platform field).
362
+ */
363
+ async queryDeviceToken(peerId) {
364
+ this.ensureInitialized();
365
+ for await (const row of this.db.eval('select PeerId, Platform, Token, UpdatedAt, Sig from CadreControl.DeviceToken where PeerId = ?', [peerId])) {
366
+ return {
367
+ peerId: row.PeerId,
368
+ platform: (row.Platform ?? ''),
369
+ token: row.Token ?? '',
370
+ updatedAt: row.UpdatedAt ?? 0,
371
+ sig: row.Sig ?? '',
372
+ };
373
+ }
374
+ return null;
375
+ }
376
+ /**
377
+ * Apply a peer's own self-signed device-token update to an existing row.
378
+ *
379
+ * Authorization is carried entirely by the record: the `Sig` column (verified by
380
+ * the `DeviceToken.AuthorizedUpdate` self-branch against the stored
381
+ * `CadrePeer.PublicKey`) plus the strictly-increasing `UpdatedAt`. No authority key
382
+ * is involved, so this is the refresh / rotation path for any member once both its
383
+ * `CadrePeer` row (for the PublicKey) and its `DeviceToken` row exist. `PeerId` is
384
+ * intentionally not in the SET list (immutable; the constraint enforces
385
+ * `new.PeerId = old.PeerId`). Mirrors {@link updateSelfPeerRecord}.
386
+ */
387
+ async updateSelfDeviceToken(record) {
388
+ this.ensureInitialized();
389
+ await this.db.exec(`
390
+ update CadreControl.DeviceToken
391
+ with context AuthorityKey = null, Signature = ?
392
+ set Platform = ?, Token = ?, UpdatedAt = ?, Sig = ?
393
+ where PeerId = ?
394
+ `, [record.sig, record.platform, record.token, record.updatedAt, record.sig, record.peerId]);
395
+ log('Self device token updated: %s (platform=%s, updatedAt=%d)', record.peerId, record.platform, record.updatedAt);
396
+ }
240
397
  /**
241
398
  * Insert the initial authority key (bootstrap - no existing authorities required)
242
399
  */
243
400
  async insertAuthorityKey(key) {
244
401
  this.ensureInitialized();
245
402
  log('Inserting authority key: %s', key);
246
- // For bootstrap, context values are not verified since no existing authorities
247
- // Use fully qualified table name since schema is CadreControl
248
- // StampId() provides the transaction's unique stamp from the optimystic transaction
249
- await this.db.exec(`
250
- insert into CadreControl.AuthorityKey (Key)
251
- with context AuthorityKey = null, Signature = null, StampId = StampId()
252
- values (?)
253
- `, [key]);
403
+ // Bootstrap is authorized by the schema's `(select count(1) from AuthorityKey) <= 1`
404
+ // branch, so no signature is needed. We still persist a fresh, unique StampId in the
405
+ // row's own column to satisfy the not-null/unique anti-replay constraint — the StampId
406
+ // is now a real column value, not the optimystic `StampId()` SQL function.
407
+ const stampId = generateStampId(this.config.libp2pNode.peerId.toString());
408
+ await this.db.exec(`
409
+ insert into CadreControl.AuthorityKey (Key, StampId)
410
+ with context AuthorityKey = null, Signature = null
411
+ values (?, ?)
412
+ `, [key, stampId]);
254
413
  log('Authority key inserted');
255
414
  }
256
415
  /**
257
- * Insert a strand into the control database using authority signature.
258
- * This starts a transaction, gets the StampId, signs it, and inserts the strand.
416
+ * Insert a strand into the control database using an authority signature.
417
+ *
418
+ * The authority signs the canonical row-bound authorization message (see
419
+ * {@link buildAuthorizationMessage}) — NOT a bare stamp — so the signature is bound to
420
+ * this strand's contents and cannot be transplanted onto an attacker-chosen row. The
421
+ * StampId is persisted as a unique column for single-use anti-replay.
259
422
  *
260
423
  * @param strandId - Unique identifier for the strand
261
424
  * @param type - Strand type: 'o' for open, 'c' for closed
262
425
  * @param authorityKey - Public key of the authorizing authority
263
- * @param signStampId - Function to sign the stamp ID with the authority's private key
426
+ * @param signMessage - Function that ed25519-signs the raw message bytes (no pre-hash)
427
+ * with the authority's private key, returning a base64url signature
264
428
  * @param memberPrivateKey - Optional private key for membership in closed strands
265
429
  */
266
- async insertStrand(strandId, type, authorityKey, signStampId, memberPrivateKey) {
430
+ async insertStrand(strandId, type, authorityKey, signMessage, memberPrivateKey) {
267
431
  this.ensureInitialized();
268
432
  log('Inserting strand: %s (type: %s)', strandId, type);
269
433
  // Generate a unique stamp ID using the peer ID for distributed uniqueness
270
434
  const peerId = this.config.libp2pNode.peerId.toString();
271
435
  const stampId = generateStampId(peerId);
272
- // Sign the stamp ID with the authority key
273
- const signature = signStampId(stampId);
274
- // Insert with the signed stamp ID
275
- await this.db.exec(`
276
- insert into CadreControl.Strand (Id, Type, MemberPrivateKey)
277
- with context AuthorityKey = ?, Signature = ?, StampId = ?
278
- values (?, ?, ?)
279
- `, [authorityKey, signature, stampId, strandId, type, memberPrivateKey ?? null]);
436
+ // Field order MUST match the schema's Strand `Authorized` verify:
437
+ // Id, Type, MemberPrivateKey ('' when null), StampId.
438
+ const message = buildAuthorizationMessage([strandId, type, memberPrivateKey ?? '', stampId]);
439
+ const signature = signMessage(message);
440
+ // StampId is a real, unique column (single-use anti-replay), no longer a context value.
441
+ await this.db.exec(`
442
+ insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId)
443
+ with context AuthorityKey = ?, Signature = ?
444
+ values (?, ?, ?, ?)
445
+ `, [authorityKey, signature, strandId, type, memberPrivateKey ?? null, stampId]);
280
446
  log('Strand inserted: %s', strandId);
281
447
  }
448
+ /**
449
+ * Insert a validation key into the control database using an authority signature.
450
+ *
451
+ * Mirrors {@link insertStrand}: the authority signs the canonical row-bound
452
+ * authorization message over (Key, StampId), and the StampId is persisted as a unique
453
+ * column for single-use anti-replay. A `ValidationKey` authorizes verifying strand
454
+ * formation disclosures.
455
+ *
456
+ * @param key - The validation public key to enroll
457
+ * @param authorityKey - Public key of the authorizing authority
458
+ * @param signMessage - Function that ed25519-signs the raw message bytes (no pre-hash)
459
+ * with the authority's private key, returning a base64url signature
460
+ */
461
+ async insertValidationKey(key, authorityKey, signMessage) {
462
+ this.ensureInitialized();
463
+ log('Inserting validation key: %s', key);
464
+ const peerId = this.config.libp2pNode.peerId.toString();
465
+ const stampId = generateStampId(peerId);
466
+ // Field order MUST match the schema's ValidationKey `Authorized` verify: Key, StampId.
467
+ const message = buildAuthorizationMessage([key, stampId]);
468
+ const signature = signMessage(message);
469
+ await this.db.exec(`
470
+ insert into CadreControl.ValidationKey (Key, StampId)
471
+ with context AuthorityKey = ?, Signature = ?
472
+ values (?, ?)
473
+ `, [authorityKey, signature, key, stampId]);
474
+ log('Validation key inserted: %s', key);
475
+ }
476
+ /**
477
+ * Insert an authority-signed `FormationInvite` (open invitation token).
478
+ *
479
+ * The invite is the on-network record that later authorizes an
480
+ * authority-signature-FREE `Strand` creation: an invited cadre peer redeems it
481
+ * by inserting a matching `FormationUsage` row (see {@link redeemInvitation}),
482
+ * which satisfies the consent branch of `Strand.Authorized`.
483
+ *
484
+ * Like {@link insertStrand}/{@link insertValidationKey}, the authority signs the
485
+ * canonical row-bound authorization message (see {@link buildAuthorizationMessage})
486
+ * over (Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId, StampId) — NOT a
487
+ * bare stamp — so the signature is bound to this invite's contents and cannot be
488
+ * transplanted onto an attacker-chosen row. The StampId is persisted as a unique
489
+ * column for single-use anti-replay. `FormationInvite.AuthorizedAddOrRemove` gates
490
+ * both insert and delete; its `coalesce(new, old)` verify binds the NEW row on
491
+ * insert and the OLD row on delete.
492
+ *
493
+ * `StrandId` binds the invite to a pre-existing host strand (provision-then-record):
494
+ * when set, a responder redeeming this token records a `FormationUsage` against that
495
+ * strand and returns it (see {@link ControlFormationUsageRecorder.resolveStrand}); a
496
+ * null `StrandId` (the default) leaves the legacy responder-provisions path in place.
497
+ * Like ValidationUrl it is a nullable bound field, signed as `''` when absent.
498
+ *
499
+ * The ExpiresAt and TotalUses message fields must byte-match what the (auto-deferred,
500
+ * because it has a subquery) CHECK sees AFTER column coercion: TotalUses becomes a
501
+ * decimal string (`String(totalUses)` ⇔ `cast(new.TotalUses as text)`) and ExpiresAt
502
+ * becomes the engine's canonical `PlainDateTime` string — sourced here from
503
+ * {@link canonicalDatetime} (a `select datetime(?)` round-trip) rather than a hand-rolled
504
+ * ISO formatter, so signer and verifier agree exactly. A null ExpiresAt / TotalUses /
505
+ * ValidationUrl signs as `''`, matching the schema's `coalesce(..., '')`.
506
+ *
507
+ * @param token - Invitation token (the `FormationInvite` primary key)
508
+ * @param sAppId - The sApp a redeemed strand will use
509
+ * @param authorityKey - Public key of the authorizing authority
510
+ * @param signMessage - ed25519-signs the raw message bytes (no pre-hash),
511
+ * returning a base64url signature — the same callback shape {@link insertStrand} uses
512
+ * @param options - Optional `expiresAtMs` (epoch ms), `totalUses`, `validationUrl`,
513
+ * `strandId` (bind to a pre-existing host strand for provision-then-record)
514
+ */
515
+ async insertFormationInvite(token, sAppId, authorityKey, signMessage, options = {}) {
516
+ this.ensureInitialized();
517
+ log('Inserting formation invite: %s', token);
518
+ const stampId = generateStampId(this.config.libp2pNode.peerId.toString());
519
+ // Build each bound field exactly as the deferred CHECK sees it post-coercion:
520
+ // - ExpiresAt: engine-canonical datetime string (or '' when absent), sourced from
521
+ // the engine so it byte-matches the column's stored/coerced form.
522
+ // - TotalUses: decimal string via String(...) (⇔ cast(new.TotalUses as text)), '' when absent.
523
+ // - ValidationUrl: the url or '' when absent.
524
+ // - StrandId: the host strand id or '' when absent (text column, no coercion).
525
+ const expiresAtCanonical = options.expiresAtMs == null
526
+ ? null
527
+ : await canonicalDatetime(this.db, options.expiresAtMs);
528
+ const expiresAtField = expiresAtCanonical ?? '';
529
+ const totalUsesField = options.totalUses == null ? '' : String(options.totalUses);
530
+ const validationUrlField = options.validationUrl ?? '';
531
+ const strandIdField = options.strandId ?? '';
532
+ // Field order MUST match the schema's FormationInvite `AuthorizedAddOrRemove` verify:
533
+ // Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId, StampId.
534
+ const message = buildAuthorizationMessage([
535
+ token, sAppId, expiresAtField, totalUsesField, validationUrlField, strandIdField, stampId,
536
+ ]);
537
+ const signature = signMessage(message);
538
+ // Persist the canonical ExpiresAt string (datetime parse is idempotent on it) so the
539
+ // signed source-of-truth and the stored value are produced once. StampId is a real,
540
+ // unique column (single-use anti-replay), no longer a context value.
541
+ await this.db.exec(`
542
+ insert into CadreControl.FormationInvite (Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId, StampId)
543
+ with context AuthorityKey = ?, Signature = ?
544
+ values (?, ?, ?, ?, ?, ?, ?)
545
+ `, [
546
+ authorityKey, signature,
547
+ token, sAppId,
548
+ expiresAtCanonical,
549
+ options.totalUses ?? null,
550
+ options.validationUrl ?? null,
551
+ options.strandId ?? null,
552
+ stampId,
553
+ ]);
554
+ log('Formation invite inserted: %s', token);
555
+ }
556
+ /**
557
+ * Redeem a `FormationInvite` by inserting the `Strand` row and a matching
558
+ * `FormationUsage` row **atomically, in one transaction**.
559
+ *
560
+ * The two CHECK constraints are mutually circular under immediate evaluation:
561
+ * `Strand.Authorized`'s consent branch requires the `FormationUsage` row, while
562
+ * `FormationUsage.StrandExists` requires the `Strand` row. Both CHECKs contain
563
+ * subqueries, so Quereus auto-defers them to transaction commit — wrapping both
564
+ * inserts in a single explicit `begin … commit` lets both deferred CHECKs see
565
+ * both rows at commit. The strand is authorised WITHOUT an authority signature
566
+ * (the `FormationUsage` branch of `Strand.Authorized`) but still gets a fresh,
567
+ * unique `StampId` column to satisfy the not-null/unique anti-replay column.
568
+ *
569
+ * `UseNumber` is computed as `max(UseNumber)+1` for the token (the `Monotonic`
570
+ * constraint); callers redeeming concurrently against the same token must
571
+ * serialise, since the next use number is read before the insert.
572
+ */
573
+ async redeemInvitation(params) {
574
+ this.ensureInitialized();
575
+ const { token, strandId, type = 'o', memberPrivateKey, disclosure = '', peerId, peerSignature, nowMs, validationKey, validationSignature, } = params;
576
+ log('Redeeming invitation %s -> strand %s', token, strandId);
577
+ const localPeerId = this.config.libp2pNode.peerId.toString();
578
+ const strandStampId = generateStampId(localPeerId);
579
+ const useNumber = await this.nextUseNumber(token);
580
+ await this.db.beginTransaction();
581
+ try {
582
+ // 1. Strand row — authorised by the FormationUsage branch (no authority sig),
583
+ // still carrying a fresh unique StampId for the anti-replay column.
584
+ await this.db.exec(`
585
+ insert into CadreControl.Strand (Id, Type, MemberPrivateKey, StampId)
586
+ with context AuthorityKey = null, Signature = null
587
+ values (?, ?, ?, ?)
588
+ `, [strandId, type, memberPrivateKey ?? null, strandStampId]);
589
+ // 2. FormationUsage row — authorised by the matching FormationInvite.
590
+ await this.execFormationUsageInsert({
591
+ token, useNumber, disclosure, strandId,
592
+ peerId: peerId ?? localPeerId, peerSignature: peerSignature ?? null, nowMs: nowMs ?? Date.now(),
593
+ validationKey: validationKey ?? null, validationSignature: validationSignature ?? null,
594
+ });
595
+ await this.db.commit();
596
+ log('Redeemed invitation %s -> strand %s (use #%d)', token, strandId, useNumber);
597
+ }
598
+ catch (error) {
599
+ // A failed commit() already tears down the transaction, so rollback() would
600
+ // throw "No transaction active" and mask the real cause — swallow only that.
601
+ try {
602
+ await this.db.rollback();
603
+ }
604
+ catch (rollbackError) {
605
+ log('Rollback after redemption failure was a no-op: %s', rollbackError);
606
+ }
607
+ throw error;
608
+ }
609
+ }
610
+ /**
611
+ * Record a `FormationUsage` against an **already-existing** `Strand` (no strand
612
+ * insert). This is the redemption path when the strand was provisioned
613
+ * separately (e.g. authority-signed) and the consent record is added after the
614
+ * fact: the single insert auto-commits, and the deferred `StrandExists` CHECK
615
+ * is satisfied by the pre-existing committed strand row. Returns the assigned
616
+ * `UseNumber`.
617
+ *
618
+ * Use {@link redeemInvitation} instead when the strand must be created by
619
+ * consent atomically with the usage.
620
+ */
621
+ async recordFormationUsage(params) {
622
+ this.ensureInitialized();
623
+ const { token, strandId, disclosure = '', peerId, peerSignature, nowMs, validationKey, validationSignature, } = params;
624
+ const localPeerId = this.config.libp2pNode.peerId.toString();
625
+ const useNumber = await this.nextUseNumber(token);
626
+ await this.execFormationUsageInsert({
627
+ token, useNumber, disclosure, strandId,
628
+ peerId: peerId ?? localPeerId, peerSignature: peerSignature ?? null, nowMs: nowMs ?? Date.now(),
629
+ validationKey: validationKey ?? null, validationSignature: validationSignature ?? null,
630
+ });
631
+ log('Recorded formation usage: token=%s strand=%s (use #%d)', token, strandId, useNumber);
632
+ return useNumber;
633
+ }
634
+ /** Parameterised `FormationUsage` insert shared by redeem + record paths. */
635
+ async execFormationUsageInsert(opts) {
636
+ // Derive `context.Now` through the same `canonicalDatetime` transform that
637
+ // produced the stored `ExpiresAt`, so the deferred CHECK's `FI.ExpiresAt >
638
+ // context.Now` compares two byte-identical engine-`datetime` strings. The
639
+ // previous `new Date(nowMs).toISOString()` form differed only by a trailing
640
+ // `.000Z` (the engine `datetime()` separator is `T`, not a space), which never
641
+ // flipped the strict `>` against a second-granular `ExpiresAt` — so this is a
642
+ // robustness/consistency change, matching the strand layer's `consumeInvite`,
643
+ // not a fix for an observable mis-ordering.
644
+ const nowCanonical = await canonicalDatetime(this.db, opts.nowMs);
645
+ await this.db.exec(`
646
+ insert into CadreControl.FormationUsage (Token, UseNumber, Disclosure, StrandId)
647
+ with context PeerId = ?, PeerSignature = ?, Now = ?, ValidationKey = ?, ValidationSignature = ?
648
+ values (?, ?, ?, ?)
649
+ `, [
650
+ opts.peerId, opts.peerSignature, nowCanonical,
651
+ opts.validationKey, opts.validationSignature,
652
+ opts.token, opts.useNumber, opts.disclosure, opts.strandId,
653
+ ]);
654
+ }
655
+ /**
656
+ * Read a `FormationInvite` row by token, or null when absent. `expiresAtMs` is
657
+ * the parsed epoch-ms of the stored `datetime` (null when the invite never
658
+ * expires); the caller compares it against the wall clock for freshness.
659
+ */
660
+ async queryFormationInvite(token) {
661
+ this.ensureInitialized();
662
+ for await (const row of this.db.eval('select Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId from CadreControl.FormationInvite where Token = ?', [token])) {
663
+ const expiresAt = row.ExpiresAt;
664
+ const expiresAtMs = expiresAt === null || expiresAt === undefined
665
+ ? null
666
+ : parseStoredDatetimeMs(expiresAt);
667
+ return {
668
+ token: row.Token,
669
+ sAppId: row.sAppId,
670
+ expiresAtMs: expiresAtMs !== null && Number.isNaN(expiresAtMs) ? null : expiresAtMs,
671
+ totalUses: row.TotalUses ?? null,
672
+ validationUrl: row.ValidationUrl ?? null,
673
+ strandId: row.StrandId ?? null,
674
+ };
675
+ }
676
+ return null;
677
+ }
678
+ /**
679
+ * Count `FormationUsage` rows recorded against a token (uses consumed so far).
680
+ */
681
+ async countFormationUsage(token) {
682
+ this.ensureInitialized();
683
+ for await (const row of this.db.eval('select count(1) as Count from CadreControl.FormationUsage where Token = ?', [token])) {
684
+ return row.Count ?? 0;
685
+ }
686
+ return 0;
687
+ }
688
+ /** Next `UseNumber` for a token = max(existing)+1, per the `Monotonic` constraint. */
689
+ async nextUseNumber(token) {
690
+ for await (const row of this.db.eval('select coalesce(max(UseNumber), 0) as MaxUse from CadreControl.FormationUsage where Token = ?', [token])) {
691
+ return row.MaxUse + 1;
692
+ }
693
+ return 1;
694
+ }
282
695
  /**
283
696
  * Close the database and cleanup resources
284
697
  */
@@ -288,7 +701,7 @@ export class ControlDatabase {
288
701
  this.collectionFactory = null;
289
702
  }
290
703
  if (this.db) {
291
- this.db.close();
704
+ void this.db.close();
292
705
  this.db = null;
293
706
  }
294
707
  this.initialized = false;