@serfab/cadre-core 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/README.md +255 -253
  2. package/dist/bootstrap-peer-store-file.d.ts +13 -0
  3. package/dist/bootstrap-peer-store-file.js +42 -0
  4. package/dist/bootstrap-peer-store-file.js.map +1 -0
  5. package/dist/bootstrap-peer-store.d.ts +73 -0
  6. package/dist/bootstrap-peer-store.js +128 -0
  7. package/dist/bootstrap-peer-store.js.map +1 -0
  8. package/dist/cadre-node.d.ts +1121 -81
  9. package/dist/cadre-node.js +2276 -262
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/control-authorization.d.ts +93 -0
  12. package/dist/control-authorization.js +57 -0
  13. package/dist/control-authorization.js.map +1 -0
  14. package/dist/control-cohort.d.ts +26 -0
  15. package/dist/control-cohort.js +26 -0
  16. package/dist/control-cohort.js.map +1 -1
  17. package/dist/control-database.d.ts +959 -54
  18. package/dist/control-database.js +1421 -148
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +90 -10
  21. package/dist/control-formation-recorder.js +130 -14
  22. package/dist/control-formation-recorder.js.map +1 -1
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +651 -72
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-stream.d.ts +38 -4
  27. package/dist/control-stream.js +70 -4
  28. package/dist/control-stream.js.map +1 -1
  29. package/dist/control-write-retry.d.ts +161 -0
  30. package/dist/control-write-retry.js +412 -0
  31. package/dist/control-write-retry.js.map +1 -0
  32. package/dist/delegate-admission.d.ts +134 -0
  33. package/dist/delegate-admission.js +244 -0
  34. package/dist/delegate-admission.js.map +1 -0
  35. package/dist/device-token.d.ts +11 -11
  36. package/dist/device-token.js +14 -13
  37. package/dist/device-token.js.map +1 -1
  38. package/dist/ed25519-key.d.ts +26 -0
  39. package/dist/ed25519-key.js +56 -1
  40. package/dist/ed25519-key.js.map +1 -1
  41. package/dist/file-durable-slot.d.ts +20 -0
  42. package/dist/file-durable-slot.js +53 -0
  43. package/dist/file-durable-slot.js.map +1 -0
  44. package/dist/formation-approval.d.ts +157 -0
  45. package/dist/formation-approval.js +375 -0
  46. package/dist/formation-approval.js.map +1 -0
  47. package/dist/fs-atomic.d.ts +38 -0
  48. package/dist/fs-atomic.js +97 -0
  49. package/dist/fs-atomic.js.map +1 -0
  50. package/dist/identity-key.d.ts +49 -0
  51. package/dist/identity-key.js +81 -0
  52. package/dist/identity-key.js.map +1 -0
  53. package/dist/index.d.ts +17 -7
  54. package/dist/index.js +40 -6
  55. package/dist/index.js.map +1 -1
  56. package/dist/key-store-file.d.ts +2 -24
  57. package/dist/key-store-file.js +10 -77
  58. package/dist/key-store-file.js.map +1 -1
  59. package/dist/membership-connection-gater.d.ts +146 -0
  60. package/dist/membership-connection-gater.js +180 -0
  61. package/dist/membership-connection-gater.js.map +1 -0
  62. package/dist/node-local-snapshot.d.ts +109 -0
  63. package/dist/node-local-snapshot.js +182 -0
  64. package/dist/node-local-snapshot.js.map +1 -0
  65. package/dist/peer-addr-book.d.ts +92 -0
  66. package/dist/peer-addr-book.js +220 -0
  67. package/dist/peer-addr-book.js.map +1 -0
  68. package/dist/peer-authorization.d.ts +135 -18
  69. package/dist/peer-authorization.js +152 -21
  70. package/dist/peer-authorization.js.map +1 -1
  71. package/dist/peer-record.d.ts +21 -8
  72. package/dist/peer-record.js +26 -10
  73. package/dist/peer-record.js.map +1 -1
  74. package/dist/relay-addrs.d.ts +45 -0
  75. package/dist/relay-addrs.js +103 -0
  76. package/dist/relay-addrs.js.map +1 -0
  77. package/dist/relay-reservation.d.ts +266 -0
  78. package/dist/relay-reservation.js +613 -0
  79. package/dist/relay-reservation.js.map +1 -0
  80. package/dist/seed-bootstrap.d.ts +228 -56
  81. package/dist/seed-bootstrap.js +340 -198
  82. package/dist/seed-bootstrap.js.map +1 -1
  83. package/dist/seed-trust-policy.d.ts +47 -21
  84. package/dist/seed-trust-policy.js +24 -15
  85. package/dist/seed-trust-policy.js.map +1 -1
  86. package/dist/strand-addr-protocol.d.ts +42 -13
  87. package/dist/strand-addr-protocol.js +58 -52
  88. package/dist/strand-addr-protocol.js.map +1 -1
  89. package/dist/strand-backfill.d.ts +109 -0
  90. package/dist/strand-backfill.js +279 -0
  91. package/dist/strand-backfill.js.map +1 -0
  92. package/dist/strand-cohort.d.ts +4 -37
  93. package/dist/strand-cohort.js +4 -15
  94. package/dist/strand-cohort.js.map +1 -1
  95. package/dist/strand-database.d.ts +11 -16
  96. package/dist/strand-database.js +19 -7
  97. package/dist/strand-database.js.map +1 -1
  98. package/dist/strand-formation-manager.d.ts +36 -7
  99. package/dist/strand-formation-manager.js +115 -15
  100. package/dist/strand-formation-manager.js.map +1 -1
  101. package/dist/strand-formation-protocol.d.ts +103 -4
  102. package/dist/strand-formation-protocol.js +232 -4
  103. package/dist/strand-formation-protocol.js.map +1 -1
  104. package/dist/strand-instance-manager.d.ts +88 -19
  105. package/dist/strand-instance-manager.js +178 -34
  106. package/dist/strand-instance-manager.js.map +1 -1
  107. package/dist/strand-member-registry.d.ts +5 -5
  108. package/dist/strand-member-registry.js +18 -10
  109. package/dist/strand-member-registry.js.map +1 -1
  110. package/dist/strand-membership-writer.d.ts +484 -88
  111. package/dist/strand-membership-writer.js +751 -128
  112. package/dist/strand-membership-writer.js.map +1 -1
  113. package/dist/strand-solicitation.d.ts +99 -33
  114. package/dist/strand-solicitation.js +100 -52
  115. package/dist/strand-solicitation.js.map +1 -1
  116. package/dist/strand-transport-key.d.ts +40 -0
  117. package/dist/strand-transport-key.js +56 -0
  118. package/dist/strand-transport-key.js.map +1 -0
  119. package/dist/strand-wake-protocol.d.ts +9 -7
  120. package/dist/strand-wake-protocol.js +22 -46
  121. package/dist/strand-wake-protocol.js.map +1 -1
  122. package/dist/strand-watcher.d.ts +17 -2
  123. package/dist/strand-watcher.js +47 -3
  124. package/dist/strand-watcher.js.map +1 -1
  125. package/dist/trusted-owner-store-file.d.ts +12 -0
  126. package/dist/trusted-owner-store-file.js +39 -0
  127. package/dist/trusted-owner-store-file.js.map +1 -0
  128. package/dist/trusted-owner-store.d.ts +64 -0
  129. package/dist/trusted-owner-store.js +126 -0
  130. package/dist/trusted-owner-store.js.map +1 -0
  131. package/dist/types.d.ts +307 -44
  132. package/dist/types.js +13 -0
  133. package/dist/types.js.map +1 -1
  134. package/package.json +20 -8
  135. package/src/arachnode-stub.ts +159 -159
  136. package/src/bootstrap-peer-store-file.ts +44 -0
  137. package/src/bootstrap-peer-store.ts +172 -0
  138. package/src/cadre-node.ts +5158 -2981
  139. package/src/canonical-json.ts +30 -30
  140. package/src/control-authorization.ts +114 -0
  141. package/src/control-cohort.ts +130 -103
  142. package/src/control-database.ts +2406 -948
  143. package/src/control-formation-recorder.ts +305 -151
  144. package/src/control-schema.ts +651 -72
  145. package/src/control-stream.ts +205 -128
  146. package/src/control-write-retry.ts +483 -0
  147. package/src/delegate-admission.ts +302 -0
  148. package/src/device-token.ts +94 -89
  149. package/src/diagnostics/connection-path.ts +277 -277
  150. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  151. package/src/ed25519-key.ts +66 -1
  152. package/src/enrollment.ts +199 -199
  153. package/src/file-durable-slot.ts +61 -0
  154. package/src/formation-approval.ts +604 -0
  155. package/src/fs-atomic.ts +107 -0
  156. package/src/hibernation-manager.ts +437 -437
  157. package/src/identity-key.ts +109 -0
  158. package/src/index.ts +137 -5
  159. package/src/key-store-file.ts +132 -203
  160. package/src/key-store.ts +99 -99
  161. package/src/membership-connection-gater.ts +204 -0
  162. package/src/node-local-snapshot.ts +260 -0
  163. package/src/peer-addr-book.ts +250 -0
  164. package/src/peer-authorization.ts +259 -81
  165. package/src/peer-record.ts +164 -146
  166. package/src/push-credentials.ts +84 -84
  167. package/src/push-node.ts +64 -64
  168. package/src/push-notifier-apns.ts +247 -247
  169. package/src/push-notifier-fcm.ts +220 -220
  170. package/src/push-notifier-shared.ts +28 -28
  171. package/src/push-notifier.ts +52 -52
  172. package/src/relay-addrs.ts +111 -0
  173. package/src/relay-reservation.ts +823 -0
  174. package/src/seed-bootstrap.ts +409 -209
  175. package/src/seed-trust-policy.ts +140 -107
  176. package/src/strand-addr-protocol.ts +441 -410
  177. package/src/strand-backfill.ts +366 -0
  178. package/src/strand-cohort.ts +38 -77
  179. package/src/strand-database.ts +202 -204
  180. package/src/strand-formation-manager.ts +491 -368
  181. package/src/strand-formation-protocol.ts +692 -391
  182. package/src/strand-instance-manager.ts +201 -46
  183. package/src/strand-member-key.ts +39 -39
  184. package/src/strand-member-registry.ts +182 -177
  185. package/src/strand-membership-writer.ts +938 -146
  186. package/src/strand-solicitation.ts +472 -407
  187. package/src/strand-transport-key.ts +58 -0
  188. package/src/strand-wake-payload.ts +32 -32
  189. package/src/strand-wake-protocol.ts +314 -331
  190. package/src/strand-watcher.ts +314 -251
  191. package/src/trusted-owner-store-file.ts +41 -0
  192. package/src/trusted-owner-store.ts +171 -0
  193. package/src/types.ts +1309 -1032
@@ -14,26 +14,125 @@ declare schema CadreControl {
14
14
  -- A key that can authorize various control changes
15
15
  table OwnerKey (
16
16
  Key text primary key,
17
- StampId text not null unique, -- single-use authorization nonce (anti-replay)
18
- constraint Authorized check (
19
- -- Bootstrap: first owner key needs no existing authorization
20
- (select count(1) from OwnerKey) <= 1
17
+ StampId text not null unique, -- per-row authorization nonce, bound into the signed digests below.
18
+ -- \`unique\` holds over LIVE rows only; a removed row's stamp is retired
19
+ -- permanently into Revocation (NotRevoked below), so the never-expiring
20
+ -- enrollment signature cannot resurrect a removed owner.
21
+ -- A removed row's StampId is retired into Revocation, and this refuses any insert
22
+ -- naming a retired stamp: the approval that seated this row can never re-seat it after
23
+ -- removal. \`unique\` alone did not do this — it only holds over LIVE rows, so a delete
24
+ -- freed the stamp and the original never-expiring signature verified again. A
25
+ -- legitimate re-add mints a FRESH StampId and a fresh signature, so it is unaffected.
26
+ constraint NotRevoked check on insert (
27
+ not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = new.StampId)
28
+ ),
29
+ -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same
30
+ -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling
31
+ -- insert is visible at commit regardless of statement order. The tombstone must also
32
+ -- name the removed ROW, not just its stamp — see Revocation.RowKey.
33
+ constraint RevocationRecorded check on delete (
34
+ exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = old.StampId and R.RowKey = old.Key)
35
+ ),
36
+ -- A party must never lose its last owner key: every other CadreControl table's
37
+ -- CHECK requires an OwnerKey row, so an owner-less control database can never
38
+ -- authorize anything again — emptying this table is a permanent denial of the
39
+ -- party's control plane. Deferred (subquery), so the count is the POST-delete count.
40
+ -- NOTE: this is a per-transaction check against locally visible rows. Two
41
+ -- partitioned nodes that concurrently remove different owners can each see a
42
+ -- survivor and still converge to zero; if partitioned rotation ever becomes a real
43
+ -- workflow, the floor needs a cross-node guard, not a local count.
44
+ constraint MinOneOwner check on delete (
45
+ (select count(1) from OwnerKey) >= 1
46
+ ),
47
+ -- Enrollment is insert + delete only; rotation is add-then-remove. No writer
48
+ -- updates an OwnerKey row, and a self-rotation branch would double as a sole-owner
49
+ -- takeover: a deferred post-image count is also true of an update that re-points
50
+ -- the only row at an attacker key. Mirrors Strand.Manager.NoUpdate.
51
+ constraint NoUpdate check on update (false),
52
+ -- NOTE: the domain tag scopes an approval to a table and an action, not to a PARTY. Two
53
+ -- parties that share an owner key would accept each other's approvals. Fine today (each
54
+ -- party has its own owner key); if shared-owner multi-party ever ships, bind a party
55
+ -- identity row into these digests.
56
+ constraint Authorized check on insert, delete (
57
+ -- Every authorizer is read from the PRE-transaction snapshot (committed.*):
58
+ -- this CHECK auto-defers to commit (it has a subquery), by which point the row
59
+ -- being inserted — and any sibling inserted alongside it — is live, so a plain
60
+ -- from-OwnerKey would let a row authorize itself, or two strangers seat each
61
+ -- other. committed.* excludes both, stating the rule directly: the authorizer
62
+ -- must have existed BEFORE this transaction.
21
63
 
22
- -- Old owner authorizes by signing over THIS row (Key, StampId); single-use via unique StampId
23
- or (old.Key is not null and old.Key = context.OwnerKey and verify(digest(new.Key, new.StampId), context.Signature, old.Key, 'ed25519'))
64
+ -- Every signed digest below (and in every other CadreControl table) leads with two
65
+ -- fixed literals — a 'CadreControl.<Table>' domain tag and an 'add'/'remove'/
66
+ -- 'vouch'/'publish' action tag (cadre-core control-authorization.ts) — so an
67
+ -- approval verifies ONLY against the one rule it was minted for. Without them,
68
+ -- e.g. a ValidationKey enrollment approval covered the identical bytes as an
69
+ -- OwnerKey enrollment: a narrow grant that doubled as full ownership.
24
70
 
25
- -- or other owners authorize by signing over THIS row (Key, StampId); single-use via unique StampId
26
- or exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest(new.Key, new.StampId), context.Signature, A.Key, 'ed25519'))
71
+ -- Bootstrap: the FOUNDING transaction — one whose pre-transaction owner set is
72
+ -- empty — needs no authorization, and every row it inserts rides this branch
73
+ -- (whoever writes it already owns the party outright, so a co-founder row grants
74
+ -- nothing a single row would not). Gated on the PRE-transaction count, so a
75
+ -- same-transaction swap of the sole owner (delete the founder, insert the
76
+ -- attacker — post-image count still 1) cannot ride it.
77
+ (old.Key is null and (select count(1) from committed.OwnerKey) = 0)
78
+
79
+ -- or a pre-existing owner authorizes by signing over THIS row (Key, StampId)
80
+ or (old.Key is null and exists (select 1 from committed.OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.OwnerKey', 'add', new.Key, new.StampId), context.Signature, A.Key, 'ed25519')))
81
+
82
+ -- or a removal authorized by ANOTHER pre-existing owner over the DISTINCT
83
+ -- 'remove'-tagged digest bound to the stored row's StampId, so an enrollment
84
+ -- signature can never be replayed as a removal (cf. CadrePeer.AuthorizedDelete).
85
+ -- A.Key <> old.Key: an owner cannot sign its own removal (no self-resignation).
86
+ or (new.Key is null and exists (select 1 from committed.OwnerKey A where A.Key = context.OwnerKey and A.Key <> old.Key and verify(digest('CadreControl.OwnerKey', 'remove', old.Key, old.StampId), context.Signature, A.Key, 'ed25519')))
27
87
  )
28
88
  ) with context (OwnerKey text null, Signature text null);
29
89
 
30
90
  -- A key that can validate a strand formation disclosure
31
91
  table ValidationKey (
32
92
  Key text primary key,
33
- StampId text not null unique, -- single-use authorization nonce (anti-replay)
34
- constraint Authorized check (
93
+ StampId text not null unique, -- single-use authorization nonce (anti-replay).
94
+ -- \`unique\` holds over LIVE rows only; a removed row's stamp is retired
95
+ -- permanently into Revocation (NotRevoked below), so the never-expiring
96
+ -- enrollment signature cannot resurrect a removed key.
97
+ -- A removed row's StampId is retired into Revocation, and this refuses any insert naming
98
+ -- a retired stamp: the approval that seated this row can never re-seat it after removal.
99
+ -- Same rationale as OwnerKey.NotRevoked, stated in full there.
100
+ -- NOTE: this table gained a consumer — FormationUsage.Authorized reads it to gate redemption of
101
+ -- a ValidationUrl invite — so the convergence gap noted on Strand.StampId now has teeth here: on
102
+ -- a node that has not yet seen the tombstone, a replayed enrollment re-seats the key and it can
103
+ -- approve redemptions there until the Revocation row arrives. Still no per-request READ surface to
104
+ -- filter (the gate is a write-time CHECK), so there is nothing to add today; if one appears, filter
105
+ -- retired stamps there.
106
+ constraint NotRevoked check on insert (
107
+ not exists (select 1 from Revocation R where R.TableName = 'ValidationKey' and R.StampId = new.StampId)
108
+ ),
109
+ -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same
110
+ -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling
111
+ -- insert is visible at commit regardless of statement order. The tombstone must also
112
+ -- name the removed ROW, not just its stamp — see Revocation.RowKey.
113
+ constraint RevocationRecorded check on delete (
114
+ exists (select 1 from Revocation R where R.TableName = 'ValidationKey' and R.StampId = old.StampId and R.RowKey = old.Key)
115
+ ),
116
+ -- Enrollment is insert + delete only; rotation is add-then-remove. No writer in the repo
117
+ -- updates a ValidationKey row. Required because the AuthorizedInsert / AuthorizedDelete
118
+ -- pair below covers neither update — and a bare \`check\`, which is what this rule used to
119
+ -- be, covers insert+update but NOT delete. Mirrors OwnerKey.NoUpdate.
120
+ constraint NoUpdate check on update (false),
121
+ constraint AuthorizedInsert check on insert (
35
122
  -- Owners authorize by signing over THIS row (Key, StampId); single-use via unique StampId
36
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest(new.Key, new.StampId), context.Signature, A.Key, 'ed25519'))
123
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.ValidationKey', 'add', new.Key, new.StampId), context.Signature, A.Key, 'ed25519'))
124
+ ),
125
+ constraint AuthorizedDelete check on delete (
126
+ -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest bound to
127
+ -- the STORED row (Key, StampId), so an enrollment approval — which never expires — can
128
+ -- never be replayed as a removal. Same shape as CadrePeer.AuthorizedDelete.
129
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.ValidationKey', 'remove', old.Key, old.StampId), context.Signature, A.Key, 'ed25519'))
130
+
131
+ -- or REAP: a COMMITTED tombstone already retires this exact row incarnation, so a node
132
+ -- that was offline at removal time may delete the stale row locally with no owner key.
133
+ -- Why committed.* and why the stamp must be bound: stated in full on
134
+ -- CadrePeer.AuthorizedDelete.
135
+ or exists (select 1 from committed.Revocation R where R.TableName = 'ValidationKey' and R.RowKey = old.Key and R.StampId = old.StampId)
37
136
  )
38
137
  ) with context (OwnerKey text, Signature text);
39
138
 
@@ -43,15 +142,133 @@ declare schema CadreControl {
43
142
  Id text primary key, -- UUID
44
143
  MemberPrivateKey text null unique, -- Our private key as a member of this strand
45
144
  Type text, -- Types: 'o' = Open, 'c' = Closed -- Open can still control writes in the sApp, but only Closed controls reads
46
- StampId text not null unique, -- single-use authorization nonce (anti-replay)
47
- constraint Authorized check (
145
+ StampId text not null unique, -- single-use authorization nonce (anti-replay).
146
+ -- \`unique\` holds over LIVE rows only; a removed row's stamp is retired
147
+ -- permanently into Revocation (NotRevoked below).
148
+ -- NOTE: NotRevoked is a per-transaction check against LOCALLY VISIBLE rows, so a node that
149
+ -- has not yet converged on the Revocation row can still accept a replayed add and end up
150
+ -- holding the resurrected strand alongside its tombstone. CadrePeer has a read-side
151
+ -- mitigation for this class (ControlDatabase.queryCadrePeers drops rows whose stamp is
152
+ -- retired, so every membership reader inherits it); Strand and ValidationKey deliberately
153
+ -- do NOT, because neither has a
154
+ -- per-request authorization surface today. If one ever gains one, filter it there.
155
+ constraint NotRevoked check on insert (
156
+ not exists (select 1 from Revocation R where R.TableName = 'Strand' and R.StampId = new.StampId)
157
+ ),
158
+ -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same
159
+ -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling
160
+ -- insert is visible at commit regardless of statement order. The tombstone must also
161
+ -- name the removed ROW, not just its stamp — see Revocation.RowKey. That is what makes
162
+ -- the consent branch of AuthorizedInsert below trustworthy: a removal cannot file a
163
+ -- tombstone that omits or misnames the id it retires.
164
+ constraint RevocationRecorded check on delete (
165
+ exists (select 1 from Revocation R where R.TableName = 'Strand' and R.StampId = old.StampId and R.RowKey = old.Id)
166
+ ),
167
+ -- Strand rows are insert + delete only. Required: the consent branch of AuthorizedInsert
168
+ -- below authorizes by the EXISTENCE of a FormationUsage row naming (new.Id, new.StampId)
169
+ -- and carries no signature, so while this rule was a bare \`check\` (insert+update) it also
170
+ -- said "anyone may REWRITE any consent-formed strand, unsigned" — flipping Type to 'o' and
171
+ -- nulling MemberPrivateKey destroys the party's own membership key for that network in place.
172
+ -- Mirrors OwnerKey.NoUpdate / FormationInvite.Immutable.
173
+ constraint NoUpdate check on update (false),
174
+ constraint AuthorizedInsert check on insert (
48
175
  -- Authorized by an owner signing over THIS row (Id, Type, MemberPrivateKey, StampId); single-use via unique StampId
49
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest(new.Id, new.Type, coalesce(new.MemberPrivateKey, ''), new.StampId), context.Signature, A.Key, 'ed25519'))
176
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.Strand', 'add', new.Id, new.Type, coalesce(new.MemberPrivateKey, ''), new.StampId), context.Signature, A.Key, 'ed25519'))
50
177
 
51
- -- or authorized by a cadre peer who has received a valid formation invitation.
52
- -- That path has no signed writer yet; when one is built it must still supply a
53
- -- fresh, unique StampId to satisfy the not-null/unique anti-replay column.
54
- or exists (select 1 from FormationUsage FU where FU.StrandId = new.Id)
178
+ -- or authorized WITHOUT a signature by a redemption record naming THIS EXACT ROW: a
179
+ -- FormationUsage row carrying both this strand's Id and its one-off StampId
180
+ -- (control-database.ts:redeemInvitation writes the pair in one transaction; both
181
+ -- CHECKs defer, so each sees the other's row at commit).
182
+ --
183
+ -- Matching the STAMP, not the id alone, is what makes a removal stick. FormationUsage
184
+ -- is append-only, so a redemption record outlives the strand it formed forever; keyed
185
+ -- on the id alone it re-authorized ANY later insert of that id, so after a legitimate
186
+ -- owner-signed, tombstoned removal any writer could re-seat the strand unsigned with a
187
+ -- fresh StampId (sidestepping NotRevoked, which retires only the removed row's stamp)
188
+ -- and an ATTACKER-CHOSEN MemberPrivateKey — the party's own secret for that network.
189
+ -- Bound to the stamp, the removal retires that stamp into Revocation and NotRevoked
190
+ -- closes this consent record's branch permanently.
191
+ --
192
+ -- Beyond the stamp match, the branch is deliberately NARROW — each clause closes one door:
193
+ -- * Type = 'o' / MemberPrivateKey null — a consent-seated strand looks exactly like
194
+ -- what the unbound redemption path writes (open, keyless). A closed strand carrying
195
+ -- a caller-chosen member key (the party's own read-gating secret for that network)
196
+ -- has no legitimate producer. MemberKeyClosedOnly already implies the second clause
197
+ -- from the first today; both are stated so this rule does not silently depend on
198
+ -- another constraint staying as it is.
199
+ -- * the inner FI.StrandId is null — only an UNBOUND invite may seat a strand at all.
200
+ -- A bound invite's host strand is owner-provisioned up front; letting the invite
201
+ -- consent-seat that id would allow an open, keyless downgrade of the real (possibly
202
+ -- closed, key-bearing) host row on a node where it has not converged yet. The bound
203
+ -- path records usage only (resolveStrand reports an absent host as missing and the
204
+ -- formation manager rejects cleanly).
205
+ -- * the not-exists over OTHER stamps — a strand id may be consent-seated once, EVER.
206
+ -- FormationUsage is append-only, so the first redemption's record survives a later
207
+ -- owner-signed removal and permanently forecloses a second consent-seating of the
208
+ -- id (a spare use of the same token minted a new stamp and rode this branch to
209
+ -- re-seat the id with an attacker-chosen row). Re-joining a removed id is
210
+ -- owner-gated: the owner re-seats it signed (fresh stamp, fresh signature) and
211
+ -- issues a BOUND invite the returning party records consent against — the id is
212
+ -- not blacklisted, only its unsigned re-seat is. This cannot be weaponised to
213
+ -- pre-block a legitimate id: StrandExists refuses a usage row naming a strand that
214
+ -- does not exist, so no usage row can be pre-planted for an unseated id — and ids
215
+ -- are 128 random bytes anyway.
216
+ -- * the not-exists over Revocation — a strand id may be consent-seated once EVER
217
+ -- and never after ANY removal of that id, however it was seated. The usage-row
218
+ -- rule above binds only ids that ever carried a consent record; an id seated
219
+ -- purely owner-signed (insertStrand, no usage row) leaves nothing behind on
220
+ -- removal, so its removal needs its own trace. Every removal files a Revocation
221
+ -- row naming the removed row's key (RowKey), and this clause refuses any id
222
+ -- that has ever been tombstoned. RevocationRecorded above makes that trace
223
+ -- mandatory AND correctly named, so no removal can slip past this clause. The
224
+ -- usage-row clause is arguably subsumed by this one (a usage row implies the
225
+ -- strand row existed, and its removal must file a tombstone), but it reaches
226
+ -- the same conclusion without depending on Revocation at all; both are stated,
227
+ -- per the style note above. The owner-signed branch is deliberately unaffected,
228
+ -- so re-join stays owner-gated exactly as described.
229
+ -- What is NOT schema-verified is a STANDALONE tombstone (one with no
230
+ -- accompanying delete — see Revocation.Authorized): an owner can file one
231
+ -- naming an id that never existed and thereby permanently foreclose
232
+ -- consent-seating of that id — owner-only, the owner already controls invite
233
+ -- issuance, and unbound ids are 128 random bytes minted at redemption, so no
234
+ -- escalation (same reasoning as the pre-plant note above).
235
+ -- NOTE: like NotRevoked above, this is a write-time check against LOCALLY
236
+ -- VISIBLE rows — a node that has not yet converged on the Revocation row still
237
+ -- accepts the re-seat. Fails in the safe direction: the tombstone wins after
238
+ -- merge for the STAMP, and the resurrected row coexists with it (same class as
239
+ -- the StampId note above).
240
+ or (
241
+ new.Type = 'o'
242
+ and new.MemberPrivateKey is null
243
+ and exists (
244
+ select 1 from FormationUsage FU
245
+ where FU.StrandId = new.Id
246
+ and FU.StrandStampId = new.StampId
247
+ and exists (select 1 from FormationInvite FI where FI.Token = FU.Token and FI.StrandId is null)
248
+ )
249
+ and not exists (
250
+ select 1 from FormationUsage FU2
251
+ where FU2.StrandId = new.Id and FU2.StrandStampId <> new.StampId
252
+ )
253
+ and not exists (
254
+ select 1 from Revocation R
255
+ where R.TableName = 'Strand' and R.RowKey = new.Id
256
+ )
257
+ )
258
+ ),
259
+ constraint AuthorizedDelete check on delete (
260
+ -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest bound to
261
+ -- the STORED row (Id, StampId), so the add approval — which never expires — can never be
262
+ -- replayed as a removal. Note the consent branch above is deliberately NOT mirrored
263
+ -- here: an invitation authorizes forming a strand, never destroying one.
264
+ --
265
+ -- DELIBERATELY no REAP branch (cf. CadrePeer.AuthorizedDelete): this row carries
266
+ -- MemberPrivateKey — the party's own membership secret for that network, stored nowhere
267
+ -- else — so this is the one guarded delete whose effect is unrecoverable, and a stale
268
+ -- row is already inert for the purpose a tombstone serves (the consent branch of
269
+ -- AuthorizedInsert above refuses any id ever tombstoned). Do not "fix" the asymmetry;
270
+ -- tickets/backlog/debt-strand-tombstone-reap.md owns any future change.
271
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.Strand', 'remove', old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))
55
272
  ),
56
273
  constraint MemberKeyClosedOnly check (
57
274
  -- An open strand ('o') has no membership gate, so it must not carry a
@@ -70,15 +287,34 @@ declare schema CadreControl {
70
287
  Multiaddr text, -- comma-joined current addrs (signaling / p2p-circuit first)
71
288
  UpdatedAt int null, -- epoch ms; strictly increases per self-update (replay/rollback guard)
72
289
  Sig text null, -- ed25519 self-signature over the signed payload (base64url); null until self-published
73
- StampId text not null unique, -- single-use authorization nonce (anti-replay), bound into the voucher/remove digests; rotates on (re)insert
290
+ StampId text not null unique, -- per-row authorization nonce, bound into the voucher/remove digests; rotates on
291
+ -- (re)insert. A removed row's stamp is retired permanently into Revocation
292
+ -- (NotRevoked below), so a captured admission approval cannot re-seat a removed peer.
74
293
  VouchOwner text null, -- ed25519 (base64url) owner key that vouched this membership (== insert context.OwnerKey)
75
- VouchSig text null, -- that owner's signature over digest(PeerId, StampId) (== insert context.Signature). A reader checks VouchOwner against its NODE-LOCAL trusted-owner anchor (not this replicated table, which a self-owner can pollute) to decide authorized membership.
294
+ VouchSig text null, -- that owner's signature over the 'vouch'-tagged digest below (== insert context.Signature). A reader checks VouchOwner against its NODE-LOCAL trusted-owner anchor (not this replicated table, which a self-owner can pollute) to decide authorized membership. The domain/action tags keep this STORED, REPLICATED signature useless against every other rule (pre-tag it satisfied OwnerKey/ValidationKey inserts for Key = PeerId).
295
+ -- A removed row's StampId is retired into Revocation, and this refuses any insert
296
+ -- naming a retired stamp: the approval that seated this row can never re-seat it after
297
+ -- removal. \`unique\` alone did not do this — it only holds over LIVE rows, so a delete
298
+ -- freed the stamp and the original never-expiring signature verified again. A
299
+ -- legitimate re-add mints a FRESH StampId and a fresh signature, so it is unaffected.
300
+ constraint NotRevoked check on insert (
301
+ not exists (select 1 from Revocation R where R.TableName = 'CadrePeer' and R.StampId = new.StampId)
302
+ ),
303
+ -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same
304
+ -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling
305
+ -- insert is visible at commit regardless of statement order. The tombstone must also
306
+ -- name the removed ROW, not just its stamp — see Revocation.RowKey.
307
+ constraint RevocationRecorded check on delete (
308
+ exists (select 1 from Revocation R where R.TableName = 'CadrePeer' and R.StampId = old.StampId and R.RowKey = old.PeerId)
309
+ ),
76
310
  constraint AuthorizedInsert check on insert (
77
311
  -- Authorized by an owner key, which vouches both membership and the
78
312
  -- PublicKey<->PeerId binding (cadre-core derives PublicKey from PeerId before insert).
79
313
  -- The digest binds PeerId + the single-use StampId nonce (two TEXT fields),
80
- -- matching cadre-core peer-authorization.ts:cadrePeerVoucherDigest.
81
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest(new.PeerId, new.StampId), context.Signature, A.Key, 'ed25519'))
314
+ -- matching cadre-core peer-authorization.ts:cadrePeerVoucherDigest. The same
315
+ -- 'vouch'-tagged digest is DELIBERATELY shared with the owner branch of
316
+ -- AuthorizedUpdate below: both mean "this owner vouches this membership row".
317
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.CadrePeer', 'vouch', new.PeerId, new.StampId), context.Signature, A.Key, 'ed25519'))
82
318
  -- Persist the vouching (owner, signature) onto the row so a reader can later
83
319
  -- re-check VouchOwner against its node-local anchor. The stored pair MUST equal
84
320
  -- the pair the verify above validated, so a writer cannot store a voucher it did
@@ -87,11 +323,34 @@ declare schema CadreControl {
87
323
  and new.VouchSig = context.Signature
88
324
  ),
89
325
  constraint AuthorizedDelete check on delete (
90
- -- Delete is authorized by a signature over a DISTINCT 'remove'-scoped digest bound
326
+ -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest bound
91
327
  -- to the row's StampId (cadre-core peer-authorization.ts:cadrePeerRemoveDigest), so
92
- -- the stored voucher (a signature over digest(PeerId, StampId)) can NEVER be replayed
93
- -- to authorize a delete. The remove signature rides in context and is never stored.
94
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest(old.PeerId, old.StampId, 'remove'), context.Signature, A.Key, 'ed25519'))
328
+ -- the stored voucher (a signature over the 'vouch'-tagged digest) can NEVER be
329
+ -- replayed to authorize a delete. The remove signature rides in context and is never stored.
330
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.CadrePeer', 'remove', old.PeerId, old.StampId), context.Signature, A.Key, 'ed25519'))
331
+
332
+ -- or REAP: this node already holds a COMMITTED tombstone retiring THIS EXACT row
333
+ -- incarnation, so the party owner has already authorized this row's removal and this
334
+ -- node is merely catching up. That is what lets a node which was offline at
335
+ -- revocation time delete the stale row locally, with no owner private key
336
+ -- (control-database.ts:reapRevokedRow). Same shape as the consent branch of
337
+ -- Strand.AuthorizedInsert: authorization by the EXISTENCE of a row rather than by a
338
+ -- signature — and that row is itself owner-signed (Revocation.Authorized), so this
339
+ -- widens WHO may execute a removal, never WHO may decide one. RevocationRecorded is
340
+ -- satisfied by the same committed tombstone, so a reap files no second one.
341
+ --
342
+ -- committed.Revocation, NOT Revocation — and the stamp clause — are both load-bearing:
343
+ -- * committed.* : this CHECK defers to commit (it has a subquery), by which point a
344
+ -- tombstone written in the SAME transaction is live. Reading plain Revocation
345
+ -- would therefore let deleteGuardedRow's own sibling tombstone satisfy this
346
+ -- branch, making the 'remove'-tagged delete signature above dead weight and
347
+ -- collapsing two domain-separated approvals into one. committed.* states the rule
348
+ -- exactly: the tombstone must have existed BEFORE this transaction.
349
+ -- * R.StampId = old.StampId : binds the ROW INCARNATION, not the name. One name may
350
+ -- legitimately carry several tombstones over its life (seat -> delete -> owner
351
+ -- re-seat -> delete). Without this clause a tombstone from a PREVIOUS incarnation
352
+ -- would authorize deleting the CURRENT row, which the owner never removed.
353
+ or exists (select 1 from committed.Revocation R where R.TableName = 'CadrePeer' and R.RowKey = old.PeerId and R.StampId = old.StampId)
95
354
  ),
96
355
  constraint AuthorizedUpdate check on update (
97
356
  -- Peer self-updates its own addrs + freshness, signing with its OWN ed25519 key
@@ -107,13 +366,19 @@ declare schema CadreControl {
107
366
  and new.VouchSig = old.VouchSig
108
367
  and new.UpdatedAt > coalesce(old.UpdatedAt, 0)
109
368
  and verify(
110
- digest(new.PeerId || '|' || new.Multiaddr || '|' || cast(new.UpdatedAt as text)),
369
+ digest('CadreControl.CadrePeer', 'publish', new.PeerId, new.Multiaddr, cast(new.UpdatedAt as text)),
111
370
  new.Sig, new.PublicKey, 'ed25519')
112
371
  )
113
372
  -- or an owner re-authorizes (rotation / correction): re-vouches the row over
114
373
  -- its current StampId, so the stored voucher is re-bound to the re-authorizing owner.
374
+ -- StampId is immutable here too: an update that rotated it would leave the OLD
375
+ -- stamp live-free and untombstoned (RevocationRecorded only retires the stamp a
376
+ -- delete carries), so the original admission approval — which is stored on the
377
+ -- replicated row as VouchSig — would resurrect the peer after a later removal.
378
+ -- Retiring a stamp is delete + Revocation row, never an update.
115
379
  or (
116
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest(new.PeerId, new.StampId), context.Signature, A.Key, 'ed25519'))
380
+ new.StampId = old.StampId
381
+ and exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.CadrePeer', 'vouch', new.PeerId, new.StampId), context.Signature, A.Key, 'ed25519'))
117
382
  and new.VouchOwner = context.OwnerKey
118
383
  and new.VouchSig = context.Signature
119
384
  )
@@ -132,26 +397,86 @@ declare schema CadreControl {
132
397
  Token text not null, -- opaque platform device/registration token
133
398
  UpdatedAt int null, -- epoch ms; strictly increases per self-update (replay guard)
134
399
  Sig text null, -- ed25519 self-sig over (PeerId|Platform|Token|UpdatedAt)
135
- constraint AuthorizedInsert check on insert, delete (
400
+ StampId text not null unique, -- single-use authorization nonce, bound into the add/remove digests;
401
+ -- rotates on (re)insert. A cleared token's stamp is retired permanently
402
+ -- into Revocation (NotRevoked below), so the approval that published a
403
+ -- token cannot re-seat it after the owner cleared it (logout).
404
+ -- A removed row's StampId is retired into Revocation, and this refuses any insert
405
+ -- naming a retired stamp: the approval that seated this row can never re-seat it after
406
+ -- the clear. \`unique\` alone did not do this — it only holds over LIVE rows, so a delete
407
+ -- freed the stamp and the original never-expiring signature verified again. A legitimate
408
+ -- re-register mints a FRESH StampId and a fresh signature, so it is unaffected. This
409
+ -- matters more here than the stored-approval case (CadrePeer.VouchSig): a resurrected
410
+ -- push token has NO freshness ceiling to retire it — cadre-node.ts:resolveDeviceToken
411
+ -- defaults maxAgeMs to infinity by design — so retirement is the only thing that sticks.
412
+ constraint NotRevoked check on insert (
413
+ not exists (select 1 from Revocation R where R.TableName = 'DeviceToken' and R.StampId = new.StampId)
414
+ ),
415
+ -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same
416
+ -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling
417
+ -- insert is visible at commit regardless of statement order. The tombstone must also
418
+ -- name the removed ROW, not just its stamp — see Revocation.RowKey.
419
+ constraint RevocationRecorded check on delete (
420
+ exists (select 1 from Revocation R where R.TableName = 'DeviceToken' and R.StampId = old.StampId and R.RowKey = old.PeerId)
421
+ ),
422
+ constraint AuthorizedInsert check on insert (
136
423
  -- Authorized by an owner key (membership vouch), exactly like CadrePeer.
137
- -- The single-field digest frames the base58btc PeerId as TEXT.
138
- exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest(coalesce(new.PeerId, old.PeerId)), context.Signature, A.Key, 'ed25519'))
424
+ -- The digest binds the WHOLE row behind the domain/action tags — every column,
425
+ -- with the nullable UpdatedAt/Sig signing as '' when absent (the shape
426
+ -- FormationInvite and Strand already use) — so a replayed approval can only ever
427
+ -- reproduce the row it approved, never one carrying attacker-chosen
428
+ -- Platform/Token/UpdatedAt; NotRevoked above then refuses even that exact row
429
+ -- once it has been cleared. The DISTINCT 'remove'-tagged digest below keeps a
430
+ -- captured insert approval from doubling as a delete (and vice versa).
431
+ -- Mirrors cadre-core peer-authorization.ts:deviceTokenAddDigest.
432
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(
433
+ digest(
434
+ 'CadreControl.DeviceToken', 'add',
435
+ new.PeerId,
436
+ new.Platform,
437
+ new.Token,
438
+ coalesce(cast(new.UpdatedAt as text), ''),
439
+ coalesce(new.Sig, ''),
440
+ new.StampId
441
+ ),
442
+ context.Signature, A.Key, 'ed25519'))
443
+ ),
444
+ constraint AuthorizedDelete check on delete (
445
+ -- Bound to the STORED row's (PeerId, StampId) — cadre-core
446
+ -- peer-authorization.ts:deviceTokenRemoveDigest — so the never-expiring insert
447
+ -- approval can never be replayed as a clear, and a captured clear approval is
448
+ -- dead once the stamp it names is retired.
449
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.DeviceToken', 'remove', old.PeerId, old.StampId), context.Signature, A.Key, 'ed25519'))
450
+
451
+ -- or REAP: a COMMITTED tombstone already retires this exact row incarnation, so a node
452
+ -- that was offline at removal time may delete the stale row locally with no owner key.
453
+ -- Why committed.* and why the stamp must be bound: stated in full on
454
+ -- CadrePeer.AuthorizedDelete.
455
+ or exists (select 1 from committed.Revocation R where R.TableName = 'DeviceToken' and R.RowKey = old.PeerId and R.StampId = old.StampId)
139
456
  ),
140
457
  constraint AuthorizedUpdate check on update (
141
458
  -- Peer self-updates its own token, signing with its OWN ed25519 key (the key
142
- -- behind PeerId). PeerId is immutable, UpdatedAt must strictly increase (replay
143
- -- guard), and Sig is verified against the stored CadrePeer.PublicKey over the
144
- -- signed payload (cadre-core device-token.ts:deviceTokenSignedPayload). Platform
145
- -- and Token may change on self-update (platform switch / reinstall / rotation).
146
- (
147
- new.PeerId = old.PeerId
148
- and new.UpdatedAt > coalesce(old.UpdatedAt, 0)
149
- and exists (select 1 from CadrePeer P where P.PeerId = new.PeerId and verify(
150
- digest(new.PeerId || '|' || new.Platform || '|' || new.Token || '|' || cast(new.UpdatedAt as text)),
151
- new.Sig, P.PublicKey, 'ed25519'))
152
- )
153
- -- or an owner re-authorizes (rotation / correction)
154
- or exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest(new.PeerId), context.Signature, A.Key, 'ed25519'))
459
+ -- behind PeerId). PeerId and StampId are immutable, UpdatedAt must strictly
460
+ -- increase (replay guard), and Sig is verified against the stored
461
+ -- CadrePeer.PublicKey over the signed payload (cadre-core
462
+ -- device-token.ts:deviceTokenSignedPayload). Platform and Token may change on
463
+ -- self-update (platform switch / reinstall / rotation).
464
+ -- StampId is immutable for the reason CadrePeer spells out: an update that
465
+ -- rotated it would leave the OLD stamp live-free and untombstoned, so retiring a
466
+ -- stamp stays delete + Revocation row, never an update.
467
+ -- This is the ONLY branch: there is deliberately NO owner re-touch. The branch
468
+ -- that used to sit beside it verified an owner signature over the peer id alone
469
+ -- and sat OUTSIDE the monotonicity requirement, so one captured owner approval
470
+ -- rewrote Platform/Token and rolled UpdatedAt BACKWARDS — and seating a
471
+ -- far-future UpdatedAt wedged the peer's own self-updates permanently. No writer
472
+ -- used it. An owner that must correct a row deletes it (retiring the stamp) and
473
+ -- inserts a fresh one, the same path it already takes for CadrePeer.
474
+ new.PeerId = old.PeerId
475
+ and new.StampId = old.StampId
476
+ and new.UpdatedAt > coalesce(old.UpdatedAt, 0)
477
+ and exists (select 1 from CadrePeer P where P.PeerId = new.PeerId and verify(
478
+ digest('CadreControl.DeviceToken', 'publish', new.PeerId, new.Platform, new.Token, cast(new.UpdatedAt as text)),
479
+ new.Sig, P.PublicKey, 'ed25519'))
155
480
  )
156
481
  ) with context (OwnerKey text null, Signature text);
157
482
 
@@ -164,59 +489,313 @@ declare schema CadreControl {
164
489
  ValidationUrl text null, -- Web hook - send disclosure, IP address...
165
490
  StrandId text null, -- Host strand this invite binds to (provision-then-record). Non-null => the responder records consent against this pre-existing strand; null => legacy responder-provisions path.
166
491
  StampId text not null unique, -- single-use authorization nonce (anti-replay)
167
- constraint AuthorizedAddOrRemove check on insert, delete (
492
+ constraint AuthorizedInsert check on insert (
168
493
  -- Authorized by an owner signing over THIS row
169
494
  -- (Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId, StampId); single-use via unique StampId.
170
- -- coalesce(new.F, old.F) binds the NEW row on insert and the OLD row on delete (cf. CadrePeer).
171
- -- StrandId is a nullable bound field: it signs as '' when absent (cf. ValidationUrl).
495
+ -- Nullable bound fields (ExpiresAt/TotalUses/ValidationUrl/StrandId) sign as '' when absent.
496
+ -- The 'remove'-tagged AuthorizedDelete digest below is DISTINCT, so a captured
497
+ -- insert approval can never be replayed to revoke-then-reissue an invite (or vice versa).
172
498
  exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(
173
499
  digest(
174
- coalesce(new.Token, old.Token),
175
- coalesce(new.sAppId, old.sAppId),
176
- coalesce(cast(coalesce(new.ExpiresAt, old.ExpiresAt) as text), ''),
177
- coalesce(cast(coalesce(new.TotalUses, old.TotalUses) as text), ''),
178
- coalesce(coalesce(new.ValidationUrl, old.ValidationUrl), ''),
179
- coalesce(coalesce(new.StrandId, old.StrandId), ''),
180
- coalesce(new.StampId, old.StampId)
500
+ 'CadreControl.FormationInvite', 'add',
501
+ new.Token,
502
+ new.sAppId,
503
+ coalesce(cast(new.ExpiresAt as text), ''),
504
+ coalesce(cast(new.TotalUses as text), ''),
505
+ coalesce(new.ValidationUrl, ''),
506
+ coalesce(new.StrandId, ''),
507
+ new.StampId
508
+ ),
509
+ context.Signature, A.Key, 'ed25519'))
510
+ ),
511
+ constraint AuthorizedDelete check on delete (
512
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(
513
+ digest(
514
+ 'CadreControl.FormationInvite', 'remove',
515
+ old.Token,
516
+ old.sAppId,
517
+ coalesce(cast(old.ExpiresAt as text), ''),
518
+ coalesce(cast(old.TotalUses as text), ''),
519
+ coalesce(old.ValidationUrl, ''),
520
+ coalesce(old.StrandId, ''),
521
+ old.StampId
181
522
  ),
182
523
  context.Signature, A.Key, 'ed25519'))
183
524
  ),
184
525
  -- Invites are insert/delete only: forbid in-place mutation so the row-bound
185
- -- AuthorizedAddOrRemove signature cannot be sidestepped by updating consent
526
+ -- AuthorizedInsert signature cannot be sidestepped by updating consent
186
527
  -- parameters (TotalUses/ExpiresAt/...) after a legitimate insert. A bare check
187
- -- defaults to insert+update; the check on insert, delete above excludes update,
528
+ -- defaults to insert+update; the checks on insert / on delete above exclude update,
188
529
  -- so this guard is required. Mirrors FormationUsage.InsertOnly.
189
530
  constraint Immutable check on update (false)
190
531
  ) with context (OwnerKey text, Signature text);
191
532
 
192
533
  table FormationUsage (
193
- Token text,
194
- UseNumber int,
534
+ Token text not null, -- the FormationInvite this acceptance redeems. Stated explicitly because
535
+ -- Token is no longer a primary-key prefix; Authorized below would refuse a
536
+ -- null anyway (null = null is never true, so its FormationInvite
537
+ -- exists-clause cannot match), but the column carries the invariant rather
538
+ -- than leaving it to a CHECK.
539
+ UsageStampId text not null, -- single-use nonce for THIS redemption, and this table's PRIMARY KEY.
540
+ -- The JOINING peer mints it and sends it in its contact message, having
541
+ -- signed it into its own 'consent' digest (PeerConsented below); the
542
+ -- responder inserts that same value and asks the approver about it, so it
543
+ -- is bound into the 'vouch' digest below too and one sign-off is spendable
544
+ -- exactly once. Neither side can swap it: a substituted nonce fails the
545
+ -- joiner's consent signature.
546
+ -- As the row key, a verbatim replay of an approval collides on the
547
+ -- primary key locally instead of on a column \`unique\`. Unlike every other
548
+ -- StampId in this schema, this table is append-only (InsertOnly below),
549
+ -- so the nonce is never freed by a delete: the key alone makes it
550
+ -- permanent and there is deliberately NO NotRevoked / RevocationRecorded
551
+ -- pair here — do not go looking for the missing one.
552
+ -- NOTE: the key is evaluated against LOCALLY VISIBLE rows, so two nodes
553
+ -- that have not yet converged could each admit the same nonce and both
554
+ -- rows survive the merge. Same class as the NotRevoked convergence notes
555
+ -- on OwnerKey / Strand / ValidationKey; the digest binding still holds on
556
+ -- both nodes, so the outcome is a duplicated audit row, never a join
557
+ -- nobody approved.
558
+ PeerKey text not null, -- the joining peer's own ed25519 public key (base64url, 32 bytes), bound
559
+ -- into BOTH the approver's 'vouch' digest and the joiner's 'consent'
560
+ -- digest below, so an approval cannot be re-filed under a different
561
+ -- joiner's name and the named joiner provably agreed (PeerConsented).
562
+ -- The key IS the joiner's identity — its libp2p peer id is derivable
563
+ -- (identity multihash of these bytes), never stored here.
564
+ PeerSig text not null, -- the joining peer's signature over the 'consent' digest — see
565
+ -- PeerConsented below for what it proves and why it is stored on the row.
195
566
  Disclosure text,
196
567
  StrandId text,
197
- primary key (Token, UseNumber),
568
+ StrandStampId text not null, -- the Strand.StampId this consent record authorizes. Consent is
569
+ -- bound to ONE strand ROW, not to a strand id forever — see
570
+ -- Strand.AuthorizedInsert's consent branch for why. NOT unique:
571
+ -- in the bound (provision-then-record) path several invitees
572
+ -- each write a usage row against the SAME host strand, so many
573
+ -- usage rows legitimately share one stamp.
574
+ primary key (UsageStampId),
198
575
  constraint InsertOnly check on update, delete (false),
199
- constraint Monotonic check (
200
- -- Read the PRE-transaction snapshot (committed.*): this CHECK auto-defers
201
- -- to commit (it has a subquery), by which point the row being inserted is
202
- -- live, so a plain from-FormationUsage would count this row itself and make
203
- -- UseNumber = max+1 unsatisfiable. committed.* excludes the in-flight row,
204
- -- giving sequential 1,2,3... per token (cross-transaction; concurrent
205
- -- redemptions of the same token collide on the (Token, UseNumber) PK).
206
- new.UseNumber = coalesce((select max(UseNumber) from committed.FormationUsage U where U.Token = new.Token), 0) + 1
207
- ),
208
576
  constraint Authorized check on insert (
209
577
  -- Satisfies an invitation
210
578
  exists (
211
579
  select 1 from FormationInvite FI
212
580
  where FI.Token = new.Token
213
- and (FI.TotalUses is null or FI.TotalUses >= new.UseNumber)
581
+ -- The use cap is COUNTED against the pre-transaction snapshot, never
582
+ -- sequenced. This CHECK auto-defers to commit (it has a subquery), by
583
+ -- which point the in-flight row is live; committed.* is what excludes
584
+ -- it, so a sequentially exhausted invite — every seat already committed
585
+ -- on this node — is still refused here. What is deliberately NOT
586
+ -- refused: concurrent redeemers on separate nodes (or nodes that have
587
+ -- not yet converged) each count the same committed snapshot and both
588
+ -- land, over-admitting by at most the number of concurrent redeemers.
589
+ -- Both rows survive in this append-only record, so the overage is
590
+ -- auditable, and removal is owner-gated (member removal + Revocation).
591
+ -- Same class as the convergence note on UsageStampId above.
592
+ -- One rule for FUTURE writers: two FormationUsage rows for one token
593
+ -- inserted in ONE transaction each read the same committed count, so
594
+ -- they can jointly exceed the cap. No writer in this repo does that; it
595
+ -- is a constraint on new writers, not a case to engineer for.
596
+ -- Do not "fix" this into a per-token sequence number to restore a
597
+ -- strict cap — that trade was weighed and rejected (2026-08-04): a
598
+ -- fought-over sequence key turns a concurrent redemption into a silent,
599
+ -- unrecoverable loss of a consented join, which is strictly worse than
600
+ -- a visible, reversible over-admission.
601
+ and (FI.TotalUses is null or FI.TotalUses > (select count(1) from committed.FormationUsage U where U.Token = new.Token))
214
602
  and (FI.ExpiresAt is null or FI.ExpiresAt > context.Now)
215
- and (FI.ValidationUrl is null or verify(digest(new.Token || new.Disclosure), context.ValidationSignature, context.ValidationKey, 'ed25519'))
603
+ -- An invite carrying a ValidationUrl demands a sign-off from a key the party
604
+ -- ENROLLED in ValidationKey. The signature is verified against the STORED VK.Key,
605
+ -- NOT against context.ValidationKey — that distinction is the whole point:
606
+ -- context.ValidationKey is a plain insert parameter, so verifying against it asked
607
+ -- only "did the redeemer sign its own disclosure with SOME key it holds?", which any
608
+ -- redeemer answers by minting a throwaway keypair. context.ValidationKey survives
609
+ -- purely to SELECT which enrolled row is being claimed; naming an enrolled key while
610
+ -- signing with a different one fails the verify against VK.Key.
611
+ --
612
+ -- Deliberate: CHECKs run on write only, so removing a validation key later does NOT
613
+ -- re-examine the FormationUsage rows it already approved. The sign-off was valid when
614
+ -- given and the strand it authorized stays formed; removal narrows who may approve
615
+ -- FUTURE redemptions, it is not a retroactive revocation of past ones.
616
+ --
617
+ -- What ONE sign-off buys: exactly ONE row. The digest covers
618
+ -- (Token, UsageStampId, StrandId, PeerKey, Disclosure), so an approval is NOT
619
+ -- transferable across invitations, redemptions, networks, joiners, or disclosure
620
+ -- text. Replay is closed twice over, by two independent mechanisms: presenting an
621
+ -- approval VERBATIM repeats its UsageStampId and is refused by this table's
622
+ -- primary key; presenting it under any OTHER redemption changes a signed field
623
+ -- and fails this verify.
624
+ -- Every signed field is supplied by the redeeming side — nothing derived from
625
+ -- the table's current state is bound — so no concurrent write can invalidate an
626
+ -- approval between the sign-off and the row landing.
627
+ -- Why StrandStampId is deliberately NOT bound: it names the strand ROW
628
+ -- incarnation, which the unbound path (redeemInvitation) mints inside its own
629
+ -- transaction, and it adds nothing on top of a strictly single-use approval —
630
+ -- StrandId already pins WHICH network the approver approved joining.
631
+ and (FI.ValidationUrl is null or exists (
632
+ select 1 from ValidationKey VK
633
+ where VK.Key = context.ValidationKey
634
+ and verify(digest('CadreControl.FormationUsage', 'vouch', new.Token, new.UsageStampId, new.StrandId, new.PeerKey, new.Disclosure), context.ValidationSignature, VK.Key, 'ed25519')))
635
+ -- A bound invite (non-null StrandId) may only ever name its own host strand:
636
+ -- without this, any holder of a bound token could record consent against an
637
+ -- arbitrary strand id — annotating an unrelated strand, or (before
638
+ -- Strand.AuthorizedInsert's consent branch was narrowed to unbound invites)
639
+ -- consent-seating that id outright.
640
+ -- NOTE: an UNBOUND invite is deliberately left free to name any strand, so a
641
+ -- holder can spend a use appending a consent row to an unrelated existing
642
+ -- strand. Harmless today (the row grants nothing, it only burns a use and
643
+ -- forecloses that id's consent-seating, which is the safe direction); if
644
+ -- unlimited-TotalUses invites ever become common, this is an append-only
645
+ -- growth surface worth bounding.
646
+ and (FI.StrandId is null or FI.StrandId = new.StrandId)
216
647
  )
217
648
  ),
218
- constraint StrandExists check (exists (select 1 from Strand S where S.Id = new.StrandId)),
219
- ) with context (PeerId text, PeerSignature text, Now datetime, ValidationKey text null, ValidationSignature text null);
649
+ -- Matched on the (id, stamp) PAIR, the same key Strand.AuthorizedInsert's consent branch
650
+ -- reads back: a usage row may only ever name a strand ROW that exists, so a consent record
651
+ -- can never be filed against a stamp of the writer's choosing and held in reserve to
652
+ -- re-seat the id after a removal.
653
+ constraint StrandExists check (exists (select 1 from Strand S where S.Id = new.StrandId and S.StampId = new.StrandStampId)),
654
+ -- The JOINING peer proves it consented to this redemption: PeerKey is its own ed25519
655
+ -- public key and PeerSig is its signature over the 'consent'-tagged digest below.
656
+ -- Unlike the approver's sign-off (context.ValidationSignature, checked against a STORED
657
+ -- ValidationKey row), the identity here IS the key, so there is no enrolled row to look
658
+ -- up and nothing for a writer to substitute: a forged joiner would need that joiner's
659
+ -- private key. Stored rather than passed in context so any later reader can re-check it
660
+ -- (verifyFormationConsent); the 'consent' action tag keeps this replicated signature
661
+ -- useless against every other rule in this schema (notably the approver's 'vouch'
662
+ -- digest over the same table).
663
+ -- NOTE: StrandId is deliberately NOT in this digest — the joiner cannot know it when it
664
+ -- signs (a bound invite's host strand arrives only in the result frame; an unbound
665
+ -- strand is responder-minted). The responder cannot substitute a strand anyway: bound
666
+ -- invites are pinned by Authorized's FI.StrandId check, unbound invites mint fresh.
667
+ constraint PeerConsented check on insert (
668
+ verify(digest('CadreControl.FormationUsage', 'consent',
669
+ new.Token, new.UsageStampId, new.PeerKey, new.Disclosure),
670
+ new.PeerSig, new.PeerKey, 'ed25519')
671
+ ),
672
+ -- Context here is only what the approver-side rules read: Now for expiry, and the
673
+ -- ValidationKey/ValidationSignature pair for the 'vouch' check in Authorized. The joiner's
674
+ -- signature is NOT context — it lives on the row (PeerSig, verified by PeerConsented above).
675
+ ) with context (Now datetime, ValidationKey text null, ValidationSignature text null);
676
+
677
+ -- Token is no longer a primary-key prefix (the key is the redemption nonce), so the
678
+ -- per-token filters — the cap count in Authorized above, and cadre-core's
679
+ -- countFormationUsage / isTokenUsed / hasOutstandingFormationInvite — get an index
680
+ -- rather than a table scan.
681
+ index FormationUsageByToken on FormationUsage (Token);
682
+
683
+ -- Append-only retirement record for the one-off StampId nonces of removed OwnerKey /
684
+ -- CadrePeer / ValidationKey / Strand rows. Without it a removal was undoable: the add
685
+ -- approval is a signature over
686
+ -- (row key, stamp) that never expires, and deleting the row freed the stamp, so anyone who
687
+ -- kept a copy of the approval could resurrect the row.
688
+ -- Each tombstone also records WHICH row was retired (RowKey below): the consent branch of
689
+ -- Strand.AuthorizedInsert reads it to refuse consent-seating any strand id that has ever
690
+ -- been removed, whichever way it was seated.
691
+ -- NOTE: the guarded tables' NotRevoked CHECK runs against locally visible rows, so a node
692
+ -- that has not yet converged on a Revocation row can still accept the replayed add, and the
693
+ -- resurrected row coexists with the tombstone after merge — same class as the MinOneOwner
694
+ -- note on OwnerKey. The read-side mitigation is ControlDatabase.queryCadrePeers, which
695
+ -- drops any CadrePeer row whose StampId appears here; every membership reader inherits it.
696
+ -- NOTE: append-only, so this table only ever grows. Every append is owner-signed
697
+ -- (Authorized below), so the growth surface is the owner keys, not every writer that can
698
+ -- reach the control database. Cadres are a handful of peers and owner rotation is rare, so
699
+ -- unbounded growth is fine today; revisit if either changes.
700
+ -- A tombstone committed while the node was alone is local-only (never broadcast); the
701
+ -- ReissuedAt counter below exists so an owner can re-write — and therefore re-broadcast —
702
+ -- such a tombstone once peers are reachable, without changing what it means.
703
+ table Revocation (
704
+ TableName text, -- 'OwnerKey' | 'CadrePeer' | 'ValidationKey' | 'Strand' | 'DeviceToken' (confined by RowIsGone below)
705
+ RowKey text not null, -- primary key of the removed row: OwnerKey.Key / ValidationKey.Key /
706
+ -- CadrePeer.PeerId / DeviceToken.PeerId / Strand.Id
707
+ -- Every guarded table's RevocationRecorded CHECK requires the
708
+ -- accompanying tombstone to carry the removed row's key here, so
709
+ -- a REMOVAL cannot file a misnamed tombstone. A tombstone with no
710
+ -- accompanying delete is not covered by that (see Authorized).
711
+ StampId text, -- the retired nonce
712
+ -- Bumped by an owner-signed re-issue so a tombstone written while the node was alone
713
+ -- (committed local-only, never broadcast) can be re-written and therefore re-broadcast
714
+ -- on cohort growth. Carries NO semantics: nothing reads it, and retirement is decided
715
+ -- by the row's existence, not by this value.
716
+ ReissuedAt integer not null default 0,
717
+ -- Keyed on the stamp, not the RowKey: stamps are unique per row incarnation, and one
718
+ -- name may legitimately carry several tombstones over its life (seat -> delete ->
719
+ -- owner re-seat -> delete).
720
+ primary key (TableName, StampId),
721
+ -- Retirement is permanent: a tombstone may never be withdrawn.
722
+ constraint NoDelete check on delete (false),
723
+ -- Pinned at 0 on insert so an owner cannot seat a tombstone at a saturated counter and
724
+ -- thereby freeze its own later re-issues (ReissueOnly below). Deliberately NOT folded
725
+ -- into the Authorized digest: the value is fixed by this rule, so signing over it would
726
+ -- only widen the signed surface for no gain, and would invalidate every existing
727
+ -- insert-side digest.
728
+ constraint FreshTombstone check on insert (new.ReissuedAt = 0),
729
+ -- A re-issue may move NOTHING but the counter, and only upward. Without the identity
730
+ -- clause an "update" would be a way to re-point a tombstone at a different row,
731
+ -- restoring exactly the replay this table exists to stop.
732
+ constraint ReissueOnly check on update (
733
+ new.TableName = old.TableName and new.RowKey = old.RowKey
734
+ and new.StampId = old.StampId and new.ReissuedAt > old.ReissuedAt
735
+ ),
736
+ -- A stamp may only be retired once its row is actually gone. Deferred (subquery), so a
737
+ -- delete in the same transaction has already landed. Retiring a stamp that never
738
+ -- existed is permitted and harmless: a stamp carries 128 bits of CSPRNG output
739
+ -- (control-database.ts:generateStampId — 16 bytes of sha256(PeerId) followed by 16
740
+ -- random bytes), so a future legitimate one cannot be guessed and pre-planted.
741
+ -- Deliberately keyed on the STAMP only, not RowKey: checking "no live row named
742
+ -- new.RowKey" breaks under out-of-order convergence — a peer removed (tombstone names
743
+ -- it, stamp1) then re-admitted (stamp2) would leave a node that converges on the
744
+ -- re-add FIRST rejecting the stamp1 tombstone forever, never learning that stamp is
745
+ -- retired. The stamp-only form passes there (stamp1 is not live).
746
+ constraint RowIsGone check on insert (
747
+ (new.TableName = 'OwnerKey' and not exists (select 1 from OwnerKey K where K.StampId = new.StampId))
748
+ or (new.TableName = 'CadrePeer' and not exists (select 1 from CadrePeer P where P.StampId = new.StampId))
749
+ or (new.TableName = 'ValidationKey' and not exists (select 1 from ValidationKey V where V.StampId = new.StampId))
750
+ or (new.TableName = 'Strand' and not exists (select 1 from Strand S where S.StampId = new.StampId))
751
+ or (new.TableName = 'DeviceToken' and not exists (select 1 from DeviceToken D where D.StampId = new.StampId))
752
+ ),
753
+ -- Appending a tombstone is an OWNER action, like every other write in this schema.
754
+ -- Ungated, any writer that could reach the control database could retire a stamp:
755
+ -- filing one against a CadrePeer row not visible locally (RowIsGone reads LOCALLY
756
+ -- VISIBLE rows — see the convergence note above) evicted that peer party-wide AND
757
+ -- permanently blocked the owner's own later re-admission of it (NotRevoked), and
758
+ -- filing arbitrary stamps flooded a table whose rows never go away.
759
+ -- The digest binds the WHOLE row (TableName, RowKey, StampId); the 'CadreControl.Revocation'
760
+ -- domain tag keeps it disjoint from every other rule — including the
761
+ -- 'CadreControl.CadrePeer' 'remove' digest the same owner signs in the SAME
762
+ -- transaction for the delete this tombstone accompanies.
763
+ -- RowKey is not cross-checked HERE against the retired row: positively binding it (e.g.
764
+ -- requiring a committed.Strand row carrying the pair) would reject a tombstone re-issued
765
+ -- in a LATER transaction — which the delete-while-alone durability path
766
+ -- (docs/architecture.md) plans to do — and reject it outright on a node that never
767
+ -- converged on the removed row. The binding lives on the other side instead: each
768
+ -- guarded table's RevocationRecorded requires the tombstone accompanying a DELETE to
769
+ -- name that row's key, which the re-issue path never trips (it files no delete).
770
+ -- Residual: a STANDALONE tombstone — owner-signed, naming a stamp no live row holds —
771
+ -- is still accepted, so an owner can name an id that never existed and thereby
772
+ -- permanently foreclose CONSENT-seating of that id (Strand.AuthorizedInsert).
773
+ -- Owner-only, the owner already controls invite issuance, and unbound ids are 128
774
+ -- random bytes minted at redemption — no escalation (same reasoning as the pre-plant
775
+ -- note on RowIsGone).
776
+ -- Reads LIVE OwnerKey (like ValidationKey / Strand / CadrePeer / DeviceToken), not
777
+ -- committed.OwnerKey. The one difference that makes: a founding transaction on an
778
+ -- owner-less database could seat an owner key and file a tombstone in one go. An
779
+ -- owner-less control database is already a total loss, and a second transaction
780
+ -- achieves the same thing under committed.*, so consistency with the siblings is
781
+ -- worth more than the distinction — do not "tighten" this without a reason other
782
+ -- than that one.
783
+ -- RowIsGone and NoDelete are unchanged: they guard an owner retiring a stamp early
784
+ -- or withdrawing one later, which authorization does not cover.
785
+ constraint Authorized check on insert (
786
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.Revocation', 'remove', new.TableName, new.RowKey, new.StampId), context.Signature, A.Key, 'ed25519'))
787
+ ),
788
+ -- A re-issue is an OWNER action, like the original append. Distinct 'reissue' action
789
+ -- tag, so an append approval can never be replayed as a re-issue and vice versa. The
790
+ -- digest adds ReissuedAt so a captured re-issue signature cannot bump the counter to
791
+ -- any other value. Reads LIVE OwnerKey, matching Authorized above.
792
+ constraint AuthorizedReissue check on update (
793
+ exists (select 1 from OwnerKey A where A.Key = context.OwnerKey
794
+ and verify(digest('CadreControl.Revocation', 'reissue',
795
+ new.TableName, new.RowKey, new.StampId, cast(new.ReissuedAt as text)),
796
+ context.Signature, A.Key, 'ed25519'))
797
+ )
798
+ ) with context (OwnerKey text, Signature text);
220
799
  }
221
800
 
222
801
  apply schema CadreControl;`;