@serfab/cadre-core 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +255 -255
  2. package/dist/cadre-node.d.ts +203 -28
  3. package/dist/cadre-node.js +445 -84
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-cohort.d.ts +26 -0
  6. package/dist/control-cohort.js +26 -0
  7. package/dist/control-cohort.js.map +1 -1
  8. package/dist/control-database.d.ts +82 -117
  9. package/dist/control-database.js +217 -295
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-formation-recorder.d.ts +8 -7
  12. package/dist/control-formation-recorder.js +8 -7
  13. package/dist/control-formation-recorder.js.map +1 -1
  14. package/dist/control-schema.d.ts +1 -1
  15. package/dist/control-schema.js +789 -774
  16. package/dist/control-schema.js.map +1 -1
  17. package/dist/control-write-retry.d.ts +15 -5
  18. package/dist/control-write-retry.js +19 -18
  19. package/dist/control-write-retry.js.map +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/peer-addr-book.d.ts +92 -0
  24. package/dist/peer-addr-book.js +220 -0
  25. package/dist/peer-addr-book.js.map +1 -0
  26. package/dist/seed-bootstrap.d.ts +7 -0
  27. package/dist/seed-bootstrap.js +15 -13
  28. package/dist/seed-bootstrap.js.map +1 -1
  29. package/dist/strand-cohort.d.ts +4 -37
  30. package/dist/strand-cohort.js +4 -15
  31. package/dist/strand-cohort.js.map +1 -1
  32. package/dist/strand-database.d.ts +11 -16
  33. package/dist/strand-database.js +19 -7
  34. package/dist/strand-database.js.map +1 -1
  35. package/dist/strand-formation-manager.d.ts +8 -8
  36. package/dist/strand-formation-manager.js +15 -18
  37. package/dist/strand-formation-manager.js.map +1 -1
  38. package/dist/strand-instance-manager.d.ts +52 -21
  39. package/dist/strand-instance-manager.js +100 -34
  40. package/dist/strand-instance-manager.js.map +1 -1
  41. package/dist/strand-membership-writer.d.ts +6 -4
  42. package/dist/strand-membership-writer.js +38 -36
  43. package/dist/strand-membership-writer.js.map +1 -1
  44. package/dist/types.d.ts +39 -31
  45. package/dist/types.js.map +1 -1
  46. package/package.json +8 -7
  47. package/src/arachnode-stub.ts +159 -159
  48. package/src/bootstrap-peer-store-file.ts +44 -44
  49. package/src/bootstrap-peer-store.ts +172 -172
  50. package/src/cadre-node.ts +5158 -4771
  51. package/src/canonical-json.ts +30 -30
  52. package/src/control-authorization.ts +114 -114
  53. package/src/control-cohort.ts +130 -103
  54. package/src/control-database.ts +2406 -2506
  55. package/src/control-formation-recorder.ts +305 -304
  56. package/src/control-schema.ts +801 -786
  57. package/src/control-stream.ts +205 -205
  58. package/src/control-write-retry.ts +483 -473
  59. package/src/delegate-admission.ts +302 -302
  60. package/src/device-token.ts +94 -94
  61. package/src/diagnostics/connection-path.ts +277 -277
  62. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  63. package/src/ed25519-key.ts +134 -134
  64. package/src/enrollment.ts +199 -199
  65. package/src/file-durable-slot.ts +61 -61
  66. package/src/formation-approval.ts +604 -604
  67. package/src/fs-atomic.ts +107 -107
  68. package/src/hibernation-manager.ts +437 -437
  69. package/src/identity-key.ts +109 -109
  70. package/src/index.ts +1 -0
  71. package/src/key-store-file.ts +132 -132
  72. package/src/key-store.ts +99 -99
  73. package/src/membership-connection-gater.ts +204 -204
  74. package/src/node-local-snapshot.ts +260 -260
  75. package/src/peer-addr-book.ts +250 -0
  76. package/src/peer-authorization.ts +259 -259
  77. package/src/peer-record.ts +164 -164
  78. package/src/push-credentials.ts +84 -84
  79. package/src/push-node.ts +64 -64
  80. package/src/push-notifier-apns.ts +247 -247
  81. package/src/push-notifier-fcm.ts +220 -220
  82. package/src/push-notifier-shared.ts +28 -28
  83. package/src/push-notifier.ts +52 -52
  84. package/src/relay-addrs.ts +111 -111
  85. package/src/relay-reservation.ts +823 -823
  86. package/src/seed-bootstrap.ts +15 -15
  87. package/src/seed-trust-policy.ts +140 -140
  88. package/src/strand-addr-protocol.ts +441 -441
  89. package/src/strand-backfill.ts +366 -366
  90. package/src/strand-cohort.ts +38 -77
  91. package/src/strand-database.ts +202 -204
  92. package/src/strand-formation-manager.ts +491 -494
  93. package/src/strand-formation-protocol.ts +692 -692
  94. package/src/strand-instance-manager.ts +108 -50
  95. package/src/strand-member-key.ts +39 -39
  96. package/src/strand-member-registry.ts +182 -182
  97. package/src/strand-membership-writer.ts +1432 -1430
  98. package/src/strand-solicitation.ts +472 -472
  99. package/src/strand-transport-key.ts +58 -58
  100. package/src/strand-wake-payload.ts +32 -32
  101. package/src/strand-wake-protocol.ts +314 -314
  102. package/src/strand-watcher.ts +314 -314
  103. package/src/trusted-owner-store-file.ts +41 -41
  104. package/src/trusted-owner-store.ts +171 -171
  105. package/src/types.ts +1309 -1303
@@ -1,1430 +1,1432 @@
1
- import debug from 'debug';
2
- import { toString as uint8ArrayToString } from 'uint8arrays';
3
- import type { Database } from '@quereus/quereus';
4
- import { digest, sign, verify, generatePrivateKey, getPublicKey, randomBytes } from '@optimystic/quereus-plugin-crypto';
5
- import type { SAppConfig } from './types.js';
6
- import type { Ed25519KeyPair } from './ed25519-key.js';
7
- import { canonicalDatetime } from './canonical-datetime.js';
8
-
9
- const log = debug('sereus:cadre:strand-membership');
10
-
11
- /**
12
- * The engine (rules-logic system) assumed to manage every strand. Persisted in
13
- * `Strand.Header.Engine`.
14
- *
15
- * PLACEHOLDER SEAM: there is no engine-selection mechanism yet — Quereus is the
16
- * only engine. When a real engine-config seam lands, the founder bootstrap should
17
- * read the strand's chosen engine from there instead of this constant. Documented
18
- * deliberately so the column is non-null and self-describing in the meantime.
19
- */
20
- export const STRAND_ENGINE = 'quereus';
21
-
22
- /**
23
- * The pinned engine version recorded in `Strand.Header.EngineVersion`. A pinned
24
- * string for the same reason as {@link STRAND_ENGINE}: it is a documented
25
- * placeholder until an engine-selection seam supplies the real running version.
26
- */
27
- export const STRAND_ENGINE_VERSION = '0.1.0';
28
-
29
- /**
30
- * The single-payload ed25519 signer the `Strand.Invite`/`Strand.ConsumedInvite`
31
- * handshake constraints verify against.
32
- *
33
- * Those constraints sign a single SHA-256 digest over a `'|'`-joined payload
34
- * (e.g. `InviteValid` verifies
35
- * `verify(digest(new.Key || '|' || coalesce(new.Expiration, '')), ...)`).
36
- * So the signer hashes the payload to raw bytes and ed25519-signs *those bytes*:
37
- * SQL `digest(...)`'s default output is base64url and `verify(...)`'s default
38
- * `inputEncoding` is base64url, so signer and verifier operate on identical bytes.
39
- * The membership/RBAC tables (Member/Manager/MemberPeer/Revocation) instead use
40
- * domain/action-tagged VARIADIC digests — see {@link signStrandApproval}.
41
- *
42
- * All strand keys are ed25519, so the explicit `'ed25519'` curve arg is mandatory
43
- * (the crypto plugin otherwise defaults to secp256k1). Mirrors the proven
44
- * `signItem` helper in the `rbac-signed-write` integration scenario.
45
- *
46
- * @param payload - The `'|'`-joined payload the matching constraint hashes.
47
- * @param privateKeyB64 - The signer's base64url ed25519 private seed.
48
- * @returns The base64url ed25519 signature over the payload's SHA-256 digest.
49
- */
50
- export function signStrandPayload(payload: string, privateKeyB64: string): string {
51
- const hashBytes = digest([payload], 'sha256', 'bytes') as Uint8Array;
52
- return sign(hashBytes, privateKeyB64, 'ed25519', 'bytes', 'base64url', 'base64url') as string;
53
- }
54
-
55
- /**
56
- * The verifier counterpart to {@link signStrandPayload}.
57
- *
58
- * Mirrors what the single-payload `Strand.*` constraints compute:
59
- * `verify(digest(payload), signature, publicKey, 'ed25519')`.
60
- * SQL `digest`'s default output and `verify`'s default `inputEncoding`/`sigEncoding`/
61
- * `keyEncoding` are all base64url, so the off-engine check operates on the exact
62
- * same bytes the in-engine CHECK does. Used by the off-engine `MemberVerifier`
63
- * (pre-flight registration checks) so the on-engine constraint is not the only
64
- * place a member self-proof is validated.
65
- *
66
- * @param payload - The `'|'`-joined payload the matching constraint hashes.
67
- * @param signatureB64 - The base64url ed25519 signature to check.
68
- * @param publicKeyB64 - The base64url ed25519 public key to verify against.
69
- * @returns `true` iff the signature is valid for the payload under that key.
70
- */
71
- export function verifyStrandPayload(payload: string, signatureB64: string, publicKeyB64: string): boolean {
72
- const payloadDigest = digest([payload], 'sha256', 'base64url') as string;
73
- return verify(payloadDigest, signatureB64, publicKeyB64, 'ed25519', 'base64url', 'base64url', 'base64url');
74
- }
75
-
76
- /**
77
- * Sign a domain/action-tagged `Strand.*` membership/RBAC approval.
78
- *
79
- * Every `Authorized` branch on `Member`/`Manager`/`MemberPeer`/`Revocation`
80
- * verifies a VARIADIC digest — `digest('<domain>', '<action>', <field>, ...,
81
- * <StampId>)` — whose leading two elements are fixed literals (the domain tag,
82
- * e.g. `'Strand.Member'`, and an action tag, e.g. `'add'`) and whose trailing
83
- * element is the row's per-incarnation StampId. The tags keep an approval from
84
- * verifying against any rule but the one it was minted for (the idiom of the
85
- * control layer's `buildAuthorizationMessage`); the StampId binding makes it
86
- * single-use — it authorizes exactly one incarnation of one row, and dies when
87
- * that row's stamp is retired into `Strand.Revocation`.
88
- *
89
- * The caller passes the digest elements exactly as the matching SQL constraint
90
- * lists them (each SQL argument = one array element), PRESERVING TYPE: the
91
- * crypto plugin's digest framing is type-tagged (INTEGER 1 and TEXT '1' encode
92
- * differently, deliberately), so `Manager.Authorized`'s promotion branch —
93
- * whose digest includes the INTEGER `new.Generation` — must be signed over the
94
- * NUMBER, not its string form. Integer `number` and `bigint` encode
95
- * identically in that framing, so JS-side numbers match however the engine
96
- * represents the SQL integer.
97
- *
98
- * Like {@link signStrandPayload}, the raw digest BYTES are ed25519-signed
99
- * directly, matching SQL `verify(...)`'s default base64url input decoding.
100
- *
101
- * @param fields - The digest elements, in constraint order (tags first, StampId last).
102
- * @param privateKeyB64 - The signer's base64url ed25519 private seed.
103
- * @returns The base64url ed25519 signature over the tagged digest.
104
- */
105
- export function signStrandApproval(fields: ReadonlyArray<string | number>, privateKeyB64: string): string {
106
- const hashBytes = digest(fields, 'sha256', 'bytes') as Uint8Array;
107
- return sign(hashBytes, privateKeyB64, 'ed25519', 'bytes', 'base64url', 'base64url') as string;
108
- }
109
-
110
- /**
111
- * Mint a fresh per-row authorization nonce (StampId) for a `Strand.Member`,
112
- * `Strand.Manager`, or `Strand.MemberPeer` row.
113
- *
114
- * 256 bits of CSPRNG output, base64url-encoded — enough entropy that a future
115
- * legitimate stamp cannot be guessed and pre-planted into `Strand.Revocation`
116
- * (the `RowIsGone` comment in `schemas/strand.qsql` leans on exactly this).
117
- * Plain randomness, deliberately NOT the control layer's peer-derived
118
- * `generateStampId`: strand rows are not per-peer, so entropy alone carries
119
- * the uniqueness.
120
- *
121
- * @returns A fresh base64url stamp (43 chars for 32 bytes).
122
- */
123
- export function generateStrandStampId(): string {
124
- // randomBytes' first arg is BITS, not bytes — 256 bits = 32 bytes.
125
- const bytes = randomBytes(256, 'bytes') as Uint8Array;
126
- return uint8ArrayToString(bytes, 'base64url');
127
- }
128
-
129
- /**
130
- * Run `fn` inside one explicit strand transaction: begin, fn, commit — with the
131
- * standard rollback-on-failure shape.
132
- *
133
- * Used wherever two `Strand.*` writes must land atomically: the invite-consume
134
- * pair (Member + ConsumedInvite) and every delete-plus-tombstone pair (the
135
- * `RevocationRecorded` constraints require the `Revocation` row in the SAME
136
- * transaction as the delete it retires).
137
- *
138
- * JOINS a caller-owned transaction instead of opening its own: Quereus's
139
- * `Database.beginTransaction()` hard-throws "Transaction already active" on any
140
- * nesting, and a caller composing several writers in one transaction (e.g. a
141
- * resign + revoke pair that must land atomically) is exactly the case where the
142
- * deferred constraints should fire once, at the CALLER's commit. In joined mode
143
- * commit/rollback belong to the caller, so failures simply propagate.
144
- */
145
- async function inStrandTransaction(db: Database, fn: () => Promise<void>): Promise<void> {
146
- if (!db.getAutocommit()) {
147
- await fn();
148
- return;
149
- }
150
- await db.beginTransaction();
151
- try {
152
- await fn();
153
- await db.commit();
154
- } catch (error) {
155
- // A failed commit() already tears down the transaction, so rollback() would
156
- // throw "No transaction active" and mask the real cause — swallow only that.
157
- try {
158
- await db.rollback();
159
- } catch (rollbackError) {
160
- log('Rollback after strand transaction failure was a no-op: %s', rollbackError);
161
- }
162
- throw error;
163
- }
164
- }
165
-
166
- /**
167
- * File the `Strand.Revocation` tombstone that retires a deleted row's StampId.
168
- *
169
- * Runs inside the SAME transaction as the delete it accompanies — the guarded
170
- * tables' `RevocationRecorded` (deferred) requires the tombstone at commit, and
171
- * `Revocation.RowIsGone` (also deferred) requires the row to already be gone, so
172
- * the pair only ever lands together.
173
- *
174
- * `Revocation.Authorized` verifies the retire-tagged digest against a
175
- * PRE-transaction (`committed.Member`) row, so the retiree must have been a
176
- * member BEFORE this transaction. Every writer flow satisfies this: managers are
177
- * members, and a self-departing member is committed until this very transaction
178
- * removes it. Unlike the sibling tables' nullable contexts, `Revocation`'s
179
- * context is non-null — both fields are always supplied.
180
- *
181
- * @param db - The strand database, INSIDE an open transaction.
182
- * @param tableName - Which guarded table the stamp belonged to.
183
- * @param stampId - The retired stamp.
184
- * @param retiree - The committed member filing the tombstone (the delete's own signer).
185
- */
186
- async function insertRevocation(
187
- db: Database,
188
- tableName: 'Member' | 'Manager' | 'MemberPeer',
189
- stampId: string,
190
- retiree: Ed25519KeyPair,
191
- ): Promise<void> {
192
- const signature = signStrandApproval(['Strand.Revocation', 'retire', tableName, stampId], retiree.privateKeyB64);
193
- await db.exec(
194
- `insert into Strand.Revocation (TableName, StampId)
195
- with context MemberKey = ?, Signature = ?
196
- values (?, ?)`,
197
- [retiree.publicKeyB64, signature, tableName, stampId],
198
- );
199
- }
200
-
201
- /** Parameters for {@link bootstrapFounderMembership}. */
202
- export interface FounderBootstrapParams {
203
- /** The strand id — written to `Header.Id`. */
204
- strandId: string;
205
- /** Strand type: `'o'` (open, Header only) or `'c'` (closed, Header+Member+Manager). */
206
- type: 'o' | 'c';
207
- /** The sApp config whose id/version/schema/signature populate the Header. */
208
- sApp: SAppConfig;
209
- /**
210
- * The founder's derived strand keypair (from {@link strandMemberKeyPair}). Its
211
- * `publicKeyB64` becomes the founding `Member.Key` and `Manager.MemberKey`.
212
- * Required for a closed strand; ignored for an open strand.
213
- */
214
- founderKeyPair?: Ed25519KeyPair;
215
- }
216
-
217
- /**
218
- * Count rows in a `Strand.*` table as seen by this database instance.
219
- *
220
- * The table name is a fixed literal supplied by this module (never user input),
221
- * so the interpolation is not an injection surface — it just keeps the singleton
222
- * insert-if-absent guards terse.
223
- */
224
- async function strandTableCount(db: Database, table: 'Header' | 'Member' | 'Manager'): Promise<number> {
225
- for await (const row of db.eval(`select count(1) as Count from Strand.${table}`)) {
226
- return (row.Count as number) ?? 0;
227
- }
228
- return 0;
229
- }
230
-
231
- /**
232
- * Insert the singleton `Strand.Header` if absent.
233
- *
234
- * Every `Header` column is NOT NULL (Quereus defaults unqualified columns to NOT
235
- * NULL; the table declares no `null` columns), so all eight are supplied non-null.
236
- * A missing `sApp.signature` (dev `requireSignedSchemas:false`) coalesces to `''`
237
- * rather than inserting null. `Header` carries only `InsertOnly` + a singleton PK,
238
- * so the insert needs no `with context`.
239
- */
240
- async function insertHeaderIfAbsent(db: Database, params: FounderBootstrapParams): Promise<void> {
241
- if (await strandTableCount(db, 'Header') > 0) {
242
- log('Header already present for strand %s; skipping', params.strandId);
243
- return;
244
- }
245
- await db.exec(
246
- `insert into Strand.Header
247
- (Id, Type, sAppId, sAppVersion, sAppSchema, sAppSignature, Engine, EngineVersion)
248
- values (?, ?, ?, ?, ?, ?, ?, ?)`,
249
- [
250
- params.strandId,
251
- params.type,
252
- params.sApp.id,
253
- params.sApp.version,
254
- params.sApp.schema,
255
- params.sApp.signature ?? '',
256
- STRAND_ENGINE,
257
- STRAND_ENGINE_VERSION,
258
- ],
259
- );
260
- log('Inserted Header for strand %s (type %s)', params.strandId, params.type);
261
- }
262
-
263
- /**
264
- * Insert the founding `Strand.Member` if no member exists yet.
265
- *
266
- * The empty PRE-transaction member set (`count(1) from committed.Member = 0`)
267
- * satisfies the bootstrap branch of `Member.Authorized`, so no signature is
268
- * needed — the context fields are explicit nulls. The branch also caps the
269
- * POST-image at one member, so it waives authorization for exactly this single
270
- * seat, never for a batch. The row still mints a fresh StampId — the column is
271
- * NOT NULL on every path; bootstrap only waives the SIGNATURE. Guarding on the
272
- * count makes this idempotent: a re-run (the founder re-`addStrand`/
273
- * `resumeStrand`) finds the member present and skips.
274
- */
275
- async function insertFounderMemberIfAbsent(db: Database, memberKey: string, strandId: string): Promise<void> {
276
- if (await strandTableCount(db, 'Member') > 0) {
277
- log('Member already present for strand %s; skipping founder Member', strandId);
278
- return;
279
- }
280
- await db.exec(
281
- `insert into Strand.Member (Key, StampId)
282
- with context ManagerKey = null, ManagerSignature = null, MemberSignature = null
283
- values (?, ?)`,
284
- [memberKey, generateStrandStampId()],
285
- );
286
- log('Inserted founding Member for strand %s', strandId);
287
- }
288
-
289
- /**
290
- * Insert the founding `Strand.Manager` if no manager exists yet.
291
- *
292
- * The empty-table state satisfies the bootstrap branch of `Manager.Authorized`, so
293
- * no signature is needed (a fresh StampId is still minted — the column is NOT
294
- * NULL). The founder is seated at `Generation = 0` — the root of
295
- * the manager lineage; the bootstrap branch requires exactly that value, and every
296
- * later manager is seated at a strictly greater generation (see {@link addManager}).
297
- * Idempotent via the same count guard.
298
- *
299
- * ORDERING IS LOAD-BEARING, not merely convenient. The bootstrap branch is gated to
300
- * the founding state and now reads `exists (select 1 from Member M where M.Key =
301
- * new.MemberKey)` alongside `count(Manager) <= 1` and `count(Member) <= 1`, so the
302
- * founding `Member` row MUST already exist when this commits — a Manager-first
303
- * seeding path is rejected. It must also run AFTER the Header insert:
304
- * `Manager.OnlyClosed` is a deferred (subquery) check evaluated at commit. The
305
- * sequential auto-commit Header→Member→Manager order in
306
- * {@link bootstrapFounderMembership} satisfies both.
307
- */
308
- async function insertFounderManagerIfAbsent(db: Database, memberKey: string, strandId: string): Promise<void> {
309
- if (await strandTableCount(db, 'Manager') > 0) {
310
- log('Manager already present for strand %s; skipping founder Manager', strandId);
311
- return;
312
- }
313
- await db.exec(
314
- `insert into Strand.Manager (MemberKey, Generation, StampId)
315
- with context ManagerKey = null, Signature = null
316
- values (?, 0, ?)`,
317
- [memberKey, generateStrandStampId()],
318
- );
319
- log('Inserted founding Manager for strand %s', strandId);
320
- }
321
-
322
- /**
323
- * Founder-only one-time bootstrap of a strand's `Strand.*` membership/RBAC rows.
324
- *
325
- * Runs once at bring-up on the strand's FOUNDER (the party that provisioned and
326
- * published the strand). A joiner never calls this — it receives these rows via
327
- * Optimystic sync. Every write is insert-if-absent (guarded by a row count) so a
328
- * restart / founder re-`addStrand` is a no-op and never double-inserts.
329
- *
330
- * Behavior by strand type:
331
- * - **Open (`'o'`)**: insert `Header` only. `Member`/`Manager`/`Invite` are
332
- * `OnlyClosed` and would trip that constraint — they are skipped entirely.
333
- * - **Closed (`'c'`)**: insert `Header(Type='c')`, then the founding `Member`
334
- * (`Key = founderKeyPair.publicKeyB64`), then the founding `Manager`
335
- * (`MemberKey = founderKeyPair.publicKeyB64`). Insert order matters: the
336
- * Header must commit before the deferred `OnlyClosed` checks on Member/Manager
337
- * evaluate at commit.
338
- *
339
- * A closed strand with no `founderKeyPair` throws: a closed strand with no founding
340
- * Manager could never admit anyone, so failing loudly here (which propagates out
341
- * of `StrandDatabase.initialize()` and triggers the runtime's rollback) is correct.
342
- *
343
- * @param db - The strand's Quereus database (schema already applied).
344
- * @param params - Strand id/type, the sApp config for the Header, and (closed only)
345
- * the derived founder keypair.
346
- * @throws If `type === 'c'` and no `founderKeyPair` is supplied.
347
- */
348
- export async function bootstrapFounderMembership(db: Database, params: FounderBootstrapParams): Promise<void> {
349
- const { strandId, type, founderKeyPair } = params;
350
- log('Founder bootstrap for strand %s (type %s)', strandId, type);
351
-
352
- // Validate BEFORE writing anything: a closed strand with no founder key must
353
- // fail without leaving a closed `Header` that has no founding Member/Manager
354
- // (such a strand could never admit anyone).
355
- if (type === 'c' && !founderKeyPair) {
356
- throw new Error(
357
- `Cannot bootstrap closed strand ${strandId}: no founder key pair derived from MemberPrivateKey. ` +
358
- 'A closed strand needs a founding Member + Manager or it can never admit members.',
359
- );
360
- }
361
-
362
- // Header is written for every strand; Member/Manager are closed-only.
363
- await insertHeaderIfAbsent(db, params);
364
-
365
- if (type === 'o') {
366
- // Open strand: Member/Manager/Invite are OnlyClosed — nothing else to write.
367
- return;
368
- }
369
-
370
- const memberKey = founderKeyPair!.publicKeyB64;
371
- await insertFounderMemberIfAbsent(db, memberKey, strandId);
372
- await insertFounderManagerIfAbsent(db, memberKey, strandId);
373
- log('Founder bootstrap complete for closed strand %s', strandId);
374
- }
375
-
376
- // ── Invite issuance + consumption (the per-strand join handshake) ─────────────
377
-
378
- /** Parameters for {@link issueInvite}. */
379
- export interface IssueInviteParams {
380
- /**
381
- * The issuing manager's strand keypair. Its `publicKeyB64` must already be a
382
- * `Strand.Manager` row (the `InviteValid` constraint rejects a non-manager).
383
- */
384
- managerKeyPair: Ed25519KeyPair;
385
- /**
386
- * Optional invite expiry as epoch milliseconds. When set, it is canonicalised
387
- * via {@link canonicalDatetime} so the signed payload segment byte-matches the
388
- * `datetime`-coerced `Invite.Expiration` the deferred CHECK sees. When omitted,
389
- * the invite never expires and the signed segment is `''` (matching the schema's
390
- * `coalesce(new.Expiration, '')`).
391
- */
392
- expiration?: number;
393
- }
394
-
395
- /** The minted invite: a public key (the `Invite.Key`) plus its private seed. */
396
- export interface IssuedInvite {
397
- /** The invite ed25519 PUBLIC key (base64url) — the `Invite.Key` primary key. */
398
- inviteKey: string;
399
- /**
400
- * The invite ed25519 PRIVATE seed (base64url). Handed out-of-band to the
401
- * invitee; whoever holds it can {@link consumeInvite} exactly once. NEVER
402
- * persisted in the strand — only the public key is.
403
- */
404
- invitePrivateKey: string;
405
- }
406
-
407
- /**
408
- * Issue a single-use invitation to join a closed strand.
409
- *
410
- * Generates a fresh invite ed25519 keypair (the public key becomes `Invite.Key`),
411
- * builds the constraint's payload (`Key || '|' || coalesce(Expiration, '')`), and
412
- * signs it TWICE: with the manager private key (→ `ManagerSignature`, proving
413
- * a manager issued it) and with the invite private key (→ `InviteSignature`,
414
- * proving the issuer actually holds the invite secret). Both signatures plus the
415
- * manager public key are bound as constraint context for the `Invite` insert.
416
- *
417
- * The returned `invitePrivateKey` is the only secret the invitee needs to redeem
418
- * the invite — it is NOT stored in the strand (only `Invite.Key`, the public half,
419
- * is). Single-use is enforced at consumption time: `ConsumedInvite`'s primary key
420
- * is `InviteKey`, so a given invite can be consumed at most once.
421
- *
422
- * @param db - The closed strand's database (founder already bootstrapped).
423
- * @param params - The issuing manager keypair and optional expiry.
424
- * @returns The invite public key and the out-of-band private seed.
425
- */
426
- export async function issueInvite(db: Database, params: IssueInviteParams): Promise<IssuedInvite> {
427
- const { managerKeyPair, expiration } = params;
428
-
429
- const invitePrivateKey = generatePrivateKey('ed25519', 'base64url') as string;
430
- const inviteKey = getPublicKey(invitePrivateKey, 'ed25519', 'base64url', 'base64url') as string;
431
-
432
- // Canonicalise the expiry to the engine's stored `datetime` form so the signed
433
- // segment matches `new.Expiration` post-coercion; null expiry signs as ''.
434
- const expirationSegment = expiration == null ? '' : await canonicalDatetime(db, expiration);
435
- const expirationColumn = expiration == null ? null : expirationSegment;
436
-
437
- const payload = `${inviteKey}|${expirationSegment}`;
438
- const managerSignature = signStrandPayload(payload, managerKeyPair.privateKeyB64);
439
- const inviteSignature = signStrandPayload(payload, invitePrivateKey);
440
-
441
- await db.exec(
442
- `insert into Strand.Invite (Key, Expiration)
443
- with context ManagerKey = ?, ManagerSignature = ?, InviteSignature = ?
444
- values (?, ?)`,
445
- [managerKeyPair.publicKeyB64, managerSignature, inviteSignature, inviteKey, expirationColumn],
446
- );
447
- log('Issued invite %s (expires=%s)', inviteKey, expirationColumn ?? 'never');
448
-
449
- return { inviteKey, invitePrivateKey };
450
- }
451
-
452
- /** Parameters for {@link consumeInvite}. */
453
- export interface ConsumeInviteParams {
454
- /** The `Invite.Key` (invite PUBLIC key, base64url) being redeemed. */
455
- inviteKey: string;
456
- /** The matching invite PRIVATE seed (base64url) received out-of-band. */
457
- invitePrivateKey: string;
458
- /** The joining member's ed25519 PUBLIC key (base64url) — the new `Member.Key`. */
459
- memberKey: string;
460
- /**
461
- * The instant (epoch ms) to compare against the invite's `Expiration` for the
462
- * `NotExpired` gate. Defaults to `Date.now()`; tests pin it so the comparison is
463
- * deterministic. Mirrors the control-layer `redeemInvitation`'s `nowMs` convention.
464
- */
465
- nowMs?: number;
466
- }
467
-
468
- /**
469
- * Redeem an invite to admit a new `Member`, atomically.
470
- *
471
- * `Member.Authorized`'s invite branch needs a `ConsumedInvite` row, while
472
- * `ConsumedInvite`'s `MemberExists` needs the `Member` row — a circular
473
- * dependency. Both are deferred (subquery-bearing) checks that evaluate
474
- * at COMMIT, so inserting `Member` then `ConsumedInvite` inside one explicit
475
- * transaction lets both rows exist when the deferred checks fire. This mirrors
476
- * `ControlDatabase.redeemInvitation` (Strand + FormationUsage in one txn).
477
- *
478
- * The `ConsumedInvite` insert carries an `InviteSignature` over
479
- * `InviteKey || '|' || MemberKey`, proving the consumer holds the invite private
480
- * key (the on-engine `ValidUsage` gate). The `Member` insert needs no member
481
- * signature — its admission is the existence of the matching `ConsumedInvite` —
482
- * but still mints a fresh StampId (NOT NULL on every path; a revoked-then-
483
- * re-invited member is a fresh incarnation under a fresh stamp).
484
- *
485
- * Single-use: `ConsumedInvite`'s primary key is `InviteKey`, so a second consume
486
- * of the same invite is rejected by the PK (a distinct layer from the control
487
- * network's `FormationUsage` single-use, which gates strand FORMATION, not the
488
- * per-strand member join enforced here).
489
- *
490
- * Expiry: the `ConsumedInvite.NotExpired` deferred check rejects redeeming an invite
491
- * whose `Expiration` is at or before `context.Now`. `Now` is supplied here as a
492
- * canonical-datetime string from `canonicalDatetime(db, nowMs)` — the SAME transform
493
- * `issueInvite` uses to store `Invite.Expiration` — so both sides of the schema's
494
- * `I.Expiration > context.Now` comparison are byte-identical canonical strings and
495
- * the lexical `>` orders chronologically at any granularity. (This intentionally
496
- * diverges from the control layer, which passes `Now` as a JS ISO string; Quereus
497
- * does not coerce context params, so an ISO `Now` would be compared lexically against
498
- * the canonical, T-separated `Expiration` and could mis-order near-same-instant
499
- * timestamps (due to a trailing `.000Z` suffix). The control tests only use far-future/far-past expiries, so that latent
500
- * skew never bites there — the strand layer avoids it outright.) A null `Expiration`
501
- * never expires. Like `ValidUsage`, `NotExpired` defers to commit, so an expired
502
- * invite rolls back the whole txn — neither the `Member` nor the `ConsumedInvite`
503
- * row survives.
504
- *
505
- * @param db - The closed strand's database.
506
- * @param params - The invite key/secret, the joining member's public key, and an
507
- * optional `nowMs` instant for the expiry comparison (default `Date.now()`).
508
- * @throws If any constraint rejects (bad signature, missing invite, or an expired
509
- * invite); the whole transaction rolls back (neither the `Member` nor the
510
- * `ConsumedInvite` row survives).
511
- */
512
- export async function consumeInvite(db: Database, params: ConsumeInviteParams): Promise<void> {
513
- const { inviteKey, invitePrivateKey, memberKey, nowMs } = params;
514
-
515
- const usagePayload = `${inviteKey}|${memberKey}`;
516
- const inviteSignature = signStrandPayload(usagePayload, invitePrivateKey);
517
-
518
- // Canonicalise "now" the same way issueInvite canonicalises Expiration, so the
519
- // schema's `I.Expiration > context.Now` compares like-for-like canonical strings.
520
- // Plain runtime Date.now() — the tess Workflow restriction is on scripts, not libs.
521
- const nowCanonical = await canonicalDatetime(db, nowMs ?? Date.now());
522
-
523
- await inStrandTransaction(db, async () => {
524
- // 1. Member — admitted by the deferred invite branch (the matching
525
- // ConsumedInvite below), so no manager signature is supplied.
526
- await db.exec(
527
- `insert into Strand.Member (Key, StampId)
528
- with context ManagerKey = null, ManagerSignature = null, MemberSignature = null
529
- values (?, ?)`,
530
- [memberKey, generateStrandStampId()],
531
- );
532
-
533
- // 2. ConsumedInvite — proves possession of the invite private key and that the
534
- // invite has not expired (NotExpired gate against the canonical Now).
535
- await db.exec(
536
- `insert into Strand.ConsumedInvite (InviteKey, MemberKey)
537
- with context InviteSignature = ?, Now = ?
538
- values (?, ?)`,
539
- [inviteSignature, nowCanonical, inviteKey, memberKey],
540
- );
541
- });
542
- log('Consumed invite %s -> member %s', inviteKey, memberKey);
543
- }
544
-
545
- /**
546
- * Every value of `InviteKey` in one of the two invite-marker tables, as a `Set`.
547
- *
548
- * Unfiltered scan + JavaScript comparison, deliberately: `ConsumedInvite` and
549
- * `CancelledInvite` each have the single column `InviteKey` as their primary key, so
550
- * ANY where-equality on it is a FULL-PK predicate — which the optimystic virtual-table
551
- * module serves via a single-key point lookup that can MISS on a networked strand (the
552
- * argument {@link scanMemberPeers} makes in full). Reading the whole column and
553
- * comparing in JS depends only on the scan returning a SUPERSET of the live rows.
554
- *
555
- * The table name is a fixed literal supplied by this module (never user input), so the
556
- * interpolation is not an injection surface — same as {@link strandTableCount}.
557
- *
558
- * NOTE: every caller pays a WHOLE-column read — {@link cancelInvite}'s idempotence guard
559
- * reads all cancelled keys to answer one membership question, and
560
- * {@link listOutstandingInvites} reads both marker tables per call. Fine at strand scale
561
- * (a handful of invitations); if invite churn ever gets large this wants a real filtered
562
- * read, which in turn needs the networked point-lookup gap closed
563
- * (`debt-composite-pk-point-lookup-unreliable-untracked`).
564
- */
565
- async function scanInviteKeys(db: Database, table: 'ConsumedInvite' | 'CancelledInvite'): Promise<Set<string>> {
566
- const keys = new Set<string>();
567
- for await (const row of db.eval(`select InviteKey from Strand.${table}`)) {
568
- keys.add(row.InviteKey as string);
569
- }
570
- return keys;
571
- }
572
-
573
- /** Parameters for {@link cancelInvite}. */
574
- export interface CancelInviteParams {
575
- /**
576
- * The cancelling manager's strand keypair. Its `publicKeyB64` must be a
577
- * PRE-EXISTING `Strand.Manager` row — `CancelledInvite.Authorized` reads
578
- * `committed.Manager`, so a manager seated in the SAME transaction cannot cancel.
579
- */
580
- managerKeyPair: Ed25519KeyPair;
581
- /** The `Invite.Key` to kill. */
582
- inviteKey: string;
583
- }
584
-
585
- /**
586
- * Cancel an outstanding invitation, permanently: it may never be consumed.
587
- *
588
- * Files a `Strand.CancelledInvite` tombstone carrying a manager signature over
589
- * `digest('Strand.CancelledInvite', 'cancel', InviteKey)`. The digest binds the exact
590
- * invite key, so an approval minted for one invitation cannot cancel another.
591
- *
592
- * One row, one statement — no transaction needed. `CancelledInvite.Authorized` is a
593
- * deferred (subquery-bearing) check, so it fires at this statement's own auto-commit.
594
- *
595
- * Insert-if-absent, matching {@link registerMemberPeer}'s and {@link revokeMember}'s
596
- * restart-safe shape: a repeat cancellation logs and returns rather than throwing on the
597
- * primary key. (Check-then-write is not atomic; the primary key is the real backstop —
598
- * the guard is for the sequential repeat/restart path.)
599
- *
600
- * Cancellation is what makes removal a re-entry gate: it is the `ConsumedInvite` insert
601
- * that `NotCancelled` blocks, and `Member.Authorized`'s invite branch needs a
602
- * same-transaction FRESH `ConsumedInvite` row, so a cancelled invitation rolls the whole
603
- * join back. Un-cancelling is impossible (`CancelledInvite.Immutable`) — to re-invite a
604
- * party, {@link issueInvite} a fresh invitation.
605
- *
606
- * Enumerate what there is to cancel with {@link listOutstandingInvites}: an invitation
607
- * names no invitee, so the strand cannot tell a manager WHICH invitations a departing
608
- * member holds. Invitee binding is tracked as `feat-strand-invitee-bound-invites`.
609
- *
610
- * @param db - The closed strand's database.
611
- * @param params - The cancelling manager's keypair and the invite key to kill.
612
- * @throws If `CancelledInvite.Authorized` rejects (a non-manager, a manager seated in
613
- * this transaction, or an approval minted for a different invite key) or `OnlyClosed`
614
- * rejects (an open strand); the insert rolls back, leaving no tombstone.
615
- */
616
- export async function cancelInvite(db: Database, params: CancelInviteParams): Promise<void> {
617
- const { managerKeyPair, inviteKey } = params;
618
-
619
- if ((await scanInviteKeys(db, 'CancelledInvite')).has(inviteKey)) {
620
- log('Invite %s already cancelled; skipping', inviteKey);
621
- return;
622
- }
623
-
624
- const signature = signStrandApproval(
625
- ['Strand.CancelledInvite', 'cancel', inviteKey],
626
- managerKeyPair.privateKeyB64,
627
- );
628
- await db.exec(
629
- `insert into Strand.CancelledInvite (InviteKey)
630
- with context ManagerKey = ?, ManagerSignature = ?
631
- values (?)`,
632
- [managerKeyPair.publicKeyB64, signature, inviteKey],
633
- );
634
- log('Cancelled invite %s by manager %s', inviteKey, managerKeyPair.publicKeyB64);
635
- }
636
-
637
- /** One redeemable invitation, as reported by {@link listOutstandingInvites}. */
638
- export interface OutstandingInvite {
639
- /** The `Invite.Key` (invite public key, base64url). */
640
- inviteKey: string;
641
- /**
642
- * The expiry as the engine's canonical `datetime` string
643
- * (`YYYY-MM-DDTHH:MM:SS[.frac]`, no zone suffix — see {@link canonicalDatetime}), or
644
- * `null` for never-expires.
645
- *
646
- * Deliberately the STORED form, not the epoch-ms {@link IssueInviteParams.expiration}
647
- * takes: it is what compares like-for-like against another canonicalised instant, and
648
- * what the on-engine `NotExpired` gate sees. It is NOT a JS-parseable ISO instant —
649
- * pass it through the engine (or `canonicalDatetime`) rather than `Date.parse`.
650
- */
651
- expiration: string | null;
652
- }
653
-
654
- /**
655
- * The invitations that are still redeemable: neither consumed, nor cancelled, nor
656
- * expired at `nowMs`.
657
- *
658
- * `Strand.Invite` is insert-only and carries no state column, so "outstanding" is not a
659
- * property of the row — it is the `Invite` set minus the `ConsumedInvite` keys, minus
660
- * the `CancelledInvite` keys, minus anything whose `Expiration` has passed. All three
661
- * exclusions mirror gates a consume would hit anyway (`ConsumedInvite`'s primary key,
662
- * `NotCancelled`, `NotExpired`).
663
- *
664
- * Reads via unfiltered scans and compares in JavaScript — see {@link scanInviteKeys} for
665
- * why a full-PK where-equality is not reliable on a networked strand.
666
- *
667
- * Expiry is compared as `expiration > canonicalDatetime(nowMs)`: the same transform
668
- * {@link issueInvite} uses to STORE `Invite.Expiration`, so the string comparison orders
669
- * chronologically, and the same strict `>` the on-engine `NotExpired` gate uses (expiry
670
- * is exclusive — an invitation is dead at its expiry instant, not after it).
671
- *
672
- * This is the manager's enumeration side of {@link cancelInvite}, and the "door is open"
673
- * pre-flight behind `StrandMemberVerifier.isAuthorizedToJoin`.
674
- *
675
- * @param db - The closed strand's database.
676
- * @param nowMs - The instant (epoch ms) to compare expiries against; defaults to
677
- * `Date.now()`. Tests pin it so the comparison is deterministic, mirroring
678
- * {@link consumeInvite}'s `nowMs` convention.
679
- * @returns The redeemable invitations, in NO guaranteed order (the scans promise only a
680
- * superset of the live rows, not a stable sequence — sort by `expiration` if order
681
- * matters); empty if none.
682
- */
683
- export async function listOutstandingInvites(db: Database, nowMs?: number): Promise<OutstandingInvite[]> {
684
- // Plain runtime Date.now() — the tess Workflow restriction is on scripts, not libs.
685
- const nowCanonical = await canonicalDatetime(db, nowMs ?? Date.now());
686
- const consumed = await scanInviteKeys(db, 'ConsumedInvite');
687
- const cancelled = await scanInviteKeys(db, 'CancelledInvite');
688
-
689
- const outstanding: OutstandingInvite[] = [];
690
- for await (const row of db.eval('select Key, Expiration from Strand.Invite')) {
691
- const inviteKey = row.Key as string;
692
- const expiration = (row.Expiration as string | null) ?? null;
693
- if (consumed.has(inviteKey) || cancelled.has(inviteKey)) {
694
- continue;
695
- }
696
- if (expiration != null && expiration <= nowCanonical) {
697
- continue;
698
- }
699
- outstanding.push({ inviteKey, expiration });
700
- }
701
- return outstanding;
702
- }
703
-
704
- // ── Member admission + removal (manager-admit, revoke, leave) ─────────────────
705
-
706
- /**
707
- * The live StampId of the `Strand.Member` row keyed by `memberKey`, or
708
- * `undefined` if no such row is visible.
709
- *
710
- * `Member`'s primary key is the single `Key` column, so ANY where-equality on it
711
- * is a full-PK predicate — which the optimystic virtual-table module serves via a
712
- * single-key point lookup that can MISS on a networked strand (the same failure
713
- * mode {@link scanMemberPeers} documents). So this reads via an UNFILTERED scan
714
- * and compares the key in JavaScript: correctness depends only on the scan
715
- * returning a superset of the live rows — the weakest possible assumption about
716
- * the storage layer.
717
- */
718
- async function memberStampId(db: Database, memberKey: string): Promise<string | undefined> {
719
- for await (const row of db.eval('select Key, StampId from Strand.Member')) {
720
- if (row.Key === memberKey) {
721
- return row.StampId as string;
722
- }
723
- }
724
- return undefined;
725
- }
726
-
727
- /** Parameters for {@link addMemberByManager}. */
728
- export interface AddMemberByManagerParams {
729
- /**
730
- * The admitting manager's strand keypair. Its `publicKeyB64` must be a
731
- * `Strand.Manager` row; it signs the add-tagged digest over the new member key
732
- * and its fresh stamp.
733
- */
734
- managerKeyPair: Ed25519KeyPair;
735
- /** The joining member's ed25519 PUBLIC key (base64url) — the new `Member.Key`. */
736
- memberKey: string;
737
- }
738
-
739
- /**
740
- * Admit a `Member` directly by manager signature — the sibling of the invite
741
- * path on `Member.Authorized`'s direct-manager branch.
742
- *
743
- * The constraint verifies the add-tagged digest
744
- * `digest('Strand.Member', 'add', new.Key, new.StampId)` against a pre-existing
745
- * (`committed.Manager`) row matching `context.ManagerKey`. The stamp is minted
746
- * fresh here and bound inside the signed digest, so the approval seats exactly
747
- * this incarnation: once the member is removed (retiring the stamp), the captured
748
- * approval can never re-seat it. No `ConsumedInvite` is involved: this is the
749
- * path a manager uses to seat a member it already trusts (e.g. a manager-side
750
- * enrollment that admits a party already authorised out-of-band).
751
- *
752
- * @param db - The closed strand's database.
753
- * @param params - The admitting manager keypair and the new member key.
754
- * @throws If `Member.Authorized` rejects (e.g. a non-manager key); the insert
755
- * rolls back, leaving no `Member` row.
756
- */
757
- export async function addMemberByManager(db: Database, params: AddMemberByManagerParams): Promise<void> {
758
- const { managerKeyPair, memberKey } = params;
759
- const stampId = generateStrandStampId();
760
- const signature = signStrandApproval(['Strand.Member', 'add', memberKey, stampId], managerKeyPair.privateKeyB64);
761
- await db.exec(
762
- `insert into Strand.Member (Key, StampId)
763
- with context ManagerKey = ?, ManagerSignature = ?, MemberSignature = null
764
- values (?, ?)`,
765
- [managerKeyPair.publicKeyB64, signature, memberKey, stampId],
766
- );
767
- log('Admitted member %s by manager %s', memberKey, managerKeyPair.publicKeyB64);
768
- }
769
-
770
- /** Parameters for {@link revokeMember}. */
771
- export interface RevokeMemberParams {
772
- /**
773
- * The revoking manager's strand keypair. Its `publicKeyB64` must be a
774
- * PRE-EXISTING `Strand.Manager` row (the manager-removal branch of
775
- * `Member.Authorized` reads `committed.Manager` — a manager seated in the same
776
- * transaction cannot authorize); it signs the remove-tagged digest over the
777
- * target row's key and live stamp, and files the accompanying tombstone.
778
- */
779
- managerKeyPair: Ed25519KeyPair;
780
- /** The `Member.Key` row to delete. */
781
- memberKey: string;
782
- }
783
-
784
- /**
785
- * Revoke a `Member` on the signature of an existing manager.
786
- *
787
- * Reads the target row's live StampId first (a quiet no-op if the row is already
788
- * absent — a repeated or restarted revocation should not throw), then runs ONE
789
- * transaction pairing the delete with its `Strand.Revocation` tombstone: the
790
- * schema's `Member.RevocationRecorded` requires the tombstone in the same
791
- * transaction, and the tombstone is what permanently retires the stamp so the
792
- * captured admission approval can never re-seat this incarnation.
793
- *
794
- * The manager-removal branch of `Member.Authorized` verifies the remove-tagged
795
- * digest `digest('Strand.Member', 'remove', old.Key, old.StampId)` against a
796
- * `committed.Manager` row matching `context.ManagerKey` — distinct from the
797
- * add-tagged admission payload, and bound to the live stamp, so neither a
798
- * captured admission nor a captured PRIOR removal (whose stamp differs) replays.
799
- *
800
- * A revoked member cannot re-admit itself off the invite it ALREADY SPENT: that
801
- * `ConsumedInvite` row is stale, and the invite branch requires a
802
- * same-transaction FRESH consumption. Re-admission normally takes a fresh
803
- * manager action ({@link addMemberByManager} or a new invite).
804
- *
805
- * An UNSPENT invite the revoked party holds is killed EXPLICITLY, by the manager
806
- * calling {@link cancelInvite} on it (enumerate the candidates with
807
- * {@link listOutstandingInvites}); a cancelled invitation can never be consumed,
808
- * and cancellation is permanent. This removal does NOT cascade into cancellation:
809
- * an invitation names no invitee, so there is nothing to match the removed member
810
- * against — the strand cannot tell which invitations were meant for it, or whether
811
- * it holds any. Binding an invitation to its invitee is tracked as
812
- * `feat-strand-invitee-bound-invites`.
813
- *
814
- * A manager must resign its `Manager` row before (or in the same transaction
815
- * as) losing membership — `Member.NotAManager` rejects un-membering a key that
816
- * still holds a Manager row. And the strand never drops to zero members
817
- * (`Member.MinOneMember`, a local-count floor with the same cross-node caveat
818
- * as `MinOneManager`).
819
- *
820
- * @param db - The closed strand's database.
821
- * @param params - The revoking manager keypair and the target member key.
822
- * @throws If `Member.Authorized` rejects (a non-manager or same-transaction
823
- * signer), `Member.NotAManager` rejects (the target still holds a Manager
824
- * row), or `Member.MinOneMember` rejects (the removal would empty the member
825
- * set); the whole delete+tombstone transaction rolls back.
826
- */
827
- export async function revokeMember(db: Database, params: RevokeMemberParams): Promise<void> {
828
- const { managerKeyPair, memberKey } = params;
829
- const stampId = await memberStampId(db, memberKey);
830
- if (stampId == null) {
831
- log('Member %s already absent; skipping revoke', memberKey);
832
- return;
833
- }
834
- const signature = signStrandApproval(['Strand.Member', 'remove', memberKey, stampId], managerKeyPair.privateKeyB64);
835
- await inStrandTransaction(db, async () => {
836
- await db.exec(
837
- `delete from Strand.Member
838
- with context ManagerKey = ?, ManagerSignature = ?, MemberSignature = null
839
- where Key = ?`,
840
- [managerKeyPair.publicKeyB64, signature, memberKey],
841
- );
842
- await insertRevocation(db, 'Member', stampId, managerKeyPair);
843
- });
844
- log('Revoked member %s by manager %s', memberKey, managerKeyPair.publicKeyB64);
845
- }
846
-
847
- /** Parameters for {@link leaveStrand}. */
848
- export interface LeaveStrandParams {
849
- /**
850
- * The departing member's OWN strand keypair. Its `publicKeyB64` is the
851
- * `Member.Key` row being deleted; it self-signs the leave-tagged digest —
852
- * the self-departure branch verifies the signature against `old.Key` itself,
853
- * so only the departing key's holder can produce it — and files the
854
- * accompanying tombstone (it is still a committed member until this very
855
- * transaction removes it, which is what `Revocation.Authorized` checks). No
856
- * manager is involved.
857
- */
858
- memberKeyPair: Ed25519KeyPair;
859
- }
860
-
861
- /**
862
- * A member leaves the strand by deleting its own `Member` row.
863
- *
864
- * The self-departure branch of `Member.Authorized` verifies
865
- * `digest('Strand.Member', 'leave', old.Key, old.StampId)` against `old.Key`
866
- * itself via `context.MemberSignature`. The `'leave'` tag (vs the manager
867
- * branch's `'remove'`) is belt-and-braces only — the two branches verify against
868
- * different keys; the anti-replay fix is the stamp binding. Like
869
- * {@link revokeMember}, the live stamp is read first (absent row → quiet no-op)
870
- * and the delete pairs with its `Strand.Revocation` tombstone in one transaction.
871
- *
872
- * The same floors as {@link revokeMember} apply: a manager must resign first
873
- * (`NotAManager`) and the last member cannot leave (`MinOneMember`).
874
- *
875
- * @param db - The closed strand's database.
876
- * @param params - The departing member's own keypair.
877
- * @throws If `Member.Authorized`, `Member.NotAManager`, or `Member.MinOneMember`
878
- * rejects; the whole delete+tombstone transaction rolls back.
879
- */
880
- export async function leaveStrand(db: Database, params: LeaveStrandParams): Promise<void> {
881
- const { memberKeyPair } = params;
882
- const memberKey = memberKeyPair.publicKeyB64;
883
- const stampId = await memberStampId(db, memberKey);
884
- if (stampId == null) {
885
- log('Member %s already absent; skipping leave', memberKey);
886
- return;
887
- }
888
- const signature = signStrandApproval(['Strand.Member', 'leave', memberKey, stampId], memberKeyPair.privateKeyB64);
889
- await inStrandTransaction(db, async () => {
890
- await db.exec(
891
- `delete from Strand.Member
892
- with context ManagerKey = null, ManagerSignature = null, MemberSignature = ?
893
- where Key = ?`,
894
- [signature, memberKey],
895
- );
896
- await insertRevocation(db, 'Member', stampId, memberKeyPair);
897
- });
898
- log('Member %s left the strand', memberKey);
899
- }
900
-
901
- // ── MemberPeer registration (a member binds its own network nodes) ─────────────
902
-
903
- /** Parameters for {@link registerMemberPeer}. */
904
- export interface RegisterMemberPeerParams {
905
- /**
906
- * The member's OWN strand keypair (`{ privateKeyB64, publicKeyB64 }`). Its
907
- * `publicKeyB64` becomes `MemberPeer.MemberKey` and it self-signs the binding —
908
- * `MemberPeer.Authorized` verifies the signature against `MemberKey` itself, so a
909
- * peer can only be registered by the very member it belongs to (no manager
910
- * involved). The founder passes its `strandMemberKeyPair`; an invited member
911
- * passes its own keypair. Typed as {@link Ed25519KeyPair} only for the shared
912
- * base64url keypair shape — no manager privilege is implied.
913
- */
914
- memberKeyPair: Ed25519KeyPair;
915
- /** The peer/node id (libp2p peer id string) to associate with the member. */
916
- peerId: string;
917
- }
918
-
919
- /**
920
- * Register a network node (`PeerId`) as acting on behalf of a member.
921
- *
922
- * The member self-signs the add-tagged digest
923
- * `digest('Strand.MemberPeer', 'add', new.MemberKey, new.PeerId, new.StampId)`
924
- * with its OWN key; the schema's `MemberPeer.Authorized` verifies that signature
925
- * against `new.MemberKey` — i.e. the member key itself — so only the member that
926
- * owns the key can register peers for it. The stamp is minted fresh here and
927
- * bound inside the digest, so a captured registration approval neither
928
- * re-registers a cleared binding (its stamp is retired) nor authorizes a removal
929
- * (wrong tag). A deferred `MemberExists` additionally requires the `Member` row
930
- * to already exist, so a peer for a non-member is rejected at commit.
931
- *
932
- * Insert-if-absent: a re-register on restart (or a redundant call) is a no-op. The
933
- * platform DOES reject a duplicate-PK insert, but a restart-safe re-register should
934
- * succeed quietly rather than throw, so the writer guards on existence instead of
935
- * catching. The guard ({@link memberPeerStampId}) scans the member's peers and compares
936
- * both key columns in JavaScript rather than seeking the composite primary key — see
937
- * {@link scanMemberPeers} for why a full-PK point lookup is not reliable on a networked
938
- * strand. A member may register multiple DISTINCT `PeerId`s (multi-device); each is its
939
- * own row (and its own stamp) under the same `MemberKey`.
940
- *
941
- * Peer DELETION is signature-checked too, not rejected outright: `Authorized` carries
942
- * distinct delete branches (self + manager), each over its own action-tagged digest
943
- * bound to the row's stamp. Both removal paths live in {@link removeMemberPeer}.
944
- * UPDATE is refused outright by `NoUpdate`: a re-binding is a remove plus a fresh
945
- * register (under a fresh stamp).
946
- *
947
- * @param db - The closed strand's database (the member already exists).
948
- * @param params - The member's own keypair and the peer id to bind.
949
- * @throws If `MemberPeer.Authorized`/`MemberExists` rejects (wrong signer, or no
950
- * matching `Member` row); the insert rolls back, leaving no `MemberPeer` row.
951
- */
952
- export async function registerMemberPeer(db: Database, params: RegisterMemberPeerParams): Promise<void> {
953
- const { memberKeyPair, peerId } = params;
954
- const memberKey = memberKeyPair.publicKeyB64;
955
-
956
- if (await memberPeerStampId(db, memberKey, peerId) != null) {
957
- log('MemberPeer (%s, %s) already present; skipping', memberKey, peerId);
958
- return;
959
- }
960
-
961
- const stampId = generateStrandStampId();
962
- const signature = signStrandApproval(
963
- ['Strand.MemberPeer', 'add', memberKey, peerId, stampId],
964
- memberKeyPair.privateKeyB64,
965
- );
966
- await db.exec(
967
- `insert into Strand.MemberPeer (MemberKey, PeerId, StampId)
968
- with context Signature = ?, ManagerKey = null, ManagerSignature = null
969
- values (?, ?, ?)`,
970
- [signature, memberKey, peerId, stampId],
971
- );
972
- log('Registered MemberPeer (%s, %s)', memberKey, peerId);
973
- }
974
-
975
- /**
976
- * Yield every `(PeerId, StampId)` bound to `memberKey`, re-comparing the member key
977
- * in JavaScript.
978
- *
979
- * Deliberately does NOT filter on the full composite primary key. `MemberPeer`'s PK
980
- * is `(MemberKey, PeerId)`, so a `where MemberKey = ? and PeerId = ?` predicate puts
981
- * an equality on BOTH key columns — which the optimystic virtual-table module reports
982
- * as fully handled and serves via a single-key point lookup (one `find` descent), with
983
- * the SQL engine adding no filter of its own. On a networked strand that descent is not
984
- * reliable: a miss returns zero rows for a row that provably exists.
985
- *
986
- * Filtering on only the LEADING key column is a partial PK match, which the same module
987
- * explicitly declines to handle — it falls through to a table scan and the SQL engine
988
- * applies `MemberKey = ?` itself. No seek is involved, so no seek can miss. The member key
989
- * is then re-compared here in JavaScript, so correctness depends only on the scan returning
990
- * a SUPERSET of the matching rows — the weakest possible assumption about the storage layer.
991
- * The `where` clause only trims what crosses into JS — it is NOT pushed down (see the cost
992
- * note below) — so it is not a correctness dependency: a dropped or mis-applied predicate
993
- * cannot produce a row attributed to the wrong member.
994
- */
995
- async function* scanMemberPeers(db: Database, memberKey: string): AsyncGenerator<{ peerId: string; stampId: string }> {
996
- // NOTE: because the predicate is not pushed down, the storage layer walks the WHOLE
997
- // MemberPeer table (every member's rows) per call and the SQL engine filters. Fine at
998
- // strand scale; if MemberPeer ever grows large, the fix is a reliable composite-key
999
- // seek, not a bigger scan.
1000
- // NOTE: if a secondary index on MemberPeer.MemberKey is ever added, this query stops
1001
- // being a scan and becomes an index seek — re-introducing the seek dependency this
1002
- // shape exists to remove.
1003
- for await (const row of db.eval(
1004
- 'select MemberKey, PeerId, StampId from Strand.MemberPeer where MemberKey = ?',
1005
- [memberKey],
1006
- )) {
1007
- if (row.MemberKey === memberKey) {
1008
- yield { peerId: row.PeerId as string, stampId: row.StampId as string };
1009
- }
1010
- }
1011
- }
1012
-
1013
- /**
1014
- * Every `PeerId` currently bound to `memberKey`, in storage order.
1015
- *
1016
- * The enumeration side of {@link removeMemberPeer}: a manager cleaning up after a
1017
- * revocation knows only the departed member's key, never which devices it registered, so
1018
- * cleanup is `listMemberPeers` then one `removeMemberPeer` per id. Reads only — the rows
1019
- * it returns may name a `MemberKey` with no `Member` row (see the `MemberPeer` table NOTE
1020
- * in the schema), so this is NOT a membership test.
1021
- *
1022
- * @param db - The closed strand's database.
1023
- * @param memberKey - The `MemberPeer.MemberKey` to enumerate.
1024
- * @returns The bound peer ids, empty if the member has none.
1025
- */
1026
- export async function listMemberPeers(db: Database, memberKey: string): Promise<string[]> {
1027
- const peerIds: string[] = [];
1028
- for await (const peer of scanMemberPeers(db, memberKey)) {
1029
- peerIds.push(peer.peerId);
1030
- }
1031
- return peerIds;
1032
- }
1033
-
1034
- /**
1035
- * The live StampId of the `MemberPeer` row for this `(MemberKey, PeerId)`, or
1036
- * `undefined` if no such row is visible — doubling as the existence probe.
1037
- *
1038
- * NOTE: check-then-write is not atomic. Two nodes registering the same
1039
- * (MemberKey, PeerId) concurrently can both observe "absent"; the primary key is the
1040
- * real backstop. The existence half of this guard is for the sequential restart /
1041
- * re-register path.
1042
- */
1043
- async function memberPeerStampId(db: Database, memberKey: string, peerId: string): Promise<string | undefined> {
1044
- for await (const peer of scanMemberPeers(db, memberKey)) {
1045
- if (peer.peerId === peerId) {
1046
- return peer.stampId;
1047
- }
1048
- }
1049
- return undefined;
1050
- }
1051
-
1052
- /** Parameters for the SELF branch of {@link removeMemberPeer}. */
1053
- export interface RemoveOwnPeerParams {
1054
- /**
1055
- * The member's OWN strand keypair. Its `publicKeyB64` is the `MemberPeer.MemberKey`
1056
- * of the row being deleted, and it signs the remove-tagged digest
1057
- * `digest('Strand.MemberPeer', 'remove', MemberKey, PeerId, StampId)` — the self
1058
- * branch of `MemberPeer.Authorized` verifies against the row's own member key, so
1059
- * no OTHER member's row is reachable this way, and the tag + stamp binding keep a
1060
- * captured registration approval from doubling as a removal (and vice versa).
1061
- */
1062
- memberKeyPair: Ed25519KeyPair;
1063
- /** The `PeerId` of the binding to delete. */
1064
- peerId: string;
1065
- }
1066
-
1067
- /** Parameters for the MANAGER branch of {@link removeMemberPeer}. */
1068
- export interface RemoveMemberPeerByManagerParams {
1069
- /**
1070
- * The clearing manager's strand keypair. Its `publicKeyB64` must be a PRE-EXISTING
1071
- * `Strand.Manager` row (the manager branch reads `committed.Manager`, so a manager
1072
- * seated in the same transaction cannot authorize); it signs the
1073
- * manager-remove-tagged digest over the exact row and its live stamp, and files
1074
- * the accompanying tombstone.
1075
- */
1076
- managerKeyPair: Ed25519KeyPair;
1077
- /** The `MemberPeer.MemberKey` whose binding is being cleared. */
1078
- memberKey: string;
1079
- /** The `PeerId` of the binding to delete. */
1080
- peerId: string;
1081
- }
1082
-
1083
- /**
1084
- * Either shape accepted by {@link removeMemberPeer}. A discriminated union rather than
1085
- * one opaque keypair: the two branches sign DIFFERENT action tags (`'remove'` self vs
1086
- * `'manager-remove'`), so each case carries exactly the fields its payload needs.
1087
- */
1088
- export type RemoveMemberPeerParams = RemoveOwnPeerParams | RemoveMemberPeerByManagerParams;
1089
-
1090
- /**
1091
- * Delete a `MemberPeer` binding — either the member clearing its own, or a manager
1092
- * clearing another member's.
1093
- *
1094
- * Reads the row's live StampId first (absent → quiet no-op, mirroring
1095
- * {@link registerMemberPeer}'s insert-if-absent, so a repeated or restarted cleanup
1096
- * is not a silent zero-row "success" the caller cannot distinguish from a real one),
1097
- * then runs ONE transaction pairing the delete with its `Strand.Revocation`
1098
- * tombstone — `MemberPeer.RevocationRecorded` requires it, and the retirement is
1099
- * what keeps the captured registration approval from re-binding the cleared row.
1100
- *
1101
- * `MemberPeer` rows do NOT cascade when the member is revoked (`MemberExists` runs on
1102
- * insert only, and nothing deletes them), so a removed member's peer bindings survive
1103
- * as orphans — enumerate them with {@link listMemberPeers}, which is how a manager
1104
- * discovers what to clear. Only that member can sign the self branch, and a member being
1105
- * removed against its will has no reason to cooperate — hence the manager branch, which
1106
- * is the cleanup path after a revocation.
1107
- *
1108
- * The manager branch is deliberately NOT gated on the member already being gone: a
1109
- * manager may clear a still-present member's binding too, matching "any manager can
1110
- * remove any member". It verifies the manager-remove-tagged
1111
- * `digest('Strand.MemberPeer', 'manager-remove', old.MemberKey, old.PeerId, old.StampId)`
1112
- * against a `committed.Manager` row; the self branch verifies the remove-tagged
1113
- * sibling against the row's own member key.
1114
- *
1115
- * Cleanup is an explicit follow-up call by the revoking manager, never a cascade inside
1116
- * {@link revokeMember}: a revocation that also had to clear an unbounded number of peer
1117
- * rows in the same transaction would couple two concerns and make its failure modes
1118
- * harder to reason about.
1119
- *
1120
- * @param db - The closed strand's database.
1121
- * @param params - Either the owning member's keypair, or a manager's keypair plus the
1122
- * target member key.
1123
- * @throws If `MemberPeer.Authorized` rejects (neither branch satisfied), or if the row
1124
- * is still present after the delete (see the point-lookup note below).
1125
- */
1126
- export async function removeMemberPeer(db: Database, params: RemoveMemberPeerParams): Promise<void> {
1127
- const memberKey = 'memberKeyPair' in params ? params.memberKeyPair.publicKeyB64 : params.memberKey;
1128
- const { peerId } = params;
1129
-
1130
- const stampId = await memberPeerStampId(db, memberKey, peerId);
1131
- if (stampId == null) {
1132
- log('MemberPeer (%s, %s) already absent; skipping', memberKey, peerId);
1133
- return;
1134
- }
1135
-
1136
- await inStrandTransaction(db, async () => {
1137
- if ('memberKeyPair' in params) {
1138
- await deleteOwnMemberPeer(db, params, stampId);
1139
- } else {
1140
- await deleteMemberPeerByManager(db, params, stampId);
1141
- }
1142
- });
1143
-
1144
- // NOTE: the delete's `where` puts an equality on BOTH composite-PK columns, which the
1145
- // optimystic vtab module serves via a single-key seek that can MISS on a networked
1146
- // strand (see scanMemberPeers' doc). A missed seek deletes zero rows and still
1147
- // reports success. `Revocation.RowIsGone` now catches that first — the tombstone filed
1148
- // in the same transaction refuses to retire a stamp whose row is still visible, so the
1149
- // commit above fails loudly and this re-check is belt-and-braces behind it. Tracked as
1150
- // `debt-composite-pk-point-lookup-unreliable-untracked`; this is an availability
1151
- // failure mode, never a security one (a miss removes nothing, it never over-removes).
1152
- if (await memberPeerStampId(db, memberKey, peerId) != null) {
1153
- throw new Error(`MemberPeer (${memberKey}, ${peerId}) still present after delete`);
1154
- }
1155
- log('Removed MemberPeer (%s, %s)', memberKey, peerId);
1156
- }
1157
-
1158
- /** The self branch: the owning member signs the remove-tagged digest + tombstone. */
1159
- async function deleteOwnMemberPeer(db: Database, params: RemoveOwnPeerParams, stampId: string): Promise<void> {
1160
- const { memberKeyPair, peerId } = params;
1161
- const memberKey = memberKeyPair.publicKeyB64;
1162
- const signature = signStrandApproval(
1163
- ['Strand.MemberPeer', 'remove', memberKey, peerId, stampId],
1164
- memberKeyPair.privateKeyB64,
1165
- );
1166
- await db.exec(
1167
- `delete from Strand.MemberPeer
1168
- with context Signature = ?, ManagerKey = null, ManagerSignature = null
1169
- where MemberKey = ? and PeerId = ?`,
1170
- [signature, memberKey, peerId],
1171
- );
1172
- await insertRevocation(db, 'MemberPeer', stampId, memberKeyPair);
1173
- }
1174
-
1175
- /** The manager branch: a manager signs the manager-remove-tagged digest + tombstone. */
1176
- async function deleteMemberPeerByManager(
1177
- db: Database,
1178
- params: RemoveMemberPeerByManagerParams,
1179
- stampId: string,
1180
- ): Promise<void> {
1181
- const { managerKeyPair, memberKey, peerId } = params;
1182
- const signature = signStrandApproval(
1183
- ['Strand.MemberPeer', 'manager-remove', memberKey, peerId, stampId],
1184
- managerKeyPair.privateKeyB64,
1185
- );
1186
- await db.exec(
1187
- `delete from Strand.MemberPeer
1188
- with context Signature = null, ManagerKey = ?, ManagerSignature = ?
1189
- where MemberKey = ? and PeerId = ?`,
1190
- [managerKeyPair.publicKeyB64, signature, memberKey, peerId],
1191
- );
1192
- await insertRevocation(db, 'MemberPeer', stampId, managerKeyPair);
1193
- }
1194
-
1195
- // ── Manager rotation (add / remove RBAC admins) ───────────────────────────────
1196
-
1197
- /**
1198
- * The live `(Generation, StampId)` of the `Strand.Manager` row keyed by
1199
- * `memberKey`, or `undefined` if no such row is visible.
1200
- *
1201
- * `Manager`'s primary key is the single `MemberKey` column, so any where-equality
1202
- * on it is a full-PK point lookup — unreliable on a networked strand (see
1203
- * {@link scanMemberPeers}). An unfiltered scan + JavaScript filter instead, same
1204
- * as {@link memberStampId}. Serves both {@link addManager} (the authorizer's
1205
- * generation) and {@link removeManager} (the target's stamp).
1206
- */
1207
- async function managerRow(db: Database, memberKey: string): Promise<{ generation: number; stampId: string } | undefined> {
1208
- for await (const row of db.eval('select MemberKey, Generation, StampId from Strand.Manager')) {
1209
- if (row.MemberKey === memberKey) {
1210
- return { generation: Number(row.Generation), stampId: row.StampId as string };
1211
- }
1212
- }
1213
- return undefined;
1214
- }
1215
-
1216
- /** Parameters for {@link addManager}. */
1217
- export interface AddManagerParams {
1218
- /**
1219
- * An EXISTING manager's strand keypair. Its `publicKeyB64` must already be a
1220
- * `Strand.Manager` row (the existing-manager branch of `Manager.Authorized`
1221
- * rejects a non-manager once the founder manager exists); it signs the
1222
- * add-tagged digest over the new manager key, generation, and fresh stamp,
1223
- * and is bound as `context.ManagerKey`.
1224
- */
1225
- byManagerKeyPair: Ed25519KeyPair;
1226
- /** The member key to promote — the new `Manager.MemberKey` row. */
1227
- newManagerKey: string;
1228
- }
1229
-
1230
- /**
1231
- * Promote a key that is ALREADY a `Strand.Member` to `Manager` on the signature of
1232
- * an existing manager — use {@link admitManager} to admit and promote atomically.
1233
- *
1234
- * The promotion branch of `Manager.Authorized` requires the authorizer to be a
1235
- * `Manager` row of STRICTLY SMALLER `Generation` than the new row, verifying
1236
- * `digest('Strand.Manager', 'add', new.MemberKey, new.Generation, new.StampId)`
1237
- * against `context.ManagerKey`. So this writer reads the authorizer's generation,
1238
- * seats the new manager at that value + 1 (the natural successor; the schema
1239
- * enforces only the strict ordering), mints a fresh stamp, and signs the
1240
- * add-tagged digest over all three: the generation inside the signed digest keeps
1241
- * a captured promotion from replaying at a different generation, and the stamp
1242
- * keeps it from re-seating a second incarnation once this one is removed.
1243
- * `new.Generation` is an SQL INTEGER digest arg — the digest framing is
1244
- * type-tagged, so the TS side signs over the NUMBER itself
1245
- * (see {@link signStrandApproval}).
1246
- *
1247
- * The strict ordering — not this writer — is what makes a same-transaction takeover
1248
- * impossible; the `Manager.Generation` column comment in `schemas/strand.qsql` carries
1249
- * that argument. All this writer owes it is a generation strictly above the
1250
- * authorizer's, inside the signed payload.
1251
- *
1252
- * When the authorizer has NO `Manager` row (a non-manager signer, or an open
1253
- * strand with no managers at all), the scan finds nothing and the writer falls
1254
- * back to generation 1 and issues the insert anyway — deliberately letting the
1255
- * SCHEMA be the rejector (`Manager.Authorized` / `OnlyClosed`), not a
1256
- * writer-thrown error, so enforcement is pinned where it actually lives.
1257
- *
1258
- * @param db - The closed strand's database (founder manager already seated).
1259
- * @param params - The authorizing manager's keypair and the new manager key.
1260
- * @throws If `Manager.Authorized` rejects, or if `Manager.MemberExists` rejects because
1261
- * `newManagerKey` holds no `Member` row (admit it first, or use
1262
- * {@link admitManager}); the insert rolls back.
1263
- */
1264
- export async function addManager(db: Database, params: AddManagerParams): Promise<void> {
1265
- const { byManagerKeyPair, newManagerKey } = params;
1266
- const authorizer = await managerRow(db, byManagerKeyPair.publicKeyB64);
1267
- // NOTE: +1 saturates at Number.MAX_SAFE_INTEGER, where the successor compares equal
1268
- // to its authorizer and the schema rejects. Unreachable while generations only ever
1269
- // grow by 1 from 0, but the schema enforces ordering, not adjacency, so a manager may
1270
- // seat a successor at any larger value; if arbitrary generations ever become writable
1271
- // from outside this function, clamp or reject here rather than emitting a dead row.
1272
- const generation = authorizer == null ? 1 : authorizer.generation + 1;
1273
- const stampId = generateStrandStampId();
1274
- const signature = signStrandApproval(
1275
- ['Strand.Manager', 'add', newManagerKey, generation, stampId],
1276
- byManagerKeyPair.privateKeyB64,
1277
- );
1278
- await db.exec(
1279
- `insert into Strand.Manager (MemberKey, Generation, StampId)
1280
- with context ManagerKey = ?, Signature = ?
1281
- values (?, ?, ?)`,
1282
- [byManagerKeyPair.publicKeyB64, signature, newManagerKey, generation, stampId],
1283
- );
1284
- log('Added manager %s (generation %d) by %s', newManagerKey, generation, byManagerKeyPair.publicKeyB64);
1285
- }
1286
-
1287
- /** Parameters for {@link admitManager} — the same shape as {@link AddManagerParams}. */
1288
- export type AdmitManagerParams = AddManagerParams;
1289
-
1290
- /**
1291
- * Admit a key as a `Member` AND promote it to `Manager`, atomically — the one-step
1292
- * pair for a key that is not in the strand yet. {@link addManager} alone promotes a
1293
- * key that is already a member.
1294
- *
1295
- * ONE transaction, because `Manager.MemberExists` is a deferred check reading the LIVE
1296
- * `Member` table: the sibling `Member` insert satisfies it at the shared commit, and a
1297
- * rejection of either half rolls BOTH rows back — never a `Member` row seated by a
1298
- * failed promotion, nor a `Manager` row with no member behind it.
1299
- *
1300
- * NO new authority: both halves are signed by the SAME manager, over two distinct
1301
- * action-tagged digests — `digest('Strand.Member', 'add', …)` for the admission and
1302
- * `digest('Strand.Manager', 'add', …)` for the promotion — each bound to its own row's
1303
- * fresh stamp. This composes exactly the two approvals that manager could already
1304
- * issue separately.
1305
- *
1306
- * The promoting manager must be a PRE-transaction manager: the direct-admit branch of
1307
- * `Member.Authorized` reads `committed.Manager`, so `admitManager` cannot be chained —
1308
- * a manager seated by an `admitManager` earlier in the SAME transaction cannot admit
1309
- * the next one. (A same-transaction promotion CHAIN rooted at a pre-existing manager
1310
- * is fine; only the `Member` half needs the committed authorizer.)
1311
- *
1312
- * NOT insert-if-absent: a repeat call for a key that is already a member fails on the
1313
- * `Member` primary key, matching {@link addMemberByManager}'s unguarded shape.
1314
- *
1315
- * @param db - The closed strand's database (founder manager already seated).
1316
- * @param params - The authorizing manager's keypair and the key to admit + promote.
1317
- * @throws If either half is rejected (`Member.Authorized`, `Manager.Authorized`, a
1318
- * duplicate `Member` key, …); the whole transaction rolls back, leaving neither row.
1319
- */
1320
- export async function admitManager(db: Database, params: AdmitManagerParams): Promise<void> {
1321
- const { byManagerKeyPair, newManagerKey } = params;
1322
- await inStrandTransaction(db, async () => {
1323
- await addMemberByManager(db, { managerKeyPair: byManagerKeyPair, memberKey: newManagerKey });
1324
- await addManager(db, { byManagerKeyPair, newManagerKey });
1325
- });
1326
- log('Admitted + promoted manager %s by %s', newManagerKey, byManagerKeyPair.publicKeyB64);
1327
- }
1328
-
1329
- /** Parameters for {@link removeManager}. */
1330
- export interface RemoveManagerParams {
1331
- /**
1332
- * The keypair authorizing the removal, bound as `context.ManagerKey`. For an
1333
- * ADMIN removal this is a DIFFERENT existing manager, signing the
1334
- * remove-tagged digest (satisfying the existing-manager branch); for a
1335
- * SELF-resignation it is the target's OWN keypair (`publicKeyB64 ===
1336
- * targetManagerKey`), signing the resign-tagged digest (satisfying the
1337
- * former-manager self branch). The writer picks the tag by comparing the keys —
1338
- * see {@link removeManager}. Either way this keypair also files the
1339
- * accompanying tombstone, which requires it to be a PRE-transaction MEMBER
1340
- * (`Revocation.Authorized` reads `committed.Member`) — true for every manager,
1341
- * since managers are members.
1342
- */
1343
- byManagerKeyPair: Ed25519KeyPair;
1344
- /** The `Manager.MemberKey` row to delete. */
1345
- targetManagerKey: string;
1346
- }
1347
-
1348
- /**
1349
- * Remove a `Manager` row — either an admin removing a different manager or a
1350
- * manager resigning itself.
1351
- *
1352
- * Reads the target row's live `(Generation, StampId)` first (absent → quiet
1353
- * no-op, same restart-safe shape as {@link revokeMember}), then runs ONE
1354
- * transaction pairing the delete with its `Strand.Revocation` tombstone
1355
- * (`Manager.RevocationRecorded`). The two delete-side branches of
1356
- * `Manager.Authorized` verify DIFFERENT action-tagged digests, each bound to
1357
- * `(old.MemberKey, old.StampId)`:
1358
- * - **Admin removal** (`byManagerKeyPair` is a different existing manager): the
1359
- * removal branch verifies `digest('Strand.Manager', 'remove', old.MemberKey,
1360
- * old.StampId)` against `A.MemberKey = context.ManagerKey`. Deliberately NO
1361
- * generation condition: a later-generation manager may remove an
1362
- * earlier-generation one (generation is lineage, not privilege), and deletes
1363
- * are safe once inserts are — every accepting branch requires a `Manager` row
1364
- * in the post-image, and the promotion branch's generation ordering keeps
1365
- * attacker rows out of it. The stamp binding is what makes a captured removal
1366
- * single-use: a re-promoted manager carries a fresh stamp the old approval
1367
- * does not match — closing the removal half of
1368
- * `bug-strand-manager-authority-antireplay` (the insert half was already
1369
- * closed by the generation-bearing promotion payload).
1370
- * - **Self-resignation** (`byManagerKeyPair` IS the target): the former-manager
1371
- * self branch verifies `digest('Strand.Manager', 'resign', old.MemberKey,
1372
- * old.StampId)` against `old.MemberKey` itself. The distinct `'resign'` tag is
1373
- * belt-and-braces (different verifying keys); the anti-replay fix is the stamp.
1374
- *
1375
- * The caller selects the case purely by which keypair it passes; the only
1376
- * branching here is the action tag, chosen by comparing the signer to the target.
1377
- *
1378
- * The optimystic bootstrap-mode transactor evaluates deferred (subquery-bearing)
1379
- * CHECK constraints on DELETE as well as INSERT, so `Manager.Authorized` — deferred —
1380
- * IS enforced here: a signer that is neither an existing manager nor the target
1381
- * itself is rejected at commit.
1382
- *
1383
- * THE LAST MANAGER CANNOT BE REMOVED. `Manager.MinOneManager` (`check on delete`,
1384
- * deferred, so it sees the POST-delete count) rejects any delete that would leave the
1385
- * strand with zero managers — an admin-less closed strand could never admit anyone
1386
- * again, since `Invite`, `addMemberByManager`, and `addManager` all require a
1387
- * `Manager` row. The bootstrap branch of `Manager.Authorized` is gated to INSERTs
1388
- * (`old.MemberKey is null`), so it does not waive the signature check on a delete
1389
- * that drops the count toward the floor: a second-to-last removal is authorized
1390
- * exactly like any other.
1391
- *
1392
- * HAND-OFF ORDER: a sole manager transferring control must ADD the successor FIRST
1393
- * and resign SECOND. A same-transaction delete-then-insert swap is rejected — the
1394
- * bootstrap branch is gated to the founding state (at most one `Member`), and the
1395
- * successor's insert has no other manager to authorize it once the sole manager's
1396
- * row is gone.
1397
- *
1398
- * Cross-node caveat: `MinOneManager` counts rows visible to THIS transaction, so two
1399
- * nodes concurrently removing different managers can each see a survivor and still
1400
- * converge to zero. Noted in the schema; a cross-node floor is not attempted here.
1401
- *
1402
- * @param db - The closed strand's database.
1403
- * @param params - The authorizing keypair and the target manager key.
1404
- * @throws If `Manager.Authorized` rejects (a signer that is neither another existing
1405
- * manager nor the target itself) or `Manager.MinOneManager` rejects (the removal
1406
- * would leave no managers); the whole delete+tombstone transaction rolls back.
1407
- */
1408
- export async function removeManager(db: Database, params: RemoveManagerParams): Promise<void> {
1409
- const { byManagerKeyPair, targetManagerKey } = params;
1410
- const target = await managerRow(db, targetManagerKey);
1411
- if (target == null) {
1412
- log('Manager %s already absent; skipping removal', targetManagerKey);
1413
- return;
1414
- }
1415
- const tag = byManagerKeyPair.publicKeyB64 === targetManagerKey ? 'resign' : 'remove';
1416
- const signature = signStrandApproval(
1417
- ['Strand.Manager', tag, targetManagerKey, target.stampId],
1418
- byManagerKeyPair.privateKeyB64,
1419
- );
1420
- await inStrandTransaction(db, async () => {
1421
- await db.exec(
1422
- `delete from Strand.Manager
1423
- with context ManagerKey = ?, Signature = ?
1424
- where MemberKey = ?`,
1425
- [byManagerKeyPair.publicKeyB64, signature, targetManagerKey],
1426
- );
1427
- await insertRevocation(db, 'Manager', target.stampId, byManagerKeyPair);
1428
- });
1429
- log('Removed manager %s by %s', targetManagerKey, byManagerKeyPair.publicKeyB64);
1430
- }
1
+ import debug from 'debug';
2
+ import { toString as uint8ArrayToString } from 'uint8arrays';
3
+ import type { Database } from '@quereus/quereus';
4
+ import { digest, sign, verify, generatePrivateKey, getPublicKey, randomBytes } from '@optimystic/quereus-plugin-crypto';
5
+ import type { SAppConfig } from './types.js';
6
+ import type { Ed25519KeyPair } from './ed25519-key.js';
7
+ import { canonicalDatetime } from './canonical-datetime.js';
8
+
9
+ const log = debug('sereus:cadre:strand-membership');
10
+
11
+ /**
12
+ * The engine (rules-logic system) assumed to manage every strand. Persisted in
13
+ * `Strand.Header.Engine`.
14
+ *
15
+ * PLACEHOLDER SEAM: there is no engine-selection mechanism yet — Quereus is the
16
+ * only engine. When a real engine-config seam lands, the founder bootstrap should
17
+ * read the strand's chosen engine from there instead of this constant. Documented
18
+ * deliberately so the column is non-null and self-describing in the meantime.
19
+ */
20
+ export const STRAND_ENGINE = 'quereus';
21
+
22
+ /**
23
+ * The pinned engine version recorded in `Strand.Header.EngineVersion`. A pinned
24
+ * string for the same reason as {@link STRAND_ENGINE}: it is a documented
25
+ * placeholder until an engine-selection seam supplies the real running version.
26
+ */
27
+ export const STRAND_ENGINE_VERSION = '0.1.0';
28
+
29
+ /**
30
+ * The single-payload ed25519 signer the `Strand.Invite`/`Strand.ConsumedInvite`
31
+ * handshake constraints verify against.
32
+ *
33
+ * Those constraints sign a single SHA-256 digest over a `'|'`-joined payload
34
+ * (e.g. `InviteValid` verifies
35
+ * `verify(digest(new.Key || '|' || coalesce(new.Expiration, '')), ...)`).
36
+ * So the signer hashes the payload to raw bytes and ed25519-signs *those bytes*:
37
+ * SQL `digest(...)`'s default output is base64url and `verify(...)`'s default
38
+ * `inputEncoding` is base64url, so signer and verifier operate on identical bytes.
39
+ * The membership/RBAC tables (Member/Manager/MemberPeer/Revocation) instead use
40
+ * domain/action-tagged VARIADIC digests — see {@link signStrandApproval}.
41
+ *
42
+ * All strand keys are ed25519, so the explicit `'ed25519'` curve arg is mandatory
43
+ * (the crypto plugin otherwise defaults to secp256k1). Mirrors the proven
44
+ * `signItem` helper in the `rbac-signed-write` integration scenario.
45
+ *
46
+ * @param payload - The `'|'`-joined payload the matching constraint hashes.
47
+ * @param privateKeyB64 - The signer's base64url ed25519 private seed.
48
+ * @returns The base64url ed25519 signature over the payload's SHA-256 digest.
49
+ */
50
+ export function signStrandPayload(payload: string, privateKeyB64: string): string {
51
+ const hashBytes = digest([payload], 'sha256', 'bytes') as Uint8Array;
52
+ return sign(hashBytes, privateKeyB64, 'ed25519', 'bytes', 'base64url', 'base64url') as string;
53
+ }
54
+
55
+ /**
56
+ * The verifier counterpart to {@link signStrandPayload}.
57
+ *
58
+ * Mirrors what the single-payload `Strand.*` constraints compute:
59
+ * `verify(digest(payload), signature, publicKey, 'ed25519')`.
60
+ * SQL `digest`'s default output and `verify`'s default `inputEncoding`/`sigEncoding`/
61
+ * `keyEncoding` are all base64url, so the off-engine check operates on the exact
62
+ * same bytes the in-engine CHECK does. Used by the off-engine `MemberVerifier`
63
+ * (pre-flight registration checks) so the on-engine constraint is not the only
64
+ * place a member self-proof is validated.
65
+ *
66
+ * @param payload - The `'|'`-joined payload the matching constraint hashes.
67
+ * @param signatureB64 - The base64url ed25519 signature to check.
68
+ * @param publicKeyB64 - The base64url ed25519 public key to verify against.
69
+ * @returns `true` iff the signature is valid for the payload under that key.
70
+ */
71
+ export function verifyStrandPayload(payload: string, signatureB64: string, publicKeyB64: string): boolean {
72
+ const payloadDigest = digest([payload], 'sha256', 'base64url') as string;
73
+ return verify(payloadDigest, signatureB64, publicKeyB64, 'ed25519', 'base64url', 'base64url', 'base64url');
74
+ }
75
+
76
+ /**
77
+ * Sign a domain/action-tagged `Strand.*` membership/RBAC approval.
78
+ *
79
+ * Every `Authorized` branch on `Member`/`Manager`/`MemberPeer`/`Revocation`
80
+ * verifies a VARIADIC digest — `digest('<domain>', '<action>', <field>, ...,
81
+ * <StampId>)` — whose leading two elements are fixed literals (the domain tag,
82
+ * e.g. `'Strand.Member'`, and an action tag, e.g. `'add'`) and whose trailing
83
+ * element is the row's per-incarnation StampId. The tags keep an approval from
84
+ * verifying against any rule but the one it was minted for (the idiom of the
85
+ * control layer's `buildAuthorizationMessage`); the StampId binding makes it
86
+ * single-use — it authorizes exactly one incarnation of one row, and dies when
87
+ * that row's stamp is retired into `Strand.Revocation`.
88
+ *
89
+ * The caller passes the digest elements exactly as the matching SQL constraint
90
+ * lists them (each SQL argument = one array element), PRESERVING TYPE: the
91
+ * crypto plugin's digest framing is type-tagged (INTEGER 1 and TEXT '1' encode
92
+ * differently, deliberately), so `Manager.Authorized`'s promotion branch —
93
+ * whose digest includes the INTEGER `new.Generation` — must be signed over the
94
+ * NUMBER, not its string form. Integer `number` and `bigint` encode
95
+ * identically in that framing, so JS-side numbers match however the engine
96
+ * represents the SQL integer.
97
+ *
98
+ * Like {@link signStrandPayload}, the raw digest BYTES are ed25519-signed
99
+ * directly, matching SQL `verify(...)`'s default base64url input decoding.
100
+ *
101
+ * @param fields - The digest elements, in constraint order (tags first, StampId last).
102
+ * @param privateKeyB64 - The signer's base64url ed25519 private seed.
103
+ * @returns The base64url ed25519 signature over the tagged digest.
104
+ */
105
+ export function signStrandApproval(fields: ReadonlyArray<string | number>, privateKeyB64: string): string {
106
+ const hashBytes = digest(fields, 'sha256', 'bytes') as Uint8Array;
107
+ return sign(hashBytes, privateKeyB64, 'ed25519', 'bytes', 'base64url', 'base64url') as string;
108
+ }
109
+
110
+ /**
111
+ * Mint a fresh per-row authorization nonce (StampId) for a `Strand.Member`,
112
+ * `Strand.Manager`, or `Strand.MemberPeer` row.
113
+ *
114
+ * 256 bits of CSPRNG output, base64url-encoded — enough entropy that a future
115
+ * legitimate stamp cannot be guessed and pre-planted into `Strand.Revocation`
116
+ * (the `RowIsGone` comment in `schemas/strand.qsql` leans on exactly this).
117
+ * Plain randomness, deliberately NOT the control layer's peer-derived
118
+ * `generateStampId`: strand rows are not per-peer, so entropy alone carries
119
+ * the uniqueness.
120
+ *
121
+ * @returns A fresh base64url stamp (43 chars for 32 bytes).
122
+ */
123
+ export function generateStrandStampId(): string {
124
+ // randomBytes' first arg is BITS, not bytes — 256 bits = 32 bytes.
125
+ const bytes = randomBytes(256, 'bytes') as Uint8Array;
126
+ return uint8ArrayToString(bytes, 'base64url');
127
+ }
128
+
129
+ /**
130
+ * Run `fn` inside one explicit strand transaction: begin, fn, commit — with the
131
+ * standard rollback-on-failure shape.
132
+ *
133
+ * Used wherever two `Strand.*` writes must land atomically: the invite-consume
134
+ * pair (Member + ConsumedInvite) and every delete-plus-tombstone pair (the
135
+ * `RevocationRecorded` constraints require the `Revocation` row in the SAME
136
+ * transaction as the delete it retires).
137
+ *
138
+ * JOINS a caller-owned transaction instead of opening its own: Quereus's
139
+ * `Database.beginTransaction()` hard-throws "Transaction already active" on any
140
+ * nesting, and a caller composing several writers in one transaction (e.g. a
141
+ * resign + revoke pair that must land atomically) is exactly the case where the
142
+ * deferred constraints should fire once, at the CALLER's commit. In joined mode
143
+ * commit/rollback belong to the caller, so failures simply propagate.
144
+ */
145
+ async function inStrandTransaction(db: Database, fn: () => Promise<void>): Promise<void> {
146
+ if (!db.getAutocommit()) {
147
+ await fn();
148
+ return;
149
+ }
150
+ await db.beginTransaction();
151
+ try {
152
+ await fn();
153
+ await db.commit();
154
+ } catch (error) {
155
+ // A failed commit() already tears down the transaction, so rollback() would
156
+ // throw "No transaction active" and mask the real cause — swallow only that.
157
+ try {
158
+ await db.rollback();
159
+ } catch (rollbackError) {
160
+ log('Rollback after strand transaction failure was a no-op: %s', rollbackError);
161
+ }
162
+ throw error;
163
+ }
164
+ }
165
+
166
+ /**
167
+ * File the `Strand.Revocation` tombstone that retires a deleted row's StampId.
168
+ *
169
+ * Runs inside the SAME transaction as the delete it accompanies — the guarded
170
+ * tables' `RevocationRecorded` (deferred) requires the tombstone at commit, and
171
+ * `Revocation.RowIsGone` (also deferred) requires the row to already be gone, so
172
+ * the pair only ever lands together.
173
+ *
174
+ * `Revocation.Authorized` verifies the retire-tagged digest against a
175
+ * PRE-transaction (`committed.Member`) row, so the retiree must have been a
176
+ * member BEFORE this transaction. Every writer flow satisfies this: managers are
177
+ * members, and a self-departing member is committed until this very transaction
178
+ * removes it. Unlike the sibling tables' nullable contexts, `Revocation`'s
179
+ * context is non-null — both fields are always supplied.
180
+ *
181
+ * @param db - The strand database, INSIDE an open transaction.
182
+ * @param tableName - Which guarded table the stamp belonged to.
183
+ * @param stampId - The retired stamp.
184
+ * @param retiree - The committed member filing the tombstone (the delete's own signer).
185
+ */
186
+ async function insertRevocation(
187
+ db: Database,
188
+ tableName: 'Member' | 'Manager' | 'MemberPeer',
189
+ stampId: string,
190
+ retiree: Ed25519KeyPair,
191
+ ): Promise<void> {
192
+ const signature = signStrandApproval(['Strand.Revocation', 'retire', tableName, stampId], retiree.privateKeyB64);
193
+ await db.exec(
194
+ `insert into Strand.Revocation (TableName, StampId)
195
+ with context MemberKey = ?, Signature = ?
196
+ values (?, ?)`,
197
+ [retiree.publicKeyB64, signature, tableName, stampId],
198
+ );
199
+ }
200
+
201
+ /** Parameters for {@link bootstrapFounderMembership}. */
202
+ export interface FounderBootstrapParams {
203
+ /** The strand id — written to `Header.Id`. */
204
+ strandId: string;
205
+ /** Strand type: `'o'` (open, Header only) or `'c'` (closed, Header+Member+Manager). */
206
+ type: 'o' | 'c';
207
+ /** The sApp config whose id/version/schema/signature populate the Header. */
208
+ sApp: SAppConfig;
209
+ /**
210
+ * The founder's derived strand keypair (from {@link strandMemberKeyPair}). Its
211
+ * `publicKeyB64` becomes the founding `Member.Key` and `Manager.MemberKey`.
212
+ * Required for a closed strand; ignored for an open strand.
213
+ */
214
+ founderKeyPair?: Ed25519KeyPair;
215
+ }
216
+
217
+ /**
218
+ * Count rows in a `Strand.*` table as seen by this database instance.
219
+ *
220
+ * The table name is a fixed literal supplied by this module (never user input),
221
+ * so the interpolation is not an injection surface — it just keeps the singleton
222
+ * insert-if-absent guards terse.
223
+ */
224
+ async function strandTableCount(db: Database, table: 'Header' | 'Member' | 'Manager'): Promise<number> {
225
+ for await (const row of db.eval(`select count(1) as Count from Strand.${table}`)) {
226
+ return (row.Count as number) ?? 0;
227
+ }
228
+ return 0;
229
+ }
230
+
231
+ /**
232
+ * Insert the singleton `Strand.Header` if absent.
233
+ *
234
+ * Every `Header` column is NOT NULL (Quereus defaults unqualified columns to NOT
235
+ * NULL; the table declares no `null` columns), so all eight are supplied non-null.
236
+ * A missing `sApp.signature` (dev `requireSignedSchemas:false`) coalesces to `''`
237
+ * rather than inserting null. `Header` carries only `InsertOnly` + a singleton PK,
238
+ * so the insert needs no `with context`.
239
+ */
240
+ async function insertHeaderIfAbsent(db: Database, params: FounderBootstrapParams): Promise<void> {
241
+ if (await strandTableCount(db, 'Header') > 0) {
242
+ log('Header already present for strand %s; skipping', params.strandId);
243
+ return;
244
+ }
245
+ await db.exec(
246
+ `insert into Strand.Header
247
+ (Id, Type, sAppId, sAppVersion, sAppSchema, sAppSignature, Engine, EngineVersion)
248
+ values (?, ?, ?, ?, ?, ?, ?, ?)`,
249
+ [
250
+ params.strandId,
251
+ params.type,
252
+ params.sApp.id,
253
+ params.sApp.version,
254
+ params.sApp.schema,
255
+ params.sApp.signature ?? '',
256
+ STRAND_ENGINE,
257
+ STRAND_ENGINE_VERSION,
258
+ ],
259
+ );
260
+ log('Inserted Header for strand %s (type %s)', params.strandId, params.type);
261
+ }
262
+
263
+ /**
264
+ * Insert the founding `Strand.Member` if no member exists yet.
265
+ *
266
+ * The empty PRE-transaction member set (`count(1) from committed.Member = 0`)
267
+ * satisfies the bootstrap branch of `Member.Authorized`, so no signature is
268
+ * needed — the context fields are explicit nulls. The branch also caps the
269
+ * POST-image at one member, so it waives authorization for exactly this single
270
+ * seat, never for a batch. The row still mints a fresh StampId — the column is
271
+ * NOT NULL on every path; bootstrap only waives the SIGNATURE. Guarding on the
272
+ * count makes this idempotent: a re-run (the founder re-`addStrand`/
273
+ * `resumeStrand`) finds the member present and skips.
274
+ */
275
+ async function insertFounderMemberIfAbsent(db: Database, memberKey: string, strandId: string): Promise<void> {
276
+ if (await strandTableCount(db, 'Member') > 0) {
277
+ log('Member already present for strand %s; skipping founder Member', strandId);
278
+ return;
279
+ }
280
+ await db.exec(
281
+ `insert into Strand.Member (Key, StampId)
282
+ with context ManagerKey = null, ManagerSignature = null, MemberSignature = null
283
+ values (?, ?)`,
284
+ [memberKey, generateStrandStampId()],
285
+ );
286
+ log('Inserted founding Member for strand %s', strandId);
287
+ }
288
+
289
+ /**
290
+ * Insert the founding `Strand.Manager` if no manager exists yet.
291
+ *
292
+ * The empty-table state satisfies the bootstrap branch of `Manager.Authorized`, so
293
+ * no signature is needed (a fresh StampId is still minted — the column is NOT
294
+ * NULL). The founder is seated at `Generation = 0` — the root of
295
+ * the manager lineage; the bootstrap branch requires exactly that value, and every
296
+ * later manager is seated at a strictly greater generation (see {@link addManager}).
297
+ * Idempotent via the same count guard.
298
+ *
299
+ * ORDERING IS LOAD-BEARING, not merely convenient. The bootstrap branch is gated to
300
+ * the founding state and now reads `exists (select 1 from Member M where M.Key =
301
+ * new.MemberKey)` alongside `count(Manager) <= 1` and `count(Member) <= 1`, so the
302
+ * founding `Member` row MUST already exist when this commits — a Manager-first
303
+ * seeding path is rejected. It must also run AFTER the Header insert:
304
+ * `Manager.OnlyClosed` is a deferred (subquery) check evaluated at commit. The
305
+ * sequential auto-commit Header→Member→Manager order in
306
+ * {@link bootstrapFounderMembership} satisfies both.
307
+ */
308
+ async function insertFounderManagerIfAbsent(db: Database, memberKey: string, strandId: string): Promise<void> {
309
+ if (await strandTableCount(db, 'Manager') > 0) {
310
+ log('Manager already present for strand %s; skipping founder Manager', strandId);
311
+ return;
312
+ }
313
+ await db.exec(
314
+ `insert into Strand.Manager (MemberKey, Generation, StampId)
315
+ with context ManagerKey = null, Signature = null
316
+ values (?, 0, ?)`,
317
+ [memberKey, generateStrandStampId()],
318
+ );
319
+ log('Inserted founding Manager for strand %s', strandId);
320
+ }
321
+
322
+ /**
323
+ * Founder-only one-time bootstrap of a strand's `Strand.*` membership/RBAC rows.
324
+ *
325
+ * Runs once at bring-up on the strand's FOUNDER (the party that provisioned and
326
+ * published the strand). A joiner never calls this — it receives these rows via
327
+ * Optimystic sync. Every write is insert-if-absent (guarded by a row count) so a
328
+ * restart / founder re-`addStrand` is a no-op and never double-inserts.
329
+ *
330
+ * Behavior by strand type:
331
+ * - **Open (`'o'`)**: insert `Header` only. `Member`/`Manager`/`Invite` are
332
+ * `OnlyClosed` and would trip that constraint — they are skipped entirely.
333
+ * - **Closed (`'c'`)**: insert `Header(Type='c')`, then the founding `Member`
334
+ * (`Key = founderKeyPair.publicKeyB64`), then the founding `Manager`
335
+ * (`MemberKey = founderKeyPair.publicKeyB64`). Insert order matters: the
336
+ * Header must commit before the deferred `OnlyClosed` checks on Member/Manager
337
+ * evaluate at commit.
338
+ *
339
+ * A closed strand with no `founderKeyPair` throws: a closed strand with no founding
340
+ * Manager could never admit anyone, so failing loudly here (which propagates out
341
+ * of `StrandDatabase.initialize()` and triggers the runtime's rollback) is correct.
342
+ *
343
+ * @param db - The strand's Quereus database (schema already applied).
344
+ * @param params - Strand id/type, the sApp config for the Header, and (closed only)
345
+ * the derived founder keypair.
346
+ * @throws If `type === 'c'` and no `founderKeyPair` is supplied.
347
+ */
348
+ export async function bootstrapFounderMembership(db: Database, params: FounderBootstrapParams): Promise<void> {
349
+ const { strandId, type, founderKeyPair } = params;
350
+ log('Founder bootstrap for strand %s (type %s)', strandId, type);
351
+
352
+ // Validate BEFORE writing anything: a closed strand with no founder key must
353
+ // fail without leaving a closed `Header` that has no founding Member/Manager
354
+ // (such a strand could never admit anyone).
355
+ if (type === 'c' && !founderKeyPair) {
356
+ throw new Error(
357
+ `Cannot bootstrap closed strand ${strandId}: no founder key pair derived from MemberPrivateKey. ` +
358
+ 'A closed strand needs a founding Member + Manager or it can never admit members.',
359
+ );
360
+ }
361
+
362
+ // Header is written for every strand; Member/Manager are closed-only.
363
+ await insertHeaderIfAbsent(db, params);
364
+
365
+ if (type === 'o') {
366
+ // Open strand: Member/Manager/Invite are OnlyClosed — nothing else to write.
367
+ return;
368
+ }
369
+
370
+ const memberKey = founderKeyPair!.publicKeyB64;
371
+ await insertFounderMemberIfAbsent(db, memberKey, strandId);
372
+ await insertFounderManagerIfAbsent(db, memberKey, strandId);
373
+ log('Founder bootstrap complete for closed strand %s', strandId);
374
+ }
375
+
376
+ // ── Invite issuance + consumption (the per-strand join handshake) ─────────────
377
+
378
+ /** Parameters for {@link issueInvite}. */
379
+ export interface IssueInviteParams {
380
+ /**
381
+ * The issuing manager's strand keypair. Its `publicKeyB64` must already be a
382
+ * `Strand.Manager` row (the `InviteValid` constraint rejects a non-manager).
383
+ */
384
+ managerKeyPair: Ed25519KeyPair;
385
+ /**
386
+ * Optional invite expiry as epoch milliseconds. When set, it is canonicalised
387
+ * via {@link canonicalDatetime} so the signed payload segment byte-matches the
388
+ * `datetime`-coerced `Invite.Expiration` the deferred CHECK sees. When omitted,
389
+ * the invite never expires and the signed segment is `''` (matching the schema's
390
+ * `coalesce(new.Expiration, '')`).
391
+ */
392
+ expiration?: number;
393
+ }
394
+
395
+ /** The minted invite: a public key (the `Invite.Key`) plus its private seed. */
396
+ export interface IssuedInvite {
397
+ /** The invite ed25519 PUBLIC key (base64url) — the `Invite.Key` primary key. */
398
+ inviteKey: string;
399
+ /**
400
+ * The invite ed25519 PRIVATE seed (base64url). Handed out-of-band to the
401
+ * invitee; whoever holds it can {@link consumeInvite} exactly once. NEVER
402
+ * persisted in the strand — only the public key is.
403
+ */
404
+ invitePrivateKey: string;
405
+ }
406
+
407
+ /**
408
+ * Issue a single-use invitation to join a closed strand.
409
+ *
410
+ * Generates a fresh invite ed25519 keypair (the public key becomes `Invite.Key`),
411
+ * builds the constraint's payload (`Key || '|' || coalesce(Expiration, '')`), and
412
+ * signs it TWICE: with the manager private key (→ `ManagerSignature`, proving
413
+ * a manager issued it) and with the invite private key (→ `InviteSignature`,
414
+ * proving the issuer actually holds the invite secret). Both signatures plus the
415
+ * manager public key are bound as constraint context for the `Invite` insert.
416
+ *
417
+ * The returned `invitePrivateKey` is the only secret the invitee needs to redeem
418
+ * the invite — it is NOT stored in the strand (only `Invite.Key`, the public half,
419
+ * is). Single-use is enforced at consumption time: `ConsumedInvite`'s primary key
420
+ * is `InviteKey`, so a given invite can be consumed at most once.
421
+ *
422
+ * @param db - The closed strand's database (founder already bootstrapped).
423
+ * @param params - The issuing manager keypair and optional expiry.
424
+ * @returns The invite public key and the out-of-band private seed.
425
+ */
426
+ export async function issueInvite(db: Database, params: IssueInviteParams): Promise<IssuedInvite> {
427
+ const { managerKeyPair, expiration } = params;
428
+
429
+ const invitePrivateKey = generatePrivateKey('ed25519', 'base64url') as string;
430
+ const inviteKey = getPublicKey(invitePrivateKey, 'ed25519', 'base64url', 'base64url') as string;
431
+
432
+ // Canonicalise the expiry to the engine's stored `datetime` form so the signed
433
+ // segment matches `new.Expiration` post-coercion; null expiry signs as ''.
434
+ const expirationSegment = expiration == null ? '' : await canonicalDatetime(db, expiration);
435
+ const expirationColumn = expiration == null ? null : expirationSegment;
436
+
437
+ const payload = `${inviteKey}|${expirationSegment}`;
438
+ const managerSignature = signStrandPayload(payload, managerKeyPair.privateKeyB64);
439
+ const inviteSignature = signStrandPayload(payload, invitePrivateKey);
440
+
441
+ await db.exec(
442
+ `insert into Strand.Invite (Key, Expiration)
443
+ with context ManagerKey = ?, ManagerSignature = ?, InviteSignature = ?
444
+ values (?, ?)`,
445
+ [managerKeyPair.publicKeyB64, managerSignature, inviteSignature, inviteKey, expirationColumn],
446
+ );
447
+ log('Issued invite %s (expires=%s)', inviteKey, expirationColumn ?? 'never');
448
+
449
+ return { inviteKey, invitePrivateKey };
450
+ }
451
+
452
+ /** Parameters for {@link consumeInvite}. */
453
+ export interface ConsumeInviteParams {
454
+ /** The `Invite.Key` (invite PUBLIC key, base64url) being redeemed. */
455
+ inviteKey: string;
456
+ /** The matching invite PRIVATE seed (base64url) received out-of-band. */
457
+ invitePrivateKey: string;
458
+ /** The joining member's ed25519 PUBLIC key (base64url) — the new `Member.Key`. */
459
+ memberKey: string;
460
+ /**
461
+ * The instant (epoch ms) to compare against the invite's `Expiration` for the
462
+ * `NotExpired` gate. Defaults to `Date.now()`; tests pin it so the comparison is
463
+ * deterministic. Mirrors the control-layer `redeemInvitation`'s `nowMs` convention.
464
+ */
465
+ nowMs?: number;
466
+ }
467
+
468
+ /**
469
+ * Redeem an invite to admit a new `Member`, atomically.
470
+ *
471
+ * `Member.Authorized`'s invite branch needs a `ConsumedInvite` row, while
472
+ * `ConsumedInvite`'s `MemberExists` needs the `Member` row — a circular
473
+ * dependency. Both are deferred (subquery-bearing) checks that evaluate
474
+ * at COMMIT, so inserting `Member` then `ConsumedInvite` inside one explicit
475
+ * transaction lets both rows exist when the deferred checks fire. This mirrors
476
+ * `ControlDatabase.redeemInvitation` (Strand + FormationUsage in one txn).
477
+ *
478
+ * The `ConsumedInvite` insert carries an `InviteSignature` over
479
+ * `InviteKey || '|' || MemberKey`, proving the consumer holds the invite private
480
+ * key (the on-engine `ValidUsage` gate). The `Member` insert needs no member
481
+ * signature — its admission is the existence of the matching `ConsumedInvite` —
482
+ * but still mints a fresh StampId (NOT NULL on every path; a revoked-then-
483
+ * re-invited member is a fresh incarnation under a fresh stamp).
484
+ *
485
+ * Single-use: `ConsumedInvite`'s primary key is `InviteKey`, so a second consume
486
+ * of the same invite is rejected by the PK (a distinct layer from the control
487
+ * network's `FormationUsage` single-use, which gates strand FORMATION, not the
488
+ * per-strand member join enforced here).
489
+ *
490
+ * Expiry: the `ConsumedInvite.NotExpired` deferred check rejects redeeming an invite
491
+ * whose `Expiration` is at or before `context.Now`. `Now` is supplied here as a
492
+ * canonical-datetime string from `canonicalDatetime(db, nowMs)` — the SAME transform
493
+ * `issueInvite` uses to store `Invite.Expiration` — so both sides of the schema's
494
+ * `I.Expiration > context.Now` comparison are byte-identical canonical strings and
495
+ * the lexical `>` orders chronologically at any granularity. (This intentionally
496
+ * diverges from the control layer, which passes `Now` as a JS ISO string; Quereus
497
+ * does not coerce context params, so an ISO `Now` would be compared lexically against
498
+ * the canonical, T-separated `Expiration` and could mis-order near-same-instant
499
+ * timestamps (due to a trailing `.000Z` suffix). The control tests only use far-future/far-past expiries, so that latent
500
+ * skew never bites there — the strand layer avoids it outright.) A null `Expiration`
501
+ * never expires. Like `ValidUsage`, `NotExpired` defers to commit, so an expired
502
+ * invite rolls back the whole txn — neither the `Member` nor the `ConsumedInvite`
503
+ * row survives.
504
+ *
505
+ * @param db - The closed strand's database.
506
+ * @param params - The invite key/secret, the joining member's public key, and an
507
+ * optional `nowMs` instant for the expiry comparison (default `Date.now()`).
508
+ * @throws If any constraint rejects (bad signature, missing invite, or an expired
509
+ * invite); the whole transaction rolls back (neither the `Member` nor the
510
+ * `ConsumedInvite` row survives).
511
+ */
512
+ export async function consumeInvite(db: Database, params: ConsumeInviteParams): Promise<void> {
513
+ const { inviteKey, invitePrivateKey, memberKey, nowMs } = params;
514
+
515
+ const usagePayload = `${inviteKey}|${memberKey}`;
516
+ const inviteSignature = signStrandPayload(usagePayload, invitePrivateKey);
517
+
518
+ // Canonicalise "now" the same way issueInvite canonicalises Expiration, so the
519
+ // schema's `I.Expiration > context.Now` compares like-for-like canonical strings.
520
+ // Plain runtime Date.now() — the tess Workflow restriction is on scripts, not libs.
521
+ const nowCanonical = await canonicalDatetime(db, nowMs ?? Date.now());
522
+
523
+ await inStrandTransaction(db, async () => {
524
+ // 1. Member — admitted by the deferred invite branch (the matching
525
+ // ConsumedInvite below), so no manager signature is supplied.
526
+ await db.exec(
527
+ `insert into Strand.Member (Key, StampId)
528
+ with context ManagerKey = null, ManagerSignature = null, MemberSignature = null
529
+ values (?, ?)`,
530
+ [memberKey, generateStrandStampId()],
531
+ );
532
+
533
+ // 2. ConsumedInvite — proves possession of the invite private key and that the
534
+ // invite has not expired (NotExpired gate against the canonical Now).
535
+ await db.exec(
536
+ `insert into Strand.ConsumedInvite (InviteKey, MemberKey)
537
+ with context InviteSignature = ?, Now = ?
538
+ values (?, ?)`,
539
+ [inviteSignature, nowCanonical, inviteKey, memberKey],
540
+ );
541
+ });
542
+ log('Consumed invite %s -> member %s', inviteKey, memberKey);
543
+ }
544
+
545
+ /**
546
+ * Every value of `InviteKey` in one of the two invite-marker tables, as a `Set`.
547
+ *
548
+ * Unfiltered scan + JavaScript comparison, deliberately: `ConsumedInvite` and
549
+ * `CancelledInvite` each have the single column `InviteKey` as their primary key, so
550
+ * ANY where-equality on it is a FULL-PK predicate — which the optimystic virtual-table
551
+ * module serves via a single-key point lookup that can MISS on a networked strand (the
552
+ * argument {@link scanMemberPeers} makes in full). Reading the whole column and
553
+ * comparing in JS depends only on the scan returning a SUPERSET of the live rows.
554
+ *
555
+ * The table name is a fixed literal supplied by this module (never user input), so the
556
+ * interpolation is not an injection surface — same as {@link strandTableCount}.
557
+ *
558
+ * NOTE: every caller pays a WHOLE-column read — {@link cancelInvite}'s idempotence guard
559
+ * reads all cancelled keys to answer one membership question, and
560
+ * {@link listOutstandingInvites} reads both marker tables per call. Fine at strand scale
561
+ * (a handful of invitations); if invite churn ever gets large this wants a real filtered
562
+ * read, which in turn needs the networked point-lookup gap closed
563
+ * (`debt-composite-pk-point-lookup-unreliable-untracked`).
564
+ */
565
+ async function scanInviteKeys(db: Database, table: 'ConsumedInvite' | 'CancelledInvite'): Promise<Set<string>> {
566
+ const keys = new Set<string>();
567
+ for await (const row of db.eval(`select InviteKey from Strand.${table}`)) {
568
+ keys.add(row.InviteKey as string);
569
+ }
570
+ return keys;
571
+ }
572
+
573
+ /** Parameters for {@link cancelInvite}. */
574
+ export interface CancelInviteParams {
575
+ /**
576
+ * The cancelling manager's strand keypair. Its `publicKeyB64` must be a
577
+ * PRE-EXISTING `Strand.Manager` row — `CancelledInvite.Authorized` reads
578
+ * `committed.Manager`, so a manager seated in the SAME transaction cannot cancel.
579
+ */
580
+ managerKeyPair: Ed25519KeyPair;
581
+ /** The `Invite.Key` to kill. */
582
+ inviteKey: string;
583
+ }
584
+
585
+ /**
586
+ * Cancel an outstanding invitation, permanently: it may never be consumed.
587
+ *
588
+ * Files a `Strand.CancelledInvite` tombstone carrying a manager signature over
589
+ * `digest('Strand.CancelledInvite', 'cancel', InviteKey)`. The digest binds the exact
590
+ * invite key, so an approval minted for one invitation cannot cancel another.
591
+ *
592
+ * One row, one statement — no transaction needed. `CancelledInvite.Authorized` is a
593
+ * deferred (subquery-bearing) check, so it fires at this statement's own auto-commit.
594
+ *
595
+ * Insert-if-absent, matching {@link registerMemberPeer}'s and {@link revokeMember}'s
596
+ * restart-safe shape: a repeat cancellation logs and returns rather than throwing on the
597
+ * primary key. (Check-then-write is not atomic; the primary key is the real backstop —
598
+ * the guard is for the sequential repeat/restart path.)
599
+ *
600
+ * Cancellation is what makes removal a re-entry gate: it is the `ConsumedInvite` insert
601
+ * that `NotCancelled` blocks, and `Member.Authorized`'s invite branch needs a
602
+ * same-transaction FRESH `ConsumedInvite` row, so a cancelled invitation rolls the whole
603
+ * join back. Un-cancelling is impossible (`CancelledInvite.Immutable`) — to re-invite a
604
+ * party, {@link issueInvite} a fresh invitation.
605
+ *
606
+ * Enumerate what there is to cancel with {@link listOutstandingInvites}: an invitation
607
+ * names no invitee, so the strand cannot tell a manager WHICH invitations a departing
608
+ * member holds. Invitee binding is tracked as `feat-strand-invitee-bound-invites`.
609
+ *
610
+ * @param db - The closed strand's database.
611
+ * @param params - The cancelling manager's keypair and the invite key to kill.
612
+ * @throws If `CancelledInvite.Authorized` rejects (a non-manager, a manager seated in
613
+ * this transaction, or an approval minted for a different invite key) or `OnlyClosed`
614
+ * rejects (an open strand); the insert rolls back, leaving no tombstone.
615
+ */
616
+ export async function cancelInvite(db: Database, params: CancelInviteParams): Promise<void> {
617
+ const { managerKeyPair, inviteKey } = params;
618
+
619
+ if ((await scanInviteKeys(db, 'CancelledInvite')).has(inviteKey)) {
620
+ log('Invite %s already cancelled; skipping', inviteKey);
621
+ return;
622
+ }
623
+
624
+ const signature = signStrandApproval(
625
+ ['Strand.CancelledInvite', 'cancel', inviteKey],
626
+ managerKeyPair.privateKeyB64,
627
+ );
628
+ await db.exec(
629
+ `insert into Strand.CancelledInvite (InviteKey)
630
+ with context ManagerKey = ?, ManagerSignature = ?
631
+ values (?)`,
632
+ [managerKeyPair.publicKeyB64, signature, inviteKey],
633
+ );
634
+ log('Cancelled invite %s by manager %s', inviteKey, managerKeyPair.publicKeyB64);
635
+ }
636
+
637
+ /** One redeemable invitation, as reported by {@link listOutstandingInvites}. */
638
+ export interface OutstandingInvite {
639
+ /** The `Invite.Key` (invite public key, base64url). */
640
+ inviteKey: string;
641
+ /**
642
+ * The expiry as the engine's canonical `datetime` string
643
+ * (`YYYY-MM-DDTHH:MM:SS[.frac]`, no zone suffix — see {@link canonicalDatetime}), or
644
+ * `null` for never-expires.
645
+ *
646
+ * Deliberately the STORED form, not the epoch-ms {@link IssueInviteParams.expiration}
647
+ * takes: it is what compares like-for-like against another canonicalised instant, and
648
+ * what the on-engine `NotExpired` gate sees. It is NOT a JS-parseable ISO instant —
649
+ * pass it through the engine (or `canonicalDatetime`) rather than `Date.parse`.
650
+ */
651
+ expiration: string | null;
652
+ }
653
+
654
+ /**
655
+ * The invitations that are still redeemable: neither consumed, nor cancelled, nor
656
+ * expired at `nowMs`.
657
+ *
658
+ * `Strand.Invite` is insert-only and carries no state column, so "outstanding" is not a
659
+ * property of the row — it is the `Invite` set minus the `ConsumedInvite` keys, minus
660
+ * the `CancelledInvite` keys, minus anything whose `Expiration` has passed. All three
661
+ * exclusions mirror gates a consume would hit anyway (`ConsumedInvite`'s primary key,
662
+ * `NotCancelled`, `NotExpired`).
663
+ *
664
+ * Reads via unfiltered scans and compares in JavaScript — see {@link scanInviteKeys} for
665
+ * why a full-PK where-equality is not reliable on a networked strand.
666
+ *
667
+ * Expiry is compared as `expiration > canonicalDatetime(nowMs)`: the same transform
668
+ * {@link issueInvite} uses to STORE `Invite.Expiration`, so the string comparison orders
669
+ * chronologically, and the same strict `>` the on-engine `NotExpired` gate uses (expiry
670
+ * is exclusive — an invitation is dead at its expiry instant, not after it).
671
+ *
672
+ * This is the manager's enumeration side of {@link cancelInvite}, and the "door is open"
673
+ * pre-flight behind `StrandMemberVerifier.isAuthorizedToJoin`.
674
+ *
675
+ * @param db - The closed strand's database.
676
+ * @param nowMs - The instant (epoch ms) to compare expiries against; defaults to
677
+ * `Date.now()`. Tests pin it so the comparison is deterministic, mirroring
678
+ * {@link consumeInvite}'s `nowMs` convention.
679
+ * @returns The redeemable invitations, in NO guaranteed order (the scans promise only a
680
+ * superset of the live rows, not a stable sequence — sort by `expiration` if order
681
+ * matters); empty if none.
682
+ */
683
+ export async function listOutstandingInvites(db: Database, nowMs?: number): Promise<OutstandingInvite[]> {
684
+ // Plain runtime Date.now() — the tess Workflow restriction is on scripts, not libs.
685
+ const nowCanonical = await canonicalDatetime(db, nowMs ?? Date.now());
686
+ const consumed = await scanInviteKeys(db, 'ConsumedInvite');
687
+ const cancelled = await scanInviteKeys(db, 'CancelledInvite');
688
+
689
+ const outstanding: OutstandingInvite[] = [];
690
+ for await (const row of db.eval('select Key, Expiration from Strand.Invite')) {
691
+ const inviteKey = row.Key as string;
692
+ const expiration = (row.Expiration as string | null) ?? null;
693
+ if (consumed.has(inviteKey) || cancelled.has(inviteKey)) {
694
+ continue;
695
+ }
696
+ if (expiration != null && expiration <= nowCanonical) {
697
+ continue;
698
+ }
699
+ outstanding.push({ inviteKey, expiration });
700
+ }
701
+ return outstanding;
702
+ }
703
+
704
+ // ── Member admission + removal (manager-admit, revoke, leave) ─────────────────
705
+
706
+ /**
707
+ * The live StampId of the `Strand.Member` row keyed by `memberKey`, or
708
+ * `undefined` if no such row is visible.
709
+ *
710
+ * `Member`'s primary key is the single `Key` column, so ANY where-equality on it
711
+ * is a full-PK predicate — which the optimystic virtual-table module serves via a
712
+ * single-key point lookup that can MISS on a networked strand (the same failure
713
+ * mode {@link scanMemberPeers} documents). So this reads via an UNFILTERED scan
714
+ * and compares the key in JavaScript: correctness depends only on the scan
715
+ * returning a superset of the live rows — the weakest possible assumption about
716
+ * the storage layer.
717
+ */
718
+ async function memberStampId(db: Database, memberKey: string): Promise<string | undefined> {
719
+ for await (const row of db.eval('select Key, StampId from Strand.Member')) {
720
+ if (row.Key === memberKey) {
721
+ return row.StampId as string;
722
+ }
723
+ }
724
+ return undefined;
725
+ }
726
+
727
+ /** Parameters for {@link addMemberByManager}. */
728
+ export interface AddMemberByManagerParams {
729
+ /**
730
+ * The admitting manager's strand keypair. Its `publicKeyB64` must be a
731
+ * `Strand.Manager` row; it signs the add-tagged digest over the new member key
732
+ * and its fresh stamp.
733
+ */
734
+ managerKeyPair: Ed25519KeyPair;
735
+ /** The joining member's ed25519 PUBLIC key (base64url) — the new `Member.Key`. */
736
+ memberKey: string;
737
+ }
738
+
739
+ /**
740
+ * Admit a `Member` directly by manager signature — the sibling of the invite
741
+ * path on `Member.Authorized`'s direct-manager branch.
742
+ *
743
+ * The constraint verifies the add-tagged digest
744
+ * `digest('Strand.Member', 'add', new.Key, new.StampId)` against a pre-existing
745
+ * (`committed.Manager`) row matching `context.ManagerKey`. The stamp is minted
746
+ * fresh here and bound inside the signed digest, so the approval seats exactly
747
+ * this incarnation: once the member is removed (retiring the stamp), the captured
748
+ * approval can never re-seat it. No `ConsumedInvite` is involved: this is the
749
+ * path a manager uses to seat a member it already trusts (e.g. a manager-side
750
+ * enrollment that admits a party already authorised out-of-band).
751
+ *
752
+ * @param db - The closed strand's database.
753
+ * @param params - The admitting manager keypair and the new member key.
754
+ * @throws If `Member.Authorized` rejects (e.g. a non-manager key); the insert
755
+ * rolls back, leaving no `Member` row.
756
+ */
757
+ export async function addMemberByManager(db: Database, params: AddMemberByManagerParams): Promise<void> {
758
+ const { managerKeyPair, memberKey } = params;
759
+ const stampId = generateStrandStampId();
760
+ const signature = signStrandApproval(['Strand.Member', 'add', memberKey, stampId], managerKeyPair.privateKeyB64);
761
+ await db.exec(
762
+ `insert into Strand.Member (Key, StampId)
763
+ with context ManagerKey = ?, ManagerSignature = ?, MemberSignature = null
764
+ values (?, ?)`,
765
+ [managerKeyPair.publicKeyB64, signature, memberKey, stampId],
766
+ );
767
+ log('Admitted member %s by manager %s', memberKey, managerKeyPair.publicKeyB64);
768
+ }
769
+
770
+ /** Parameters for {@link revokeMember}. */
771
+ export interface RevokeMemberParams {
772
+ /**
773
+ * The revoking manager's strand keypair. Its `publicKeyB64` must be a
774
+ * PRE-EXISTING `Strand.Manager` row (the manager-removal branch of
775
+ * `Member.Authorized` reads `committed.Manager` — a manager seated in the same
776
+ * transaction cannot authorize); it signs the remove-tagged digest over the
777
+ * target row's key and live stamp, and files the accompanying tombstone.
778
+ */
779
+ managerKeyPair: Ed25519KeyPair;
780
+ /** The `Member.Key` row to delete. */
781
+ memberKey: string;
782
+ }
783
+
784
+ /**
785
+ * Revoke a `Member` on the signature of an existing manager.
786
+ *
787
+ * Reads the target row's live StampId first (a quiet no-op if the row is already
788
+ * absent — a repeated or restarted revocation should not throw), then runs ONE
789
+ * transaction pairing the delete with its `Strand.Revocation` tombstone: the
790
+ * schema's `Member.RevocationRecorded` requires the tombstone in the same
791
+ * transaction, and the tombstone is what permanently retires the stamp so the
792
+ * captured admission approval can never re-seat this incarnation.
793
+ *
794
+ * The manager-removal branch of `Member.Authorized` verifies the remove-tagged
795
+ * digest `digest('Strand.Member', 'remove', old.Key, old.StampId)` against a
796
+ * `committed.Manager` row matching `context.ManagerKey` — distinct from the
797
+ * add-tagged admission payload, and bound to the live stamp, so neither a
798
+ * captured admission nor a captured PRIOR removal (whose stamp differs) replays.
799
+ *
800
+ * A revoked member cannot re-admit itself off the invite it ALREADY SPENT: that
801
+ * `ConsumedInvite` row is stale, and the invite branch requires a
802
+ * same-transaction FRESH consumption. Re-admission normally takes a fresh
803
+ * manager action ({@link addMemberByManager} or a new invite).
804
+ *
805
+ * An UNSPENT invite the revoked party holds is killed EXPLICITLY, by the manager
806
+ * calling {@link cancelInvite} on it (enumerate the candidates with
807
+ * {@link listOutstandingInvites}); a cancelled invitation can never be consumed,
808
+ * and cancellation is permanent. This removal does NOT cascade into cancellation:
809
+ * an invitation names no invitee, so there is nothing to match the removed member
810
+ * against — the strand cannot tell which invitations were meant for it, or whether
811
+ * it holds any. Binding an invitation to its invitee is tracked as
812
+ * `feat-strand-invitee-bound-invites`.
813
+ *
814
+ * A manager must resign its `Manager` row before (or in the same transaction
815
+ * as) losing membership — `Member.NotAManager` rejects un-membering a key that
816
+ * still holds a Manager row. And the strand never drops to zero members
817
+ * (`Member.MinOneMember`, a local-count floor with the same cross-node caveat
818
+ * as `MinOneManager`).
819
+ *
820
+ * @param db - The closed strand's database.
821
+ * @param params - The revoking manager keypair and the target member key.
822
+ * @throws If `Member.Authorized` rejects (a non-manager or same-transaction
823
+ * signer), `Member.NotAManager` rejects (the target still holds a Manager
824
+ * row), or `Member.MinOneMember` rejects (the removal would empty the member
825
+ * set); the whole delete+tombstone transaction rolls back.
826
+ */
827
+ export async function revokeMember(db: Database, params: RevokeMemberParams): Promise<void> {
828
+ const { managerKeyPair, memberKey } = params;
829
+ const stampId = await memberStampId(db, memberKey);
830
+ if (stampId == null) {
831
+ log('Member %s already absent; skipping revoke', memberKey);
832
+ return;
833
+ }
834
+ const signature = signStrandApproval(['Strand.Member', 'remove', memberKey, stampId], managerKeyPair.privateKeyB64);
835
+ await inStrandTransaction(db, async () => {
836
+ await db.exec(
837
+ `delete from Strand.Member
838
+ with context ManagerKey = ?, ManagerSignature = ?, MemberSignature = null
839
+ where Key = ?`,
840
+ [managerKeyPair.publicKeyB64, signature, memberKey],
841
+ );
842
+ await insertRevocation(db, 'Member', stampId, managerKeyPair);
843
+ });
844
+ log('Revoked member %s by manager %s', memberKey, managerKeyPair.publicKeyB64);
845
+ }
846
+
847
+ /** Parameters for {@link leaveStrand}. */
848
+ export interface LeaveStrandParams {
849
+ /**
850
+ * The departing member's OWN strand keypair. Its `publicKeyB64` is the
851
+ * `Member.Key` row being deleted; it self-signs the leave-tagged digest —
852
+ * the self-departure branch verifies the signature against `old.Key` itself,
853
+ * so only the departing key's holder can produce it — and files the
854
+ * accompanying tombstone (it is still a committed member until this very
855
+ * transaction removes it, which is what `Revocation.Authorized` checks). No
856
+ * manager is involved.
857
+ */
858
+ memberKeyPair: Ed25519KeyPair;
859
+ }
860
+
861
+ /**
862
+ * A member leaves the strand by deleting its own `Member` row.
863
+ *
864
+ * The self-departure branch of `Member.Authorized` verifies
865
+ * `digest('Strand.Member', 'leave', old.Key, old.StampId)` against `old.Key`
866
+ * itself via `context.MemberSignature`. The `'leave'` tag (vs the manager
867
+ * branch's `'remove'`) is belt-and-braces only — the two branches verify against
868
+ * different keys; the anti-replay fix is the stamp binding. Like
869
+ * {@link revokeMember}, the live stamp is read first (absent row → quiet no-op)
870
+ * and the delete pairs with its `Strand.Revocation` tombstone in one transaction.
871
+ *
872
+ * The same floors as {@link revokeMember} apply: a manager must resign first
873
+ * (`NotAManager`) and the last member cannot leave (`MinOneMember`).
874
+ *
875
+ * @param db - The closed strand's database.
876
+ * @param params - The departing member's own keypair.
877
+ * @throws If `Member.Authorized`, `Member.NotAManager`, or `Member.MinOneMember`
878
+ * rejects; the whole delete+tombstone transaction rolls back.
879
+ */
880
+ export async function leaveStrand(db: Database, params: LeaveStrandParams): Promise<void> {
881
+ const { memberKeyPair } = params;
882
+ const memberKey = memberKeyPair.publicKeyB64;
883
+ const stampId = await memberStampId(db, memberKey);
884
+ if (stampId == null) {
885
+ log('Member %s already absent; skipping leave', memberKey);
886
+ return;
887
+ }
888
+ const signature = signStrandApproval(['Strand.Member', 'leave', memberKey, stampId], memberKeyPair.privateKeyB64);
889
+ await inStrandTransaction(db, async () => {
890
+ await db.exec(
891
+ `delete from Strand.Member
892
+ with context ManagerKey = null, ManagerSignature = null, MemberSignature = ?
893
+ where Key = ?`,
894
+ [signature, memberKey],
895
+ );
896
+ await insertRevocation(db, 'Member', stampId, memberKeyPair);
897
+ });
898
+ log('Member %s left the strand', memberKey);
899
+ }
900
+
901
+ // ── MemberPeer registration (a member binds its own network nodes) ─────────────
902
+
903
+ /** Parameters for {@link registerMemberPeer}. */
904
+ export interface RegisterMemberPeerParams {
905
+ /**
906
+ * The member's OWN strand keypair (`{ privateKeyB64, publicKeyB64 }`). Its
907
+ * `publicKeyB64` becomes `MemberPeer.MemberKey` and it self-signs the binding —
908
+ * `MemberPeer.Authorized` verifies the signature against `MemberKey` itself, so a
909
+ * peer can only be registered by the very member it belongs to (no manager
910
+ * involved). The founder passes its `strandMemberKeyPair`; an invited member
911
+ * passes its own keypair. Typed as {@link Ed25519KeyPair} only for the shared
912
+ * base64url keypair shape — no manager privilege is implied.
913
+ */
914
+ memberKeyPair: Ed25519KeyPair;
915
+ /** The peer/node id (libp2p peer id string) to associate with the member. */
916
+ peerId: string;
917
+ }
918
+
919
+ /**
920
+ * Register a network node (`PeerId`) as acting on behalf of a member.
921
+ *
922
+ * The member self-signs the add-tagged digest
923
+ * `digest('Strand.MemberPeer', 'add', new.MemberKey, new.PeerId, new.StampId)`
924
+ * with its OWN key; the schema's `MemberPeer.Authorized` verifies that signature
925
+ * against `new.MemberKey` — i.e. the member key itself — so only the member that
926
+ * owns the key can register peers for it. The stamp is minted fresh here and
927
+ * bound inside the digest, so a captured registration approval neither
928
+ * re-registers a cleared binding (its stamp is retired) nor authorizes a removal
929
+ * (wrong tag). A deferred `MemberExists` additionally requires the `Member` row
930
+ * to already exist, so a peer for a non-member is rejected at commit.
931
+ *
932
+ * Insert-if-absent: a re-register on restart (or a redundant call) is a no-op. The
933
+ * platform DOES reject a duplicate-PK insert, but a restart-safe re-register should
934
+ * succeed quietly rather than throw, so the writer guards on existence instead of
935
+ * catching. The guard ({@link memberPeerStampId}) scans the member's peers and compares
936
+ * both key columns in JavaScript rather than seeking the composite primary key — see
937
+ * {@link scanMemberPeers} for why a full-PK point lookup is not reliable on a networked
938
+ * strand. A member may register multiple DISTINCT `PeerId`s (multi-device); each is its
939
+ * own row (and its own stamp) under the same `MemberKey`.
940
+ *
941
+ * Peer DELETION is signature-checked too, not rejected outright: `Authorized` carries
942
+ * distinct delete branches (self + manager), each over its own action-tagged digest
943
+ * bound to the row's stamp. Both removal paths live in {@link removeMemberPeer}.
944
+ * UPDATE is refused outright by `NoUpdate`: a re-binding is a remove plus a fresh
945
+ * register (under a fresh stamp).
946
+ *
947
+ * @param db - The closed strand's database (the member already exists).
948
+ * @param params - The member's own keypair and the peer id to bind.
949
+ * @throws If `MemberPeer.Authorized`/`MemberExists` rejects (wrong signer, or no
950
+ * matching `Member` row); the insert rolls back, leaving no `MemberPeer` row.
951
+ */
952
+ export async function registerMemberPeer(db: Database, params: RegisterMemberPeerParams): Promise<void> {
953
+ const { memberKeyPair, peerId } = params;
954
+ const memberKey = memberKeyPair.publicKeyB64;
955
+
956
+ if (await memberPeerStampId(db, memberKey, peerId) != null) {
957
+ log('MemberPeer (%s, %s) already present; skipping', memberKey, peerId);
958
+ return;
959
+ }
960
+
961
+ const stampId = generateStrandStampId();
962
+ const signature = signStrandApproval(
963
+ ['Strand.MemberPeer', 'add', memberKey, peerId, stampId],
964
+ memberKeyPair.privateKeyB64,
965
+ );
966
+ await db.exec(
967
+ `insert into Strand.MemberPeer (MemberKey, PeerId, StampId)
968
+ with context Signature = ?, ManagerKey = null, ManagerSignature = null
969
+ values (?, ?, ?)`,
970
+ [signature, memberKey, peerId, stampId],
971
+ );
972
+ log('Registered MemberPeer (%s, %s)', memberKey, peerId);
973
+ }
974
+
975
+ /**
976
+ * Yield every `(PeerId, StampId)` bound to `memberKey`, re-comparing the member key
977
+ * in JavaScript.
978
+ *
979
+ * Deliberately does NOT filter on the full composite primary key. `MemberPeer`'s PK
980
+ * is `(MemberKey, PeerId)`, so a `where MemberKey = ? and PeerId = ?` predicate puts
981
+ * an equality on BOTH key columns — which the optimystic virtual-table module reports
982
+ * as fully handled and serves via a single-key point lookup (one `find` descent), with
983
+ * the SQL engine adding no filter of its own. On a networked strand that descent is not
984
+ * reliable: a miss returns zero rows for a row that provably exists.
985
+ *
986
+ * Filtering on only the LEADING key column is a partial PK match, which the same module
987
+ * explicitly declines to handle — it falls through to a table scan and the SQL engine
988
+ * applies `MemberKey = ?` itself. No seek is involved, so no seek can miss. The member key
989
+ * is then re-compared here in JavaScript, so correctness depends only on the scan returning
990
+ * a SUPERSET of the matching rows — the weakest possible assumption about the storage layer.
991
+ * The `where` clause only trims what crosses into JS — it is NOT pushed down (see the cost
992
+ * note below) — so it is not a correctness dependency: a dropped or mis-applied predicate
993
+ * cannot produce a row attributed to the wrong member.
994
+ */
995
+ async function* scanMemberPeers(db: Database, memberKey: string): AsyncGenerator<{ peerId: string; stampId: string }> {
996
+ // NOTE: because the predicate is not pushed down, the storage layer walks the WHOLE
997
+ // MemberPeer table (every member's rows) per call and the SQL engine filters. Fine at
998
+ // strand scale; if MemberPeer ever grows large, the fix is a reliable composite-key
999
+ // seek, not a bigger scan.
1000
+ // NOTE: if a secondary index on MemberPeer.MemberKey is ever added, this query stops
1001
+ // being a scan and becomes an index seek — re-introducing the seek dependency this
1002
+ // shape exists to remove.
1003
+ for await (const row of db.eval(
1004
+ 'select MemberKey, PeerId, StampId from Strand.MemberPeer where MemberKey = ?',
1005
+ [memberKey],
1006
+ )) {
1007
+ if (row.MemberKey === memberKey) {
1008
+ yield { peerId: row.PeerId as string, stampId: row.StampId as string };
1009
+ }
1010
+ }
1011
+ }
1012
+
1013
+ /**
1014
+ * Every `PeerId` currently bound to `memberKey`, in storage order.
1015
+ *
1016
+ * The enumeration side of {@link removeMemberPeer}: a manager cleaning up after a
1017
+ * revocation knows only the departed member's key, never which devices it registered, so
1018
+ * cleanup is `listMemberPeers` then one `removeMemberPeer` per id. Reads only — the rows
1019
+ * it returns may name a `MemberKey` with no `Member` row (see the `MemberPeer` table NOTE
1020
+ * in the schema), so this is NOT a membership test.
1021
+ *
1022
+ * @param db - The closed strand's database.
1023
+ * @param memberKey - The `MemberPeer.MemberKey` to enumerate.
1024
+ * @returns The bound peer ids, empty if the member has none.
1025
+ */
1026
+ export async function listMemberPeers(db: Database, memberKey: string): Promise<string[]> {
1027
+ const peerIds: string[] = [];
1028
+ for await (const peer of scanMemberPeers(db, memberKey)) {
1029
+ peerIds.push(peer.peerId);
1030
+ }
1031
+ return peerIds;
1032
+ }
1033
+
1034
+ /**
1035
+ * The live StampId of the `MemberPeer` row for this `(MemberKey, PeerId)`, or
1036
+ * `undefined` if no such row is visible — doubling as the existence probe.
1037
+ *
1038
+ * NOTE: check-then-write is not atomic. Two nodes registering the same
1039
+ * (MemberKey, PeerId) concurrently can both observe "absent"; the primary key is the
1040
+ * real backstop. The existence half of this guard is for the sequential restart /
1041
+ * re-register path.
1042
+ */
1043
+ async function memberPeerStampId(db: Database, memberKey: string, peerId: string): Promise<string | undefined> {
1044
+ for await (const peer of scanMemberPeers(db, memberKey)) {
1045
+ if (peer.peerId === peerId) {
1046
+ return peer.stampId;
1047
+ }
1048
+ }
1049
+ return undefined;
1050
+ }
1051
+
1052
+ /** Parameters for the SELF branch of {@link removeMemberPeer}. */
1053
+ export interface RemoveOwnPeerParams {
1054
+ /**
1055
+ * The member's OWN strand keypair. Its `publicKeyB64` is the `MemberPeer.MemberKey`
1056
+ * of the row being deleted, and it signs the remove-tagged digest
1057
+ * `digest('Strand.MemberPeer', 'remove', MemberKey, PeerId, StampId)` — the self
1058
+ * branch of `MemberPeer.Authorized` verifies against the row's own member key, so
1059
+ * no OTHER member's row is reachable this way, and the tag + stamp binding keep a
1060
+ * captured registration approval from doubling as a removal (and vice versa).
1061
+ */
1062
+ memberKeyPair: Ed25519KeyPair;
1063
+ /** The `PeerId` of the binding to delete. */
1064
+ peerId: string;
1065
+ }
1066
+
1067
+ /** Parameters for the MANAGER branch of {@link removeMemberPeer}. */
1068
+ export interface RemoveMemberPeerByManagerParams {
1069
+ /**
1070
+ * The clearing manager's strand keypair. Its `publicKeyB64` must be a PRE-EXISTING
1071
+ * `Strand.Manager` row (the manager branch reads `committed.Manager`, so a manager
1072
+ * seated in the same transaction cannot authorize); it signs the
1073
+ * manager-remove-tagged digest over the exact row and its live stamp, and files
1074
+ * the accompanying tombstone.
1075
+ */
1076
+ managerKeyPair: Ed25519KeyPair;
1077
+ /** The `MemberPeer.MemberKey` whose binding is being cleared. */
1078
+ memberKey: string;
1079
+ /** The `PeerId` of the binding to delete. */
1080
+ peerId: string;
1081
+ }
1082
+
1083
+ /**
1084
+ * Either shape accepted by {@link removeMemberPeer}. A discriminated union rather than
1085
+ * one opaque keypair: the two branches sign DIFFERENT action tags (`'remove'` self vs
1086
+ * `'manager-remove'`), so each case carries exactly the fields its payload needs.
1087
+ */
1088
+ export type RemoveMemberPeerParams = RemoveOwnPeerParams | RemoveMemberPeerByManagerParams;
1089
+
1090
+ /**
1091
+ * Delete a `MemberPeer` binding — either the member clearing its own, or a manager
1092
+ * clearing another member's.
1093
+ *
1094
+ * Reads the row's live StampId first (absent → quiet no-op, mirroring
1095
+ * {@link registerMemberPeer}'s insert-if-absent, so a repeated or restarted cleanup
1096
+ * is not a silent zero-row "success" the caller cannot distinguish from a real one),
1097
+ * then runs ONE transaction pairing the delete with its `Strand.Revocation`
1098
+ * tombstone — `MemberPeer.RevocationRecorded` requires it, and the retirement is
1099
+ * what keeps the captured registration approval from re-binding the cleared row.
1100
+ *
1101
+ * `MemberPeer` rows do NOT cascade when the member is revoked (`MemberExists` runs on
1102
+ * insert only, and nothing deletes them), so a removed member's peer bindings survive
1103
+ * as orphans — enumerate them with {@link listMemberPeers}, which is how a manager
1104
+ * discovers what to clear. Only that member can sign the self branch, and a member being
1105
+ * removed against its will has no reason to cooperate — hence the manager branch, which
1106
+ * is the cleanup path after a revocation.
1107
+ *
1108
+ * The manager branch is deliberately NOT gated on the member already being gone: a
1109
+ * manager may clear a still-present member's binding too, matching "any manager can
1110
+ * remove any member". It verifies the manager-remove-tagged
1111
+ * `digest('Strand.MemberPeer', 'manager-remove', old.MemberKey, old.PeerId, old.StampId)`
1112
+ * against a `committed.Manager` row; the self branch verifies the remove-tagged
1113
+ * sibling against the row's own member key.
1114
+ *
1115
+ * Cleanup is an explicit follow-up call by the revoking manager, never a cascade inside
1116
+ * {@link revokeMember}: a revocation that also had to clear an unbounded number of peer
1117
+ * rows in the same transaction would couple two concerns and make its failure modes
1118
+ * harder to reason about.
1119
+ *
1120
+ * @param db - The closed strand's database.
1121
+ * @param params - Either the owning member's keypair, or a manager's keypair plus the
1122
+ * target member key.
1123
+ * @throws If `MemberPeer.Authorized` rejects (neither branch satisfied), or if the row
1124
+ * is still present after the delete (see the point-lookup note below).
1125
+ */
1126
+ export async function removeMemberPeer(db: Database, params: RemoveMemberPeerParams): Promise<void> {
1127
+ const memberKey = 'memberKeyPair' in params ? params.memberKeyPair.publicKeyB64 : params.memberKey;
1128
+ const { peerId } = params;
1129
+
1130
+ const stampId = await memberPeerStampId(db, memberKey, peerId);
1131
+ if (stampId == null) {
1132
+ log('MemberPeer (%s, %s) already absent; skipping', memberKey, peerId);
1133
+ return;
1134
+ }
1135
+
1136
+ await inStrandTransaction(db, async () => {
1137
+ if ('memberKeyPair' in params) {
1138
+ await deleteOwnMemberPeer(db, params, stampId);
1139
+ } else {
1140
+ await deleteMemberPeerByManager(db, params, stampId);
1141
+ }
1142
+ });
1143
+
1144
+ // NOTE: the delete's `where` puts an equality on BOTH composite-PK columns, which the
1145
+ // optimystic vtab module serves via a single-key seek that can MISS on a networked
1146
+ // strand (see scanMemberPeers' doc). A missed seek deletes zero rows and still
1147
+ // reports success. `Revocation.RowIsGone` now catches that first — the tombstone filed
1148
+ // in the same transaction refuses to retire a stamp whose row is still visible, so the
1149
+ // commit above fails loudly and this re-check is belt-and-braces behind it. Tracked as
1150
+ // `debt-composite-pk-point-lookup-unreliable-untracked`; this is an availability
1151
+ // failure mode, never a security one (a miss removes nothing, it never over-removes).
1152
+ if (await memberPeerStampId(db, memberKey, peerId) != null) {
1153
+ throw new Error(`MemberPeer (${memberKey}, ${peerId}) still present after delete`);
1154
+ }
1155
+ log('Removed MemberPeer (%s, %s)', memberKey, peerId);
1156
+ }
1157
+
1158
+ /** The self branch: the owning member signs the remove-tagged digest + tombstone. */
1159
+ async function deleteOwnMemberPeer(db: Database, params: RemoveOwnPeerParams, stampId: string): Promise<void> {
1160
+ const { memberKeyPair, peerId } = params;
1161
+ const memberKey = memberKeyPair.publicKeyB64;
1162
+ const signature = signStrandApproval(
1163
+ ['Strand.MemberPeer', 'remove', memberKey, peerId, stampId],
1164
+ memberKeyPair.privateKeyB64,
1165
+ );
1166
+ await db.exec(
1167
+ `delete from Strand.MemberPeer
1168
+ with context Signature = ?, ManagerKey = null, ManagerSignature = null
1169
+ where MemberKey = ? and PeerId = ?`,
1170
+ [signature, memberKey, peerId],
1171
+ );
1172
+ await insertRevocation(db, 'MemberPeer', stampId, memberKeyPair);
1173
+ }
1174
+
1175
+ /** The manager branch: a manager signs the manager-remove-tagged digest + tombstone. */
1176
+ async function deleteMemberPeerByManager(
1177
+ db: Database,
1178
+ params: RemoveMemberPeerByManagerParams,
1179
+ stampId: string,
1180
+ ): Promise<void> {
1181
+ const { managerKeyPair, memberKey, peerId } = params;
1182
+ const signature = signStrandApproval(
1183
+ ['Strand.MemberPeer', 'manager-remove', memberKey, peerId, stampId],
1184
+ managerKeyPair.privateKeyB64,
1185
+ );
1186
+ await db.exec(
1187
+ `delete from Strand.MemberPeer
1188
+ with context Signature = null, ManagerKey = ?, ManagerSignature = ?
1189
+ where MemberKey = ? and PeerId = ?`,
1190
+ [managerKeyPair.publicKeyB64, signature, memberKey, peerId],
1191
+ );
1192
+ await insertRevocation(db, 'MemberPeer', stampId, managerKeyPair);
1193
+ }
1194
+
1195
+ // ── Manager rotation (add / remove RBAC admins) ───────────────────────────────
1196
+
1197
+ /**
1198
+ * The live `(Generation, StampId)` of the `Strand.Manager` row keyed by
1199
+ * `memberKey`, or `undefined` if no such row is visible.
1200
+ *
1201
+ * `Manager`'s primary key is the single `MemberKey` column, so any where-equality
1202
+ * on it is a full-PK point lookup — unreliable on a networked strand (see
1203
+ * {@link scanMemberPeers}). An unfiltered scan + JavaScript filter instead, same
1204
+ * as {@link memberStampId}. Serves both {@link addManager} (the authorizer's
1205
+ * generation) and {@link removeManager} (the target's stamp).
1206
+ */
1207
+ async function managerRow(db: Database, memberKey: string): Promise<{ generation: number; stampId: string } | undefined> {
1208
+ for await (const row of db.eval('select MemberKey, Generation, StampId from Strand.Manager')) {
1209
+ if (row.MemberKey === memberKey) {
1210
+ return { generation: Number(row.Generation), stampId: row.StampId as string };
1211
+ }
1212
+ }
1213
+ return undefined;
1214
+ }
1215
+
1216
+ /** Parameters for {@link addManager}. */
1217
+ export interface AddManagerParams {
1218
+ /**
1219
+ * An EXISTING manager's strand keypair. Its `publicKeyB64` must already be a
1220
+ * `Strand.Manager` row (the existing-manager branch of `Manager.Authorized`
1221
+ * rejects a non-manager once the founder manager exists); it signs the
1222
+ * add-tagged digest over the new manager key, generation, and fresh stamp,
1223
+ * and is bound as `context.ManagerKey`.
1224
+ */
1225
+ byManagerKeyPair: Ed25519KeyPair;
1226
+ /** The member key to promote — the new `Manager.MemberKey` row. */
1227
+ newManagerKey: string;
1228
+ }
1229
+
1230
+ /**
1231
+ * Promote a key that is ALREADY a `Strand.Member` to `Manager` on the signature of
1232
+ * an existing manager — use {@link admitManager} to admit and promote atomically.
1233
+ *
1234
+ * The promotion branch of `Manager.Authorized` requires the authorizer to be a
1235
+ * `Manager` row of STRICTLY SMALLER `Generation` than the new row, verifying
1236
+ * `digest('Strand.Manager', 'add', new.MemberKey, new.Generation, new.StampId)`
1237
+ * against `context.ManagerKey`. So this writer reads the authorizer's generation,
1238
+ * seats the new manager at that value + 1 (the natural successor; the schema
1239
+ * enforces only the strict ordering), mints a fresh stamp, and signs the
1240
+ * add-tagged digest over all three: the generation inside the signed digest keeps
1241
+ * a captured promotion from replaying at a different generation, and the stamp
1242
+ * keeps it from re-seating a second incarnation once this one is removed.
1243
+ * `new.Generation` is an SQL INTEGER digest arg — the digest framing is
1244
+ * type-tagged, so the TS side signs over the NUMBER itself
1245
+ * (see {@link signStrandApproval}).
1246
+ *
1247
+ * The strict ordering — not this writer — is what makes a same-transaction takeover
1248
+ * impossible; the `Manager.Generation` column comment in `schemas/strand.qsql` carries
1249
+ * that argument. All this writer owes it is a generation strictly above the
1250
+ * authorizer's, inside the signed payload.
1251
+ *
1252
+ * When the authorizer has NO `Manager` row (a non-manager signer, or an open
1253
+ * strand with no managers at all), the scan finds nothing and the writer falls
1254
+ * back to generation 1 and issues the insert anyway — deliberately letting the
1255
+ * SCHEMA be the rejector (`Manager.Authorized` / `OnlyClosed`), not a
1256
+ * writer-thrown error, so enforcement is pinned where it actually lives.
1257
+ *
1258
+ * @param db - The closed strand's database (founder manager already seated).
1259
+ * @param params - The authorizing manager's keypair and the new manager key.
1260
+ * @throws If `Manager.Authorized` rejects, or if `Manager.MemberExists` rejects because
1261
+ * `newManagerKey` holds no `Member` row (admit it first, or use
1262
+ * {@link admitManager}); the insert rolls back.
1263
+ */
1264
+ export async function addManager(db: Database, params: AddManagerParams): Promise<void> {
1265
+ const { byManagerKeyPair, newManagerKey } = params;
1266
+ const authorizer = await managerRow(db, byManagerKeyPair.publicKeyB64);
1267
+ // NOTE: +1 saturates at Number.MAX_SAFE_INTEGER, where the successor compares equal
1268
+ // to its authorizer and the schema rejects. Unreachable while generations only ever
1269
+ // grow by 1 from 0, but the schema enforces ordering, not adjacency, so a manager may
1270
+ // seat a successor at any larger value; if arbitrary generations ever become writable
1271
+ // from outside this function, clamp or reject here rather than emitting a dead row.
1272
+ const generation = authorizer == null ? 1 : authorizer.generation + 1;
1273
+ const stampId = generateStrandStampId();
1274
+ const signature = signStrandApproval(
1275
+ ['Strand.Manager', 'add', newManagerKey, generation, stampId],
1276
+ byManagerKeyPair.privateKeyB64,
1277
+ );
1278
+ await db.exec(
1279
+ `insert into Strand.Manager (MemberKey, Generation, StampId)
1280
+ with context ManagerKey = ?, Signature = ?
1281
+ values (?, ?, ?)`,
1282
+ [byManagerKeyPair.publicKeyB64, signature, newManagerKey, generation, stampId],
1283
+ );
1284
+ log('Added manager %s (generation %d) by %s', newManagerKey, generation, byManagerKeyPair.publicKeyB64);
1285
+ }
1286
+
1287
+ /** Parameters for {@link admitManager} — the same shape as {@link AddManagerParams}. */
1288
+ export type AdmitManagerParams = AddManagerParams;
1289
+
1290
+ /**
1291
+ * Admit a key as a `Member` AND promote it to `Manager`, atomically — the one-step
1292
+ * pair for a key that is not in the strand yet. {@link addManager} alone promotes a
1293
+ * key that is already a member.
1294
+ *
1295
+ * ONE transaction, because `Manager.MemberExists` is a deferred check reading the LIVE
1296
+ * `Member` table: the sibling `Member` insert satisfies it at the shared commit, and a
1297
+ * rejection of either half rolls BOTH rows back — never a `Member` row seated by a
1298
+ * failed promotion, nor a `Manager` row with no member behind it.
1299
+ *
1300
+ * NO new authority: both halves are signed by the SAME manager, over two distinct
1301
+ * action-tagged digests — `digest('Strand.Member', 'add', …)` for the admission and
1302
+ * `digest('Strand.Manager', 'add', …)` for the promotion — each bound to its own row's
1303
+ * fresh stamp. This composes exactly the two approvals that manager could already
1304
+ * issue separately.
1305
+ *
1306
+ * The promoting manager must be a PRE-transaction manager: the direct-admit branch of
1307
+ * `Member.Authorized` reads `committed.Manager`, so `admitManager` cannot be chained —
1308
+ * a manager seated by an `admitManager` earlier in the SAME transaction cannot admit
1309
+ * the next one. (A same-transaction promotion CHAIN rooted at a pre-existing manager
1310
+ * is fine; only the `Member` half needs the committed authorizer.)
1311
+ *
1312
+ * NOT insert-if-absent: a repeat call for a key that is already a member fails on the
1313
+ * `Member` primary key, matching {@link addMemberByManager}'s unguarded shape.
1314
+ *
1315
+ * @param db - The closed strand's database (founder manager already seated).
1316
+ * @param params - The authorizing manager's keypair and the key to admit + promote.
1317
+ * @throws If either half is rejected (`Member.Authorized`, `Manager.Authorized`, a
1318
+ * duplicate `Member` key, …); the whole transaction rolls back, leaving neither row.
1319
+ */
1320
+ export async function admitManager(db: Database, params: AdmitManagerParams): Promise<void> {
1321
+ const { byManagerKeyPair, newManagerKey } = params;
1322
+ await inStrandTransaction(db, async () => {
1323
+ await addMemberByManager(db, { managerKeyPair: byManagerKeyPair, memberKey: newManagerKey });
1324
+ await addManager(db, { byManagerKeyPair, newManagerKey });
1325
+ });
1326
+ log('Admitted + promoted manager %s by %s', newManagerKey, byManagerKeyPair.publicKeyB64);
1327
+ }
1328
+
1329
+ /** Parameters for {@link removeManager}. */
1330
+ export interface RemoveManagerParams {
1331
+ /**
1332
+ * The keypair authorizing the removal, bound as `context.ManagerKey`. For an
1333
+ * ADMIN removal this is a DIFFERENT existing manager, signing the
1334
+ * remove-tagged digest (satisfying the existing-manager branch); for a
1335
+ * SELF-resignation it is the target's OWN keypair (`publicKeyB64 ===
1336
+ * targetManagerKey`), signing the resign-tagged digest (satisfying the
1337
+ * former-manager self branch). The writer picks the tag by comparing the keys —
1338
+ * see {@link removeManager}. Either way this keypair also files the
1339
+ * accompanying tombstone, which requires it to be a PRE-transaction MEMBER
1340
+ * (`Revocation.Authorized` reads `committed.Member`) — true for every manager,
1341
+ * since managers are members.
1342
+ */
1343
+ byManagerKeyPair: Ed25519KeyPair;
1344
+ /** The `Manager.MemberKey` row to delete. */
1345
+ targetManagerKey: string;
1346
+ }
1347
+
1348
+ /**
1349
+ * Remove a `Manager` row — either an admin removing a different manager or a
1350
+ * manager resigning itself.
1351
+ *
1352
+ * Reads the target row's live `(Generation, StampId)` first (absent → quiet
1353
+ * no-op, same restart-safe shape as {@link revokeMember}), then runs ONE
1354
+ * transaction pairing the delete with its `Strand.Revocation` tombstone
1355
+ * (`Manager.RevocationRecorded`). The two delete-side branches of
1356
+ * `Manager.Authorized` verify DIFFERENT action-tagged digests, each bound to
1357
+ * `(old.MemberKey, old.StampId)`:
1358
+ * - **Admin removal** (`byManagerKeyPair` is a different existing manager): the
1359
+ * removal branch verifies `digest('Strand.Manager', 'remove', old.MemberKey,
1360
+ * old.StampId)` against `A.MemberKey = context.ManagerKey`. Deliberately NO
1361
+ * generation condition: a later-generation manager may remove an
1362
+ * earlier-generation one (generation is lineage, not privilege), and deletes
1363
+ * are safe once inserts are — every accepting branch requires a `Manager` row
1364
+ * in the post-image, and the promotion branch's generation ordering keeps
1365
+ * attacker rows out of it. The stamp binding is what makes a captured removal
1366
+ * single-use: a re-promoted manager carries a fresh stamp the old approval
1367
+ * does not match — closing the removal half of
1368
+ * `bug-strand-manager-authority-antireplay` (the insert half was already
1369
+ * closed by the generation-bearing promotion payload).
1370
+ * - **Self-resignation** (`byManagerKeyPair` IS the target): the former-manager
1371
+ * self branch verifies `digest('Strand.Manager', 'resign', old.MemberKey,
1372
+ * old.StampId)` against `old.MemberKey` itself. The distinct `'resign'` tag is
1373
+ * belt-and-braces (different verifying keys); the anti-replay fix is the stamp.
1374
+ *
1375
+ * The caller selects the case purely by which keypair it passes; the only
1376
+ * branching here is the action tag, chosen by comparing the signer to the target.
1377
+ *
1378
+ * Deferred (subquery-bearing) CHECK constraints are evaluated on DELETE as well
1379
+ * as INSERT by Quereus plus the Optimystic vtab session — enforcement lives above
1380
+ * the transactor (proven on the network transactor by
1381
+ * `strand-membership-network-transactor-parity.spec.ts`), so `Manager.Authorized`
1382
+ * — deferred — IS enforced here: a signer that is neither an existing manager nor
1383
+ * the target itself is rejected at commit.
1384
+ *
1385
+ * THE LAST MANAGER CANNOT BE REMOVED. `Manager.MinOneManager` (`check on delete`,
1386
+ * deferred, so it sees the POST-delete count) rejects any delete that would leave the
1387
+ * strand with zero managers — an admin-less closed strand could never admit anyone
1388
+ * again, since `Invite`, `addMemberByManager`, and `addManager` all require a
1389
+ * `Manager` row. The bootstrap branch of `Manager.Authorized` is gated to INSERTs
1390
+ * (`old.MemberKey is null`), so it does not waive the signature check on a delete
1391
+ * that drops the count toward the floor: a second-to-last removal is authorized
1392
+ * exactly like any other.
1393
+ *
1394
+ * HAND-OFF ORDER: a sole manager transferring control must ADD the successor FIRST
1395
+ * and resign SECOND. A same-transaction delete-then-insert swap is rejected — the
1396
+ * bootstrap branch is gated to the founding state (at most one `Member`), and the
1397
+ * successor's insert has no other manager to authorize it once the sole manager's
1398
+ * row is gone.
1399
+ *
1400
+ * Cross-node caveat: `MinOneManager` counts rows visible to THIS transaction, so two
1401
+ * nodes concurrently removing different managers can each see a survivor and still
1402
+ * converge to zero. Noted in the schema; a cross-node floor is not attempted here.
1403
+ *
1404
+ * @param db - The closed strand's database.
1405
+ * @param params - The authorizing keypair and the target manager key.
1406
+ * @throws If `Manager.Authorized` rejects (a signer that is neither another existing
1407
+ * manager nor the target itself) or `Manager.MinOneManager` rejects (the removal
1408
+ * would leave no managers); the whole delete+tombstone transaction rolls back.
1409
+ */
1410
+ export async function removeManager(db: Database, params: RemoveManagerParams): Promise<void> {
1411
+ const { byManagerKeyPair, targetManagerKey } = params;
1412
+ const target = await managerRow(db, targetManagerKey);
1413
+ if (target == null) {
1414
+ log('Manager %s already absent; skipping removal', targetManagerKey);
1415
+ return;
1416
+ }
1417
+ const tag = byManagerKeyPair.publicKeyB64 === targetManagerKey ? 'resign' : 'remove';
1418
+ const signature = signStrandApproval(
1419
+ ['Strand.Manager', tag, targetManagerKey, target.stampId],
1420
+ byManagerKeyPair.privateKeyB64,
1421
+ );
1422
+ await inStrandTransaction(db, async () => {
1423
+ await db.exec(
1424
+ `delete from Strand.Manager
1425
+ with context ManagerKey = ?, Signature = ?
1426
+ where MemberKey = ?`,
1427
+ [byManagerKeyPair.publicKeyB64, signature, targetManagerKey],
1428
+ );
1429
+ await insertRevocation(db, 'Manager', target.stampId, byManagerKeyPair);
1430
+ });
1431
+ log('Removed manager %s by %s', targetManagerKey, byManagerKeyPair.publicKeyB64);
1432
+ }