@serfab/cadre-core 1.17.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +3 -2
  2. package/dist/cadre-invite-protocol.d.ts +35 -13
  3. package/dist/cadre-invite-protocol.js +90 -25
  4. package/dist/cadre-invite-protocol.js.map +1 -1
  5. package/dist/cadre-node.d.ts +586 -255
  6. package/dist/cadre-node.js +1182 -566
  7. package/dist/cadre-node.js.map +1 -1
  8. package/dist/control-cohort.d.ts +66 -9
  9. package/dist/control-cohort.js +67 -9
  10. package/dist/control-cohort.js.map +1 -1
  11. package/dist/control-database.d.ts +451 -193
  12. package/dist/control-database.js +701 -359
  13. package/dist/control-database.js.map +1 -1
  14. package/dist/control-formation-recorder.d.ts +46 -43
  15. package/dist/control-formation-recorder.js +77 -78
  16. package/dist/control-formation-recorder.js.map +1 -1
  17. package/dist/control-protocol-guard.d.ts +6 -0
  18. package/dist/control-protocol-guard.js +14 -2
  19. package/dist/control-protocol-guard.js.map +1 -1
  20. package/dist/control-schema-version.d.ts +48 -31
  21. package/dist/control-schema-version.js +67 -45
  22. package/dist/control-schema-version.js.map +1 -1
  23. package/dist/control-schema.d.ts +8 -8
  24. package/dist/control-schema.js +16 -16
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-write-retry.d.ts +42 -7
  27. package/dist/control-write-retry.js +87 -19
  28. package/dist/control-write-retry.js.map +1 -1
  29. package/dist/enrolled-machine-store.d.ts +3 -3
  30. package/dist/enrolled-machine-store.js +3 -3
  31. package/dist/formation-token.d.ts +48 -0
  32. package/dist/formation-token.js +26 -0
  33. package/dist/formation-token.js.map +1 -0
  34. package/dist/index.d.ts +15 -14
  35. package/dist/index.js +17 -14
  36. package/dist/index.js.map +1 -1
  37. package/dist/joined-strand-store.d.ts +26 -9
  38. package/dist/joined-strand-store.js +63 -24
  39. package/dist/joined-strand-store.js.map +1 -1
  40. package/dist/link-budget.d.ts +9 -7
  41. package/dist/link-budget.js +9 -7
  42. package/dist/link-budget.js.map +1 -1
  43. package/dist/member-redemption.d.ts +15 -9
  44. package/dist/member-redemption.js +13 -8
  45. package/dist/member-redemption.js.map +1 -1
  46. package/dist/membership-view.d.ts +91 -0
  47. package/dist/membership-view.js +110 -0
  48. package/dist/membership-view.js.map +1 -0
  49. package/dist/owner-grant-protocol.d.ts +11 -7
  50. package/dist/owner-grant-protocol.js +31 -17
  51. package/dist/owner-grant-protocol.js.map +1 -1
  52. package/dist/peer-addr-book.d.ts +10 -1
  53. package/dist/peer-addr-book.js +4 -3
  54. package/dist/peer-addr-book.js.map +1 -1
  55. package/dist/peer-join-backfill.d.ts +96 -30
  56. package/dist/peer-join-backfill.js +272 -128
  57. package/dist/peer-join-backfill.js.map +1 -1
  58. package/dist/pending-join-runner.d.ts +48 -18
  59. package/dist/pending-join-runner.js +74 -56
  60. package/dist/pending-join-runner.js.map +1 -1
  61. package/dist/seed-bootstrap.d.ts +47 -40
  62. package/dist/seed-bootstrap.js +66 -61
  63. package/dist/seed-bootstrap.js.map +1 -1
  64. package/dist/self-address-update.d.ts +13 -0
  65. package/dist/self-address-update.js +19 -0
  66. package/dist/self-address-update.js.map +1 -0
  67. package/dist/strand-database.d.ts +23 -2
  68. package/dist/strand-database.js +26 -6
  69. package/dist/strand-database.js.map +1 -1
  70. package/dist/strand-first-sync-gate.d.ts +176 -89
  71. package/dist/strand-first-sync-gate.js +288 -122
  72. package/dist/strand-first-sync-gate.js.map +1 -1
  73. package/dist/strand-formation-deadlines.d.ts +9 -9
  74. package/dist/strand-formation-deadlines.js +9 -9
  75. package/dist/strand-formation-manager.d.ts +23 -17
  76. package/dist/strand-formation-manager.js +46 -44
  77. package/dist/strand-formation-manager.js.map +1 -1
  78. package/dist/strand-formation-protocol.d.ts +5 -8
  79. package/dist/strand-formation-protocol.js +101 -16
  80. package/dist/strand-formation-protocol.js.map +1 -1
  81. package/dist/strand-instance-manager.d.ts +26 -17
  82. package/dist/strand-instance-manager.js +119 -50
  83. package/dist/strand-instance-manager.js.map +1 -1
  84. package/dist/strand-membership-reconciler.d.ts +16 -13
  85. package/dist/strand-membership-reconciler.js +28 -22
  86. package/dist/strand-membership-reconciler.js.map +1 -1
  87. package/dist/strand-membership-writer.d.ts +40 -28
  88. package/dist/strand-membership-writer.js +212 -153
  89. package/dist/strand-membership-writer.js.map +1 -1
  90. package/dist/strand-move.js +5 -2
  91. package/dist/strand-move.js.map +1 -1
  92. package/dist/strand-revocation-enforcer.d.ts +134 -60
  93. package/dist/strand-revocation-enforcer.js +144 -71
  94. package/dist/strand-revocation-enforcer.js.map +1 -1
  95. package/dist/strand-solicitation.d.ts +50 -39
  96. package/dist/strand-solicitation.js +10 -3
  97. package/dist/strand-solicitation.js.map +1 -1
  98. package/dist/strand-watcher.d.ts +80 -13
  99. package/dist/strand-watcher.js +152 -48
  100. package/dist/strand-watcher.js.map +1 -1
  101. package/dist/table-change-watch.d.ts +63 -0
  102. package/dist/table-change-watch.js +209 -0
  103. package/dist/table-change-watch.js.map +1 -0
  104. package/dist/timeout-scheduler.d.ts +4 -3
  105. package/dist/timeout-scheduler.js +4 -3
  106. package/dist/timeout-scheduler.js.map +1 -1
  107. package/dist/types.d.ts +90 -49
  108. package/dist/types.js +4 -4
  109. package/dist/types.js.map +1 -1
  110. package/package.json +8 -8
  111. package/src/cadre-invite-protocol.ts +119 -31
  112. package/src/cadre-node.ts +1289 -588
  113. package/src/control-cohort.ts +86 -9
  114. package/src/control-database.ts +848 -403
  115. package/src/control-formation-recorder.ts +359 -353
  116. package/src/control-protocol-guard.ts +16 -2
  117. package/src/control-schema-version.ts +101 -51
  118. package/src/control-schema.ts +16 -16
  119. package/src/control-write-retry.ts +91 -19
  120. package/src/delegate-admission.ts +351 -351
  121. package/src/enrolled-machine-store.ts +3 -3
  122. package/src/formation-token.ts +63 -0
  123. package/src/index.ts +30 -18
  124. package/src/joined-strand-store.ts +69 -24
  125. package/src/link-budget.ts +9 -7
  126. package/src/member-redemption.ts +20 -13
  127. package/src/membership-view.ts +144 -0
  128. package/src/owner-grant-protocol.ts +33 -18
  129. package/src/peer-addr-book.ts +4 -3
  130. package/src/peer-join-backfill.ts +961 -761
  131. package/src/pending-join-runner.ts +76 -53
  132. package/src/seed-bootstrap.ts +72 -67
  133. package/src/self-address-update.ts +19 -0
  134. package/src/strand-database.ts +352 -322
  135. package/src/strand-first-sync-gate.ts +334 -134
  136. package/src/strand-formation-deadlines.ts +227 -227
  137. package/src/strand-formation-manager.ts +731 -725
  138. package/src/strand-formation-protocol.ts +122 -24
  139. package/src/strand-instance-manager.ts +2092 -2026
  140. package/src/strand-membership-reconciler.ts +31 -25
  141. package/src/strand-membership-writer.ts +2093 -2019
  142. package/src/strand-move.ts +5 -2
  143. package/src/strand-revocation-enforcer.ts +740 -654
  144. package/src/strand-solicitation.ts +61 -34
  145. package/src/strand-watcher.ts +175 -56
  146. package/src/table-change-watch.ts +285 -0
  147. package/src/timeout-scheduler.ts +29 -28
  148. package/src/types.ts +89 -51
@@ -1,353 +1,359 @@
1
- import debug from 'debug';
2
- import { FormationAbortedError, InvitationExhaustedError, type ControlDatabase } from './control-database.js';
3
- import { mintStrandId } from './strand-id.js';
4
- import {
5
- createHttpFormationApprover,
6
- verifyFormationApproval,
7
- FormationApprovalError,
8
- type FormationApprover,
9
- type FormationApproval,
10
- type FormationApprovalRequest
11
- } from './formation-approval.js';
12
- import type {
13
- AuthorizedFormationUsage,
14
- FormationUsageParams,
15
- FormationUsageRecorder,
16
- ResolvedHostStrand
17
- } from './strand-solicitation.js';
18
- import type { OpenInvitation } from './types.js';
19
-
20
- const log = debug('sereus:cadre:formation-recorder');
21
-
22
- /** Far-future sentinel for an invitation that never expires (max valid JS Date). */
23
- const NEVER_EXPIRES = new Date(8640000000000000);
24
-
25
- /**
26
- * {@link FormationUsageRecorder} backed by the real `CadreControl` tables.
27
- *
28
- * It reads `FormationInvite` / `FormationUsage` to answer token-validity and
29
- * usage questions, and writes the consent row that records a redemption. Two
30
- * provisioning shapes are supported, keyed on whether the invite binds a host strand:
31
- *
32
- * - **Bound (provision-then-record):** the host strand already exists (owner-signed
33
- * up front and named by the invite's `StrandId`), so {@link resolveStrand} reports it
34
- * and {@link authorizeUsage} then its `record()` (or {@link recordUsage}, both at once)
35
- * writes the consent row against that pre-existing strand
36
- * (record-only) rather than inserting a new `Strand`.
37
- * - **Unbound (responder-provisions):** the invite carries no `StrandId`, so
38
- * {@link provisionAndRecord} mints a fresh strand and records consent against it
39
- * ATOMICALLY (one `FormationUsage` row), closing the single-use hole the older
40
- * never-record fallback left open.
41
- *
42
- * Every `CadreNode`'s formation responder uses it unless the embedder passes another
43
- * recorder to `initializeStrandSolicitation`.
44
- *
45
- * Usage accounting follows the schema's `FormationUsage.Authorized` semantics:
46
- * a null `TotalUses` means unlimited uses; otherwise the invite is "used up"
47
- * once the recorded usage count reaches `TotalUses`.
48
- *
49
- * When the invite carries a `ValidationUrl`, both write paths first obtain an outside
50
- * approval ({@link obtainApproval}) — the recorder is the one place where the nonce that is
51
- * SIGNED and the nonce that is INSERTED are trivially the same value, since it also performs
52
- * the write. That makes this class do network I/O; failures surface as
53
- * {@link FormationApprovalError}s the manager maps to protocol rejection reasons. The bound
54
- * path is split in two ({@link authorizeUsage}, then the returned `record()`) so the manager
55
- * can issue the joiner's membership pass between the approval and the write; the handle
56
- * carries the approved fields across, which keeps the signed and inserted nonce the same.
57
- */
58
- export class ControlFormationUsageRecorder implements FormationUsageRecorder {
59
- private readonly approver: FormationApprover;
60
-
61
- /**
62
- * `approver` defaults to the real HTTP hook client — deliberately ON: `CadreNode` builds this
63
- * recorder for every node's responder with no options, so an opt-in approver would leave
64
- * every real deployment unable to redeem a `ValidationUrl`-bearing invite. Tests inject a fake.
65
- */
66
- constructor(
67
- private readonly controlDatabase: ControlDatabase,
68
- options?: { approver?: FormationApprover }
69
- ) {
70
- this.approver = options?.approver ?? createHttpFormationApprover();
71
- }
72
-
73
- /** A token is valid when a matching, unexpired `FormationInvite` exists. */
74
- async isTokenValid(token: string): Promise<{ valid: boolean; reason?: 'unknown' | 'expired'; invitation?: OpenInvitation }> {
75
- const invite = await this.controlDatabase.queryFormationInvite(token);
76
- if (!invite) {
77
- return { valid: false, reason: 'unknown' };
78
- }
79
- if (invite.expiresAtMs !== null && invite.expiresAtMs <= Date.now()) {
80
- log('Token expired: %s', token);
81
- return { valid: false, reason: 'expired' };
82
- }
83
- return {
84
- valid: true,
85
- invitation: {
86
- token: invite.token,
87
- sAppId: invite.sAppId,
88
- expiration: invite.expiresAtMs !== null ? new Date(invite.expiresAtMs) : NEVER_EXPIRES,
89
- bootstrap: [],
90
- },
91
- };
92
- }
93
-
94
- /**
95
- * A token is "used" when its recorded usage count has reached the invite's
96
- * `TotalUses`. A null `TotalUses` (unlimited) is never used up; an unknown
97
- * token is reported not-used (validity is handled by {@link isTokenValid}).
98
- */
99
- async isTokenUsed(token: string): Promise<boolean> {
100
- const invite = await this.controlDatabase.queryFormationInvite(token);
101
- if (!invite || invite.totalUses === null) {
102
- return false;
103
- }
104
- const uses = await this.controlDatabase.countFormationUsage(token);
105
- return uses >= invite.totalUses;
106
- }
107
-
108
- /**
109
- * Any `FormationInvite` row still unexpired and not fully consumed — the
110
- * durable half of the control-network connection gate's "does this node
111
- * expect a stranger?" question. Survives a restart and sees invites
112
- * replicated in from sibling nodes of the same cadre.
113
- */
114
- async hasOutstandingInvitation(): Promise<boolean> {
115
- return await this.controlDatabase.hasOutstandingFormationInvite();
116
- }
117
-
118
- /**
119
- * Obtain the approval material for ONE redemption, when the invite demands it.
120
- *
121
- * `validationUrl === null` → `{}`: no approval required. The `usageStampId` nonce is
122
- * ALWAYS supplied by the caller — the JOINER mints it, signs its own consent over it, and
123
- * sends it in the contact message — so the approver signs over the identical nonce in both
124
- * paths. Two local pre-checks run before anything is written:
125
- *
126
- * - {@link verifyFormationApproval} — did the hook sign the exact fields we hold?
127
- * - {@link ControlDatabase.queryValidationKeyStampId} — is the approval's key enrolled?
128
- *
129
- * Both pre-checks exist purely for legibility — they turn a bad approval into a named
130
- * {@link FormationApprovalError} instead of an opaque `CHECK constraint failed: Authorized`
131
- * at commit. The database re-verifies against the STORED `ValidationKey` row and remains
132
- * the security authority; do not "simplify" the database check away in favour of these.
133
- */
134
- private async obtainApproval(
135
- request: Omit<FormationApprovalRequest, 'validationUrl'> & { validationUrl: string | null },
136
- signal?: AbortSignal
137
- ): Promise<{ validationKey?: string; validationSignature?: string }> {
138
- const { validationUrl, ...fields } = request;
139
- if (validationUrl === null) {
140
- return {};
141
- }
142
- if (signal?.aborted) {
143
- throw new FormationAbortedError(fields.token, 'approval');
144
- }
145
- const fullRequest: FormationApprovalRequest = { ...fields, validationUrl };
146
- const approval = await this.askApprover(fullRequest, signal);
147
- if (!verifyFormationApproval(fullRequest, approval)) {
148
- throw new FormationApprovalError(
149
- 'malformed',
150
- `Approval signature does not verify over this redemption (token ${fields.token})`
151
- );
152
- }
153
- if (await this.controlDatabase.queryValidationKeyStampId(approval.validationKey) === null) {
154
- throw new FormationApprovalError(
155
- 'unenrolled',
156
- 'Approval is signed by a key that is not an enrolled ValidationKey'
157
- );
158
- }
159
- return approval;
160
- }
161
-
162
- /**
163
- * Ask the approver, re-labelling a caller-abort as a {@link FormationAbortedError}.
164
- *
165
- * The HTTP client relays a caller-abort onto its own request and reports it as an
166
- * `unavailable` {@link FormationApprovalError} — which the manager cannot tell from a
167
- * genuinely dead hook, and so maps to a rejection reason and RETURNS. Every other abort on
168
- * this path THROWS, which is what makes the manager rethrow and leave the reply to the
169
- * listener's timeout path; a mid-hook abort belongs in the same class. The approval error
170
- * is kept as `cause` so the transport-level detail is not lost.
171
- */
172
- private async askApprover(
173
- request: FormationApprovalRequest,
174
- signal?: AbortSignal
175
- ): Promise<FormationApproval> {
176
- try {
177
- return await this.approver.requestApproval(request, signal);
178
- } catch (err) {
179
- if (signal?.aborted) {
180
- throw new FormationAbortedError(request.token, 'approval', { cause: err });
181
- }
182
- throw err;
183
- }
184
- }
185
-
186
- /**
187
- * Record consent against an **already-existing** host strand (record-only): the
188
- * single `FormationUsage` insert auto-commits and the deferred `StrandExists`
189
- * CHECK is satisfied by the pre-existing strand. This is the provision-then-record
190
- * commitment — the strand was minted owner-signed up front, so we do NOT
191
- * re-insert it (which would double-insert the same PK). `peerKey` is written as the
192
- * usage `PeerKey`, which BOTH signed digests cover: the joiner's own consent signature
193
- * (`peerSignature`, verified by the schema's `PeerConsented` CHECK) and — when the invite
194
- * carries a `ValidationUrl` — the approver's sign-off, so it is the joiner an approval is
195
- * spent on AND provably the joiner that agreed. Use
196
- * {@link ControlDatabase.redeemInvitation} for the consent-creates-strand path instead.
197
- *
198
- * Authorizes ({@link authorizeUsage}) and writes in one step, for callers with nothing to do
199
- * in between.
200
- */
201
- async recordUsage(params: FormationUsageParams): Promise<void> {
202
- await (await this.authorizeUsage(params)).record();
203
- }
204
-
205
- /**
206
- * Everything {@link recordUsage} does before its write, so the manager can issue the
207
- * joiner's membership pass into the host strand only once the redemption is cleared, and
208
- * spend the token only after that.
209
- *
210
- * Reads the invite first (one extra read per redemption) to learn its `ValidationUrl` and
211
- * seat budget, obtains the approval through {@link obtainApproval} when one is demanded,
212
- * re-checks the abort (the approval call may have been long), and pre-checks the seat
213
- * budget ({@link assertSeatFree}). The returned `record()` closes over the captured fields
214
- * and approval, so the nonce the approver signed is the nonce inserted without the caller
215
- * ever passing it back.
216
- */
217
- async authorizeUsage(params: FormationUsageParams): Promise<AuthorizedFormationUsage> {
218
- const { token, peerKey, peerSignature, usageStampId, strandId, disclosure, signal } = params;
219
- if (signal?.aborted) {
220
- throw new FormationAbortedError(token, 'usage recording');
221
- }
222
- const invite = await this.controlDatabase.queryFormationInvite(token);
223
- // NOTE: a missing invite row reads as "no approval required" here and in
224
- // `provisionAndRecord`, so an invite that vanished between `resolveStrand` and this read
225
- // would be written unapproved. Safe only because the database's `FormationUsage.Authorized`
226
- // CHECK demands a matching `FormationInvite` and rolls the write back regardless; if that
227
- // CHECK ever loosens, reject on `invite === null` instead of defaulting to null.
228
- const approval = await this.obtainApproval({
229
- token, usageStampId, strandId, peerKey, disclosure,
230
- validationUrl: invite?.validationUrl ?? null,
231
- }, signal);
232
- if (signal?.aborted) {
233
- throw new FormationAbortedError(token, 'usage recording');
234
- }
235
- const totalUses = invite?.totalUses ?? null;
236
- await this.assertSeatFree(token, totalUses);
237
- return {
238
- record: async () => {
239
- await this.controlDatabase.recordFormationUsage({
240
- token, strandId, peerKey, peerSignature, usageStampId, disclosure, signal,
241
- totalUses, ...approval,
242
- });
243
- log('Recorded formation usage: token=%s strand=%s', token, strandId);
244
- }
245
- };
246
- }
247
-
248
- /**
249
- * Refuse a redemption whose invite has no seat left, BEFORE anything is written — the
250
- * authoritative check is the one `recordFormationUsage` repeats inside its write lock.
251
- * Catches a same-node rival that took the last seat while this redemption waited on the
252
- * approval hook, which `runSession`'s up-front `isTokenUsed` check could not see.
253
- *
254
- * NOTE: two redemptions that both pass this check within the time one of them takes to
255
- * issue its membership pass still both issue one, and the loser's pass is orphaned
256
- * (expiry-bounded, never handed out). Holding the control write lock across issuance would
257
- * close it, but `lockedWithRetry` re-runs locked bodies on transient failures (a re-run
258
- * would double-issue) and every control write would stall behind a strand-database write.
259
- * If orphaned passes from same-node races ever matter, reserve the seat before issuance.
260
- */
261
- private async assertSeatFree(token: string, totalUses: number | null): Promise<void> {
262
- if (totalUses === null) {
263
- return;
264
- }
265
- const used = await this.controlDatabase.countFormationUsage(token);
266
- if (used >= totalUses) {
267
- throw new InvitationExhaustedError(token, used, totalUses);
268
- }
269
- }
270
-
271
- /**
272
- * Classify the host strand this invite binds to (see {@link ResolvedHostStrand}):
273
- *
274
- * - no invite / no `StrandId` → `unbound` (responder-provisions path).
275
- * - `StrandId` set AND the strand row is present → `bound`, carrying its
276
- * `MemberPrivateKey` (the closed-strand read-gating secret) for delivery to a
277
- * validated invitee.
278
- * - `StrandId` set but the strand row is absent → `missing` (the host strand has not
279
- * converged on this responder yet); the manager rejects cleanly instead of recording
280
- * usage against a non-existent strand, which would fail the deferred `StrandExists`
281
- * CHECK at commit and drop the result frame.
282
- */
283
- async resolveStrand(token: string): Promise<ResolvedHostStrand> {
284
- const invite = await this.controlDatabase.queryFormationInvite(token);
285
- if (!invite || !invite.strandId) {
286
- return { kind: 'unbound' };
287
- }
288
- const strand = await this.controlDatabase.queryStrand(invite.strandId);
289
- if (!strand) {
290
- return { kind: 'missing', strandId: invite.strandId };
291
- }
292
- return {
293
- kind: 'bound',
294
- strandId: invite.strandId,
295
- memberPrivateKey: strand.MemberPrivateKey ?? null,
296
- };
297
- }
298
-
299
- /**
300
- * Provision a NEW strand for an UNBOUND invite and record consent against it in ONE
301
- * transaction (the responder-provisions fallback, now single-use-enforced).
302
- *
303
- * Mints a fresh, globally-unique strand id with {@link mintStrandId} — an
304
- * unguessable CSPRNG id, and one `strand-id.ts` has already checked is usable as a
305
- * storage scope key and network name — then delegates to
306
- * {@link ControlDatabase.redeemInvitation}, whose
307
- * single `begin … commit` inserts the consent-authorized `Strand` row AND the matching
308
- * `FormationUsage` row together (both deferred CHECKs see both rows at commit). That one
309
- * `FormationUsage` row makes the unbound redemption single-use exactly like the bound
310
- * path: the next redemption of a `TotalUses:1` invite sees `count 1 >= 1` and is rejected.
311
- *
312
- * The strand is open (`'o'`) — an unbound responder-provisioned strand has no membership
313
- * key — so the returned `memberPrivateKey` is null. `sAppId` is accepted for parity/future
314
- * use; `redeemInvitation` does not currently thread it into the `Strand` row.
315
- *
316
- * A concurrent redemption of the same single-use invite still THROWS for the loser — the
317
- * manager maps that to a clean protocol rejection (it never lets the dropped insert close
318
- * the stream silently): the local write queue serializes the two writes, so the loser's
319
- * seat check reads the winner's committed row against the cap and is refused as a named
320
- * `InvitationExhaustedError`. A CROSS-node race is not a collision to retry at all — each
321
- * redemption writes under its own `UsageStampId`, both rows land and survive convergence,
322
- * and the cap can over-admit by the number of concurrent redeemers. That over-admission is
323
- * the accepted trade (visible in the append-only record, reversible by owner-gated
324
- * removal), chosen over a fought-over shared key whose failure mode was the silent loss of
325
- * a consented join.
326
- */
327
- async provisionAndRecord(params: {
328
- token: string;
329
- peerKey: string;
330
- peerSignature: string;
331
- usageStampId: string;
332
- sAppId: string;
333
- disclosure: string;
334
- signal?: AbortSignal;
335
- }): Promise<{ strandId: string; memberPrivateKey: string | null }> {
336
- const { token, peerKey, peerSignature, usageStampId, disclosure, signal } = params;
337
- if (signal?.aborted) {
338
- throw new FormationAbortedError(token, 'redemption');
339
- }
340
- const strandId = mintStrandId();
341
- const invite = await this.controlDatabase.queryFormationInvite(token);
342
- const approval = await this.obtainApproval({
343
- token, usageStampId, strandId, peerKey, disclosure,
344
- validationUrl: invite?.validationUrl ?? null,
345
- }, signal);
346
- await this.controlDatabase.redeemInvitation({
347
- token, strandId, peerKey, peerSignature, usageStampId, disclosure, signal,
348
- totalUses: invite?.totalUses ?? null, ...approval,
349
- });
350
- log('Provisioned + recorded unbound strand: token=%s strand=%s', token, strandId);
351
- return { strandId, memberPrivateKey: null };
352
- }
353
- }
1
+ import debug from 'debug';
2
+ import { FormationAbortedError, InvitationExhaustedError, type ControlDatabase } from './control-database.js';
3
+ import { mintStrandId } from './strand-id.js';
4
+ import {
5
+ createHttpFormationApprover,
6
+ verifyFormationApproval,
7
+ FormationApprovalError,
8
+ type FormationApprover,
9
+ type FormationApproval,
10
+ type FormationApprovalRequest
11
+ } from './formation-approval.js';
12
+ import type {
13
+ AuthorizedFormationUsage,
14
+ BoundHostStrand,
15
+ FormationUsageParams,
16
+ FormationUsageRecorder,
17
+ ResolvedHostStrand
18
+ } from './strand-solicitation.js';
19
+ import { isInviteExpired, type FormationInviteFacts, type FormationTokenRead } from './formation-token.js';
20
+
21
+ const log = debug('sereus:cadre:formation-recorder');
22
+
23
+ /**
24
+ * {@link FormationUsageRecorder} backed by the real `CadreControl` tables.
25
+ *
26
+ * It reads a session's token once ({@link readToken}: the `FormationInvite` row and its
27
+ * `FormationUsage` count), and writes the consent row that records a redemption from that
28
+ * read. Two provisioning shapes are supported, keyed on whether the invite binds a host strand:
29
+ *
30
+ * - **Bound (provision-then-record):** the host strand already exists (owner-signed
31
+ * up front and named by the invite's `StrandId`), so {@link resolveStrand} reports it
32
+ * and {@link authorizeUsage} then its `record()` (or {@link recordUsage}, both at once)
33
+ * writes the consent row against that pre-existing strand
34
+ * (record-only) rather than inserting a new `Strand`.
35
+ * - **Unbound (responder-provisions):** the invite carries no `StrandId`, so
36
+ * {@link provisionAndRecord} mints a fresh strand and records consent against it
37
+ * ATOMICALLY (one `FormationUsage` row), closing the single-use hole the older
38
+ * never-record fallback left open.
39
+ *
40
+ * Every `CadreNode`'s formation responder uses it unless the embedder passes another
41
+ * recorder to `initializeStrandSolicitation`.
42
+ *
43
+ * Usage accounting follows the schema's `FormationUsage.Authorized` semantics:
44
+ * a null `TotalUses` means unlimited uses; otherwise the invite is "used up"
45
+ * once the recorded usage count reaches `TotalUses`.
46
+ *
47
+ * When the invite carries a `ValidationUrl`, both write paths first obtain an outside
48
+ * approval ({@link obtainApproval}) — the recorder is the one place where the nonce that is
49
+ * SIGNED and the nonce that is INSERTED are trivially the same value, since it also performs
50
+ * the write. That makes this class do network I/O; failures surface as
51
+ * {@link FormationApprovalError}s the manager maps to protocol rejection reasons. The bound
52
+ * path is split in two ({@link authorizeUsage}, then the returned `record()`) so the manager
53
+ * can issue the joiner's membership pass between the approval and the write; the handle
54
+ * carries the approved fields across, which keeps the signed and inserted nonce the same.
55
+ */
56
+ export class ControlFormationUsageRecorder implements FormationUsageRecorder {
57
+ private readonly approver: FormationApprover;
58
+
59
+ /**
60
+ * `approver` defaults to the real HTTP hook client — deliberately ON: `CadreNode` builds this
61
+ * recorder for every node's responder with no options, so an opt-in approver would leave
62
+ * every real deployment unable to redeem a `ValidationUrl`-bearing invite. Tests inject a fake.
63
+ */
64
+ constructor(
65
+ private readonly controlDatabase: ControlDatabase,
66
+ options?: { approver?: FormationApprover }
67
+ ) {
68
+ this.approver = options?.approver ?? createHttpFormationApprover();
69
+ }
70
+
71
+ /**
72
+ * One `FormationInvite` read, then one `FormationUsage` count only when the invite is
73
+ * metered (`TotalUses` set) and unexpired: an unknown, expired or unlimited token has no
74
+ * seat to count. This early count refuses a spent token before anything costly (the outside
75
+ * approval call, the strand-database write that issues the membership invite); the count
76
+ * inside the write lock decides.
77
+ */
78
+ async readToken(token: string): Promise<FormationTokenRead> {
79
+ const invite = await this.controlDatabase.queryFormationInvite(token);
80
+ const metered = invite !== null && invite.totalUses !== null && !isInviteExpired(invite, Date.now());
81
+ return {
82
+ token,
83
+ invite,
84
+ usesRecorded: metered ? await this.controlDatabase.countFormationUsage(token) : null,
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Any `FormationInvite` row still unexpired and not fully consumed — the
90
+ * durable half of the control-network connection gate's "does this node
91
+ * expect a stranger?" question. Survives a restart and sees invites
92
+ * replicated in from sibling nodes of the same cadre.
93
+ */
94
+ async hasOutstandingInvitation(): Promise<boolean> {
95
+ return await this.controlDatabase.hasOutstandingFormationInvite();
96
+ }
97
+
98
+ /**
99
+ * Obtain the approval material for ONE redemption, when the invite demands it.
100
+ *
101
+ * `validationUrl === null` → `{}`: no approval required. The `usageStampId` nonce is
102
+ * ALWAYS supplied by the caller — the JOINER mints it, signs its own consent over it, and
103
+ * sends it in the contact message — so the approver signs over the identical nonce in both
104
+ * paths. Two local pre-checks run before anything is written:
105
+ *
106
+ * - {@link verifyFormationApproval} — did the hook sign the exact fields we hold?
107
+ * - {@link ControlDatabase.queryValidationKeyStampId} — is the approval's key enrolled?
108
+ *
109
+ * Both pre-checks exist purely for legibility — they turn a bad approval into a named
110
+ * {@link FormationApprovalError} instead of an opaque `CHECK constraint failed: Authorized`
111
+ * at commit. The database re-verifies against the STORED `ValidationKey` row and remains
112
+ * the security authority; do not "simplify" the database check away in favour of these.
113
+ */
114
+ private async obtainApproval(
115
+ request: Omit<FormationApprovalRequest, 'validationUrl'> & { validationUrl: string | null },
116
+ signal?: AbortSignal
117
+ ): Promise<{ validationKey?: string; validationSignature?: string }> {
118
+ const { validationUrl, ...fields } = request;
119
+ if (validationUrl === null) {
120
+ return {};
121
+ }
122
+ if (signal?.aborted) {
123
+ throw new FormationAbortedError(fields.token, 'approval');
124
+ }
125
+ const fullRequest: FormationApprovalRequest = { ...fields, validationUrl };
126
+ const approval = await this.askApprover(fullRequest, signal);
127
+ if (!verifyFormationApproval(fullRequest, approval)) {
128
+ throw new FormationApprovalError(
129
+ 'malformed',
130
+ `Approval signature does not verify over this redemption (token ${fields.token})`
131
+ );
132
+ }
133
+ if (await this.controlDatabase.queryValidationKeyStampId(approval.validationKey) === null) {
134
+ throw new FormationApprovalError(
135
+ 'unenrolled',
136
+ 'Approval is signed by a key that is not an enrolled ValidationKey'
137
+ );
138
+ }
139
+ return approval;
140
+ }
141
+
142
+ /**
143
+ * Ask the approver, re-labelling a caller-abort as a {@link FormationAbortedError}.
144
+ *
145
+ * The HTTP client relays a caller-abort onto its own request and reports it as an
146
+ * `unavailable` {@link FormationApprovalError} — which the manager cannot tell from a
147
+ * genuinely dead hook, and so maps to a rejection reason and RETURNS. Every other abort on
148
+ * this path THROWS, which is what makes the manager rethrow and leave the reply to the
149
+ * listener's timeout path; a mid-hook abort belongs in the same class. The approval error
150
+ * is kept as `cause` so the transport-level detail is not lost.
151
+ */
152
+ private async askApprover(
153
+ request: FormationApprovalRequest,
154
+ signal?: AbortSignal
155
+ ): Promise<FormationApproval> {
156
+ try {
157
+ return await this.approver.requestApproval(request, signal);
158
+ } catch (err) {
159
+ if (signal?.aborted) {
160
+ throw new FormationAbortedError(request.token, 'approval', { cause: err });
161
+ }
162
+ throw err;
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Record consent against an **already-existing** host strand (record-only): the
168
+ * single `FormationUsage` insert auto-commits and the deferred `StrandExists`
169
+ * CHECK is satisfied by the pre-existing strand. This is the provision-then-record
170
+ * commitment — the strand was minted owner-signed up front, so we do NOT
171
+ * re-insert it (which would double-insert the same PK). `peerKey` is written as the
172
+ * usage `PeerKey`, which BOTH signed digests cover: the joiner's own consent signature
173
+ * (`peerSignature`, verified by the schema's `PeerConsented` CHECK) and — when the invite
174
+ * carries a `ValidationUrl` — the approver's sign-off, so it is the joiner an approval is
175
+ * spent on AND provably the joiner that agreed. Use
176
+ * {@link ControlDatabase.redeemInvitation} for the consent-creates-strand path instead.
177
+ *
178
+ * Reads the invite for itself (it is handed no session read) and the strand's stamp inside
179
+ * `recordFormationUsage`; otherwise authorizes as {@link authorizeUsage} does and writes in
180
+ * one step, for callers with nothing to do in between.
181
+ */
182
+ async recordUsage(params: FormationUsageParams): Promise<void> {
183
+ if (params.signal?.aborted) {
184
+ throw new FormationAbortedError(params.token, 'usage recording');
185
+ }
186
+ const invite = await this.controlDatabase.queryFormationInvite(params.token);
187
+ await (await this.authorize(params, invite, undefined)).record();
188
+ }
189
+
190
+ /**
191
+ * Everything {@link recordUsage} does before its write, so the manager can issue the
192
+ * joiner's membership pass into the host strand only once the redemption is cleared, and
193
+ * spend the token only after that. Takes the invite's `ValidationUrl` and seat budget from
194
+ * the session's `read`, and the host strand's stamp from `host`, so it reads neither again.
195
+ */
196
+ async authorizeUsage(
197
+ params: FormationUsageParams,
198
+ read: FormationTokenRead,
199
+ host: BoundHostStrand
200
+ ): Promise<AuthorizedFormationUsage> {
201
+ return await this.authorize(params, read.invite, host.strandStampId);
202
+ }
203
+
204
+ /**
205
+ * Obtain the approval through {@link obtainApproval} when `invite` demands one, re-check the
206
+ * abort (the approval call may have been long), and after an obtained approval re-check the
207
+ * seat budget ({@link assertSeatFree}). The returned `record()` closes over the captured
208
+ * fields and approval, so the nonce the approver signed is the nonce inserted without the
209
+ * caller ever passing it back. `strandStampId` undefined makes `recordFormationUsage` read it.
210
+ */
211
+ private async authorize(
212
+ params: FormationUsageParams,
213
+ invite: FormationInviteFacts | null,
214
+ strandStampId: string | undefined
215
+ ): Promise<AuthorizedFormationUsage> {
216
+ const { token, peerKey, peerSignature, usageStampId, strandId, disclosure, signal } = params;
217
+ if (signal?.aborted) {
218
+ throw new FormationAbortedError(token, 'usage recording');
219
+ }
220
+ // NOTE: a missing invite row reads as "no approval required" here and in
221
+ // `provisionAndRecord`, so an invite that was absent from the session's read (or vanished
222
+ // before `recordUsage`'s) would be written unapproved. Safe only because the database's
223
+ // `FormationUsage.Authorized` CHECK demands a matching `FormationInvite` and rolls the write
224
+ // back regardless; if that CHECK ever loosens, reject on `invite === null` instead of
225
+ // defaulting to null.
226
+ const validationUrl = invite?.validationUrl ?? null;
227
+ const approval = await this.obtainApproval({
228
+ token, usageStampId, strandId, peerKey, disclosure, validationUrl,
229
+ }, signal);
230
+ if (signal?.aborted) {
231
+ throw new FormationAbortedError(token, 'usage recording');
232
+ }
233
+ const totalUses = invite?.totalUses ?? null;
234
+ if (validationUrl !== null) {
235
+ await this.assertSeatFree(token, totalUses);
236
+ }
237
+ return {
238
+ record: async () => {
239
+ await this.controlDatabase.recordFormationUsage({
240
+ token, strandId, peerKey, peerSignature, usageStampId, disclosure, signal,
241
+ totalUses, strandStampId, ...approval,
242
+ });
243
+ log('Recorded formation usage: token=%s strand=%s', token, strandId);
244
+ }
245
+ };
246
+ }
247
+
248
+ /**
249
+ * Refuse a redemption whose invite lost its last seat while this redemption waited on its
250
+ * outside approval, BEFORE anything is written — the authoritative check is the one
251
+ * `recordFormationUsage` repeats inside its write lock. Runs only after an obtained approval:
252
+ * that call is the one long wait between the session's early count (`readToken`) and the
253
+ * membership pass, in which a same-node rival could take the seat unseen.
254
+ *
255
+ * NOTE: two redemptions that both pass the last count before issuance (this one after an
256
+ * approval, `readToken`'s without one) within the time one of them takes to issue its
257
+ * membership pass still both issue one, and the loser's pass is orphaned (expiry-bounded,
258
+ * never handed out). Holding the control write lock across issuance would close it, but
259
+ * `lockedWithRetry` re-runs locked bodies on transient failures (a re-run would double-issue)
260
+ * and every control write would stall behind a strand-database write. If orphaned passes from
261
+ * same-node races ever matter, reserve the seat before issuance.
262
+ */
263
+ private async assertSeatFree(token: string, totalUses: number | null): Promise<void> {
264
+ if (totalUses === null) {
265
+ return;
266
+ }
267
+ const used = await this.controlDatabase.countFormationUsage(token);
268
+ if (used >= totalUses) {
269
+ throw new InvitationExhaustedError(token, used, totalUses);
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Classify the host strand the read invite binds to (see {@link ResolvedHostStrand}), with
275
+ * one `Strand` read and no invite read:
276
+ *
277
+ * - no invite / no `StrandId` → `unbound` (responder-provisions path).
278
+ * - `StrandId` set AND the strand row is present → `bound`, carrying its type, its
279
+ * `StampId` (which the consent row names) and its `MemberPrivateKey` (the closed-strand
280
+ * read-gating secret) for delivery to a validated invitee.
281
+ * - `StrandId` set but the strand row is absent → `missing` (the host strand has not
282
+ * converged on this responder yet); the manager rejects cleanly instead of recording
283
+ * usage against a non-existent strand, which would fail the deferred `StrandExists`
284
+ * CHECK at commit and drop the result frame.
285
+ */
286
+ async resolveStrand(read: FormationTokenRead): Promise<ResolvedHostStrand> {
287
+ const strandId = read.invite?.strandId;
288
+ if (!strandId) {
289
+ return { kind: 'unbound' };
290
+ }
291
+ const strand = await this.controlDatabase.queryStrandWithStamp(strandId);
292
+ if (!strand) {
293
+ return { kind: 'missing', strandId };
294
+ }
295
+ return {
296
+ kind: 'bound',
297
+ strandId,
298
+ strandType: strand.Type,
299
+ strandStampId: strand.StampId,
300
+ memberPrivateKey: strand.MemberPrivateKey ?? null,
301
+ };
302
+ }
303
+
304
+ /**
305
+ * Provision a NEW strand for an UNBOUND invite and record consent against it in ONE
306
+ * transaction (the responder-provisions fallback, now single-use-enforced).
307
+ *
308
+ * Mints a fresh, globally-unique strand id with {@link mintStrandId} — an
309
+ * unguessable CSPRNG id, and one `strand-id.ts` has already checked is usable as a
310
+ * storage scope key and network name — then delegates to
311
+ * {@link ControlDatabase.redeemInvitation}, whose
312
+ * single `begin … commit` inserts the consent-authorized `Strand` row AND the matching
313
+ * `FormationUsage` row together (both deferred CHECKs see both rows at commit). That one
314
+ * `FormationUsage` row makes the unbound redemption single-use exactly like the bound
315
+ * path: the next redemption of a `TotalUses:1` invite sees `count 1 >= 1` and is rejected.
316
+ *
317
+ * The strand is open (`'o'`) — an unbound responder-provisioned strand has no membership
318
+ * key — so the returned `memberPrivateKey` is null. `sAppId` is accepted for parity/future
319
+ * use; `redeemInvitation` does not currently thread it into the `Strand` row. The invite's
320
+ * `ValidationUrl` and seat budget come from the session's `read`.
321
+ *
322
+ * A concurrent redemption of the same single-use invite still THROWS for the loser — the
323
+ * manager maps that to a clean protocol rejection (it never lets the dropped insert close
324
+ * the stream silently): the local write queue serializes the two writes, so the loser's
325
+ * seat check reads the winner's committed row against the cap and is refused as a named
326
+ * `InvitationExhaustedError`. A CROSS-node race is not a collision to retry at all — each
327
+ * redemption writes under its own `UsageStampId`, both rows land and survive convergence,
328
+ * and the cap can over-admit by the number of concurrent redeemers. That over-admission is
329
+ * the accepted trade (visible in the append-only record, reversible by owner-gated
330
+ * removal), chosen over a fought-over shared key whose failure mode was the silent loss of
331
+ * a consented join.
332
+ */
333
+ async provisionAndRecord(params: {
334
+ token: string;
335
+ peerKey: string;
336
+ peerSignature: string;
337
+ usageStampId: string;
338
+ sAppId: string;
339
+ disclosure: string;
340
+ signal?: AbortSignal;
341
+ }, read: FormationTokenRead): Promise<{ strandId: string; memberPrivateKey: string | null }> {
342
+ const { token, peerKey, peerSignature, usageStampId, disclosure, signal } = params;
343
+ if (signal?.aborted) {
344
+ throw new FormationAbortedError(token, 'redemption');
345
+ }
346
+ const strandId = mintStrandId();
347
+ const invite = read.invite;
348
+ const approval = await this.obtainApproval({
349
+ token, usageStampId, strandId, peerKey, disclosure,
350
+ validationUrl: invite?.validationUrl ?? null,
351
+ }, signal);
352
+ await this.controlDatabase.redeemInvitation({
353
+ token, strandId, peerKey, peerSignature, usageStampId, disclosure, signal,
354
+ totalUses: invite?.totalUses ?? null, ...approval,
355
+ });
356
+ log('Provisioned + recorded unbound strand: token=%s strand=%s', token, strandId);
357
+ return { strandId, memberPrivateKey: null };
358
+ }
359
+ }