@serfab/cadre-core 0.9.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 (193) hide show
  1. package/README.md +255 -253
  2. package/dist/bootstrap-peer-store-file.d.ts +13 -0
  3. package/dist/bootstrap-peer-store-file.js +42 -0
  4. package/dist/bootstrap-peer-store-file.js.map +1 -0
  5. package/dist/bootstrap-peer-store.d.ts +73 -0
  6. package/dist/bootstrap-peer-store.js +128 -0
  7. package/dist/bootstrap-peer-store.js.map +1 -0
  8. package/dist/cadre-node.d.ts +1121 -81
  9. package/dist/cadre-node.js +2276 -262
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/control-authorization.d.ts +93 -0
  12. package/dist/control-authorization.js +57 -0
  13. package/dist/control-authorization.js.map +1 -0
  14. package/dist/control-cohort.d.ts +26 -0
  15. package/dist/control-cohort.js +26 -0
  16. package/dist/control-cohort.js.map +1 -1
  17. package/dist/control-database.d.ts +959 -54
  18. package/dist/control-database.js +1421 -148
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +90 -10
  21. package/dist/control-formation-recorder.js +130 -14
  22. package/dist/control-formation-recorder.js.map +1 -1
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +651 -72
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-stream.d.ts +38 -4
  27. package/dist/control-stream.js +70 -4
  28. package/dist/control-stream.js.map +1 -1
  29. package/dist/control-write-retry.d.ts +161 -0
  30. package/dist/control-write-retry.js +412 -0
  31. package/dist/control-write-retry.js.map +1 -0
  32. package/dist/delegate-admission.d.ts +134 -0
  33. package/dist/delegate-admission.js +244 -0
  34. package/dist/delegate-admission.js.map +1 -0
  35. package/dist/device-token.d.ts +11 -11
  36. package/dist/device-token.js +14 -13
  37. package/dist/device-token.js.map +1 -1
  38. package/dist/ed25519-key.d.ts +26 -0
  39. package/dist/ed25519-key.js +56 -1
  40. package/dist/ed25519-key.js.map +1 -1
  41. package/dist/file-durable-slot.d.ts +20 -0
  42. package/dist/file-durable-slot.js +53 -0
  43. package/dist/file-durable-slot.js.map +1 -0
  44. package/dist/formation-approval.d.ts +157 -0
  45. package/dist/formation-approval.js +375 -0
  46. package/dist/formation-approval.js.map +1 -0
  47. package/dist/fs-atomic.d.ts +38 -0
  48. package/dist/fs-atomic.js +97 -0
  49. package/dist/fs-atomic.js.map +1 -0
  50. package/dist/identity-key.d.ts +49 -0
  51. package/dist/identity-key.js +81 -0
  52. package/dist/identity-key.js.map +1 -0
  53. package/dist/index.d.ts +17 -7
  54. package/dist/index.js +40 -6
  55. package/dist/index.js.map +1 -1
  56. package/dist/key-store-file.d.ts +2 -24
  57. package/dist/key-store-file.js +10 -77
  58. package/dist/key-store-file.js.map +1 -1
  59. package/dist/membership-connection-gater.d.ts +146 -0
  60. package/dist/membership-connection-gater.js +180 -0
  61. package/dist/membership-connection-gater.js.map +1 -0
  62. package/dist/node-local-snapshot.d.ts +109 -0
  63. package/dist/node-local-snapshot.js +182 -0
  64. package/dist/node-local-snapshot.js.map +1 -0
  65. package/dist/peer-addr-book.d.ts +92 -0
  66. package/dist/peer-addr-book.js +220 -0
  67. package/dist/peer-addr-book.js.map +1 -0
  68. package/dist/peer-authorization.d.ts +135 -18
  69. package/dist/peer-authorization.js +152 -21
  70. package/dist/peer-authorization.js.map +1 -1
  71. package/dist/peer-record.d.ts +21 -8
  72. package/dist/peer-record.js +26 -10
  73. package/dist/peer-record.js.map +1 -1
  74. package/dist/relay-addrs.d.ts +45 -0
  75. package/dist/relay-addrs.js +103 -0
  76. package/dist/relay-addrs.js.map +1 -0
  77. package/dist/relay-reservation.d.ts +266 -0
  78. package/dist/relay-reservation.js +613 -0
  79. package/dist/relay-reservation.js.map +1 -0
  80. package/dist/seed-bootstrap.d.ts +228 -56
  81. package/dist/seed-bootstrap.js +340 -198
  82. package/dist/seed-bootstrap.js.map +1 -1
  83. package/dist/seed-trust-policy.d.ts +47 -21
  84. package/dist/seed-trust-policy.js +24 -15
  85. package/dist/seed-trust-policy.js.map +1 -1
  86. package/dist/strand-addr-protocol.d.ts +42 -13
  87. package/dist/strand-addr-protocol.js +58 -52
  88. package/dist/strand-addr-protocol.js.map +1 -1
  89. package/dist/strand-backfill.d.ts +109 -0
  90. package/dist/strand-backfill.js +279 -0
  91. package/dist/strand-backfill.js.map +1 -0
  92. package/dist/strand-cohort.d.ts +4 -37
  93. package/dist/strand-cohort.js +4 -15
  94. package/dist/strand-cohort.js.map +1 -1
  95. package/dist/strand-database.d.ts +11 -16
  96. package/dist/strand-database.js +19 -7
  97. package/dist/strand-database.js.map +1 -1
  98. package/dist/strand-formation-manager.d.ts +36 -7
  99. package/dist/strand-formation-manager.js +115 -15
  100. package/dist/strand-formation-manager.js.map +1 -1
  101. package/dist/strand-formation-protocol.d.ts +103 -4
  102. package/dist/strand-formation-protocol.js +232 -4
  103. package/dist/strand-formation-protocol.js.map +1 -1
  104. package/dist/strand-instance-manager.d.ts +88 -19
  105. package/dist/strand-instance-manager.js +178 -34
  106. package/dist/strand-instance-manager.js.map +1 -1
  107. package/dist/strand-member-registry.d.ts +5 -5
  108. package/dist/strand-member-registry.js +18 -10
  109. package/dist/strand-member-registry.js.map +1 -1
  110. package/dist/strand-membership-writer.d.ts +484 -88
  111. package/dist/strand-membership-writer.js +751 -128
  112. package/dist/strand-membership-writer.js.map +1 -1
  113. package/dist/strand-solicitation.d.ts +99 -33
  114. package/dist/strand-solicitation.js +100 -52
  115. package/dist/strand-solicitation.js.map +1 -1
  116. package/dist/strand-transport-key.d.ts +40 -0
  117. package/dist/strand-transport-key.js +56 -0
  118. package/dist/strand-transport-key.js.map +1 -0
  119. package/dist/strand-wake-protocol.d.ts +9 -7
  120. package/dist/strand-wake-protocol.js +22 -46
  121. package/dist/strand-wake-protocol.js.map +1 -1
  122. package/dist/strand-watcher.d.ts +17 -2
  123. package/dist/strand-watcher.js +47 -3
  124. package/dist/strand-watcher.js.map +1 -1
  125. package/dist/trusted-owner-store-file.d.ts +12 -0
  126. package/dist/trusted-owner-store-file.js +39 -0
  127. package/dist/trusted-owner-store-file.js.map +1 -0
  128. package/dist/trusted-owner-store.d.ts +64 -0
  129. package/dist/trusted-owner-store.js +126 -0
  130. package/dist/trusted-owner-store.js.map +1 -0
  131. package/dist/types.d.ts +307 -44
  132. package/dist/types.js +13 -0
  133. package/dist/types.js.map +1 -1
  134. package/package.json +20 -8
  135. package/src/arachnode-stub.ts +159 -159
  136. package/src/bootstrap-peer-store-file.ts +44 -0
  137. package/src/bootstrap-peer-store.ts +172 -0
  138. package/src/cadre-node.ts +5158 -2981
  139. package/src/canonical-json.ts +30 -30
  140. package/src/control-authorization.ts +114 -0
  141. package/src/control-cohort.ts +130 -103
  142. package/src/control-database.ts +2406 -948
  143. package/src/control-formation-recorder.ts +305 -151
  144. package/src/control-schema.ts +651 -72
  145. package/src/control-stream.ts +205 -128
  146. package/src/control-write-retry.ts +483 -0
  147. package/src/delegate-admission.ts +302 -0
  148. package/src/device-token.ts +94 -89
  149. package/src/diagnostics/connection-path.ts +277 -277
  150. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  151. package/src/ed25519-key.ts +66 -1
  152. package/src/enrollment.ts +199 -199
  153. package/src/file-durable-slot.ts +61 -0
  154. package/src/formation-approval.ts +604 -0
  155. package/src/fs-atomic.ts +107 -0
  156. package/src/hibernation-manager.ts +437 -437
  157. package/src/identity-key.ts +109 -0
  158. package/src/index.ts +137 -5
  159. package/src/key-store-file.ts +132 -203
  160. package/src/key-store.ts +99 -99
  161. package/src/membership-connection-gater.ts +204 -0
  162. package/src/node-local-snapshot.ts +260 -0
  163. package/src/peer-addr-book.ts +250 -0
  164. package/src/peer-authorization.ts +259 -81
  165. package/src/peer-record.ts +164 -146
  166. package/src/push-credentials.ts +84 -84
  167. package/src/push-node.ts +64 -64
  168. package/src/push-notifier-apns.ts +247 -247
  169. package/src/push-notifier-fcm.ts +220 -220
  170. package/src/push-notifier-shared.ts +28 -28
  171. package/src/push-notifier.ts +52 -52
  172. package/src/relay-addrs.ts +111 -0
  173. package/src/relay-reservation.ts +823 -0
  174. package/src/seed-bootstrap.ts +409 -209
  175. package/src/seed-trust-policy.ts +140 -107
  176. package/src/strand-addr-protocol.ts +441 -410
  177. package/src/strand-backfill.ts +366 -0
  178. package/src/strand-cohort.ts +38 -77
  179. package/src/strand-database.ts +202 -204
  180. package/src/strand-formation-manager.ts +491 -368
  181. package/src/strand-formation-protocol.ts +692 -391
  182. package/src/strand-instance-manager.ts +201 -46
  183. package/src/strand-member-key.ts +39 -39
  184. package/src/strand-member-registry.ts +182 -177
  185. package/src/strand-membership-writer.ts +938 -146
  186. package/src/strand-solicitation.ts +472 -407
  187. package/src/strand-transport-key.ts +58 -0
  188. package/src/strand-wake-payload.ts +32 -32
  189. package/src/strand-wake-protocol.ts +314 -331
  190. package/src/strand-watcher.ts +314 -251
  191. package/src/trusted-owner-store-file.ts +41 -0
  192. package/src/trusted-owner-store.ts +171 -0
  193. package/src/types.ts +1309 -1032
@@ -1,6 +1,7 @@
1
1
  import debug from 'debug';
2
+ import { toString as uint8ArrayToString } from 'uint8arrays';
2
3
  import type { Database } from '@quereus/quereus';
3
- import { digest, sign, verify, generatePrivateKey, getPublicKey } from '@optimystic/quereus-plugin-crypto';
4
+ import { digest, sign, verify, generatePrivateKey, getPublicKey, randomBytes } from '@optimystic/quereus-plugin-crypto';
4
5
  import type { SAppConfig } from './types.js';
5
6
  import type { Ed25519KeyPair } from './ed25519-key.js';
6
7
  import { canonicalDatetime } from './canonical-datetime.js';
@@ -26,18 +27,17 @@ export const STRAND_ENGINE = 'quereus';
26
27
  export const STRAND_ENGINE_VERSION = '0.1.0';
27
28
 
28
29
  /**
29
- * The single-digest ed25519 signer the `Strand.*` membership/RBAC constraints
30
- * verify against.
30
+ * The single-payload ed25519 signer the `Strand.Invite`/`Strand.ConsumedInvite`
31
+ * handshake constraints verify against.
31
32
  *
32
- * `schemas/strand.qsql` signs a single SHA-256 digest over a `'|'`-joined payload
33
- * (e.g. `Member.Authorized` verifies
34
- * `verify(digest(new.Key), context.ManagerSignature, A.MemberKey, 'ed25519')`).
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, '')), ...)`).
35
36
  * So the signer hashes the payload to raw bytes and ed25519-signs *those bytes*:
36
37
  * SQL `digest(...)`'s default output is base64url and `verify(...)`'s default
37
38
  * `inputEncoding` is base64url, so signer and verifier operate on identical bytes.
38
- * This differs from the control-layer's multi-field `buildAuthorizationMessage`
39
- * (a single digest over MANY fields) — the strand layer is a single digest over ONE
40
- * joined payload field.
39
+ * The membership/RBAC tables (Member/Manager/MemberPeer/Revocation) instead use
40
+ * domain/action-tagged VARIADIC digests — see {@link signStrandApproval}.
41
41
  *
42
42
  * All strand keys are ed25519, so the explicit `'ed25519'` curve arg is mandatory
43
43
  * (the crypto plugin otherwise defaults to secp256k1). Mirrors the proven
@@ -55,7 +55,7 @@ export function signStrandPayload(payload: string, privateKeyB64: string): strin
55
55
  /**
56
56
  * The verifier counterpart to {@link signStrandPayload}.
57
57
  *
58
- * Mirrors what every `Strand.*` constraint computes:
58
+ * Mirrors what the single-payload `Strand.*` constraints compute:
59
59
  * `verify(digest(payload), signature, publicKey, 'ed25519')`.
60
60
  * SQL `digest`'s default output and `verify`'s default `inputEncoding`/`sigEncoding`/
61
61
  * `keyEncoding` are all base64url, so the off-engine check operates on the exact
@@ -73,6 +73,131 @@ export function verifyStrandPayload(payload: string, signatureB64: string, publi
73
73
  return verify(payloadDigest, signatureB64, publicKeyB64, 'ed25519', 'base64url', 'base64url', 'base64url');
74
74
  }
75
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
+
76
201
  /** Parameters for {@link bootstrapFounderMembership}. */
77
202
  export interface FounderBootstrapParams {
78
203
  /** The strand id — written to `Header.Id`. */
@@ -138,10 +263,14 @@ async function insertHeaderIfAbsent(db: Database, params: FounderBootstrapParams
138
263
  /**
139
264
  * Insert the founding `Strand.Member` if no member exists yet.
140
265
  *
141
- * The empty-table state satisfies the `count(1) from Member <= 1` bootstrap branch
142
- * of `Member.Authorized`, so no manager signature is needed — the context fields
143
- * are explicit nulls. Guarding on the count makes this idempotent: a re-run (the
144
- * founder re-`addStrand`/`resumeStrand`) finds the member present and skips.
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.
145
274
  */
146
275
  async function insertFounderMemberIfAbsent(db: Database, memberKey: string, strandId: string): Promise<void> {
147
276
  if (await strandTableCount(db, 'Member') > 0) {
@@ -149,10 +278,10 @@ async function insertFounderMemberIfAbsent(db: Database, memberKey: string, stra
149
278
  return;
150
279
  }
151
280
  await db.exec(
152
- `insert into Strand.Member (Key)
153
- with context ManagerKey = null, ManagerSignature = null
154
- values (?)`,
155
- [memberKey],
281
+ `insert into Strand.Member (Key, StampId)
282
+ with context ManagerKey = null, ManagerSignature = null, MemberSignature = null
283
+ values (?, ?)`,
284
+ [memberKey, generateStrandStampId()],
156
285
  );
157
286
  log('Inserted founding Member for strand %s', strandId);
158
287
  }
@@ -160,11 +289,21 @@ async function insertFounderMemberIfAbsent(db: Database, memberKey: string, stra
160
289
  /**
161
290
  * Insert the founding `Strand.Manager` if no manager exists yet.
162
291
  *
163
- * The empty-table state satisfies the `count(1) from Manager <= 1` bootstrap
164
- * branch of `Manager.Authorized`, so no signature is needed. Idempotent via the
165
- * same count guard. Must run AFTER the Header insert: `Manager.OnlyClosed` is a
166
- * deferred (subquery) check evaluated at commit, and the sequential auto-commit
167
- * Header→Member→Manager order ensures the closed `Header` is committed first.
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.
168
307
  */
169
308
  async function insertFounderManagerIfAbsent(db: Database, memberKey: string, strandId: string): Promise<void> {
170
309
  if (await strandTableCount(db, 'Manager') > 0) {
@@ -172,10 +311,10 @@ async function insertFounderManagerIfAbsent(db: Database, memberKey: string, str
172
311
  return;
173
312
  }
174
313
  await db.exec(
175
- `insert into Strand.Manager (MemberKey)
314
+ `insert into Strand.Manager (MemberKey, Generation, StampId)
176
315
  with context ManagerKey = null, Signature = null
177
- values (?)`,
178
- [memberKey],
316
+ values (?, 0, ?)`,
317
+ [memberKey, generateStrandStampId()],
179
318
  );
180
319
  log('Inserted founding Manager for strand %s', strandId);
181
320
  }
@@ -330,8 +469,8 @@ export interface ConsumeInviteParams {
330
469
  * Redeem an invite to admit a new `Member`, atomically.
331
470
  *
332
471
  * `Member.Authorized`'s invite branch needs a `ConsumedInvite` row, while
333
- * `ConsumedInvite`'s `MemberExists`/`MemberValid` need the `Member` row — a
334
- * circular dependency. Both are deferred (subquery-bearing) checks that evaluate
472
+ * `ConsumedInvite`'s `MemberExists` needs the `Member` row — a circular
473
+ * dependency. Both are deferred (subquery-bearing) checks that evaluate
335
474
  * at COMMIT, so inserting `Member` then `ConsumedInvite` inside one explicit
336
475
  * transaction lets both rows exist when the deferred checks fire. This mirrors
337
476
  * `ControlDatabase.redeemInvitation` (Strand + FormationUsage in one txn).
@@ -339,7 +478,9 @@ export interface ConsumeInviteParams {
339
478
  * The `ConsumedInvite` insert carries an `InviteSignature` over
340
479
  * `InviteKey || '|' || MemberKey`, proving the consumer holds the invite private
341
480
  * key (the on-engine `ValidUsage` gate). The `Member` insert needs no member
342
- * signature — its admission is the existence of the matching `ConsumedInvite`.
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).
343
484
  *
344
485
  * Single-use: `ConsumedInvite`'s primary key is `InviteKey`, so a second consume
345
486
  * of the same invite is rejected by the PK (a distinct layer from the control
@@ -379,15 +520,14 @@ export async function consumeInvite(db: Database, params: ConsumeInviteParams):
379
520
  // Plain runtime Date.now() — the tess Workflow restriction is on scripts, not libs.
380
521
  const nowCanonical = await canonicalDatetime(db, nowMs ?? Date.now());
381
522
 
382
- await db.beginTransaction();
383
- try {
523
+ await inStrandTransaction(db, async () => {
384
524
  // 1. Member — admitted by the deferred invite branch (the matching
385
525
  // ConsumedInvite below), so no manager signature is supplied.
386
526
  await db.exec(
387
- `insert into Strand.Member (Key)
388
- with context ManagerKey = null, ManagerSignature = null
389
- values (?)`,
390
- [memberKey],
527
+ `insert into Strand.Member (Key, StampId)
528
+ with context ManagerKey = null, ManagerSignature = null, MemberSignature = null
529
+ values (?, ?)`,
530
+ [memberKey, generateStrandStampId()],
391
531
  );
392
532
 
393
533
  // 2. ConsumedInvite — proves possession of the invite private key and that the
@@ -398,26 +538,198 @@ export async function consumeInvite(db: Database, params: ConsumeInviteParams):
398
538
  values (?, ?)`,
399
539
  [inviteSignature, nowCanonical, inviteKey, memberKey],
400
540
  );
541
+ });
542
+ log('Consumed invite %s -> member %s', inviteKey, memberKey);
543
+ }
401
544
 
402
- await db.commit();
403
- log('Consumed invite %s -> member %s', inviteKey, memberKey);
404
- } catch (error) {
405
- // A failed commit() already tears down the transaction, so rollback() would
406
- // throw "No transaction active" and mask the real cause — swallow only that.
407
- try {
408
- await db.rollback();
409
- } catch (rollbackError) {
410
- log('Rollback after consumeInvite failure was a no-op: %s', rollbackError);
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;
411
695
  }
412
- throw error;
696
+ if (expiration != null && expiration <= nowCanonical) {
697
+ continue;
698
+ }
699
+ outstanding.push({ inviteKey, expiration });
413
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;
414
725
  }
415
726
 
416
727
  /** Parameters for {@link addMemberByManager}. */
417
728
  export interface AddMemberByManagerParams {
418
729
  /**
419
730
  * The admitting manager's strand keypair. Its `publicKeyB64` must be a
420
- * `Strand.Manager` row; it signs the new member key directly.
731
+ * `Strand.Manager` row; it signs the add-tagged digest over the new member key
732
+ * and its fresh stamp.
421
733
  */
422
734
  managerKeyPair: Ed25519KeyPair;
423
735
  /** The joining member's ed25519 PUBLIC key (base64url) — the new `Member.Key`. */
@@ -428,11 +740,14 @@ export interface AddMemberByManagerParams {
428
740
  * Admit a `Member` directly by manager signature — the sibling of the invite
429
741
  * path on `Member.Authorized`'s direct-manager branch.
430
742
  *
431
- * The constraint verifies `digest(new.Key)` against a `Manager` row matching
432
- * `context.ManagerKey`, so the payload is just the member key (no `'|'` join).
433
- * No `ConsumedInvite` is involved: this is the path a manager uses to seat a
434
- * member it already trusts (e.g. a manager-side enrollment that admits a
435
- * party already authorised out-of-band).
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).
436
751
  *
437
752
  * @param db - The closed strand's database.
438
753
  * @param params - The admitting manager keypair and the new member key.
@@ -441,16 +756,148 @@ export interface AddMemberByManagerParams {
441
756
  */
442
757
  export async function addMemberByManager(db: Database, params: AddMemberByManagerParams): Promise<void> {
443
758
  const { managerKeyPair, memberKey } = params;
444
- const signature = signStrandPayload(memberKey, managerKeyPair.privateKeyB64);
759
+ const stampId = generateStrandStampId();
760
+ const signature = signStrandApproval(['Strand.Member', 'add', memberKey, stampId], managerKeyPair.privateKeyB64);
445
761
  await db.exec(
446
- `insert into Strand.Member (Key)
447
- with context ManagerKey = ?, ManagerSignature = ?
448
- values (?)`,
449
- [managerKeyPair.publicKeyB64, signature, memberKey],
762
+ `insert into Strand.Member (Key, StampId)
763
+ with context ManagerKey = ?, ManagerSignature = ?, MemberSignature = null
764
+ values (?, ?)`,
765
+ [managerKeyPair.publicKeyB64, signature, memberKey, stampId],
450
766
  );
451
767
  log('Admitted member %s by manager %s', memberKey, managerKeyPair.publicKeyB64);
452
768
  }
453
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
+
454
901
  // ── MemberPeer registration (a member binds its own network nodes) ─────────────
455
902
 
456
903
  /** Parameters for {@link registerMemberPeer}. */
@@ -472,23 +919,30 @@ export interface RegisterMemberPeerParams {
472
919
  /**
473
920
  * Register a network node (`PeerId`) as acting on behalf of a member.
474
921
  *
475
- * The member self-signs `MemberKey || '|' || PeerId` with its OWN key; the schema's
476
- * `MemberPeer.Authorized` verifies that signature against `coalesce(new.MemberKey,
477
- * old.MemberKey)` — i.e. the member key itself — so only the member that owns the
478
- * key can register peers for it. A deferred `MemberExists` additionally requires the
479
- * `Member` row to already exist, so a peer for a non-member is rejected at commit.
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.
480
931
  *
481
- * Insert-if-absent on the composite PK `(MemberKey, PeerId)`: a re-register on
482
- * restart (or a redundant call) is a no-op rather than relying on the platform's
483
- * PK-uniqueness rejection (not enforced in bootstrap mode — see
484
- * `optimystic-insert-pk-uniqueness-not-enforced`). A member may register multiple
485
- * DISTINCT `PeerId`s (multi-device); each is its own row under the same `MemberKey`.
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`.
486
940
  *
487
- * Out of scope: peer DELETION. The schema's `MemberExists` reads `new.MemberKey`,
488
- * which is null on delete, so a `MemberPeer` delete is currently rejected by the
489
- * schema (noted in the `apply-strand-membership-schema` review). Removing a peer
490
- * would need a schema tweak (e.g. `coalesce(new.MemberKey, old.MemberKey)` in
491
- * `MemberExists`), so no `removeMemberPeer` is provided here.
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).
492
946
  *
493
947
  * @param db - The closed strand's database (the member already exists).
494
948
  * @param params - The member's own keypair and the peer id to bind.
@@ -499,42 +953,274 @@ export async function registerMemberPeer(db: Database, params: RegisterMemberPee
499
953
  const { memberKeyPair, peerId } = params;
500
954
  const memberKey = memberKeyPair.publicKeyB64;
501
955
 
502
- if (await memberPeerExists(db, memberKey, peerId)) {
956
+ if (await memberPeerStampId(db, memberKey, peerId) != null) {
503
957
  log('MemberPeer (%s, %s) already present; skipping', memberKey, peerId);
504
958
  return;
505
959
  }
506
960
 
507
- const payload = `${memberKey}|${peerId}`;
508
- const signature = signStrandPayload(payload, memberKeyPair.privateKeyB64);
961
+ const stampId = generateStrandStampId();
962
+ const signature = signStrandApproval(
963
+ ['Strand.MemberPeer', 'add', memberKey, peerId, stampId],
964
+ memberKeyPair.privateKeyB64,
965
+ );
509
966
  await db.exec(
510
- `insert into Strand.MemberPeer (MemberKey, PeerId)
511
- with context Signature = ?
512
- values (?, ?)`,
513
- [signature, memberKey, peerId],
967
+ `insert into Strand.MemberPeer (MemberKey, PeerId, StampId)
968
+ with context Signature = ?, ManagerKey = null, ManagerSignature = null
969
+ values (?, ?, ?)`,
970
+ [signature, memberKey, peerId, stampId],
514
971
  );
515
972
  log('Registered MemberPeer (%s, %s)', memberKey, peerId);
516
973
  }
517
974
 
518
- /** True iff a `MemberPeer` row already exists for this `(MemberKey, PeerId)`. */
519
- async function memberPeerExists(db: Database, memberKey: string, peerId: string): Promise<boolean> {
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.
520
1003
  for await (const row of db.eval(
521
- 'select count(1) as Count from Strand.MemberPeer where MemberKey = ? and PeerId = ?',
522
- [memberKey, peerId],
1004
+ 'select MemberKey, PeerId, StampId from Strand.MemberPeer where MemberKey = ?',
1005
+ [memberKey],
523
1006
  )) {
524
- return ((row.Count as number) ?? 0) > 0;
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;
525
1134
  }
526
- return false;
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);
527
1193
  }
528
1194
 
529
1195
  // ── Manager rotation (add / remove RBAC admins) ───────────────────────────────
530
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
+
531
1216
  /** Parameters for {@link addManager}. */
532
1217
  export interface AddManagerParams {
533
1218
  /**
534
1219
  * An EXISTING manager's strand keypair. Its `publicKeyB64` must already be a
535
1220
  * `Strand.Manager` row (the existing-manager branch of `Manager.Authorized`
536
- * rejects a non-manager once the founder manager exists); it signs the new
537
- * manager key and is bound as `context.ManagerKey`.
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`.
538
1224
  */
539
1225
  byManagerKeyPair: Ed25519KeyPair;
540
1226
  /** The member key to promote — the new `Manager.MemberKey` row. */
@@ -542,46 +1228,117 @@ export interface AddManagerParams {
542
1228
  }
543
1229
 
544
1230
  /**
545
- * Promote a member to `Manager` on the signature of an existing manager.
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.
546
1233
  *
547
- * The existing-manager branch of `Manager.Authorized` verifies
548
- * `digest(coalesce(new.MemberKey, old.MemberKey))` — `new.MemberKey` =
549
- * `newManagerKey` on insert — against a `Manager` row matching
550
- * `context.ManagerKey`. So the signer signs the new manager key directly (no
551
- * `'|'` join) and binds itself as `context.ManagerKey`.
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}).
552
1246
  *
553
- * Once the founder manager exists, the schema's `(select count(1) from Manager)
554
- * <= 1` bootstrap shortcut no longer applies to a second add (at commit the count
555
- * includes the new row, so it is ≥ 2), so this genuinely exercises signature
556
- * verification — a non-manager signer, or a signature over the wrong key, is
557
- * rejected.
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.
558
1257
  *
559
1258
  * @param db - The closed strand's database (founder manager already seated).
560
1259
  * @param params - The authorizing manager's keypair and the new manager key.
561
- * @throws If `Manager.Authorized` rejects; the insert rolls back.
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.
562
1263
  */
563
1264
  export async function addManager(db: Database, params: AddManagerParams): Promise<void> {
564
1265
  const { byManagerKeyPair, newManagerKey } = params;
565
- const signature = signStrandPayload(newManagerKey, byManagerKeyPair.privateKeyB64);
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
+ );
566
1278
  await db.exec(
567
- `insert into Strand.Manager (MemberKey)
1279
+ `insert into Strand.Manager (MemberKey, Generation, StampId)
568
1280
  with context ManagerKey = ?, Signature = ?
569
- values (?)`,
570
- [byManagerKeyPair.publicKeyB64, signature, newManagerKey],
1281
+ values (?, ?, ?)`,
1282
+ [byManagerKeyPair.publicKeyB64, signature, newManagerKey, generation, stampId],
571
1283
  );
572
- log('Added manager %s by %s', newManagerKey, byManagerKeyPair.publicKeyB64);
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);
573
1327
  }
574
1328
 
575
1329
  /** Parameters for {@link removeManager}. */
576
1330
  export interface RemoveManagerParams {
577
1331
  /**
578
- * The keypair authorizing the removal, bound as `context.ManagerKey` and
579
- * signing `digest(targetManagerKey)`. For an ADMIN removal this is a DIFFERENT
580
- * existing manager (satisfying the existing-manager branch); for a
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
581
1335
  * SELF-resignation it is the target's OWN keypair (`publicKeyB64 ===
582
- * targetManagerKey`, satisfying the former-manager self branch). The same
583
- * context construction satisfies whichever branch applies — see
584
- * {@link removeManager}.
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.
585
1342
  */
586
1343
  byManagerKeyPair: Ed25519KeyPair;
587
1344
  /** The `Manager.MemberKey` row to delete. */
@@ -592,49 +1349,84 @@ export interface RemoveManagerParams {
592
1349
  * Remove a `Manager` row — either an admin removing a different manager or a
593
1350
  * manager resigning itself.
594
1351
  *
595
- * On a DELETE, `coalesce(new.MemberKey, old.MemberKey)` binds `old.MemberKey =
596
- * targetManagerKey` (there is no `new` row), so the signed payload is the target
597
- * key for BOTH accepting branches of `Manager.Authorized`, and a single context
598
- * construction serves both:
599
- * - **Admin removal**: `byManagerKeyPair` is a different existing manager; the
600
- * existing-manager branch verifies the signature against `A.MemberKey =
601
- * context.ManagerKey`.
602
- * - **Self-resignation**: `byManagerKeyPair` IS the target (its `publicKeyB64`
603
- * equals `targetManagerKey`); the former-manager self branch verifies
604
- * `old.MemberKey = context.ManagerKey` and the self-signature over `old.MemberKey`.
605
- *
606
- * The caller selects the case purely by which keypair it passes — no branching here.
607
- *
608
- * KNOWN PLATFORM GAP (not fixable here): the optimystic bootstrap-mode transactor
609
- * evaluates deferred (subquery-bearing) CHECK constraints only on INSERT, not on
610
- * DELETE. `Manager.Authorized` is deferred, so the platform currently accepts ANY
611
- * `Manager` delete regardless of signature — `removeManager`'s authorization is
612
- * effectively unenforced at runtime until that gap is closed (filed as
613
- * `optimystic-deferred-check-not-enforced-on-delete`). This writer still builds the
614
- * correct, signed delete so it works unchanged once enforcement lands — exactly as
615
- * the invite path issues correct inserts despite the open PK-uniqueness gap.
616
- *
617
- * KNOWN SCHEMA HAZARD (not guarded here): even with enforcement, `Manager.
618
- * Authorized`'s `(select count(1) from Manager) <= 1` bootstrap branch is true at
619
- * commit whenever a delete drops the count to ≤ 1, so removing the strand's LAST (or
620
- * second-to-last) manager would be accepted regardless of signature — and removing
621
- * the last one orphans the strand (no one can ever add another). The schema does not
622
- * prevent this; a "min-one-manager" invariant is deferred to a future schema change
623
- * rather than grown into this writer.
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.
624
1403
  *
625
1404
  * @param db - The closed strand's database.
626
1405
  * @param params - The authorizing keypair and the target manager key.
627
- * @throws If `Manager.Authorized` rejects (e.g. a non-manager admin removal
628
- * while > 2 managers remain); the delete rolls back.
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.
629
1409
  */
630
1410
  export async function removeManager(db: Database, params: RemoveManagerParams): Promise<void> {
631
1411
  const { byManagerKeyPair, targetManagerKey } = params;
632
- const signature = signStrandPayload(targetManagerKey, byManagerKeyPair.privateKeyB64);
633
- await db.exec(
634
- `delete from Strand.Manager
635
- with context ManagerKey = ?, Signature = ?
636
- where MemberKey = ?`,
637
- [byManagerKeyPair.publicKeyB64, signature, targetManagerKey],
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,
638
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
+ });
639
1431
  log('Removed manager %s by %s', targetManagerKey, byManagerKeyPair.publicKeyB64);
640
1432
  }