@serfab/cadre-core 1.22.0 → 1.24.0

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