@serfab/cadre-core 1.7.0 → 1.9.0

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