@serfab/cadre-core 1.23.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 (313) 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 +145 -44
  8. package/dist/cadre-node.js +239 -79
  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 +2 -2
  82. package/dist/node-claim-payload.d.ts +15 -7
  83. package/dist/node-claim-payload.js +25 -9
  84. package/dist/node-claim-payload.js.map +1 -1
  85. package/dist/node-class.d.ts +36 -0
  86. package/dist/node-class.js +26 -0
  87. package/dist/node-class.js.map +1 -0
  88. package/dist/node-default-transports.d.ts +50 -3
  89. package/dist/node-default-transports.js +48 -3
  90. package/dist/node-default-transports.js.map +1 -1
  91. package/dist/node-roles.d.ts +118 -0
  92. package/dist/node-roles.js +142 -0
  93. package/dist/node-roles.js.map +1 -0
  94. package/dist/node-transports.d.ts +6 -2
  95. package/dist/node-transports.js +39 -7
  96. package/dist/node-transports.js.map +1 -1
  97. package/dist/owner-anchor-sync.js +1 -1
  98. package/dist/owner-key-export.js +1 -1
  99. package/dist/owner-key-flows.d.ts +1 -1
  100. package/dist/owner-key-store.js +1 -1
  101. package/dist/owner-signer.js +1 -1
  102. package/dist/peer-authorization.d.ts +3 -1
  103. package/dist/peer-authorization.js +3 -1
  104. package/dist/peer-authorization.js.map +1 -1
  105. package/dist/peer-dial.d.ts +74 -10
  106. package/dist/peer-dial.js +89 -17
  107. package/dist/peer-dial.js.map +1 -1
  108. package/dist/peer-join-backfill.js +4 -4
  109. package/dist/peer-join-backfill.js.map +1 -1
  110. package/dist/peer-record.d.ts +34 -9
  111. package/dist/peer-record.js +66 -13
  112. package/dist/peer-record.js.map +1 -1
  113. package/dist/pending-join-runner.d.ts +1 -1
  114. package/dist/pending-join-runner.js +1 -1
  115. package/dist/provider/client.d.ts +6 -5
  116. package/dist/provider/client.js +3 -3
  117. package/dist/provider/client.js.map +1 -1
  118. package/dist/provider/descriptor.d.ts +1 -1
  119. package/dist/provider/descriptor.js +1 -1
  120. package/dist/provider/oauth.d.ts +1 -1
  121. package/dist/provider/oauth.js +1 -1
  122. package/dist/provider/rent-node.d.ts +4 -3
  123. package/dist/provider/rent-node.js +3 -3
  124. package/dist/provider/rent-node.js.map +1 -1
  125. package/dist/relay-addrs.d.ts +62 -7
  126. package/dist/relay-addrs.js +74 -11
  127. package/dist/relay-addrs.js.map +1 -1
  128. package/dist/relay-reservation.d.ts +1 -1
  129. package/dist/relay-reservation.js +1 -1
  130. package/dist/relay-server.d.ts +6 -5
  131. package/dist/relay-server.js +5 -5
  132. package/dist/relay-server.js.map +1 -1
  133. package/dist/schema-verification.d.ts +13 -10
  134. package/dist/schema-verification.js +32 -24
  135. package/dist/schema-verification.js.map +1 -1
  136. package/dist/sealed-party-key.js +1 -1
  137. package/dist/seed-bootstrap.d.ts +4 -3
  138. package/dist/seed-bootstrap.js +6 -7
  139. package/dist/seed-bootstrap.js.map +1 -1
  140. package/dist/strand-addr-protocol.d.ts +8 -6
  141. package/dist/strand-addr-protocol.js +12 -10
  142. package/dist/strand-addr-protocol.js.map +1 -1
  143. package/dist/strand-app-schema-report.d.ts +16 -2
  144. package/dist/strand-app-schema-report.js +15 -0
  145. package/dist/strand-app-schema-report.js.map +1 -1
  146. package/dist/strand-cohort.d.ts +1 -4
  147. package/dist/strand-cohort.js.map +1 -1
  148. package/dist/strand-commit-durability.d.ts +1 -1
  149. package/dist/strand-database.d.ts +13 -6
  150. package/dist/strand-database.js +17 -9
  151. package/dist/strand-database.js.map +1 -1
  152. package/dist/strand-first-sync-gate.d.ts +3 -2
  153. package/dist/strand-first-sync-gate.js +3 -2
  154. package/dist/strand-first-sync-gate.js.map +1 -1
  155. package/dist/strand-formation-deadlines.d.ts +2 -2
  156. package/dist/strand-formation-deadlines.js +2 -2
  157. package/dist/strand-formation-protocol.d.ts +1 -1
  158. package/dist/strand-formation-protocol.js +51 -16
  159. package/dist/strand-formation-protocol.js.map +1 -1
  160. package/dist/strand-instance-manager.d.ts +67 -33
  161. package/dist/strand-instance-manager.js +164 -55
  162. package/dist/strand-instance-manager.js.map +1 -1
  163. package/dist/strand-membership-reconciler.d.ts +8 -3
  164. package/dist/strand-membership-reconciler.js +8 -3
  165. package/dist/strand-membership-reconciler.js.map +1 -1
  166. package/dist/strand-membership-writer.d.ts +2 -2
  167. package/dist/strand-membership-writer.js +41 -39
  168. package/dist/strand-membership-writer.js.map +1 -1
  169. package/dist/strand-move.js +1 -1
  170. package/dist/strand-network-config.d.ts +15 -5
  171. package/dist/strand-network-config.js +7 -6
  172. package/dist/strand-network-config.js.map +1 -1
  173. package/dist/strand-party-key-rotation.d.ts +7 -3
  174. package/dist/strand-party-key-rotation.js +7 -3
  175. package/dist/strand-party-key-rotation.js.map +1 -1
  176. package/dist/strand-party-machines.d.ts +19 -8
  177. package/dist/strand-party-machines.js +26 -11
  178. package/dist/strand-party-machines.js.map +1 -1
  179. package/dist/strand-party-peers.d.ts +36 -14
  180. package/dist/strand-party-peers.js +24 -15
  181. package/dist/strand-party-peers.js.map +1 -1
  182. package/dist/strand-peer-redial.d.ts +1 -1
  183. package/dist/strand-peer-redial.js +1 -1
  184. package/dist/strand-reactivity.d.ts +20 -17
  185. package/dist/strand-reactivity.js +31 -18
  186. package/dist/strand-reactivity.js.map +1 -1
  187. package/dist/strand-revocation-enforcer.d.ts +3 -3
  188. package/dist/strand-revocation-enforcer.js +3 -3
  189. package/dist/strand-wake-protocol.d.ts +19 -7
  190. package/dist/strand-wake-protocol.js +22 -10
  191. package/dist/strand-wake-protocol.js.map +1 -1
  192. package/dist/strand-watcher.d.ts +1 -1
  193. package/dist/strand-watcher.js +1 -1
  194. package/dist/table-change-watch.js +1 -1
  195. package/dist/types.d.ts +116 -55
  196. package/dist/types.js.map +1 -1
  197. package/dist/webrtc-upgrade.d.ts +254 -0
  198. package/dist/webrtc-upgrade.js +355 -0
  199. package/dist/webrtc-upgrade.js.map +1 -0
  200. package/package.json +9 -9
  201. package/src/announce-addrs.ts +93 -93
  202. package/src/arachnode-stub.ts +18 -10
  203. package/src/bootstrap-peer-store-file.ts +44 -44
  204. package/src/bootstrap-peer-store.ts +214 -214
  205. package/src/cadre-invite-protocol.ts +741 -740
  206. package/src/cadre-node.ts +12462 -12280
  207. package/src/claim-proof.ts +147 -147
  208. package/src/control-authorization.ts +290 -276
  209. package/src/control-cohort.ts +223 -204
  210. package/src/control-database.ts +72 -28
  211. package/src/control-formation-recorder.ts +359 -359
  212. package/src/control-protocol-guard.ts +370 -366
  213. package/src/control-read-retry.ts +222 -180
  214. package/src/control-retry.ts +36 -4
  215. package/src/control-schema-version.ts +301 -301
  216. package/src/control-schema.ts +1108 -1087
  217. package/src/control-write-retry.ts +639 -669
  218. package/src/delegate-admission.ts +351 -351
  219. package/src/describe-thrown.ts +60 -60
  220. package/src/ed25519-key.ts +185 -185
  221. package/src/edge-node/config.ts +13 -10
  222. package/src/edge-node/dissolve.ts +252 -252
  223. package/src/edge-node/edge-join.ts +320 -320
  224. package/src/edge-node/edge-node.ts +1095 -1095
  225. package/src/edge-node/index.ts +60 -59
  226. package/src/edge-node/join-credential.ts +16 -16
  227. package/src/edge-node/lazy-raw-storage.ts +194 -178
  228. package/src/edge-node/listen-addrs.ts +26 -0
  229. package/src/edge-node/node-local.ts +84 -84
  230. package/src/edge-node/options.ts +195 -195
  231. package/src/edge-node/owner-grant.ts +63 -63
  232. package/src/edge-node/platform.ts +5 -4
  233. package/src/edge-node/strand-move.ts +266 -266
  234. package/src/edge-node/strands.ts +27 -12
  235. package/src/enrolled-machine-store-file.ts +43 -43
  236. package/src/enrolled-machine-store.ts +280 -280
  237. package/src/fetch-impl.ts +23 -23
  238. package/src/file-durable-slot.ts +64 -64
  239. package/src/file-safe-name.ts +32 -32
  240. package/src/formation-approval.ts +604 -604
  241. package/src/formation-token.ts +63 -63
  242. package/src/fs-atomic.ts +92 -92
  243. package/src/index.ts +987 -957
  244. package/src/invitation-bootstrap.ts +152 -118
  245. package/src/joined-strand-store.ts +553 -553
  246. package/src/key-store-file.ts +142 -142
  247. package/src/link-budget.ts +61 -5
  248. package/src/machine-removal.ts +211 -210
  249. package/src/member-redemption.ts +643 -643
  250. package/src/membership-connection-gater.ts +650 -650
  251. package/src/membership-view.ts +147 -147
  252. package/src/node-claim-payload.ts +34 -12
  253. package/src/node-class.ts +47 -0
  254. package/src/node-default-transports.ts +65 -3
  255. package/src/node-roles.ts +220 -0
  256. package/src/node-transports.ts +86 -49
  257. package/src/owner-anchor-sync.ts +172 -172
  258. package/src/owner-grant-protocol.ts +547 -547
  259. package/src/owner-key-export.ts +348 -348
  260. package/src/owner-key-flows.ts +109 -109
  261. package/src/owner-key-store.ts +1 -1
  262. package/src/owner-keys.ts +179 -179
  263. package/src/owner-signer.ts +92 -92
  264. package/src/peer-addr-book.ts +252 -252
  265. package/src/peer-authorization.ts +584 -582
  266. package/src/peer-dial.ts +698 -605
  267. package/src/peer-join-backfill.ts +961 -961
  268. package/src/peer-record.ts +71 -16
  269. package/src/pending-join-runner.ts +798 -798
  270. package/src/primary-lan-address.ts +47 -47
  271. package/src/provider/client.ts +327 -326
  272. package/src/provider/descriptor.ts +129 -129
  273. package/src/provider/index.ts +59 -59
  274. package/src/provider/oauth.ts +285 -285
  275. package/src/provider/rent-node.ts +276 -275
  276. package/src/relay-addrs.ts +90 -12
  277. package/src/relay-reservation.ts +1 -1
  278. package/src/relay-server.ts +99 -98
  279. package/src/schema-verification.ts +38 -23
  280. package/src/sealed-party-key.ts +190 -190
  281. package/src/seed-bootstrap.ts +8 -11
  282. package/src/seed-trust-policy.ts +353 -353
  283. package/src/self-address-update.ts +19 -19
  284. package/src/strand-addr-protocol.ts +17 -14
  285. package/src/strand-app-schema-report.ts +147 -122
  286. package/src/strand-cohort.ts +1 -5
  287. package/src/strand-commit-durability.ts +165 -165
  288. package/src/strand-database.ts +522 -510
  289. package/src/strand-first-sync-gate.ts +3 -2
  290. package/src/strand-formation-deadlines.ts +227 -227
  291. package/src/strand-formation-manager.ts +731 -731
  292. package/src/strand-formation-protocol.ts +1174 -1138
  293. package/src/strand-fret-addrs.ts +179 -179
  294. package/src/strand-instance-manager.ts +188 -63
  295. package/src/strand-membership-reconciler.ts +1315 -1310
  296. package/src/strand-membership-writer.ts +2152 -2150
  297. package/src/strand-move.ts +1 -1
  298. package/src/strand-network-config.ts +16 -6
  299. package/src/strand-offline.ts +178 -178
  300. package/src/strand-party-key-rotation.ts +440 -436
  301. package/src/strand-party-machines.ts +308 -293
  302. package/src/strand-party-peers.ts +151 -129
  303. package/src/strand-peer-redial.ts +1 -1
  304. package/src/strand-reactivity.ts +36 -19
  305. package/src/strand-revocation-enforcer.ts +758 -758
  306. package/src/strand-wake-protocol.ts +406 -394
  307. package/src/strand-watcher.ts +1 -1
  308. package/src/table-change-watch.ts +285 -285
  309. package/src/timed-step.ts +28 -28
  310. package/src/timeout-scheduler.ts +29 -29
  311. package/src/trusted-owner-store.ts +242 -242
  312. package/src/types.ts +3182 -3121
  313. package/src/webrtc-upgrade.ts +439 -0
@@ -1,1087 +1,1108 @@
1
- import { Parser } from '@quereus/quereus';
2
-
3
- /**
4
- * The version of the declared control schema, carried in the schema text as the
5
- * {@link CONTROL_SCHEMA_VERSION_TAG} tag on the `OwnerKey` table. A warm start compares
6
- * it with the version the store records before applying anything, and the apply then
7
- * migrates the store to this version and records it (`control-schema-version.ts`).
8
- *
9
- * When it changes, what a new version may change, and the fixture each version keeps:
10
- * docs/architecture.md → "Control schema versions and migrations", enforced by
11
- * `control-schema-versions.spec.ts`.
12
- */
13
- export const CONTROL_SCHEMA_VERSION = 4;
14
-
15
- /**
16
- * The first control schema version whose fixture is kept, and the oldest a store can be
17
- * migrated from. A store that records a version below it (written by 1.16.0 and earlier,
18
- * which recorded none) is refused with reason `before-migrations`; docs/architecture.md
19
- * says why it is not migrated.
20
- */
21
- export const CONTROL_SCHEMA_BASELINE_VERSION = 3;
22
-
23
- /** The `OwnerKey` table tag that records {@link CONTROL_SCHEMA_VERSION} in the schema and in every store. */
24
- export const CONTROL_SCHEMA_VERSION_TAG = 'sereus.controlSchemaVersion';
25
-
26
- /**
27
- * The `declare schema CadreControl { … }` statement, with its header comment.
28
- *
29
- * Together with {@link APPLY_CONTROL_SCHEMA} this is the authoritative runtime copy of
30
- * the CadreControl authorization schema ({@link CONTROL_SCHEMA}). It is duplicated from
31
- * `schemas/control.qsql` so that React Native and other filesystem-less environments
32
- * get the schema without a runtime file read. Held apart from the apply because
33
- * `ControlDatabase.loadSchema` declares, checks the pending changes, and only then
34
- * applies.
35
- *
36
- * The two copies MUST stay identical — `control-schema-drift.spec.ts` fails the
37
- * build if they drift. Any edit here must be mirrored in `schemas/control.qsql`
38
- * and vice versa.
39
- */
40
- export const CONTROL_SCHEMA_DECLARATION = `-- A Sereus party's cadre (its nodes) and their participation in strands (networks).
41
- --
42
- -- Every write is authorized by a check: an owner signs an action-tagged digest of the row
43
- -- (cadre-core control-authorization.ts), or a peer signs its own record. Each digest leads
44
- -- with a 'CadreControl.<Table>' domain tag, an action tag and party_id(), the party this
45
- -- machine is configured for (a zero-argument function ControlDatabase registers on its own
46
- -- engine, never read from a context value or a replicated table), so an approval verifies
47
- -- only against the one rule, in the one party, it was minted for: two parties that share
48
- -- an owner key never accept each other's approvals. FormationUsage is the exception, its
49
- -- two digests scoped by the invitation token instead (FormationUsage.Authorized).
50
- --
51
- -- Rows of the guarded tables (OwnerKey, ValidationKey, Strand, StrandPartyKey,
52
- -- PendingStrandPartyKey, JoinedStrand, JoinRequest, CadrePeer, DeviceToken, CadreInvite,
53
- -- OwnerGrant) carry a one-off StampId bound into their add and remove digests. \`unique\` holds
54
- -- over live rows only, so a delete retires
55
- -- the stamp into Revocation in the same transaction (RevocationRecorded) and an insert refuses
56
- -- a retired stamp (NotRevoked): the never-expiring add approval cannot re-seat a removed row.
57
- -- A legitimate re-add mints a fresh stamp and a fresh signature. CadreInvite and OwnerGrant
58
- -- are the two guarded tables that are never deleted: a tombstone there withdraws the
59
- -- invitation or grant while the row stays, because the rows it admitted prove themselves
60
- -- through it.
61
- --
62
- -- A check whose expression evaluates to null passes (SQL three-valued logic), so every
63
- -- comparison over a nullable column that is meant to pin a value is written null-safe
64
- -- (\`coalesce(col, '')\` or an explicit \`is null\`); a bare \`new.Col = context.X\` over a null
65
- -- column would pass with nothing pinned.
66
- --
67
- -- A check with a subquery defers to commit, so a sibling row written in the same transaction
68
- -- is visible to it; \`committed.<Table>\` reads the pre-transaction snapshot instead. Every
69
- -- check reads the rows this node holds: a node that has not converged on a Revocation row
70
- -- still accepts the replayed add, and the resurrected row then coexists with its tombstone.
71
- -- ControlDatabase drops retired stamps on the reads that matter (queryCadrePeers,
72
- -- queryPendingJoins, getOwnerKeys), and every owner lookup in the checks below drops them
73
- -- too (the \`not exists ... Revocation\` conjunct beside each OwnerKey read, reading live
74
- -- Revocation so a tombstone filed in the same transaction counts), so a removal is
75
- -- effective at the writer as soon as its tombstone arrives, whether or not the row's delete
76
- -- has. Only the founding count in OwnerKey.Authorized stays raw.
77
- declare schema CadreControl {
78
- -- A key that can authorize control changes. A row is seated one of three ways, told apart
79
- -- by the vouch columns: the founding row (all three null), an owner-signed add (VouchOwner
80
- -- and VouchSig pinned to the insert context, VouchUsage null), or an owner grant redeemed
81
- -- by consent (VouchOwner = the grant's IssuerKey, VouchSig null, VouchUsage = the
82
- -- OwnerGrantUsage row that seated it). A machine invitation (CadreInvite) admits a machine
83
- -- and never seats a row here: a machine's identity key is never an owner key. A reader
84
- -- judges the stored proof against its node-local anchor, never against this replicated
85
- -- table.
86
- table OwnerKey (
87
- Key text primary key,
88
- Label text null, -- the user's name for the key ("phone", "paper backup"); bound into the
89
- -- signed add, so a relayed approval cannot seat the key under another name
90
- StampId text unique,
91
- VouchOwner text null,
92
- VouchSig text null,
93
- VouchUsage text null,
94
- constraint NotRevoked check on insert (
95
- not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = new.StampId)
96
- ),
97
- -- Never empty: the add digest binds coalesce(Label, ''), so an empty label would sign as none.
98
- constraint LabelLength check (
99
- Label is null or length(Label) between 1 and 64
100
- ),
101
- -- The tombstone must name the removed row, not just its stamp (Revocation.RowKey).
102
- constraint RevocationRecorded check on delete (
103
- exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = old.StampId and R.RowKey = old.Key)
104
- ),
105
- -- Every other table's checks require an owner, so an empty table is a permanent denial of
106
- -- the party's control plane. Counted post-delete, on this node's rows only: two partitioned
107
- -- nodes removing different owners can still converge to zero.
108
- constraint MinOneOwner check on delete (
109
- (select count(1) from OwnerKey) >= 1
110
- ),
111
- -- Rotation is add-then-remove. An update branch would let the sole owner be re-pointed at
112
- -- another key under a post-image count of one.
113
- constraint NoUpdate check on update (false),
114
- -- The authorizer is read from the pre-transaction snapshot: the check defers to commit, by
115
- -- which point the inserted row (and any sibling) is live, so a plain OwnerKey read would let
116
- -- a row authorize itself or two strangers seat each other. The founding transaction, whose
117
- -- pre-transaction owner set is empty, needs no authorization; gating on the pre-transaction
118
- -- count keeps a same-transaction swap of the sole owner off that branch. That count is
119
- -- deliberately raw, the one owner read here that ignores Revocation: a machine holding only
120
- -- a retired owner row must still be refused a second genesis, or a removed device could
121
- -- re-found the party on its own copy. An owner cannot sign its own removal.
122
- -- The consent branch seats an owner with no signature at all: an OwnerGrantUsage row
123
- -- written in the same transaction names this exact row (Key and stamp), and the grant
124
- -- it redeemed was issued by the stored VouchOwner and carries the row's label (the
125
- -- issuer's choice, bound into the grant's signature). The grant is read from its
126
- -- committed table, so it cannot be seated and redeemed in one transaction; the usage
127
- -- row carries the liveness conditions.
128
- constraint Authorized check on insert, delete (
129
- (old.Key is null and (select count(1) from committed.OwnerKey) = 0
130
- and new.VouchOwner is null and new.VouchSig is null and new.VouchUsage is null)
131
- or (old.Key is null and exists (select 1 from committed.OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.OwnerKey', 'add', party_id(), new.Key, coalesce(new.Label, ''), new.StampId), context.Signature, A.Key, 'ed25519'))
132
- and coalesce(new.VouchOwner, '') = context.OwnerKey
133
- and coalesce(new.VouchSig, '') = context.Signature
134
- and new.VouchUsage is null)
135
- or (old.Key is null and new.VouchSig is null and new.VouchUsage is not null
136
- and exists (
137
- select 1 from OwnerGrantUsage U
138
- where U.UsageStampId = new.VouchUsage
139
- and U.SeatedKey = new.Key
140
- and U.SeatedStampId = new.StampId
141
- and exists (select 1 from committed.OwnerGrant G
142
- where G.Key = U.GrantKey and G.IssuerKey = new.VouchOwner
143
- and coalesce(G.Label, '') = coalesce(new.Label, ''))
144
- ))
145
- or (new.Key is null and exists (select 1 from committed.OwnerKey A where A.Key = context.OwnerKey and A.Key <> old.Key and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.OwnerKey', 'remove', party_id(), old.Key, old.StampId), context.Signature, A.Key, 'ed25519')))
146
- )
147
- -- The tag is the version of this whole schema (cadre-core CONTROL_SCHEMA_VERSION): every edit
148
- -- to the schema bumps it, and a warm start reads the store's copy before applying anything.
149
- ) with tags ("${CONTROL_SCHEMA_VERSION_TAG}" = ${CONTROL_SCHEMA_VERSION}) with context (OwnerKey text null, Signature text null);
150
-
151
- -- A key that can validate a strand formation disclosure (FormationUsage.Authorized).
152
- table ValidationKey (
153
- Key text primary key,
154
- StampId text unique,
155
- constraint NotRevoked check on insert (
156
- not exists (select 1 from Revocation R where R.TableName = 'ValidationKey' and R.StampId = new.StampId)
157
- ),
158
- constraint RevocationRecorded check on delete (
159
- exists (select 1 from Revocation R where R.TableName = 'ValidationKey' and R.StampId = old.StampId and R.RowKey = old.Key)
160
- ),
161
- constraint NoUpdate check on update (false),
162
- constraint AuthorizedInsert check on insert (
163
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.ValidationKey', 'add', party_id(), new.Key, new.StampId), context.Signature, A.Key, 'ed25519'))
164
- ),
165
- -- Owner-signed over the stored row, or a reap: a committed tombstone naming this exact row
166
- -- incarnation lets a node that was offline at removal time delete the stale row unsigned
167
- -- (ControlDatabase.reapRevokedRow). committed.*, so a tombstone filed in this transaction
168
- -- cannot stand in for the signature; the stamp clause, so a tombstone of an earlier
169
- -- incarnation cannot remove the current one.
170
- constraint AuthorizedDelete check on delete (
171
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.ValidationKey', 'remove', party_id(), old.Key, old.StampId), context.Signature, A.Key, 'ed25519'))
172
- or exists (select 1 from committed.Revocation R where R.TableName = 'ValidationKey' and R.RowKey = old.Key and R.StampId = old.StampId)
173
- )
174
- ) with context (OwnerKey text, Signature text);
175
-
176
- -- A network of members sharing an sApp database, each contributing its cadre's peers. This
177
- -- party's own strands; a strand joined from another party is a JoinedStrand row.
178
- table Strand (
179
- Id text primary key, -- UUID
180
- MemberPrivateKey text null unique, -- the strand's shared read secret; closed strands only
181
- Type text, -- 'o' open | 'c' closed: open gates writes in the sApp, only closed gates reads
182
- FounderOwnerKey text null, -- the owner key that signed the insert; null on a consent-seated strand,
183
- -- whose insert carries no signature. Provenance, not content (strandRowMismatches).
184
- FounderPeerId text null, -- peer id of the machine that runs the founder bootstrap (cadre-node.ts
185
- -- launchStrand), bound into the signed add; null on a consent-seated strand.
186
- -- Not pinned to a CadrePeer row: a solo founder publishes before its own
187
- -- row exists, and only an owner can name it. Provenance, as FounderOwnerKey.
188
- StampId text unique,
189
- constraint NotRevoked check on insert (
190
- not exists (select 1 from Revocation R where R.TableName = 'Strand' and R.StampId = new.StampId)
191
- ),
192
- constraint RevocationRecorded check on delete (
193
- exists (select 1 from Revocation R where R.TableName = 'Strand' and R.StampId = old.StampId and R.RowKey = old.Id)
194
- ),
195
- -- The consent branch below carries no signature, so an update rule would let anyone rewrite
196
- -- a consent-seated strand.
197
- constraint NoUpdate check on update (false),
198
- -- Owner-signed, with FounderOwnerKey pinned to the verified signer and FounderPeerId bound
199
- -- into the signature; or consent-seated by a FormationUsage row naming this exact row (id
200
- -- and stamp), written in the same transaction (ControlDatabase.redeemInvitation). Binding
201
- -- the stamp is what makes a removal stick:
202
- -- the usage row outlives the strand, and keyed on the id alone it would re-authorize an
203
- -- unsigned re-seat under a fresh stamp. The consent branch is narrow, each clause closing
204
- -- one door:
205
- -- * open and keyless: a closed strand with a caller-chosen read secret has no legitimate
206
- -- producer;
207
- -- * through an unbound invite only: a bound invite's host strand is owner-provisioned,
208
- -- and consent-seating its id would downgrade the real row on a node it has not reached;
209
- -- * no usage row under another stamp, and no tombstone for the id: an id is consent-seated
210
- -- once, ever, and never after any removal. Re-joining a removed id is owner-signed.
211
- -- A standalone tombstone (no accompanying delete, Revocation.Authorized) lets an owner
212
- -- foreclose consent-seating of an id that never existed: owner-only, and ids are random.
213
- constraint AuthorizedInsert check on insert (
214
- (exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.Strand', 'add', party_id(), new.Id, new.Type, coalesce(new.MemberPrivateKey, ''), new.FounderPeerId, new.StampId), context.Signature, A.Key, 'ed25519'))
215
- and new.FounderOwnerKey = context.OwnerKey
216
- and new.FounderPeerId is not null)
217
- or (
218
- new.Type = 'o'
219
- and new.MemberPrivateKey is null
220
- and new.FounderOwnerKey is null
221
- and new.FounderPeerId is null
222
- and exists (
223
- select 1 from FormationUsage FU
224
- where FU.StrandId = new.Id
225
- and FU.StrandStampId = new.StampId
226
- and exists (select 1 from FormationInvite FI where FI.Token = FU.Token and FI.StrandId is null)
227
- )
228
- and not exists (
229
- select 1 from FormationUsage FU2
230
- where FU2.StrandId = new.Id and FU2.StrandStampId <> new.StampId
231
- )
232
- and not exists (
233
- select 1 from Revocation R
234
- where R.TableName = 'Strand' and R.RowKey = new.Id
235
- )
236
- )
237
- ),
238
- -- No consent branch (an invitation forms a strand, never destroys one) and no reap branch:
239
- -- MemberPrivateKey is stored nowhere else, so this delete is unrecoverable
240
- -- (tickets/backlog/debt-strand-tombstone-reap.md owns any change).
241
- constraint AuthorizedDelete check on delete (
242
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.Strand', 'remove', party_id(), old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))
243
- ),
244
- -- An open strand has no membership gate, so no member key.
245
- constraint MemberKeyClosedOnly check (
246
- new.MemberPrivateKey is null or new.Type = 'c'
247
- )
248
- ) with context (OwnerKey text, Signature text);
249
-
250
- -- This party's own membership identity for one strand: the private key whose public half
251
- -- seats its Strand.Member / Strand.Manager rows. Separate from Strand.MemberPrivateKey, which
252
- -- every joining party receives and so could forge (gotchoices/sereus#4). A side table because
253
- -- a joiner holds no Strand row. Replicated in plaintext to every machine the party owns
254
- -- (docs/strands.md → "Closed-Strand Member Key Handling") but never put on the formation wire.
255
- table StrandPartyKey (
256
- Id text primary key, -- the strand id
257
- PrivateKey text, -- ed25519, base64 protobuf, as Strand.MemberPrivateKey (cadre-core strandMemberKeyPair)
258
- StampId text unique,
259
- constraint NotRevoked check on insert (
260
- not exists (select 1 from Revocation R where R.TableName = 'StrandPartyKey' and R.StampId = new.StampId)
261
- ),
262
- constraint RevocationRecorded check on delete (
263
- exists (select 1 from Revocation R where R.TableName = 'StrandPartyKey' and R.StampId = old.StampId and R.RowKey = old.Id)
264
- ),
265
- constraint NoUpdate check on update (false),
266
- -- Binding PrivateKey means a captured approval can only reproduce the key it approved.
267
- constraint AuthorizedInsert check on insert (
268
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.StrandPartyKey', 'add', party_id(), new.Id, new.PrivateKey, new.StampId), context.Signature, A.Key, 'ed25519'))
269
- ),
270
- -- No reap branch: the key is stored nowhere else (as Strand.AuthorizedDelete).
271
- constraint AuthorizedDelete check on delete (
272
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.StrandPartyKey', 'remove', party_id(), old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))
273
- )
274
- ) with context (OwnerKey text, Signature text);
275
-
276
- -- The key this party's membership in one closed strand is moving to, while the move is under
277
- -- way. It is written before the strand is touched and swapped into StrandPartyKey only after
278
- -- the strand-side work is done: seating a fresh key and crashing before the control row changes
279
- -- would leave a manager seat nobody holds, and changing the control row first would delete the
280
- -- only copy of the old key, which the seating needs. A table of its own because StrandPartyKey
281
- -- is keyed on the strand id alone and NoUpdate. Guarded as StrandPartyKey is, with no reap
282
- -- branch for the same reason: the key is stored nowhere else.
283
- -- NOTE: unlike a tombstone (Revocation.ReissuedAt), a pending row committed while the remover
284
- -- was alone has no re-issue path, so a remover that removes alone and is lost before its
285
- -- rotations finish loses the rows with it. If that ever matters, give this table that idiom.
286
- table PendingStrandPartyKey (
287
- Id text primary key, -- the strand id
288
- PublicKey text, -- the key being moved to, public half (base64url): the Strand.Member.Key it is seated as.
289
- -- In the clear so a second removal lists it in Superseded without opening the row.
290
- SealedKey text, -- its private half (StrandPartyKey.PrivateKey encoding), sealed to the identity keys of the
291
- -- machines that remain (sealed-party-key.ts): the row is written in the removed machine's last
292
- -- control transaction and reaches it, so what it carries must open only for the others.
293
- Superseded text null, -- comma-joined public keys (base64url) of earlier pending keys this row replaced.
294
- -- A second removal replaces the row because the old key may have reached the
295
- -- machine it removes, and a seat that key already holds must then be revoked.
296
- StampId text unique,
297
- constraint NotRevoked check on insert (
298
- not exists (select 1 from Revocation R where R.TableName = 'PendingStrandPartyKey' and R.StampId = new.StampId)
299
- ),
300
- constraint RevocationRecorded check on delete (
301
- exists (select 1 from Revocation R where R.TableName = 'PendingStrandPartyKey' and R.StampId = old.StampId and R.RowKey = old.Id)
302
- ),
303
- constraint NoUpdate check on update (false),
304
- -- Binding Superseded as well as the key: a captured approval cannot drop a key from the list.
305
- constraint AuthorizedInsert check on insert (
306
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.PendingStrandPartyKey', 'add', party_id(), new.Id, new.PublicKey, new.SealedKey, coalesce(new.Superseded, ''), new.StampId), context.Signature, A.Key, 'ed25519'))
307
- ),
308
- constraint AuthorizedDelete check on delete (
309
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.PendingStrandPartyKey', 'remove', party_id(), old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))
310
- )
311
- ) with context (OwnerKey text, Signature text);
312
-
313
- -- A strand this party joined from another party, whose control database holds the Strand
314
- -- row. Every machine of the party reads it, so a replica host keeps a copy and the party's
315
- -- other machines can attach. A separate table because every reader of Strand takes it to
316
- -- mean this party's own strand. MemberPrivateKey is held by the founding party and every
317
- -- member, so a removed row is recoverable by re-forming, which is why this table has a reap
318
- -- branch (unlike Strand and StrandPartyKey).
319
- table JoinedStrand (
320
- Id text primary key, -- the founder's Strand.Id
321
- Type text, -- 'o' | 'c', as Strand.Type
322
- MemberPrivateKey text null, -- the closed strand's shared read secret
323
- StampId text unique,
324
- constraint NotRevoked check on insert (
325
- not exists (select 1 from Revocation R where R.TableName = 'JoinedStrand' and R.StampId = new.StampId)
326
- ),
327
- constraint RevocationRecorded check on delete (
328
- exists (select 1 from Revocation R where R.TableName = 'JoinedStrand' and R.StampId = old.StampId and R.RowKey = old.Id)
329
- ),
330
- constraint NoUpdate check on update (false),
331
- -- Readers cast Type (ControlDatabase.queryJoinedStrands).
332
- constraint KnownType check (new.Type = 'o' or new.Type = 'c'),
333
- constraint MemberKeyClosedOnly check (new.MemberPrivateKey is null or new.Type = 'c'),
334
- -- Owner-signed only: every always-on machine of the party downloads the strands named
335
- -- here, so a machine that is not an owner keeps its joins machine-local.
336
- constraint AuthorizedInsert check on insert (
337
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.JoinedStrand', 'add', party_id(), new.Id, new.Type, coalesce(new.MemberPrivateKey, ''), new.StampId), context.Signature, A.Key, 'ed25519'))
338
- ),
339
- constraint AuthorizedDelete check on delete (
340
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.JoinedStrand', 'remove', party_id(), old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))
341
- or exists (select 1 from committed.Revocation R where R.TableName = 'JoinedStrand' and R.RowKey = old.Id and R.StampId = old.StampId)
342
- )
343
- ) with context (OwnerKey text, Signature text);
344
-
345
- -- A join this party asked for by redeeming another party's invitation, kept party-wide so
346
- -- the request outlives the device that asked and any owner machine can carry it on
347
- -- (docs/strands.md → "Joining while the inviter is offline"). The row is the request alone
348
- -- and never changes; its outcome is a JoinSuccess or JoinFailure row keyed by this row's
349
- -- stamp, so asking again (a fresh stamp) starts clean and a dismissal's tombstone retires
350
- -- the outcome with the request. Invitation is a bearer credential, replicated in plaintext
351
- -- to every machine the party owns, under the same accepted risk as JoinedStrand.
352
- -- Owner-signed only; whether a machine that is not an owner may write here is
353
- -- tickets/blocked/decide-non-owner-machine-completes-a-pending-join.md.
354
- -- The three tables reference only tables declared before them, so an apply that fails
355
- -- midway can drop them in reverse order. The two rules that would close a cycle are the
356
- -- writer's (ControlDatabase): a request's delete takes its outcome row with it, and a join
357
- -- recorded over a failure deletes the failure. An outcome row left behind is unreadable,
358
- -- since readers start from the request.
359
- table JoinRequest (
360
- Id text primary key, -- base64url sha256 of the invitation token (cadre-core pendingJoinId),
361
- -- so the token never reaches Revocation
362
- Invitation text, -- CadreNode.encodeInvitation
363
- Disclosure text, -- canonicalJson of the disclosure the requester gave
364
- RequestedAt integer, -- epoch ms
365
- ExpiresAt integer, -- epoch ms; no attempt starts at or after it
366
- StampId text unique,
367
- constraint NotRevoked check on insert (
368
- not exists (select 1 from Revocation R where R.TableName = 'JoinRequest' and R.StampId = new.StampId)
369
- ),
370
- constraint RevocationRecorded check on delete (
371
- exists (select 1 from Revocation R where R.TableName = 'JoinRequest' and R.StampId = old.StampId and R.RowKey = old.Id)
372
- ),
373
- constraint NoUpdate check on update (false),
374
- constraint AuthorizedInsert check on insert (
375
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
376
- digest('CadreControl.JoinRequest', 'add', party_id(), new.Id, new.Invitation, new.Disclosure, cast(new.RequestedAt as text), cast(new.ExpiresAt as text), new.StampId),
377
- context.Signature, A.Key, 'ed25519'))
378
- ),
379
- -- Reapable: the inviting party and the user hold the invitation too.
380
- constraint AuthorizedDelete check on delete (
381
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.JoinRequest', 'remove', party_id(), old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))
382
- or exists (select 1 from committed.Revocation R where R.TableName = 'JoinRequest' and R.RowKey = old.Id and R.StampId = old.StampId)
383
- )
384
- ) with context (OwnerKey text null, Signature text null);
385
-
386
- -- The outcome of a JoinRequest that joined: the strand the formation returned and, for a
387
- -- closed strand, the single-use membership invitation it delivered. Keyed by the request's
388
- -- stamp, so it names one request incarnation and a replayed approval can only re-seat the
389
- -- row it approved, against the request it approved. A join is final: it may be recorded
390
- -- over a failure (whose row the writer deletes with it), and nothing is recorded over it.
391
- table JoinSuccess (
392
- RequestStampId text primary key,
393
- RecordedAt integer, -- epoch ms
394
- StrandId text,
395
- MembershipInvite text null, -- JSON {inviteKey, invitePrivateKey}, the StrandMembershipInvite; closed strands only
396
- constraint RequestExists check on insert (
397
- exists (select 1 from JoinRequest R where R.StampId = new.RequestStampId)
398
- ),
399
- constraint NoUpdate check on update (false),
400
- constraint AuthorizedInsert check on insert (
401
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
402
- digest('CadreControl.JoinSuccess', 'add', party_id(), new.RequestStampId, cast(new.RecordedAt as text), new.StrandId, coalesce(new.MembershipInvite, '')),
403
- context.Signature, A.Key, 'ed25519'))
404
- ),
405
- -- Removed only with its request: the tombstone retiring the request's stamp (owner-signed,
406
- -- or already committed for a reap) authorizes this delete.
407
- constraint AuthorizedDelete check on delete (
408
- exists (select 1 from Revocation R where R.TableName = 'JoinRequest' and R.StampId = old.RequestStampId)
409
- )
410
- ) with context (OwnerKey text null, Signature text null);
411
-
412
- -- The outcome of a JoinRequest that failed for good. Keyed as JoinSuccess is.
413
- table JoinFailure (
414
- RequestStampId text primary key,
415
- RecordedAt integer, -- epoch ms
416
- Code text, -- a FormationRejectionCode, 'expired' or 'local'
417
- Reason text, -- human-readable
418
- constraint RequestExists check on insert (
419
- exists (select 1 from JoinRequest R where R.StampId = new.RequestStampId)
420
- ),
421
- -- A join is final: nothing records a failure over it.
422
- constraint NotJoined check on insert (
423
- not exists (select 1 from JoinSuccess S where S.RequestStampId = new.RequestStampId)
424
- ),
425
- constraint NoUpdate check on update (false),
426
- constraint AuthorizedInsert check on insert (
427
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
428
- digest('CadreControl.JoinFailure', 'add', party_id(), new.RequestStampId, cast(new.RecordedAt as text), new.Code, new.Reason),
429
- context.Signature, A.Key, 'ed25519'))
430
- ),
431
- -- Removed with its request (JoinSuccess.AuthorizedDelete), or superseded by a join
432
- -- recorded in the same transaction.
433
- constraint AuthorizedDelete check on delete (
434
- exists (select 1 from Revocation R where R.TableName = 'JoinRequest' and R.StampId = old.RequestStampId)
435
- or exists (select 1 from JoinSuccess S where S.RequestStampId = old.RequestStampId)
436
- )
437
- ) with context (OwnerKey text null, Signature text null);
438
-
439
- -- A node of the cadre, carrying its self-published, freshness-stamped, self-signed address
440
- -- record (cadre-core PeerAddressRecord): a resolver re-verifies Sig against PublicKey,
441
- -- checks UpdatedAt and trust, then dials Multiaddr.
442
- table CadrePeer (
443
- PeerId text primary key,
444
- PublicKey text null, -- ed25519 (base64url) behind PeerId; null if not ed25519
445
- Multiaddr text, -- comma-joined current addrs (signaling / p2p-circuit first)
446
- UpdatedAt int null, -- epoch ms; strictly increases per self-update
447
- Sig text null, -- self-signature over the 'publish' digest; null until self-published
448
- StampId text unique,
449
- VouchOwner text null, -- the owner key that vouched this membership (== insert context.OwnerKey), or
450
- -- the issuer of the invitation that admitted it (CadreInvite.IssuerKey)
451
- VouchSig text null, -- that owner's 'vouch' signature (== insert context.Signature); null on an
452
- -- invitation-admitted row. A reader checks VouchOwner against its node-local
453
- -- trusted-owner anchor, not against this replicated table, which a self-owner
454
- -- can pollute.
455
- VouchUsage text null, -- the CadreInviteUsage.UsageStampId that admitted this row; null on an
456
- -- owner-vouched row. A row carries exactly one proof: a signature or a usage.
457
- Profile text null, -- the machine's own node profile (cadre-core NodeProfile): 'transaction' is an
458
- -- app (phone, browser), 'storage' an always-on node; null until it self-publishes.
459
- -- Self-declared and covered by Sig. No insert rule constrains it: an owner could
460
- -- only mislabel a machine it already has full authority over, and that machine's
461
- -- next self-publish corrects it.
462
- constraint NotRevoked check on insert (
463
- not exists (select 1 from Revocation R where R.TableName = 'CadrePeer' and R.StampId = new.StampId)
464
- ),
465
- constraint KnownProfile check (new.Profile is null or new.Profile in ('transaction', 'storage')),
466
- constraint RevocationRecorded check on delete (
467
- exists (select 1 from Revocation R where R.TableName = 'CadrePeer' and R.StampId = old.StampId and R.RowKey = old.PeerId)
468
- ),
469
- -- The owner vouches membership and the PublicKey<->PeerId binding (cadre-core derives
470
- -- PublicKey from PeerId) over (PeerId, StampId); the stored voucher must be the pair
471
- -- verified here. The same 'vouch' digest serves the owner branch of AuthorizedUpdate:
472
- -- both mean "this owner vouches this membership row".
473
- -- Or admitted by consent: a CadreInviteUsage row written in the same transaction names
474
- -- this exact row incarnation (PeerId, StampId and PublicKey), and the invitation it
475
- -- redeemed, read from committed.CadreInvite, was issued by the stored VouchOwner. The
476
- -- usage row carries the liveness conditions (unexpired, not withdrawn, uses left,
477
- -- issuer still an owner); this branch only requires that it exists. A reader verifies
478
- -- the chain row -> usage -> invitation against its anchor (cadre-core
479
- -- verifyInvitationAdmission), so the invitation row must outlive the rows it admitted.
480
- -- A removed device may redeem a still-live invitation again and come back: keeping a
481
- -- device out is removing its row AND withdrawing the invitation.
482
- constraint AuthorizedInsert check on insert (
483
- (
484
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.CadrePeer', 'vouch', party_id(), new.PeerId, new.StampId), context.Signature, A.Key, 'ed25519'))
485
- and coalesce(new.VouchOwner, '') = context.OwnerKey
486
- and coalesce(new.VouchSig, '') = context.Signature
487
- and new.VouchUsage is null
488
- )
489
- or (
490
- new.VouchSig is null
491
- and new.VouchOwner is not null
492
- and new.VouchUsage is not null
493
- and exists (
494
- select 1 from CadreInviteUsage U
495
- where U.UsageStampId = new.VouchUsage
496
- and U.PeerId = new.PeerId
497
- and U.PeerStampId = new.StampId
498
- and U.PeerKey = new.PublicKey
499
- and exists (select 1 from committed.CadreInvite I where I.Key = U.InviteKey and I.IssuerKey = new.VouchOwner)
500
- )
501
- )
502
- ),
503
- -- The stored 'vouch' voucher never authorizes a delete; the 'remove' signature rides in
504
- -- context and is never stored. Or a reap (ValidationKey.AuthorizedDelete).
505
- constraint AuthorizedDelete check on delete (
506
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.CadrePeer', 'remove', party_id(), old.PeerId, old.StampId), context.Signature, A.Key, 'ed25519'))
507
- or exists (select 1 from committed.Revocation R where R.TableName = 'CadrePeer' and R.RowKey = old.PeerId and R.StampId = old.StampId)
508
- ),
509
- -- A peer re-publishes its own addrs, profile and freshness under its own key (cadre-core
510
- -- peer-record.ts); everything else is immutable and UpdatedAt must increase. Or an owner
511
- -- re-vouches the row over its current stamp, which also clears VouchUsage: the row then
512
- -- stands on the signature and its invitation is no longer consulted for it. The owner
513
- -- branch keeps what the machine itself declares (PublicKey, Multiaddr, Sig, Profile): the
514
- -- row's stored VouchSig is a valid re-vouch signature, so any machine holding the row can
515
- -- take this branch. NOTE: it may still bump UpdatedAt (reauthorizeCadrePeer's re-broadcast
516
- -- needs it), which on a self-published row leaves Sig unverifiable until the machine's
517
- -- next heartbeat re-signs past it; if that window ever matters, pin UpdatedAt here when
518
- -- old.Sig is not null. StampId never
519
- -- changes on update: an update that rotated it would leave the old stamp free and
520
- -- untombstoned, so retiring a stamp is delete plus tombstone. The proof columns are
521
- -- compared null-safe: VouchSig and VouchUsage are null on one of the two row kinds, and a
522
- -- bare \`new.X = old.X\` over a null would let a self-publish fill the column in.
523
- constraint AuthorizedUpdate check on update (
524
- (
525
- new.PeerId = old.PeerId
526
- and new.PublicKey = old.PublicKey
527
- and new.StampId = old.StampId
528
- and new.VouchOwner = old.VouchOwner
529
- and coalesce(new.VouchSig, '') = coalesce(old.VouchSig, '')
530
- and coalesce(new.VouchUsage, '') = coalesce(old.VouchUsage, '')
531
- and new.UpdatedAt > coalesce(old.UpdatedAt, 0)
532
- and verify(
533
- digest('CadreControl.CadrePeer', 'publish', party_id(), new.PeerId, new.Multiaddr, cast(new.UpdatedAt as text), coalesce(new.Profile, '')),
534
- new.Sig, new.PublicKey, 'ed25519')
535
- )
536
- or (
537
- new.StampId = old.StampId
538
- and exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.CadrePeer', 'vouch', party_id(), new.PeerId, new.StampId), context.Signature, A.Key, 'ed25519'))
539
- and coalesce(new.VouchOwner, '') = context.OwnerKey
540
- and coalesce(new.VouchSig, '') = context.Signature
541
- and new.VouchUsage is null
542
- and coalesce(new.PublicKey, '') = coalesce(old.PublicKey, '')
543
- and coalesce(new.Multiaddr, '') = coalesce(old.Multiaddr, '')
544
- and coalesce(new.Sig, '') = coalesce(old.Sig, '')
545
- and coalesce(new.Profile, '') = coalesce(old.Profile, '')
546
- )
547
- )
548
- ) with context (OwnerKey text null, Signature text);
549
-
550
- -- A mobile peer's platform push token, self-published so a server peer can push-wake a
551
- -- suspended app. A resolver re-verifies Sig against the CadrePeer.PublicKey for PeerId
552
- -- (cadre-core device-token.ts), checks freshness, then hands the token to the push sender.
553
- table DeviceToken (
554
- PeerId text primary key,
555
- Platform text, -- 'fcm' | 'apns'
556
- Token text, -- opaque platform device/registration token
557
- UpdatedAt int null, -- epoch ms; strictly increases per self-update
558
- Sig text null, -- self-signature over the 'publish' digest
559
- StampId text unique,
560
- -- A resurrected token has no freshness ceiling to retire it (resolveDeviceToken defaults
561
- -- maxAgeMs to infinity), so stamp retirement is what makes a clear stick.
562
- constraint NotRevoked check on insert (
563
- not exists (select 1 from Revocation R where R.TableName = 'DeviceToken' and R.StampId = new.StampId)
564
- ),
565
- constraint RevocationRecorded check on delete (
566
- exists (select 1 from Revocation R where R.TableName = 'DeviceToken' and R.StampId = old.StampId and R.RowKey = old.PeerId)
567
- ),
568
- -- The owner signs the whole row, nullable columns as '', so a replayed approval can only
569
- -- reproduce the row it approved (cadre-core peer-authorization.ts deviceTokenAddDigest).
570
- constraint AuthorizedInsert check on insert (
571
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
572
- digest(
573
- 'CadreControl.DeviceToken', 'add', party_id(),
574
- new.PeerId,
575
- new.Platform,
576
- new.Token,
577
- coalesce(cast(new.UpdatedAt as text), ''),
578
- coalesce(new.Sig, ''),
579
- new.StampId
580
- ),
581
- context.Signature, A.Key, 'ed25519'))
582
- ),
583
- constraint AuthorizedDelete check on delete (
584
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.DeviceToken', 'remove', party_id(), old.PeerId, old.StampId), context.Signature, A.Key, 'ed25519'))
585
- or exists (select 1 from committed.Revocation R where R.TableName = 'DeviceToken' and R.RowKey = old.PeerId and R.StampId = old.StampId)
586
- ),
587
- -- Self-update only: Platform and Token may change, PeerId and StampId may not, UpdatedAt
588
- -- must increase. No owner re-touch branch: one outside the monotonicity rule would let a
589
- -- captured approval roll UpdatedAt back; an owner correcting a row deletes and re-inserts.
590
- constraint AuthorizedUpdate check on update (
591
- new.PeerId = old.PeerId
592
- and new.StampId = old.StampId
593
- and new.UpdatedAt > coalesce(old.UpdatedAt, 0)
594
- and exists (select 1 from CadrePeer P where P.PeerId = new.PeerId and verify(
595
- digest('CadreControl.DeviceToken', 'publish', party_id(), new.PeerId, new.Platform, new.Token, cast(new.UpdatedAt as text)),
596
- new.Sig, P.PublicKey, 'ed25519'))
597
- )
598
- ) with context (OwnerKey text null, Signature text);
599
-
600
- -- Each machine's own signed statement of the peer id it uses in one strand. That id derives from
601
- -- the machine's private identity seed (cadre-core strandTransportKey), so no other machine can
602
- -- compute it, and a machine removal needs it to tell the removed machine's Strand.MemberPeer
603
- -- binding from its siblings'. A row is a permanent fact: the derivation is deterministic, and a
604
- -- removed machine's rows are how its orphaned bindings stay attributed to it. So no stamp, no
605
- -- tombstone and no delete, and no Revocation.RowIsGone branch.
606
- -- The check defers (it has a subquery), so a CadrePeer row written in the same transaction
607
- -- counts. A node that does not hold the machine's CadrePeer row yet refuses the insert, and the
608
- -- writer tries again later. The check runs only on the node that takes the insert, and it cannot
609
- -- tell whether PublicKey is really the key behind PeerId, so a reader re-verifies Sig against the
610
- -- key derived from PeerId (ControlDatabase.queryStrandPeers) and judges PeerId against the
611
- -- membership views.
612
- table StrandPeer (
613
- StrandId text, -- a Strand.Id or JoinedStrand.Id
614
- PeerId text, -- the machine's control peer id (CadrePeer.PeerId)
615
- StrandPeerId text, -- that machine's peer id in the strand's own network
616
- Sig text, -- the machine's signature over the 'add' digest
617
- primary key (StrandId, PeerId),
618
- constraint Immutable check on update, delete (false),
619
- constraint Authorized check on insert (
620
- exists (select 1 from CadrePeer P where P.PeerId = new.PeerId and verify(digest('CadreControl.StrandPeer', 'add', party_id(), new.StrandId, new.PeerId, new.StrandPeerId), new.Sig, P.PublicKey, 'ed25519'))
621
- )
622
- );
623
-
624
- -- An open invitation to form a strand with this party.
625
- table FormationInvite (
626
- Token text primary key, -- a random string
627
- sAppId text, -- the app of the strand to be formed
628
- ExpiresAt datetime null,
629
- TotalUses int null check (TotalUses >= 0),
630
- ValidationUrl text null, -- web hook sent the disclosure; a ValidationKey then signs off each redemption
631
- StrandId text null, -- bound invite: the host strand consent is recorded against;
632
- -- null: the responder provisions a fresh open strand per redemption
633
- StampId text unique,
634
- -- The owner signs the whole row, nullable columns as ''.
635
- constraint AuthorizedInsert check on insert (
636
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
637
- digest(
638
- 'CadreControl.FormationInvite', 'add', party_id(),
639
- new.Token,
640
- new.sAppId,
641
- coalesce(cast(new.ExpiresAt as text), ''),
642
- coalesce(cast(new.TotalUses as text), ''),
643
- coalesce(new.ValidationUrl, ''),
644
- coalesce(new.StrandId, ''),
645
- new.StampId
646
- ),
647
- context.Signature, A.Key, 'ed25519'))
648
- ),
649
- constraint AuthorizedDelete check on delete (
650
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
651
- digest(
652
- 'CadreControl.FormationInvite', 'remove', party_id(),
653
- old.Token,
654
- old.sAppId,
655
- coalesce(cast(old.ExpiresAt as text), ''),
656
- coalesce(cast(old.TotalUses as text), ''),
657
- coalesce(old.ValidationUrl, ''),
658
- coalesce(old.StrandId, ''),
659
- old.StampId
660
- ),
661
- context.Signature, A.Key, 'ed25519'))
662
- ),
663
- -- Insert and delete only, so the consent parameters cannot change under a signature.
664
- constraint Immutable check on update (false)
665
- ) with context (OwnerKey text, Signature text);
666
-
667
- -- Append-only record of formation invite redemptions, one row per redemption.
668
- table FormationUsage (
669
- Token text, -- the FormationInvite redeemed
670
- UsageStampId text, -- single-use nonce minted by the joining peer, signed into its 'consent' digest
671
- -- and the approver's 'vouch' digest. The primary key: this table never
672
- -- deletes, so the key alone makes a nonce permanent and there is no
673
- -- NotRevoked pair here. Two nodes that have not converged can each admit
674
- -- the same nonce: a duplicated audit row, never a join nobody approved.
675
- PeerKey text, -- the joining peer's ed25519 public key (base64url); its peer id derives from it
676
- PeerSig text, -- the joiner's signature over the 'consent' digest (PeerConsented)
677
- Disclosure text,
678
- StrandId text,
679
- StrandStampId text, -- the Strand.StampId this consent names: one strand row, not an id forever
680
- -- (Strand.AuthorizedInsert). Not unique: a bound invite's redeemers share
681
- -- a host strand.
682
- primary key (UsageStampId),
683
- constraint InsertOnly check on update, delete (false),
684
- -- The use cap counts the pre-transaction snapshot, so concurrent redeemers on separate
685
- -- nodes can over-admit by their number; both rows survive and removal is owner-gated. A
686
- -- strict per-token sequence was rejected: a lost race would silently drop a consented
687
- -- join. Two usage rows for one token in one transaction read the same count; no writer
688
- -- does that.
689
- -- A ValidationUrl invite needs a sign-off verified against a STORED ValidationKey row;
690
- -- context.ValidationKey only selects which row, so a redeemer cannot approve itself with
691
- -- a throwaway key. The sign-off covers (Token, UsageStampId, StrandId, PeerKey,
692
- -- Disclosure), so it buys exactly one row; StrandStampId is not bound because the
693
- -- unbound path mints it inside the redeeming transaction. Removing the key later does
694
- -- not revisit rows it approved.
695
- -- A bound invite may only name its own host strand. An unbound invite may name any
696
- -- existing strand, which burns a use and forecloses that id's consent-seating: harmless.
697
- -- Neither digest of this table binds party_id(), alone in this schema: the joiner signs
698
- -- its consent before the responder's party id reaches it (it arrives in the result
699
- -- frame) and with a key made fresh for this one formation, and the outside approver
700
- -- behind ValidationUrl is sent only the five fields below. Both digests bind the
701
- -- invitation Token, a random secret seated in one party's FormationInvite table, so
702
- -- replaying either in another party needs that party's owner to seat the same token in
703
- -- its own database, and the only database harmed would be its own.
704
- constraint Authorized check on insert (
705
- exists (
706
- select 1 from FormationInvite FI
707
- where FI.Token = new.Token
708
- and (FI.TotalUses is null or FI.TotalUses > (select count(1) from committed.FormationUsage U where U.Token = new.Token))
709
- and (FI.ExpiresAt is null or FI.ExpiresAt > context.Now)
710
- and (FI.ValidationUrl is null or exists (
711
- select 1 from ValidationKey VK
712
- where VK.Key = context.ValidationKey
713
- and verify(digest('CadreControl.FormationUsage', 'vouch', new.Token, new.UsageStampId, new.StrandId, new.PeerKey, new.Disclosure), context.ValidationSignature, VK.Key, 'ed25519')))
714
- and (FI.StrandId is null or FI.StrandId = new.StrandId)
715
- )
716
- ),
717
- -- A usage row may only name a strand row that exists, so a consent record cannot be held
718
- -- in reserve to re-seat an id after its removal.
719
- constraint StrandExists check (exists (select 1 from Strand S where S.Id = new.StrandId and S.StampId = new.StrandStampId)),
720
- -- The joiner proves it agreed. PeerKey is its own key, so there is nothing for a writer to
721
- -- substitute; stored on the row so any reader can re-check it (verifyFormationConsent).
722
- -- StrandId and the party id are not signed: the joiner cannot know them when it signs
723
- -- (Authorized, above).
724
- constraint PeerConsented check on insert (
725
- verify(digest('CadreControl.FormationUsage', 'consent',
726
- new.Token, new.UsageStampId, new.PeerKey, new.Disclosure),
727
- new.PeerSig, new.PeerKey, 'ed25519')
728
- )
729
- ) with context (Now datetime, ValidationKey text null, ValidationSignature text null);
730
-
731
- -- Serves the per-token reads (the cap count above; cadre-core's countFormationUsage,
732
- -- readToken and hasOutstandingFormationInvite) on an append-only table. Its cross-machine
733
- -- convergence is guarded by the integration scenario strand-formation-concurrent-redemption.
734
- index FormationUsageByToken on FormationUsage (Token);
735
-
736
- -- An owner-signed invitation to join this cadre as a machine, redeemable on the owner's
737
- -- behalf by any member machine (ControlDatabase.redeemCadreInvite). It admits a machine
738
- -- and grants nothing else; ownership is an OwnerGrant. The invitation is a keypair, not a
739
- -- bearer token: the row holds the public half and the holder proves possession by signing
740
- -- with the private half (CadreInviteUsage.InvitePossessed), so a member that only relays
741
- -- it can neither admit a machine of its own choosing with it nor spend its uses. Rows are
742
- -- never deleted: a device admitted
743
- -- through one carries no owner signature of its own, and its membership is the chain
744
- -- invitation -> usage -> peer row, verified at read time, so the row must outlive every
745
- -- device it admitted. Withdrawing an invitation is an owner-signed Revocation tombstone
746
- -- over the row's stamp with the row kept (Revocation.RowIsGone); liveness is read as no
747
- -- tombstone, unexpired, uses left, issuer still an owner (CadreInviteUsage.Authorized).
748
- -- NOTE: expired and withdrawn rows accumulate for the life of the party; the same tripwire
749
- -- as hasOutstandingFormationInvite applies (ControlDatabase.hasLiveCadreInvite). An owner
750
- -- retires a device's dependency on its invitation by re-vouching the row (the owner branch
751
- -- of CadrePeer.AuthorizedUpdate).
752
- table CadreInvite (
753
- Key text primary key, -- the invitation's ed25519 public key (base64url)
754
- PeerId text null, -- the device this invitation is for; null: whoever redeems first designates it
755
- ExpiresAt datetime null,
756
- TotalUses int null check (TotalUses >= 0),
757
- IssuerKey text, -- the owner that signed the row (== insert context.OwnerKey). A reader checks it
758
- -- against its node-local anchor, never against the replicated OwnerKey table.
759
- IssuerSig text, -- that owner's 'add' signature (== insert context.Signature), stored so any reader
760
- -- can re-verify the row from the holder's copy or the replicated one
761
- StampId text unique,
762
- -- A withdrawn invitation cannot be re-seated from the signed copy its holder keeps, on
763
- -- any node that holds the tombstone (schema header for the node that does not).
764
- constraint NotRevoked check on insert (
765
- not exists (select 1 from Revocation R where R.TableName = 'CadreInvite' and R.StampId = new.StampId)
766
- ),
767
- -- The owner signs the whole row, nullable columns as '' (cadre-core cadreInviteRowFields),
768
- -- and the stored issuer pair must be the pair verified here, as CadrePeer pins its voucher.
769
- constraint AuthorizedInsert check on insert (
770
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
771
- digest(
772
- 'CadreControl.CadreInvite', 'add', party_id(),
773
- new.Key,
774
- coalesce(new.PeerId, ''),
775
- coalesce(cast(new.ExpiresAt as text), ''),
776
- coalesce(cast(new.TotalUses as text), ''),
777
- new.StampId
778
- ),
779
- context.Signature, A.Key, 'ed25519'))
780
- and coalesce(new.IssuerKey, '') = context.OwnerKey
781
- and coalesce(new.IssuerSig, '') = context.Signature
782
- ),
783
- constraint NoUpdate check on update (false),
784
- -- Never deleted (table comment). Withdrawal is the tombstone alone.
785
- constraint NoDelete check on delete (false)
786
- ) with context (OwnerKey text, Signature text);
787
-
788
- -- Append-only record of cadre invitation redemptions, one row per redemption: the proof a
789
- -- CadrePeer row was admitted by consent rather than by an owner signature.
790
- table CadreInviteUsage (
791
- UsageStampId text primary key, -- nonce minted by the redeeming device and signed into both signatures
792
- -- below. The primary key: this table never deletes, so the key alone
793
- -- makes a nonce permanent and there is no NotRevoked pair here. Two nodes
794
- -- that have not converged can each admit the same nonce (FormationUsage).
795
- InviteKey text, -- the CadreInvite redeemed
796
- PeerId text, -- the redeeming device: the identity multihash of PeerKey. The writer
797
- -- asserts the pair and a reader re-derives it (verifyInvitationAdmission);
798
- -- the schema cannot unwrap a multihash.
799
- PeerKey text, -- the redeeming device's ed25519 public key (base64url)
800
- PeerStampId text, -- the CadrePeer.StampId this usage seats: one row incarnation, not a peer id
801
- -- forever. Minted by the writer inside the redeeming transaction and not
802
- -- signed (FormationUsage.StrandStampId).
803
- InviteSig text, -- by the invitation's private key over the 'redeem' digest: proof of possession
804
- PeerSig text, -- by PeerKey over the 'consent' digest: the device agreed to join
805
- constraint InsertOnly check on update, delete (false),
806
- -- The invitation is read from the pre-transaction snapshot, so an invitation cannot be
807
- -- seated and redeemed in one transaction (the CadrePeer consent branch rests on that).
808
- -- NOTE: accepted tradeoff — the use cap counts committed usage, so two redeemers racing
809
- -- for a single-use machine invitation on different machines may both be admitted until
810
- -- merge, and after merge both rows stand (FormationUsage.Authorized). Serializing would
811
- -- need cross-machine coordination the control plane does not have; the mitigations are
812
- -- the single-use default, the targeted form, and the owner seeing the extra machine and
813
- -- removing it. Revisit if the control plane gains a cross-machine sequencer. The owner
814
- -- grant's half of this tradeoff is at OwnerGrantUsage.Authorized. An issuer removed
815
- -- since issuing takes its outstanding invitations with it (the committed.OwnerKey
816
- -- clause, which a tombstone alone satisfies); devices it already admitted stay members.
817
- constraint Authorized check on insert (
818
- exists (
819
- select 1 from committed.CadreInvite I
820
- where I.Key = new.InviteKey
821
- and not exists (select 1 from Revocation R where R.TableName = 'CadreInvite' and R.StampId = I.StampId)
822
- and (I.ExpiresAt is null or I.ExpiresAt > context.Now)
823
- and (I.TotalUses is null or I.TotalUses > (select count(1) from committed.CadreInviteUsage U where U.InviteKey = new.InviteKey))
824
- and (I.PeerId is null or I.PeerId = new.PeerId)
825
- and exists (select 1 from committed.OwnerKey K where K.Key = I.IssuerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = K.StampId))
826
- )
827
- ),
828
- -- Verified against the invitation key itself: the member writing the row can check this
829
- -- signature but, holding only the public half, cannot produce it.
830
- constraint InvitePossessed check on insert (
831
- verify(digest('CadreControl.CadreInviteUsage', 'redeem', party_id(), new.InviteKey, new.UsageStampId, new.PeerKey),
832
- new.InviteSig, new.InviteKey, 'ed25519')
833
- ),
834
- -- The device proves it agreed (FormationUsage.PeerConsented).
835
- constraint PeerConsented check on insert (
836
- verify(digest('CadreControl.CadreInviteUsage', 'consent', party_id(), new.InviteKey, new.UsageStampId, new.PeerKey),
837
- new.PeerSig, new.PeerKey, 'ed25519')
838
- ),
839
- -- Deferred, so the same-transaction peer insert counts: a usage row can never be held in
840
- -- reserve to seat a row later (FormationUsage.StrandExists). PeerKey must be the key the
841
- -- peer row stores, so the usage names the admitted machine's own key and no other.
842
- constraint PeerExists check (exists (
843
- select 1 from CadrePeer P where P.PeerId = new.PeerId and P.StampId = new.PeerStampId and P.PublicKey = new.PeerKey
844
- ))
845
- ) with context (Now datetime);
846
-
847
- -- Serves the cap count above and the liveness reads (cadre-core countCadreInviteUsage,
848
- -- hasLiveCadreInvite) on an append-only table, as FormationUsageByToken does.
849
- index CadreInviteUsageByInvite on CadreInviteUsage (InviteKey);
850
-
851
- -- An owner-signed grant of ownership to whoever holds the grant's private half: it seats an
852
- -- OwnerKey row for a key the holder generates or already holds, and admits no machine (a
853
- -- machine is admitted by a CadreInvite; peer identity and ownership are unrelated, so the
854
- -- row names no peer id). The grant is a keypair as the invitation is: the row holds the
855
- -- public half, the holder proves possession by signing with the private half
856
- -- (OwnerGrantUsage.GrantPossessed), and the member machine that writes the redemption can
857
- -- verify that signature but never produce it, so it cannot seat an owner for itself. Rows
858
- -- are never deleted: a key seated through one carries no owner signature of its own, and
859
- -- its proof is the chain grant -> usage -> OwnerKey row, verified at read time, so the row
860
- -- must outlive every key it seated. Withdrawal is an owner-signed Revocation tombstone over
861
- -- the row's stamp with the row kept (Revocation.RowIsGone); liveness is read as no
862
- -- tombstone, unexpired, uses left, issuer still an owner (OwnerGrantUsage.Authorized).
863
- -- NOTE: expired and withdrawn rows accumulate for the life of the party, as CadreInvite's.
864
- -- The label is the issuer's: it is bound into the grant's signature and the seated OwnerKey
865
- -- row must carry it (the grant branch of OwnerKey.Authorized), so a key seated on a fresh
866
- -- device during recovery needs no naming prompt, and nothing the holder writes names it.
867
- table OwnerGrant (
868
- Key text primary key, -- the grant's ed25519 public key (base64url)
869
- Label text null, -- the label the seated OwnerKey row carries, chosen by the issuer
870
- ExpiresAt datetime null, -- null: never. The writer defaults to a short expiry; a lifetime with
871
- -- no end is the issuer's explicit choice (a backup grant)
872
- TotalUses int null check (TotalUses >= 0),
873
- IssuerKey text, -- the owner that signed the row (== insert context.OwnerKey); a reader checks
874
- -- it against its node-local anchor, never against the replicated OwnerKey table
875
- IssuerSig text, -- that owner's 'add' signature (== insert context.Signature), stored so any
876
- -- reader can re-verify the row from the holder's copy or the replicated one
877
- StampId text unique,
878
- -- A withdrawn grant cannot be re-seated from the signed copy its holder keeps, on any
879
- -- node that holds the tombstone (schema header for the node that does not).
880
- constraint NotRevoked check on insert (
881
- not exists (select 1 from Revocation R where R.TableName = 'OwnerGrant' and R.StampId = new.StampId)
882
- ),
883
- -- Never empty, as OwnerKey.LabelLength: the add digest binds coalesce(Label, '').
884
- constraint LabelLength check (
885
- Label is null or length(Label) between 1 and 64
886
- ),
887
- -- The owner signs the whole row, nullable columns as '' (cadre-core ownerGrantRowFields),
888
- -- and the stored issuer pair must be the pair verified here, as CadreInvite pins its issuer.
889
- constraint AuthorizedInsert check on insert (
890
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
891
- digest(
892
- 'CadreControl.OwnerGrant', 'add', party_id(),
893
- new.Key,
894
- coalesce(new.Label, ''),
895
- coalesce(cast(new.ExpiresAt as text), ''),
896
- coalesce(cast(new.TotalUses as text), ''),
897
- new.StampId
898
- ),
899
- context.Signature, A.Key, 'ed25519'))
900
- and coalesce(new.IssuerKey, '') = context.OwnerKey
901
- and coalesce(new.IssuerSig, '') = context.Signature
902
- ),
903
- constraint NoUpdate check on update (false),
904
- -- Never deleted (table comment). Withdrawal is the tombstone alone.
905
- constraint NoDelete check on delete (false)
906
- ) with context (OwnerKey text, Signature text);
907
-
908
- -- Append-only record of owner-grant redemptions, one row per redemption: the proof an
909
- -- OwnerKey row was seated by consent rather than by an owner signature.
910
- table OwnerGrantUsage (
911
- UsageStampId text primary key, -- nonce minted by the holder and signed into both signatures below. The
912
- -- primary key: this table never deletes, so the key alone makes a nonce
913
- -- permanent and there is no NotRevoked pair here (CadreInviteUsage).
914
- GrantKey text, -- the OwnerGrant redeemed
915
- SeatedKey text, -- the owner key seated (base64url ed25519): the holder's, fresh or already held
916
- SeatedStampId text, -- the OwnerKey.StampId this usage seats: one row incarnation, not a key
917
- -- forever. Minted by the writer inside the redeeming transaction and not
918
- -- signed (CadreInviteUsage.PeerStampId).
919
- GrantSig text, -- by the grant's private key over the 'redeem' digest: proof of possession
920
- OwnerSig text, -- by SeatedKey over the 'consent' digest: the holder holds the key it seats
921
- constraint InsertOnly check on update, delete (false),
922
- -- The grant is read from the pre-transaction snapshot, so a grant cannot be seated and
923
- -- redeemed in one transaction (the grant branch of OwnerKey.Authorized rests on that).
924
- -- NOTE: accepted tradeoff — the use cap counts committed usage, so two holders of one
925
- -- single-use grant redeeming on different machines may both be seated until merge, and
926
- -- after merge both rows stand (CadreInviteUsage.Authorized). Serializing would need
927
- -- cross-machine coordination the control plane does not have; the mitigations are the
928
- -- defaults the writer sets (single use and a 15-minute expiry, a longer lifetime only
929
- -- when the user chooses one) and the owner seeing the extra key in the owner-key list
930
- -- and removing it. Revisit if the control plane gains a cross-machine sequencer. An
931
- -- issuer removed since issuing takes its outstanding grants with it (the
932
- -- committed.OwnerKey clause, which a tombstone alone satisfies); keys it already
933
- -- seated stay owners.
934
- constraint Authorized check on insert (
935
- exists (
936
- select 1 from committed.OwnerGrant G
937
- where G.Key = new.GrantKey
938
- and not exists (select 1 from Revocation R where R.TableName = 'OwnerGrant' and R.StampId = G.StampId)
939
- and (G.ExpiresAt is null or G.ExpiresAt > context.Now)
940
- and (G.TotalUses is null or G.TotalUses > (select count(1) from committed.OwnerGrantUsage U where U.GrantKey = new.GrantKey))
941
- and exists (select 1 from committed.OwnerKey K where K.Key = G.IssuerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = K.StampId))
942
- )
943
- ),
944
- -- Verified against the grant key itself: the member writing the row can check this
945
- -- signature but, holding only the public half, cannot produce it.
946
- constraint GrantPossessed check on insert (
947
- verify(digest('CadreControl.OwnerGrantUsage', 'redeem', party_id(), new.GrantKey, new.UsageStampId, new.SeatedKey),
948
- new.GrantSig, new.GrantKey, 'ed25519')
949
- ),
950
- -- The holder proves it holds the key being seated (CadreInviteUsage.PeerConsented).
951
- constraint OwnerConsented check on insert (
952
- verify(digest('CadreControl.OwnerGrantUsage', 'consent', party_id(), new.GrantKey, new.UsageStampId, new.SeatedKey),
953
- new.OwnerSig, new.SeatedKey, 'ed25519')
954
- ),
955
- -- Deferred, so the same-transaction OwnerKey insert counts: a usage row can never be
956
- -- held in reserve to seat a row later (CadreInviteUsage.PeerExists).
957
- constraint SeatedExists check (
958
- exists (select 1 from OwnerKey K where K.Key = new.SeatedKey and K.StampId = new.SeatedStampId)
959
- )
960
- ) with context (Now datetime);
961
-
962
- -- Serves the cap count above and the liveness reads (cadre-core countOwnerGrantUsage,
963
- -- listOwnerGrantStatuses) on an append-only table, as CadreInviteUsageByInvite does.
964
- index OwnerGrantUsageByGrant on OwnerGrantUsage (GrantKey);
965
-
966
- -- Append-only retirement record for the stamps of removed rows of every guarded table, with
967
- -- the removed row's key. Every append is owner-signed, so the growth surface is the owner
968
- -- keys. A party founded before genesis created every control collection may hold one marker
969
- -- row, ('Revocation', 'ledger', 'opened'), which retires nothing: an owner filed it so this
970
- -- table had a collection. Nothing files it now. Readers filter on their own guarded
971
- -- TableName, and queryRevocations skips it. A 'CadreInvite' or 'OwnerGrant' row withdraws
972
- -- an invitation or a grant whose row stays (the table comments).
973
- table Revocation (
974
- TableName text, -- 'OwnerKey' | 'ValidationKey' | 'Strand' | 'StrandPartyKey' |
975
- -- 'PendingStrandPartyKey' | 'JoinedStrand' | 'JoinRequest' | 'CadrePeer' |
976
- -- 'DeviceToken' | 'CadreInvite' | 'OwnerGrant', or 'Revocation' for an older
977
- -- party's marker
978
- RowKey text, -- primary key of the removed row
979
- StampId text, -- the retired stamp
980
- ReissuedAt integer default 0, -- bumped by an owner-signed re-issue so a tombstone committed while the
981
- -- node was alone can be re-written and so re-broadcast; nothing reads it
982
- SignerKey text null, -- the owner that filed the tombstone (== insert context.OwnerKey)
983
- SignerSig text null, -- that owner's 'remove' signature (== insert context.Signature). A node that
984
- -- received the row by replication re-verifies the pair and judges SignerKey
985
- -- against its node-local trusted-owner anchor (cadre-core
986
- -- verifyRevocationSigner), not against this replicated table.
987
- -- Keyed on the stamp: one row key may carry several tombstones over its life.
988
- primary key (TableName, StampId),
989
- -- Retirement is permanent.
990
- constraint NoDelete check on delete (false),
991
- -- Pinned at 0 so an owner cannot seat a tombstone at a counter its own re-issues cannot pass.
992
- constraint FreshTombstone check on insert (new.ReissuedAt = 0),
993
- -- A re-issue moves nothing but the counter, and only upward. The signer pair stays the
994
- -- filing owner's; the re-issuing owner's signature rides in context only.
995
- constraint ReissueOnly check on update (
996
- new.TableName = old.TableName and new.RowKey = old.RowKey
997
- and new.StampId = old.StampId and new.ReissuedAt > old.ReissuedAt
998
- and coalesce(new.SignerKey, '') = coalesce(old.SignerKey, '')
999
- and coalesce(new.SignerSig, '') = coalesce(old.SignerSig, '')
1000
- ),
1001
- -- A stamp is retired only once its row is gone (deferred, so the same-transaction delete
1002
- -- counts). Keyed on the stamp, not RowKey: a node that converges on a re-admission before
1003
- -- the earlier removal's tombstone must still accept that tombstone. Retiring a stamp that
1004
- -- never existed is harmless: stamps carry 128 random bits (generateStampId). For
1005
- -- 'CadreInvite' and 'OwnerGrant' there is no row-gone test: a tombstone there is a
1006
- -- withdrawal, and the row stays (the table comments). The last branch admits the marker
1007
- -- row an older party may hold, and nothing else under 'Revocation'; nothing files it now.
1008
- -- NOTE: drop this branch, REVOCATION_LEDGER_MARKER and the readers' skip together with the
1009
- -- next CONTROL_SCHEMA_VERSION change that already needs a migration.
1010
- constraint RowIsGone check on insert (
1011
- (new.TableName = 'OwnerKey' and not exists (select 1 from OwnerKey K where K.StampId = new.StampId))
1012
- or (new.TableName = 'CadrePeer' and not exists (select 1 from CadrePeer P where P.StampId = new.StampId))
1013
- or (new.TableName = 'ValidationKey' and not exists (select 1 from ValidationKey V where V.StampId = new.StampId))
1014
- or (new.TableName = 'Strand' and not exists (select 1 from Strand S where S.StampId = new.StampId))
1015
- or (new.TableName = 'StrandPartyKey' and not exists (select 1 from StrandPartyKey K where K.StampId = new.StampId))
1016
- or (new.TableName = 'PendingStrandPartyKey' and not exists (select 1 from PendingStrandPartyKey K where K.StampId = new.StampId))
1017
- or (new.TableName = 'JoinedStrand' and not exists (select 1 from JoinedStrand J where J.StampId = new.StampId))
1018
- or (new.TableName = 'JoinRequest' and not exists (select 1 from JoinRequest J where J.StampId = new.StampId))
1019
- or (new.TableName = 'DeviceToken' and not exists (select 1 from DeviceToken D where D.StampId = new.StampId))
1020
- or (new.TableName = 'CadreInvite')
1021
- or (new.TableName = 'OwnerGrant')
1022
- or (new.TableName = 'Revocation' and new.RowKey = 'ledger' and new.StampId = 'opened')
1023
- ),
1024
- -- Owner-signed over the whole row under its own domain tag, so the delete's 'remove'
1025
- -- signature filed in the same transaction never doubles as the tombstone's. Ungated, any
1026
- -- writer could evict a peer party-wide and block its re-admission. RowKey is not checked
1027
- -- against the retired row here (that would reject a tombstone re-issued later, or filed on
1028
- -- a node that never held the row); each guarded table's RevocationRecorded binds it
1029
- -- instead. Reads live OwnerKey like the sibling tables. An older party's marker was signed
1030
- -- under this rule too. The stored signer pair must be the pair verified here.
1031
- constraint Authorized check on insert (
1032
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.Revocation', 'remove', party_id(), new.TableName, new.RowKey, new.StampId), context.Signature, A.Key, 'ed25519'))
1033
- and coalesce(new.SignerKey, '') = context.OwnerKey
1034
- and coalesce(new.SignerSig, '') = context.Signature
1035
- ),
1036
- -- Distinct 'reissue' tag, binding ReissuedAt, so neither approval replays as the other.
1037
- constraint AuthorizedReissue check on update (
1038
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey
1039
- and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId)
1040
- and verify(digest('CadreControl.Revocation', 'reissue', party_id(),
1041
- new.TableName, new.RowKey, new.StampId, cast(new.ReissuedAt as text)),
1042
- context.Signature, A.Key, 'ed25519'))
1043
- )
1044
- ) with context (OwnerKey text, Signature text);
1045
- }`;
1046
-
1047
- /** The name the control schema is declared under; Quereus compares schema names without regard to case. */
1048
- export const CONTROL_SCHEMA_NAME = 'CadreControl';
1049
-
1050
- /** The statement that applies {@link CONTROL_SCHEMA_DECLARATION}, run only after the store has been checked against it. */
1051
- export const APPLY_CONTROL_SCHEMA = `apply schema ${CONTROL_SCHEMA_NAME};`;
1052
-
1053
- /** The whole control schema as `schemas/control.qsql` holds it: the declaration, then the apply. */
1054
- export const CONTROL_SCHEMA = `${CONTROL_SCHEMA_DECLARATION}
1055
-
1056
- ${APPLY_CONTROL_SCHEMA}
1057
- `;
1058
-
1059
- /**
1060
- * The declaration statement of a control schema file (`ControlDatabaseConfig.schemaPath`),
1061
- * cut from the file's own text.
1062
- *
1063
- * Refuses a file that is anything other than one `declare schema CadreControl { … }`
1064
- * followed by one plain `apply schema CadreControl` — the shape of {@link CONTROL_SCHEMA}.
1065
- * `loadSchema` runs its own {@link APPLY_CONTROL_SCHEMA} once the store has been checked,
1066
- * so any other statement in the file, or an option on its apply, would be dropped or run
1067
- * unchecked.
1068
- */
1069
- export function controlSchemaFileDeclaration(source: string): string {
1070
- const statements = new Parser().parseAll(source);
1071
- const [declaration, apply] = statements;
1072
- if (statements.length !== 2
1073
- || declaration.type !== 'declareSchema' || !isControlSchemaName(declaration.schemaName)
1074
- || apply.type !== 'applySchema' || !isControlSchemaName(apply.schemaName)
1075
- || apply.options !== undefined || apply.toVersion !== undefined || apply.withSeed === true
1076
- || declaration.loc === undefined) {
1077
- throw new Error(
1078
- `A control schema file must hold exactly \`declare schema ${CONTROL_SCHEMA_NAME} { … }\` ` +
1079
- `followed by \`${APPLY_CONTROL_SCHEMA}\`, the shape of schemas/control.qsql.`
1080
- );
1081
- }
1082
- return source.slice(declaration.loc.start.offset, declaration.loc.end.offset);
1083
- }
1084
-
1085
- function isControlSchemaName(name: string | undefined): boolean {
1086
- return name?.toLowerCase() === CONTROL_SCHEMA_NAME.toLowerCase();
1087
- }
1
+ import { Parser } from '@quereus/quereus';
2
+
3
+ /**
4
+ * The version of the declared control schema, carried in the schema text as the
5
+ * {@link CONTROL_SCHEMA_VERSION_TAG} tag on the `OwnerKey` table. A warm start compares
6
+ * it with the version the store records before applying anything, and the apply then
7
+ * migrates the store to this version and records it (`control-schema-version.ts`).
8
+ *
9
+ * When it changes, what a new version may change, and the fixture each version keeps:
10
+ * docs/cadre/control-schema.md → "Schema versions and migrations", enforced by
11
+ * `control-schema-versions.spec.ts`.
12
+ */
13
+ export const CONTROL_SCHEMA_VERSION = 5;
14
+
15
+ /**
16
+ * The first control schema version whose fixture is kept, and the oldest a store can be
17
+ * migrated from. A store that records a version below it (written by 1.16.0 and earlier,
18
+ * which recorded none) is refused with reason `before-migrations`; docs/cadre/control-schema.md
19
+ * says why it is not migrated.
20
+ */
21
+ export const CONTROL_SCHEMA_BASELINE_VERSION = 3;
22
+
23
+ /** The `OwnerKey` table tag that records {@link CONTROL_SCHEMA_VERSION} in the schema and in every store. */
24
+ export const CONTROL_SCHEMA_VERSION_TAG = 'sereus.controlSchemaVersion';
25
+
26
+ /**
27
+ * The `declare schema CadreControl { … }` statement, with its header comment.
28
+ *
29
+ * Together with {@link APPLY_CONTROL_SCHEMA} this is the authoritative runtime copy of
30
+ * the CadreControl authorization schema ({@link CONTROL_SCHEMA}). It is duplicated from
31
+ * `schemas/control.qsql` so that React Native and other filesystem-less environments
32
+ * get the schema without a runtime file read. Held apart from the apply because
33
+ * `ControlDatabase.loadSchema` declares, checks the pending changes, and only then
34
+ * applies.
35
+ *
36
+ * The two copies MUST stay identical — `control-schema-drift.spec.ts` fails the
37
+ * build if they drift. Any edit here must be mirrored in `schemas/control.qsql`
38
+ * and vice versa.
39
+ */
40
+ export const CONTROL_SCHEMA_DECLARATION = `-- A Sereus party's cadre (its nodes) and their participation in strands (networks).
41
+ --
42
+ -- Every write is authorized by a check: an owner signs an action-tagged digest of the row
43
+ -- (cadre-core control-authorization.ts), or a peer signs its own record. Each digest leads
44
+ -- with a 'CadreControl.<Table>' domain tag, an action tag and party_id(), the party this
45
+ -- machine is configured for (a zero-argument function ControlDatabase registers on its own
46
+ -- engine, never read from a context value or a replicated table), so an approval verifies
47
+ -- only against the one rule, in the one party, it was minted for: two parties that share
48
+ -- an owner key never accept each other's approvals. FormationUsage is the exception, its
49
+ -- two digests scoped by the invitation token instead (FormationUsage.Authorized).
50
+ --
51
+ -- Rows of the guarded tables (OwnerKey, ValidationKey, Strand, StrandPartyKey,
52
+ -- PendingStrandPartyKey, JoinedStrand, JoinRequest, CadrePeer, DeviceToken, CadreInvite,
53
+ -- OwnerGrant) carry a one-off StampId bound into their add and remove digests. \`unique\` holds
54
+ -- over live rows only, so a delete retires
55
+ -- the stamp into Revocation in the same transaction (RevocationRecorded) and an insert refuses
56
+ -- a retired stamp (NotRevoked): the never-expiring add approval cannot re-seat a removed row.
57
+ -- A legitimate re-add mints a fresh stamp and a fresh signature. CadreInvite and OwnerGrant
58
+ -- are the two guarded tables that are never deleted: a tombstone there withdraws the
59
+ -- invitation or grant while the row stays, because the rows it admitted prove themselves
60
+ -- through it.
61
+ --
62
+ -- A check whose expression evaluates to null passes (SQL three-valued logic), so every
63
+ -- comparison over a nullable column that is meant to pin a value is written null-safe
64
+ -- (\`coalesce(col, '')\` or an explicit \`is null\`); a bare \`new.Col = context.X\` over a null
65
+ -- column would pass with nothing pinned.
66
+ --
67
+ -- A check with a subquery defers to commit, so a sibling row written in the same transaction
68
+ -- is visible to it; \`committed.<Table>\` reads the pre-transaction snapshot instead. Every
69
+ -- check reads the rows this node holds: a node that has not converged on a Revocation row
70
+ -- still accepts the replayed add, and the resurrected row then coexists with its tombstone.
71
+ -- ControlDatabase drops retired stamps on the reads that matter (queryCadrePeers,
72
+ -- queryPendingJoins, getOwnerKeys), and every owner lookup in the checks below drops them
73
+ -- too (the \`not exists ... Revocation\` conjunct beside each OwnerKey read, reading live
74
+ -- Revocation so a tombstone filed in the same transaction counts), so a removal is
75
+ -- effective at the writer as soon as its tombstone arrives, whether or not the row's delete
76
+ -- has. Only the founding count in OwnerKey.Authorized stays raw.
77
+ declare schema CadreControl {
78
+ -- A key that can authorize control changes. A row is seated one of three ways, told apart
79
+ -- by the vouch columns: the founding row (all three null), an owner-signed add (VouchOwner
80
+ -- and VouchSig pinned to the insert context, VouchUsage null), or an owner grant redeemed
81
+ -- by consent (VouchOwner = the grant's IssuerKey, VouchSig null, VouchUsage = the
82
+ -- OwnerGrantUsage row that seated it). A machine invitation (CadreInvite) admits a machine
83
+ -- and never seats a row here: a machine's identity key is never an owner key. A reader
84
+ -- judges the stored proof against its node-local anchor, never against this replicated
85
+ -- table.
86
+ table OwnerKey (
87
+ Key text primary key,
88
+ Label text null, -- the user's name for the key ("phone", "paper backup"); bound into the
89
+ -- signed add, so a relayed approval cannot seat the key under another name
90
+ StampId text unique,
91
+ VouchOwner text null,
92
+ VouchSig text null,
93
+ VouchUsage text null,
94
+ constraint NotRevoked check on insert (
95
+ not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = new.StampId)
96
+ ),
97
+ -- Never empty: the add digest binds coalesce(Label, ''), so an empty label would sign as none.
98
+ constraint LabelLength check (
99
+ Label is null or length(Label) between 1 and 64
100
+ ),
101
+ -- The tombstone must name the removed row, not just its stamp (Revocation.RowKey).
102
+ constraint RevocationRecorded check on delete (
103
+ exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = old.StampId and R.RowKey = old.Key)
104
+ ),
105
+ -- Every other table's checks require an owner, so an empty table is a permanent denial of
106
+ -- the party's control plane. Counted post-delete, on this node's rows only: two partitioned
107
+ -- nodes removing different owners can still converge to zero.
108
+ constraint MinOneOwner check on delete (
109
+ (select count(1) from OwnerKey) >= 1
110
+ ),
111
+ -- Rotation is add-then-remove. An update branch would let the sole owner be re-pointed at
112
+ -- another key under a post-image count of one.
113
+ constraint NoUpdate check on update (false),
114
+ -- The authorizer is read from the pre-transaction snapshot: the check defers to commit, by
115
+ -- which point the inserted row (and any sibling) is live, so a plain OwnerKey read would let
116
+ -- a row authorize itself or two strangers seat each other. The founding transaction, whose
117
+ -- pre-transaction owner set is empty, needs no authorization; gating on the pre-transaction
118
+ -- count keeps a same-transaction swap of the sole owner off that branch. That count is
119
+ -- deliberately raw, the one owner read here that ignores Revocation: a machine holding only
120
+ -- a retired owner row must still be refused a second genesis, or a removed device could
121
+ -- re-found the party on its own copy. An owner cannot sign its own removal.
122
+ -- The consent branch seats an owner with no signature at all: an OwnerGrantUsage row
123
+ -- written in the same transaction names this exact row (Key and stamp), and the grant
124
+ -- it redeemed was issued by the stored VouchOwner and carries the row's label (the
125
+ -- issuer's choice, bound into the grant's signature). The grant is read from its
126
+ -- committed table, so it cannot be seated and redeemed in one transaction; the usage
127
+ -- row carries the liveness conditions.
128
+ constraint Authorized check on insert, delete (
129
+ (old.Key is null and (select count(1) from committed.OwnerKey) = 0
130
+ and new.VouchOwner is null and new.VouchSig is null and new.VouchUsage is null)
131
+ or (old.Key is null and exists (select 1 from committed.OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.OwnerKey', 'add', party_id(), new.Key, coalesce(new.Label, ''), new.StampId), context.Signature, A.Key, 'ed25519'))
132
+ and coalesce(new.VouchOwner, '') = context.OwnerKey
133
+ and coalesce(new.VouchSig, '') = context.Signature
134
+ and new.VouchUsage is null)
135
+ or (old.Key is null and new.VouchSig is null and new.VouchUsage is not null
136
+ and exists (
137
+ select 1 from OwnerGrantUsage U
138
+ where U.UsageStampId = new.VouchUsage
139
+ and U.SeatedKey = new.Key
140
+ and U.SeatedStampId = new.StampId
141
+ and exists (select 1 from committed.OwnerGrant G
142
+ where G.Key = U.GrantKey and G.IssuerKey = new.VouchOwner
143
+ and coalesce(G.Label, '') = coalesce(new.Label, ''))
144
+ ))
145
+ or (new.Key is null and exists (select 1 from committed.OwnerKey A where A.Key = context.OwnerKey and A.Key <> old.Key and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.OwnerKey', 'remove', party_id(), old.Key, old.StampId), context.Signature, A.Key, 'ed25519')))
146
+ )
147
+ -- The tag is the version of this whole schema (cadre-core CONTROL_SCHEMA_VERSION): every edit
148
+ -- to the schema bumps it, and a warm start reads the store's copy before applying anything.
149
+ ) with tags ("${CONTROL_SCHEMA_VERSION_TAG}" = ${CONTROL_SCHEMA_VERSION}) with context (OwnerKey text null, Signature text null);
150
+
151
+ -- A key that can validate a strand formation disclosure (FormationUsage.Authorized).
152
+ table ValidationKey (
153
+ Key text primary key,
154
+ StampId text unique,
155
+ constraint NotRevoked check on insert (
156
+ not exists (select 1 from Revocation R where R.TableName = 'ValidationKey' and R.StampId = new.StampId)
157
+ ),
158
+ constraint RevocationRecorded check on delete (
159
+ exists (select 1 from Revocation R where R.TableName = 'ValidationKey' and R.StampId = old.StampId and R.RowKey = old.Key)
160
+ ),
161
+ constraint NoUpdate check on update (false),
162
+ constraint AuthorizedInsert check on insert (
163
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.ValidationKey', 'add', party_id(), new.Key, new.StampId), context.Signature, A.Key, 'ed25519'))
164
+ ),
165
+ -- Owner-signed over the stored row, or a reap: a committed tombstone naming this exact row
166
+ -- incarnation lets a node that was offline at removal time delete the stale row unsigned
167
+ -- (ControlDatabase.reapRevokedRow). committed.*, so a tombstone filed in this transaction
168
+ -- cannot stand in for the signature; the stamp clause, so a tombstone of an earlier
169
+ -- incarnation cannot remove the current one.
170
+ constraint AuthorizedDelete check on delete (
171
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.ValidationKey', 'remove', party_id(), old.Key, old.StampId), context.Signature, A.Key, 'ed25519'))
172
+ or exists (select 1 from committed.Revocation R where R.TableName = 'ValidationKey' and R.RowKey = old.Key and R.StampId = old.StampId)
173
+ )
174
+ ) with context (OwnerKey text, Signature text);
175
+
176
+ -- A network of members sharing an sApp database, each contributing its cadre's peers. This
177
+ -- party's own strands; a strand joined from another party is a JoinedStrand row.
178
+ table Strand (
179
+ Id text primary key, -- UUID
180
+ MemberPrivateKey text null unique, -- the strand's shared read secret; closed strands only
181
+ Type text, -- 'o' open | 'c' closed: open gates writes in the sApp, only closed gates reads
182
+ FounderOwnerKey text null, -- the owner key that signed the insert; null on a consent-seated strand,
183
+ -- whose insert carries no signature. Provenance, not content (strandRowMismatches).
184
+ FounderPeerId text null, -- peer id of the machine that runs the founder bootstrap (cadre-node.ts
185
+ -- launchStrand), bound into the signed add; null on a consent-seated strand.
186
+ -- Not pinned to a CadrePeer row: a solo founder publishes before its own
187
+ -- row exists, and only an owner can name it. Provenance, as FounderOwnerKey.
188
+ StampId text unique,
189
+ constraint NotRevoked check on insert (
190
+ not exists (select 1 from Revocation R where R.TableName = 'Strand' and R.StampId = new.StampId)
191
+ ),
192
+ constraint RevocationRecorded check on delete (
193
+ exists (select 1 from Revocation R where R.TableName = 'Strand' and R.StampId = old.StampId and R.RowKey = old.Id)
194
+ ),
195
+ -- The consent branch below carries no signature, so an update rule would let anyone rewrite
196
+ -- a consent-seated strand.
197
+ constraint NoUpdate check on update (false),
198
+ -- Owner-signed, with FounderOwnerKey pinned to the verified signer and FounderPeerId bound
199
+ -- into the signature; or consent-seated by a FormationUsage row naming this exact row (id
200
+ -- and stamp), written in the same transaction (ControlDatabase.redeemInvitation). Binding
201
+ -- the stamp is what makes a removal stick:
202
+ -- the usage row outlives the strand, and keyed on the id alone it would re-authorize an
203
+ -- unsigned re-seat under a fresh stamp. The consent branch is narrow, each clause closing
204
+ -- one door:
205
+ -- * open and keyless: a closed strand with a caller-chosen read secret has no legitimate
206
+ -- producer;
207
+ -- * through an unbound invite only: a bound invite's host strand is owner-provisioned,
208
+ -- and consent-seating its id would downgrade the real row on a node it has not reached;
209
+ -- * no usage row under another stamp, and no tombstone for the id: an id is consent-seated
210
+ -- once, ever, and never after any removal. Re-joining a removed id is owner-signed.
211
+ -- A standalone tombstone (no accompanying delete, Revocation.Authorized) lets an owner
212
+ -- foreclose consent-seating of an id that never existed: owner-only, and ids are random.
213
+ constraint AuthorizedInsert check on insert (
214
+ (exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.Strand', 'add', party_id(), new.Id, new.Type, coalesce(new.MemberPrivateKey, ''), new.FounderPeerId, new.StampId), context.Signature, A.Key, 'ed25519'))
215
+ and new.FounderOwnerKey = context.OwnerKey
216
+ and new.FounderPeerId is not null)
217
+ or (
218
+ new.Type = 'o'
219
+ and new.MemberPrivateKey is null
220
+ and new.FounderOwnerKey is null
221
+ and new.FounderPeerId is null
222
+ and exists (
223
+ select 1 from FormationUsage FU
224
+ where FU.StrandId = new.Id
225
+ and FU.StrandStampId = new.StampId
226
+ and exists (select 1 from FormationInvite FI where FI.Token = FU.Token and FI.StrandId is null)
227
+ )
228
+ and not exists (
229
+ select 1 from FormationUsage FU2
230
+ where FU2.StrandId = new.Id and FU2.StrandStampId <> new.StampId
231
+ )
232
+ and not exists (
233
+ select 1 from Revocation R
234
+ where R.TableName = 'Strand' and R.RowKey = new.Id
235
+ )
236
+ )
237
+ ),
238
+ -- No consent branch (an invitation forms a strand, never destroys one) and no reap branch:
239
+ -- MemberPrivateKey is stored nowhere else, so this delete is unrecoverable
240
+ -- (tickets/backlog/debt-strand-tombstone-reap.md owns any change).
241
+ constraint AuthorizedDelete check on delete (
242
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.Strand', 'remove', party_id(), old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))
243
+ ),
244
+ -- An open strand has no membership gate, so no member key.
245
+ constraint MemberKeyClosedOnly check (
246
+ new.MemberPrivateKey is null or new.Type = 'c'
247
+ )
248
+ ) with context (OwnerKey text, Signature text);
249
+
250
+ -- This party's own membership identity for one strand: the private key whose public half
251
+ -- seats its Strand.Member / Strand.Manager rows. Separate from Strand.MemberPrivateKey, which
252
+ -- every joining party receives and so could forge (gotchoices/sereus#4). A side table because
253
+ -- a joiner holds no Strand row. Replicated in plaintext to every machine the party owns
254
+ -- (docs/strands/keys.md → "Closed-strand member key handling") but never put on the formation wire.
255
+ table StrandPartyKey (
256
+ Id text primary key, -- the strand id
257
+ PrivateKey text, -- ed25519, base64 protobuf, as Strand.MemberPrivateKey (cadre-core strandMemberKeyPair)
258
+ StampId text unique,
259
+ constraint NotRevoked check on insert (
260
+ not exists (select 1 from Revocation R where R.TableName = 'StrandPartyKey' and R.StampId = new.StampId)
261
+ ),
262
+ constraint RevocationRecorded check on delete (
263
+ exists (select 1 from Revocation R where R.TableName = 'StrandPartyKey' and R.StampId = old.StampId and R.RowKey = old.Id)
264
+ ),
265
+ constraint NoUpdate check on update (false),
266
+ -- Binding PrivateKey means a captured approval can only reproduce the key it approved.
267
+ constraint AuthorizedInsert check on insert (
268
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.StrandPartyKey', 'add', party_id(), new.Id, new.PrivateKey, new.StampId), context.Signature, A.Key, 'ed25519'))
269
+ ),
270
+ -- No reap branch: the key is stored nowhere else (as Strand.AuthorizedDelete).
271
+ constraint AuthorizedDelete check on delete (
272
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.StrandPartyKey', 'remove', party_id(), old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))
273
+ )
274
+ ) with context (OwnerKey text, Signature text);
275
+
276
+ -- The key this party's membership in one closed strand is moving to, while the move is under
277
+ -- way. It is written before the strand is touched and swapped into StrandPartyKey only after
278
+ -- the strand-side work is done: seating a fresh key and crashing before the control row changes
279
+ -- would leave a manager seat nobody holds, and changing the control row first would delete the
280
+ -- only copy of the old key, which the seating needs. A table of its own because StrandPartyKey
281
+ -- is keyed on the strand id alone and NoUpdate. Guarded as StrandPartyKey is, with no reap
282
+ -- branch for the same reason: the key is stored nowhere else.
283
+ -- NOTE: unlike a tombstone (Revocation.ReissuedAt), a pending row committed while the remover
284
+ -- was alone has no re-issue path, so a remover that removes alone and is lost before its
285
+ -- rotations finish loses the rows with it. If that ever matters, give this table that idiom.
286
+ table PendingStrandPartyKey (
287
+ Id text primary key, -- the strand id
288
+ PublicKey text, -- the key being moved to, public half (base64url): the Strand.Member.Key it is seated as.
289
+ -- In the clear so a second removal lists it in Superseded without opening the row.
290
+ SealedKey text, -- its private half (StrandPartyKey.PrivateKey encoding), sealed to the identity keys of the
291
+ -- machines that remain (sealed-party-key.ts): the row is written in the removed machine's last
292
+ -- control transaction and reaches it, so what it carries must open only for the others.
293
+ Superseded text null, -- comma-joined public keys (base64url) of earlier pending keys this row replaced.
294
+ -- A second removal replaces the row because the old key may have reached the
295
+ -- machine it removes, and a seat that key already holds must then be revoked.
296
+ StampId text unique,
297
+ constraint NotRevoked check on insert (
298
+ not exists (select 1 from Revocation R where R.TableName = 'PendingStrandPartyKey' and R.StampId = new.StampId)
299
+ ),
300
+ constraint RevocationRecorded check on delete (
301
+ exists (select 1 from Revocation R where R.TableName = 'PendingStrandPartyKey' and R.StampId = old.StampId and R.RowKey = old.Id)
302
+ ),
303
+ constraint NoUpdate check on update (false),
304
+ -- Binding Superseded as well as the key: a captured approval cannot drop a key from the list.
305
+ constraint AuthorizedInsert check on insert (
306
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.PendingStrandPartyKey', 'add', party_id(), new.Id, new.PublicKey, new.SealedKey, coalesce(new.Superseded, ''), new.StampId), context.Signature, A.Key, 'ed25519'))
307
+ ),
308
+ constraint AuthorizedDelete check on delete (
309
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.PendingStrandPartyKey', 'remove', party_id(), old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))
310
+ )
311
+ ) with context (OwnerKey text, Signature text);
312
+
313
+ -- A strand this party joined from another party, whose control database holds the Strand
314
+ -- row. Every machine of the party reads it, so a replica host keeps a copy and the party's
315
+ -- other machines can attach. A separate table because every reader of Strand takes it to
316
+ -- mean this party's own strand. MemberPrivateKey is held by the founding party and every
317
+ -- member, so a removed row is recoverable by re-forming, which is why this table has a reap
318
+ -- branch (unlike Strand and StrandPartyKey).
319
+ table JoinedStrand (
320
+ Id text primary key, -- the founder's Strand.Id
321
+ Type text, -- 'o' | 'c', as Strand.Type
322
+ MemberPrivateKey text null, -- the closed strand's shared read secret
323
+ StampId text unique,
324
+ constraint NotRevoked check on insert (
325
+ not exists (select 1 from Revocation R where R.TableName = 'JoinedStrand' and R.StampId = new.StampId)
326
+ ),
327
+ constraint RevocationRecorded check on delete (
328
+ exists (select 1 from Revocation R where R.TableName = 'JoinedStrand' and R.StampId = old.StampId and R.RowKey = old.Id)
329
+ ),
330
+ constraint NoUpdate check on update (false),
331
+ -- Readers cast Type (ControlDatabase.queryJoinedStrands).
332
+ constraint KnownType check (new.Type = 'o' or new.Type = 'c'),
333
+ constraint MemberKeyClosedOnly check (new.MemberPrivateKey is null or new.Type = 'c'),
334
+ -- Owner-signed only: every always-on machine of the party downloads the strands named
335
+ -- here, so a machine that is not an owner keeps its joins machine-local.
336
+ constraint AuthorizedInsert check on insert (
337
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.JoinedStrand', 'add', party_id(), new.Id, new.Type, coalesce(new.MemberPrivateKey, ''), new.StampId), context.Signature, A.Key, 'ed25519'))
338
+ ),
339
+ constraint AuthorizedDelete check on delete (
340
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.JoinedStrand', 'remove', party_id(), old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))
341
+ or exists (select 1 from committed.Revocation R where R.TableName = 'JoinedStrand' and R.RowKey = old.Id and R.StampId = old.StampId)
342
+ )
343
+ ) with context (OwnerKey text, Signature text);
344
+
345
+ -- A join this party asked for by redeeming another party's invitation, kept party-wide so
346
+ -- the request outlives the device that asked and any owner machine can carry it on
347
+ -- (docs/strands/formation.md → "Joining while the inviter is offline"). The row is the request alone
348
+ -- and never changes; its outcome is a JoinSuccess or JoinFailure row keyed by this row's
349
+ -- stamp, so asking again (a fresh stamp) starts clean and a dismissal's tombstone retires
350
+ -- the outcome with the request. Invitation is a bearer credential, replicated in plaintext
351
+ -- to every machine the party owns, under the same accepted risk as JoinedStrand.
352
+ -- Owner-signed only; whether a machine that is not an owner may write here is
353
+ -- tickets/blocked/decide-non-owner-machine-completes-a-pending-join.md.
354
+ -- The three tables reference only tables declared before them, so an apply that fails
355
+ -- midway can drop them in reverse order. The two rules that would close a cycle are the
356
+ -- writer's (ControlDatabase): a request's delete takes its outcome row with it, and a join
357
+ -- recorded over a failure deletes the failure. An outcome row left behind is unreadable,
358
+ -- since readers start from the request.
359
+ table JoinRequest (
360
+ Id text primary key, -- base64url sha256 of the invitation token (cadre-core pendingJoinId),
361
+ -- so the token never reaches Revocation
362
+ Invitation text, -- CadreNode.encodeInvitation
363
+ Disclosure text, -- canonicalJson of the disclosure the requester gave
364
+ RequestedAt integer, -- epoch ms
365
+ ExpiresAt integer, -- epoch ms; no attempt starts at or after it
366
+ StampId text unique,
367
+ constraint NotRevoked check on insert (
368
+ not exists (select 1 from Revocation R where R.TableName = 'JoinRequest' and R.StampId = new.StampId)
369
+ ),
370
+ constraint RevocationRecorded check on delete (
371
+ exists (select 1 from Revocation R where R.TableName = 'JoinRequest' and R.StampId = old.StampId and R.RowKey = old.Id)
372
+ ),
373
+ constraint NoUpdate check on update (false),
374
+ constraint AuthorizedInsert check on insert (
375
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
376
+ digest('CadreControl.JoinRequest', 'add', party_id(), new.Id, new.Invitation, new.Disclosure, cast(new.RequestedAt as text), cast(new.ExpiresAt as text), new.StampId),
377
+ context.Signature, A.Key, 'ed25519'))
378
+ ),
379
+ -- Reapable: the inviting party and the user hold the invitation too.
380
+ constraint AuthorizedDelete check on delete (
381
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.JoinRequest', 'remove', party_id(), old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))
382
+ or exists (select 1 from committed.Revocation R where R.TableName = 'JoinRequest' and R.RowKey = old.Id and R.StampId = old.StampId)
383
+ )
384
+ ) with context (OwnerKey text null, Signature text null);
385
+
386
+ -- The outcome of a JoinRequest that joined: the strand the formation returned and, for a
387
+ -- closed strand, the single-use membership invitation it delivered. Keyed by the request's
388
+ -- stamp, so it names one request incarnation and a replayed approval can only re-seat the
389
+ -- row it approved, against the request it approved. A join is final: it may be recorded
390
+ -- over a failure (whose row the writer deletes with it), and nothing is recorded over it.
391
+ table JoinSuccess (
392
+ RequestStampId text primary key,
393
+ RecordedAt integer, -- epoch ms
394
+ StrandId text,
395
+ MembershipInvite text null, -- JSON {inviteKey, invitePrivateKey}, the StrandMembershipInvite; closed strands only
396
+ constraint RequestExists check on insert (
397
+ exists (select 1 from JoinRequest R where R.StampId = new.RequestStampId)
398
+ ),
399
+ constraint NoUpdate check on update (false),
400
+ constraint AuthorizedInsert check on insert (
401
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
402
+ digest('CadreControl.JoinSuccess', 'add', party_id(), new.RequestStampId, cast(new.RecordedAt as text), new.StrandId, coalesce(new.MembershipInvite, '')),
403
+ context.Signature, A.Key, 'ed25519'))
404
+ ),
405
+ -- Removed only with its request: the tombstone retiring the request's stamp (owner-signed,
406
+ -- or already committed for a reap) authorizes this delete.
407
+ constraint AuthorizedDelete check on delete (
408
+ exists (select 1 from Revocation R where R.TableName = 'JoinRequest' and R.StampId = old.RequestStampId)
409
+ )
410
+ ) with context (OwnerKey text null, Signature text null);
411
+
412
+ -- The outcome of a JoinRequest that failed for good. Keyed as JoinSuccess is.
413
+ table JoinFailure (
414
+ RequestStampId text primary key,
415
+ RecordedAt integer, -- epoch ms
416
+ Code text, -- a FormationRejectionCode, 'expired' or 'local'
417
+ Reason text, -- human-readable
418
+ constraint RequestExists check on insert (
419
+ exists (select 1 from JoinRequest R where R.StampId = new.RequestStampId)
420
+ ),
421
+ -- A join is final: nothing records a failure over it.
422
+ constraint NotJoined check on insert (
423
+ not exists (select 1 from JoinSuccess S where S.RequestStampId = new.RequestStampId)
424
+ ),
425
+ constraint NoUpdate check on update (false),
426
+ constraint AuthorizedInsert check on insert (
427
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
428
+ digest('CadreControl.JoinFailure', 'add', party_id(), new.RequestStampId, cast(new.RecordedAt as text), new.Code, new.Reason),
429
+ context.Signature, A.Key, 'ed25519'))
430
+ ),
431
+ -- Removed with its request (JoinSuccess.AuthorizedDelete), or superseded by a join
432
+ -- recorded in the same transaction.
433
+ constraint AuthorizedDelete check on delete (
434
+ exists (select 1 from Revocation R where R.TableName = 'JoinRequest' and R.StampId = old.RequestStampId)
435
+ or exists (select 1 from JoinSuccess S where S.RequestStampId = old.RequestStampId)
436
+ )
437
+ ) with context (OwnerKey text null, Signature text null);
438
+
439
+ -- A node of the cadre, carrying its self-published, freshness-stamped, self-signed address
440
+ -- record (cadre-core PeerAddressRecord): a resolver re-verifies Sig against PublicKey,
441
+ -- checks UpdatedAt and trust, then dials Multiaddr.
442
+ table CadrePeer (
443
+ PeerId text primary key,
444
+ PublicKey text null, -- ed25519 (base64url) behind PeerId; null if not ed25519
445
+ Multiaddr text, -- comma-joined current addrs (relayed first, WebRTC last)
446
+ UpdatedAt int null, -- epoch ms; strictly increases per self-update
447
+ Sig text null, -- self-signature over the 'publish' digest; null until self-published
448
+ StampId text unique,
449
+ VouchOwner text null, -- the owner key that vouched this membership (== insert context.OwnerKey), or
450
+ -- the issuer of the invitation that admitted it (CadreInvite.IssuerKey)
451
+ VouchSig text null, -- that owner's 'vouch' signature (== insert context.Signature); null on an
452
+ -- invitation-admitted row. A reader checks VouchOwner against its node-local
453
+ -- trusted-owner anchor, not against this replicated table, which a self-owner
454
+ -- can pollute.
455
+ VouchUsage text null, -- the CadreInviteUsage.UsageStampId that admitted this row; null on an
456
+ -- owner-vouched row. A row carries exactly one proof: a signature or a usage.
457
+ Profile text null, -- whether the machine is always on: 'storage' yes, 'transaction' no; null until
458
+ -- it self-publishes. The two codes are a stored form only (cadre-core
459
+ -- node-class.ts), kept because a column rename cannot be migrated and a party's
460
+ -- machines update one at a time, so an older build would refuse a new value
461
+ -- replicated from an updated sibling (docs/cadre/control-schema.md -> "Schema
462
+ -- versions and migrations"). Self-declared and covered by Sig. No insert rule
463
+ -- constrains it: an owner could only mislabel a machine it already has full
464
+ -- authority over, and that machine's next self-publish corrects it.
465
+ constraint NotRevoked check on insert (
466
+ not exists (select 1 from Revocation R where R.TableName = 'CadrePeer' and R.StampId = new.StampId)
467
+ ),
468
+ constraint KnownProfile check (new.Profile is null or new.Profile in ('transaction', 'storage')),
469
+ constraint RevocationRecorded check on delete (
470
+ exists (select 1 from Revocation R where R.TableName = 'CadrePeer' and R.StampId = old.StampId and R.RowKey = old.PeerId)
471
+ ),
472
+ -- The owner vouches membership and the PublicKey<->PeerId binding (cadre-core derives
473
+ -- PublicKey from PeerId) over (PeerId, StampId); the stored voucher must be the pair
474
+ -- verified here. The same 'vouch' digest serves the owner branch of AuthorizedUpdate:
475
+ -- both mean "this owner vouches this membership row".
476
+ -- Or admitted by consent: a CadreInviteUsage row written in the same transaction names
477
+ -- this exact row incarnation (PeerId, StampId and PublicKey), and the invitation it
478
+ -- redeemed, read from committed.CadreInvite, was issued by the stored VouchOwner. The
479
+ -- usage row carries the liveness conditions (unexpired, not withdrawn, uses left,
480
+ -- issuer still an owner); this branch only requires that it exists. A reader verifies
481
+ -- the chain row -> usage -> invitation against its anchor (cadre-core
482
+ -- verifyInvitationAdmission), so the invitation row must outlive the rows it admitted.
483
+ -- A removed device may redeem a still-live invitation again and come back: keeping a
484
+ -- device out is removing its row AND withdrawing the invitation.
485
+ constraint AuthorizedInsert check on insert (
486
+ (
487
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.CadrePeer', 'vouch', party_id(), new.PeerId, new.StampId), context.Signature, A.Key, 'ed25519'))
488
+ and coalesce(new.VouchOwner, '') = context.OwnerKey
489
+ and coalesce(new.VouchSig, '') = context.Signature
490
+ and new.VouchUsage is null
491
+ )
492
+ or (
493
+ new.VouchSig is null
494
+ and new.VouchOwner is not null
495
+ and new.VouchUsage is not null
496
+ and exists (
497
+ select 1 from CadreInviteUsage U
498
+ where U.UsageStampId = new.VouchUsage
499
+ and U.PeerId = new.PeerId
500
+ and U.PeerStampId = new.StampId
501
+ and U.PeerKey = new.PublicKey
502
+ and exists (select 1 from committed.CadreInvite I where I.Key = U.InviteKey and I.IssuerKey = new.VouchOwner)
503
+ )
504
+ )
505
+ ),
506
+ -- The stored 'vouch' voucher never authorizes a delete; the 'remove' signature rides in
507
+ -- context and is never stored. Or a reap (ValidationKey.AuthorizedDelete).
508
+ constraint AuthorizedDelete check on delete (
509
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.CadrePeer', 'remove', party_id(), old.PeerId, old.StampId), context.Signature, A.Key, 'ed25519'))
510
+ or exists (select 1 from committed.Revocation R where R.TableName = 'CadrePeer' and R.RowKey = old.PeerId and R.StampId = old.StampId)
511
+ ),
512
+ -- A peer re-publishes its own addrs, always-on code and freshness under its own key (cadre-core
513
+ -- peer-record.ts); everything else is immutable and UpdatedAt must increase. Or an owner
514
+ -- re-vouches the row over its current stamp, which also clears VouchUsage: the row then
515
+ -- stands on the signature and its invitation is no longer consulted for it. The owner
516
+ -- branch keeps what the machine itself declares (PublicKey, Multiaddr, Sig, Profile): the
517
+ -- row's stored VouchSig is a valid re-vouch signature, so any machine holding the row can
518
+ -- take this branch. NOTE: it may still bump UpdatedAt (reauthorizeCadrePeer's re-broadcast
519
+ -- needs it), which on a self-published row leaves Sig unverifiable until the machine's
520
+ -- next heartbeat re-signs past it; if that window ever matters, pin UpdatedAt here when
521
+ -- old.Sig is not null. StampId never
522
+ -- changes on update: an update that rotated it would leave the old stamp free and
523
+ -- untombstoned, so retiring a stamp is delete plus tombstone. The proof columns are
524
+ -- compared null-safe: VouchSig and VouchUsage are null on one of the two row kinds, and a
525
+ -- bare \`new.X = old.X\` over a null would let a self-publish fill the column in.
526
+ constraint AuthorizedUpdate check on update (
527
+ (
528
+ new.PeerId = old.PeerId
529
+ and new.PublicKey = old.PublicKey
530
+ and new.StampId = old.StampId
531
+ and new.VouchOwner = old.VouchOwner
532
+ and coalesce(new.VouchSig, '') = coalesce(old.VouchSig, '')
533
+ and coalesce(new.VouchUsage, '') = coalesce(old.VouchUsage, '')
534
+ and new.UpdatedAt > coalesce(old.UpdatedAt, 0)
535
+ and verify(
536
+ digest('CadreControl.CadrePeer', 'publish', party_id(), new.PeerId, new.Multiaddr, cast(new.UpdatedAt as text), coalesce(new.Profile, '')),
537
+ new.Sig, new.PublicKey, 'ed25519')
538
+ )
539
+ or (
540
+ new.StampId = old.StampId
541
+ and exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.CadrePeer', 'vouch', party_id(), new.PeerId, new.StampId), context.Signature, A.Key, 'ed25519'))
542
+ and coalesce(new.VouchOwner, '') = context.OwnerKey
543
+ and coalesce(new.VouchSig, '') = context.Signature
544
+ and new.VouchUsage is null
545
+ and coalesce(new.PublicKey, '') = coalesce(old.PublicKey, '')
546
+ and coalesce(new.Multiaddr, '') = coalesce(old.Multiaddr, '')
547
+ and coalesce(new.Sig, '') = coalesce(old.Sig, '')
548
+ and coalesce(new.Profile, '') = coalesce(old.Profile, '')
549
+ )
550
+ )
551
+ ) with context (OwnerKey text null, Signature text);
552
+
553
+ -- A mobile peer's platform push token, self-published so a server peer can push-wake a
554
+ -- suspended app. A resolver re-verifies Sig against the CadrePeer.PublicKey for PeerId
555
+ -- (cadre-core device-token.ts), checks freshness, then hands the token to the push sender.
556
+ table DeviceToken (
557
+ PeerId text primary key,
558
+ Platform text, -- 'fcm' | 'apns'
559
+ Token text, -- opaque platform device/registration token
560
+ UpdatedAt int null, -- epoch ms; strictly increases per self-update
561
+ Sig text null, -- self-signature over the 'publish' digest
562
+ StampId text unique,
563
+ -- A resurrected token has no freshness ceiling to retire it (resolveDeviceToken defaults
564
+ -- maxAgeMs to infinity), so stamp retirement is what makes a clear stick.
565
+ constraint NotRevoked check on insert (
566
+ not exists (select 1 from Revocation R where R.TableName = 'DeviceToken' and R.StampId = new.StampId)
567
+ ),
568
+ constraint RevocationRecorded check on delete (
569
+ exists (select 1 from Revocation R where R.TableName = 'DeviceToken' and R.StampId = old.StampId and R.RowKey = old.PeerId)
570
+ ),
571
+ -- The owner signs the whole row, nullable columns as '', so a replayed approval can only
572
+ -- reproduce the row it approved (cadre-core peer-authorization.ts deviceTokenAddDigest).
573
+ constraint AuthorizedInsert check on insert (
574
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
575
+ digest(
576
+ 'CadreControl.DeviceToken', 'add', party_id(),
577
+ new.PeerId,
578
+ new.Platform,
579
+ new.Token,
580
+ coalesce(cast(new.UpdatedAt as text), ''),
581
+ coalesce(new.Sig, ''),
582
+ new.StampId
583
+ ),
584
+ context.Signature, A.Key, 'ed25519'))
585
+ ),
586
+ constraint AuthorizedDelete check on delete (
587
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.DeviceToken', 'remove', party_id(), old.PeerId, old.StampId), context.Signature, A.Key, 'ed25519'))
588
+ or exists (select 1 from committed.Revocation R where R.TableName = 'DeviceToken' and R.RowKey = old.PeerId and R.StampId = old.StampId)
589
+ ),
590
+ -- Self-update only: Platform and Token may change, PeerId and StampId may not, UpdatedAt
591
+ -- must increase. No owner re-touch branch: one outside the monotonicity rule would let a
592
+ -- captured approval roll UpdatedAt back; an owner correcting a row deletes and re-inserts.
593
+ constraint AuthorizedUpdate check on update (
594
+ new.PeerId = old.PeerId
595
+ and new.StampId = old.StampId
596
+ and new.UpdatedAt > coalesce(old.UpdatedAt, 0)
597
+ and exists (select 1 from CadrePeer P where P.PeerId = new.PeerId and verify(
598
+ digest('CadreControl.DeviceToken', 'publish', party_id(), new.PeerId, new.Platform, new.Token, cast(new.UpdatedAt as text)),
599
+ new.Sig, P.PublicKey, 'ed25519'))
600
+ )
601
+ ) with context (OwnerKey text null, Signature text);
602
+
603
+ -- Each machine's own signed statement of the peer id it uses in one strand, and of whether it
604
+ -- serves that strand (Role). The id derives from the machine's private identity seed (cadre-core
605
+ -- strandTransportKey), so no other machine can compute it, and a machine removal needs it to tell
606
+ -- the removed machine's Strand.MemberPeer binding from its siblings'. A row is a permanent fact:
607
+ -- the derivation is deterministic, and a removed machine's rows are how its orphaned bindings
608
+ -- stay attributed to it. So no stamp, no tombstone and no delete, and no Revocation.RowIsGone
609
+ -- branch. Being immutable, the row fixes the role at the machine's first publish for the strand.
610
+ -- Role: null means the machine serves the strand, that is, stores its blocks, because that is
611
+ -- what every row written before the column existed meant; 'client' means it runs the strand
612
+ -- without storing any of it (docs/concepts.md). Per strand rather than per machine, because a
613
+ -- node's strandCohortMember role is a node setting and nothing stops one node from being
614
+ -- reconfigured between strands.
615
+ -- Two signed forms, because the framed digest is injective over its field list. A row with Role
616
+ -- null is signed over (StrandId, PeerId, StrandPeerId), exactly as under version 4, so a serving
617
+ -- machine's row is byte-identical to one written then and a machine still on version 4 verifies
618
+ -- it. A row with Role set is signed over those three and Role; a version-4 machine verifies it
619
+ -- against the three-field form, fails, and drops it, which leaves that machine where it was
620
+ -- before the client had a row. One digest over coalesce(Role, '') would instead change the form
621
+ -- every serving machine signs, and a version-4 reader would then drop every new serving row.
622
+ -- The check defers (it has a subquery), so a CadrePeer row written in the same transaction
623
+ -- counts. A node that does not hold the machine's CadrePeer row yet refuses the insert, and the
624
+ -- writer tries again later. The check runs only on the node that takes the insert, and it cannot
625
+ -- tell whether PublicKey is really the key behind PeerId, so a reader re-verifies Sig against the
626
+ -- key derived from PeerId (ControlDatabase.queryStrandPeers) and judges PeerId against the
627
+ -- membership views.
628
+ table StrandPeer (
629
+ StrandId text, -- a Strand.Id or JoinedStrand.Id
630
+ PeerId text, -- the machine's control peer id (CadrePeer.PeerId)
631
+ StrandPeerId text, -- that machine's peer id in the strand's own network
632
+ Role text null, -- null: the machine serves the strand; 'client': it stores none of it
633
+ Sig text, -- the machine's signature over the 'add' digest, in the form Role selects
634
+ primary key (StrandId, PeerId),
635
+ constraint Immutable check on update, delete (false),
636
+ constraint KnownStrandPeerRole check (new.Role is null or new.Role = 'client'),
637
+ constraint Authorized check on insert (
638
+ exists (select 1 from CadrePeer P where P.PeerId = new.PeerId and (
639
+ (new.Role is null and verify(digest('CadreControl.StrandPeer', 'add', party_id(), new.StrandId, new.PeerId, new.StrandPeerId), new.Sig, P.PublicKey, 'ed25519'))
640
+ or (new.Role is not null and verify(digest('CadreControl.StrandPeer', 'add', party_id(), new.StrandId, new.PeerId, new.StrandPeerId, new.Role), new.Sig, P.PublicKey, 'ed25519'))
641
+ ))
642
+ )
643
+ );
644
+
645
+ -- An open invitation to form a strand with this party.
646
+ table FormationInvite (
647
+ Token text primary key, -- a random string
648
+ sAppId text, -- the app of the strand to be formed
649
+ ExpiresAt datetime null,
650
+ TotalUses int null check (TotalUses >= 0),
651
+ ValidationUrl text null, -- web hook sent the disclosure; a ValidationKey then signs off each redemption
652
+ StrandId text null, -- bound invite: the host strand consent is recorded against;
653
+ -- null: the responder provisions a fresh open strand per redemption
654
+ StampId text unique,
655
+ -- The owner signs the whole row, nullable columns as ''.
656
+ constraint AuthorizedInsert check on insert (
657
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
658
+ digest(
659
+ 'CadreControl.FormationInvite', 'add', party_id(),
660
+ new.Token,
661
+ new.sAppId,
662
+ coalesce(cast(new.ExpiresAt as text), ''),
663
+ coalesce(cast(new.TotalUses as text), ''),
664
+ coalesce(new.ValidationUrl, ''),
665
+ coalesce(new.StrandId, ''),
666
+ new.StampId
667
+ ),
668
+ context.Signature, A.Key, 'ed25519'))
669
+ ),
670
+ constraint AuthorizedDelete check on delete (
671
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
672
+ digest(
673
+ 'CadreControl.FormationInvite', 'remove', party_id(),
674
+ old.Token,
675
+ old.sAppId,
676
+ coalesce(cast(old.ExpiresAt as text), ''),
677
+ coalesce(cast(old.TotalUses as text), ''),
678
+ coalesce(old.ValidationUrl, ''),
679
+ coalesce(old.StrandId, ''),
680
+ old.StampId
681
+ ),
682
+ context.Signature, A.Key, 'ed25519'))
683
+ ),
684
+ -- Insert and delete only, so the consent parameters cannot change under a signature.
685
+ constraint Immutable check on update (false)
686
+ ) with context (OwnerKey text, Signature text);
687
+
688
+ -- Append-only record of formation invite redemptions, one row per redemption.
689
+ table FormationUsage (
690
+ Token text, -- the FormationInvite redeemed
691
+ UsageStampId text, -- single-use nonce minted by the joining peer, signed into its 'consent' digest
692
+ -- and the approver's 'vouch' digest. The primary key: this table never
693
+ -- deletes, so the key alone makes a nonce permanent and there is no
694
+ -- NotRevoked pair here. Two nodes that have not converged can each admit
695
+ -- the same nonce: a duplicated audit row, never a join nobody approved.
696
+ PeerKey text, -- the joining peer's ed25519 public key (base64url); its peer id derives from it
697
+ PeerSig text, -- the joiner's signature over the 'consent' digest (PeerConsented)
698
+ Disclosure text,
699
+ StrandId text,
700
+ StrandStampId text, -- the Strand.StampId this consent names: one strand row, not an id forever
701
+ -- (Strand.AuthorizedInsert). Not unique: a bound invite's redeemers share
702
+ -- a host strand.
703
+ primary key (UsageStampId),
704
+ constraint InsertOnly check on update, delete (false),
705
+ -- The use cap counts the pre-transaction snapshot, so concurrent redeemers on separate
706
+ -- nodes can over-admit by their number; both rows survive and removal is owner-gated. A
707
+ -- strict per-token sequence was rejected: a lost race would silently drop a consented
708
+ -- join. Two usage rows for one token in one transaction read the same count; no writer
709
+ -- does that.
710
+ -- A ValidationUrl invite needs a sign-off verified against a STORED ValidationKey row;
711
+ -- context.ValidationKey only selects which row, so a redeemer cannot approve itself with
712
+ -- a throwaway key. The sign-off covers (Token, UsageStampId, StrandId, PeerKey,
713
+ -- Disclosure), so it buys exactly one row; StrandStampId is not bound because the
714
+ -- unbound path mints it inside the redeeming transaction. Removing the key later does
715
+ -- not revisit rows it approved.
716
+ -- A bound invite may only name its own host strand. An unbound invite may name any
717
+ -- existing strand, which burns a use and forecloses that id's consent-seating: harmless.
718
+ -- Neither digest of this table binds party_id(), alone in this schema: the joiner signs
719
+ -- its consent before the responder's party id reaches it (it arrives in the result
720
+ -- frame) and with a key made fresh for this one formation, and the outside approver
721
+ -- behind ValidationUrl is sent only the five fields below. Both digests bind the
722
+ -- invitation Token, a random secret seated in one party's FormationInvite table, so
723
+ -- replaying either in another party needs that party's owner to seat the same token in
724
+ -- its own database, and the only database harmed would be its own.
725
+ constraint Authorized check on insert (
726
+ exists (
727
+ select 1 from FormationInvite FI
728
+ where FI.Token = new.Token
729
+ and (FI.TotalUses is null or FI.TotalUses > (select count(1) from committed.FormationUsage U where U.Token = new.Token))
730
+ and (FI.ExpiresAt is null or FI.ExpiresAt > context.Now)
731
+ and (FI.ValidationUrl is null or exists (
732
+ select 1 from ValidationKey VK
733
+ where VK.Key = context.ValidationKey
734
+ and verify(digest('CadreControl.FormationUsage', 'vouch', new.Token, new.UsageStampId, new.StrandId, new.PeerKey, new.Disclosure), context.ValidationSignature, VK.Key, 'ed25519')))
735
+ and (FI.StrandId is null or FI.StrandId = new.StrandId)
736
+ )
737
+ ),
738
+ -- A usage row may only name a strand row that exists, so a consent record cannot be held
739
+ -- in reserve to re-seat an id after its removal.
740
+ constraint StrandExists check (exists (select 1 from Strand S where S.Id = new.StrandId and S.StampId = new.StrandStampId)),
741
+ -- The joiner proves it agreed. PeerKey is its own key, so there is nothing for a writer to
742
+ -- substitute; stored on the row so any reader can re-check it (verifyFormationConsent).
743
+ -- StrandId and the party id are not signed: the joiner cannot know them when it signs
744
+ -- (Authorized, above).
745
+ constraint PeerConsented check on insert (
746
+ verify(digest('CadreControl.FormationUsage', 'consent',
747
+ new.Token, new.UsageStampId, new.PeerKey, new.Disclosure),
748
+ new.PeerSig, new.PeerKey, 'ed25519')
749
+ )
750
+ ) with context (Now datetime, ValidationKey text null, ValidationSignature text null);
751
+
752
+ -- Serves the per-token reads (the cap count above; cadre-core's countFormationUsage,
753
+ -- readToken and hasOutstandingFormationInvite) on an append-only table. Its cross-machine
754
+ -- convergence is guarded by the integration scenario strand-formation-concurrent-redemption.
755
+ index FormationUsageByToken on FormationUsage (Token);
756
+
757
+ -- An owner-signed invitation to join this cadre as a machine, redeemable on the owner's
758
+ -- behalf by any member machine (ControlDatabase.redeemCadreInvite). It admits a machine
759
+ -- and grants nothing else; ownership is an OwnerGrant. The invitation is a keypair, not a
760
+ -- bearer token: the row holds the public half and the holder proves possession by signing
761
+ -- with the private half (CadreInviteUsage.InvitePossessed), so a member that only relays
762
+ -- it can neither admit a machine of its own choosing with it nor spend its uses. Rows are
763
+ -- never deleted: a device admitted
764
+ -- through one carries no owner signature of its own, and its membership is the chain
765
+ -- invitation -> usage -> peer row, verified at read time, so the row must outlive every
766
+ -- device it admitted. Withdrawing an invitation is an owner-signed Revocation tombstone
767
+ -- over the row's stamp with the row kept (Revocation.RowIsGone); liveness is read as no
768
+ -- tombstone, unexpired, uses left, issuer still an owner (CadreInviteUsage.Authorized).
769
+ -- NOTE: expired and withdrawn rows accumulate for the life of the party; the same tripwire
770
+ -- as hasOutstandingFormationInvite applies (ControlDatabase.hasLiveCadreInvite). An owner
771
+ -- retires a device's dependency on its invitation by re-vouching the row (the owner branch
772
+ -- of CadrePeer.AuthorizedUpdate).
773
+ table CadreInvite (
774
+ Key text primary key, -- the invitation's ed25519 public key (base64url)
775
+ PeerId text null, -- the device this invitation is for; null: whoever redeems first designates it
776
+ ExpiresAt datetime null,
777
+ TotalUses int null check (TotalUses >= 0),
778
+ IssuerKey text, -- the owner that signed the row (== insert context.OwnerKey). A reader checks it
779
+ -- against its node-local anchor, never against the replicated OwnerKey table.
780
+ IssuerSig text, -- that owner's 'add' signature (== insert context.Signature), stored so any reader
781
+ -- can re-verify the row from the holder's copy or the replicated one
782
+ StampId text unique,
783
+ -- A withdrawn invitation cannot be re-seated from the signed copy its holder keeps, on
784
+ -- any node that holds the tombstone (schema header for the node that does not).
785
+ constraint NotRevoked check on insert (
786
+ not exists (select 1 from Revocation R where R.TableName = 'CadreInvite' and R.StampId = new.StampId)
787
+ ),
788
+ -- The owner signs the whole row, nullable columns as '' (cadre-core cadreInviteRowFields),
789
+ -- and the stored issuer pair must be the pair verified here, as CadrePeer pins its voucher.
790
+ constraint AuthorizedInsert check on insert (
791
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
792
+ digest(
793
+ 'CadreControl.CadreInvite', 'add', party_id(),
794
+ new.Key,
795
+ coalesce(new.PeerId, ''),
796
+ coalesce(cast(new.ExpiresAt as text), ''),
797
+ coalesce(cast(new.TotalUses as text), ''),
798
+ new.StampId
799
+ ),
800
+ context.Signature, A.Key, 'ed25519'))
801
+ and coalesce(new.IssuerKey, '') = context.OwnerKey
802
+ and coalesce(new.IssuerSig, '') = context.Signature
803
+ ),
804
+ constraint NoUpdate check on update (false),
805
+ -- Never deleted (table comment). Withdrawal is the tombstone alone.
806
+ constraint NoDelete check on delete (false)
807
+ ) with context (OwnerKey text, Signature text);
808
+
809
+ -- Append-only record of cadre invitation redemptions, one row per redemption: the proof a
810
+ -- CadrePeer row was admitted by consent rather than by an owner signature.
811
+ table CadreInviteUsage (
812
+ UsageStampId text primary key, -- nonce minted by the redeeming device and signed into both signatures
813
+ -- below. The primary key: this table never deletes, so the key alone
814
+ -- makes a nonce permanent and there is no NotRevoked pair here. Two nodes
815
+ -- that have not converged can each admit the same nonce (FormationUsage).
816
+ InviteKey text, -- the CadreInvite redeemed
817
+ PeerId text, -- the redeeming device: the identity multihash of PeerKey. The writer
818
+ -- asserts the pair and a reader re-derives it (verifyInvitationAdmission);
819
+ -- the schema cannot unwrap a multihash.
820
+ PeerKey text, -- the redeeming device's ed25519 public key (base64url)
821
+ PeerStampId text, -- the CadrePeer.StampId this usage seats: one row incarnation, not a peer id
822
+ -- forever. Minted by the writer inside the redeeming transaction and not
823
+ -- signed (FormationUsage.StrandStampId).
824
+ InviteSig text, -- by the invitation's private key over the 'redeem' digest: proof of possession
825
+ PeerSig text, -- by PeerKey over the 'consent' digest: the device agreed to join
826
+ constraint InsertOnly check on update, delete (false),
827
+ -- The invitation is read from the pre-transaction snapshot, so an invitation cannot be
828
+ -- seated and redeemed in one transaction (the CadrePeer consent branch rests on that).
829
+ -- NOTE: accepted tradeoff — the use cap counts committed usage, so two redeemers racing
830
+ -- for a single-use machine invitation on different machines may both be admitted until
831
+ -- merge, and after merge both rows stand (FormationUsage.Authorized). Serializing would
832
+ -- need cross-machine coordination the control plane does not have; the mitigations are
833
+ -- the single-use default, the targeted form, and the owner seeing the extra machine and
834
+ -- removing it. Revisit if the control plane gains a cross-machine sequencer. The owner
835
+ -- grant's half of this tradeoff is at OwnerGrantUsage.Authorized. An issuer removed
836
+ -- since issuing takes its outstanding invitations with it (the committed.OwnerKey
837
+ -- clause, which a tombstone alone satisfies); devices it already admitted stay members.
838
+ constraint Authorized check on insert (
839
+ exists (
840
+ select 1 from committed.CadreInvite I
841
+ where I.Key = new.InviteKey
842
+ and not exists (select 1 from Revocation R where R.TableName = 'CadreInvite' and R.StampId = I.StampId)
843
+ and (I.ExpiresAt is null or I.ExpiresAt > context.Now)
844
+ and (I.TotalUses is null or I.TotalUses > (select count(1) from committed.CadreInviteUsage U where U.InviteKey = new.InviteKey))
845
+ and (I.PeerId is null or I.PeerId = new.PeerId)
846
+ and exists (select 1 from committed.OwnerKey K where K.Key = I.IssuerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = K.StampId))
847
+ )
848
+ ),
849
+ -- Verified against the invitation key itself: the member writing the row can check this
850
+ -- signature but, holding only the public half, cannot produce it.
851
+ constraint InvitePossessed check on insert (
852
+ verify(digest('CadreControl.CadreInviteUsage', 'redeem', party_id(), new.InviteKey, new.UsageStampId, new.PeerKey),
853
+ new.InviteSig, new.InviteKey, 'ed25519')
854
+ ),
855
+ -- The device proves it agreed (FormationUsage.PeerConsented).
856
+ constraint PeerConsented check on insert (
857
+ verify(digest('CadreControl.CadreInviteUsage', 'consent', party_id(), new.InviteKey, new.UsageStampId, new.PeerKey),
858
+ new.PeerSig, new.PeerKey, 'ed25519')
859
+ ),
860
+ -- Deferred, so the same-transaction peer insert counts: a usage row can never be held in
861
+ -- reserve to seat a row later (FormationUsage.StrandExists). PeerKey must be the key the
862
+ -- peer row stores, so the usage names the admitted machine's own key and no other.
863
+ constraint PeerExists check (exists (
864
+ select 1 from CadrePeer P where P.PeerId = new.PeerId and P.StampId = new.PeerStampId and P.PublicKey = new.PeerKey
865
+ ))
866
+ ) with context (Now datetime);
867
+
868
+ -- Serves the cap count above and the liveness reads (cadre-core countCadreInviteUsage,
869
+ -- hasLiveCadreInvite) on an append-only table, as FormationUsageByToken does.
870
+ index CadreInviteUsageByInvite on CadreInviteUsage (InviteKey);
871
+
872
+ -- An owner-signed grant of ownership to whoever holds the grant's private half: it seats an
873
+ -- OwnerKey row for a key the holder generates or already holds, and admits no machine (a
874
+ -- machine is admitted by a CadreInvite; peer identity and ownership are unrelated, so the
875
+ -- row names no peer id). The grant is a keypair as the invitation is: the row holds the
876
+ -- public half, the holder proves possession by signing with the private half
877
+ -- (OwnerGrantUsage.GrantPossessed), and the member machine that writes the redemption can
878
+ -- verify that signature but never produce it, so it cannot seat an owner for itself. Rows
879
+ -- are never deleted: a key seated through one carries no owner signature of its own, and
880
+ -- its proof is the chain grant -> usage -> OwnerKey row, verified at read time, so the row
881
+ -- must outlive every key it seated. Withdrawal is an owner-signed Revocation tombstone over
882
+ -- the row's stamp with the row kept (Revocation.RowIsGone); liveness is read as no
883
+ -- tombstone, unexpired, uses left, issuer still an owner (OwnerGrantUsage.Authorized).
884
+ -- NOTE: expired and withdrawn rows accumulate for the life of the party, as CadreInvite's.
885
+ -- The label is the issuer's: it is bound into the grant's signature and the seated OwnerKey
886
+ -- row must carry it (the grant branch of OwnerKey.Authorized), so a key seated on a fresh
887
+ -- device during recovery needs no naming prompt, and nothing the holder writes names it.
888
+ table OwnerGrant (
889
+ Key text primary key, -- the grant's ed25519 public key (base64url)
890
+ Label text null, -- the label the seated OwnerKey row carries, chosen by the issuer
891
+ ExpiresAt datetime null, -- null: never. The writer defaults to a short expiry; a lifetime with
892
+ -- no end is the issuer's explicit choice (a backup grant)
893
+ TotalUses int null check (TotalUses >= 0),
894
+ IssuerKey text, -- the owner that signed the row (== insert context.OwnerKey); a reader checks
895
+ -- it against its node-local anchor, never against the replicated OwnerKey table
896
+ IssuerSig text, -- that owner's 'add' signature (== insert context.Signature), stored so any
897
+ -- reader can re-verify the row from the holder's copy or the replicated one
898
+ StampId text unique,
899
+ -- A withdrawn grant cannot be re-seated from the signed copy its holder keeps, on any
900
+ -- node that holds the tombstone (schema header for the node that does not).
901
+ constraint NotRevoked check on insert (
902
+ not exists (select 1 from Revocation R where R.TableName = 'OwnerGrant' and R.StampId = new.StampId)
903
+ ),
904
+ -- Never empty, as OwnerKey.LabelLength: the add digest binds coalesce(Label, '').
905
+ constraint LabelLength check (
906
+ Label is null or length(Label) between 1 and 64
907
+ ),
908
+ -- The owner signs the whole row, nullable columns as '' (cadre-core ownerGrantRowFields),
909
+ -- and the stored issuer pair must be the pair verified here, as CadreInvite pins its issuer.
910
+ constraint AuthorizedInsert check on insert (
911
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(
912
+ digest(
913
+ 'CadreControl.OwnerGrant', 'add', party_id(),
914
+ new.Key,
915
+ coalesce(new.Label, ''),
916
+ coalesce(cast(new.ExpiresAt as text), ''),
917
+ coalesce(cast(new.TotalUses as text), ''),
918
+ new.StampId
919
+ ),
920
+ context.Signature, A.Key, 'ed25519'))
921
+ and coalesce(new.IssuerKey, '') = context.OwnerKey
922
+ and coalesce(new.IssuerSig, '') = context.Signature
923
+ ),
924
+ constraint NoUpdate check on update (false),
925
+ -- Never deleted (table comment). Withdrawal is the tombstone alone.
926
+ constraint NoDelete check on delete (false)
927
+ ) with context (OwnerKey text, Signature text);
928
+
929
+ -- Append-only record of owner-grant redemptions, one row per redemption: the proof an
930
+ -- OwnerKey row was seated by consent rather than by an owner signature.
931
+ table OwnerGrantUsage (
932
+ UsageStampId text primary key, -- nonce minted by the holder and signed into both signatures below. The
933
+ -- primary key: this table never deletes, so the key alone makes a nonce
934
+ -- permanent and there is no NotRevoked pair here (CadreInviteUsage).
935
+ GrantKey text, -- the OwnerGrant redeemed
936
+ SeatedKey text, -- the owner key seated (base64url ed25519): the holder's, fresh or already held
937
+ SeatedStampId text, -- the OwnerKey.StampId this usage seats: one row incarnation, not a key
938
+ -- forever. Minted by the writer inside the redeeming transaction and not
939
+ -- signed (CadreInviteUsage.PeerStampId).
940
+ GrantSig text, -- by the grant's private key over the 'redeem' digest: proof of possession
941
+ OwnerSig text, -- by SeatedKey over the 'consent' digest: the holder holds the key it seats
942
+ constraint InsertOnly check on update, delete (false),
943
+ -- The grant is read from the pre-transaction snapshot, so a grant cannot be seated and
944
+ -- redeemed in one transaction (the grant branch of OwnerKey.Authorized rests on that).
945
+ -- NOTE: accepted tradeoff — the use cap counts committed usage, so two holders of one
946
+ -- single-use grant redeeming on different machines may both be seated until merge, and
947
+ -- after merge both rows stand (CadreInviteUsage.Authorized). Serializing would need
948
+ -- cross-machine coordination the control plane does not have; the mitigations are the
949
+ -- defaults the writer sets (single use and a 15-minute expiry, a longer lifetime only
950
+ -- when the user chooses one) and the owner seeing the extra key in the owner-key list
951
+ -- and removing it. Revisit if the control plane gains a cross-machine sequencer. An
952
+ -- issuer removed since issuing takes its outstanding grants with it (the
953
+ -- committed.OwnerKey clause, which a tombstone alone satisfies); keys it already
954
+ -- seated stay owners.
955
+ constraint Authorized check on insert (
956
+ exists (
957
+ select 1 from committed.OwnerGrant G
958
+ where G.Key = new.GrantKey
959
+ and not exists (select 1 from Revocation R where R.TableName = 'OwnerGrant' and R.StampId = G.StampId)
960
+ and (G.ExpiresAt is null or G.ExpiresAt > context.Now)
961
+ and (G.TotalUses is null or G.TotalUses > (select count(1) from committed.OwnerGrantUsage U where U.GrantKey = new.GrantKey))
962
+ and exists (select 1 from committed.OwnerKey K where K.Key = G.IssuerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = K.StampId))
963
+ )
964
+ ),
965
+ -- Verified against the grant key itself: the member writing the row can check this
966
+ -- signature but, holding only the public half, cannot produce it.
967
+ constraint GrantPossessed check on insert (
968
+ verify(digest('CadreControl.OwnerGrantUsage', 'redeem', party_id(), new.GrantKey, new.UsageStampId, new.SeatedKey),
969
+ new.GrantSig, new.GrantKey, 'ed25519')
970
+ ),
971
+ -- The holder proves it holds the key being seated (CadreInviteUsage.PeerConsented).
972
+ constraint OwnerConsented check on insert (
973
+ verify(digest('CadreControl.OwnerGrantUsage', 'consent', party_id(), new.GrantKey, new.UsageStampId, new.SeatedKey),
974
+ new.OwnerSig, new.SeatedKey, 'ed25519')
975
+ ),
976
+ -- Deferred, so the same-transaction OwnerKey insert counts: a usage row can never be
977
+ -- held in reserve to seat a row later (CadreInviteUsage.PeerExists).
978
+ constraint SeatedExists check (
979
+ exists (select 1 from OwnerKey K where K.Key = new.SeatedKey and K.StampId = new.SeatedStampId)
980
+ )
981
+ ) with context (Now datetime);
982
+
983
+ -- Serves the cap count above and the liveness reads (cadre-core countOwnerGrantUsage,
984
+ -- listOwnerGrantStatuses) on an append-only table, as CadreInviteUsageByInvite does.
985
+ index OwnerGrantUsageByGrant on OwnerGrantUsage (GrantKey);
986
+
987
+ -- Append-only retirement record for the stamps of removed rows of every guarded table, with
988
+ -- the removed row's key. Every append is owner-signed, so the growth surface is the owner
989
+ -- keys. A party founded before genesis created every control collection may hold one marker
990
+ -- row, ('Revocation', 'ledger', 'opened'), which retires nothing: an owner filed it so this
991
+ -- table had a collection. Nothing files it now. Readers filter on their own guarded
992
+ -- TableName, and queryRevocations skips it. A 'CadreInvite' or 'OwnerGrant' row withdraws
993
+ -- an invitation or a grant whose row stays (the table comments).
994
+ table Revocation (
995
+ TableName text, -- 'OwnerKey' | 'ValidationKey' | 'Strand' | 'StrandPartyKey' |
996
+ -- 'PendingStrandPartyKey' | 'JoinedStrand' | 'JoinRequest' | 'CadrePeer' |
997
+ -- 'DeviceToken' | 'CadreInvite' | 'OwnerGrant', or 'Revocation' for an older
998
+ -- party's marker
999
+ RowKey text, -- primary key of the removed row
1000
+ StampId text, -- the retired stamp
1001
+ ReissuedAt integer default 0, -- bumped by an owner-signed re-issue so a tombstone committed while the
1002
+ -- node was alone can be re-written and so re-broadcast; nothing reads it
1003
+ SignerKey text null, -- the owner that filed the tombstone (== insert context.OwnerKey)
1004
+ SignerSig text null, -- that owner's 'remove' signature (== insert context.Signature). A node that
1005
+ -- received the row by replication re-verifies the pair and judges SignerKey
1006
+ -- against its node-local trusted-owner anchor (cadre-core
1007
+ -- verifyRevocationSigner), not against this replicated table.
1008
+ -- Keyed on the stamp: one row key may carry several tombstones over its life.
1009
+ primary key (TableName, StampId),
1010
+ -- Retirement is permanent.
1011
+ constraint NoDelete check on delete (false),
1012
+ -- Pinned at 0 so an owner cannot seat a tombstone at a counter its own re-issues cannot pass.
1013
+ constraint FreshTombstone check on insert (new.ReissuedAt = 0),
1014
+ -- A re-issue moves nothing but the counter, and only upward. The signer pair stays the
1015
+ -- filing owner's; the re-issuing owner's signature rides in context only.
1016
+ constraint ReissueOnly check on update (
1017
+ new.TableName = old.TableName and new.RowKey = old.RowKey
1018
+ and new.StampId = old.StampId and new.ReissuedAt > old.ReissuedAt
1019
+ and coalesce(new.SignerKey, '') = coalesce(old.SignerKey, '')
1020
+ and coalesce(new.SignerSig, '') = coalesce(old.SignerSig, '')
1021
+ ),
1022
+ -- A stamp is retired only once its row is gone (deferred, so the same-transaction delete
1023
+ -- counts). Keyed on the stamp, not RowKey: a node that converges on a re-admission before
1024
+ -- the earlier removal's tombstone must still accept that tombstone. Retiring a stamp that
1025
+ -- never existed is harmless: stamps carry 128 random bits (generateStampId). For
1026
+ -- 'CadreInvite' and 'OwnerGrant' there is no row-gone test: a tombstone there is a
1027
+ -- withdrawal, and the row stays (the table comments). The last branch admits the marker
1028
+ -- row an older party may hold, and nothing else under 'Revocation'; nothing files it now.
1029
+ -- NOTE: drop this branch, REVOCATION_LEDGER_MARKER and the readers' skip together with the
1030
+ -- next CONTROL_SCHEMA_VERSION change that already needs a migration.
1031
+ constraint RowIsGone check on insert (
1032
+ (new.TableName = 'OwnerKey' and not exists (select 1 from OwnerKey K where K.StampId = new.StampId))
1033
+ or (new.TableName = 'CadrePeer' and not exists (select 1 from CadrePeer P where P.StampId = new.StampId))
1034
+ or (new.TableName = 'ValidationKey' and not exists (select 1 from ValidationKey V where V.StampId = new.StampId))
1035
+ or (new.TableName = 'Strand' and not exists (select 1 from Strand S where S.StampId = new.StampId))
1036
+ or (new.TableName = 'StrandPartyKey' and not exists (select 1 from StrandPartyKey K where K.StampId = new.StampId))
1037
+ or (new.TableName = 'PendingStrandPartyKey' and not exists (select 1 from PendingStrandPartyKey K where K.StampId = new.StampId))
1038
+ or (new.TableName = 'JoinedStrand' and not exists (select 1 from JoinedStrand J where J.StampId = new.StampId))
1039
+ or (new.TableName = 'JoinRequest' and not exists (select 1 from JoinRequest J where J.StampId = new.StampId))
1040
+ or (new.TableName = 'DeviceToken' and not exists (select 1 from DeviceToken D where D.StampId = new.StampId))
1041
+ or (new.TableName = 'CadreInvite')
1042
+ or (new.TableName = 'OwnerGrant')
1043
+ or (new.TableName = 'Revocation' and new.RowKey = 'ledger' and new.StampId = 'opened')
1044
+ ),
1045
+ -- Owner-signed over the whole row under its own domain tag, so the delete's 'remove'
1046
+ -- signature filed in the same transaction never doubles as the tombstone's. Ungated, any
1047
+ -- writer could evict a peer party-wide and block its re-admission. RowKey is not checked
1048
+ -- against the retired row here (that would reject a tombstone re-issued later, or filed on
1049
+ -- a node that never held the row); each guarded table's RevocationRecorded binds it
1050
+ -- instead. Reads live OwnerKey like the sibling tables. An older party's marker was signed
1051
+ -- under this rule too. The stored signer pair must be the pair verified here.
1052
+ constraint Authorized check on insert (
1053
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId) and verify(digest('CadreControl.Revocation', 'remove', party_id(), new.TableName, new.RowKey, new.StampId), context.Signature, A.Key, 'ed25519'))
1054
+ and coalesce(new.SignerKey, '') = context.OwnerKey
1055
+ and coalesce(new.SignerSig, '') = context.Signature
1056
+ ),
1057
+ -- Distinct 'reissue' tag, binding ReissuedAt, so neither approval replays as the other.
1058
+ constraint AuthorizedReissue check on update (
1059
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey
1060
+ and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId)
1061
+ and verify(digest('CadreControl.Revocation', 'reissue', party_id(),
1062
+ new.TableName, new.RowKey, new.StampId, cast(new.ReissuedAt as text)),
1063
+ context.Signature, A.Key, 'ed25519'))
1064
+ )
1065
+ ) with context (OwnerKey text, Signature text);
1066
+ }`;
1067
+
1068
+ /** The name the control schema is declared under; Quereus compares schema names without regard to case. */
1069
+ export const CONTROL_SCHEMA_NAME = 'CadreControl';
1070
+
1071
+ /** The statement that applies {@link CONTROL_SCHEMA_DECLARATION}, run only after the store has been checked against it. */
1072
+ export const APPLY_CONTROL_SCHEMA = `apply schema ${CONTROL_SCHEMA_NAME};`;
1073
+
1074
+ /** The whole control schema as `schemas/control.qsql` holds it: the declaration, then the apply. */
1075
+ export const CONTROL_SCHEMA = `${CONTROL_SCHEMA_DECLARATION}
1076
+
1077
+ ${APPLY_CONTROL_SCHEMA}
1078
+ `;
1079
+
1080
+ /**
1081
+ * The declaration statement of a control schema file (`ControlDatabaseConfig.schemaPath`),
1082
+ * cut from the file's own text.
1083
+ *
1084
+ * Refuses a file that is anything other than one `declare schema CadreControl { … }`
1085
+ * followed by one plain `apply schema CadreControl` — the shape of {@link CONTROL_SCHEMA}.
1086
+ * `loadSchema` runs its own {@link APPLY_CONTROL_SCHEMA} once the store has been checked,
1087
+ * so any other statement in the file, or an option on its apply, would be dropped or run
1088
+ * unchecked.
1089
+ */
1090
+ export function controlSchemaFileDeclaration(source: string): string {
1091
+ const statements = new Parser().parseAll(source);
1092
+ const [declaration, apply] = statements;
1093
+ if (statements.length !== 2
1094
+ || declaration.type !== 'declareSchema' || !isControlSchemaName(declaration.schemaName)
1095
+ || apply.type !== 'applySchema' || !isControlSchemaName(apply.schemaName)
1096
+ || apply.options !== undefined || apply.toVersion !== undefined || apply.withSeed === true
1097
+ || declaration.loc === undefined) {
1098
+ throw new Error(
1099
+ `A control schema file must hold exactly \`declare schema ${CONTROL_SCHEMA_NAME} { … }\` ` +
1100
+ `followed by \`${APPLY_CONTROL_SCHEMA}\`, the shape of schemas/control.qsql.`
1101
+ );
1102
+ }
1103
+ return source.slice(declaration.loc.start.offset, declaration.loc.end.offset);
1104
+ }
1105
+
1106
+ function isControlSchemaName(name: string | undefined): boolean {
1107
+ return name?.toLowerCase() === CONTROL_SCHEMA_NAME.toLowerCase();
1108
+ }