@serfab/cadre-core 1.22.0 → 1.24.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 (314) hide show
  1. package/README.md +216 -294
  2. package/dist/arachnode-stub.d.ts +12 -4
  3. package/dist/arachnode-stub.js +15 -8
  4. package/dist/arachnode-stub.js.map +1 -1
  5. package/dist/cadre-invite-protocol.js +5 -4
  6. package/dist/cadre-invite-protocol.js.map +1 -1
  7. package/dist/cadre-node.d.ts +159 -53
  8. package/dist/cadre-node.js +276 -89
  9. package/dist/cadre-node.js.map +1 -1
  10. package/dist/control-authorization.d.ts +14 -2
  11. package/dist/control-authorization.js +8 -3
  12. package/dist/control-authorization.js.map +1 -1
  13. package/dist/control-cohort.d.ts +27 -13
  14. package/dist/control-cohort.js +21 -14
  15. package/dist/control-cohort.js.map +1 -1
  16. package/dist/control-database.d.ts +18 -16
  17. package/dist/control-database.js +57 -22
  18. package/dist/control-database.js.map +1 -1
  19. package/dist/control-protocol-guard.d.ts +1 -1
  20. package/dist/control-protocol-guard.js +7 -3
  21. package/dist/control-protocol-guard.js.map +1 -1
  22. package/dist/control-read-retry.d.ts +49 -11
  23. package/dist/control-read-retry.js +56 -15
  24. package/dist/control-read-retry.js.map +1 -1
  25. package/dist/control-retry.d.ts +32 -3
  26. package/dist/control-retry.js +35 -4
  27. package/dist/control-retry.js.map +1 -1
  28. package/dist/control-schema-version.d.ts +5 -5
  29. package/dist/control-schema-version.js +5 -5
  30. package/dist/control-schema-version.js.map +1 -1
  31. package/dist/control-schema.d.ts +5 -5
  32. package/dist/control-schema.js +1032 -1011
  33. package/dist/control-schema.js.map +1 -1
  34. package/dist/control-write-retry.d.ts +54 -65
  35. package/dist/control-write-retry.js +134 -158
  36. package/dist/control-write-retry.js.map +1 -1
  37. package/dist/delegate-admission.d.ts +1 -1
  38. package/dist/delegate-admission.js +1 -1
  39. package/dist/edge-node/config.d.ts +4 -3
  40. package/dist/edge-node/config.js +11 -9
  41. package/dist/edge-node/config.js.map +1 -1
  42. package/dist/edge-node/dissolve.d.ts +4 -4
  43. package/dist/edge-node/dissolve.js +4 -4
  44. package/dist/edge-node/edge-join.d.ts +1 -1
  45. package/dist/edge-node/edge-join.js +1 -1
  46. package/dist/edge-node/edge-node.js +2 -2
  47. package/dist/edge-node/edge-node.js.map +1 -1
  48. package/dist/edge-node/index.d.ts +1 -0
  49. package/dist/edge-node/index.js +1 -0
  50. package/dist/edge-node/index.js.map +1 -1
  51. package/dist/edge-node/join-credential.d.ts +1 -1
  52. package/dist/edge-node/join-credential.js +1 -1
  53. package/dist/edge-node/lazy-raw-storage.js +12 -0
  54. package/dist/edge-node/lazy-raw-storage.js.map +1 -1
  55. package/dist/edge-node/listen-addrs.d.ts +21 -0
  56. package/dist/edge-node/listen-addrs.js +25 -0
  57. package/dist/edge-node/listen-addrs.js.map +1 -0
  58. package/dist/edge-node/owner-grant.d.ts +1 -1
  59. package/dist/edge-node/owner-grant.js +1 -1
  60. package/dist/edge-node/platform.d.ts +5 -4
  61. package/dist/edge-node/platform.js.map +1 -1
  62. package/dist/edge-node/strand-move.d.ts +1 -1
  63. package/dist/edge-node/strand-move.js +1 -1
  64. package/dist/edge-node/strands.js +27 -11
  65. package/dist/edge-node/strands.js.map +1 -1
  66. package/dist/index.d.ts +7 -5
  67. package/dist/index.js +18 -7
  68. package/dist/index.js.map +1 -1
  69. package/dist/invitation-bootstrap.d.ts +28 -5
  70. package/dist/invitation-bootstrap.js +41 -8
  71. package/dist/invitation-bootstrap.js.map +1 -1
  72. package/dist/link-budget.d.ts +53 -4
  73. package/dist/link-budget.js +58 -5
  74. package/dist/link-budget.js.map +1 -1
  75. package/dist/machine-removal.d.ts +2 -2
  76. package/dist/machine-removal.js +4 -3
  77. package/dist/machine-removal.js.map +1 -1
  78. package/dist/membership-connection-gater.d.ts +2 -2
  79. package/dist/membership-connection-gater.js +2 -2
  80. package/dist/membership-view.d.ts +2 -2
  81. package/dist/membership-view.js +6 -3
  82. package/dist/membership-view.js.map +1 -1
  83. package/dist/node-claim-payload.d.ts +15 -7
  84. package/dist/node-claim-payload.js +25 -9
  85. package/dist/node-claim-payload.js.map +1 -1
  86. package/dist/node-class.d.ts +36 -0
  87. package/dist/node-class.js +26 -0
  88. package/dist/node-class.js.map +1 -0
  89. package/dist/node-default-transports.d.ts +50 -3
  90. package/dist/node-default-transports.js +48 -3
  91. package/dist/node-default-transports.js.map +1 -1
  92. package/dist/node-roles.d.ts +118 -0
  93. package/dist/node-roles.js +142 -0
  94. package/dist/node-roles.js.map +1 -0
  95. package/dist/node-transports.d.ts +6 -2
  96. package/dist/node-transports.js +39 -7
  97. package/dist/node-transports.js.map +1 -1
  98. package/dist/owner-anchor-sync.js +1 -1
  99. package/dist/owner-key-export.js +1 -1
  100. package/dist/owner-key-flows.d.ts +1 -1
  101. package/dist/owner-key-store.js +1 -1
  102. package/dist/owner-signer.js +1 -1
  103. package/dist/peer-authorization.d.ts +3 -1
  104. package/dist/peer-authorization.js +3 -1
  105. package/dist/peer-authorization.js.map +1 -1
  106. package/dist/peer-dial.d.ts +74 -10
  107. package/dist/peer-dial.js +89 -17
  108. package/dist/peer-dial.js.map +1 -1
  109. package/dist/peer-join-backfill.js +4 -4
  110. package/dist/peer-join-backfill.js.map +1 -1
  111. package/dist/peer-record.d.ts +34 -9
  112. package/dist/peer-record.js +66 -13
  113. package/dist/peer-record.js.map +1 -1
  114. package/dist/pending-join-runner.d.ts +1 -1
  115. package/dist/pending-join-runner.js +1 -1
  116. package/dist/provider/client.d.ts +6 -5
  117. package/dist/provider/client.js +3 -3
  118. package/dist/provider/client.js.map +1 -1
  119. package/dist/provider/descriptor.d.ts +1 -1
  120. package/dist/provider/descriptor.js +1 -1
  121. package/dist/provider/oauth.d.ts +1 -1
  122. package/dist/provider/oauth.js +1 -1
  123. package/dist/provider/rent-node.d.ts +4 -3
  124. package/dist/provider/rent-node.js +3 -3
  125. package/dist/provider/rent-node.js.map +1 -1
  126. package/dist/relay-addrs.d.ts +62 -7
  127. package/dist/relay-addrs.js +74 -11
  128. package/dist/relay-addrs.js.map +1 -1
  129. package/dist/relay-reservation.d.ts +1 -1
  130. package/dist/relay-reservation.js +1 -1
  131. package/dist/relay-server.d.ts +6 -5
  132. package/dist/relay-server.js +5 -5
  133. package/dist/relay-server.js.map +1 -1
  134. package/dist/schema-verification.d.ts +13 -10
  135. package/dist/schema-verification.js +32 -24
  136. package/dist/schema-verification.js.map +1 -1
  137. package/dist/sealed-party-key.js +1 -1
  138. package/dist/seed-bootstrap.d.ts +4 -3
  139. package/dist/seed-bootstrap.js +6 -7
  140. package/dist/seed-bootstrap.js.map +1 -1
  141. package/dist/strand-addr-protocol.d.ts +8 -6
  142. package/dist/strand-addr-protocol.js +12 -10
  143. package/dist/strand-addr-protocol.js.map +1 -1
  144. package/dist/strand-app-schema-report.d.ts +16 -2
  145. package/dist/strand-app-schema-report.js +15 -0
  146. package/dist/strand-app-schema-report.js.map +1 -1
  147. package/dist/strand-cohort.d.ts +1 -4
  148. package/dist/strand-cohort.js.map +1 -1
  149. package/dist/strand-commit-durability.d.ts +1 -1
  150. package/dist/strand-database.d.ts +13 -6
  151. package/dist/strand-database.js +17 -9
  152. package/dist/strand-database.js.map +1 -1
  153. package/dist/strand-first-sync-gate.d.ts +3 -2
  154. package/dist/strand-first-sync-gate.js +3 -2
  155. package/dist/strand-first-sync-gate.js.map +1 -1
  156. package/dist/strand-formation-deadlines.d.ts +2 -2
  157. package/dist/strand-formation-deadlines.js +2 -2
  158. package/dist/strand-formation-protocol.d.ts +1 -1
  159. package/dist/strand-formation-protocol.js +51 -16
  160. package/dist/strand-formation-protocol.js.map +1 -1
  161. package/dist/strand-instance-manager.d.ts +134 -42
  162. package/dist/strand-instance-manager.js +331 -76
  163. package/dist/strand-instance-manager.js.map +1 -1
  164. package/dist/strand-membership-reconciler.d.ts +8 -3
  165. package/dist/strand-membership-reconciler.js +8 -3
  166. package/dist/strand-membership-reconciler.js.map +1 -1
  167. package/dist/strand-membership-writer.d.ts +2 -2
  168. package/dist/strand-membership-writer.js +41 -39
  169. package/dist/strand-membership-writer.js.map +1 -1
  170. package/dist/strand-move.js +1 -1
  171. package/dist/strand-network-config.d.ts +15 -5
  172. package/dist/strand-network-config.js +7 -6
  173. package/dist/strand-network-config.js.map +1 -1
  174. package/dist/strand-party-key-rotation.d.ts +7 -3
  175. package/dist/strand-party-key-rotation.js +7 -3
  176. package/dist/strand-party-key-rotation.js.map +1 -1
  177. package/dist/strand-party-machines.d.ts +19 -8
  178. package/dist/strand-party-machines.js +26 -11
  179. package/dist/strand-party-machines.js.map +1 -1
  180. package/dist/strand-party-peers.d.ts +36 -14
  181. package/dist/strand-party-peers.js +24 -15
  182. package/dist/strand-party-peers.js.map +1 -1
  183. package/dist/strand-peer-redial.d.ts +1 -1
  184. package/dist/strand-peer-redial.js +1 -1
  185. package/dist/strand-reactivity.d.ts +20 -17
  186. package/dist/strand-reactivity.js +31 -18
  187. package/dist/strand-reactivity.js.map +1 -1
  188. package/dist/strand-revocation-enforcer.d.ts +3 -3
  189. package/dist/strand-revocation-enforcer.js +3 -3
  190. package/dist/strand-wake-protocol.d.ts +19 -7
  191. package/dist/strand-wake-protocol.js +22 -10
  192. package/dist/strand-wake-protocol.js.map +1 -1
  193. package/dist/strand-watcher.d.ts +1 -1
  194. package/dist/strand-watcher.js +1 -1
  195. package/dist/table-change-watch.js +1 -1
  196. package/dist/types.d.ts +127 -57
  197. package/dist/types.js.map +1 -1
  198. package/dist/webrtc-upgrade.d.ts +254 -0
  199. package/dist/webrtc-upgrade.js +355 -0
  200. package/dist/webrtc-upgrade.js.map +1 -0
  201. package/package.json +9 -9
  202. package/src/announce-addrs.ts +93 -93
  203. package/src/arachnode-stub.ts +18 -10
  204. package/src/bootstrap-peer-store-file.ts +44 -44
  205. package/src/bootstrap-peer-store.ts +214 -214
  206. package/src/cadre-invite-protocol.ts +741 -740
  207. package/src/cadre-node.ts +12462 -12252
  208. package/src/claim-proof.ts +147 -147
  209. package/src/control-authorization.ts +290 -276
  210. package/src/control-cohort.ts +223 -204
  211. package/src/control-database.ts +72 -28
  212. package/src/control-formation-recorder.ts +359 -359
  213. package/src/control-protocol-guard.ts +370 -366
  214. package/src/control-read-retry.ts +222 -180
  215. package/src/control-retry.ts +36 -4
  216. package/src/control-schema-version.ts +301 -301
  217. package/src/control-schema.ts +1108 -1087
  218. package/src/control-write-retry.ts +639 -669
  219. package/src/delegate-admission.ts +351 -351
  220. package/src/describe-thrown.ts +60 -60
  221. package/src/ed25519-key.ts +185 -185
  222. package/src/edge-node/config.ts +13 -10
  223. package/src/edge-node/dissolve.ts +252 -252
  224. package/src/edge-node/edge-join.ts +320 -320
  225. package/src/edge-node/edge-node.ts +1095 -1095
  226. package/src/edge-node/index.ts +60 -59
  227. package/src/edge-node/join-credential.ts +16 -16
  228. package/src/edge-node/lazy-raw-storage.ts +194 -178
  229. package/src/edge-node/listen-addrs.ts +26 -0
  230. package/src/edge-node/node-local.ts +84 -84
  231. package/src/edge-node/options.ts +195 -195
  232. package/src/edge-node/owner-grant.ts +63 -63
  233. package/src/edge-node/platform.ts +5 -4
  234. package/src/edge-node/strand-move.ts +266 -266
  235. package/src/edge-node/strands.ts +27 -12
  236. package/src/enrolled-machine-store-file.ts +43 -43
  237. package/src/enrolled-machine-store.ts +280 -280
  238. package/src/fetch-impl.ts +23 -23
  239. package/src/file-durable-slot.ts +64 -64
  240. package/src/file-safe-name.ts +32 -32
  241. package/src/formation-approval.ts +604 -604
  242. package/src/formation-token.ts +63 -63
  243. package/src/fs-atomic.ts +92 -92
  244. package/src/index.ts +987 -957
  245. package/src/invitation-bootstrap.ts +152 -118
  246. package/src/joined-strand-store.ts +553 -553
  247. package/src/key-store-file.ts +142 -142
  248. package/src/link-budget.ts +61 -5
  249. package/src/machine-removal.ts +211 -210
  250. package/src/member-redemption.ts +643 -643
  251. package/src/membership-connection-gater.ts +650 -650
  252. package/src/membership-view.ts +147 -144
  253. package/src/node-claim-payload.ts +34 -12
  254. package/src/node-class.ts +47 -0
  255. package/src/node-default-transports.ts +65 -3
  256. package/src/node-roles.ts +220 -0
  257. package/src/node-transports.ts +86 -49
  258. package/src/owner-anchor-sync.ts +172 -172
  259. package/src/owner-grant-protocol.ts +547 -547
  260. package/src/owner-key-export.ts +348 -348
  261. package/src/owner-key-flows.ts +109 -109
  262. package/src/owner-key-store.ts +1 -1
  263. package/src/owner-keys.ts +179 -179
  264. package/src/owner-signer.ts +92 -92
  265. package/src/peer-addr-book.ts +252 -252
  266. package/src/peer-authorization.ts +584 -582
  267. package/src/peer-dial.ts +698 -605
  268. package/src/peer-join-backfill.ts +961 -961
  269. package/src/peer-record.ts +71 -16
  270. package/src/pending-join-runner.ts +798 -798
  271. package/src/primary-lan-address.ts +47 -47
  272. package/src/provider/client.ts +327 -326
  273. package/src/provider/descriptor.ts +129 -129
  274. package/src/provider/index.ts +59 -59
  275. package/src/provider/oauth.ts +285 -285
  276. package/src/provider/rent-node.ts +276 -275
  277. package/src/relay-addrs.ts +90 -12
  278. package/src/relay-reservation.ts +1 -1
  279. package/src/relay-server.ts +99 -98
  280. package/src/schema-verification.ts +38 -23
  281. package/src/sealed-party-key.ts +190 -190
  282. package/src/seed-bootstrap.ts +8 -11
  283. package/src/seed-trust-policy.ts +353 -353
  284. package/src/self-address-update.ts +19 -19
  285. package/src/strand-addr-protocol.ts +17 -14
  286. package/src/strand-app-schema-report.ts +147 -122
  287. package/src/strand-cohort.ts +1 -5
  288. package/src/strand-commit-durability.ts +165 -165
  289. package/src/strand-database.ts +522 -510
  290. package/src/strand-first-sync-gate.ts +3 -2
  291. package/src/strand-formation-deadlines.ts +227 -227
  292. package/src/strand-formation-manager.ts +731 -731
  293. package/src/strand-formation-protocol.ts +1174 -1138
  294. package/src/strand-fret-addrs.ts +179 -179
  295. package/src/strand-instance-manager.ts +381 -85
  296. package/src/strand-membership-reconciler.ts +1315 -1310
  297. package/src/strand-membership-writer.ts +2152 -2150
  298. package/src/strand-move.ts +1 -1
  299. package/src/strand-network-config.ts +16 -6
  300. package/src/strand-offline.ts +178 -178
  301. package/src/strand-party-key-rotation.ts +440 -436
  302. package/src/strand-party-machines.ts +308 -293
  303. package/src/strand-party-peers.ts +151 -129
  304. package/src/strand-peer-redial.ts +1 -1
  305. package/src/strand-reactivity.ts +36 -19
  306. package/src/strand-revocation-enforcer.ts +758 -758
  307. package/src/strand-wake-protocol.ts +406 -394
  308. package/src/strand-watcher.ts +1 -1
  309. package/src/table-change-watch.ts +285 -285
  310. package/src/timed-step.ts +28 -28
  311. package/src/timeout-scheduler.ts +29 -29
  312. package/src/trusted-owner-store.ts +242 -242
  313. package/src/types.ts +3182 -3112
  314. package/src/webrtc-upgrade.ts +439 -0
@@ -1,2150 +1,2152 @@
1
- import debug from 'debug';
2
- import { toString as uint8ArrayToString } from 'uint8arrays';
3
- import { TransactionActiveError } from '@quereus/quereus';
4
- import type { Database, SqlValue } from '@quereus/quereus';
5
- import { digest, sign, verify, generatePrivateKey, getPublicKey, randomBytes } from '@optimystic/quereus-plugin-crypto';
6
- import { offlineControllerOf } from '@serfab/quereus-plugin-sereus';
7
- import type { SAppConfig } from './types.js';
8
- import type { Ed25519KeyPair } from './ed25519-key.js';
9
- import { canonicalDatetime } from './canonical-datetime.js';
10
-
11
- const log = debug('sereus:cadre:strand-membership');
12
-
13
- /**
14
- * The engine (rules-logic system) assumed to manage every strand. Persisted in
15
- * `Strand.Header.Engine`.
16
- *
17
- * PLACEHOLDER SEAM: there is no engine-selection mechanism yet — Quereus is the
18
- * only engine. When a real engine-config seam lands, the founder bootstrap should
19
- * read the strand's chosen engine from there instead of this constant. Documented
20
- * deliberately so the column is non-null and self-describing in the meantime.
21
- */
22
- export const STRAND_ENGINE = 'quereus';
23
-
24
- /**
25
- * The pinned engine version recorded in `Strand.Header.EngineVersion`. A pinned
26
- * string for the same reason as {@link STRAND_ENGINE}: it is a documented
27
- * placeholder until an engine-selection seam supplies the real running version.
28
- */
29
- export const STRAND_ENGINE_VERSION = '0.1.0';
30
-
31
- /**
32
- * The single-payload ed25519 signer the `Strand.Invite`/`Strand.ConsumedInvite`
33
- * handshake constraints verify against.
34
- *
35
- * Those constraints sign a single SHA-256 digest over a `'|'`-joined payload
36
- * (e.g. `InviteValid` verifies
37
- * `verify(digest(new.Key || '|' || coalesce(new.Expiration, '')), ...)`).
38
- * So the signer hashes the payload to raw bytes and ed25519-signs *those bytes*:
39
- * SQL `digest(...)`'s default output is base64url and `verify(...)`'s default
40
- * `inputEncoding` is base64url, so signer and verifier operate on identical bytes.
41
- * The membership/RBAC tables (Member/Manager/MemberPeer/Revocation) instead use
42
- * domain/action-tagged VARIADIC digests — see {@link signStrandApproval}.
43
- *
44
- * All strand keys are ed25519, so the explicit `'ed25519'` curve arg is mandatory
45
- * (the crypto plugin otherwise defaults to secp256k1). Mirrors the proven
46
- * `signItem` helper in the `rbac-signed-write` integration scenario.
47
- *
48
- * @param payload - The `'|'`-joined payload the matching constraint hashes.
49
- * @param privateKeyB64 - The signer's base64url ed25519 private seed.
50
- * @returns The base64url ed25519 signature over the payload's SHA-256 digest.
51
- */
52
- export function signStrandPayload(payload: string, privateKeyB64: string): string {
53
- const hashBytes = digest([payload], 'sha256', 'bytes') as Uint8Array;
54
- return sign(hashBytes, privateKeyB64, 'ed25519', 'bytes', 'base64url', 'base64url') as string;
55
- }
56
-
57
- /**
58
- * The verifier counterpart to {@link signStrandPayload}.
59
- *
60
- * Mirrors what the single-payload `Strand.*` constraints compute:
61
- * `verify(digest(payload), signature, publicKey, 'ed25519')`.
62
- * SQL `digest`'s default output and `verify`'s default `inputEncoding`/`sigEncoding`/
63
- * `keyEncoding` are all base64url, so the off-engine check operates on the exact
64
- * same bytes the in-engine CHECK does. Used by the off-engine `MemberVerifier`
65
- * (pre-flight registration checks) so the on-engine constraint is not the only
66
- * place a member self-proof is validated.
67
- *
68
- * @param payload - The `'|'`-joined payload the matching constraint hashes.
69
- * @param signatureB64 - The base64url ed25519 signature to check.
70
- * @param publicKeyB64 - The base64url ed25519 public key to verify against.
71
- * @returns `true` iff the signature is valid for the payload under that key.
72
- */
73
- export function verifyStrandPayload(payload: string, signatureB64: string, publicKeyB64: string): boolean {
74
- const payloadDigest = digest([payload], 'sha256', 'base64url') as string;
75
- return verify(payloadDigest, signatureB64, publicKeyB64, 'ed25519', 'base64url', 'base64url', 'base64url');
76
- }
77
-
78
- /**
79
- * Sign a domain/action-tagged `Strand.*` membership/RBAC approval.
80
- *
81
- * Every `Authorized` branch on `Member`/`Manager`/`MemberPeer`/`Revocation`
82
- * verifies a VARIADIC digest — `digest('<domain>', '<action>', <field>, ...,
83
- * <StampId>)` — whose leading two elements are fixed literals (the domain tag,
84
- * e.g. `'Strand.Member'`, and an action tag, e.g. `'add'`) and whose trailing
85
- * element is the row's per-incarnation StampId. The tags keep an approval from
86
- * verifying against any rule but the one it was minted for (the idiom of the
87
- * control layer's `buildAuthorizationMessage`); the StampId binding makes it
88
- * single-use — it authorizes exactly one incarnation of one row, and dies when
89
- * that row's stamp is retired into `Strand.Revocation`.
90
- *
91
- * The caller passes the digest elements exactly as the matching SQL constraint
92
- * lists them (each SQL argument = one array element), PRESERVING TYPE: the
93
- * crypto plugin's digest framing is type-tagged (INTEGER 1 and TEXT '1' encode
94
- * differently, deliberately), so `Manager.Authorized`'s promotion branch —
95
- * whose digest includes the INTEGER `new.Generation` — must be signed over the
96
- * NUMBER, not its string form. Integer `number` and `bigint` encode
97
- * identically in that framing, so JS-side numbers match however the engine
98
- * represents the SQL integer.
99
- *
100
- * Like {@link signStrandPayload}, the raw digest BYTES are ed25519-signed
101
- * directly, matching SQL `verify(...)`'s default base64url input decoding.
102
- *
103
- * @param fields - The digest elements, in constraint order (tags first, StampId last).
104
- * @param privateKeyB64 - The signer's base64url ed25519 private seed.
105
- * @returns The base64url ed25519 signature over the tagged digest.
106
- */
107
- export function signStrandApproval(fields: ReadonlyArray<string | number>, privateKeyB64: string): string {
108
- const hashBytes = digest(fields, 'sha256', 'bytes') as Uint8Array;
109
- return sign(hashBytes, privateKeyB64, 'ed25519', 'bytes', 'base64url', 'base64url') as string;
110
- }
111
-
112
- /**
113
- * Mint a fresh per-row authorization nonce (StampId) for a `Strand.Member`,
114
- * `Strand.Manager`, or `Strand.MemberPeer` row.
115
- *
116
- * 256 bits of CSPRNG output, base64url-encoded — enough entropy that a future
117
- * legitimate stamp cannot be guessed and pre-planted into `Strand.Revocation`
118
- * (the `RowIsGone` comment in `schemas/strand.qsql` leans on exactly this).
119
- * Plain randomness, deliberately NOT the control layer's peer-derived
120
- * `generateStampId`: strand rows are not per-peer, so entropy alone carries
121
- * the uniqueness.
122
- *
123
- * @returns A fresh base64url stamp (43 chars for 32 bytes).
124
- */
125
- export function generateStrandStampId(): string {
126
- // randomBytes' first arg is BITS, not bytes — 256 bits = 32 bytes.
127
- const bytes = randomBytes(256, 'bytes') as Uint8Array;
128
- return uint8ArrayToString(bytes, 'base64url');
129
- }
130
-
131
- // ── Write batches (every membership write is one indivisible transaction) ──────
132
-
133
- /**
134
- * A membership writer that runs only in a transaction of its own found another
135
- * transaction already open on the strand database, and wrote nothing. Raised only
136
- * under `joinOpenTransaction: false` (see {@link StrandWriteOptions}) — the background
137
- * callers, which treat it as "the app is mid-transaction; try again later".
138
- */
139
- export class StrandTransactionBusyError extends Error {
140
- constructor(options?: ErrorOptions) {
141
- super(
142
- 'Another transaction is open on the strand database. This membership write runs only in a '
143
- + 'transaction of its own, so nothing was written; retry once that transaction closes.',
144
- options,
145
- );
146
- this.name = 'StrandTransactionBusyError';
147
- }
148
- }
149
-
150
- /**
151
- * A membership write refused because the strand's offline queue holds transactions its members
152
- * have not taken yet (docs/strands.md → "Offline mode"). Every `Strand` table is network-acknowledged, and a
153
- * network-acknowledged commit made while transactions are queued waits for them to settle while
154
- * holding Quereus's execution lock, so every other statement on the strand database, the app's
155
- * included, would wait with it for up to the plugin's `networkCommitTimeoutMs`. Nothing was
156
- * written. Raised whether or not the write would have joined an open transaction: joining would
157
- * make the app's own commit wait the same way.
158
- */
159
- export class StrandOfflineQueueBusyError extends Error {
160
- /** The queued transactions the write would have waited behind, in queue order. */
161
- readonly transactionIds: readonly string[];
162
-
163
- constructor(transactionIds: readonly string[]) {
164
- super(
165
- `The strand's offline queue holds ${transactionIds.length} transaction(s) its members have not taken yet `
166
- + `(${transactionIds.join(', ')}). A membership write is acknowledged by the strand's members and would `
167
- + 'wait behind them, holding the strand database, so nothing was written; await '
168
- + 'strand.database.offline.whenDrained() and retry.',
169
- );
170
- this.name = 'StrandOfflineQueueBusyError';
171
- this.transactionIds = transactionIds;
172
- }
173
- }
174
-
175
- /** Options every transactional membership writer accepts. */
176
- export interface StrandWriteOptions {
177
- /**
178
- * Default true: when a transaction is already open on the database, run the writer's
179
- * statements inside it. The caller composes several writers in one transaction (e.g. a
180
- * resign + revoke pair that must land together) and owns its commit and rollback, so
181
- * the deferred constraints fire once, at the caller's commit.
182
- *
183
- * Background callers (the membership reconciler, the unpublish binding cleanup) pass
184
- * false: they share the database with the app and must never join a transaction
185
- * someone else opened, so the writer throws {@link StrandTransactionBusyError} instead.
186
- */
187
- joinOpenTransaction?: boolean;
188
- }
189
-
190
- /**
191
- * SQL statements, each terminated by `;`, plus the named parameters they bind. The unit
192
- * the writers assemble a batch from: a writer does every read, signature, and
193
- * `canonicalDatetime` first, and only then issues all its statements in ONE `db.exec`.
194
- */
195
- interface StrandStatements {
196
- sql: string;
197
- params: Record<string, SqlValue>;
198
- }
199
-
200
- /**
201
- * Join statement fragments into one batch. Named parameters bind across the whole batch,
202
- * so each fragment builder uses its own parameter names; a name bound twice would
203
- * silently hand one fragment the other's value, so it throws instead.
204
- */
205
- function combineStatements(...fragments: StrandStatements[]): StrandStatements {
206
- const params: Record<string, SqlValue> = {};
207
- for (const fragment of fragments) {
208
- for (const [name, value] of Object.entries(fragment.params)) {
209
- if (name in params) {
210
- throw new Error(`Strand write batch binds the parameter :${name} in two statements`);
211
- }
212
- params[name] = value;
213
- }
214
- }
215
- return { sql: fragments.map((fragment) => fragment.sql).join('\n'), params };
216
- }
217
-
218
- /**
219
- * Run `statements` as one indivisible transaction on the shared strand database.
220
- *
221
- * `exec(..., { transaction: true })` begins, runs, and commits or rolls back the whole
222
- * batch under a single hold of Quereus's execution mutex. That is what makes the
223
- * transaction indivisible on a `Database` the app shares with the background writers: no
224
- * other caller's statement can run inside it, so none is ever swept into a membership
225
- * write and lost when that write fails — not even a statement that fails before `commit`
226
- * (a primary-key collision, an immediate CHECK, a storage read error), whose rollback also
227
- * happens before the mutex is released. A hand-rolled `begin` / … / `commit` batch is not
228
- * equivalent, and a `beginTransaction()` / `exec` / `commit()` sequence even less so:
229
- * those are separate mutex acquisitions.
230
- *
231
- * Whether a transaction is already open is decided by the batch itself, under the mutex,
232
- * not by `getAutocommit()` beforehand: that reads false whenever another caller's
233
- * autocommit statement is merely in flight, which would make a background writer refuse
234
- * spuriously and a composing caller run its statements as separate autocommits.
235
- *
236
- * - The strand's offline queue holds transactions: {@link StrandOfflineQueueBusyError}, before
237
- * anything runs, every writer and every option alike (see {@link refuseBehindOfflineQueue}).
238
- * - No transaction was open: the batch commits or fails as a unit, leaving nothing open.
239
- * - One was already open, so the batch refuses with `TransactionActiveError` having run
240
- * nothing. With `joinOpenTransaction: false` that becomes a
241
- * {@link StrandTransactionBusyError} (with the refusal as `cause`), and the open
242
- * transaction — someone else's — is left alone. Otherwise the statements run inside it,
243
- * and its owner commits or rolls back.
244
- */
245
- async function execStrandTransaction(
246
- db: Database,
247
- statements: StrandStatements,
248
- options?: StrandWriteOptions,
249
- ): Promise<void> {
250
- refuseBehindOfflineQueue(db);
251
- try {
252
- await db.exec(statements.sql, statements.params, { transaction: true });
253
- return;
254
- } catch (error) {
255
- if (!(error instanceof TransactionActiveError)) {
256
- throw error;
257
- }
258
- if (options?.joinOpenTransaction === false) {
259
- throw new StrandTransactionBusyError({ cause: error });
260
- }
261
- }
262
- // NOTE: the join retry cannot ask for `{ transaction: true }` — the point is to run INSIDE the
263
- // caller's transaction — so it is atomic only for as long as that transaction stays open. Every
264
- // joining caller today opens its transaction, awaits the writer, then commits, so the
265
- // transaction cannot close in the window between the refusal above and this line. If a caller
266
- // ever closes its transaction concurrently with a writer call it did not await, these statements
267
- // run as separate autocommit statements instead of one unit. The writers whose statements are
268
- // circularly dependent (`consumeInvite`'s Member + ConsumedInvite, every delete + its Revocation
269
- // tombstone) fail loudly on their own deferred checks in that case; a writer whose statements are
270
- // each valid alone (`admitManager`) could commit only the first. If a caller ever needs to write
271
- // membership rows without awaiting, give it `joinOpenTransaction: false` rather than relying on
272
- // this path.
273
- await db.exec(statements.sql, statements.params);
274
- }
275
-
276
- /**
277
- * Throw {@link StrandOfflineQueueBusyError} while the strand's offline queue lists any
278
- * transaction. `entries()` also lists the journaled ones a restore has not put back yet, and a
279
- * network-acknowledged commit waits behind those too.
280
- *
281
- * NOTE: racy by nature: an app commit queued between this check and the batch's `exec` makes the
282
- * membership commit wait behind it, for up to `networkCommitTimeoutMs`, holding the execution
283
- * lock. That is upstream's bounded wait in the rare case. If a frozen strand database is ever
284
- * traced to a membership write that slipped past this check, hold the app's writes during
285
- * membership commits instead.
286
- */
287
- function refuseBehindOfflineQueue(db: Database): void {
288
- const queued = offlineControllerOf(db)?.entries() ?? [];
289
- if (queued.length > 0) {
290
- throw new StrandOfflineQueueBusyError(queued.map((entry) => entry.transactionId));
291
- }
292
- }
293
-
294
- /**
295
- * The `Strand.Revocation` tombstone insert that retires a deleted row's StampId.
296
- *
297
- * Always batched with the delete it accompanies — the guarded tables'
298
- * `RevocationRecorded` (deferred) requires the tombstone at commit, and
299
- * `Revocation.RowIsGone` (also deferred) requires the row to already be gone, so
300
- * the pair only ever lands together.
301
- *
302
- * `Revocation.Authorized` verifies the retire-tagged digest against a
303
- * PRE-transaction (`committed.Member`) row, so the retiree must have been a
304
- * member BEFORE this transaction. Every writer flow satisfies this: managers are
305
- * members, and a self-departing member is committed until this very transaction
306
- * removes it. Unlike the sibling tables' nullable contexts, `Revocation`'s
307
- * context is non-null — both fields are always supplied.
308
- *
309
- * @param tableName - Which guarded table the stamp belonged to.
310
- * @param stampId - The retired stamp.
311
- * @param retiree - The committed member filing the tombstone (the delete's own signer).
312
- */
313
- function revocationStatement(
314
- tableName: 'Member' | 'Manager' | 'MemberPeer',
315
- stampId: string,
316
- retiree: Ed25519KeyPair,
317
- ): StrandStatements {
318
- return {
319
- sql: `insert into Strand.Revocation (TableName, StampId)
320
- with context MemberKey = :revocationSignerKey, Signature = :revocationSignature
321
- values (:revocationTable, :revocationStampId);`,
322
- params: {
323
- revocationSignerKey: retiree.publicKeyB64,
324
- revocationSignature: signStrandApproval(['Strand.Revocation', 'retire', tableName, stampId], retiree.privateKeyB64),
325
- revocationTable: tableName,
326
- revocationStampId: stampId,
327
- },
328
- };
329
- }
330
-
331
- /** Parameters for {@link bootstrapFounderMembership}. */
332
- export interface FounderBootstrapParams {
333
- /** The strand id — written to `Header.Id`. */
334
- strandId: string;
335
- /** Strand type: `'o'` (open, Header only) or `'c'` (closed, Header+Member+Manager). */
336
- type: 'o' | 'c';
337
- /** The sApp config whose id/version/schema/signature populate the Header. */
338
- sApp: SAppConfig;
339
- /**
340
- * The founder's derived strand keypair (from {@link strandMemberKeyPair}). Its
341
- * `publicKeyB64` becomes the founding `Member.Key` and `Manager.MemberKey`.
342
- * Required for a closed strand; ignored for an open strand.
343
- */
344
- founderKeyPair?: Ed25519KeyPair;
345
- /**
346
- * The public key derived from the strand row's SHARED `MemberPrivateKey` (the read
347
- * secret every joining party holds). When supplied for a closed strand, a
348
- * `Strand.Member` or `Strand.Manager` row holding it refuses the bootstrap with
349
- * {@link PreSplitStrandIdentityError} (see {@link assertNotPreSplitStrand}): nothing
350
- * seats that key since the per-party identity split, so its presence is exactly the
351
- * fingerprint of a strand founded before it. Omitted, no such check runs (a caller that
352
- * holds no shared key has nothing to compare against). Ignored for an open strand.
353
- */
354
- sharedMemberPublicKey?: string;
355
- /**
356
- * This machine's strand transport peer id. When supplied for a closed strand, the run that
357
- * seats the founding `Member` also writes this machine's `Strand.MemberPeer` binding in the
358
- * same transaction, instead of leaving it to the membership reconciler's first pass (a
359
- * commit of its own). Omitted, no binding is written here: a database with no transport,
360
- * or a node whose reconciler is disarmed. Ignored for an open strand.
361
- */
362
- founderPeerId?: string;
363
- /**
364
- * Commit an empty collection for every table the strand declares except the qualified
365
- * tables named, resolving to how many it committed: the composition's
366
- * `createEmptyCollections`. Run once, on the founding run that finds no `Header` — see
367
- * {@link createDeclaredCollections}.
368
- */
369
- createEmptyCollections: (except?: readonly string[]) => Promise<number>;
370
- }
371
-
372
- /**
373
- * A closed strand founded BEFORE the per-party identity split: its founding
374
- * `Strand.Member` (and, unless handed on, `Strand.Manager`) is the key derived from the
375
- * shared `MemberPrivateKey`, which every joining party holds, so any member can sign as
376
- * the founder. There is no repair — rewriting the membership cannot be trusted, since any
377
- * joiner could already have admitted or revoked anyone, or could race the rewrite — so
378
- * the strand must be recreated. Thrown by {@link assertNotPreSplitStrand} (a founder
379
- * bootstrap, or membership-invite issuance); the formation layer maps it to a
380
- * non-retryable rejection.
381
- */
382
- export class PreSplitStrandIdentityError extends Error {
383
- constructor(readonly strandId: string) {
384
- super(
385
- `Closed strand ${strandId} was founded before per-party strand identity: its founding ` +
386
- 'member key is derived from the shared MemberPrivateKey that every joining party holds, ' +
387
- 'so any member can act as its founder. It cannot be repaired — recreate the strand ' +
388
- '(unpublish it and found a new one).',
389
- );
390
- this.name = 'PreSplitStrandIdentityError';
391
- }
392
- }
393
-
394
- /**
395
- * Count rows in a `Strand.*` table as seen by this database instance.
396
- *
397
- * The table name is a fixed literal supplied by this module (never user input),
398
- * so the interpolation is not an injection surface — it just keeps the singleton
399
- * insert-if-absent guards terse.
400
- */
401
- async function strandTableCount(db: Database, table: 'Header' | 'Member' | 'Manager'): Promise<number> {
402
- for await (const row of db.eval(`select count(1) as Count from Strand.${table}`)) {
403
- return (row.Count as number) ?? 0;
404
- }
405
- return 0;
406
- }
407
-
408
- /**
409
- * Whether any `Strand.Revocation` row has ever retired a `Manager` seat — the
410
- * exact condition that permanently closes the founding branch of
411
- * `Manager.Authorized` (see the schema's bootstrap-branch comment). Unfiltered
412
- * scan + JavaScript comparison, the module's scan-not-seek idiom (rationale on
413
- * {@link scanMemberPeers}).
414
- *
415
- * NOTE: walks the whole append-only `Strand.Revocation` table when no `Manager`
416
- * tombstone is present (it returns on the first one it finds). Cheap at strand
417
- * scale; if membership churn ever makes that table large — the growth the
418
- * `Revocation` schema comment already flags, tracked by `debt-strand-tombstone-reap`
419
- * — this wants a stored "founding closed" marker rather than a scan per call.
420
- *
421
- */
422
- async function strandHasManagerRevocation(db: Database): Promise<boolean> {
423
- for await (const row of db.eval('select TableName from Strand.Revocation')) {
424
- if (row.TableName === 'Manager') {
425
- return true;
426
- }
427
- }
428
- return false;
429
- }
430
-
431
- /** One founding row still missing: its qualified table and the statement that inserts it. */
432
- interface FoundingRow {
433
- table: 'Strand.Header' | 'Strand.Member' | 'Strand.Manager' | 'Strand.MemberPeer';
434
- statements: StrandStatements;
435
- }
436
-
437
- /**
438
- * Commit an empty collection for every table the strand declares except `writtenTables`, so a
439
- * read of a table nobody has written is answered from local storage instead of asking the
440
- * block's cohort to prove the collection absent, and still answers with the other members
441
- * offline. Peer-join backfill hands these collections to every joiner. The founding
442
- * transaction's own tables are left out because its inserts create their collections anyway.
443
- *
444
- * Only while the Header is absent, and before the founding transaction writes it: a machine
445
- * cannot write to a strand before it holds the Header (`strand-first-sync-gate.ts`), so no other
446
- * machine can yet have created any of these collections and this cannot fork one. On a founder
447
- * restart the Header is present and this does not run; running it there could commit an empty
448
- * second history beside a table a joiner wrote while the founder was away. A crash between this
449
- * and the founding commit repeats it on the next run, which commits only the collections still
450
- * missing.
451
- *
452
- * NOTE: one `sync()` per collection, in sequence. Measured 2026-10-17 on a lone node over the
453
- * network transactor (`connectToStrand`, then the step alone, 3 runs each): a nine-table app
454
- * schema (20 collections with the strand's own) took 32–82 ms in memory and 465–486 ms on
455
- * `FileRawStorage`; the reference chat schema (13 collections) 19–30 ms and 298–350 ms. About
456
- * 23 ms per collection on disk, once per strand, before `foundStrand` returns. Leaving out the
457
- * founding transaction's tables brings the chat schema to 6 collections on a closed strand whose
458
- * founder binds its peer, and 12 on an open one. If founding latency starts to matter (slower
459
- * phone storage, much larger schemas), commit them as one batch through a coordinator, the way
460
- * the transaction bridge's `commitBatchLegacy` does.
461
- */
462
- async function createDeclaredCollections(params: FounderBootstrapParams, writtenTables: readonly string[]): Promise<void> {
463
- const t0 = performance.now();
464
- const committed = await params.createEmptyCollections(writtenTables);
465
- log('Committed %d empty collections for strand %s in %dms',
466
- committed, params.strandId, Math.round(performance.now() - t0));
467
- }
468
-
469
- /**
470
- * The singleton `Strand.Header` insert.
471
- *
472
- * Every `Header` column is NOT NULL (Quereus defaults unqualified columns to NOT
473
- * NULL; the table declares no `null` columns), so all eight are supplied non-null.
474
- * A missing `sApp.signature` (dev `requireSignedSchemas:false`) coalesces to `''`
475
- * rather than inserting null. `Header` carries only `InsertOnly` + a singleton PK,
476
- * so the insert needs no `with context`.
477
- */
478
- function headerRow(params: FounderBootstrapParams): FoundingRow {
479
- return {
480
- table: 'Strand.Header',
481
- statements: {
482
- sql: `insert into Strand.Header
483
- (Id, Type, sAppId, sAppVersion, sAppSchema, sAppSignature, Engine, EngineVersion)
484
- values (:headerId, :headerType, :headerSAppId, :headerSAppVersion, :headerSAppSchema,
485
- :headerSAppSignature, :headerEngine, :headerEngineVersion);`,
486
- params: {
487
- headerId: params.strandId,
488
- headerType: params.type,
489
- headerSAppId: params.sApp.id,
490
- headerSAppVersion: params.sApp.version,
491
- headerSAppSchema: params.sApp.schema,
492
- headerSAppSignature: params.sApp.signature ?? '',
493
- headerEngine: STRAND_ENGINE,
494
- headerEngineVersion: STRAND_ENGINE_VERSION,
495
- },
496
- },
497
- };
498
- }
499
-
500
- /**
501
- * The founding `Strand.Member` insert.
502
- *
503
- * The empty PRE-transaction member set (`count(1) from committed.Member = 0`)
504
- * satisfies the bootstrap branch of `Member.Authorized`, so no signature is
505
- * needed — the context fields are explicit nulls. The branch also caps the
506
- * POST-image at one member, so it waives authorization for exactly this single
507
- * seat, never for a batch. The row still mints a fresh StampId — the column is
508
- * NOT NULL on every path; bootstrap only waives the SIGNATURE.
509
- */
510
- function founderMemberRow(memberKey: string): FoundingRow {
511
- return {
512
- table: 'Strand.Member',
513
- statements: {
514
- sql: `insert into Strand.Member (Key, StampId)
515
- with context ManagerKey = null, ManagerSignature = null, MemberSignature = null
516
- values (:founderMemberKey, :founderMemberStampId);`,
517
- params: { founderMemberKey: memberKey, founderMemberStampId: generateStrandStampId() },
518
- },
519
- };
520
- }
521
-
522
- /**
523
- * The founding `Strand.Manager` insert, at `Generation = 0` — the root of the manager
524
- * lineage; the bootstrap branch of `Manager.Authorized` requires exactly that value, and
525
- * every later manager is seated at a strictly greater generation (see {@link addManager}).
526
- * No signature is needed (a fresh StampId is still minted — the column is NOT NULL).
527
- *
528
- * The bootstrap branch, `Manager.MemberExists` and `Manager.OnlyClosed` all have subqueries,
529
- * so they defer to commit and read the live `Member` and `Header` tables: a founding
530
- * `Manager` whose `Member` and `Header` are neither committed already nor in its own
531
- * transaction is rejected.
532
- */
533
- function founderManagerRow(memberKey: string): FoundingRow {
534
- return {
535
- table: 'Strand.Manager',
536
- statements: {
537
- sql: `insert into Strand.Manager (MemberKey, Generation, StampId)
538
- with context ManagerKey = null, Signature = null
539
- values (:founderManagerKey, 0, :founderManagerStampId);`,
540
- params: { founderManagerKey: memberKey, founderManagerStampId: generateStrandStampId() },
541
- },
542
- };
543
- }
544
-
545
- /**
546
- * Whether the founding `Strand.Manager` still has to be seated: no manager exists and the
547
- * strand is not SEALED. A strand whose sole manager has {@link sealStrand}ed also has zero
548
- * `Manager` rows, but its founding branch is closed for good (the schema's bootstrap branch
549
- * requires no `Manager`-table `Revocation` row to exist). Seating it there would be
550
- * schema-rejected and turn every founder restart of a sealed strand into a loud failure — so
551
- * this mirrors the schema's own gate. A founding that never committed its Manager leaves no
552
- * Revocation rows at all, so that restart still completes the founding.
553
- */
554
- async function founderManagerMissing(db: Database, strandId: string): Promise<boolean> {
555
- if (await strandTableCount(db, 'Manager') > 0) {
556
- log('Manager already present for strand %s; skipping founder Manager', strandId);
557
- return false;
558
- }
559
- if (await strandHasManagerRevocation(db)) {
560
- log('Strand %s has retired a manager seat (sealed); skipping founder Manager', strandId);
561
- return false;
562
- }
563
- return true;
564
- }
565
-
566
- /**
567
- * This machine's `Strand.MemberPeer` binding, unless there is no peer id to bind or the
568
- * binding is already present (a re-run after a torn founding commit).
569
- */
570
- async function founderBindingIfAbsent(
571
- db: Database,
572
- founderKeyPair: Ed25519KeyPair,
573
- peerId: string | undefined,
574
- ): Promise<FoundingRow[]> {
575
- if (peerId === undefined) {
576
- return [];
577
- }
578
- if (await memberPeerStampId(db, founderKeyPair.publicKeyB64, peerId) !== undefined) {
579
- log('MemberPeer (%s, %s) already present; skipping founder binding', founderKeyPair.publicKeyB64, peerId);
580
- return [];
581
- }
582
- return [{ table: 'Strand.MemberPeer', statements: memberPeerInsertStatement(founderKeyPair, peerId) }];
583
- }
584
-
585
- /**
586
- * The closed strand's founding rows that are still missing, in Member → Manager → MemberPeer
587
- * order. Each is behind an insert-if-absent guard, so a re-run after a crash or a torn commit
588
- * writes only what is missing.
589
- *
590
- * The binding joins only a run that seats the founding `Member`. With a member row already
591
- * present the founder may since have left the strand or been removed, and
592
- * `MemberPeer.MemberExists` would then refuse the whole founding transaction; the membership
593
- * reconciler, which binds only once it sees this party's member row, writes it instead.
594
- */
595
- async function missingClosedFoundingRows(
596
- db: Database,
597
- founderKeyPair: Ed25519KeyPair,
598
- params: FounderBootstrapParams,
599
- ): Promise<FoundingRow[]> {
600
- const memberKey = founderKeyPair.publicKeyB64;
601
- const seatsMember = await strandTableCount(db, 'Member') === 0;
602
- if (!seatsMember) {
603
- log('Member already present for strand %s; skipping founder Member', params.strandId);
604
- }
605
- const seatsManager = await founderManagerMissing(db, params.strandId);
606
- const binding = seatsMember ? await founderBindingIfAbsent(db, founderKeyPair, params.founderPeerId) : [];
607
- return [
608
- ...(seatsMember ? [founderMemberRow(memberKey)] : []),
609
- ...(seatsManager ? [founderManagerRow(memberKey)] : []),
610
- ...binding,
611
- ];
612
- }
613
-
614
- /**
615
- * Refuse a closed strand whose membership still holds the key derived from the shared
616
- * `MemberPrivateKey` (see {@link FounderBootstrapParams.sharedMemberPublicKey}). `Member`
617
- * is the primary probe — every manager is a member (`Manager.MemberExists`), so it also
618
- * catches a pre-split founder who handed management to another key and resigned, or a
619
- * sealed pre-split strand. `Manager` is probed too, for the partition case the schema
620
- * notes on `MemberExists` (a Manager row converged without its Member row). Cannot
621
- * misfire: nothing seats the shared-derived key since the split, and rows not yet loaded
622
- * read as absent.
623
- *
624
- * @throws {PreSplitStrandIdentityError} when a `Strand.Member` or `Strand.Manager` row is
625
- * the shared-derived key.
626
- */
627
- export async function assertNotPreSplitStrand(db: Database, strandId: string, sharedMemberPublicKey: string): Promise<void> {
628
- if (await memberStampId(db, sharedMemberPublicKey) !== undefined
629
- || await managerRow(db, sharedMemberPublicKey) !== undefined) {
630
- throw new PreSplitStrandIdentityError(strandId);
631
- }
632
- }
633
-
634
- /**
635
- * Founder-only one-time bootstrap of a strand's `Strand.*` membership/RBAC rows.
636
- *
637
- * Runs once at bring-up on the strand's FOUNDER (the party that provisioned and
638
- * published the strand). A joiner never calls this — it receives these rows via
639
- * Optimystic sync. It reads which founding rows are missing, then writes all of them in
640
- * ONE strand transaction. Every row is insert-if-absent, so a restart / founder
641
- * re-`addStrand` writes nothing, and a re-run after a failed or torn founding commit
642
- * writes only what is missing.
643
- *
644
- * On the run that finds no `Header`, it first commits an empty collection for every
645
- * table the `Strand` and `App` schemas declare except the ones the founding transaction
646
- * writes, so no read of a declared table ever needs another member to prove it empty
647
- * ({@link createDeclaredCollections}).
648
- *
649
- * Behavior by strand type:
650
- * - **Open (`'o'`)**: `Header` only. `Member`/`Manager`/`Invite` are `OnlyClosed` and
651
- * would trip that constraint — they are skipped entirely.
652
- * - **Closed (`'c'`)**: `Header(Type='c')`, the founding `Member` and `Manager` (both
653
- * `founderKeyPair.publicKeyB64`) and, when `founderPeerId` is supplied, this machine's
654
- * `MemberPeer` binding. Every check that reads another founding row has a subquery, so
655
- * it defers to commit and sees the whole transaction.
656
- *
657
- * A closed strand with no `founderKeyPair` throws: a closed strand with no founding
658
- * Manager could never admit anyone, so failing loudly here (which propagates out
659
- * of `StrandDatabase.initialize()` and triggers the runtime's rollback) is correct.
660
- *
661
- * A closed strand whose membership holds `sharedMemberPublicKey` throws
662
- * {@link PreSplitStrandIdentityError} before writing anything: the insert-if-absent
663
- * guards would otherwise skip over its pre-split founding rows and leave the shared
664
- * key seated. Checked only when the `Header` is already present: a strand founded before
665
- * the key split committed its Header first, alone, so a strand with no Header has none
666
- * of those rows.
667
- *
668
- * @param db - The strand's Quereus database (schema already applied).
669
- * @param params - Strand id/type, the sApp config for the Header, the composition's
670
- * empty-collection step, and (closed only) the derived founder keypair, the
671
- * shared-derived public key to refuse and this machine's peer id to bind.
672
- * @throws If `type === 'c'` and no `founderKeyPair` is supplied.
673
- * @throws {PreSplitStrandIdentityError} If `type === 'c'` and a `Strand.Member` or
674
- * `Strand.Manager` row is `sharedMemberPublicKey`.
675
- */
676
- export async function bootstrapFounderMembership(db: Database, params: FounderBootstrapParams): Promise<void> {
677
- const { strandId, type, founderKeyPair, sharedMemberPublicKey } = params;
678
- log('Founder bootstrap for strand %s (type %s)', strandId, type);
679
-
680
- // Validate BEFORE writing anything: a closed strand with no founder key must
681
- // fail without leaving a closed `Header` that has no founding Member/Manager
682
- // (such a strand could never admit anyone).
683
- if (type === 'c' && !founderKeyPair) {
684
- throw new Error(
685
- `Cannot bootstrap closed strand ${strandId}: no founder key pair derived from this party's ` +
686
- 'StrandPartyKey. A closed strand needs a founding Member + Manager or it can never admit members.',
687
- );
688
- }
689
- const headerPresent = await strandTableCount(db, 'Header') > 0;
690
- if (headerPresent && type === 'c' && sharedMemberPublicKey !== undefined) {
691
- await assertNotPreSplitStrand(db, strandId, sharedMemberPublicKey);
692
- }
693
-
694
- const rows = [
695
- ...(headerPresent ? [] : [headerRow(params)]),
696
- ...(type === 'c' ? await missingClosedFoundingRows(db, founderKeyPair!, params) : []),
697
- ];
698
- if (!headerPresent) {
699
- await createDeclaredCollections(params, rows.map((row) => row.table));
700
- }
701
- if (rows.length === 0) {
702
- log('Strand %s is already founded; nothing to write', strandId);
703
- return;
704
- }
705
- // NOTE: a torn founding commit (some of the batch's collections saved, others not) can leave
706
- // the Header committed beside a founding table with no collection, which committing every
707
- // table's empty collection first used to rule out. A sibling machine of this party could then
708
- // create that collection itself (its reconciler binding its own peer into MemberPeer). The
709
- // re-run's guards, and this machine's reconciler, read each table before writing it, and a
710
- // networked read asks the cohort, so the healing write appends to the sibling's collection
711
- // unless the sibling is unreachable at that moment. A torn founding that saves this
712
- // machine's MemberPeer without its Member also leaves an orphaned binding, which every
713
- // machine's revocation enforcer (this one's and any joiner's) reads as a removed founder
714
- // until a later run of this bootstrap seats the Member. If torn founding commits are ever
715
- // observed, commit the founding tables a sibling writes (MemberPeer) as empty collections
716
- // before this batch again.
717
- await execStrandTransaction(db, combineStatements(...rows.map((row) => row.statements)));
718
- log('Founder bootstrap for strand %s wrote %s', strandId, rows.map((row) => row.table).join(', '));
719
- }
720
-
721
- // ── Invite issuance + consumption (the per-strand join handshake) ─────────────
722
-
723
- /** Parameters for {@link issueInvite}. */
724
- export interface IssueInviteParams {
725
- /**
726
- * The issuing manager's strand keypair. Its `publicKeyB64` must already be a
727
- * `Strand.Manager` row (the `InviteValid` constraint rejects a non-manager).
728
- */
729
- managerKeyPair: Ed25519KeyPair;
730
- /**
731
- * Optional invite expiry as epoch milliseconds. When set, it is canonicalised
732
- * via {@link canonicalDatetime} so the signed payload segment byte-matches the
733
- * `datetime`-coerced `Invite.Expiration` the deferred CHECK sees. When omitted,
734
- * the invite never expires and the signed segment is `''` (matching the schema's
735
- * `coalesce(new.Expiration, '')`).
736
- */
737
- expiration?: number;
738
- }
739
-
740
- /** The minted invite: a public key (the `Invite.Key`) plus its private seed. */
741
- export interface IssuedInvite {
742
- /** The invite ed25519 PUBLIC key (base64url) — the `Invite.Key` primary key. */
743
- inviteKey: string;
744
- /**
745
- * The invite ed25519 PRIVATE seed (base64url). Handed out-of-band to the
746
- * invitee; whoever holds it can {@link consumeInvite} exactly once. NEVER
747
- * persisted in the strand — only the public key is.
748
- */
749
- invitePrivateKey: string;
750
- }
751
-
752
- /**
753
- * Issue a single-use invitation to join a closed strand.
754
- *
755
- * Generates a fresh invite ed25519 keypair (the public key becomes `Invite.Key`),
756
- * builds the constraint's payload (`Key || '|' || coalesce(Expiration, '')`), and
757
- * signs it TWICE: with the manager private key (→ `ManagerSignature`, proving
758
- * a manager issued it) and with the invite private key (→ `InviteSignature`,
759
- * proving the issuer actually holds the invite secret). Both signatures plus the
760
- * manager public key are bound as constraint context for the `Invite` insert.
761
- *
762
- * The returned `invitePrivateKey` is the only secret the invitee needs to redeem
763
- * the invite — it is NOT stored in the strand (only `Invite.Key`, the public half,
764
- * is). Single-use is enforced at consumption time: `ConsumedInvite`'s primary key
765
- * is `InviteKey`, so a given invite can be consumed at most once.
766
- *
767
- * @param db - The closed strand's database (founder already bootstrapped).
768
- * @param params - The issuing manager keypair and optional expiry.
769
- * @returns The invite public key and the out-of-band private seed.
770
- */
771
- export async function issueInvite(db: Database, params: IssueInviteParams): Promise<IssuedInvite> {
772
- const { managerKeyPair, expiration } = params;
773
-
774
- const invitePrivateKey = generatePrivateKey('ed25519', 'base64url') as string;
775
- const inviteKey = getPublicKey(invitePrivateKey, 'ed25519', 'base64url', 'base64url') as string;
776
-
777
- // Canonicalise the expiry to the engine's stored `datetime` form so the signed
778
- // segment matches `new.Expiration` post-coercion; null expiry signs as ''.
779
- const expirationSegment = expiration == null ? '' : await canonicalDatetime(db, expiration);
780
- const expirationColumn = expiration == null ? null : expirationSegment;
781
-
782
- const payload = `${inviteKey}|${expirationSegment}`;
783
- const managerSignature = signStrandPayload(payload, managerKeyPair.privateKeyB64);
784
- const inviteSignature = signStrandPayload(payload, invitePrivateKey);
785
-
786
- await execStrandTransaction(db, {
787
- sql: `insert into Strand.Invite (Key, Expiration)
788
- with context ManagerKey = :managerKey, ManagerSignature = :managerSignature, InviteSignature = :inviteSignature
789
- values (:inviteKey, :expiration);`,
790
- params: { managerKey: managerKeyPair.publicKeyB64, managerSignature, inviteSignature, inviteKey, expiration: expirationColumn },
791
- });
792
- log('Issued invite %s (expires=%s)', inviteKey, expirationColumn ?? 'never');
793
-
794
- return { inviteKey, invitePrivateKey };
795
- }
796
-
797
- /** Parameters for {@link consumeInvite}. */
798
- export interface ConsumeInviteParams {
799
- /** The `Invite.Key` (invite PUBLIC key, base64url) being redeemed. */
800
- inviteKey: string;
801
- /** The matching invite PRIVATE seed (base64url) received out-of-band. */
802
- invitePrivateKey: string;
803
- /** The joining member's ed25519 PUBLIC key (base64url) — the new `Member.Key`. */
804
- memberKey: string;
805
- /**
806
- * The instant (epoch ms) to compare against the invite's `Expiration` for the
807
- * `NotExpired` gate. Defaults to `Date.now()`; tests pin it so the comparison is
808
- * deterministic. Mirrors the control-layer `redeemInvitation`'s `nowMs` convention.
809
- */
810
- nowMs?: number;
811
- }
812
-
813
- /**
814
- * Redeem an invite to admit a new `Member`, atomically.
815
- *
816
- * `Member.Authorized`'s invite branch needs a `ConsumedInvite` row, while
817
- * `ConsumedInvite`'s `MemberExists` needs the `Member` row — a circular
818
- * dependency. Both are deferred (subquery-bearing) checks that evaluate
819
- * at COMMIT, so inserting `Member` then `ConsumedInvite` inside one explicit
820
- * transaction lets both rows exist when the deferred checks fire. This mirrors
821
- * `ControlDatabase.redeemInvitation` (Strand + FormationUsage in one txn).
822
- *
823
- * The `ConsumedInvite` insert carries an `InviteSignature` over
824
- * `InviteKey || '|' || MemberKey`, proving the consumer holds the invite private
825
- * key (the on-engine `ValidUsage` gate). The `Member` insert needs no member
826
- * signature — its admission is the existence of the matching `ConsumedInvite` —
827
- * but still mints a fresh StampId (NOT NULL on every path; a revoked-then-
828
- * re-invited member is a fresh incarnation under a fresh stamp).
829
- *
830
- * Single-use: `ConsumedInvite`'s primary key is `InviteKey`, so a second consume
831
- * of the same invite is rejected by the PK (a distinct layer from the control
832
- * network's `FormationUsage` single-use, which gates strand FORMATION, not the
833
- * per-strand member join enforced here).
834
- *
835
- * Expiry: the `ConsumedInvite.NotExpired` deferred check rejects redeeming an invite
836
- * whose `Expiration` is at or before `context.Now`. `Now` is supplied here as a
837
- * canonical-datetime string from `canonicalDatetime(db, nowMs)` — the SAME transform
838
- * `issueInvite` uses to store `Invite.Expiration` — so both sides of the schema's
839
- * `I.Expiration > context.Now` comparison are byte-identical canonical strings and
840
- * the lexical `>` orders chronologically at any granularity. (This intentionally
841
- * diverges from the control layer, which passes `Now` as a JS ISO string; Quereus
842
- * does not coerce context params, so an ISO `Now` would be compared lexically against
843
- * the canonical, T-separated `Expiration` and could mis-order near-same-instant
844
- * timestamps (due to a trailing `.000Z` suffix). The control tests only use far-future/far-past expiries, so that latent
845
- * skew never bites there — the strand layer avoids it outright.) A null `Expiration`
846
- * never expires. Like `ValidUsage`, `NotExpired` defers to commit, so an expired
847
- * invite rolls back the whole txn — neither the `Member` nor the `ConsumedInvite`
848
- * row survives.
849
- *
850
- * @param db - The closed strand's database.
851
- * @param params - The invite key/secret, the joining member's public key, and an
852
- * optional `nowMs` instant for the expiry comparison (default `Date.now()`).
853
- * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
854
- * @throws If any constraint rejects (bad signature, missing invite, or an expired
855
- * invite); the whole transaction rolls back (neither the `Member` nor the
856
- * `ConsumedInvite` row survives).
857
- * @throws {StrandTransactionBusyError} Under `joinOpenTransaction: false`, when another
858
- * transaction is open; nothing was written.
859
- */
860
- export async function consumeInvite(
861
- db: Database,
862
- params: ConsumeInviteParams,
863
- options?: StrandWriteOptions,
864
- ): Promise<void> {
865
- const { inviteKey, memberKey } = params;
866
- // Member first — admitted by the deferred invite branch (the matching ConsumedInvite
867
- // after it), so no manager signature is supplied.
868
- const member: StrandStatements = {
869
- sql: `insert into Strand.Member (Key, StampId)
870
- with context ManagerKey = null, ManagerSignature = null, MemberSignature = null
871
- values (:memberKey, :memberStampId);`,
872
- params: { memberKey, memberStampId: generateStrandStampId() },
873
- };
874
- await execStrandTransaction(db, combineStatements(member, await consumedInviteStatement(db, params)), options);
875
- log('Consumed invite %s -> member %s', inviteKey, memberKey);
876
- }
877
-
878
- /**
879
- * The `Strand.ConsumedInvite` marker row insert — the possession-plus-freshness proof
880
- * shared by {@link consumeInvite} (batched after its `Member` insert) and
881
- * {@link burnInvite} (alone, against an already-seated member).
882
- *
883
- * The invite signature covers `InviteKey || '|' || MemberKey` (the `ValidUsage` gate),
884
- * and "now" is canonicalised the same way {@link issueInvite} canonicalises
885
- * `Expiration`, so the schema's `I.Expiration > context.Now` compares like-for-like
886
- * canonical strings. Plain runtime Date.now() — the tess Workflow restriction is on
887
- * scripts, not libs.
888
- */
889
- async function consumedInviteStatement(db: Database, params: ConsumeInviteParams): Promise<StrandStatements> {
890
- const { inviteKey, invitePrivateKey, memberKey, nowMs } = params;
891
- return {
892
- sql: `insert into Strand.ConsumedInvite (InviteKey, MemberKey)
893
- with context InviteSignature = :consumedSignature, Now = :consumedNow
894
- values (:consumedInviteKey, :consumedMemberKey);`,
895
- params: {
896
- consumedSignature: signStrandPayload(`${inviteKey}|${memberKey}`, invitePrivateKey),
897
- consumedNow: await canonicalDatetime(db, nowMs ?? Date.now()),
898
- consumedInviteKey: inviteKey,
899
- consumedMemberKey: memberKey,
900
- },
901
- };
902
- }
903
-
904
- /**
905
- * Burn an invitation against an ALREADY-SEATED member: insert the
906
- * `Strand.ConsumedInvite` row alone, naming the existing `Member.Key`, so the bearer
907
- * credential can never be spent by anyone else.
908
- *
909
- * The already-member arm of the bring-up membership reconciler
910
- * (`strand-membership-reconciler.ts`): a machine that finds its party's `Member` row
911
- * already present (a sibling machine redeemed the invitation's twin first, or a
912
- * manager admitted the party directly) may still hold an UNSPENT formation-delivered
913
- * invitation — a bearer credential whoever presents can join with. Every
914
- * `ConsumedInvite` constraint is satisfiable without a same-transaction `Member`
915
- * insert (`MemberExists` reads the live table), so this is one statement whose
916
- * deferred checks fire at its own commit. It seats nobody now or later:
917
- * `Member.Authorized`'s invite branch requires a same-transaction FRESH consumption,
918
- * so the row it leaves is exactly as inert as any other spent invitation's.
919
- *
920
- * @param db - The closed strand's database (the member already exists).
921
- * @param params - The invite key/secret and the EXISTING member's public key, plus the
922
- * optional `nowMs` instant for the expiry gate (default `Date.now()`).
923
- * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
924
- * @throws If any constraint rejects — already consumed (the `InviteKey` primary key),
925
- * cancelled, expired, or a sealed strand — or the cohort refuses the write. The
926
- * reconciler routes these through the same classifier as a `consumeInvite` rejection:
927
- * a dead invitation is dropped, a refused write keeps it staged for a retry.
928
- * @throws {StrandTransactionBusyError} Under `joinOpenTransaction: false`, when another
929
- * transaction is open; nothing was tried, so the invitation is exactly as live as before.
930
- */
931
- export async function burnInvite(
932
- db: Database,
933
- params: ConsumeInviteParams,
934
- options?: StrandWriteOptions,
935
- ): Promise<void> {
936
- await execStrandTransaction(db, await consumedInviteStatement(db, params), options);
937
- log('Burned invite %s against existing member %s', params.inviteKey, params.memberKey);
938
- }
939
-
940
- /**
941
- * Every value of `InviteKey` in one of the two invite-marker tables, as a `Set`.
942
- *
943
- * Unfiltered scan + JavaScript comparison, deliberately: `ConsumedInvite` and
944
- * `CancelledInvite` each have the single column `InviteKey` as their primary key, so
945
- * ANY where-equality on it is a FULL-PK predicate — which the optimystic virtual-table
946
- * module serves via a single-key point lookup that can MISS on a networked strand (the
947
- * argument {@link scanMemberPeers} makes in full). Reading the whole column and
948
- * comparing in JS depends only on the scan returning a SUPERSET of the live rows.
949
- *
950
- * The table name is a fixed literal supplied by this module (never user input), so the
951
- * interpolation is not an injection surface — same as {@link strandTableCount}.
952
- *
953
- * NOTE: every caller pays a WHOLE-column read — {@link cancelInvite}'s idempotence guard
954
- * reads all cancelled keys to answer one membership question, and
955
- * {@link listOutstandingInvites} reads both marker tables per call. Fine at strand scale
956
- * (a handful of invitations); if invite churn ever gets large this wants a real filtered
957
- * read, which in turn needs the networked point-lookup gap closed
958
- * (`debt-composite-pk-point-lookup-unreliable-untracked`).
959
- */
960
- async function scanInviteKeys(db: Database, table: 'ConsumedInvite' | 'CancelledInvite'): Promise<Set<string>> {
961
- const keys = new Set<string>();
962
- for await (const row of db.eval(`select InviteKey from Strand.${table}`)) {
963
- keys.add(row.InviteKey as string);
964
- }
965
- return keys;
966
- }
967
-
968
- /** Parameters for {@link cancelInvite}. */
969
- export interface CancelInviteParams {
970
- /**
971
- * The cancelling manager's strand keypair. Its `publicKeyB64` must be a
972
- * PRE-EXISTING `Strand.Manager` row — `CancelledInvite.Authorized` reads
973
- * `committed.Manager`, so a manager seated in the SAME transaction cannot cancel.
974
- */
975
- managerKeyPair: Ed25519KeyPair;
976
- /** The `Invite.Key` to kill. */
977
- inviteKey: string;
978
- }
979
-
980
- /**
981
- * Cancel an outstanding invitation, permanently: it may never be consumed.
982
- *
983
- * Files a `Strand.CancelledInvite` tombstone carrying a manager signature over
984
- * `digest('Strand.CancelledInvite', 'cancel', InviteKey)`. The digest binds the exact
985
- * invite key, so an approval minted for one invitation cannot cancel another.
986
- *
987
- * One row, one statement. `CancelledInvite.Authorized` is a deferred (subquery-bearing)
988
- * check, so it fires at the batch's commit, or at the caller's when it joins an open one.
989
- *
990
- * Insert-if-absent, matching {@link registerMemberPeer}'s and {@link revokeMember}'s
991
- * restart-safe shape: a repeat cancellation logs and returns rather than throwing on the
992
- * primary key. (Check-then-write is not atomic; the primary key is the real backstop —
993
- * the guard is for the sequential repeat/restart path.)
994
- *
995
- * Cancellation is what makes removal a re-entry gate: it is the `ConsumedInvite` insert
996
- * that `NotCancelled` blocks, and `Member.Authorized`'s invite branch needs a
997
- * same-transaction FRESH `ConsumedInvite` row, so a cancelled invitation rolls the whole
998
- * join back. Un-cancelling is impossible (`CancelledInvite.Immutable`) — to re-invite a
999
- * party, {@link issueInvite} a fresh invitation.
1000
- *
1001
- * Enumerate what there is to cancel with {@link listOutstandingInvites}: an invitation
1002
- * names no invitee, so the strand cannot tell a manager WHICH invitations a departing
1003
- * member holds. Invitee binding is tracked as `feat-strand-invitee-bound-invites`.
1004
- *
1005
- * @param db - The closed strand's database.
1006
- * @param params - The cancelling manager's keypair and the invite key to kill.
1007
- * @throws If `CancelledInvite.Authorized` rejects (a non-manager, a manager seated in
1008
- * this transaction, or an approval minted for a different invite key) or `OnlyClosed`
1009
- * rejects (an open strand); the insert rolls back, leaving no tombstone.
1010
- */
1011
- export async function cancelInvite(db: Database, params: CancelInviteParams): Promise<void> {
1012
- const { managerKeyPair, inviteKey } = params;
1013
-
1014
- if ((await scanInviteKeys(db, 'CancelledInvite')).has(inviteKey)) {
1015
- log('Invite %s already cancelled; skipping', inviteKey);
1016
- return;
1017
- }
1018
-
1019
- const signature = signStrandApproval(
1020
- ['Strand.CancelledInvite', 'cancel', inviteKey],
1021
- managerKeyPair.privateKeyB64,
1022
- );
1023
- await execStrandTransaction(db, {
1024
- sql: `insert into Strand.CancelledInvite (InviteKey)
1025
- with context ManagerKey = :managerKey, ManagerSignature = :managerSignature
1026
- values (:inviteKey);`,
1027
- params: { managerKey: managerKeyPair.publicKeyB64, managerSignature: signature, inviteKey },
1028
- });
1029
- log('Cancelled invite %s by manager %s', inviteKey, managerKeyPair.publicKeyB64);
1030
- }
1031
-
1032
- /** One redeemable invitation, as reported by {@link listOutstandingInvites}. */
1033
- export interface OutstandingInvite {
1034
- /** The `Invite.Key` (invite public key, base64url). */
1035
- inviteKey: string;
1036
- /**
1037
- * The expiry as the engine's canonical `datetime` string
1038
- * (`YYYY-MM-DDTHH:MM:SS[.frac]`, no zone suffix — see {@link canonicalDatetime}), or
1039
- * `null` for never-expires.
1040
- *
1041
- * Deliberately the STORED form, not the epoch-ms {@link IssueInviteParams.expiration}
1042
- * takes: it is what compares like-for-like against another canonicalised instant, and
1043
- * what the on-engine `NotExpired` gate sees. It is NOT a JS-parseable ISO instant —
1044
- * pass it through the engine (or `canonicalDatetime`) rather than `Date.parse`.
1045
- */
1046
- expiration: string | null;
1047
- }
1048
-
1049
- /**
1050
- * The invitations that are still redeemable: neither consumed, nor cancelled, nor
1051
- * expired at `nowMs`.
1052
- *
1053
- * `Strand.Invite` is insert-only and carries no state column, so "outstanding" is not a
1054
- * property of the row — it is the `Invite` set minus the `ConsumedInvite` keys, minus
1055
- * the `CancelledInvite` keys, minus anything whose `Expiration` has passed. All three
1056
- * exclusions mirror gates a consume would hit anyway (`ConsumedInvite`'s primary key,
1057
- * `NotCancelled`, `NotExpired`).
1058
- *
1059
- * Reads via unfiltered scans and compares in JavaScript — see {@link scanInviteKeys} for
1060
- * why a full-PK where-equality is not reliable on a networked strand.
1061
- *
1062
- * Expiry is compared as `expiration > canonicalDatetime(nowMs)`: the same transform
1063
- * {@link issueInvite} uses to STORE `Invite.Expiration`, so the string comparison orders
1064
- * chronologically, and the same strict `>` the on-engine `NotExpired` gate uses (expiry
1065
- * is exclusive — an invitation is dead at its expiry instant, not after it).
1066
- *
1067
- * This is the manager's enumeration side of {@link cancelInvite}, and the "door is open"
1068
- * pre-flight behind `StrandMemberVerifier.isAuthorizedToJoin`.
1069
- *
1070
- * @param db - The closed strand's database.
1071
- * @param nowMs - The instant (epoch ms) to compare expiries against; defaults to
1072
- * `Date.now()`. Tests pin it so the comparison is deterministic, mirroring
1073
- * {@link consumeInvite}'s `nowMs` convention.
1074
- * @returns The redeemable invitations, in NO guaranteed order (the scans promise only a
1075
- * superset of the live rows, not a stable sequence — sort by `expiration` if order
1076
- * matters); empty if none.
1077
- */
1078
- export async function listOutstandingInvites(db: Database, nowMs?: number): Promise<OutstandingInvite[]> {
1079
- // Plain runtime Date.now() — the tess Workflow restriction is on scripts, not libs.
1080
- const nowCanonical = await canonicalDatetime(db, nowMs ?? Date.now());
1081
- const consumed = await scanInviteKeys(db, 'ConsumedInvite');
1082
- const cancelled = await scanInviteKeys(db, 'CancelledInvite');
1083
-
1084
- const outstanding: OutstandingInvite[] = [];
1085
- for await (const row of db.eval('select Key, Expiration from Strand.Invite')) {
1086
- const inviteKey = row.Key as string;
1087
- const expiration = (row.Expiration as string | null) ?? null;
1088
- if (consumed.has(inviteKey) || cancelled.has(inviteKey)) {
1089
- continue;
1090
- }
1091
- if (expiration != null && expiration <= nowCanonical) {
1092
- continue;
1093
- }
1094
- outstanding.push({ inviteKey, expiration });
1095
- }
1096
- return outstanding;
1097
- }
1098
-
1099
- // ── Member admission + removal (manager-admit, revoke, leave) ─────────────────
1100
-
1101
- /**
1102
- * The live StampId of the `Strand.Member` row keyed by `memberKey`, or
1103
- * `undefined` if no such row is visible.
1104
- *
1105
- * `Member`'s primary key is the single `Key` column, so ANY where-equality on it
1106
- * is a full-PK predicate — which the optimystic virtual-table module serves via a
1107
- * single-key point lookup that can MISS on a networked strand (the same failure
1108
- * mode {@link scanMemberPeers} documents). So this reads via an UNFILTERED scan
1109
- * and compares the key in JavaScript: correctness depends only on the scan
1110
- * returning a superset of the live rows — the weakest possible assumption about
1111
- * the storage layer.
1112
- */
1113
- async function memberStampId(db: Database, memberKey: string): Promise<string | undefined> {
1114
- for await (const row of db.eval('select Key, StampId from Strand.Member')) {
1115
- if (row.Key === memberKey) {
1116
- return row.StampId as string;
1117
- }
1118
- }
1119
- return undefined;
1120
- }
1121
-
1122
- /**
1123
- * Whether `memberKey` holds a live `Strand.Member` row, as seen by THIS database
1124
- * instance — the membership probe behind the bring-up reconciler
1125
- * (`strand-membership-reconciler.ts`). Reads via {@link memberStampId}'s unfiltered
1126
- * scan + JavaScript compare (the {@link scanMemberPeers} argument for why a PK point
1127
- * lookup is not reliable on a networked strand). Local visibility only: `false` can
1128
- * mean "not replicated here yet", never a durable verdict about the strand.
1129
- */
1130
- export async function isStrandMember(db: Database, memberKey: string): Promise<boolean> {
1131
- return await memberStampId(db, memberKey) != null;
1132
- }
1133
-
1134
- /**
1135
- * Whether `memberKey` holds a live `Strand.Manager` row, as seen by THIS database instance:
1136
- * the sibling of {@link isStrandMember} for the manager seat, which the party key rotation
1137
- * driver (`strand-party-key-rotation.ts`) reads to know whether the party can seat its own
1138
- * new key. Same unfiltered scan, same local-visibility caveat.
1139
- */
1140
- export async function isStrandManager(db: Database, memberKey: string): Promise<boolean> {
1141
- return await managerRow(db, memberKey) !== undefined;
1142
- }
1143
-
1144
- /** Parameters for {@link addMemberByManager}. */
1145
- export interface AddMemberByManagerParams {
1146
- /**
1147
- * The admitting manager's strand keypair. Its `publicKeyB64` must be a
1148
- * `Strand.Manager` row; it signs the add-tagged digest over the new member key
1149
- * and its fresh stamp.
1150
- */
1151
- managerKeyPair: Ed25519KeyPair;
1152
- /** The joining member's ed25519 PUBLIC key (base64url) — the new `Member.Key`. */
1153
- memberKey: string;
1154
- }
1155
-
1156
- /**
1157
- * Admit a `Member` directly by manager signature — the sibling of the invite
1158
- * path on `Member.Authorized`'s direct-manager branch.
1159
- *
1160
- * The constraint verifies the add-tagged digest
1161
- * `digest('Strand.Member', 'add', new.Key, new.StampId)` against a pre-existing
1162
- * (`committed.Manager`) row matching `context.ManagerKey`. The stamp is minted
1163
- * fresh here and bound inside the signed digest, so the approval seats exactly
1164
- * this incarnation: once the member is removed (retiring the stamp), the captured
1165
- * approval can never re-seat it. No `ConsumedInvite` is involved: this is the
1166
- * path a manager uses to seat a member it already trusts (e.g. a manager-side
1167
- * enrollment that admits a party already authorised out-of-band).
1168
- *
1169
- * @param db - The closed strand's database.
1170
- * @param params - The admitting manager keypair and the new member key.
1171
- * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1172
- * @throws If `Member.Authorized` rejects (e.g. a non-manager key); the insert
1173
- * rolls back, leaving no `Member` row.
1174
- */
1175
- export async function addMemberByManager(
1176
- db: Database,
1177
- params: AddMemberByManagerParams,
1178
- options?: StrandWriteOptions,
1179
- ): Promise<void> {
1180
- const { managerKeyPair, memberKey } = params;
1181
- await execStrandTransaction(db, memberAddByManagerStatement(params), options);
1182
- log('Admitted member %s by manager %s', memberKey, managerKeyPair.publicKeyB64);
1183
- }
1184
-
1185
- /** The manager-signed `Strand.Member` insert behind {@link addMemberByManager}, under a fresh stamp. */
1186
- function memberAddByManagerStatement(params: AddMemberByManagerParams): StrandStatements {
1187
- const { managerKeyPair, memberKey } = params;
1188
- const stampId = generateStrandStampId();
1189
- return {
1190
- sql: `insert into Strand.Member (Key, StampId)
1191
- with context ManagerKey = :memberAdmitterKey, ManagerSignature = :memberAdmitterSignature, MemberSignature = null
1192
- values (:memberKey, :memberStampId);`,
1193
- params: {
1194
- memberAdmitterKey: managerKeyPair.publicKeyB64,
1195
- memberAdmitterSignature: signStrandApproval(['Strand.Member', 'add', memberKey, stampId], managerKeyPair.privateKeyB64),
1196
- memberKey,
1197
- memberStampId: stampId,
1198
- },
1199
- };
1200
- }
1201
-
1202
- /** Parameters for {@link revokeMember}. */
1203
- export interface RevokeMemberParams {
1204
- /**
1205
- * The revoking manager's strand keypair. Its `publicKeyB64` must be a
1206
- * PRE-EXISTING `Strand.Manager` row (the manager-removal branch of
1207
- * `Member.Authorized` reads `committed.Manager` — a manager seated in the same
1208
- * transaction cannot authorize); it signs the remove-tagged digest over the
1209
- * target row's key and live stamp, and files the accompanying tombstone.
1210
- */
1211
- managerKeyPair: Ed25519KeyPair;
1212
- /** The `Member.Key` row to delete. */
1213
- memberKey: string;
1214
- }
1215
-
1216
- /**
1217
- * Revoke a `Member` on the signature of an existing manager.
1218
- *
1219
- * Reads the target row's live StampId first (a quiet no-op if the row is already
1220
- * absent — a repeated or restarted revocation should not throw), then runs ONE
1221
- * transaction pairing the delete with its `Strand.Revocation` tombstone: the
1222
- * schema's `Member.RevocationRecorded` requires the tombstone in the same
1223
- * transaction, and the tombstone is what permanently retires the stamp so the
1224
- * captured admission approval can never re-seat this incarnation.
1225
- *
1226
- * The manager-removal branch of `Member.Authorized` verifies the remove-tagged
1227
- * digest `digest('Strand.Member', 'remove', old.Key, old.StampId)` against a
1228
- * `committed.Manager` row matching `context.ManagerKey` — distinct from the
1229
- * add-tagged admission payload, and bound to the live stamp, so neither a
1230
- * captured admission nor a captured PRIOR removal (whose stamp differs) replays.
1231
- *
1232
- * A revoked member cannot re-admit itself off the invite it ALREADY SPENT: that
1233
- * `ConsumedInvite` row is stale, and the invite branch requires a
1234
- * same-transaction FRESH consumption. Re-admission normally takes a fresh
1235
- * manager action ({@link addMemberByManager} or a new invite).
1236
- *
1237
- * An UNSPENT invite the revoked party holds is killed EXPLICITLY, by the manager
1238
- * calling {@link cancelInvite} on it (enumerate the candidates with
1239
- * {@link listOutstandingInvites}); a cancelled invitation can never be consumed,
1240
- * and cancellation is permanent. This removal does NOT cascade into cancellation:
1241
- * an invitation names no invitee, so there is nothing to match the removed member
1242
- * against — the strand cannot tell which invitations were meant for it, or whether
1243
- * it holds any. Binding an invitation to its invitee is tracked as
1244
- * `feat-strand-invitee-bound-invites`.
1245
- *
1246
- * A manager must resign its `Manager` row before (or in the same transaction
1247
- * as) losing membership — `Member.NotAManager` rejects un-membering a key that
1248
- * still holds a Manager row. And the strand never drops to zero members
1249
- * (`Member.MinOneMember`, a local-count floor with the cross-node caveat its
1250
- * schema NOTE states).
1251
- *
1252
- * Inside a cadre runtime the removed party's machines are then refused at the
1253
- * network layer by the strand's revoked-peer gate (`strand-revocation-enforcer.ts`),
1254
- * which re-reads membership when this write commits on the runtime's own
1255
- * `Database`. A caller that wants to await the cut follows the write with
1256
- * `CadreNode.refreshRevocationEnforcement(strandId)`, which resolves after it.
1257
- *
1258
- * @param db - The closed strand's database.
1259
- * @param params - The revoking manager keypair and the target member key.
1260
- * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1261
- * @throws If `Member.Authorized` rejects (a non-manager or same-transaction
1262
- * signer), `Member.NotAManager` rejects (the target still holds a Manager
1263
- * row), or `Member.MinOneMember` rejects (the removal would empty the member
1264
- * set); the whole delete+tombstone transaction rolls back.
1265
- */
1266
- export async function revokeMember(
1267
- db: Database,
1268
- params: RevokeMemberParams,
1269
- options?: StrandWriteOptions,
1270
- ): Promise<void> {
1271
- const { managerKeyPair, memberKey } = params;
1272
- const stampId = await memberStampId(db, memberKey);
1273
- if (stampId == null) {
1274
- log('Member %s already absent; skipping revoke', memberKey);
1275
- return;
1276
- }
1277
- const removal: StrandStatements = {
1278
- sql: `delete from Strand.Member
1279
- with context ManagerKey = :memberRemoverKey, ManagerSignature = :memberRemoverSignature, MemberSignature = null
1280
- where Key = :memberKey;`,
1281
- params: {
1282
- memberRemoverKey: managerKeyPair.publicKeyB64,
1283
- memberRemoverSignature: signStrandApproval(['Strand.Member', 'remove', memberKey, stampId], managerKeyPair.privateKeyB64),
1284
- memberKey,
1285
- },
1286
- };
1287
- await execStrandTransaction(
1288
- db,
1289
- combineStatements(removal, revocationStatement('Member', stampId, managerKeyPair)),
1290
- options,
1291
- );
1292
- log('Revoked member %s by manager %s', memberKey, managerKeyPair.publicKeyB64);
1293
- }
1294
-
1295
- /** Parameters for {@link leaveStrand}. */
1296
- export interface LeaveStrandParams {
1297
- /**
1298
- * The departing member's OWN strand keypair. Its `publicKeyB64` is the
1299
- * `Member.Key` row being deleted; it self-signs the leave-tagged digest —
1300
- * the self-departure branch verifies the signature against `old.Key` itself,
1301
- * so only the departing key's holder can produce it — and files the
1302
- * accompanying tombstone (it is still a committed member until this very
1303
- * transaction removes it, which is what `Revocation.Authorized` checks). No
1304
- * manager is involved.
1305
- */
1306
- memberKeyPair: Ed25519KeyPair;
1307
- }
1308
-
1309
- /**
1310
- * A member leaves the strand by deleting its own `Member` row.
1311
- *
1312
- * The self-departure branch of `Member.Authorized` verifies
1313
- * `digest('Strand.Member', 'leave', old.Key, old.StampId)` against `old.Key`
1314
- * itself via `context.MemberSignature`. The `'leave'` tag (vs the manager
1315
- * branch's `'remove'`) is belt-and-braces only — the two branches verify against
1316
- * different keys; the anti-replay fix is the stamp binding. Like
1317
- * {@link revokeMember}, the live stamp is read first (absent row → quiet no-op)
1318
- * and the delete pairs with its `Strand.Revocation` tombstone in one transaction.
1319
- *
1320
- * The same floors as {@link revokeMember} apply: a manager must resign first
1321
- * (`NotAManager`) and the last member cannot leave (`MinOneMember`).
1322
- *
1323
- * Like {@link revokeMember}, inside a cadre runtime the write wakes the strand's
1324
- * revoked-peer gate, which emits `strand:revoked` when it finds this node's own
1325
- * peer id revoked; `CadreNode.refreshRevocationEnforcement(strandId)` awaits that
1326
- * refresh.
1327
- *
1328
- * @param db - The closed strand's database.
1329
- * @param params - The departing member's own keypair.
1330
- * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1331
- * @throws If `Member.Authorized`, `Member.NotAManager`, or `Member.MinOneMember`
1332
- * rejects; the whole delete+tombstone transaction rolls back.
1333
- */
1334
- export async function leaveStrand(
1335
- db: Database,
1336
- params: LeaveStrandParams,
1337
- options?: StrandWriteOptions,
1338
- ): Promise<void> {
1339
- const { memberKeyPair } = params;
1340
- const memberKey = memberKeyPair.publicKeyB64;
1341
- const stampId = await memberStampId(db, memberKey);
1342
- if (stampId == null) {
1343
- log('Member %s already absent; skipping leave', memberKey);
1344
- return;
1345
- }
1346
- const departure: StrandStatements = {
1347
- sql: `delete from Strand.Member
1348
- with context ManagerKey = null, ManagerSignature = null, MemberSignature = :memberSignature
1349
- where Key = :memberKey;`,
1350
- params: {
1351
- memberSignature: signStrandApproval(['Strand.Member', 'leave', memberKey, stampId], memberKeyPair.privateKeyB64),
1352
- memberKey,
1353
- },
1354
- };
1355
- await execStrandTransaction(
1356
- db,
1357
- combineStatements(departure, revocationStatement('Member', stampId, memberKeyPair)),
1358
- options,
1359
- );
1360
- log('Member %s left the strand', memberKey);
1361
- }
1362
-
1363
- // ── MemberPeer registration (a member binds its own network nodes) ─────────────
1364
-
1365
- /** Parameters for {@link registerMemberPeer}. */
1366
- export interface RegisterMemberPeerParams {
1367
- /**
1368
- * The member's OWN strand keypair (`{ privateKeyB64, publicKeyB64 }`). Its
1369
- * `publicKeyB64` becomes `MemberPeer.MemberKey` and it self-signs the binding —
1370
- * `MemberPeer.Authorized` verifies the signature against `MemberKey` itself, so a
1371
- * peer can only be registered by the very member it belongs to (no manager
1372
- * involved). The founder passes its `strandMemberKeyPair`; an invited member
1373
- * passes its own keypair. Typed as {@link Ed25519KeyPair} only for the shared
1374
- * base64url keypair shape — no manager privilege is implied.
1375
- */
1376
- memberKeyPair: Ed25519KeyPair;
1377
- /** The peer/node id (libp2p peer id string) to associate with the member. */
1378
- peerId: string;
1379
- }
1380
-
1381
- /**
1382
- * Register a network node (`PeerId`) as acting on behalf of a member.
1383
- *
1384
- * The member self-signs the add-tagged digest
1385
- * `digest('Strand.MemberPeer', 'add', new.MemberKey, new.PeerId, new.StampId)`
1386
- * with its OWN key; the schema's `MemberPeer.Authorized` verifies that signature
1387
- * against `new.MemberKey` — i.e. the member key itself — so only the member that
1388
- * owns the key can register peers for it. The stamp is minted fresh here and
1389
- * bound inside the digest, so a captured registration approval neither
1390
- * re-registers a cleared binding (its stamp is retired) nor authorizes a removal
1391
- * (wrong tag). A deferred `MemberExists` additionally requires the `Member` row
1392
- * to already exist, so a peer for a non-member is rejected at commit.
1393
- *
1394
- * Insert-if-absent: a re-register on restart (or a redundant call) is a no-op. The
1395
- * platform DOES reject a duplicate-PK insert, but a restart-safe re-register should
1396
- * succeed quietly rather than throw, so the writer guards on existence instead of
1397
- * catching. The guard ({@link memberPeerStampId}) scans the member's peers and compares
1398
- * both key columns in JavaScript rather than seeking the composite primary key — see
1399
- * {@link scanMemberPeers} for why a full-PK point lookup is not reliable on a networked
1400
- * strand. A member may register multiple DISTINCT `PeerId`s (multi-device); each is its
1401
- * own row (and its own stamp) under the same `MemberKey`.
1402
- *
1403
- * Peer DELETION is signature-checked too, not rejected outright: `Authorized` carries
1404
- * distinct delete branches (self + manager), each over its own action-tagged digest
1405
- * bound to the row's stamp. Both removal paths live in {@link removeMemberPeer}.
1406
- * UPDATE is refused outright by `NoUpdate`: a re-binding is a remove plus a fresh
1407
- * register (under a fresh stamp).
1408
- *
1409
- * @param db - The closed strand's database (the member already exists).
1410
- * @param params - The member's own keypair and the peer id to bind.
1411
- * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1412
- * @throws If `MemberPeer.Authorized`/`MemberExists` rejects (wrong signer, or no
1413
- * matching `Member` row); the insert rolls back, leaving no `MemberPeer` row.
1414
- * @throws {StrandTransactionBusyError} Under `joinOpenTransaction: false`, when another
1415
- * transaction is open; nothing was written.
1416
- */
1417
- export async function registerMemberPeer(
1418
- db: Database,
1419
- params: RegisterMemberPeerParams,
1420
- options?: StrandWriteOptions,
1421
- ): Promise<void> {
1422
- const { memberKeyPair, peerId } = params;
1423
- const memberKey = memberKeyPair.publicKeyB64;
1424
-
1425
- if (await memberPeerStampId(db, memberKey, peerId) != null) {
1426
- log('MemberPeer (%s, %s) already present; skipping', memberKey, peerId);
1427
- return;
1428
- }
1429
-
1430
- await execStrandTransaction(db, memberPeerInsertStatement(memberKeyPair, peerId), options);
1431
- log('Registered MemberPeer (%s, %s)', memberKey, peerId);
1432
- }
1433
-
1434
- /**
1435
- * The self-signed `Strand.MemberPeer` insert binding `peerId` to the member, under a fresh
1436
- * stamp bound into the add-tagged digest (see {@link registerMemberPeer}).
1437
- */
1438
- function memberPeerInsertStatement(memberKeyPair: Ed25519KeyPair, peerId: string): StrandStatements {
1439
- const memberKey = memberKeyPair.publicKeyB64;
1440
- const stampId = generateStrandStampId();
1441
- return {
1442
- sql: `insert into Strand.MemberPeer (MemberKey, PeerId, StampId)
1443
- with context Signature = :peerSignature, ManagerKey = null, ManagerSignature = null
1444
- values (:peerMemberKey, :peerId, :peerStampId);`,
1445
- params: {
1446
- peerSignature: signStrandApproval(['Strand.MemberPeer', 'add', memberKey, peerId, stampId], memberKeyPair.privateKeyB64),
1447
- peerMemberKey: memberKey,
1448
- peerId,
1449
- peerStampId: stampId,
1450
- },
1451
- };
1452
- }
1453
-
1454
- /**
1455
- * Yield every `(PeerId, StampId)` bound to `memberKey`, re-comparing the member key
1456
- * in JavaScript.
1457
- *
1458
- * Deliberately does NOT filter on the full composite primary key. `MemberPeer`'s PK
1459
- * is `(MemberKey, PeerId)`, so a `where MemberKey = ? and PeerId = ?` predicate puts
1460
- * an equality on BOTH key columns — which the optimystic virtual-table module reports
1461
- * as fully handled and serves via a single-key point lookup (one `find` descent), with
1462
- * the SQL engine adding no filter of its own. On a networked strand that descent is not
1463
- * reliable: a miss returns zero rows for a row that provably exists.
1464
- *
1465
- * Filtering on only the LEADING key column is a partial PK match, which the same module
1466
- * explicitly declines to handle — it falls through to a table scan and the SQL engine
1467
- * applies `MemberKey = ?` itself. No seek is involved, so no seek can miss. The member key
1468
- * is then re-compared here in JavaScript, so correctness depends only on the scan returning
1469
- * a SUPERSET of the matching rows — the weakest possible assumption about the storage layer.
1470
- * The `where` clause only trims what crosses into JS — it is NOT pushed down (see the cost
1471
- * note below) — so it is not a correctness dependency: a dropped or mis-applied predicate
1472
- * cannot produce a row attributed to the wrong member.
1473
- */
1474
- async function* scanMemberPeers(db: Database, memberKey: string): AsyncGenerator<{ peerId: string; stampId: string }> {
1475
- // NOTE: because the predicate is not pushed down, the storage layer walks the WHOLE
1476
- // MemberPeer table (every member's rows) per call and the SQL engine filters. Fine at
1477
- // strand scale; if MemberPeer ever grows large, the fix is a reliable composite-key
1478
- // seek, not a bigger scan.
1479
- // NOTE: if a secondary index on MemberPeer.MemberKey is ever added, this query stops
1480
- // being a scan and becomes an index seek — re-introducing the seek dependency this
1481
- // shape exists to remove.
1482
- for await (const row of db.eval(
1483
- 'select MemberKey, PeerId, StampId from Strand.MemberPeer where MemberKey = ?',
1484
- [memberKey],
1485
- )) {
1486
- if (row.MemberKey === memberKey) {
1487
- yield { peerId: row.PeerId as string, stampId: row.StampId as string };
1488
- }
1489
- }
1490
- }
1491
-
1492
- /**
1493
- * Every `PeerId` currently bound to `memberKey`, in storage order.
1494
- *
1495
- * The enumeration side of {@link removeMemberPeer}: a manager cleaning up after a
1496
- * revocation knows only the departed member's key, never which devices it registered, so
1497
- * cleanup is `listMemberPeers` then one `removeMemberPeer` per id. Reads only — the rows
1498
- * it returns may name a `MemberKey` with no `Member` row (see the `MemberPeer` table NOTE
1499
- * in the schema), so this is NOT a membership test.
1500
- *
1501
- * @param db - The closed strand's database.
1502
- * @param memberKey - The `MemberPeer.MemberKey` to enumerate.
1503
- * @returns The bound peer ids, empty if the member has none.
1504
- */
1505
- export async function listMemberPeers(db: Database, memberKey: string): Promise<string[]> {
1506
- const peerIds: string[] = [];
1507
- for await (const peer of scanMemberPeers(db, memberKey)) {
1508
- peerIds.push(peer.peerId);
1509
- }
1510
- return peerIds;
1511
- }
1512
-
1513
- /**
1514
- * The live StampId of the `MemberPeer` row for this `(MemberKey, PeerId)`, or
1515
- * `undefined` if no such row is visible — doubling as the existence probe.
1516
- *
1517
- * NOTE: check-then-write is not atomic. Two nodes registering the same
1518
- * (MemberKey, PeerId) concurrently can both observe "absent"; the primary key is the
1519
- * real backstop. The existence half of this guard is for the sequential restart /
1520
- * re-register path.
1521
- */
1522
- async function memberPeerStampId(db: Database, memberKey: string, peerId: string): Promise<string | undefined> {
1523
- for await (const peer of scanMemberPeers(db, memberKey)) {
1524
- if (peer.peerId === peerId) {
1525
- return peer.stampId;
1526
- }
1527
- }
1528
- return undefined;
1529
- }
1530
-
1531
- /** Parameters for the SELF branch of {@link removeMemberPeer}. */
1532
- export interface RemoveOwnPeerParams {
1533
- /**
1534
- * The member's OWN strand keypair. Its `publicKeyB64` is the `MemberPeer.MemberKey`
1535
- * of the row being deleted, and it signs the remove-tagged digest
1536
- * `digest('Strand.MemberPeer', 'remove', MemberKey, PeerId, StampId)` — the self
1537
- * branch of `MemberPeer.Authorized` verifies against the row's own member key, so
1538
- * no OTHER member's row is reachable this way, and the tag + stamp binding keep a
1539
- * captured registration approval from doubling as a removal (and vice versa).
1540
- */
1541
- memberKeyPair: Ed25519KeyPair;
1542
- /** The `PeerId` of the binding to delete. */
1543
- peerId: string;
1544
- }
1545
-
1546
- /** Parameters for the MANAGER branch of {@link removeMemberPeer}. */
1547
- export interface RemoveMemberPeerByManagerParams {
1548
- /**
1549
- * The clearing manager's strand keypair. Its `publicKeyB64` must be a PRE-EXISTING
1550
- * `Strand.Manager` row (the manager branch reads `committed.Manager`, so a manager
1551
- * seated in the same transaction cannot authorize); it signs the
1552
- * manager-remove-tagged digest over the exact row and its live stamp, and files
1553
- * the accompanying tombstone.
1554
- */
1555
- managerKeyPair: Ed25519KeyPair;
1556
- /** The `MemberPeer.MemberKey` whose binding is being cleared. */
1557
- memberKey: string;
1558
- /** The `PeerId` of the binding to delete. */
1559
- peerId: string;
1560
- }
1561
-
1562
- /**
1563
- * Either shape accepted by {@link removeMemberPeer}. A discriminated union rather than
1564
- * one opaque keypair: the two branches sign DIFFERENT action tags (`'remove'` self vs
1565
- * `'manager-remove'`), so each case carries exactly the fields its payload needs.
1566
- */
1567
- export type RemoveMemberPeerParams = RemoveOwnPeerParams | RemoveMemberPeerByManagerParams;
1568
-
1569
- /**
1570
- * Delete a `MemberPeer` binding — either the member clearing its own, or a manager
1571
- * clearing another member's.
1572
- *
1573
- * Reads the row's live StampId first (absent → quiet no-op, mirroring
1574
- * {@link registerMemberPeer}'s insert-if-absent, so a repeated or restarted cleanup
1575
- * is not a silent zero-row "success" the caller cannot distinguish from a real one),
1576
- * then runs ONE transaction pairing the delete with its `Strand.Revocation`
1577
- * tombstone — `MemberPeer.RevocationRecorded` requires it, and the retirement is
1578
- * what keeps the captured registration approval from re-binding the cleared row.
1579
- *
1580
- * `MemberPeer` rows do NOT cascade when the member is revoked (`MemberExists` runs on
1581
- * insert only, and nothing deletes them), so a removed member's peer bindings survive
1582
- * as orphans — enumerate them with {@link listMemberPeers}, which is how a manager
1583
- * discovers what to clear. Only that member can sign the self branch, and a member being
1584
- * removed against its will has no reason to cooperate — hence the manager branch, which
1585
- * is the cleanup path after a revocation.
1586
- *
1587
- * The manager branch is deliberately NOT gated on the member already being gone: a
1588
- * manager may clear a still-present member's binding too, matching "any manager can
1589
- * remove any member". It verifies the manager-remove-tagged
1590
- * `digest('Strand.MemberPeer', 'manager-remove', old.MemberKey, old.PeerId, old.StampId)`
1591
- * against a `committed.Manager` row; the self branch verifies the remove-tagged
1592
- * sibling against the row's own member key.
1593
- *
1594
- * Cleanup is an explicit follow-up call by the revoking manager, never a cascade inside
1595
- * {@link revokeMember}: a revocation that also had to clear an unbounded number of peer
1596
- * rows in the same transaction would couple two concerns and make its failure modes
1597
- * harder to reason about.
1598
- *
1599
- * @param db - The closed strand's database.
1600
- * @param params - Either the owning member's keypair, or a manager's keypair plus the
1601
- * target member key.
1602
- * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1603
- * @throws If `MemberPeer.Authorized` rejects (neither branch satisfied), or if the row
1604
- * is still present after the delete (see the point-lookup note below).
1605
- * @throws {StrandTransactionBusyError} Under `joinOpenTransaction: false`, when another
1606
- * transaction is open; nothing was written.
1607
- */
1608
- export async function removeMemberPeer(
1609
- db: Database,
1610
- params: RemoveMemberPeerParams,
1611
- options?: StrandWriteOptions,
1612
- ): Promise<void> {
1613
- const memberKey = 'memberKeyPair' in params ? params.memberKeyPair.publicKeyB64 : params.memberKey;
1614
- const { peerId } = params;
1615
-
1616
- const stampId = await memberPeerStampId(db, memberKey, peerId);
1617
- if (stampId == null) {
1618
- log('MemberPeer (%s, %s) already absent; skipping', memberKey, peerId);
1619
- return;
1620
- }
1621
-
1622
- const removal = 'memberKeyPair' in params
1623
- ? ownMemberPeerRemovalStatements(params, stampId)
1624
- : memberPeerRemovalByManagerStatements(params, stampId);
1625
- await execStrandTransaction(db, removal, options);
1626
-
1627
- // NOTE: the delete's `where` puts an equality on BOTH composite-PK columns, which the
1628
- // optimystic vtab module serves via a single-key seek that can MISS on a networked
1629
- // strand (see scanMemberPeers' doc). A missed seek deletes zero rows and still
1630
- // reports success. `Revocation.RowIsGone` now catches that first — the tombstone filed
1631
- // in the same transaction refuses to retire a stamp whose row is still visible, so the
1632
- // commit above fails loudly and this re-check is belt-and-braces behind it. Tracked as
1633
- // `debt-composite-pk-point-lookup-unreliable-untracked`; this is an availability
1634
- // failure mode, never a security one (a miss removes nothing, it never over-removes).
1635
- if (await memberPeerStampId(db, memberKey, peerId) != null) {
1636
- throw new Error(`MemberPeer (${memberKey}, ${peerId}) still present after delete`);
1637
- }
1638
- log('Removed MemberPeer (%s, %s)', memberKey, peerId);
1639
- }
1640
-
1641
- /** The self branch: the owning member signs the remove-tagged digest + tombstone. */
1642
- function ownMemberPeerRemovalStatements(params: RemoveOwnPeerParams, stampId: string): StrandStatements {
1643
- const { memberKeyPair, peerId } = params;
1644
- const memberKey = memberKeyPair.publicKeyB64;
1645
- const removal: StrandStatements = {
1646
- sql: `delete from Strand.MemberPeer
1647
- with context Signature = :peerSignature, ManagerKey = null, ManagerSignature = null
1648
- where MemberKey = :peerMemberKey and PeerId = :peerId;`,
1649
- params: {
1650
- peerSignature: signStrandApproval(['Strand.MemberPeer', 'remove', memberKey, peerId, stampId], memberKeyPair.privateKeyB64),
1651
- peerMemberKey: memberKey,
1652
- peerId,
1653
- },
1654
- };
1655
- return combineStatements(removal, revocationStatement('MemberPeer', stampId, memberKeyPair));
1656
- }
1657
-
1658
- /**
1659
- * The manager branch: a manager signs the manager-remove-tagged digest + tombstone.
1660
- *
1661
- * NOTE: clearing an ORPHANED binding (one whose member was already removed) also
1662
- * forgets the NETWORK DENIAL of that peer id. The orphaned `MemberPeer` row IS
1663
- * the record the strand revoked-peer gate derives its deny set from
1664
- * (`strand-revocation-enforcer.ts`) — the `Strand.Revocation` tombstone keeps
1665
- * only the stamp, not the peer id — so once the orphan is cleared, remaining
1666
- * members' nodes resume answering and dialing that peer. Only clear a binding
1667
- * that should never have existed, or a peer that is truly gone.
1668
- */
1669
- function memberPeerRemovalByManagerStatements(
1670
- params: RemoveMemberPeerByManagerParams,
1671
- stampId: string,
1672
- ): StrandStatements {
1673
- const { managerKeyPair, memberKey, peerId } = params;
1674
- const removal: StrandStatements = {
1675
- sql: `delete from Strand.MemberPeer
1676
- with context Signature = null, ManagerKey = :peerManagerKey, ManagerSignature = :peerManagerSignature
1677
- where MemberKey = :peerMemberKey and PeerId = :peerId;`,
1678
- params: {
1679
- peerManagerKey: managerKeyPair.publicKeyB64,
1680
- peerManagerSignature: signStrandApproval(
1681
- ['Strand.MemberPeer', 'manager-remove', memberKey, peerId, stampId],
1682
- managerKeyPair.privateKeyB64,
1683
- ),
1684
- peerMemberKey: memberKey,
1685
- peerId,
1686
- },
1687
- };
1688
- return combineStatements(removal, revocationStatement('MemberPeer', stampId, managerKeyPair));
1689
- }
1690
-
1691
- // ── Manager rotation (add / remove RBAC admins) ───────────────────────────────
1692
-
1693
- /**
1694
- * The live `(Generation, StampId)` of the `Strand.Manager` row keyed by
1695
- * `memberKey`, or `undefined` if no such row is visible.
1696
- *
1697
- * `Manager`'s primary key is the single `MemberKey` column, so any where-equality
1698
- * on it is a full-PK point lookup — unreliable on a networked strand (see
1699
- * {@link scanMemberPeers}). An unfiltered scan + JavaScript filter instead, same
1700
- * as {@link memberStampId}. Serves both {@link addManager} (the authorizer's
1701
- * generation) and {@link removeManager} (the target's stamp).
1702
- */
1703
- async function managerRow(db: Database, memberKey: string): Promise<{ generation: number; stampId: string } | undefined> {
1704
- for await (const row of db.eval('select MemberKey, Generation, StampId from Strand.Manager')) {
1705
- if (row.MemberKey === memberKey) {
1706
- return { generation: Number(row.Generation), stampId: row.StampId as string };
1707
- }
1708
- }
1709
- return undefined;
1710
- }
1711
-
1712
- /** Parameters for {@link addManager}. */
1713
- export interface AddManagerParams {
1714
- /**
1715
- * An EXISTING manager's strand keypair. Its `publicKeyB64` must already be a
1716
- * `Strand.Manager` row (the existing-manager branch of `Manager.Authorized`
1717
- * rejects a non-manager once the founder manager exists); it signs the
1718
- * add-tagged digest over the new manager key, generation, and fresh stamp,
1719
- * and is bound as `context.ManagerKey`.
1720
- */
1721
- byManagerKeyPair: Ed25519KeyPair;
1722
- /** The member key to promote — the new `Manager.MemberKey` row. */
1723
- newManagerKey: string;
1724
- }
1725
-
1726
- /**
1727
- * Promote a key that is ALREADY a `Strand.Member` to `Manager` on the signature of
1728
- * an existing manager — use {@link admitManager} to admit and promote atomically.
1729
- *
1730
- * The promotion branch of `Manager.Authorized` requires the authorizer to be a
1731
- * `Manager` row of STRICTLY SMALLER `Generation` than the new row, verifying
1732
- * `digest('Strand.Manager', 'add', new.MemberKey, new.Generation, new.StampId)`
1733
- * against `context.ManagerKey`. So this writer reads the authorizer's generation,
1734
- * seats the new manager at that value + 1 (the natural successor; the schema
1735
- * enforces only the strict ordering), mints a fresh stamp, and signs the
1736
- * add-tagged digest over all three: the generation inside the signed digest keeps
1737
- * a captured promotion from replaying at a different generation, and the stamp
1738
- * keeps it from re-seating a second incarnation once this one is removed.
1739
- * `new.Generation` is an SQL INTEGER digest arg — the digest framing is
1740
- * type-tagged, so the TS side signs over the NUMBER itself
1741
- * (see {@link signStrandApproval}).
1742
- *
1743
- * The strict ordering — not this writer — is what makes a same-transaction takeover
1744
- * impossible; the `Manager.Generation` column comment in `schemas/strand.qsql` carries
1745
- * that argument. All this writer owes it is a generation strictly above the
1746
- * authorizer's, inside the signed payload.
1747
- *
1748
- * When the authorizer has NO `Manager` row (a non-manager signer, or an open
1749
- * strand with no managers at all), the scan finds nothing and the writer falls
1750
- * back to generation 1 and issues the insert anyway — deliberately letting the
1751
- * SCHEMA be the rejector (`Manager.Authorized` / `OnlyClosed`), not a
1752
- * writer-thrown error, so enforcement is pinned where it actually lives.
1753
- *
1754
- * @param db - The closed strand's database (founder manager already seated).
1755
- * @param params - The authorizing manager's keypair and the new manager key.
1756
- * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1757
- * @throws If `Manager.Authorized` rejects, or if `Manager.MemberExists` rejects because
1758
- * `newManagerKey` holds no `Member` row (admit it first, or use
1759
- * {@link admitManager}); the insert rolls back.
1760
- */
1761
- export async function addManager(
1762
- db: Database,
1763
- params: AddManagerParams,
1764
- options?: StrandWriteOptions,
1765
- ): Promise<void> {
1766
- const { byManagerKeyPair, newManagerKey } = params;
1767
- const promotion = await managerAddStatement(db, params);
1768
- await execStrandTransaction(db, promotion, options);
1769
- log('Added manager %s (generation %d) by %s', newManagerKey, promotion.params.managerGeneration,
1770
- byManagerKeyPair.publicKeyB64);
1771
- }
1772
-
1773
- /**
1774
- * The `Strand.Manager` insert behind {@link addManager}: reads the authorizer's generation,
1775
- * seats the new manager one above it under a fresh stamp, and signs all three.
1776
- */
1777
- async function managerAddStatement(db: Database, params: AddManagerParams): Promise<StrandStatements> {
1778
- const { byManagerKeyPair, newManagerKey } = params;
1779
- const authorizer = await managerRow(db, byManagerKeyPair.publicKeyB64);
1780
- // NOTE: +1 saturates at Number.MAX_SAFE_INTEGER, where the successor compares equal
1781
- // to its authorizer and the schema rejects. Unreachable while generations only ever
1782
- // grow by 1 from 0, but the schema enforces ordering, not adjacency, so a manager may
1783
- // seat a successor at any larger value; if arbitrary generations ever become writable
1784
- // from outside this function, clamp or reject here rather than emitting a dead row.
1785
- const generation = authorizer == null ? 1 : authorizer.generation + 1;
1786
- const stampId = generateStrandStampId();
1787
- return {
1788
- sql: `insert into Strand.Manager (MemberKey, Generation, StampId)
1789
- with context ManagerKey = :managerAuthorizerKey, Signature = :managerSignature
1790
- values (:managerMemberKey, :managerGeneration, :managerStampId);`,
1791
- params: {
1792
- managerAuthorizerKey: byManagerKeyPair.publicKeyB64,
1793
- managerSignature: signStrandApproval(
1794
- ['Strand.Manager', 'add', newManagerKey, generation, stampId],
1795
- byManagerKeyPair.privateKeyB64,
1796
- ),
1797
- managerMemberKey: newManagerKey,
1798
- managerGeneration: generation,
1799
- managerStampId: stampId,
1800
- },
1801
- };
1802
- }
1803
-
1804
- /** Parameters for {@link admitManager} — the same shape as {@link AddManagerParams}. */
1805
- export type AdmitManagerParams = AddManagerParams;
1806
-
1807
- /**
1808
- * Admit a key as a `Member` AND promote it to `Manager`, atomically — the one-step
1809
- * pair for a key that is not in the strand yet. {@link addManager} alone promotes a
1810
- * key that is already a member.
1811
- *
1812
- * ONE transaction, because `Manager.MemberExists` is a deferred check reading the LIVE
1813
- * `Member` table: the sibling `Member` insert satisfies it at the shared commit, and a
1814
- * rejection of either half rolls BOTH rows back — never a `Member` row seated by a
1815
- * failed promotion, nor a `Manager` row with no member behind it.
1816
- *
1817
- * NO new authority: both halves are signed by the SAME manager, over two distinct
1818
- * action-tagged digests — `digest('Strand.Member', 'add', …)` for the admission and
1819
- * `digest('Strand.Manager', 'add', …)` for the promotion — each bound to its own row's
1820
- * fresh stamp. This composes exactly the two approvals that manager could already
1821
- * issue separately.
1822
- *
1823
- * The promoting manager must be a PRE-transaction manager: the direct-admit branch of
1824
- * `Member.Authorized` reads `committed.Manager`, so `admitManager` cannot be chained —
1825
- * a manager seated by an `admitManager` earlier in the SAME transaction cannot admit
1826
- * the next one. (A same-transaction promotion CHAIN rooted at a pre-existing manager
1827
- * is fine; only the `Member` half needs the committed authorizer.)
1828
- *
1829
- * NOT insert-if-absent: a repeat call for a key that is already a member fails on the
1830
- * `Member` primary key, matching {@link addMemberByManager}'s unguarded shape.
1831
- *
1832
- * @param db - The closed strand's database (founder manager already seated).
1833
- * @param params - The authorizing manager's keypair and the key to admit + promote.
1834
- * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1835
- * @throws If either half is rejected (`Member.Authorized`, `Manager.Authorized`, a
1836
- * duplicate `Member` key, …); the whole transaction rolls back, leaving neither row.
1837
- */
1838
- export async function admitManager(
1839
- db: Database,
1840
- params: AdmitManagerParams,
1841
- options?: StrandWriteOptions,
1842
- ): Promise<void> {
1843
- const { byManagerKeyPair, newManagerKey } = params;
1844
- const admission = memberAddByManagerStatement({ managerKeyPair: byManagerKeyPair, memberKey: newManagerKey });
1845
- const promotion = await managerAddStatement(db, params);
1846
- await execStrandTransaction(db, combineStatements(admission, promotion), options);
1847
- log('Admitted + promoted manager %s by %s', newManagerKey, byManagerKeyPair.publicKeyB64);
1848
- }
1849
-
1850
- /** Parameters for {@link removeManager}. */
1851
- export interface RemoveManagerParams {
1852
- /**
1853
- * The keypair authorizing the removal, bound as `context.ManagerKey`. For an
1854
- * ADMIN removal this is a DIFFERENT existing manager, signing the
1855
- * remove-tagged digest (satisfying the existing-manager branch); for a
1856
- * SELF-resignation it is the target's OWN keypair (`publicKeyB64 ===
1857
- * targetManagerKey`), signing the resign-tagged digest (satisfying the
1858
- * former-manager self branch). The writer picks the tag by comparing the keys —
1859
- * see {@link removeManager}. Either way this keypair also files the
1860
- * accompanying tombstone, which requires it to be a PRE-transaction MEMBER
1861
- * (`Revocation.Authorized` reads `committed.Member`) — true for every manager,
1862
- * since managers are members.
1863
- */
1864
- byManagerKeyPair: Ed25519KeyPair;
1865
- /** The `Manager.MemberKey` row to delete. */
1866
- targetManagerKey: string;
1867
- }
1868
-
1869
- /**
1870
- * Remove a `Manager` row — either an admin removing a different manager or a
1871
- * manager resigning itself.
1872
- *
1873
- * Reads the target row's live `(Generation, StampId)` first (absent → quiet
1874
- * no-op, same restart-safe shape as {@link revokeMember}), then runs ONE
1875
- * transaction pairing the delete with its `Strand.Revocation` tombstone
1876
- * (`Manager.RevocationRecorded`). The two delete-side branches of
1877
- * `Manager.Authorized` verify DIFFERENT action-tagged digests, each bound to
1878
- * `(old.MemberKey, old.StampId)`:
1879
- * - **Admin removal** (`byManagerKeyPair` is a different existing manager): the
1880
- * removal branch verifies `digest('Strand.Manager', 'remove', old.MemberKey,
1881
- * old.StampId)` against `A.MemberKey = context.ManagerKey`. Deliberately NO
1882
- * generation condition: a later-generation manager may remove an
1883
- * earlier-generation one (generation is lineage, not privilege), and deletes
1884
- * are safe once inserts are — every accepting branch requires a `Manager` row
1885
- * in the post-image, and the promotion branch's generation ordering keeps
1886
- * attacker rows out of it. The stamp binding is what makes a captured removal
1887
- * single-use: a re-promoted manager carries a fresh stamp the old approval
1888
- * does not match — closing the removal half of
1889
- * `bug-strand-manager-authority-antireplay` (the insert half was already
1890
- * closed by the generation-bearing promotion payload).
1891
- * - **Self-resignation** (`byManagerKeyPair` IS the target): the former-manager
1892
- * self branch verifies `digest('Strand.Manager', 'resign', old.MemberKey,
1893
- * old.StampId)` against `old.MemberKey` itself. The distinct `'resign'` tag is
1894
- * belt-and-braces (different verifying keys); the anti-replay fix is the stamp.
1895
- *
1896
- * The caller selects the case purely by which keypair it passes; the only
1897
- * branching here is the action tag, chosen by comparing the signer to the target.
1898
- *
1899
- * Deferred (subquery-bearing) CHECK constraints are evaluated on DELETE as well
1900
- * as INSERT by Quereus plus the Optimystic vtab session — enforcement lives above
1901
- * the transactor (proven on the network transactor by
1902
- * `strand-membership-network-transactor-parity.spec.ts`), so `Manager.Authorized`
1903
- * — deferred — IS enforced here: a signer that is neither an existing manager nor
1904
- * the target itself is rejected at commit.
1905
- *
1906
- * THE SOLE MANAGER CANNOT ORDINARILY RESIGN — it SEALS instead. The `'resign'`
1907
- * branch of `Manager.Authorized` requires at least one manager in the POST-delete
1908
- * image, so a resignation that would empty the `Manager` table is schema-rejected;
1909
- * emptying it deliberately is a distinct, self-signed act — {@link sealStrand} —
1910
- * that permanently freezes admission. This writer refuses the sole-manager
1911
- * self-resignation up front with an error naming `sealStrand`; that TS guard is UX,
1912
- * not the trust boundary — the schema rejects a mis-counted `'resign'` approval
1913
- * regardless. Reading the count inside a caller-joined transaction is correct: an
1914
- * add-then-resign hand-off composed in one transaction sees 2 and passes, while
1915
- * the already-rejected delete-then-add swap sees 1 and is refused here as well as
1916
- * by the schema. The bootstrap branch of `Manager.Authorized` is gated to INSERTs
1917
- * (`old.MemberKey is null`), so it does not waive the signature check on a delete
1918
- * that drops the count toward zero: a second-to-last removal is authorized
1919
- * exactly like any other.
1920
- *
1921
- * HAND-OFF ORDER: a sole manager transferring control must ADD the successor FIRST
1922
- * and resign SECOND. A same-transaction delete-then-insert swap is rejected — the
1923
- * bootstrap branch is gated to the founding state (at most one `Member`), and the
1924
- * successor's insert has no other manager to authorize it once the sole manager's
1925
- * row is gone.
1926
- *
1927
- * Cross-node caveat: the `'resign'`/`'seal'` branches count rows visible to THIS
1928
- * transaction, so two nodes concurrently removing different managers can each see
1929
- * a survivor and still converge to zero — an unintended seal. Noted in the schema
1930
- * (the `Manager` table's seal-propagation NOTE); a cross-node floor is not
1931
- * attempted here.
1932
- *
1933
- * @param db - The closed strand's database.
1934
- * @param params - The authorizing keypair and the target manager key.
1935
- * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1936
- * @throws If the signer IS the target and it is the sole manager (before writing —
1937
- * the operation the caller wants is {@link sealStrand}), or if `Manager.Authorized`
1938
- * rejects (a signer that is neither another existing manager nor the target
1939
- * itself, or a raw sole-manager `'resign'` whose post-image count is zero); the
1940
- * whole delete+tombstone transaction rolls back.
1941
- */
1942
- export async function removeManager(
1943
- db: Database,
1944
- params: RemoveManagerParams,
1945
- options?: StrandWriteOptions,
1946
- ): Promise<void> {
1947
- const { byManagerKeyPair, targetManagerKey } = params;
1948
- const target = await managerRow(db, targetManagerKey);
1949
- if (target == null) {
1950
- log('Manager %s already absent; skipping removal', targetManagerKey);
1951
- return;
1952
- }
1953
- const tag = byManagerKeyPair.publicKeyB64 === targetManagerKey ? 'resign' : 'remove';
1954
- if (tag === 'resign' && await strandTableCount(db, 'Manager') === 1) {
1955
- throw new Error(
1956
- 'Cannot resign as the SOLE manager: an ordinary resignation never empties the '
1957
- + 'Manager table. To permanently freeze admission instead, call sealStrand.',
1958
- );
1959
- }
1960
- const signature = signStrandApproval(
1961
- ['Strand.Manager', tag, targetManagerKey, target.stampId],
1962
- byManagerKeyPair.privateKeyB64,
1963
- );
1964
- await execStrandTransaction(
1965
- db,
1966
- managerRemovalStatements(byManagerKeyPair, signature, targetManagerKey, target.stampId),
1967
- options,
1968
- );
1969
- log('Removed manager %s by %s', targetManagerKey, byManagerKeyPair.publicKeyB64);
1970
- }
1971
-
1972
- /**
1973
- * The `Strand.Manager` delete plus its tombstone, shared by {@link removeManager} and
1974
- * {@link sealStrand}, which differ only in the action tag `signature` was minted under.
1975
- */
1976
- function managerRemovalStatements(
1977
- signer: Ed25519KeyPair,
1978
- signature: string,
1979
- targetManagerKey: string,
1980
- targetStampId: string,
1981
- ): StrandStatements {
1982
- const removal: StrandStatements = {
1983
- sql: `delete from Strand.Manager
1984
- with context ManagerKey = :managerRemoverKey, Signature = :managerRemoverSignature
1985
- where MemberKey = :managerMemberKey;`,
1986
- params: {
1987
- managerRemoverKey: signer.publicKeyB64,
1988
- managerRemoverSignature: signature,
1989
- managerMemberKey: targetManagerKey,
1990
- },
1991
- };
1992
- return combineStatements(removal, revocationStatement('Manager', targetStampId, signer));
1993
- }
1994
-
1995
- // ── Sealing (the sole manager permanently freezes admission) ──────────────────
1996
-
1997
- /** Parameters for {@link sealStrand}. */
1998
- export interface SealStrandParams {
1999
- /**
2000
- * The SOLE manager's strand keypair. Its `publicKeyB64` must be the one live
2001
- * `Strand.Manager` row; it signs the seal-tagged digest over its own key and
2002
- * live stamp, and files the accompanying tombstone (it is still a committed
2003
- * member, which is what `Revocation.Authorized` checks).
2004
- */
2005
- managerKeyPair: Ed25519KeyPair;
2006
- }
2007
-
2008
- /**
2009
- * Seal the strand: the SOLE manager deliberately steps down, permanently freezing
2010
- * membership.
2011
- *
2012
- * A sealed strand has zero `Manager` rows, and every admission path — issuing or
2013
- * cancelling an invitation, consuming one issued BEFORE the seal
2014
- * (`ConsumedInvite.NotSealed`), admitting a member, promoting a manager — requires
2015
- * one, so nobody can ever be let in again. That freeze is a privacy guarantee to
2016
- * everyone who contributed: no key holds the power to admit a party who would then
2017
- * read the strand's whole history. Sealing is irreversible — the founding branch
2018
- * of `Manager.Authorized` closes for good once any manager stamp is retired into
2019
- * `Strand.Revocation`. What remains possible: members may {@link leaveStrand}
2020
- * (floored by `MinOneMember`), manage their own `MemberPeer` rows, and file
2021
- * `Revocation` tombstones.
2022
- *
2023
- * The `'seal'` branch of `Manager.Authorized` accepts a self-signed delete only
2024
- * when the POST-image manager count is ZERO — a distinct action tag from
2025
- * `'resign'`, so a captured resignation approval can never seal and a raw writer
2026
- * cannot seal by accident. Like {@link removeManager}, the delete pairs with its
2027
- * `Strand.Revocation` tombstone in one transaction.
2028
- *
2029
- * The TS count/identity checks below are UX guards, not the trust boundary — the
2030
- * schema rejects a mis-tagged or mis-counted approval regardless of what this
2031
- * writer (or any raw writer) presents.
2032
- *
2033
- * NOTE: a seal approval is a bearer token for its row incarnation, like every other
2034
- * self-signed approval here — but the `'seal'` branch's post-image count of 0 is
2035
- * satisfied for EVERY row deleted in the same transaction, so N managers each
2036
- * presenting a valid `'seal'` approval seal jointly (pinned as an accepted case in
2037
- * `strand-seal.spec.ts`). Unreachable today: this writer mints a seal signature only
2038
- * while its caller is the SOLE manager, and spends it immediately, so a second
2039
- * manager never has one to combine. If seal-approval MINTING is ever split from
2040
- * spending — offline signing, a two-phase seal, a queued approval — one manager
2041
- * holding another's unspent seal approval could freeze the strand irreversibly
2042
- * without its current consent; re-gate here (or narrow the schema branch) then.
2043
- *
2044
- * @param db - The closed strand's database.
2045
- * @param params - The sole manager's own keypair.
2046
- * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
2047
- * @throws If more than one manager exists (the caller wants {@link removeManager}),
2048
- * or the supplied keypair holds no `Manager` row while one exists, or the strand
2049
- * holds no `Manager` row and has never retired one (not founded yet — see
2050
- * {@link isStrandSealed}), or any schema constraint rejects; the whole
2051
- * delete+tombstone transaction rolls back. A strand that is ALREADY sealed logs
2052
- * and returns quietly (restart-safe, matching {@link bootstrapFounderMembership}
2053
- * and {@link removeManager}'s absent-row no-op).
2054
- */
2055
- export async function sealStrand(
2056
- db: Database,
2057
- params: SealStrandParams,
2058
- options?: StrandWriteOptions,
2059
- ): Promise<void> {
2060
- const { managerKeyPair } = params;
2061
- const managerCount = await strandTableCount(db, 'Manager');
2062
- if (managerCount === 0) {
2063
- // Zero managers is NOT by itself a seal — a closed strand between its Header
2064
- // and Manager founding inserts looks identical. The retired `Manager` stamp is
2065
- // what separates "frozen forever" from "still foundable"; returning quietly on
2066
- // the latter would report a seal that never happened.
2067
- if (await strandHasManagerRevocation(db)) {
2068
- log('Strand already sealed (no Manager rows, manager stamp retired); skipping seal');
2069
- return;
2070
- }
2071
- throw new Error(
2072
- 'Cannot seal: the strand holds no Manager row and has never retired one — it is '
2073
- + 'not founded yet, not sealed. Bootstrap the founding manager first.',
2074
- );
2075
- }
2076
- if (managerCount > 1) {
2077
- throw new Error(
2078
- `Cannot seal: ${managerCount} managers exist and sealing is the SOLE manager's act. `
2079
- + 'The other managers must step down first (removeManager).',
2080
- );
2081
- }
2082
- const self = await managerRow(db, managerKeyPair.publicKeyB64);
2083
- if (self == null) {
2084
- throw new Error('Cannot seal: the supplied keypair does not hold the sole Manager row.');
2085
- }
2086
- const signature = signStrandApproval(
2087
- ['Strand.Manager', 'seal', managerKeyPair.publicKeyB64, self.stampId],
2088
- managerKeyPair.privateKeyB64,
2089
- );
2090
- await execStrandTransaction(
2091
- db,
2092
- managerRemovalStatements(managerKeyPair, signature, managerKeyPair.publicKeyB64, self.stampId),
2093
- options,
2094
- );
2095
- log('Sealed strand: sole manager %s stepped down', managerKeyPair.publicKeyB64);
2096
- }
2097
-
2098
- /**
2099
- * The sApp id the strand's singleton `Strand.Header` names, or `undefined` when no
2100
- * Header row is held yet. A storage replica reads it to learn which app the strand it
2101
- * hosts belongs to (`CadreNode.getSAppId`).
2102
- */
2103
- export async function readStrandHeaderSAppId(db: Database): Promise<string | undefined> {
2104
- for await (const row of db.eval('select sAppId from Strand.Header')) {
2105
- return typeof row.sAppId === 'string' ? row.sAppId : undefined;
2106
- }
2107
- return undefined;
2108
- }
2109
-
2110
- /**
2111
- * Whether the strand is `Type = 'c'` (closed). Reads the singleton `Header` via
2112
- * the same `db.eval` scan idiom as {@link strandTableCount}; a strand with no
2113
- * `Header` row yet reports `false`.
2114
- */
2115
- async function strandIsClosed(db: Database): Promise<boolean> {
2116
- for await (const row of db.eval('select Type from Strand.Header')) {
2117
- return row.Type === 'c';
2118
- }
2119
- return false;
2120
- }
2121
-
2122
- /**
2123
- * Whether the strand is sealed: a CLOSED strand that holds no `Manager` rows AND
2124
- * has retired at least one `Manager` stamp into `Strand.Revocation`.
2125
- *
2126
- * All three conjuncts are load-bearing:
2127
- * - `Header.Type` — an OPEN strand never holds `Manager` rows at all
2128
- * (`Manager.OnlyClosed`), so a bare manager-count test would report every open
2129
- * strand as sealed.
2130
- * - the manager count — sealing IS the empty `Manager` table.
2131
- * - the retired `Manager` stamp — "sealed" means admission is frozen FOREVER, and
2132
- * what makes it permanent is the founding branch of `Manager.Authorized`
2133
- * refusing to re-seat a generation-0 manager once any `Manager` stamp has been
2134
- * retired. Without this conjunct a closed strand that is merely NOT FOUNDED YET
2135
- * reads as sealed: {@link bootstrapFounderMembership} commits `Header`,
2136
- * `Member` and `Manager` as three sequential statements, so the window between
2137
- * the first and the last is exactly "closed, zero managers, still foundable".
2138
- *
2139
- * Reads locally visible rows — a node that has not yet converged on the seal
2140
- * still reports `false` (the schema's seal-propagation NOTE).
2141
- *
2142
- * @param db - The strand's database.
2143
- * @returns `true` iff the strand is closed, holds zero `Manager` rows, and has
2144
- * permanently closed its founding branch.
2145
- */
2146
- export async function isStrandSealed(db: Database): Promise<boolean> {
2147
- return await strandIsClosed(db)
2148
- && await strandTableCount(db, 'Manager') === 0
2149
- && await strandHasManagerRevocation(db);
2150
- }
1
+ import debug from 'debug';
2
+ import { toString as uint8ArrayToString } from 'uint8arrays';
3
+ import { TransactionActiveError } from '@quereus/quereus';
4
+ import type { Database, SqlValue } from '@quereus/quereus';
5
+ import { digest, sign, verify, generatePrivateKey, getPublicKey, randomBytes } from '@optimystic/quereus-plugin-crypto';
6
+ import { offlineControllerOf } from '@serfab/quereus-plugin-sereus';
7
+ import type { SAppConfig } from './types.js';
8
+ import type { Ed25519KeyPair } from './ed25519-key.js';
9
+ import { canonicalDatetime } from './canonical-datetime.js';
10
+
11
+ const log = debug('sereus:cadre:strand-membership');
12
+
13
+ /**
14
+ * The engine (rules-logic system) assumed to manage every strand. Persisted in
15
+ * `Strand.Header.Engine`.
16
+ *
17
+ * PLACEHOLDER SEAM: there is no engine-selection mechanism yet — Quereus is the
18
+ * only engine. When a real engine-config seam lands, the founder bootstrap should
19
+ * read the strand's chosen engine from there instead of this constant. Documented
20
+ * deliberately so the column is non-null and self-describing in the meantime.
21
+ */
22
+ export const STRAND_ENGINE = 'quereus';
23
+
24
+ /**
25
+ * The pinned engine version recorded in `Strand.Header.EngineVersion`. A pinned
26
+ * string for the same reason as {@link STRAND_ENGINE}: it is a documented
27
+ * placeholder until an engine-selection seam supplies the real running version.
28
+ */
29
+ export const STRAND_ENGINE_VERSION = '0.1.0';
30
+
31
+ /**
32
+ * The single-payload ed25519 signer the `Strand.Invite`/`Strand.ConsumedInvite`
33
+ * handshake constraints verify against.
34
+ *
35
+ * Those constraints sign a single SHA-256 digest over a `'|'`-joined payload
36
+ * (e.g. `InviteValid` verifies
37
+ * `verify(digest(new.Key || '|' || coalesce(new.Expiration, '')), ...)`).
38
+ * So the signer hashes the payload to raw bytes and ed25519-signs *those bytes*:
39
+ * SQL `digest(...)`'s default output is base64url and `verify(...)`'s default
40
+ * `inputEncoding` is base64url, so signer and verifier operate on identical bytes.
41
+ * The membership/RBAC tables (Member/Manager/MemberPeer/Revocation) instead use
42
+ * domain/action-tagged VARIADIC digests — see {@link signStrandApproval}.
43
+ *
44
+ * All strand keys are ed25519, so the explicit `'ed25519'` curve arg is mandatory
45
+ * (the crypto plugin otherwise defaults to secp256k1). Mirrors the proven
46
+ * `signItem` helper in the `rbac-signed-write` integration scenario.
47
+ *
48
+ * @param payload - The `'|'`-joined payload the matching constraint hashes.
49
+ * @param privateKeyB64 - The signer's base64url ed25519 private seed.
50
+ * @returns The base64url ed25519 signature over the payload's SHA-256 digest.
51
+ */
52
+ export function signStrandPayload(payload: string, privateKeyB64: string): string {
53
+ const hashBytes = digest([payload], 'sha256', 'bytes') as Uint8Array;
54
+ return sign(hashBytes, privateKeyB64, 'ed25519', 'bytes', 'base64url', 'base64url') as string;
55
+ }
56
+
57
+ /**
58
+ * The verifier counterpart to {@link signStrandPayload}.
59
+ *
60
+ * Mirrors what the single-payload `Strand.*` constraints compute:
61
+ * `verify(digest(payload), signature, publicKey, 'ed25519')`.
62
+ * SQL `digest`'s default output and `verify`'s default `inputEncoding`/`sigEncoding`/
63
+ * `keyEncoding` are all base64url, so the off-engine check operates on the exact
64
+ * same bytes the in-engine CHECK does. Used by the off-engine `MemberVerifier`
65
+ * (pre-flight registration checks) so the on-engine constraint is not the only
66
+ * place a member self-proof is validated.
67
+ *
68
+ * @param payload - The `'|'`-joined payload the matching constraint hashes.
69
+ * @param signatureB64 - The base64url ed25519 signature to check.
70
+ * @param publicKeyB64 - The base64url ed25519 public key to verify against.
71
+ * @returns `true` iff the signature is valid for the payload under that key.
72
+ */
73
+ export function verifyStrandPayload(payload: string, signatureB64: string, publicKeyB64: string): boolean {
74
+ const payloadDigest = digest([payload], 'sha256', 'base64url') as string;
75
+ return verify(payloadDigest, signatureB64, publicKeyB64, 'ed25519', 'base64url', 'base64url', 'base64url');
76
+ }
77
+
78
+ /**
79
+ * Sign a domain/action-tagged `Strand.*` membership/RBAC approval.
80
+ *
81
+ * Every `Authorized` branch on `Member`/`Manager`/`MemberPeer`/`Revocation`
82
+ * verifies a VARIADIC digest — `digest('<domain>', '<action>', <field>, ...,
83
+ * <StampId>)` — whose leading two elements are fixed literals (the domain tag,
84
+ * e.g. `'Strand.Member'`, and an action tag, e.g. `'add'`) and whose trailing
85
+ * element is the row's per-incarnation StampId. The tags keep an approval from
86
+ * verifying against any rule but the one it was minted for (the idiom of the
87
+ * control layer's `buildAuthorizationMessage`); the StampId binding makes it
88
+ * single-use — it authorizes exactly one incarnation of one row, and dies when
89
+ * that row's stamp is retired into `Strand.Revocation`.
90
+ *
91
+ * The caller passes the digest elements exactly as the matching SQL constraint
92
+ * lists them (each SQL argument = one array element), PRESERVING TYPE: the
93
+ * crypto plugin's digest framing is type-tagged (INTEGER 1 and TEXT '1' encode
94
+ * differently, deliberately), so `Manager.Authorized`'s promotion branch —
95
+ * whose digest includes the INTEGER `new.Generation` — must be signed over the
96
+ * NUMBER, not its string form. Integer `number` and `bigint` encode
97
+ * identically in that framing, so JS-side numbers match however the engine
98
+ * represents the SQL integer.
99
+ *
100
+ * Like {@link signStrandPayload}, the raw digest BYTES are ed25519-signed
101
+ * directly, matching SQL `verify(...)`'s default base64url input decoding.
102
+ *
103
+ * @param fields - The digest elements, in constraint order (tags first, StampId last).
104
+ * @param privateKeyB64 - The signer's base64url ed25519 private seed.
105
+ * @returns The base64url ed25519 signature over the tagged digest.
106
+ */
107
+ export function signStrandApproval(fields: ReadonlyArray<string | number>, privateKeyB64: string): string {
108
+ const hashBytes = digest(fields, 'sha256', 'bytes') as Uint8Array;
109
+ return sign(hashBytes, privateKeyB64, 'ed25519', 'bytes', 'base64url', 'base64url') as string;
110
+ }
111
+
112
+ /**
113
+ * Mint a fresh per-row authorization nonce (StampId) for a `Strand.Member`,
114
+ * `Strand.Manager`, or `Strand.MemberPeer` row.
115
+ *
116
+ * 256 bits of CSPRNG output, base64url-encoded — enough entropy that a future
117
+ * legitimate stamp cannot be guessed and pre-planted into `Strand.Revocation`
118
+ * (the `RowIsGone` comment in `schemas/strand.qsql` leans on exactly this).
119
+ * Plain randomness, deliberately NOT the control layer's peer-derived
120
+ * `generateStampId`: strand rows are not per-peer, so entropy alone carries
121
+ * the uniqueness.
122
+ *
123
+ * @returns A fresh base64url stamp (43 chars for 32 bytes).
124
+ */
125
+ export function generateStrandStampId(): string {
126
+ // randomBytes' first arg is BITS, not bytes — 256 bits = 32 bytes.
127
+ const bytes = randomBytes(256, 'bytes') as Uint8Array;
128
+ return uint8ArrayToString(bytes, 'base64url');
129
+ }
130
+
131
+ // ── Write batches (every membership write is one indivisible transaction) ──────
132
+
133
+ /**
134
+ * A membership writer that runs only in a transaction of its own found another
135
+ * transaction already open on the strand database, and wrote nothing. Raised only
136
+ * under `joinOpenTransaction: false` (see {@link StrandWriteOptions}) — the background
137
+ * callers, which treat it as "the app is mid-transaction; try again later".
138
+ */
139
+ export class StrandTransactionBusyError extends Error {
140
+ constructor(options?: ErrorOptions) {
141
+ super(
142
+ 'Another transaction is open on the strand database. This membership write runs only in a '
143
+ + 'transaction of its own, so nothing was written; retry once that transaction closes.',
144
+ options,
145
+ );
146
+ this.name = 'StrandTransactionBusyError';
147
+ }
148
+ }
149
+
150
+ /**
151
+ * A membership write refused because the strand's offline queue holds transactions its members
152
+ * have not taken yet (docs/strands/writes.md → "Offline mode"). Every `Strand` table is network-acknowledged, and a
153
+ * network-acknowledged commit made while transactions are queued waits for them to settle while
154
+ * holding Quereus's execution lock, so every other statement on the strand database, the app's
155
+ * included, would wait with it for up to the plugin's `networkCommitTimeoutMs`. Nothing was
156
+ * written. Raised whether or not the write would have joined an open transaction: joining would
157
+ * make the app's own commit wait the same way.
158
+ */
159
+ export class StrandOfflineQueueBusyError extends Error {
160
+ /** The queued transactions the write would have waited behind, in queue order. */
161
+ readonly transactionIds: readonly string[];
162
+
163
+ constructor(transactionIds: readonly string[]) {
164
+ super(
165
+ `The strand's offline queue holds ${transactionIds.length} transaction(s) its members have not taken yet `
166
+ + `(${transactionIds.join(', ')}). A membership write is acknowledged by the strand's members and would `
167
+ + 'wait behind them, holding the strand database, so nothing was written; await '
168
+ + 'strand.database.offline.whenDrained() and retry.',
169
+ );
170
+ this.name = 'StrandOfflineQueueBusyError';
171
+ this.transactionIds = transactionIds;
172
+ }
173
+ }
174
+
175
+ /** Options every transactional membership writer accepts. */
176
+ export interface StrandWriteOptions {
177
+ /**
178
+ * Default true: when a transaction is already open on the database, run the writer's
179
+ * statements inside it. The caller composes several writers in one transaction (e.g. a
180
+ * resign + revoke pair that must land together) and owns its commit and rollback, so
181
+ * the deferred constraints fire once, at the caller's commit.
182
+ *
183
+ * Background callers (the membership reconciler, the unpublish binding cleanup) pass
184
+ * false: they share the database with the app and must never join a transaction
185
+ * someone else opened, so the writer throws {@link StrandTransactionBusyError} instead.
186
+ */
187
+ joinOpenTransaction?: boolean;
188
+ }
189
+
190
+ /**
191
+ * SQL statements, each terminated by `;`, plus the named parameters they bind. The unit
192
+ * the writers assemble a batch from: a writer does every read, signature, and
193
+ * `canonicalDatetime` first, and only then issues all its statements in ONE `db.exec`.
194
+ */
195
+ interface StrandStatements {
196
+ sql: string;
197
+ params: Record<string, SqlValue>;
198
+ }
199
+
200
+ /**
201
+ * Join statement fragments into one batch. Named parameters bind across the whole batch,
202
+ * so each fragment builder uses its own parameter names; a name bound twice would
203
+ * silently hand one fragment the other's value, so it throws instead.
204
+ */
205
+ function combineStatements(...fragments: StrandStatements[]): StrandStatements {
206
+ const params: Record<string, SqlValue> = {};
207
+ for (const fragment of fragments) {
208
+ for (const [name, value] of Object.entries(fragment.params)) {
209
+ if (name in params) {
210
+ throw new Error(`Strand write batch binds the parameter :${name} in two statements`);
211
+ }
212
+ params[name] = value;
213
+ }
214
+ }
215
+ return { sql: fragments.map((fragment) => fragment.sql).join('\n'), params };
216
+ }
217
+
218
+ /**
219
+ * Run `statements` as one indivisible transaction on the shared strand database.
220
+ *
221
+ * `exec(..., { transaction: true })` begins, runs, and commits or rolls back the whole
222
+ * batch under a single hold of Quereus's execution mutex. That is what makes the
223
+ * transaction indivisible on a `Database` the app shares with the background writers: no
224
+ * other caller's statement can run inside it, so none is ever swept into a membership
225
+ * write and lost when that write fails — not even a statement that fails before `commit`
226
+ * (a primary-key collision, an immediate CHECK, a storage read error), whose rollback also
227
+ * happens before the mutex is released. A hand-rolled `begin` / … / `commit` batch is not
228
+ * equivalent, and a `beginTransaction()` / `exec` / `commit()` sequence even less so:
229
+ * those are separate mutex acquisitions.
230
+ *
231
+ * Whether a transaction is already open is decided by the batch itself, under the mutex,
232
+ * not by `getAutocommit()` beforehand: that reads false whenever another caller's
233
+ * autocommit statement is merely in flight, which would make a background writer refuse
234
+ * spuriously and a composing caller run its statements as separate autocommits.
235
+ *
236
+ * - The strand's offline queue holds transactions: {@link StrandOfflineQueueBusyError}, before
237
+ * anything runs, every writer and every option alike (see {@link refuseBehindOfflineQueue}).
238
+ * - No transaction was open: the batch commits or fails as a unit, leaving nothing open.
239
+ * - One was already open, so the batch refuses with `TransactionActiveError` having run
240
+ * nothing. With `joinOpenTransaction: false` that becomes a
241
+ * {@link StrandTransactionBusyError} (with the refusal as `cause`), and the open
242
+ * transaction — someone else's — is left alone. Otherwise the statements run inside it,
243
+ * and its owner commits or rolls back.
244
+ */
245
+ async function execStrandTransaction(
246
+ db: Database,
247
+ statements: StrandStatements,
248
+ options?: StrandWriteOptions,
249
+ ): Promise<void> {
250
+ refuseBehindOfflineQueue(db);
251
+ try {
252
+ await db.exec(statements.sql, statements.params, { transaction: true });
253
+ return;
254
+ } catch (error) {
255
+ if (!(error instanceof TransactionActiveError)) {
256
+ throw error;
257
+ }
258
+ if (options?.joinOpenTransaction === false) {
259
+ throw new StrandTransactionBusyError({ cause: error });
260
+ }
261
+ }
262
+ // NOTE: the join retry cannot ask for `{ transaction: true }` — the point is to run INSIDE the
263
+ // caller's transaction — so it is atomic only for as long as that transaction stays open. Every
264
+ // joining caller today opens its transaction, awaits the writer, then commits, so the
265
+ // transaction cannot close in the window between the refusal above and this line. If a caller
266
+ // ever closes its transaction concurrently with a writer call it did not await, these statements
267
+ // run as separate autocommit statements instead of one unit. The writers whose statements are
268
+ // circularly dependent (`consumeInvite`'s Member + ConsumedInvite, every delete + its Revocation
269
+ // tombstone) fail loudly on their own deferred checks in that case; a writer whose statements are
270
+ // each valid alone (`admitManager`) could commit only the first. If a caller ever needs to write
271
+ // membership rows without awaiting, give it `joinOpenTransaction: false` rather than relying on
272
+ // this path.
273
+ await db.exec(statements.sql, statements.params);
274
+ }
275
+
276
+ /**
277
+ * Throw {@link StrandOfflineQueueBusyError} while the strand's offline queue lists any
278
+ * transaction. `entries()` also lists the journaled ones a restore has not put back yet, and a
279
+ * network-acknowledged commit waits behind those too.
280
+ *
281
+ * NOTE: racy by nature: an app commit queued between this check and the batch's `exec` makes the
282
+ * membership commit wait behind it, for up to `networkCommitTimeoutMs`, holding the execution
283
+ * lock. That is upstream's bounded wait in the rare case. If a frozen strand database is ever
284
+ * traced to a membership write that slipped past this check, hold the app's writes during
285
+ * membership commits instead.
286
+ */
287
+ function refuseBehindOfflineQueue(db: Database): void {
288
+ const queued = offlineControllerOf(db)?.entries() ?? [];
289
+ if (queued.length > 0) {
290
+ throw new StrandOfflineQueueBusyError(queued.map((entry) => entry.transactionId));
291
+ }
292
+ }
293
+
294
+ /**
295
+ * The `Strand.Revocation` tombstone insert that retires a deleted row's StampId.
296
+ *
297
+ * Always batched with the delete it accompanies — the guarded tables'
298
+ * `RevocationRecorded` (deferred) requires the tombstone at commit, and
299
+ * `Revocation.RowIsGone` (also deferred) requires the row to already be gone, so
300
+ * the pair only ever lands together.
301
+ *
302
+ * `Revocation.Authorized` verifies the retire-tagged digest against a
303
+ * PRE-transaction (`committed.Member`) row, so the retiree must have been a
304
+ * member BEFORE this transaction. Every writer flow satisfies this: managers are
305
+ * members, and a self-departing member is committed until this very transaction
306
+ * removes it. Unlike the sibling tables' nullable contexts, `Revocation`'s
307
+ * context is non-null — both fields are always supplied.
308
+ *
309
+ * @param tableName - Which guarded table the stamp belonged to.
310
+ * @param stampId - The retired stamp.
311
+ * @param retiree - The committed member filing the tombstone (the delete's own signer).
312
+ */
313
+ function revocationStatement(
314
+ tableName: 'Member' | 'Manager' | 'MemberPeer',
315
+ stampId: string,
316
+ retiree: Ed25519KeyPair,
317
+ ): StrandStatements {
318
+ return {
319
+ sql: `insert into Strand.Revocation (TableName, StampId)
320
+ with context MemberKey = :revocationSignerKey, Signature = :revocationSignature
321
+ values (:revocationTable, :revocationStampId);`,
322
+ params: {
323
+ revocationSignerKey: retiree.publicKeyB64,
324
+ revocationSignature: signStrandApproval(['Strand.Revocation', 'retire', tableName, stampId], retiree.privateKeyB64),
325
+ revocationTable: tableName,
326
+ revocationStampId: stampId,
327
+ },
328
+ };
329
+ }
330
+
331
+ /** Parameters for {@link bootstrapFounderMembership}. */
332
+ export interface FounderBootstrapParams {
333
+ /** The strand id — written to `Header.Id`. */
334
+ strandId: string;
335
+ /** Strand type: `'o'` (open, Header only) or `'c'` (closed, Header+Member+Manager). */
336
+ type: 'o' | 'c';
337
+ /** The sApp config whose id/version/schemaVersion/schema/signature populate the Header. */
338
+ sApp: SAppConfig;
339
+ /**
340
+ * The founder's derived strand keypair (from {@link strandMemberKeyPair}). Its
341
+ * `publicKeyB64` becomes the founding `Member.Key` and `Manager.MemberKey`.
342
+ * Required for a closed strand; ignored for an open strand.
343
+ */
344
+ founderKeyPair?: Ed25519KeyPair;
345
+ /**
346
+ * The public key derived from the strand row's SHARED `MemberPrivateKey` (the read
347
+ * secret every joining party holds). When supplied for a closed strand, a
348
+ * `Strand.Member` or `Strand.Manager` row holding it refuses the bootstrap with
349
+ * {@link PreSplitStrandIdentityError} (see {@link assertNotPreSplitStrand}): nothing
350
+ * seats that key since the per-party identity split, so its presence is exactly the
351
+ * fingerprint of a strand founded before it. Omitted, no such check runs (a caller that
352
+ * holds no shared key has nothing to compare against). Ignored for an open strand.
353
+ */
354
+ sharedMemberPublicKey?: string;
355
+ /**
356
+ * This machine's strand transport peer id. When supplied for a closed strand, the run that
357
+ * seats the founding `Member` also writes this machine's `Strand.MemberPeer` binding in the
358
+ * same transaction, instead of leaving it to the membership reconciler's first pass (a
359
+ * commit of its own). Omitted, no binding is written here: a database with no transport,
360
+ * or a node whose reconciler is disarmed. Ignored for an open strand.
361
+ */
362
+ founderPeerId?: string;
363
+ /**
364
+ * Commit an empty collection for every table the strand declares except the qualified
365
+ * tables named, resolving to how many it committed: the composition's
366
+ * `createEmptyCollections`. Run once, on the founding run that finds no `Header` — see
367
+ * {@link createDeclaredCollections}.
368
+ */
369
+ createEmptyCollections: (except?: readonly string[]) => Promise<number>;
370
+ }
371
+
372
+ /**
373
+ * A closed strand founded BEFORE the per-party identity split: its founding
374
+ * `Strand.Member` (and, unless handed on, `Strand.Manager`) is the key derived from the
375
+ * shared `MemberPrivateKey`, which every joining party holds, so any member can sign as
376
+ * the founder. There is no repair — rewriting the membership cannot be trusted, since any
377
+ * joiner could already have admitted or revoked anyone, or could race the rewrite — so
378
+ * the strand must be recreated. Thrown by {@link assertNotPreSplitStrand} (a founder
379
+ * bootstrap, or membership-invite issuance); the formation layer maps it to a
380
+ * non-retryable rejection.
381
+ */
382
+ export class PreSplitStrandIdentityError extends Error {
383
+ constructor(readonly strandId: string) {
384
+ super(
385
+ `Closed strand ${strandId} was founded before per-party strand identity: its founding ` +
386
+ 'member key is derived from the shared MemberPrivateKey that every joining party holds, ' +
387
+ 'so any member can act as its founder. It cannot be repaired — recreate the strand ' +
388
+ '(unpublish it and found a new one).',
389
+ );
390
+ this.name = 'PreSplitStrandIdentityError';
391
+ }
392
+ }
393
+
394
+ /**
395
+ * Count rows in a `Strand.*` table as seen by this database instance.
396
+ *
397
+ * The table name is a fixed literal supplied by this module (never user input),
398
+ * so the interpolation is not an injection surface — it just keeps the singleton
399
+ * insert-if-absent guards terse.
400
+ */
401
+ async function strandTableCount(db: Database, table: 'Header' | 'Member' | 'Manager'): Promise<number> {
402
+ for await (const row of db.eval(`select count(1) as Count from Strand.${table}`)) {
403
+ return (row.Count as number) ?? 0;
404
+ }
405
+ return 0;
406
+ }
407
+
408
+ /**
409
+ * Whether any `Strand.Revocation` row has ever retired a `Manager` seat — the
410
+ * exact condition that permanently closes the founding branch of
411
+ * `Manager.Authorized` (see the schema's bootstrap-branch comment). Unfiltered
412
+ * scan + JavaScript comparison, the module's scan-not-seek idiom (rationale on
413
+ * {@link scanMemberPeers}).
414
+ *
415
+ * NOTE: walks the whole append-only `Strand.Revocation` table when no `Manager`
416
+ * tombstone is present (it returns on the first one it finds). Cheap at strand
417
+ * scale; if membership churn ever makes that table large — the growth the
418
+ * `Revocation` schema comment already flags, tracked by `debt-strand-tombstone-reap`
419
+ * — this wants a stored "founding closed" marker rather than a scan per call.
420
+ *
421
+ */
422
+ async function strandHasManagerRevocation(db: Database): Promise<boolean> {
423
+ for await (const row of db.eval('select TableName from Strand.Revocation')) {
424
+ if (row.TableName === 'Manager') {
425
+ return true;
426
+ }
427
+ }
428
+ return false;
429
+ }
430
+
431
+ /** One founding row still missing: its qualified table and the statement that inserts it. */
432
+ interface FoundingRow {
433
+ table: 'Strand.Header' | 'Strand.Member' | 'Strand.Manager' | 'Strand.MemberPeer';
434
+ statements: StrandStatements;
435
+ }
436
+
437
+ /**
438
+ * Commit an empty collection for every table the strand declares except `writtenTables`, so a
439
+ * read of a table nobody has written is answered from local storage instead of asking the
440
+ * block's cohort to prove the collection absent, and still answers with the other members
441
+ * offline. Peer-join backfill hands these collections to every joiner. The founding
442
+ * transaction's own tables are left out because its inserts create their collections anyway.
443
+ *
444
+ * Only while the Header is absent, and before the founding transaction writes it: a machine
445
+ * cannot write to a strand before it holds the Header (`strand-first-sync-gate.ts`), so no other
446
+ * machine can yet have created any of these collections and this cannot fork one. On a founder
447
+ * restart the Header is present and this does not run; running it there could commit an empty
448
+ * second history beside a table a joiner wrote while the founder was away. A crash between this
449
+ * and the founding commit repeats it on the next run, which commits only the collections still
450
+ * missing.
451
+ *
452
+ * NOTE: one `sync()` per collection, in sequence. Measured 2026-10-17 on a lone node over the
453
+ * network transactor (`connectToStrand`, then the step alone, 3 runs each): a nine-table app
454
+ * schema (20 collections with the strand's own) took 32–82 ms in memory and 465–486 ms on
455
+ * `FileRawStorage`; the reference chat schema (13 collections) 19–30 ms and 298–350 ms. About
456
+ * 23 ms per collection on disk, once per strand, before `foundStrand` returns. Leaving out the
457
+ * founding transaction's tables brings the chat schema to 6 collections on a closed strand whose
458
+ * founder binds its peer, and 12 on an open one. If founding latency starts to matter (slower
459
+ * phone storage, much larger schemas), commit them as one batch through a coordinator, the way
460
+ * the transaction bridge's `commitBatchLegacy` does.
461
+ */
462
+ async function createDeclaredCollections(params: FounderBootstrapParams, writtenTables: readonly string[]): Promise<void> {
463
+ const t0 = performance.now();
464
+ const committed = await params.createEmptyCollections(writtenTables);
465
+ log('Committed %d empty collections for strand %s in %dms',
466
+ committed, params.strandId, Math.round(performance.now() - t0));
467
+ }
468
+
469
+ /**
470
+ * The singleton `Strand.Header` insert.
471
+ *
472
+ * Every `Header` column but `sAppSchemaVersion` is NOT NULL (Quereus defaults
473
+ * unqualified columns to NOT NULL), and all nine are supplied non-null; that one is
474
+ * nullable only so the column could be added to existing strands. A missing
475
+ * `sApp.signature` (dev `requireSignedSchemas:false`) coalesces to `''` rather than
476
+ * inserting null. `Header` carries only `InsertOnly` + a singleton PK,
477
+ * so the insert needs no `with context`.
478
+ */
479
+ function headerRow(params: FounderBootstrapParams): FoundingRow {
480
+ return {
481
+ table: 'Strand.Header',
482
+ statements: {
483
+ sql: `insert into Strand.Header
484
+ (Id, Type, sAppId, sAppVersion, sAppSchemaVersion, sAppSchema, sAppSignature, Engine, EngineVersion)
485
+ values (:headerId, :headerType, :headerSAppId, :headerSAppVersion, :headerSAppSchemaVersion,
486
+ :headerSAppSchema, :headerSAppSignature, :headerEngine, :headerEngineVersion);`,
487
+ params: {
488
+ headerId: params.strandId,
489
+ headerType: params.type,
490
+ headerSAppId: params.sApp.id,
491
+ headerSAppVersion: params.sApp.version,
492
+ headerSAppSchemaVersion: params.sApp.schemaVersion,
493
+ headerSAppSchema: params.sApp.schema,
494
+ headerSAppSignature: params.sApp.signature ?? '',
495
+ headerEngine: STRAND_ENGINE,
496
+ headerEngineVersion: STRAND_ENGINE_VERSION,
497
+ },
498
+ },
499
+ };
500
+ }
501
+
502
+ /**
503
+ * The founding `Strand.Member` insert.
504
+ *
505
+ * The empty PRE-transaction member set (`count(1) from committed.Member = 0`)
506
+ * satisfies the bootstrap branch of `Member.Authorized`, so no signature is
507
+ * needed — the context fields are explicit nulls. The branch also caps the
508
+ * POST-image at one member, so it waives authorization for exactly this single
509
+ * seat, never for a batch. The row still mints a fresh StampId — the column is
510
+ * NOT NULL on every path; bootstrap only waives the SIGNATURE.
511
+ */
512
+ function founderMemberRow(memberKey: string): FoundingRow {
513
+ return {
514
+ table: 'Strand.Member',
515
+ statements: {
516
+ sql: `insert into Strand.Member (Key, StampId)
517
+ with context ManagerKey = null, ManagerSignature = null, MemberSignature = null
518
+ values (:founderMemberKey, :founderMemberStampId);`,
519
+ params: { founderMemberKey: memberKey, founderMemberStampId: generateStrandStampId() },
520
+ },
521
+ };
522
+ }
523
+
524
+ /**
525
+ * The founding `Strand.Manager` insert, at `Generation = 0` — the root of the manager
526
+ * lineage; the bootstrap branch of `Manager.Authorized` requires exactly that value, and
527
+ * every later manager is seated at a strictly greater generation (see {@link addManager}).
528
+ * No signature is needed (a fresh StampId is still minted — the column is NOT NULL).
529
+ *
530
+ * The bootstrap branch, `Manager.MemberExists` and `Manager.OnlyClosed` all have subqueries,
531
+ * so they defer to commit and read the live `Member` and `Header` tables: a founding
532
+ * `Manager` whose `Member` and `Header` are neither committed already nor in its own
533
+ * transaction is rejected.
534
+ */
535
+ function founderManagerRow(memberKey: string): FoundingRow {
536
+ return {
537
+ table: 'Strand.Manager',
538
+ statements: {
539
+ sql: `insert into Strand.Manager (MemberKey, Generation, StampId)
540
+ with context ManagerKey = null, Signature = null
541
+ values (:founderManagerKey, 0, :founderManagerStampId);`,
542
+ params: { founderManagerKey: memberKey, founderManagerStampId: generateStrandStampId() },
543
+ },
544
+ };
545
+ }
546
+
547
+ /**
548
+ * Whether the founding `Strand.Manager` still has to be seated: no manager exists and the
549
+ * strand is not SEALED. A strand whose sole manager has {@link sealStrand}ed also has zero
550
+ * `Manager` rows, but its founding branch is closed for good (the schema's bootstrap branch
551
+ * requires no `Manager`-table `Revocation` row to exist). Seating it there would be
552
+ * schema-rejected and turn every founder restart of a sealed strand into a loud failure — so
553
+ * this mirrors the schema's own gate. A founding that never committed its Manager leaves no
554
+ * Revocation rows at all, so that restart still completes the founding.
555
+ */
556
+ async function founderManagerMissing(db: Database, strandId: string): Promise<boolean> {
557
+ if (await strandTableCount(db, 'Manager') > 0) {
558
+ log('Manager already present for strand %s; skipping founder Manager', strandId);
559
+ return false;
560
+ }
561
+ if (await strandHasManagerRevocation(db)) {
562
+ log('Strand %s has retired a manager seat (sealed); skipping founder Manager', strandId);
563
+ return false;
564
+ }
565
+ return true;
566
+ }
567
+
568
+ /**
569
+ * This machine's `Strand.MemberPeer` binding, unless there is no peer id to bind or the
570
+ * binding is already present (a re-run after a torn founding commit).
571
+ */
572
+ async function founderBindingIfAbsent(
573
+ db: Database,
574
+ founderKeyPair: Ed25519KeyPair,
575
+ peerId: string | undefined,
576
+ ): Promise<FoundingRow[]> {
577
+ if (peerId === undefined) {
578
+ return [];
579
+ }
580
+ if (await memberPeerStampId(db, founderKeyPair.publicKeyB64, peerId) !== undefined) {
581
+ log('MemberPeer (%s, %s) already present; skipping founder binding', founderKeyPair.publicKeyB64, peerId);
582
+ return [];
583
+ }
584
+ return [{ table: 'Strand.MemberPeer', statements: memberPeerInsertStatement(founderKeyPair, peerId) }];
585
+ }
586
+
587
+ /**
588
+ * The closed strand's founding rows that are still missing, in Member → Manager → MemberPeer
589
+ * order. Each is behind an insert-if-absent guard, so a re-run after a crash or a torn commit
590
+ * writes only what is missing.
591
+ *
592
+ * The binding joins only a run that seats the founding `Member`. With a member row already
593
+ * present the founder may since have left the strand or been removed, and
594
+ * `MemberPeer.MemberExists` would then refuse the whole founding transaction; the membership
595
+ * reconciler, which binds only once it sees this party's member row, writes it instead.
596
+ */
597
+ async function missingClosedFoundingRows(
598
+ db: Database,
599
+ founderKeyPair: Ed25519KeyPair,
600
+ params: FounderBootstrapParams,
601
+ ): Promise<FoundingRow[]> {
602
+ const memberKey = founderKeyPair.publicKeyB64;
603
+ const seatsMember = await strandTableCount(db, 'Member') === 0;
604
+ if (!seatsMember) {
605
+ log('Member already present for strand %s; skipping founder Member', params.strandId);
606
+ }
607
+ const seatsManager = await founderManagerMissing(db, params.strandId);
608
+ const binding = seatsMember ? await founderBindingIfAbsent(db, founderKeyPair, params.founderPeerId) : [];
609
+ return [
610
+ ...(seatsMember ? [founderMemberRow(memberKey)] : []),
611
+ ...(seatsManager ? [founderManagerRow(memberKey)] : []),
612
+ ...binding,
613
+ ];
614
+ }
615
+
616
+ /**
617
+ * Refuse a closed strand whose membership still holds the key derived from the shared
618
+ * `MemberPrivateKey` (see {@link FounderBootstrapParams.sharedMemberPublicKey}). `Member`
619
+ * is the primary probe — every manager is a member (`Manager.MemberExists`), so it also
620
+ * catches a pre-split founder who handed management to another key and resigned, or a
621
+ * sealed pre-split strand. `Manager` is probed too, for the partition case the schema
622
+ * notes on `MemberExists` (a Manager row converged without its Member row). Cannot
623
+ * misfire: nothing seats the shared-derived key since the split, and rows not yet loaded
624
+ * read as absent.
625
+ *
626
+ * @throws {PreSplitStrandIdentityError} when a `Strand.Member` or `Strand.Manager` row is
627
+ * the shared-derived key.
628
+ */
629
+ export async function assertNotPreSplitStrand(db: Database, strandId: string, sharedMemberPublicKey: string): Promise<void> {
630
+ if (await memberStampId(db, sharedMemberPublicKey) !== undefined
631
+ || await managerRow(db, sharedMemberPublicKey) !== undefined) {
632
+ throw new PreSplitStrandIdentityError(strandId);
633
+ }
634
+ }
635
+
636
+ /**
637
+ * Founder-only one-time bootstrap of a strand's `Strand.*` membership/RBAC rows.
638
+ *
639
+ * Runs once at bring-up on the strand's FOUNDER (the party that provisioned and
640
+ * published the strand). A joiner never calls this — it receives these rows via
641
+ * Optimystic sync. It reads which founding rows are missing, then writes all of them in
642
+ * ONE strand transaction. Every row is insert-if-absent, so a restart / founder
643
+ * re-`addStrand` writes nothing, and a re-run after a failed or torn founding commit
644
+ * writes only what is missing.
645
+ *
646
+ * On the run that finds no `Header`, it first commits an empty collection for every
647
+ * table the `Strand` and `App` schemas declare except the ones the founding transaction
648
+ * writes, so no read of a declared table ever needs another member to prove it empty
649
+ * ({@link createDeclaredCollections}).
650
+ *
651
+ * Behavior by strand type:
652
+ * - **Open (`'o'`)**: `Header` only. `Member`/`Manager`/`Invite` are `OnlyClosed` and
653
+ * would trip that constraint — they are skipped entirely.
654
+ * - **Closed (`'c'`)**: `Header(Type='c')`, the founding `Member` and `Manager` (both
655
+ * `founderKeyPair.publicKeyB64`) and, when `founderPeerId` is supplied, this machine's
656
+ * `MemberPeer` binding. Every check that reads another founding row has a subquery, so
657
+ * it defers to commit and sees the whole transaction.
658
+ *
659
+ * A closed strand with no `founderKeyPair` throws: a closed strand with no founding
660
+ * Manager could never admit anyone, so failing loudly here (which propagates out
661
+ * of `StrandDatabase.initialize()` and triggers the runtime's rollback) is correct.
662
+ *
663
+ * A closed strand whose membership holds `sharedMemberPublicKey` throws
664
+ * {@link PreSplitStrandIdentityError} before writing anything: the insert-if-absent
665
+ * guards would otherwise skip over its pre-split founding rows and leave the shared
666
+ * key seated. Checked only when the `Header` is already present: a strand founded before
667
+ * the key split committed its Header first, alone, so a strand with no Header has none
668
+ * of those rows.
669
+ *
670
+ * @param db - The strand's Quereus database (schema already applied).
671
+ * @param params - Strand id/type, the sApp config for the Header, the composition's
672
+ * empty-collection step, and (closed only) the derived founder keypair, the
673
+ * shared-derived public key to refuse and this machine's peer id to bind.
674
+ * @throws If `type === 'c'` and no `founderKeyPair` is supplied.
675
+ * @throws {PreSplitStrandIdentityError} If `type === 'c'` and a `Strand.Member` or
676
+ * `Strand.Manager` row is `sharedMemberPublicKey`.
677
+ */
678
+ export async function bootstrapFounderMembership(db: Database, params: FounderBootstrapParams): Promise<void> {
679
+ const { strandId, type, founderKeyPair, sharedMemberPublicKey } = params;
680
+ log('Founder bootstrap for strand %s (type %s)', strandId, type);
681
+
682
+ // Validate BEFORE writing anything: a closed strand with no founder key must
683
+ // fail without leaving a closed `Header` that has no founding Member/Manager
684
+ // (such a strand could never admit anyone).
685
+ if (type === 'c' && !founderKeyPair) {
686
+ throw new Error(
687
+ `Cannot bootstrap closed strand ${strandId}: no founder key pair derived from this party's ` +
688
+ 'StrandPartyKey. A closed strand needs a founding Member + Manager or it can never admit members.',
689
+ );
690
+ }
691
+ const headerPresent = await strandTableCount(db, 'Header') > 0;
692
+ if (headerPresent && type === 'c' && sharedMemberPublicKey !== undefined) {
693
+ await assertNotPreSplitStrand(db, strandId, sharedMemberPublicKey);
694
+ }
695
+
696
+ const rows = [
697
+ ...(headerPresent ? [] : [headerRow(params)]),
698
+ ...(type === 'c' ? await missingClosedFoundingRows(db, founderKeyPair!, params) : []),
699
+ ];
700
+ if (!headerPresent) {
701
+ await createDeclaredCollections(params, rows.map((row) => row.table));
702
+ }
703
+ if (rows.length === 0) {
704
+ log('Strand %s is already founded; nothing to write', strandId);
705
+ return;
706
+ }
707
+ // NOTE: a torn founding commit (some of the batch's collections saved, others not) can leave
708
+ // the Header committed beside a founding table with no collection, which committing every
709
+ // table's empty collection first used to rule out. A sibling machine of this party could then
710
+ // create that collection itself (its reconciler binding its own peer into MemberPeer). The
711
+ // re-run's guards, and this machine's reconciler, read each table before writing it, and a
712
+ // networked read asks the cohort, so the healing write appends to the sibling's collection
713
+ // unless the sibling is unreachable at that moment. A torn founding that saves this
714
+ // machine's MemberPeer without its Member also leaves an orphaned binding, which every
715
+ // machine's revocation enforcer (this one's and any joiner's) reads as a removed founder
716
+ // until a later run of this bootstrap seats the Member. If torn founding commits are ever
717
+ // observed, commit the founding tables a sibling writes (MemberPeer) as empty collections
718
+ // before this batch again.
719
+ await execStrandTransaction(db, combineStatements(...rows.map((row) => row.statements)));
720
+ log('Founder bootstrap for strand %s wrote %s', strandId, rows.map((row) => row.table).join(', '));
721
+ }
722
+
723
+ // ── Invite issuance + consumption (the per-strand join handshake) ─────────────
724
+
725
+ /** Parameters for {@link issueInvite}. */
726
+ export interface IssueInviteParams {
727
+ /**
728
+ * The issuing manager's strand keypair. Its `publicKeyB64` must already be a
729
+ * `Strand.Manager` row (the `InviteValid` constraint rejects a non-manager).
730
+ */
731
+ managerKeyPair: Ed25519KeyPair;
732
+ /**
733
+ * Optional invite expiry as epoch milliseconds. When set, it is canonicalised
734
+ * via {@link canonicalDatetime} so the signed payload segment byte-matches the
735
+ * `datetime`-coerced `Invite.Expiration` the deferred CHECK sees. When omitted,
736
+ * the invite never expires and the signed segment is `''` (matching the schema's
737
+ * `coalesce(new.Expiration, '')`).
738
+ */
739
+ expiration?: number;
740
+ }
741
+
742
+ /** The minted invite: a public key (the `Invite.Key`) plus its private seed. */
743
+ export interface IssuedInvite {
744
+ /** The invite ed25519 PUBLIC key (base64url) — the `Invite.Key` primary key. */
745
+ inviteKey: string;
746
+ /**
747
+ * The invite ed25519 PRIVATE seed (base64url). Handed out-of-band to the
748
+ * invitee; whoever holds it can {@link consumeInvite} exactly once. NEVER
749
+ * persisted in the strand — only the public key is.
750
+ */
751
+ invitePrivateKey: string;
752
+ }
753
+
754
+ /**
755
+ * Issue a single-use invitation to join a closed strand.
756
+ *
757
+ * Generates a fresh invite ed25519 keypair (the public key becomes `Invite.Key`),
758
+ * builds the constraint's payload (`Key || '|' || coalesce(Expiration, '')`), and
759
+ * signs it TWICE: with the manager private key (→ `ManagerSignature`, proving
760
+ * a manager issued it) and with the invite private key (→ `InviteSignature`,
761
+ * proving the issuer actually holds the invite secret). Both signatures plus the
762
+ * manager public key are bound as constraint context for the `Invite` insert.
763
+ *
764
+ * The returned `invitePrivateKey` is the only secret the invitee needs to redeem
765
+ * the invite — it is NOT stored in the strand (only `Invite.Key`, the public half,
766
+ * is). Single-use is enforced at consumption time: `ConsumedInvite`'s primary key
767
+ * is `InviteKey`, so a given invite can be consumed at most once.
768
+ *
769
+ * @param db - The closed strand's database (founder already bootstrapped).
770
+ * @param params - The issuing manager keypair and optional expiry.
771
+ * @returns The invite public key and the out-of-band private seed.
772
+ */
773
+ export async function issueInvite(db: Database, params: IssueInviteParams): Promise<IssuedInvite> {
774
+ const { managerKeyPair, expiration } = params;
775
+
776
+ const invitePrivateKey = generatePrivateKey('ed25519', 'base64url') as string;
777
+ const inviteKey = getPublicKey(invitePrivateKey, 'ed25519', 'base64url', 'base64url') as string;
778
+
779
+ // Canonicalise the expiry to the engine's stored `datetime` form so the signed
780
+ // segment matches `new.Expiration` post-coercion; null expiry signs as ''.
781
+ const expirationSegment = expiration == null ? '' : await canonicalDatetime(db, expiration);
782
+ const expirationColumn = expiration == null ? null : expirationSegment;
783
+
784
+ const payload = `${inviteKey}|${expirationSegment}`;
785
+ const managerSignature = signStrandPayload(payload, managerKeyPair.privateKeyB64);
786
+ const inviteSignature = signStrandPayload(payload, invitePrivateKey);
787
+
788
+ await execStrandTransaction(db, {
789
+ sql: `insert into Strand.Invite (Key, Expiration)
790
+ with context ManagerKey = :managerKey, ManagerSignature = :managerSignature, InviteSignature = :inviteSignature
791
+ values (:inviteKey, :expiration);`,
792
+ params: { managerKey: managerKeyPair.publicKeyB64, managerSignature, inviteSignature, inviteKey, expiration: expirationColumn },
793
+ });
794
+ log('Issued invite %s (expires=%s)', inviteKey, expirationColumn ?? 'never');
795
+
796
+ return { inviteKey, invitePrivateKey };
797
+ }
798
+
799
+ /** Parameters for {@link consumeInvite}. */
800
+ export interface ConsumeInviteParams {
801
+ /** The `Invite.Key` (invite PUBLIC key, base64url) being redeemed. */
802
+ inviteKey: string;
803
+ /** The matching invite PRIVATE seed (base64url) received out-of-band. */
804
+ invitePrivateKey: string;
805
+ /** The joining member's ed25519 PUBLIC key (base64url) — the new `Member.Key`. */
806
+ memberKey: string;
807
+ /**
808
+ * The instant (epoch ms) to compare against the invite's `Expiration` for the
809
+ * `NotExpired` gate. Defaults to `Date.now()`; tests pin it so the comparison is
810
+ * deterministic. Mirrors the control-layer `redeemInvitation`'s `nowMs` convention.
811
+ */
812
+ nowMs?: number;
813
+ }
814
+
815
+ /**
816
+ * Redeem an invite to admit a new `Member`, atomically.
817
+ *
818
+ * `Member.Authorized`'s invite branch needs a `ConsumedInvite` row, while
819
+ * `ConsumedInvite`'s `MemberExists` needs the `Member` row — a circular
820
+ * dependency. Both are deferred (subquery-bearing) checks that evaluate
821
+ * at COMMIT, so inserting `Member` then `ConsumedInvite` inside one explicit
822
+ * transaction lets both rows exist when the deferred checks fire. This mirrors
823
+ * `ControlDatabase.redeemInvitation` (Strand + FormationUsage in one txn).
824
+ *
825
+ * The `ConsumedInvite` insert carries an `InviteSignature` over
826
+ * `InviteKey || '|' || MemberKey`, proving the consumer holds the invite private
827
+ * key (the on-engine `ValidUsage` gate). The `Member` insert needs no member
828
+ * signature — its admission is the existence of the matching `ConsumedInvite` —
829
+ * but still mints a fresh StampId (NOT NULL on every path; a revoked-then-
830
+ * re-invited member is a fresh incarnation under a fresh stamp).
831
+ *
832
+ * Single-use: `ConsumedInvite`'s primary key is `InviteKey`, so a second consume
833
+ * of the same invite is rejected by the PK (a distinct layer from the control
834
+ * network's `FormationUsage` single-use, which gates strand FORMATION, not the
835
+ * per-strand member join enforced here).
836
+ *
837
+ * Expiry: the `ConsumedInvite.NotExpired` deferred check rejects redeeming an invite
838
+ * whose `Expiration` is at or before `context.Now`. `Now` is supplied here as a
839
+ * canonical-datetime string from `canonicalDatetime(db, nowMs)` — the SAME transform
840
+ * `issueInvite` uses to store `Invite.Expiration` — so both sides of the schema's
841
+ * `I.Expiration > context.Now` comparison are byte-identical canonical strings and
842
+ * the lexical `>` orders chronologically at any granularity. (This intentionally
843
+ * diverges from the control layer, which passes `Now` as a JS ISO string; Quereus
844
+ * does not coerce context params, so an ISO `Now` would be compared lexically against
845
+ * the canonical, T-separated `Expiration` and could mis-order near-same-instant
846
+ * timestamps (due to a trailing `.000Z` suffix). The control tests only use far-future/far-past expiries, so that latent
847
+ * skew never bites there — the strand layer avoids it outright.) A null `Expiration`
848
+ * never expires. Like `ValidUsage`, `NotExpired` defers to commit, so an expired
849
+ * invite rolls back the whole txn — neither the `Member` nor the `ConsumedInvite`
850
+ * row survives.
851
+ *
852
+ * @param db - The closed strand's database.
853
+ * @param params - The invite key/secret, the joining member's public key, and an
854
+ * optional `nowMs` instant for the expiry comparison (default `Date.now()`).
855
+ * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
856
+ * @throws If any constraint rejects (bad signature, missing invite, or an expired
857
+ * invite); the whole transaction rolls back (neither the `Member` nor the
858
+ * `ConsumedInvite` row survives).
859
+ * @throws {StrandTransactionBusyError} Under `joinOpenTransaction: false`, when another
860
+ * transaction is open; nothing was written.
861
+ */
862
+ export async function consumeInvite(
863
+ db: Database,
864
+ params: ConsumeInviteParams,
865
+ options?: StrandWriteOptions,
866
+ ): Promise<void> {
867
+ const { inviteKey, memberKey } = params;
868
+ // Member first — admitted by the deferred invite branch (the matching ConsumedInvite
869
+ // after it), so no manager signature is supplied.
870
+ const member: StrandStatements = {
871
+ sql: `insert into Strand.Member (Key, StampId)
872
+ with context ManagerKey = null, ManagerSignature = null, MemberSignature = null
873
+ values (:memberKey, :memberStampId);`,
874
+ params: { memberKey, memberStampId: generateStrandStampId() },
875
+ };
876
+ await execStrandTransaction(db, combineStatements(member, await consumedInviteStatement(db, params)), options);
877
+ log('Consumed invite %s -> member %s', inviteKey, memberKey);
878
+ }
879
+
880
+ /**
881
+ * The `Strand.ConsumedInvite` marker row insert — the possession-plus-freshness proof
882
+ * shared by {@link consumeInvite} (batched after its `Member` insert) and
883
+ * {@link burnInvite} (alone, against an already-seated member).
884
+ *
885
+ * The invite signature covers `InviteKey || '|' || MemberKey` (the `ValidUsage` gate),
886
+ * and "now" is canonicalised the same way {@link issueInvite} canonicalises
887
+ * `Expiration`, so the schema's `I.Expiration > context.Now` compares like-for-like
888
+ * canonical strings. Plain runtime Date.now() — the tess Workflow restriction is on
889
+ * scripts, not libs.
890
+ */
891
+ async function consumedInviteStatement(db: Database, params: ConsumeInviteParams): Promise<StrandStatements> {
892
+ const { inviteKey, invitePrivateKey, memberKey, nowMs } = params;
893
+ return {
894
+ sql: `insert into Strand.ConsumedInvite (InviteKey, MemberKey)
895
+ with context InviteSignature = :consumedSignature, Now = :consumedNow
896
+ values (:consumedInviteKey, :consumedMemberKey);`,
897
+ params: {
898
+ consumedSignature: signStrandPayload(`${inviteKey}|${memberKey}`, invitePrivateKey),
899
+ consumedNow: await canonicalDatetime(db, nowMs ?? Date.now()),
900
+ consumedInviteKey: inviteKey,
901
+ consumedMemberKey: memberKey,
902
+ },
903
+ };
904
+ }
905
+
906
+ /**
907
+ * Burn an invitation against an ALREADY-SEATED member: insert the
908
+ * `Strand.ConsumedInvite` row alone, naming the existing `Member.Key`, so the bearer
909
+ * credential can never be spent by anyone else.
910
+ *
911
+ * The already-member arm of the bring-up membership reconciler
912
+ * (`strand-membership-reconciler.ts`): a machine that finds its party's `Member` row
913
+ * already present (a sibling machine redeemed the invitation's twin first, or a
914
+ * manager admitted the party directly) may still hold an UNSPENT formation-delivered
915
+ * invitation — a bearer credential whoever presents can join with. Every
916
+ * `ConsumedInvite` constraint is satisfiable without a same-transaction `Member`
917
+ * insert (`MemberExists` reads the live table), so this is one statement whose
918
+ * deferred checks fire at its own commit. It seats nobody now or later:
919
+ * `Member.Authorized`'s invite branch requires a same-transaction FRESH consumption,
920
+ * so the row it leaves is exactly as inert as any other spent invitation's.
921
+ *
922
+ * @param db - The closed strand's database (the member already exists).
923
+ * @param params - The invite key/secret and the EXISTING member's public key, plus the
924
+ * optional `nowMs` instant for the expiry gate (default `Date.now()`).
925
+ * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
926
+ * @throws If any constraint rejects — already consumed (the `InviteKey` primary key),
927
+ * cancelled, expired, or a sealed strand — or the cohort refuses the write. The
928
+ * reconciler routes these through the same classifier as a `consumeInvite` rejection:
929
+ * a dead invitation is dropped, a refused write keeps it staged for a retry.
930
+ * @throws {StrandTransactionBusyError} Under `joinOpenTransaction: false`, when another
931
+ * transaction is open; nothing was tried, so the invitation is exactly as live as before.
932
+ */
933
+ export async function burnInvite(
934
+ db: Database,
935
+ params: ConsumeInviteParams,
936
+ options?: StrandWriteOptions,
937
+ ): Promise<void> {
938
+ await execStrandTransaction(db, await consumedInviteStatement(db, params), options);
939
+ log('Burned invite %s against existing member %s', params.inviteKey, params.memberKey);
940
+ }
941
+
942
+ /**
943
+ * Every value of `InviteKey` in one of the two invite-marker tables, as a `Set`.
944
+ *
945
+ * Unfiltered scan + JavaScript comparison, deliberately: `ConsumedInvite` and
946
+ * `CancelledInvite` each have the single column `InviteKey` as their primary key, so
947
+ * ANY where-equality on it is a FULL-PK predicate — which the optimystic virtual-table
948
+ * module serves via a single-key point lookup that can MISS on a networked strand (the
949
+ * argument {@link scanMemberPeers} makes in full). Reading the whole column and
950
+ * comparing in JS depends only on the scan returning a SUPERSET of the live rows.
951
+ *
952
+ * The table name is a fixed literal supplied by this module (never user input), so the
953
+ * interpolation is not an injection surface — same as {@link strandTableCount}.
954
+ *
955
+ * NOTE: every caller pays a WHOLE-column read — {@link cancelInvite}'s idempotence guard
956
+ * reads all cancelled keys to answer one membership question, and
957
+ * {@link listOutstandingInvites} reads both marker tables per call. Fine at strand scale
958
+ * (a handful of invitations); if invite churn ever gets large this wants a real filtered
959
+ * read, which in turn needs the networked point-lookup gap closed
960
+ * (`debt-composite-pk-point-lookup-unreliable-untracked`).
961
+ */
962
+ async function scanInviteKeys(db: Database, table: 'ConsumedInvite' | 'CancelledInvite'): Promise<Set<string>> {
963
+ const keys = new Set<string>();
964
+ for await (const row of db.eval(`select InviteKey from Strand.${table}`)) {
965
+ keys.add(row.InviteKey as string);
966
+ }
967
+ return keys;
968
+ }
969
+
970
+ /** Parameters for {@link cancelInvite}. */
971
+ export interface CancelInviteParams {
972
+ /**
973
+ * The cancelling manager's strand keypair. Its `publicKeyB64` must be a
974
+ * PRE-EXISTING `Strand.Manager` row — `CancelledInvite.Authorized` reads
975
+ * `committed.Manager`, so a manager seated in the SAME transaction cannot cancel.
976
+ */
977
+ managerKeyPair: Ed25519KeyPair;
978
+ /** The `Invite.Key` to kill. */
979
+ inviteKey: string;
980
+ }
981
+
982
+ /**
983
+ * Cancel an outstanding invitation, permanently: it may never be consumed.
984
+ *
985
+ * Files a `Strand.CancelledInvite` tombstone carrying a manager signature over
986
+ * `digest('Strand.CancelledInvite', 'cancel', InviteKey)`. The digest binds the exact
987
+ * invite key, so an approval minted for one invitation cannot cancel another.
988
+ *
989
+ * One row, one statement. `CancelledInvite.Authorized` is a deferred (subquery-bearing)
990
+ * check, so it fires at the batch's commit, or at the caller's when it joins an open one.
991
+ *
992
+ * Insert-if-absent, matching {@link registerMemberPeer}'s and {@link revokeMember}'s
993
+ * restart-safe shape: a repeat cancellation logs and returns rather than throwing on the
994
+ * primary key. (Check-then-write is not atomic; the primary key is the real backstop —
995
+ * the guard is for the sequential repeat/restart path.)
996
+ *
997
+ * Cancellation is what makes removal a re-entry gate: it is the `ConsumedInvite` insert
998
+ * that `NotCancelled` blocks, and `Member.Authorized`'s invite branch needs a
999
+ * same-transaction FRESH `ConsumedInvite` row, so a cancelled invitation rolls the whole
1000
+ * join back. Un-cancelling is impossible (`CancelledInvite.Immutable`) — to re-invite a
1001
+ * party, {@link issueInvite} a fresh invitation.
1002
+ *
1003
+ * Enumerate what there is to cancel with {@link listOutstandingInvites}: an invitation
1004
+ * names no invitee, so the strand cannot tell a manager WHICH invitations a departing
1005
+ * member holds. Invitee binding is tracked as `feat-strand-invitee-bound-invites`.
1006
+ *
1007
+ * @param db - The closed strand's database.
1008
+ * @param params - The cancelling manager's keypair and the invite key to kill.
1009
+ * @throws If `CancelledInvite.Authorized` rejects (a non-manager, a manager seated in
1010
+ * this transaction, or an approval minted for a different invite key) or `OnlyClosed`
1011
+ * rejects (an open strand); the insert rolls back, leaving no tombstone.
1012
+ */
1013
+ export async function cancelInvite(db: Database, params: CancelInviteParams): Promise<void> {
1014
+ const { managerKeyPair, inviteKey } = params;
1015
+
1016
+ if ((await scanInviteKeys(db, 'CancelledInvite')).has(inviteKey)) {
1017
+ log('Invite %s already cancelled; skipping', inviteKey);
1018
+ return;
1019
+ }
1020
+
1021
+ const signature = signStrandApproval(
1022
+ ['Strand.CancelledInvite', 'cancel', inviteKey],
1023
+ managerKeyPair.privateKeyB64,
1024
+ );
1025
+ await execStrandTransaction(db, {
1026
+ sql: `insert into Strand.CancelledInvite (InviteKey)
1027
+ with context ManagerKey = :managerKey, ManagerSignature = :managerSignature
1028
+ values (:inviteKey);`,
1029
+ params: { managerKey: managerKeyPair.publicKeyB64, managerSignature: signature, inviteKey },
1030
+ });
1031
+ log('Cancelled invite %s by manager %s', inviteKey, managerKeyPair.publicKeyB64);
1032
+ }
1033
+
1034
+ /** One redeemable invitation, as reported by {@link listOutstandingInvites}. */
1035
+ export interface OutstandingInvite {
1036
+ /** The `Invite.Key` (invite public key, base64url). */
1037
+ inviteKey: string;
1038
+ /**
1039
+ * The expiry as the engine's canonical `datetime` string
1040
+ * (`YYYY-MM-DDTHH:MM:SS[.frac]`, no zone suffix — see {@link canonicalDatetime}), or
1041
+ * `null` for never-expires.
1042
+ *
1043
+ * Deliberately the STORED form, not the epoch-ms {@link IssueInviteParams.expiration}
1044
+ * takes: it is what compares like-for-like against another canonicalised instant, and
1045
+ * what the on-engine `NotExpired` gate sees. It is NOT a JS-parseable ISO instant —
1046
+ * pass it through the engine (or `canonicalDatetime`) rather than `Date.parse`.
1047
+ */
1048
+ expiration: string | null;
1049
+ }
1050
+
1051
+ /**
1052
+ * The invitations that are still redeemable: neither consumed, nor cancelled, nor
1053
+ * expired at `nowMs`.
1054
+ *
1055
+ * `Strand.Invite` is insert-only and carries no state column, so "outstanding" is not a
1056
+ * property of the row — it is the `Invite` set minus the `ConsumedInvite` keys, minus
1057
+ * the `CancelledInvite` keys, minus anything whose `Expiration` has passed. All three
1058
+ * exclusions mirror gates a consume would hit anyway (`ConsumedInvite`'s primary key,
1059
+ * `NotCancelled`, `NotExpired`).
1060
+ *
1061
+ * Reads via unfiltered scans and compares in JavaScript — see {@link scanInviteKeys} for
1062
+ * why a full-PK where-equality is not reliable on a networked strand.
1063
+ *
1064
+ * Expiry is compared as `expiration > canonicalDatetime(nowMs)`: the same transform
1065
+ * {@link issueInvite} uses to STORE `Invite.Expiration`, so the string comparison orders
1066
+ * chronologically, and the same strict `>` the on-engine `NotExpired` gate uses (expiry
1067
+ * is exclusive — an invitation is dead at its expiry instant, not after it).
1068
+ *
1069
+ * This is the manager's enumeration side of {@link cancelInvite}, and the "door is open"
1070
+ * pre-flight behind `StrandMemberVerifier.isAuthorizedToJoin`.
1071
+ *
1072
+ * @param db - The closed strand's database.
1073
+ * @param nowMs - The instant (epoch ms) to compare expiries against; defaults to
1074
+ * `Date.now()`. Tests pin it so the comparison is deterministic, mirroring
1075
+ * {@link consumeInvite}'s `nowMs` convention.
1076
+ * @returns The redeemable invitations, in NO guaranteed order (the scans promise only a
1077
+ * superset of the live rows, not a stable sequence — sort by `expiration` if order
1078
+ * matters); empty if none.
1079
+ */
1080
+ export async function listOutstandingInvites(db: Database, nowMs?: number): Promise<OutstandingInvite[]> {
1081
+ // Plain runtime Date.now() — the tess Workflow restriction is on scripts, not libs.
1082
+ const nowCanonical = await canonicalDatetime(db, nowMs ?? Date.now());
1083
+ const consumed = await scanInviteKeys(db, 'ConsumedInvite');
1084
+ const cancelled = await scanInviteKeys(db, 'CancelledInvite');
1085
+
1086
+ const outstanding: OutstandingInvite[] = [];
1087
+ for await (const row of db.eval('select Key, Expiration from Strand.Invite')) {
1088
+ const inviteKey = row.Key as string;
1089
+ const expiration = (row.Expiration as string | null) ?? null;
1090
+ if (consumed.has(inviteKey) || cancelled.has(inviteKey)) {
1091
+ continue;
1092
+ }
1093
+ if (expiration != null && expiration <= nowCanonical) {
1094
+ continue;
1095
+ }
1096
+ outstanding.push({ inviteKey, expiration });
1097
+ }
1098
+ return outstanding;
1099
+ }
1100
+
1101
+ // ── Member admission + removal (manager-admit, revoke, leave) ─────────────────
1102
+
1103
+ /**
1104
+ * The live StampId of the `Strand.Member` row keyed by `memberKey`, or
1105
+ * `undefined` if no such row is visible.
1106
+ *
1107
+ * `Member`'s primary key is the single `Key` column, so ANY where-equality on it
1108
+ * is a full-PK predicate — which the optimystic virtual-table module serves via a
1109
+ * single-key point lookup that can MISS on a networked strand (the same failure
1110
+ * mode {@link scanMemberPeers} documents). So this reads via an UNFILTERED scan
1111
+ * and compares the key in JavaScript: correctness depends only on the scan
1112
+ * returning a superset of the live rows — the weakest possible assumption about
1113
+ * the storage layer.
1114
+ */
1115
+ async function memberStampId(db: Database, memberKey: string): Promise<string | undefined> {
1116
+ for await (const row of db.eval('select Key, StampId from Strand.Member')) {
1117
+ if (row.Key === memberKey) {
1118
+ return row.StampId as string;
1119
+ }
1120
+ }
1121
+ return undefined;
1122
+ }
1123
+
1124
+ /**
1125
+ * Whether `memberKey` holds a live `Strand.Member` row, as seen by THIS database
1126
+ * instance — the membership probe behind the bring-up reconciler
1127
+ * (`strand-membership-reconciler.ts`). Reads via {@link memberStampId}'s unfiltered
1128
+ * scan + JavaScript compare (the {@link scanMemberPeers} argument for why a PK point
1129
+ * lookup is not reliable on a networked strand). Local visibility only: `false` can
1130
+ * mean "not replicated here yet", never a durable verdict about the strand.
1131
+ */
1132
+ export async function isStrandMember(db: Database, memberKey: string): Promise<boolean> {
1133
+ return await memberStampId(db, memberKey) != null;
1134
+ }
1135
+
1136
+ /**
1137
+ * Whether `memberKey` holds a live `Strand.Manager` row, as seen by THIS database instance:
1138
+ * the sibling of {@link isStrandMember} for the manager seat, which the party key rotation
1139
+ * driver (`strand-party-key-rotation.ts`) reads to know whether the party can seat its own
1140
+ * new key. Same unfiltered scan, same local-visibility caveat.
1141
+ */
1142
+ export async function isStrandManager(db: Database, memberKey: string): Promise<boolean> {
1143
+ return await managerRow(db, memberKey) !== undefined;
1144
+ }
1145
+
1146
+ /** Parameters for {@link addMemberByManager}. */
1147
+ export interface AddMemberByManagerParams {
1148
+ /**
1149
+ * The admitting manager's strand keypair. Its `publicKeyB64` must be a
1150
+ * `Strand.Manager` row; it signs the add-tagged digest over the new member key
1151
+ * and its fresh stamp.
1152
+ */
1153
+ managerKeyPair: Ed25519KeyPair;
1154
+ /** The joining member's ed25519 PUBLIC key (base64url) — the new `Member.Key`. */
1155
+ memberKey: string;
1156
+ }
1157
+
1158
+ /**
1159
+ * Admit a `Member` directly by manager signature — the sibling of the invite
1160
+ * path on `Member.Authorized`'s direct-manager branch.
1161
+ *
1162
+ * The constraint verifies the add-tagged digest
1163
+ * `digest('Strand.Member', 'add', new.Key, new.StampId)` against a pre-existing
1164
+ * (`committed.Manager`) row matching `context.ManagerKey`. The stamp is minted
1165
+ * fresh here and bound inside the signed digest, so the approval seats exactly
1166
+ * this incarnation: once the member is removed (retiring the stamp), the captured
1167
+ * approval can never re-seat it. No `ConsumedInvite` is involved: this is the
1168
+ * path a manager uses to seat a member it already trusts (e.g. a manager-side
1169
+ * enrollment that admits a party already authorised out-of-band).
1170
+ *
1171
+ * @param db - The closed strand's database.
1172
+ * @param params - The admitting manager keypair and the new member key.
1173
+ * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1174
+ * @throws If `Member.Authorized` rejects (e.g. a non-manager key); the insert
1175
+ * rolls back, leaving no `Member` row.
1176
+ */
1177
+ export async function addMemberByManager(
1178
+ db: Database,
1179
+ params: AddMemberByManagerParams,
1180
+ options?: StrandWriteOptions,
1181
+ ): Promise<void> {
1182
+ const { managerKeyPair, memberKey } = params;
1183
+ await execStrandTransaction(db, memberAddByManagerStatement(params), options);
1184
+ log('Admitted member %s by manager %s', memberKey, managerKeyPair.publicKeyB64);
1185
+ }
1186
+
1187
+ /** The manager-signed `Strand.Member` insert behind {@link addMemberByManager}, under a fresh stamp. */
1188
+ function memberAddByManagerStatement(params: AddMemberByManagerParams): StrandStatements {
1189
+ const { managerKeyPair, memberKey } = params;
1190
+ const stampId = generateStrandStampId();
1191
+ return {
1192
+ sql: `insert into Strand.Member (Key, StampId)
1193
+ with context ManagerKey = :memberAdmitterKey, ManagerSignature = :memberAdmitterSignature, MemberSignature = null
1194
+ values (:memberKey, :memberStampId);`,
1195
+ params: {
1196
+ memberAdmitterKey: managerKeyPair.publicKeyB64,
1197
+ memberAdmitterSignature: signStrandApproval(['Strand.Member', 'add', memberKey, stampId], managerKeyPair.privateKeyB64),
1198
+ memberKey,
1199
+ memberStampId: stampId,
1200
+ },
1201
+ };
1202
+ }
1203
+
1204
+ /** Parameters for {@link revokeMember}. */
1205
+ export interface RevokeMemberParams {
1206
+ /**
1207
+ * The revoking manager's strand keypair. Its `publicKeyB64` must be a
1208
+ * PRE-EXISTING `Strand.Manager` row (the manager-removal branch of
1209
+ * `Member.Authorized` reads `committed.Manager` — a manager seated in the same
1210
+ * transaction cannot authorize); it signs the remove-tagged digest over the
1211
+ * target row's key and live stamp, and files the accompanying tombstone.
1212
+ */
1213
+ managerKeyPair: Ed25519KeyPair;
1214
+ /** The `Member.Key` row to delete. */
1215
+ memberKey: string;
1216
+ }
1217
+
1218
+ /**
1219
+ * Revoke a `Member` on the signature of an existing manager.
1220
+ *
1221
+ * Reads the target row's live StampId first (a quiet no-op if the row is already
1222
+ * absent — a repeated or restarted revocation should not throw), then runs ONE
1223
+ * transaction pairing the delete with its `Strand.Revocation` tombstone: the
1224
+ * schema's `Member.RevocationRecorded` requires the tombstone in the same
1225
+ * transaction, and the tombstone is what permanently retires the stamp so the
1226
+ * captured admission approval can never re-seat this incarnation.
1227
+ *
1228
+ * The manager-removal branch of `Member.Authorized` verifies the remove-tagged
1229
+ * digest `digest('Strand.Member', 'remove', old.Key, old.StampId)` against a
1230
+ * `committed.Manager` row matching `context.ManagerKey` — distinct from the
1231
+ * add-tagged admission payload, and bound to the live stamp, so neither a
1232
+ * captured admission nor a captured PRIOR removal (whose stamp differs) replays.
1233
+ *
1234
+ * A revoked member cannot re-admit itself off the invite it ALREADY SPENT: that
1235
+ * `ConsumedInvite` row is stale, and the invite branch requires a
1236
+ * same-transaction FRESH consumption. Re-admission normally takes a fresh
1237
+ * manager action ({@link addMemberByManager} or a new invite).
1238
+ *
1239
+ * An UNSPENT invite the revoked party holds is killed EXPLICITLY, by the manager
1240
+ * calling {@link cancelInvite} on it (enumerate the candidates with
1241
+ * {@link listOutstandingInvites}); a cancelled invitation can never be consumed,
1242
+ * and cancellation is permanent. This removal does NOT cascade into cancellation:
1243
+ * an invitation names no invitee, so there is nothing to match the removed member
1244
+ * against — the strand cannot tell which invitations were meant for it, or whether
1245
+ * it holds any. Binding an invitation to its invitee is tracked as
1246
+ * `feat-strand-invitee-bound-invites`.
1247
+ *
1248
+ * A manager must resign its `Manager` row before (or in the same transaction
1249
+ * as) losing membership — `Member.NotAManager` rejects un-membering a key that
1250
+ * still holds a Manager row. And the strand never drops to zero members
1251
+ * (`Member.MinOneMember`, a local-count floor with the cross-node caveat its
1252
+ * schema NOTE states).
1253
+ *
1254
+ * Inside a cadre runtime the removed party's machines are then refused at the
1255
+ * network layer by the strand's revoked-peer gate (`strand-revocation-enforcer.ts`),
1256
+ * which re-reads membership when this write commits on the runtime's own
1257
+ * `Database`. A caller that wants to await the cut follows the write with
1258
+ * `CadreNode.refreshRevocationEnforcement(strandId)`, which resolves after it.
1259
+ *
1260
+ * @param db - The closed strand's database.
1261
+ * @param params - The revoking manager keypair and the target member key.
1262
+ * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1263
+ * @throws If `Member.Authorized` rejects (a non-manager or same-transaction
1264
+ * signer), `Member.NotAManager` rejects (the target still holds a Manager
1265
+ * row), or `Member.MinOneMember` rejects (the removal would empty the member
1266
+ * set); the whole delete+tombstone transaction rolls back.
1267
+ */
1268
+ export async function revokeMember(
1269
+ db: Database,
1270
+ params: RevokeMemberParams,
1271
+ options?: StrandWriteOptions,
1272
+ ): Promise<void> {
1273
+ const { managerKeyPair, memberKey } = params;
1274
+ const stampId = await memberStampId(db, memberKey);
1275
+ if (stampId == null) {
1276
+ log('Member %s already absent; skipping revoke', memberKey);
1277
+ return;
1278
+ }
1279
+ const removal: StrandStatements = {
1280
+ sql: `delete from Strand.Member
1281
+ with context ManagerKey = :memberRemoverKey, ManagerSignature = :memberRemoverSignature, MemberSignature = null
1282
+ where Key = :memberKey;`,
1283
+ params: {
1284
+ memberRemoverKey: managerKeyPair.publicKeyB64,
1285
+ memberRemoverSignature: signStrandApproval(['Strand.Member', 'remove', memberKey, stampId], managerKeyPair.privateKeyB64),
1286
+ memberKey,
1287
+ },
1288
+ };
1289
+ await execStrandTransaction(
1290
+ db,
1291
+ combineStatements(removal, revocationStatement('Member', stampId, managerKeyPair)),
1292
+ options,
1293
+ );
1294
+ log('Revoked member %s by manager %s', memberKey, managerKeyPair.publicKeyB64);
1295
+ }
1296
+
1297
+ /** Parameters for {@link leaveStrand}. */
1298
+ export interface LeaveStrandParams {
1299
+ /**
1300
+ * The departing member's OWN strand keypair. Its `publicKeyB64` is the
1301
+ * `Member.Key` row being deleted; it self-signs the leave-tagged digest —
1302
+ * the self-departure branch verifies the signature against `old.Key` itself,
1303
+ * so only the departing key's holder can produce it — and files the
1304
+ * accompanying tombstone (it is still a committed member until this very
1305
+ * transaction removes it, which is what `Revocation.Authorized` checks). No
1306
+ * manager is involved.
1307
+ */
1308
+ memberKeyPair: Ed25519KeyPair;
1309
+ }
1310
+
1311
+ /**
1312
+ * A member leaves the strand by deleting its own `Member` row.
1313
+ *
1314
+ * The self-departure branch of `Member.Authorized` verifies
1315
+ * `digest('Strand.Member', 'leave', old.Key, old.StampId)` against `old.Key`
1316
+ * itself via `context.MemberSignature`. The `'leave'` tag (vs the manager
1317
+ * branch's `'remove'`) is belt-and-braces only — the two branches verify against
1318
+ * different keys; the anti-replay fix is the stamp binding. Like
1319
+ * {@link revokeMember}, the live stamp is read first (absent row → quiet no-op)
1320
+ * and the delete pairs with its `Strand.Revocation` tombstone in one transaction.
1321
+ *
1322
+ * The same floors as {@link revokeMember} apply: a manager must resign first
1323
+ * (`NotAManager`) and the last member cannot leave (`MinOneMember`).
1324
+ *
1325
+ * Like {@link revokeMember}, inside a cadre runtime the write wakes the strand's
1326
+ * revoked-peer gate, which emits `strand:revoked` when it finds this node's own
1327
+ * peer id revoked; `CadreNode.refreshRevocationEnforcement(strandId)` awaits that
1328
+ * refresh.
1329
+ *
1330
+ * @param db - The closed strand's database.
1331
+ * @param params - The departing member's own keypair.
1332
+ * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1333
+ * @throws If `Member.Authorized`, `Member.NotAManager`, or `Member.MinOneMember`
1334
+ * rejects; the whole delete+tombstone transaction rolls back.
1335
+ */
1336
+ export async function leaveStrand(
1337
+ db: Database,
1338
+ params: LeaveStrandParams,
1339
+ options?: StrandWriteOptions,
1340
+ ): Promise<void> {
1341
+ const { memberKeyPair } = params;
1342
+ const memberKey = memberKeyPair.publicKeyB64;
1343
+ const stampId = await memberStampId(db, memberKey);
1344
+ if (stampId == null) {
1345
+ log('Member %s already absent; skipping leave', memberKey);
1346
+ return;
1347
+ }
1348
+ const departure: StrandStatements = {
1349
+ sql: `delete from Strand.Member
1350
+ with context ManagerKey = null, ManagerSignature = null, MemberSignature = :memberSignature
1351
+ where Key = :memberKey;`,
1352
+ params: {
1353
+ memberSignature: signStrandApproval(['Strand.Member', 'leave', memberKey, stampId], memberKeyPair.privateKeyB64),
1354
+ memberKey,
1355
+ },
1356
+ };
1357
+ await execStrandTransaction(
1358
+ db,
1359
+ combineStatements(departure, revocationStatement('Member', stampId, memberKeyPair)),
1360
+ options,
1361
+ );
1362
+ log('Member %s left the strand', memberKey);
1363
+ }
1364
+
1365
+ // ── MemberPeer registration (a member binds its own network nodes) ─────────────
1366
+
1367
+ /** Parameters for {@link registerMemberPeer}. */
1368
+ export interface RegisterMemberPeerParams {
1369
+ /**
1370
+ * The member's OWN strand keypair (`{ privateKeyB64, publicKeyB64 }`). Its
1371
+ * `publicKeyB64` becomes `MemberPeer.MemberKey` and it self-signs the binding —
1372
+ * `MemberPeer.Authorized` verifies the signature against `MemberKey` itself, so a
1373
+ * peer can only be registered by the very member it belongs to (no manager
1374
+ * involved). The founder passes its `strandMemberKeyPair`; an invited member
1375
+ * passes its own keypair. Typed as {@link Ed25519KeyPair} only for the shared
1376
+ * base64url keypair shape — no manager privilege is implied.
1377
+ */
1378
+ memberKeyPair: Ed25519KeyPair;
1379
+ /** The peer/node id (libp2p peer id string) to associate with the member. */
1380
+ peerId: string;
1381
+ }
1382
+
1383
+ /**
1384
+ * Register a network node (`PeerId`) as acting on behalf of a member.
1385
+ *
1386
+ * The member self-signs the add-tagged digest
1387
+ * `digest('Strand.MemberPeer', 'add', new.MemberKey, new.PeerId, new.StampId)`
1388
+ * with its OWN key; the schema's `MemberPeer.Authorized` verifies that signature
1389
+ * against `new.MemberKey` — i.e. the member key itself — so only the member that
1390
+ * owns the key can register peers for it. The stamp is minted fresh here and
1391
+ * bound inside the digest, so a captured registration approval neither
1392
+ * re-registers a cleared binding (its stamp is retired) nor authorizes a removal
1393
+ * (wrong tag). A deferred `MemberExists` additionally requires the `Member` row
1394
+ * to already exist, so a peer for a non-member is rejected at commit.
1395
+ *
1396
+ * Insert-if-absent: a re-register on restart (or a redundant call) is a no-op. The
1397
+ * platform DOES reject a duplicate-PK insert, but a restart-safe re-register should
1398
+ * succeed quietly rather than throw, so the writer guards on existence instead of
1399
+ * catching. The guard ({@link memberPeerStampId}) scans the member's peers and compares
1400
+ * both key columns in JavaScript rather than seeking the composite primary key — see
1401
+ * {@link scanMemberPeers} for why a full-PK point lookup is not reliable on a networked
1402
+ * strand. A member may register multiple DISTINCT `PeerId`s (multi-device); each is its
1403
+ * own row (and its own stamp) under the same `MemberKey`.
1404
+ *
1405
+ * Peer DELETION is signature-checked too, not rejected outright: `Authorized` carries
1406
+ * distinct delete branches (self + manager), each over its own action-tagged digest
1407
+ * bound to the row's stamp. Both removal paths live in {@link removeMemberPeer}.
1408
+ * UPDATE is refused outright by `NoUpdate`: a re-binding is a remove plus a fresh
1409
+ * register (under a fresh stamp).
1410
+ *
1411
+ * @param db - The closed strand's database (the member already exists).
1412
+ * @param params - The member's own keypair and the peer id to bind.
1413
+ * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1414
+ * @throws If `MemberPeer.Authorized`/`MemberExists` rejects (wrong signer, or no
1415
+ * matching `Member` row); the insert rolls back, leaving no `MemberPeer` row.
1416
+ * @throws {StrandTransactionBusyError} Under `joinOpenTransaction: false`, when another
1417
+ * transaction is open; nothing was written.
1418
+ */
1419
+ export async function registerMemberPeer(
1420
+ db: Database,
1421
+ params: RegisterMemberPeerParams,
1422
+ options?: StrandWriteOptions,
1423
+ ): Promise<void> {
1424
+ const { memberKeyPair, peerId } = params;
1425
+ const memberKey = memberKeyPair.publicKeyB64;
1426
+
1427
+ if (await memberPeerStampId(db, memberKey, peerId) != null) {
1428
+ log('MemberPeer (%s, %s) already present; skipping', memberKey, peerId);
1429
+ return;
1430
+ }
1431
+
1432
+ await execStrandTransaction(db, memberPeerInsertStatement(memberKeyPair, peerId), options);
1433
+ log('Registered MemberPeer (%s, %s)', memberKey, peerId);
1434
+ }
1435
+
1436
+ /**
1437
+ * The self-signed `Strand.MemberPeer` insert binding `peerId` to the member, under a fresh
1438
+ * stamp bound into the add-tagged digest (see {@link registerMemberPeer}).
1439
+ */
1440
+ function memberPeerInsertStatement(memberKeyPair: Ed25519KeyPair, peerId: string): StrandStatements {
1441
+ const memberKey = memberKeyPair.publicKeyB64;
1442
+ const stampId = generateStrandStampId();
1443
+ return {
1444
+ sql: `insert into Strand.MemberPeer (MemberKey, PeerId, StampId)
1445
+ with context Signature = :peerSignature, ManagerKey = null, ManagerSignature = null
1446
+ values (:peerMemberKey, :peerId, :peerStampId);`,
1447
+ params: {
1448
+ peerSignature: signStrandApproval(['Strand.MemberPeer', 'add', memberKey, peerId, stampId], memberKeyPair.privateKeyB64),
1449
+ peerMemberKey: memberKey,
1450
+ peerId,
1451
+ peerStampId: stampId,
1452
+ },
1453
+ };
1454
+ }
1455
+
1456
+ /**
1457
+ * Yield every `(PeerId, StampId)` bound to `memberKey`, re-comparing the member key
1458
+ * in JavaScript.
1459
+ *
1460
+ * Deliberately does NOT filter on the full composite primary key. `MemberPeer`'s PK
1461
+ * is `(MemberKey, PeerId)`, so a `where MemberKey = ? and PeerId = ?` predicate puts
1462
+ * an equality on BOTH key columns — which the optimystic virtual-table module reports
1463
+ * as fully handled and serves via a single-key point lookup (one `find` descent), with
1464
+ * the SQL engine adding no filter of its own. On a networked strand that descent is not
1465
+ * reliable: a miss returns zero rows for a row that provably exists.
1466
+ *
1467
+ * Filtering on only the LEADING key column is a partial PK match, which the same module
1468
+ * explicitly declines to handle — it falls through to a table scan and the SQL engine
1469
+ * applies `MemberKey = ?` itself. No seek is involved, so no seek can miss. The member key
1470
+ * is then re-compared here in JavaScript, so correctness depends only on the scan returning
1471
+ * a SUPERSET of the matching rows — the weakest possible assumption about the storage layer.
1472
+ * The `where` clause only trims what crosses into JS — it is NOT pushed down (see the cost
1473
+ * note below) — so it is not a correctness dependency: a dropped or mis-applied predicate
1474
+ * cannot produce a row attributed to the wrong member.
1475
+ */
1476
+ async function* scanMemberPeers(db: Database, memberKey: string): AsyncGenerator<{ peerId: string; stampId: string }> {
1477
+ // NOTE: because the predicate is not pushed down, the storage layer walks the WHOLE
1478
+ // MemberPeer table (every member's rows) per call and the SQL engine filters. Fine at
1479
+ // strand scale; if MemberPeer ever grows large, the fix is a reliable composite-key
1480
+ // seek, not a bigger scan.
1481
+ // NOTE: if a secondary index on MemberPeer.MemberKey is ever added, this query stops
1482
+ // being a scan and becomes an index seek — re-introducing the seek dependency this
1483
+ // shape exists to remove.
1484
+ for await (const row of db.eval(
1485
+ 'select MemberKey, PeerId, StampId from Strand.MemberPeer where MemberKey = ?',
1486
+ [memberKey],
1487
+ )) {
1488
+ if (row.MemberKey === memberKey) {
1489
+ yield { peerId: row.PeerId as string, stampId: row.StampId as string };
1490
+ }
1491
+ }
1492
+ }
1493
+
1494
+ /**
1495
+ * Every `PeerId` currently bound to `memberKey`, in storage order.
1496
+ *
1497
+ * The enumeration side of {@link removeMemberPeer}: a manager cleaning up after a
1498
+ * revocation knows only the departed member's key, never which devices it registered, so
1499
+ * cleanup is `listMemberPeers` then one `removeMemberPeer` per id. Reads only — the rows
1500
+ * it returns may name a `MemberKey` with no `Member` row (see the `MemberPeer` table NOTE
1501
+ * in the schema), so this is NOT a membership test.
1502
+ *
1503
+ * @param db - The closed strand's database.
1504
+ * @param memberKey - The `MemberPeer.MemberKey` to enumerate.
1505
+ * @returns The bound peer ids, empty if the member has none.
1506
+ */
1507
+ export async function listMemberPeers(db: Database, memberKey: string): Promise<string[]> {
1508
+ const peerIds: string[] = [];
1509
+ for await (const peer of scanMemberPeers(db, memberKey)) {
1510
+ peerIds.push(peer.peerId);
1511
+ }
1512
+ return peerIds;
1513
+ }
1514
+
1515
+ /**
1516
+ * The live StampId of the `MemberPeer` row for this `(MemberKey, PeerId)`, or
1517
+ * `undefined` if no such row is visible — doubling as the existence probe.
1518
+ *
1519
+ * NOTE: check-then-write is not atomic. Two nodes registering the same
1520
+ * (MemberKey, PeerId) concurrently can both observe "absent"; the primary key is the
1521
+ * real backstop. The existence half of this guard is for the sequential restart /
1522
+ * re-register path.
1523
+ */
1524
+ async function memberPeerStampId(db: Database, memberKey: string, peerId: string): Promise<string | undefined> {
1525
+ for await (const peer of scanMemberPeers(db, memberKey)) {
1526
+ if (peer.peerId === peerId) {
1527
+ return peer.stampId;
1528
+ }
1529
+ }
1530
+ return undefined;
1531
+ }
1532
+
1533
+ /** Parameters for the SELF branch of {@link removeMemberPeer}. */
1534
+ export interface RemoveOwnPeerParams {
1535
+ /**
1536
+ * The member's OWN strand keypair. Its `publicKeyB64` is the `MemberPeer.MemberKey`
1537
+ * of the row being deleted, and it signs the remove-tagged digest
1538
+ * `digest('Strand.MemberPeer', 'remove', MemberKey, PeerId, StampId)` — the self
1539
+ * branch of `MemberPeer.Authorized` verifies against the row's own member key, so
1540
+ * no OTHER member's row is reachable this way, and the tag + stamp binding keep a
1541
+ * captured registration approval from doubling as a removal (and vice versa).
1542
+ */
1543
+ memberKeyPair: Ed25519KeyPair;
1544
+ /** The `PeerId` of the binding to delete. */
1545
+ peerId: string;
1546
+ }
1547
+
1548
+ /** Parameters for the MANAGER branch of {@link removeMemberPeer}. */
1549
+ export interface RemoveMemberPeerByManagerParams {
1550
+ /**
1551
+ * The clearing manager's strand keypair. Its `publicKeyB64` must be a PRE-EXISTING
1552
+ * `Strand.Manager` row (the manager branch reads `committed.Manager`, so a manager
1553
+ * seated in the same transaction cannot authorize); it signs the
1554
+ * manager-remove-tagged digest over the exact row and its live stamp, and files
1555
+ * the accompanying tombstone.
1556
+ */
1557
+ managerKeyPair: Ed25519KeyPair;
1558
+ /** The `MemberPeer.MemberKey` whose binding is being cleared. */
1559
+ memberKey: string;
1560
+ /** The `PeerId` of the binding to delete. */
1561
+ peerId: string;
1562
+ }
1563
+
1564
+ /**
1565
+ * Either shape accepted by {@link removeMemberPeer}. A discriminated union rather than
1566
+ * one opaque keypair: the two branches sign DIFFERENT action tags (`'remove'` self vs
1567
+ * `'manager-remove'`), so each case carries exactly the fields its payload needs.
1568
+ */
1569
+ export type RemoveMemberPeerParams = RemoveOwnPeerParams | RemoveMemberPeerByManagerParams;
1570
+
1571
+ /**
1572
+ * Delete a `MemberPeer` binding — either the member clearing its own, or a manager
1573
+ * clearing another member's.
1574
+ *
1575
+ * Reads the row's live StampId first (absent → quiet no-op, mirroring
1576
+ * {@link registerMemberPeer}'s insert-if-absent, so a repeated or restarted cleanup
1577
+ * is not a silent zero-row "success" the caller cannot distinguish from a real one),
1578
+ * then runs ONE transaction pairing the delete with its `Strand.Revocation`
1579
+ * tombstone — `MemberPeer.RevocationRecorded` requires it, and the retirement is
1580
+ * what keeps the captured registration approval from re-binding the cleared row.
1581
+ *
1582
+ * `MemberPeer` rows do NOT cascade when the member is revoked (`MemberExists` runs on
1583
+ * insert only, and nothing deletes them), so a removed member's peer bindings survive
1584
+ * as orphans — enumerate them with {@link listMemberPeers}, which is how a manager
1585
+ * discovers what to clear. Only that member can sign the self branch, and a member being
1586
+ * removed against its will has no reason to cooperate — hence the manager branch, which
1587
+ * is the cleanup path after a revocation.
1588
+ *
1589
+ * The manager branch is deliberately NOT gated on the member already being gone: a
1590
+ * manager may clear a still-present member's binding too, matching "any manager can
1591
+ * remove any member". It verifies the manager-remove-tagged
1592
+ * `digest('Strand.MemberPeer', 'manager-remove', old.MemberKey, old.PeerId, old.StampId)`
1593
+ * against a `committed.Manager` row; the self branch verifies the remove-tagged
1594
+ * sibling against the row's own member key.
1595
+ *
1596
+ * Cleanup is an explicit follow-up call by the revoking manager, never a cascade inside
1597
+ * {@link revokeMember}: a revocation that also had to clear an unbounded number of peer
1598
+ * rows in the same transaction would couple two concerns and make its failure modes
1599
+ * harder to reason about.
1600
+ *
1601
+ * @param db - The closed strand's database.
1602
+ * @param params - Either the owning member's keypair, or a manager's keypair plus the
1603
+ * target member key.
1604
+ * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1605
+ * @throws If `MemberPeer.Authorized` rejects (neither branch satisfied), or if the row
1606
+ * is still present after the delete (see the point-lookup note below).
1607
+ * @throws {StrandTransactionBusyError} Under `joinOpenTransaction: false`, when another
1608
+ * transaction is open; nothing was written.
1609
+ */
1610
+ export async function removeMemberPeer(
1611
+ db: Database,
1612
+ params: RemoveMemberPeerParams,
1613
+ options?: StrandWriteOptions,
1614
+ ): Promise<void> {
1615
+ const memberKey = 'memberKeyPair' in params ? params.memberKeyPair.publicKeyB64 : params.memberKey;
1616
+ const { peerId } = params;
1617
+
1618
+ const stampId = await memberPeerStampId(db, memberKey, peerId);
1619
+ if (stampId == null) {
1620
+ log('MemberPeer (%s, %s) already absent; skipping', memberKey, peerId);
1621
+ return;
1622
+ }
1623
+
1624
+ const removal = 'memberKeyPair' in params
1625
+ ? ownMemberPeerRemovalStatements(params, stampId)
1626
+ : memberPeerRemovalByManagerStatements(params, stampId);
1627
+ await execStrandTransaction(db, removal, options);
1628
+
1629
+ // NOTE: the delete's `where` puts an equality on BOTH composite-PK columns, which the
1630
+ // optimystic vtab module serves via a single-key seek that can MISS on a networked
1631
+ // strand (see scanMemberPeers' doc). A missed seek deletes zero rows and still
1632
+ // reports success. `Revocation.RowIsGone` now catches that first — the tombstone filed
1633
+ // in the same transaction refuses to retire a stamp whose row is still visible, so the
1634
+ // commit above fails loudly and this re-check is belt-and-braces behind it. Tracked as
1635
+ // `debt-composite-pk-point-lookup-unreliable-untracked`; this is an availability
1636
+ // failure mode, never a security one (a miss removes nothing, it never over-removes).
1637
+ if (await memberPeerStampId(db, memberKey, peerId) != null) {
1638
+ throw new Error(`MemberPeer (${memberKey}, ${peerId}) still present after delete`);
1639
+ }
1640
+ log('Removed MemberPeer (%s, %s)', memberKey, peerId);
1641
+ }
1642
+
1643
+ /** The self branch: the owning member signs the remove-tagged digest + tombstone. */
1644
+ function ownMemberPeerRemovalStatements(params: RemoveOwnPeerParams, stampId: string): StrandStatements {
1645
+ const { memberKeyPair, peerId } = params;
1646
+ const memberKey = memberKeyPair.publicKeyB64;
1647
+ const removal: StrandStatements = {
1648
+ sql: `delete from Strand.MemberPeer
1649
+ with context Signature = :peerSignature, ManagerKey = null, ManagerSignature = null
1650
+ where MemberKey = :peerMemberKey and PeerId = :peerId;`,
1651
+ params: {
1652
+ peerSignature: signStrandApproval(['Strand.MemberPeer', 'remove', memberKey, peerId, stampId], memberKeyPair.privateKeyB64),
1653
+ peerMemberKey: memberKey,
1654
+ peerId,
1655
+ },
1656
+ };
1657
+ return combineStatements(removal, revocationStatement('MemberPeer', stampId, memberKeyPair));
1658
+ }
1659
+
1660
+ /**
1661
+ * The manager branch: a manager signs the manager-remove-tagged digest + tombstone.
1662
+ *
1663
+ * NOTE: clearing an ORPHANED binding (one whose member was already removed) also
1664
+ * forgets the NETWORK DENIAL of that peer id. The orphaned `MemberPeer` row IS
1665
+ * the record the strand revoked-peer gate derives its deny set from
1666
+ * (`strand-revocation-enforcer.ts`) — the `Strand.Revocation` tombstone keeps
1667
+ * only the stamp, not the peer id — so once the orphan is cleared, remaining
1668
+ * members' nodes resume answering and dialing that peer. Only clear a binding
1669
+ * that should never have existed, or a peer that is truly gone.
1670
+ */
1671
+ function memberPeerRemovalByManagerStatements(
1672
+ params: RemoveMemberPeerByManagerParams,
1673
+ stampId: string,
1674
+ ): StrandStatements {
1675
+ const { managerKeyPair, memberKey, peerId } = params;
1676
+ const removal: StrandStatements = {
1677
+ sql: `delete from Strand.MemberPeer
1678
+ with context Signature = null, ManagerKey = :peerManagerKey, ManagerSignature = :peerManagerSignature
1679
+ where MemberKey = :peerMemberKey and PeerId = :peerId;`,
1680
+ params: {
1681
+ peerManagerKey: managerKeyPair.publicKeyB64,
1682
+ peerManagerSignature: signStrandApproval(
1683
+ ['Strand.MemberPeer', 'manager-remove', memberKey, peerId, stampId],
1684
+ managerKeyPair.privateKeyB64,
1685
+ ),
1686
+ peerMemberKey: memberKey,
1687
+ peerId,
1688
+ },
1689
+ };
1690
+ return combineStatements(removal, revocationStatement('MemberPeer', stampId, managerKeyPair));
1691
+ }
1692
+
1693
+ // ── Manager rotation (add / remove RBAC admins) ───────────────────────────────
1694
+
1695
+ /**
1696
+ * The live `(Generation, StampId)` of the `Strand.Manager` row keyed by
1697
+ * `memberKey`, or `undefined` if no such row is visible.
1698
+ *
1699
+ * `Manager`'s primary key is the single `MemberKey` column, so any where-equality
1700
+ * on it is a full-PK point lookup — unreliable on a networked strand (see
1701
+ * {@link scanMemberPeers}). An unfiltered scan + JavaScript filter instead, same
1702
+ * as {@link memberStampId}. Serves both {@link addManager} (the authorizer's
1703
+ * generation) and {@link removeManager} (the target's stamp).
1704
+ */
1705
+ async function managerRow(db: Database, memberKey: string): Promise<{ generation: number; stampId: string } | undefined> {
1706
+ for await (const row of db.eval('select MemberKey, Generation, StampId from Strand.Manager')) {
1707
+ if (row.MemberKey === memberKey) {
1708
+ return { generation: Number(row.Generation), stampId: row.StampId as string };
1709
+ }
1710
+ }
1711
+ return undefined;
1712
+ }
1713
+
1714
+ /** Parameters for {@link addManager}. */
1715
+ export interface AddManagerParams {
1716
+ /**
1717
+ * An EXISTING manager's strand keypair. Its `publicKeyB64` must already be a
1718
+ * `Strand.Manager` row (the existing-manager branch of `Manager.Authorized`
1719
+ * rejects a non-manager once the founder manager exists); it signs the
1720
+ * add-tagged digest over the new manager key, generation, and fresh stamp,
1721
+ * and is bound as `context.ManagerKey`.
1722
+ */
1723
+ byManagerKeyPair: Ed25519KeyPair;
1724
+ /** The member key to promote — the new `Manager.MemberKey` row. */
1725
+ newManagerKey: string;
1726
+ }
1727
+
1728
+ /**
1729
+ * Promote a key that is ALREADY a `Strand.Member` to `Manager` on the signature of
1730
+ * an existing manager — use {@link admitManager} to admit and promote atomically.
1731
+ *
1732
+ * The promotion branch of `Manager.Authorized` requires the authorizer to be a
1733
+ * `Manager` row of STRICTLY SMALLER `Generation` than the new row, verifying
1734
+ * `digest('Strand.Manager', 'add', new.MemberKey, new.Generation, new.StampId)`
1735
+ * against `context.ManagerKey`. So this writer reads the authorizer's generation,
1736
+ * seats the new manager at that value + 1 (the natural successor; the schema
1737
+ * enforces only the strict ordering), mints a fresh stamp, and signs the
1738
+ * add-tagged digest over all three: the generation inside the signed digest keeps
1739
+ * a captured promotion from replaying at a different generation, and the stamp
1740
+ * keeps it from re-seating a second incarnation once this one is removed.
1741
+ * `new.Generation` is an SQL INTEGER digest arg — the digest framing is
1742
+ * type-tagged, so the TS side signs over the NUMBER itself
1743
+ * (see {@link signStrandApproval}).
1744
+ *
1745
+ * The strict ordering — not this writer — is what makes a same-transaction takeover
1746
+ * impossible; the `Manager.Generation` column comment in `schemas/strand.qsql` carries
1747
+ * that argument. All this writer owes it is a generation strictly above the
1748
+ * authorizer's, inside the signed payload.
1749
+ *
1750
+ * When the authorizer has NO `Manager` row (a non-manager signer, or an open
1751
+ * strand with no managers at all), the scan finds nothing and the writer falls
1752
+ * back to generation 1 and issues the insert anyway — deliberately letting the
1753
+ * SCHEMA be the rejector (`Manager.Authorized` / `OnlyClosed`), not a
1754
+ * writer-thrown error, so enforcement is pinned where it actually lives.
1755
+ *
1756
+ * @param db - The closed strand's database (founder manager already seated).
1757
+ * @param params - The authorizing manager's keypair and the new manager key.
1758
+ * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1759
+ * @throws If `Manager.Authorized` rejects, or if `Manager.MemberExists` rejects because
1760
+ * `newManagerKey` holds no `Member` row (admit it first, or use
1761
+ * {@link admitManager}); the insert rolls back.
1762
+ */
1763
+ export async function addManager(
1764
+ db: Database,
1765
+ params: AddManagerParams,
1766
+ options?: StrandWriteOptions,
1767
+ ): Promise<void> {
1768
+ const { byManagerKeyPair, newManagerKey } = params;
1769
+ const promotion = await managerAddStatement(db, params);
1770
+ await execStrandTransaction(db, promotion, options);
1771
+ log('Added manager %s (generation %d) by %s', newManagerKey, promotion.params.managerGeneration,
1772
+ byManagerKeyPair.publicKeyB64);
1773
+ }
1774
+
1775
+ /**
1776
+ * The `Strand.Manager` insert behind {@link addManager}: reads the authorizer's generation,
1777
+ * seats the new manager one above it under a fresh stamp, and signs all three.
1778
+ */
1779
+ async function managerAddStatement(db: Database, params: AddManagerParams): Promise<StrandStatements> {
1780
+ const { byManagerKeyPair, newManagerKey } = params;
1781
+ const authorizer = await managerRow(db, byManagerKeyPair.publicKeyB64);
1782
+ // NOTE: +1 saturates at Number.MAX_SAFE_INTEGER, where the successor compares equal
1783
+ // to its authorizer and the schema rejects. Unreachable while generations only ever
1784
+ // grow by 1 from 0, but the schema enforces ordering, not adjacency, so a manager may
1785
+ // seat a successor at any larger value; if arbitrary generations ever become writable
1786
+ // from outside this function, clamp or reject here rather than emitting a dead row.
1787
+ const generation = authorizer == null ? 1 : authorizer.generation + 1;
1788
+ const stampId = generateStrandStampId();
1789
+ return {
1790
+ sql: `insert into Strand.Manager (MemberKey, Generation, StampId)
1791
+ with context ManagerKey = :managerAuthorizerKey, Signature = :managerSignature
1792
+ values (:managerMemberKey, :managerGeneration, :managerStampId);`,
1793
+ params: {
1794
+ managerAuthorizerKey: byManagerKeyPair.publicKeyB64,
1795
+ managerSignature: signStrandApproval(
1796
+ ['Strand.Manager', 'add', newManagerKey, generation, stampId],
1797
+ byManagerKeyPair.privateKeyB64,
1798
+ ),
1799
+ managerMemberKey: newManagerKey,
1800
+ managerGeneration: generation,
1801
+ managerStampId: stampId,
1802
+ },
1803
+ };
1804
+ }
1805
+
1806
+ /** Parameters for {@link admitManager} — the same shape as {@link AddManagerParams}. */
1807
+ export type AdmitManagerParams = AddManagerParams;
1808
+
1809
+ /**
1810
+ * Admit a key as a `Member` AND promote it to `Manager`, atomically — the one-step
1811
+ * pair for a key that is not in the strand yet. {@link addManager} alone promotes a
1812
+ * key that is already a member.
1813
+ *
1814
+ * ONE transaction, because `Manager.MemberExists` is a deferred check reading the LIVE
1815
+ * `Member` table: the sibling `Member` insert satisfies it at the shared commit, and a
1816
+ * rejection of either half rolls BOTH rows back — never a `Member` row seated by a
1817
+ * failed promotion, nor a `Manager` row with no member behind it.
1818
+ *
1819
+ * NO new authority: both halves are signed by the SAME manager, over two distinct
1820
+ * action-tagged digests — `digest('Strand.Member', 'add', …)` for the admission and
1821
+ * `digest('Strand.Manager', 'add', …)` for the promotion — each bound to its own row's
1822
+ * fresh stamp. This composes exactly the two approvals that manager could already
1823
+ * issue separately.
1824
+ *
1825
+ * The promoting manager must be a PRE-transaction manager: the direct-admit branch of
1826
+ * `Member.Authorized` reads `committed.Manager`, so `admitManager` cannot be chained —
1827
+ * a manager seated by an `admitManager` earlier in the SAME transaction cannot admit
1828
+ * the next one. (A same-transaction promotion CHAIN rooted at a pre-existing manager
1829
+ * is fine; only the `Member` half needs the committed authorizer.)
1830
+ *
1831
+ * NOT insert-if-absent: a repeat call for a key that is already a member fails on the
1832
+ * `Member` primary key, matching {@link addMemberByManager}'s unguarded shape.
1833
+ *
1834
+ * @param db - The closed strand's database (founder manager already seated).
1835
+ * @param params - The authorizing manager's keypair and the key to admit + promote.
1836
+ * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1837
+ * @throws If either half is rejected (`Member.Authorized`, `Manager.Authorized`, a
1838
+ * duplicate `Member` key, …); the whole transaction rolls back, leaving neither row.
1839
+ */
1840
+ export async function admitManager(
1841
+ db: Database,
1842
+ params: AdmitManagerParams,
1843
+ options?: StrandWriteOptions,
1844
+ ): Promise<void> {
1845
+ const { byManagerKeyPair, newManagerKey } = params;
1846
+ const admission = memberAddByManagerStatement({ managerKeyPair: byManagerKeyPair, memberKey: newManagerKey });
1847
+ const promotion = await managerAddStatement(db, params);
1848
+ await execStrandTransaction(db, combineStatements(admission, promotion), options);
1849
+ log('Admitted + promoted manager %s by %s', newManagerKey, byManagerKeyPair.publicKeyB64);
1850
+ }
1851
+
1852
+ /** Parameters for {@link removeManager}. */
1853
+ export interface RemoveManagerParams {
1854
+ /**
1855
+ * The keypair authorizing the removal, bound as `context.ManagerKey`. For an
1856
+ * ADMIN removal this is a DIFFERENT existing manager, signing the
1857
+ * remove-tagged digest (satisfying the existing-manager branch); for a
1858
+ * SELF-resignation it is the target's OWN keypair (`publicKeyB64 ===
1859
+ * targetManagerKey`), signing the resign-tagged digest (satisfying the
1860
+ * former-manager self branch). The writer picks the tag by comparing the keys —
1861
+ * see {@link removeManager}. Either way this keypair also files the
1862
+ * accompanying tombstone, which requires it to be a PRE-transaction MEMBER
1863
+ * (`Revocation.Authorized` reads `committed.Member`) — true for every manager,
1864
+ * since managers are members.
1865
+ */
1866
+ byManagerKeyPair: Ed25519KeyPair;
1867
+ /** The `Manager.MemberKey` row to delete. */
1868
+ targetManagerKey: string;
1869
+ }
1870
+
1871
+ /**
1872
+ * Remove a `Manager` row — either an admin removing a different manager or a
1873
+ * manager resigning itself.
1874
+ *
1875
+ * Reads the target row's live `(Generation, StampId)` first (absent → quiet
1876
+ * no-op, same restart-safe shape as {@link revokeMember}), then runs ONE
1877
+ * transaction pairing the delete with its `Strand.Revocation` tombstone
1878
+ * (`Manager.RevocationRecorded`). The two delete-side branches of
1879
+ * `Manager.Authorized` verify DIFFERENT action-tagged digests, each bound to
1880
+ * `(old.MemberKey, old.StampId)`:
1881
+ * - **Admin removal** (`byManagerKeyPair` is a different existing manager): the
1882
+ * removal branch verifies `digest('Strand.Manager', 'remove', old.MemberKey,
1883
+ * old.StampId)` against `A.MemberKey = context.ManagerKey`. Deliberately NO
1884
+ * generation condition: a later-generation manager may remove an
1885
+ * earlier-generation one (generation is lineage, not privilege), and deletes
1886
+ * are safe once inserts are — every accepting branch requires a `Manager` row
1887
+ * in the post-image, and the promotion branch's generation ordering keeps
1888
+ * attacker rows out of it. The stamp binding is what makes a captured removal
1889
+ * single-use: a re-promoted manager carries a fresh stamp the old approval
1890
+ * does not match — closing the removal half of
1891
+ * `bug-strand-manager-authority-antireplay` (the insert half was already
1892
+ * closed by the generation-bearing promotion payload).
1893
+ * - **Self-resignation** (`byManagerKeyPair` IS the target): the former-manager
1894
+ * self branch verifies `digest('Strand.Manager', 'resign', old.MemberKey,
1895
+ * old.StampId)` against `old.MemberKey` itself. The distinct `'resign'` tag is
1896
+ * belt-and-braces (different verifying keys); the anti-replay fix is the stamp.
1897
+ *
1898
+ * The caller selects the case purely by which keypair it passes; the only
1899
+ * branching here is the action tag, chosen by comparing the signer to the target.
1900
+ *
1901
+ * Deferred (subquery-bearing) CHECK constraints are evaluated on DELETE as well
1902
+ * as INSERT by Quereus plus the Optimystic vtab session — enforcement lives above
1903
+ * the transactor (proven on the network transactor by
1904
+ * `strand-membership-network-transactor-parity.spec.ts`), so `Manager.Authorized`
1905
+ * — deferred — IS enforced here: a signer that is neither an existing manager nor
1906
+ * the target itself is rejected at commit.
1907
+ *
1908
+ * THE SOLE MANAGER CANNOT ORDINARILY RESIGN — it SEALS instead. The `'resign'`
1909
+ * branch of `Manager.Authorized` requires at least one manager in the POST-delete
1910
+ * image, so a resignation that would empty the `Manager` table is schema-rejected;
1911
+ * emptying it deliberately is a distinct, self-signed act — {@link sealStrand} —
1912
+ * that permanently freezes admission. This writer refuses the sole-manager
1913
+ * self-resignation up front with an error naming `sealStrand`; that TS guard is UX,
1914
+ * not the trust boundary — the schema rejects a mis-counted `'resign'` approval
1915
+ * regardless. Reading the count inside a caller-joined transaction is correct: an
1916
+ * add-then-resign hand-off composed in one transaction sees 2 and passes, while
1917
+ * the already-rejected delete-then-add swap sees 1 and is refused here as well as
1918
+ * by the schema. The bootstrap branch of `Manager.Authorized` is gated to INSERTs
1919
+ * (`old.MemberKey is null`), so it does not waive the signature check on a delete
1920
+ * that drops the count toward zero: a second-to-last removal is authorized
1921
+ * exactly like any other.
1922
+ *
1923
+ * HAND-OFF ORDER: a sole manager transferring control must ADD the successor FIRST
1924
+ * and resign SECOND. A same-transaction delete-then-insert swap is rejected — the
1925
+ * bootstrap branch is gated to the founding state (at most one `Member`), and the
1926
+ * successor's insert has no other manager to authorize it once the sole manager's
1927
+ * row is gone.
1928
+ *
1929
+ * Cross-node caveat: the `'resign'`/`'seal'` branches count rows visible to THIS
1930
+ * transaction, so two nodes concurrently removing different managers can each see
1931
+ * a survivor and still converge to zero — an unintended seal. Noted in the schema
1932
+ * (the `Manager` table's seal-propagation NOTE); a cross-node floor is not
1933
+ * attempted here.
1934
+ *
1935
+ * @param db - The closed strand's database.
1936
+ * @param params - The authorizing keypair and the target manager key.
1937
+ * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
1938
+ * @throws If the signer IS the target and it is the sole manager (before writing —
1939
+ * the operation the caller wants is {@link sealStrand}), or if `Manager.Authorized`
1940
+ * rejects (a signer that is neither another existing manager nor the target
1941
+ * itself, or a raw sole-manager `'resign'` whose post-image count is zero); the
1942
+ * whole delete+tombstone transaction rolls back.
1943
+ */
1944
+ export async function removeManager(
1945
+ db: Database,
1946
+ params: RemoveManagerParams,
1947
+ options?: StrandWriteOptions,
1948
+ ): Promise<void> {
1949
+ const { byManagerKeyPair, targetManagerKey } = params;
1950
+ const target = await managerRow(db, targetManagerKey);
1951
+ if (target == null) {
1952
+ log('Manager %s already absent; skipping removal', targetManagerKey);
1953
+ return;
1954
+ }
1955
+ const tag = byManagerKeyPair.publicKeyB64 === targetManagerKey ? 'resign' : 'remove';
1956
+ if (tag === 'resign' && await strandTableCount(db, 'Manager') === 1) {
1957
+ throw new Error(
1958
+ 'Cannot resign as the SOLE manager: an ordinary resignation never empties the '
1959
+ + 'Manager table. To permanently freeze admission instead, call sealStrand.',
1960
+ );
1961
+ }
1962
+ const signature = signStrandApproval(
1963
+ ['Strand.Manager', tag, targetManagerKey, target.stampId],
1964
+ byManagerKeyPair.privateKeyB64,
1965
+ );
1966
+ await execStrandTransaction(
1967
+ db,
1968
+ managerRemovalStatements(byManagerKeyPair, signature, targetManagerKey, target.stampId),
1969
+ options,
1970
+ );
1971
+ log('Removed manager %s by %s', targetManagerKey, byManagerKeyPair.publicKeyB64);
1972
+ }
1973
+
1974
+ /**
1975
+ * The `Strand.Manager` delete plus its tombstone, shared by {@link removeManager} and
1976
+ * {@link sealStrand}, which differ only in the action tag `signature` was minted under.
1977
+ */
1978
+ function managerRemovalStatements(
1979
+ signer: Ed25519KeyPair,
1980
+ signature: string,
1981
+ targetManagerKey: string,
1982
+ targetStampId: string,
1983
+ ): StrandStatements {
1984
+ const removal: StrandStatements = {
1985
+ sql: `delete from Strand.Manager
1986
+ with context ManagerKey = :managerRemoverKey, Signature = :managerRemoverSignature
1987
+ where MemberKey = :managerMemberKey;`,
1988
+ params: {
1989
+ managerRemoverKey: signer.publicKeyB64,
1990
+ managerRemoverSignature: signature,
1991
+ managerMemberKey: targetManagerKey,
1992
+ },
1993
+ };
1994
+ return combineStatements(removal, revocationStatement('Manager', targetStampId, signer));
1995
+ }
1996
+
1997
+ // ── Sealing (the sole manager permanently freezes admission) ──────────────────
1998
+
1999
+ /** Parameters for {@link sealStrand}. */
2000
+ export interface SealStrandParams {
2001
+ /**
2002
+ * The SOLE manager's strand keypair. Its `publicKeyB64` must be the one live
2003
+ * `Strand.Manager` row; it signs the seal-tagged digest over its own key and
2004
+ * live stamp, and files the accompanying tombstone (it is still a committed
2005
+ * member, which is what `Revocation.Authorized` checks).
2006
+ */
2007
+ managerKeyPair: Ed25519KeyPair;
2008
+ }
2009
+
2010
+ /**
2011
+ * Seal the strand: the SOLE manager deliberately steps down, permanently freezing
2012
+ * membership.
2013
+ *
2014
+ * A sealed strand has zero `Manager` rows, and every admission path — issuing or
2015
+ * cancelling an invitation, consuming one issued BEFORE the seal
2016
+ * (`ConsumedInvite.NotSealed`), admitting a member, promoting a manager — requires
2017
+ * one, so nobody can ever be let in again. That freeze is a privacy guarantee to
2018
+ * everyone who contributed: no key holds the power to admit a party who would then
2019
+ * read the strand's whole history. Sealing is irreversible — the founding branch
2020
+ * of `Manager.Authorized` closes for good once any manager stamp is retired into
2021
+ * `Strand.Revocation`. What remains possible: members may {@link leaveStrand}
2022
+ * (floored by `MinOneMember`), manage their own `MemberPeer` rows, and file
2023
+ * `Revocation` tombstones.
2024
+ *
2025
+ * The `'seal'` branch of `Manager.Authorized` accepts a self-signed delete only
2026
+ * when the POST-image manager count is ZERO — a distinct action tag from
2027
+ * `'resign'`, so a captured resignation approval can never seal and a raw writer
2028
+ * cannot seal by accident. Like {@link removeManager}, the delete pairs with its
2029
+ * `Strand.Revocation` tombstone in one transaction.
2030
+ *
2031
+ * The TS count/identity checks below are UX guards, not the trust boundary — the
2032
+ * schema rejects a mis-tagged or mis-counted approval regardless of what this
2033
+ * writer (or any raw writer) presents.
2034
+ *
2035
+ * NOTE: a seal approval is a bearer token for its row incarnation, like every other
2036
+ * self-signed approval here — but the `'seal'` branch's post-image count of 0 is
2037
+ * satisfied for EVERY row deleted in the same transaction, so N managers each
2038
+ * presenting a valid `'seal'` approval seal jointly (pinned as an accepted case in
2039
+ * `strand-seal.spec.ts`). Unreachable today: this writer mints a seal signature only
2040
+ * while its caller is the SOLE manager, and spends it immediately, so a second
2041
+ * manager never has one to combine. If seal-approval MINTING is ever split from
2042
+ * spending — offline signing, a two-phase seal, a queued approval — one manager
2043
+ * holding another's unspent seal approval could freeze the strand irreversibly
2044
+ * without its current consent; re-gate here (or narrow the schema branch) then.
2045
+ *
2046
+ * @param db - The closed strand's database.
2047
+ * @param params - The sole manager's own keypair.
2048
+ * @param options - Whether to join an already-open transaction (see {@link StrandWriteOptions}).
2049
+ * @throws If more than one manager exists (the caller wants {@link removeManager}),
2050
+ * or the supplied keypair holds no `Manager` row while one exists, or the strand
2051
+ * holds no `Manager` row and has never retired one (not founded yet — see
2052
+ * {@link isStrandSealed}), or any schema constraint rejects; the whole
2053
+ * delete+tombstone transaction rolls back. A strand that is ALREADY sealed logs
2054
+ * and returns quietly (restart-safe, matching {@link bootstrapFounderMembership}
2055
+ * and {@link removeManager}'s absent-row no-op).
2056
+ */
2057
+ export async function sealStrand(
2058
+ db: Database,
2059
+ params: SealStrandParams,
2060
+ options?: StrandWriteOptions,
2061
+ ): Promise<void> {
2062
+ const { managerKeyPair } = params;
2063
+ const managerCount = await strandTableCount(db, 'Manager');
2064
+ if (managerCount === 0) {
2065
+ // Zero managers is NOT by itself a seal — a closed strand between its Header
2066
+ // and Manager founding inserts looks identical. The retired `Manager` stamp is
2067
+ // what separates "frozen forever" from "still foundable"; returning quietly on
2068
+ // the latter would report a seal that never happened.
2069
+ if (await strandHasManagerRevocation(db)) {
2070
+ log('Strand already sealed (no Manager rows, manager stamp retired); skipping seal');
2071
+ return;
2072
+ }
2073
+ throw new Error(
2074
+ 'Cannot seal: the strand holds no Manager row and has never retired one — it is '
2075
+ + 'not founded yet, not sealed. Bootstrap the founding manager first.',
2076
+ );
2077
+ }
2078
+ if (managerCount > 1) {
2079
+ throw new Error(
2080
+ `Cannot seal: ${managerCount} managers exist and sealing is the SOLE manager's act. `
2081
+ + 'The other managers must step down first (removeManager).',
2082
+ );
2083
+ }
2084
+ const self = await managerRow(db, managerKeyPair.publicKeyB64);
2085
+ if (self == null) {
2086
+ throw new Error('Cannot seal: the supplied keypair does not hold the sole Manager row.');
2087
+ }
2088
+ const signature = signStrandApproval(
2089
+ ['Strand.Manager', 'seal', managerKeyPair.publicKeyB64, self.stampId],
2090
+ managerKeyPair.privateKeyB64,
2091
+ );
2092
+ await execStrandTransaction(
2093
+ db,
2094
+ managerRemovalStatements(managerKeyPair, signature, managerKeyPair.publicKeyB64, self.stampId),
2095
+ options,
2096
+ );
2097
+ log('Sealed strand: sole manager %s stepped down', managerKeyPair.publicKeyB64);
2098
+ }
2099
+
2100
+ /**
2101
+ * The sApp id the strand's singleton `Strand.Header` names, or `undefined` when no
2102
+ * Header row is held yet. A storage replica reads it to learn which app the strand it
2103
+ * hosts belongs to (`CadreNode.getSAppId`).
2104
+ */
2105
+ export async function readStrandHeaderSAppId(db: Database): Promise<string | undefined> {
2106
+ for await (const row of db.eval('select sAppId from Strand.Header')) {
2107
+ return typeof row.sAppId === 'string' ? row.sAppId : undefined;
2108
+ }
2109
+ return undefined;
2110
+ }
2111
+
2112
+ /**
2113
+ * Whether the strand is `Type = 'c'` (closed). Reads the singleton `Header` via
2114
+ * the same `db.eval` scan idiom as {@link strandTableCount}; a strand with no
2115
+ * `Header` row yet reports `false`.
2116
+ */
2117
+ async function strandIsClosed(db: Database): Promise<boolean> {
2118
+ for await (const row of db.eval('select Type from Strand.Header')) {
2119
+ return row.Type === 'c';
2120
+ }
2121
+ return false;
2122
+ }
2123
+
2124
+ /**
2125
+ * Whether the strand is sealed: a CLOSED strand that holds no `Manager` rows AND
2126
+ * has retired at least one `Manager` stamp into `Strand.Revocation`.
2127
+ *
2128
+ * All three conjuncts are load-bearing:
2129
+ * - `Header.Type` — an OPEN strand never holds `Manager` rows at all
2130
+ * (`Manager.OnlyClosed`), so a bare manager-count test would report every open
2131
+ * strand as sealed.
2132
+ * - the manager count — sealing IS the empty `Manager` table.
2133
+ * - the retired `Manager` stamp — "sealed" means admission is frozen FOREVER, and
2134
+ * what makes it permanent is the founding branch of `Manager.Authorized`
2135
+ * refusing to re-seat a generation-0 manager once any `Manager` stamp has been
2136
+ * retired. Without this conjunct a closed strand that is merely NOT FOUNDED YET
2137
+ * reads as sealed: {@link bootstrapFounderMembership} commits `Header`,
2138
+ * `Member` and `Manager` as three sequential statements, so the window between
2139
+ * the first and the last is exactly "closed, zero managers, still foundable".
2140
+ *
2141
+ * Reads locally visible rows — a node that has not yet converged on the seal
2142
+ * still reports `false` (the schema's seal-propagation NOTE).
2143
+ *
2144
+ * @param db - The strand's database.
2145
+ * @returns `true` iff the strand is closed, holds zero `Manager` rows, and has
2146
+ * permanently closed its founding branch.
2147
+ */
2148
+ export async function isStrandSealed(db: Database): Promise<boolean> {
2149
+ return await strandIsClosed(db)
2150
+ && await strandTableCount(db, 'Manager') === 0
2151
+ && await strandHasManagerRevocation(db);
2152
+ }