@serfab/cadre-core 1.13.0 → 1.15.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.
- package/README.md +293 -274
- package/dist/cadre-invite-protocol.d.ts +383 -0
- package/dist/cadre-invite-protocol.js +774 -0
- package/dist/cadre-invite-protocol.js.map +1 -0
- package/dist/cadre-join-request.d.ts +42 -0
- package/dist/cadre-join-request.js +144 -0
- package/dist/cadre-join-request.js.map +1 -0
- package/dist/cadre-node.d.ts +849 -210
- package/dist/cadre-node.js +1574 -374
- package/dist/cadre-node.js.map +1 -1
- package/dist/claim-proof.d.ts +45 -0
- package/dist/claim-proof.js +132 -0
- package/dist/claim-proof.js.map +1 -0
- package/dist/control-authorization.d.ts +80 -19
- package/dist/control-authorization.js +55 -13
- package/dist/control-authorization.js.map +1 -1
- package/dist/control-cohort.js +1 -1
- package/dist/control-cohort.js.map +1 -1
- package/dist/control-database.d.ts +605 -108
- package/dist/control-database.js +1299 -280
- package/dist/control-database.js.map +1 -1
- package/dist/control-protocol-guard.d.ts +142 -0
- package/dist/control-protocol-guard.js +293 -0
- package/dist/control-protocol-guard.js.map +1 -0
- package/dist/control-schema.d.ts +1 -1
- package/dist/control-schema.js +817 -1067
- package/dist/control-schema.js.map +1 -1
- package/dist/control-stream.d.ts +4 -0
- package/dist/control-stream.js +22 -7
- package/dist/control-stream.js.map +1 -1
- package/dist/delegate-admission.d.ts +1 -1
- package/dist/delegate-admission.js +1 -1
- package/dist/device-token.d.ts +11 -9
- package/dist/device-token.js +14 -12
- package/dist/device-token.js.map +1 -1
- package/dist/ed25519-key.d.ts +22 -9
- package/dist/ed25519-key.js +47 -10
- package/dist/ed25519-key.js.map +1 -1
- package/dist/fetch-impl.d.ts +12 -0
- package/dist/fetch-impl.js +23 -0
- package/dist/fetch-impl.js.map +1 -0
- package/dist/file-durable-slot.js +2 -1
- package/dist/file-durable-slot.js.map +1 -1
- package/dist/file-safe-name.d.ts +25 -0
- package/dist/file-safe-name.js +29 -0
- package/dist/file-safe-name.js.map +1 -0
- package/dist/formation-approval.js +5 -11
- package/dist/formation-approval.js.map +1 -1
- package/dist/fs-atomic.d.ts +0 -19
- package/dist/fs-atomic.js +3 -24
- package/dist/fs-atomic.js.map +1 -1
- package/dist/index.d.ts +22 -10
- package/dist/index.js +54 -11
- package/dist/index.js.map +1 -1
- package/dist/invitation-bootstrap.d.ts +50 -12
- package/dist/invitation-bootstrap.js +76 -13
- package/dist/invitation-bootstrap.js.map +1 -1
- package/dist/joined-strand-store.d.ts +7 -0
- package/dist/joined-strand-store.js +9 -0
- package/dist/joined-strand-store.js.map +1 -1
- package/dist/key-store-file.js +2 -1
- package/dist/key-store-file.js.map +1 -1
- package/dist/link-budget.d.ts +25 -33
- package/dist/link-budget.js +25 -35
- package/dist/link-budget.js.map +1 -1
- package/dist/machine-removal.d.ts +78 -0
- package/dist/machine-removal.js +166 -0
- package/dist/machine-removal.js.map +1 -0
- package/dist/membership-connection-gater.d.ts +191 -151
- package/dist/membership-connection-gater.js +236 -173
- package/dist/membership-connection-gater.js.map +1 -1
- package/dist/node-claim-payload.d.ts +74 -0
- package/dist/node-claim-payload.js +224 -0
- package/dist/node-claim-payload.js.map +1 -0
- package/dist/node-default-transports.d.ts +27 -0
- package/dist/node-default-transports.js +35 -0
- package/dist/node-default-transports.js.map +1 -0
- package/dist/node-transports.d.ts +30 -0
- package/dist/node-transports.js +40 -0
- package/dist/node-transports.js.map +1 -0
- package/dist/owner-anchor-sync.d.ts +22 -0
- package/dist/owner-anchor-sync.js +143 -0
- package/dist/owner-anchor-sync.js.map +1 -0
- package/dist/peer-authorization.d.ts +113 -18
- package/dist/peer-authorization.js +225 -29
- package/dist/peer-authorization.js.map +1 -1
- package/dist/peer-dial.d.ts +143 -27
- package/dist/peer-dial.js +276 -31
- package/dist/peer-dial.js.map +1 -1
- package/dist/peer-join-backfill.d.ts +26 -2
- package/dist/peer-join-backfill.js +60 -12
- package/dist/peer-join-backfill.js.map +1 -1
- package/dist/peer-record.d.ts +17 -52
- package/dist/peer-record.js +20 -58
- package/dist/peer-record.js.map +1 -1
- package/dist/pending-join-runner.d.ts +66 -58
- package/dist/pending-join-runner.js +136 -145
- package/dist/pending-join-runner.js.map +1 -1
- package/dist/primary-lan-address.d.ts +8 -0
- package/dist/primary-lan-address.js +46 -0
- package/dist/primary-lan-address.js.map +1 -0
- package/dist/provider/client.d.ts +131 -0
- package/dist/provider/client.js +226 -0
- package/dist/provider/client.js.map +1 -0
- package/dist/provider/descriptor.d.ts +41 -0
- package/dist/provider/descriptor.js +103 -0
- package/dist/provider/descriptor.js.map +1 -0
- package/dist/provider/index.d.ts +9 -0
- package/dist/provider/index.js +10 -0
- package/dist/provider/index.js.map +1 -0
- package/dist/provider/oauth.d.ts +125 -0
- package/dist/provider/oauth.js +199 -0
- package/dist/provider/oauth.js.map +1 -0
- package/dist/provider/rent-node.d.ts +101 -0
- package/dist/provider/rent-node.js +220 -0
- package/dist/provider/rent-node.js.map +1 -0
- package/dist/push-fanout.d.ts +8 -2
- package/dist/push-fanout.js +8 -2
- package/dist/push-fanout.js.map +1 -1
- package/dist/relay-addrs.d.ts +9 -4
- package/dist/relay-addrs.js +9 -4
- package/dist/relay-addrs.js.map +1 -1
- package/dist/relay-reservation.d.ts +51 -16
- package/dist/relay-reservation.js +107 -24
- package/dist/relay-reservation.js.map +1 -1
- package/dist/seed-bootstrap.d.ts +165 -123
- package/dist/seed-bootstrap.js +313 -275
- package/dist/seed-bootstrap.js.map +1 -1
- package/dist/seed-trust-policy.d.ts +98 -37
- package/dist/seed-trust-policy.js +188 -2
- package/dist/seed-trust-policy.js.map +1 -1
- package/dist/strand-addr-protocol.d.ts +24 -26
- package/dist/strand-addr-protocol.js +19 -26
- package/dist/strand-addr-protocol.js.map +1 -1
- package/dist/strand-commit-durability.d.ts +54 -0
- package/dist/strand-commit-durability.js +74 -0
- package/dist/strand-commit-durability.js.map +1 -0
- package/dist/strand-database.d.ts +23 -8
- package/dist/strand-database.js +41 -13
- package/dist/strand-database.js.map +1 -1
- package/dist/strand-first-sync-gate.d.ts +7 -1
- package/dist/strand-first-sync-gate.js +7 -1
- package/dist/strand-first-sync-gate.js.map +1 -1
- package/dist/strand-formation-protocol.js +5 -2
- package/dist/strand-formation-protocol.js.map +1 -1
- package/dist/strand-fret-addrs.d.ts +19 -1
- package/dist/strand-fret-addrs.js +27 -9
- package/dist/strand-fret-addrs.js.map +1 -1
- package/dist/strand-instance-manager.d.ts +81 -19
- package/dist/strand-instance-manager.js +216 -105
- package/dist/strand-instance-manager.js.map +1 -1
- package/dist/strand-move.d.ts +124 -0
- package/dist/strand-move.js +438 -0
- package/dist/strand-move.js.map +1 -0
- package/dist/strand-network-config.js +7 -6
- package/dist/strand-network-config.js.map +1 -1
- package/dist/strand-peer-redial.d.ts +113 -0
- package/dist/strand-peer-redial.js +236 -0
- package/dist/strand-peer-redial.js.map +1 -0
- package/dist/strand-revocation-enforcer.d.ts +11 -11
- package/dist/strand-revocation-enforcer.js +11 -11
- package/dist/strand-wake-protocol.d.ts +13 -16
- package/dist/strand-wake-protocol.js +23 -27
- package/dist/strand-wake-protocol.js.map +1 -1
- package/dist/trusted-owner-store.d.ts +35 -5
- package/dist/trusted-owner-store.js +50 -8
- package/dist/trusted-owner-store.js.map +1 -1
- package/dist/types.d.ts +512 -89
- package/dist/types.js +10 -0
- package/dist/types.js.map +1 -1
- package/package.json +19 -10
- package/src/cadre-invite-protocol.ts +1052 -0
- package/src/cadre-join-request.ts +167 -0
- package/src/cadre-node.ts +1703 -386
- package/src/claim-proof.ts +147 -0
- package/src/control-authorization.ts +203 -117
- package/src/control-cohort.ts +1 -1
- package/src/control-database.ts +4663 -3453
- package/src/control-protocol-guard.ts +348 -0
- package/src/control-schema.ts +828 -1078
- package/src/control-stream.ts +26 -7
- package/src/delegate-admission.ts +1 -1
- package/src/device-token.ts +14 -10
- package/src/ed25519-key.ts +47 -10
- package/src/fetch-impl.ts +23 -0
- package/src/file-durable-slot.ts +64 -63
- package/src/file-safe-name.ts +32 -0
- package/src/formation-approval.ts +604 -610
- package/src/fs-atomic.ts +92 -117
- package/src/index.ts +789 -648
- package/src/invitation-bootstrap.ts +91 -13
- package/src/joined-strand-store.ts +508 -498
- package/src/key-store-file.ts +142 -141
- package/src/link-budget.ts +25 -36
- package/src/machine-removal.ts +216 -0
- package/src/membership-connection-gater.ts +259 -191
- package/src/node-claim-payload.ts +259 -0
- package/src/node-default-transports.ts +38 -0
- package/src/node-transports.ts +49 -0
- package/src/owner-anchor-sync.ts +171 -0
- package/src/peer-authorization.ts +258 -29
- package/src/peer-dial.ts +604 -315
- package/src/peer-join-backfill.ts +62 -11
- package/src/peer-record.ts +159 -197
- package/src/pending-join-runner.ts +729 -735
- package/src/primary-lan-address.ts +47 -0
- package/src/provider/client.ts +326 -0
- package/src/provider/descriptor.ts +129 -0
- package/src/provider/index.ts +59 -0
- package/src/provider/oauth.ts +285 -0
- package/src/provider/rent-node.ts +275 -0
- package/src/push-fanout.ts +8 -2
- package/src/relay-addrs.ts +9 -4
- package/src/relay-reservation.ts +1211 -1121
- package/src/seed-bootstrap.ts +1502 -1448
- package/src/seed-trust-policy.ts +353 -140
- package/src/strand-addr-protocol.ts +26 -35
- package/src/strand-commit-durability.ts +116 -0
- package/src/strand-database.ts +46 -14
- package/src/strand-first-sync-gate.ts +7 -1
- package/src/strand-formation-protocol.ts +1039 -1036
- package/src/strand-fret-addrs.ts +179 -145
- package/src/strand-instance-manager.ts +2026 -1883
- package/src/strand-move.ts +585 -0
- package/src/strand-network-config.ts +7 -6
- package/src/strand-peer-redial.ts +307 -0
- package/src/strand-revocation-enforcer.ts +11 -11
- package/src/strand-wake-protocol.ts +23 -30
- package/src/trusted-owner-store.ts +242 -171
- package/src/types.ts +2687 -2242
package/dist/control-schema.d.ts
CHANGED
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* build if they drift. Any edit here must be mirrored in `schemas/control.qsql`
|
|
10
10
|
* and vice versa.
|
|
11
11
|
*/
|
|
12
|
-
export declare const CONTROL_SCHEMA = "-- This manages a Sereus party's cadre, or set of nodes, and their participation in strands (networks)\ndeclare schema CadreControl {\n -- A key that can authorize various control changes\n table OwnerKey (\n Key text primary key,\n StampId text not null unique, -- per-row authorization nonce, bound into the signed digests below.\n -- `unique` holds over LIVE rows only; a removed row's stamp is retired\n -- permanently into Revocation (NotRevoked below), so the never-expiring\n -- enrollment signature cannot resurrect a removed owner.\n -- A removed row's StampId is retired into Revocation, and this refuses any insert\n -- naming a retired stamp: the approval that seated this row can never re-seat it after\n -- removal. `unique` alone did not do this \u2014 it only holds over LIVE rows, so a delete\n -- freed the stamp and the original never-expiring signature verified again. A\n -- legitimate re-add mints a FRESH StampId and a fresh signature, so it is unaffected.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = old.StampId and R.RowKey = old.Key)\n ),\n -- A party must never lose its last owner key: every other CadreControl table's\n -- CHECK requires an OwnerKey row, so an owner-less control database can never\n -- authorize anything again \u2014 emptying this table is a permanent denial of the\n -- party's control plane. Deferred (subquery), so the count is the POST-delete count.\n -- NOTE: this is a per-transaction check against locally visible rows. Two\n -- partitioned nodes that concurrently remove different owners can each see a\n -- survivor and still converge to zero; if partitioned rotation ever becomes a real\n -- workflow, the floor needs a cross-node guard, not a local count.\n constraint MinOneOwner check on delete (\n (select count(1) from OwnerKey) >= 1\n ),\n -- Enrollment is insert + delete only; rotation is add-then-remove. No writer\n -- updates an OwnerKey row, and a self-rotation branch would double as a sole-owner\n -- takeover: a deferred post-image count is also true of an update that re-points\n -- the only row at an attacker key. Mirrors Strand.Manager.NoUpdate.\n constraint NoUpdate check on update (false),\n -- NOTE: the domain tag scopes an approval to a table and an action, not to a PARTY. Two\n -- parties that share an owner key would accept each other's approvals. Fine today (each\n -- party has its own owner key); if shared-owner multi-party ever ships, bind a party\n -- identity row into these digests.\n constraint Authorized check on insert, delete (\n -- Every authorizer is read from the PRE-transaction snapshot (committed.*):\n -- this CHECK auto-defers to commit (it has a subquery), by which point the row\n -- being inserted \u2014 and any sibling inserted alongside it \u2014 is live, so a plain\n -- from-OwnerKey would let a row authorize itself, or two strangers seat each\n -- other. committed.* excludes both, stating the rule directly: the authorizer\n -- must have existed BEFORE this transaction.\n\n -- Every signed digest below (and in every other CadreControl table) leads with two\n -- fixed literals \u2014 a 'CadreControl.<Table>' domain tag and an 'add'/'remove'/\n -- 'vouch'/'publish' action tag (cadre-core control-authorization.ts) \u2014 so an\n -- approval verifies ONLY against the one rule it was minted for. Without them,\n -- e.g. a ValidationKey enrollment approval covered the identical bytes as an\n -- OwnerKey enrollment: a narrow grant that doubled as full ownership.\n\n -- Bootstrap: the FOUNDING transaction \u2014 one whose pre-transaction owner set is\n -- empty \u2014 needs no authorization, and every row it inserts rides this branch\n -- (whoever writes it already owns the party outright, so a co-founder row grants\n -- nothing a single row would not). Gated on the PRE-transaction count, so a\n -- same-transaction swap of the sole owner (delete the founder, insert the\n -- attacker \u2014 post-image count still 1) cannot ride it.\n (old.Key is null and (select count(1) from committed.OwnerKey) = 0)\n\n -- or a pre-existing owner authorizes by signing over THIS row (Key, StampId)\n 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')))\n\n -- or a removal authorized by ANOTHER pre-existing owner over the DISTINCT\n -- 'remove'-tagged digest bound to the stored row's StampId, so an enrollment\n -- signature can never be replayed as a removal (cf. CadrePeer.AuthorizedDelete).\n -- A.Key <> old.Key: an owner cannot sign its own removal (no self-resignation).\n 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')))\n )\n ) with context (OwnerKey text null, Signature text null);\n\n -- A key that can validate a strand formation disclosure\n table ValidationKey (\n Key text primary key,\n StampId text not null unique, -- single-use authorization nonce (anti-replay).\n -- `unique` holds over LIVE rows only; a removed row's stamp is retired\n -- permanently into Revocation (NotRevoked below), so the never-expiring\n -- enrollment signature cannot resurrect a removed key.\n -- A removed row's StampId is retired into Revocation, and this refuses any insert naming\n -- a retired stamp: the approval that seated this row can never re-seat it after removal.\n -- Same rationale as OwnerKey.NotRevoked, stated in full there.\n -- NOTE: this table gained a consumer \u2014 FormationUsage.Authorized reads it to gate redemption of\n -- a ValidationUrl invite \u2014 so the convergence gap noted on Strand.StampId now has teeth here: on\n -- a node that has not yet seen the tombstone, a replayed enrollment re-seats the key and it can\n -- approve redemptions there until the Revocation row arrives. Still no per-request READ surface to\n -- filter (the gate is a write-time CHECK), so there is nothing to add today; if one appears, filter\n -- retired stamps there.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'ValidationKey' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'ValidationKey' and R.StampId = old.StampId and R.RowKey = old.Key)\n ),\n -- Enrollment is insert + delete only; rotation is add-then-remove. No writer in the repo\n -- updates a ValidationKey row. Required because the AuthorizedInsert / AuthorizedDelete\n -- pair below covers neither update \u2014 and a bare `check`, which is what this rule used to\n -- be, covers insert+update but NOT delete. Mirrors OwnerKey.NoUpdate.\n constraint NoUpdate check on update (false),\n constraint AuthorizedInsert check on insert (\n -- Owners authorize by signing over THIS row (Key, StampId); single-use via unique StampId\n 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'))\n ),\n constraint AuthorizedDelete check on delete (\n -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest bound to\n -- the STORED row (Key, StampId), so an enrollment approval \u2014 which never expires \u2014 can\n -- never be replayed as a removal. Same shape as CadrePeer.AuthorizedDelete.\n 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'))\n\n -- or REAP: a COMMITTED tombstone already retires this exact row incarnation, so a node\n -- that was offline at removal time may delete the stale row locally with no owner key.\n -- Why committed.* and why the stamp must be bound: stated in full on\n -- CadrePeer.AuthorizedDelete.\n or exists (select 1 from committed.Revocation R where R.TableName = 'ValidationKey' and R.RowKey = old.Key and R.StampId = old.StampId)\n )\n ) with context (OwnerKey text, Signature text);\n\n -- A network of members sharing an sApp database, each contributing peer nodes (their cadre) to the overall cohort\n -- Cadre peers should participate in each of these strands\n table Strand (\n Id text primary key, -- UUID\n MemberPrivateKey text null unique, -- Our private key as a member of this strand\n Type text, -- Types: 'o' = Open, 'c' = Closed -- Open can still control writes in the sApp, but only Closed controls reads\n FounderOwnerKey text null, -- ed25519 (base64url) owner key of the MACHINE that published this row\n -- (== insert context.OwnerKey; in the reference model each machine's\n -- owner key is the key behind its PeerId, so this names the founding\n -- machine \u2014 the one machine that runs the strand's one-time founder\n -- bootstrap). cadre-core derives \"am I the founder?\" at launch by\n -- comparing it to the node's own owner key (cadre-node.ts\n -- launchStrand). Null on a consent-seated strand \u2014 the consent branch\n -- of AuthorizedInsert carries no signature, so there is no\n -- trustworthy signer to record (see the NOTE on that branch below).\n -- Provenance, not content: cadre-node.ts strandRowMismatches\n -- deliberately excludes it from the identical-content comparison.\n StampId text not null unique, -- single-use authorization nonce (anti-replay).\n -- `unique` holds over LIVE rows only; a removed row's stamp is retired\n -- permanently into Revocation (NotRevoked below).\n -- NOTE: NotRevoked is a per-transaction check against LOCALLY VISIBLE rows, so a node that\n -- has not yet converged on the Revocation row can still accept a replayed add and end up\n -- holding the resurrected strand alongside its tombstone. CadrePeer has a read-side\n -- mitigation for this class (ControlDatabase.queryCadrePeers drops rows whose stamp is\n -- retired, so every membership reader inherits it); Strand and ValidationKey deliberately\n -- do NOT, because neither has a\n -- per-request authorization surface today. If one ever gains one, filter it there.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'Strand' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey. That is what makes\n -- the consent branch of AuthorizedInsert below trustworthy: a removal cannot file a\n -- tombstone that omits or misnames the id it retires.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'Strand' and R.StampId = old.StampId and R.RowKey = old.Id)\n ),\n -- Strand rows are insert + delete only. Required: the consent branch of AuthorizedInsert\n -- below authorizes by the EXISTENCE of a FormationUsage row naming (new.Id, new.StampId)\n -- and carries no signature, so while this rule was a bare `check` (insert+update) it also\n -- said \"anyone may REWRITE any consent-formed strand, unsigned\" \u2014 flipping Type to 'o' and\n -- nulling MemberPrivateKey destroys the party's own membership key for that network in place.\n -- Mirrors OwnerKey.NoUpdate / FormationInvite.Immutable.\n constraint NoUpdate check on update (false),\n constraint AuthorizedInsert check on insert (\n -- Authorized by an owner signing over THIS row (Id, Type, MemberPrivateKey, StampId); single-use via unique StampId.\n -- FounderOwnerKey persists WHO published the row, so the founding machine can later\n -- recognise its own strand (founder derivation, cadre-node.ts launchStrand). The\n -- equality pins the stored column to the VERIFIED signer \u2014 same shape as\n -- CadrePeer.VouchOwner \u2014 so a writer cannot record a founder it is not. Deliberately\n -- NOT added to the signed digest: the equality already binds it to the signature's\n -- context.OwnerKey, and widening the digest would churn every existing\n -- insertStrand field-order contract for nothing.\n (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'))\n and new.FounderOwnerKey = context.OwnerKey)\n\n -- or authorized WITHOUT a signature by a redemption record naming THIS EXACT ROW: a\n -- FormationUsage row carrying both this strand's Id and its one-off StampId\n -- (control-database.ts:redeemInvitation writes the pair in one transaction; both\n -- CHECKs defer, so each sees the other's row at commit).\n --\n -- Matching the STAMP, not the id alone, is what makes a removal stick. FormationUsage\n -- is append-only, so a redemption record outlives the strand it formed forever; keyed\n -- on the id alone it re-authorized ANY later insert of that id, so after a legitimate\n -- owner-signed, tombstoned removal any writer could re-seat the strand unsigned with a\n -- fresh StampId (sidestepping NotRevoked, which retires only the removed row's stamp)\n -- and an ATTACKER-CHOSEN MemberPrivateKey \u2014 the party's own secret for that network.\n -- Bound to the stamp, the removal retires that stamp into Revocation and NotRevoked\n -- closes this consent record's branch permanently.\n --\n -- Beyond the stamp match, the branch is deliberately NARROW \u2014 each clause closes one door:\n -- * Type = 'o' / MemberPrivateKey null \u2014 a consent-seated strand looks exactly like\n -- what the unbound redemption path writes (open, keyless). A closed strand carrying\n -- a caller-chosen member key (the party's own read-gating secret for that network)\n -- has no legitimate producer. MemberKeyClosedOnly already implies the second clause\n -- from the first today; both are stated so this rule does not silently depend on\n -- another constraint staying as it is.\n -- * the inner FI.StrandId is null \u2014 only an UNBOUND invite may seat a strand at all.\n -- A bound invite's host strand is owner-provisioned up front; letting the invite\n -- consent-seat that id would allow an open, keyless downgrade of the real (possibly\n -- closed, key-bearing) host row on a node where it has not converged yet. The bound\n -- path records usage only (resolveStrand reports an absent host as missing and the\n -- formation manager rejects cleanly).\n -- * the not-exists over OTHER stamps \u2014 a strand id may be consent-seated once, EVER.\n -- FormationUsage is append-only, so the first redemption's record survives a later\n -- owner-signed removal and permanently forecloses a second consent-seating of the\n -- id (a spare use of the same token minted a new stamp and rode this branch to\n -- re-seat the id with an attacker-chosen row). Re-joining a removed id is\n -- owner-gated: the owner re-seats it signed (fresh stamp, fresh signature) and\n -- issues a BOUND invite the returning party records consent against \u2014 the id is\n -- not blacklisted, only its unsigned re-seat is. This cannot be weaponised to\n -- pre-block a legitimate id: StrandExists refuses a usage row naming a strand that\n -- does not exist, so no usage row can be pre-planted for an unseated id \u2014 and ids\n -- are 128 random bytes anyway.\n -- * the not-exists over Revocation \u2014 a strand id may be consent-seated once EVER\n -- and never after ANY removal of that id, however it was seated. The usage-row\n -- rule above binds only ids that ever carried a consent record; an id seated\n -- purely owner-signed (insertStrand, no usage row) leaves nothing behind on\n -- removal, so its removal needs its own trace. Every removal files a Revocation\n -- row naming the removed row's key (RowKey), and this clause refuses any id\n -- that has ever been tombstoned. RevocationRecorded above makes that trace\n -- mandatory AND correctly named, so no removal can slip past this clause. The\n -- usage-row clause is arguably subsumed by this one (a usage row implies the\n -- strand row existed, and its removal must file a tombstone), but it reaches\n -- the same conclusion without depending on Revocation at all; both are stated,\n -- per the style note above. The owner-signed branch is deliberately unaffected,\n -- so re-join stays owner-gated exactly as described.\n -- What is NOT schema-verified is a STANDALONE tombstone (one with no\n -- accompanying delete \u2014 see Revocation.Authorized): an owner can file one\n -- naming an id that never existed and thereby permanently foreclose\n -- consent-seating of that id \u2014 owner-only, the owner already controls invite\n -- issuance, and unbound ids are 128 random bytes minted at redemption, so no\n -- escalation (same reasoning as the pre-plant note above).\n -- NOTE: like NotRevoked above, this is a write-time check against LOCALLY\n -- VISIBLE rows \u2014 a node that has not yet converged on the Revocation row still\n -- accepts the re-seat. Fails in the safe direction: the tombstone wins after\n -- merge for the STAMP, and the resurrected row coexists with it (same class as\n -- the StampId note above).\n or (\n new.Type = 'o'\n and new.MemberPrivateKey is null\n -- NOTE: a consent-seated strand records NO founder machine \u2014 this branch\n -- carries no signature, so there is no trustworthy signer to persist.\n -- Consequence: the restart-before-founding orphan shape (a relaunch cannot\n -- derive founder-ness from the row) persists for consent-formed strands\n -- only; the responder that provisions one must keep passing an explicit\n -- founder flag at launch. Revisit if consent-formed strands ever hit the\n -- empty-Header symptom in practice: FormationUsage names the redeeming\n -- peer (PeerKey), which is the candidate derivation source.\n and new.FounderOwnerKey is null\n and exists (\n select 1 from FormationUsage FU\n where FU.StrandId = new.Id\n and FU.StrandStampId = new.StampId\n and exists (select 1 from FormationInvite FI where FI.Token = FU.Token and FI.StrandId is null)\n )\n and not exists (\n select 1 from FormationUsage FU2\n where FU2.StrandId = new.Id and FU2.StrandStampId <> new.StampId\n )\n and not exists (\n select 1 from Revocation R\n where R.TableName = 'Strand' and R.RowKey = new.Id\n )\n )\n ),\n constraint AuthorizedDelete check on delete (\n -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest bound to\n -- the STORED row (Id, StampId), so the add approval \u2014 which never expires \u2014 can never be\n -- replayed as a removal. Note the consent branch above is deliberately NOT mirrored\n -- here: an invitation authorizes forming a strand, never destroying one.\n --\n -- DELIBERATELY no REAP branch (cf. CadrePeer.AuthorizedDelete): this row carries\n -- MemberPrivateKey \u2014 the party's own membership secret for that network, stored nowhere\n -- else \u2014 so this is the one guarded delete whose effect is unrecoverable, and a stale\n -- row is already inert for the purpose a tombstone serves (the consent branch of\n -- AuthorizedInsert above refuses any id ever tombstoned). Do not \"fix\" the asymmetry;\n -- tickets/backlog/debt-strand-tombstone-reap.md owns any future change.\n 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'))\n ),\n constraint MemberKeyClosedOnly check (\n -- An open strand ('o') has no membership gate, so it must not carry a\n -- member key. A non-null MemberPrivateKey requires a closed strand ('c').\n new.MemberPrivateKey is null or new.Type = 'c'\n )\n ) with context (OwnerKey text, Signature text);\n\n -- ONE party's own membership identity for one strand: the private key whose public\n -- half seats this party's `Strand.Member` / `Strand.Manager` rows. Deliberately a\n -- SEPARATE key from Strand.MemberPrivateKey \u2014 that column is the strand-wide read\n -- secret formation hands to EVERY joining party, so an identity derived from it is\n -- one every joiner can forge (gotchoices/sereus#4). A side table rather than a\n -- Strand column because a JOINER holds no control Strand row at all (reference apps\n -- attach formed strands from an in-memory row) yet must persist its own party key\n -- too; keyed by strand id it serves founder and joiner uniformly, and it leaves the\n -- heavily-audited Strand insert digest untouched. Deliberately NO closed-strands-only\n -- cross-table check: the joiner writes this row with no local Strand row to check\n -- against. Party-private in the same sense as MemberPrivateKey \u2014 replicated in\n -- plaintext to every machine the party owns (docs/strands.md \u2192 \"Closed-Strand Member\n -- Key Handling\"; that replication is what lets any of the party's machines sign\n -- membership writes) \u2014 but unlike MemberPrivateKey it is NEVER put on the formation\n -- wire.\n table StrandPartyKey (\n Id text primary key, -- the strand id this key is for\n PrivateKey text not null, -- THIS party's ed25519 strand member private key, base64\n -- protobuf \u2014 the same encoding as Strand.MemberPrivateKey;\n -- decode with cadre-core's strandMemberKeyPair.\n StampId text not null unique, -- single-use authorization nonce (anti-replay).\n -- `unique` holds over LIVE rows only; a removed row's stamp is\n -- retired permanently into Revocation (NotRevoked below).\n -- A removed row's StampId is retired into Revocation, and this refuses any insert\n -- naming a retired stamp: the approval that seated this row can never re-seat it\n -- after removal. Same rationale as OwnerKey.NotRevoked, stated in full there.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'StrandPartyKey' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'StrandPartyKey' and R.StampId = old.StampId and R.RowKey = old.Id)\n ),\n -- Insert + delete only; a rotation is remove-then-insert (fresh stamp, fresh\n -- signature). Required because AuthorizedInsert / AuthorizedDelete below cover\n -- neither update \u2014 an in-place rewrite would swap the party's identity key with\n -- no signature at all. Mirrors ValidationKey.NoUpdate.\n constraint NoUpdate check on update (false),\n constraint AuthorizedInsert check on insert (\n -- Owners authorize by signing over THIS row (Id, PrivateKey, StampId);\n -- single-use via unique StampId. Binding PrivateKey means a captured approval\n -- can only ever reproduce the exact key it approved, never seat an\n -- attacker-chosen identity under the party's name.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.StrandPartyKey', 'add', new.Id, new.PrivateKey, new.StampId), context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest\n -- bound to the STORED row (Id, StampId), so the enrollment approval \u2014 which\n -- never expires \u2014 can never be replayed as a removal.\n -- DELIBERATELY no REAP branch (cf. ValidationKey.AuthorizedDelete): like\n -- Strand.MemberPrivateKey, PrivateKey is a secret stored nowhere else, so this\n -- delete's effect is unrecoverable and stays strictly owner-signed. Same\n -- reasoning as Strand.AuthorizedDelete.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.StrandPartyKey', 'remove', old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))\n )\n ) with context (OwnerKey text, Signature text);\n\n -- A strand THIS party joined from ANOTHER party. The founding party's control database\n -- holds its Strand row, so without this table only the machine that joined would know of\n -- it. Every machine of the party reads it (the strand watcher offers each row like a\n -- Strand row), so a replica host keeps a copy and the party's other machines can attach.\n -- A separate table rather than a Strand row with a provenance marker: Strand means \"this\n -- party's own strand\" to every reader of it (founder derivation, FormationUsage.StrandExists,\n -- unpublish, the consent branch of Strand.AuthorizedInsert), and each would need a\n -- provenance check. MemberPrivateKey is the closed strand's shared read secret the\n -- formation delivered \u2014 replicated in plaintext to every machine the party owns, under the\n -- same accepted risk as Strand.MemberPrivateKey (docs/strands.md \u2192 \"Closed-Strand Member\n -- Key Handling\"). Unlike that column it is not held only here: the founding party and\n -- every member hold it, so a removed row is recoverable by re-forming, which is why this\n -- table (unlike Strand) carries a REAP branch.\n table JoinedStrand (\n Id text primary key, -- the joined strand's id (the founder's Strand.Id)\n Type text not null, -- 'o' | 'c', as Strand.Type\n MemberPrivateKey text null, -- closed strand's shared read secret; null for open\n StampId text not null unique, -- single-use authorization nonce (anti-replay).\n -- `unique` holds over LIVE rows only; a removed row's stamp is\n -- retired permanently into Revocation (NotRevoked below).\n -- The approval that seated a removed row can never re-seat it. Same rationale as\n -- OwnerKey.NotRevoked, stated in full there.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'JoinedStrand' and R.StampId = new.StampId)\n ),\n -- A delete must file its correctly named tombstone in the same transaction. Same\n -- rationale as StrandPartyKey.RevocationRecorded.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'JoinedStrand' and R.StampId = old.StampId and R.RowKey = old.Id)\n ),\n -- Insert + delete only: neither Authorized rule below covers update, so an in-place\n -- rewrite would swap the read secret unsigned. Mirrors StrandPartyKey.NoUpdate.\n constraint NoUpdate check on update (false),\n -- Readers cast Type to 'o' | 'c' (ControlDatabase.queryJoinedStrands).\n constraint KnownType check (new.Type = 'o' or new.Type = 'c'),\n -- An open strand has no read gate, so no read secret. Same rule as Strand.MemberKeyClosedOnly.\n constraint MemberKeyClosedOnly check (new.MemberPrivateKey is null or new.Type = 'c'),\n constraint AuthorizedInsert check on insert (\n -- Owners authorize by signing over THIS row (Id, Type, MemberPrivateKey, StampId),\n -- MemberPrivateKey signing as '' when null, so a captured approval can only reproduce\n -- the exact secret it approved. Owner-signed, deliberately NOT self-signable by an\n -- enrolled CadrePeer: every always-on machine of the party downloads the strands this\n -- table names, so a non-owner machine could otherwise make them all host an arbitrary\n -- strand. A machine that is not an owner keeps its joins machine-local.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.JoinedStrand', 'add', new.Id, new.Type, coalesce(new.MemberPrivateKey, ''), new.StampId), context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n -- 'remove'-tagged digest over the STORED row (Id, StampId), so the add approval can\n -- never be replayed as a removal.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.JoinedStrand', 'remove', old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))\n\n -- or REAP: a COMMITTED tombstone already retires this exact row incarnation.\n -- Why committed.* and why the stamp is bound: stated in full on\n -- CadrePeer.AuthorizedDelete. Allowed here, unlike Strand / StrandPartyKey,\n -- because MemberPrivateKey is recoverable (see the table comment).\n or exists (select 1 from committed.Revocation R where R.TableName = 'JoinedStrand' and R.RowKey = old.Id and R.StampId = old.StampId)\n )\n ) with context (OwnerKey text, Signature text);\n\n -- A join THIS party asked for, by redeeming another party's invitation, that it has not\n -- finished yet, or has finished and not yet dismissed. Party-wide rather than kept on the\n -- device that asked, so the attempt outlives that device and any owner machine of the party\n -- can carry it on and record how it ended. Invitation is a bearer credential and\n -- MembershipInvite a single-use one; both are replicated in plaintext to every machine the\n -- party owns, under the same accepted risk as JoinedStrand.MemberPrivateKey (docs/strands.md\n -- \u2192 \"Closed-Strand Member Key Handling\").\n -- Every write is a whole-row insert or delete: recording an outcome deletes the row (with its\n -- tombstone) and inserts its successor under a fresh stamp in one transaction\n -- (ControlDatabase.replacePendingJoin). Which outcome may follow which is CadreNode policy,\n -- not a rule here, because every writer is an owner.\n -- Carries a REAP branch, like JoinedStrand, because nothing here is stored only here: the\n -- inviting party holds the FormationInvite row, the user holds the shared link, and the\n -- membership invitation is a copy of what the inviter issued.\n table PendingJoin (\n Id text primary key, -- base64url sha256 of the invitation token (cadre-core's\n -- pendingJoinId): one row per invitation, and the Revocation\n -- tombstone that names a removed row never holds the token.\n Invitation text not null, -- CadreNode.encodeInvitation: token, sAppId, expiration and\n -- bootstrap addresses. A few kilobytes at most, since\n -- createOpenInvitation caps the addresses an invitation carries.\n Disclosure text not null, -- canonicalJson of the disclosure the requester gave; the\n -- formation sets partyId itself on each attempt\n RequestedAt integer not null, -- epoch ms\n ExpiresAt integer not null, -- epoch ms; no attempt starts at or after it\n Outcome text null, -- null while pending | 'joined' | 'failed'\n OutcomeAt integer null, -- epoch ms the outcome was recorded\n StrandId text null, -- 'joined': the strand the formation returned\n MembershipInvite text null, -- 'joined', closed strand only: JSON {inviteKey, invitePrivateKey},\n -- the StrandMembershipInvite the formation delivered\n FailureCode text null, -- 'failed': a FormationRejectionCode, 'expired' or 'local'\n FailureReason text null, -- 'failed': human-readable text\n StampId text not null unique, -- single-use authorization nonce (anti-replay).\n -- `unique` holds over LIVE rows only; a removed row's stamp is\n -- retired permanently into Revocation (NotRevoked below).\n -- The approval that seated a removed row can never re-seat it, so a dismissed or replaced\n -- row cannot be brought back. Same rationale as OwnerKey.NotRevoked, stated in full there.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'PendingJoin' and R.StampId = new.StampId)\n ),\n -- A delete must file its correctly named tombstone in the same transaction. Same\n -- rationale as StrandPartyKey.RevocationRecorded.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'PendingJoin' and R.StampId = old.StampId and R.RowKey = old.Id)\n ),\n -- Insert + delete only: neither Authorized rule below covers update, so an in-place\n -- rewrite would change the outcome unsigned. Mirrors StrandPartyKey.NoUpdate.\n constraint NoUpdate check on update (false),\n -- Readers cast Outcome to null | 'joined' | 'failed' (ControlDatabase.queryPendingJoins).\n constraint KnownOutcome check (new.Outcome is null or new.Outcome = 'joined' or new.Outcome = 'failed'),\n -- Each outcome carries exactly its own columns, so a reader can trust the shape it reads.\n constraint OutcomeShape check (\n (new.Outcome is null\n and new.OutcomeAt is null and new.StrandId is null and new.MembershipInvite is null\n and new.FailureCode is null and new.FailureReason is null)\n or (new.Outcome = 'joined'\n and new.OutcomeAt is not null and new.StrandId is not null\n and new.FailureCode is null and new.FailureReason is null)\n or (new.Outcome = 'failed'\n and new.OutcomeAt is not null and new.FailureCode is not null\n and new.StrandId is null and new.MembershipInvite is null)\n ),\n constraint AuthorizedInsert check on insert (\n -- Owners authorize by signing over THIS row, every column ending in StampId; nullable\n -- columns sign as '' and integers as their text, so a captured approval can only\n -- reproduce the exact row it approved. Owner-signed only: whether a machine that is\n -- not an owner may record an outcome is an open decision\n -- (tickets/blocked/decide-non-owner-machine-completes-a-pending-join.md).\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.PendingJoin', 'add',\n new.Id, new.Invitation, new.Disclosure, cast(new.RequestedAt as text), cast(new.ExpiresAt as text),\n coalesce(new.Outcome, ''), coalesce(cast(new.OutcomeAt as text), ''), coalesce(new.StrandId, ''),\n coalesce(new.MembershipInvite, ''), coalesce(new.FailureCode, ''), coalesce(new.FailureReason, ''),\n new.StampId), context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n -- 'remove'-tagged digest over the STORED row (Id, StampId), so the add approval can\n -- never be replayed as a removal.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(digest('CadreControl.PendingJoin', 'remove', old.Id, old.StampId), context.Signature, A.Key, 'ed25519'))\n\n -- or REAP: a COMMITTED tombstone already retires this exact row incarnation.\n -- Why committed.* and why the stamp is bound: stated in full on\n -- CadrePeer.AuthorizedDelete. Allowed for the reason the table comment gives.\n or exists (select 1 from committed.Revocation R where R.TableName = 'PendingJoin' and R.RowKey = old.Id and R.StampId = old.StampId)\n )\n ) with context (OwnerKey text, Signature text);\n\n -- A peer (node) that is part of the cadre, carrying a self-published,\n -- freshness-stamped, self-signed address record (see PeerAddressRecord in cadre-core).\n -- The row IS the peer-address record: a resolver reads it, re-verifies Sig against\n -- PublicKey, checks freshness (UpdatedAt) and trust, then dials the addrs.\n table CadrePeer (\n PeerId text primary key,\n PublicKey text null, -- ed25519 (base64url) whose libp2p identity == PeerId (null if non-Ed25519)\n Multiaddr text, -- comma-joined current addrs (signaling / p2p-circuit first)\n UpdatedAt int null, -- epoch ms; strictly increases per self-update (replay/rollback guard)\n Sig text null, -- ed25519 self-signature over the signed payload (base64url); null until self-published\n StampId text not null unique, -- per-row authorization nonce, bound into the voucher/remove digests; rotates on\n -- (re)insert. A removed row's stamp is retired permanently into Revocation\n -- (NotRevoked below), so a captured admission approval cannot re-seat a removed peer.\n VouchOwner text null, -- ed25519 (base64url) owner key that vouched this membership (== insert context.OwnerKey)\n 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).\n -- A removed row's StampId is retired into Revocation, and this refuses any insert\n -- naming a retired stamp: the approval that seated this row can never re-seat it after\n -- removal. `unique` alone did not do this \u2014 it only holds over LIVE rows, so a delete\n -- freed the stamp and the original never-expiring signature verified again. A\n -- legitimate re-add mints a FRESH StampId and a fresh signature, so it is unaffected.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'CadrePeer' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'CadrePeer' and R.StampId = old.StampId and R.RowKey = old.PeerId)\n ),\n constraint AuthorizedInsert check on insert (\n -- Authorized by an owner key, which vouches both membership and the\n -- PublicKey<->PeerId binding (cadre-core derives PublicKey from PeerId before insert).\n -- The digest binds PeerId + the single-use StampId nonce (two TEXT fields),\n -- matching cadre-core peer-authorization.ts:cadrePeerVoucherDigest. The same\n -- 'vouch'-tagged digest is DELIBERATELY shared with the owner branch of\n -- AuthorizedUpdate below: both mean \"this owner vouches this membership row\".\n 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'))\n -- Persist the vouching (owner, signature) onto the row so a reader can later\n -- re-check VouchOwner against its node-local anchor. The stored pair MUST equal\n -- the pair the verify above validated, so a writer cannot store a voucher it did\n -- not actually receive a signature for.\n and new.VouchOwner = context.OwnerKey\n and new.VouchSig = context.Signature\n ),\n constraint AuthorizedDelete check on delete (\n -- Delete is authorized by a signature over the DISTINCT 'remove'-tagged digest bound\n -- to the row's StampId (cadre-core peer-authorization.ts:cadrePeerRemoveDigest), so\n -- the stored voucher (a signature over the 'vouch'-tagged digest) can NEVER be\n -- replayed to authorize a delete. The remove signature rides in context and is never stored.\n 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'))\n\n -- or REAP: this node already holds a COMMITTED tombstone retiring THIS EXACT row\n -- incarnation, so the party owner has already authorized this row's removal and this\n -- node is merely catching up. That is what lets a node which was offline at\n -- revocation time delete the stale row locally, with no owner private key\n -- (control-database.ts:reapRevokedRow). Same shape as the consent branch of\n -- Strand.AuthorizedInsert: authorization by the EXISTENCE of a row rather than by a\n -- signature \u2014 and that row is itself owner-signed (Revocation.Authorized), so this\n -- widens WHO may execute a removal, never WHO may decide one. RevocationRecorded is\n -- satisfied by the same committed tombstone, so a reap files no second one.\n --\n -- committed.Revocation, NOT Revocation \u2014 and the stamp clause \u2014 are both load-bearing:\n -- * committed.* : this CHECK defers to commit (it has a subquery), by which point a\n -- tombstone written in the SAME transaction is live. Reading plain Revocation\n -- would therefore let deleteGuardedRow's own sibling tombstone satisfy this\n -- branch, making the 'remove'-tagged delete signature above dead weight and\n -- collapsing two domain-separated approvals into one. committed.* states the rule\n -- exactly: the tombstone must have existed BEFORE this transaction.\n -- * R.StampId = old.StampId : binds the ROW INCARNATION, not the name. One name may\n -- legitimately carry several tombstones over its life (seat -> delete -> owner\n -- re-seat -> delete). Without this clause a tombstone from a PREVIOUS incarnation\n -- would authorize deleting the CURRENT row, which the owner never removed.\n or exists (select 1 from committed.Revocation R where R.TableName = 'CadrePeer' and R.RowKey = old.PeerId and R.StampId = old.StampId)\n ),\n constraint AuthorizedUpdate check on update (\n -- Peer self-updates its own addrs + freshness, signing with its OWN ed25519 key\n -- (the key behind PeerId). PeerId/PublicKey/StampId/voucher are immutable on\n -- self-update, UpdatedAt must strictly increase (replay guard), and Sig is verified\n -- against the stored PublicKey over the same payload the publish path signs\n -- (cadre-core peer-record.ts:peerRecordSignedPayload).\n (\n new.PeerId = old.PeerId\n and new.PublicKey = old.PublicKey\n and new.StampId = old.StampId\n and new.VouchOwner = old.VouchOwner\n and new.VouchSig = old.VouchSig\n and new.UpdatedAt > coalesce(old.UpdatedAt, 0)\n and verify(\n digest('CadreControl.CadrePeer', 'publish', new.PeerId, new.Multiaddr, cast(new.UpdatedAt as text)),\n new.Sig, new.PublicKey, 'ed25519')\n )\n -- or an owner re-authorizes (rotation / correction): re-vouches the row over\n -- its current StampId, so the stored voucher is re-bound to the re-authorizing owner.\n -- StampId is immutable here too: an update that rotated it would leave the OLD\n -- stamp live-free and untombstoned (RevocationRecorded only retires the stamp a\n -- delete carries), so the original admission approval \u2014 which is stored on the\n -- replicated row as VouchSig \u2014 would resurrect the peer after a later removal.\n -- Retiring a stamp is delete + Revocation row, never an update.\n or (\n new.StampId = old.StampId\n 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'))\n and new.VouchOwner = context.OwnerKey\n and new.VouchSig = context.Signature\n )\n )\n ) with context (OwnerKey text null, Signature text);\n\n -- A mobile cadre peer's platform push token (FCM/APNs), self-published so a\n -- server peer can deliver a push-wake to a suspended app over the platform push\n -- channel (a control-network dial cannot reach an OS-suspended process). The row\n -- mirrors CadrePeer: a resolver re-verifies Sig against the CadrePeer.PublicKey for\n -- this PeerId (see device-token.ts:deviceTokenSignedPayload), checks freshness, then\n -- hands the token to the push sender.\n table DeviceToken (\n PeerId text primary key, -- the CadrePeer this token belongs to\n Platform text not null, -- 'fcm' | 'apns'\n Token text not null, -- opaque platform device/registration token\n UpdatedAt int null, -- epoch ms; strictly increases per self-update (replay guard)\n Sig text null, -- ed25519 self-sig over (PeerId|Platform|Token|UpdatedAt)\n StampId text not null unique, -- single-use authorization nonce, bound into the add/remove digests;\n -- rotates on (re)insert. A cleared token's stamp is retired permanently\n -- into Revocation (NotRevoked below), so the approval that published a\n -- token cannot re-seat it after the owner cleared it (logout).\n -- A removed row's StampId is retired into Revocation, and this refuses any insert\n -- naming a retired stamp: the approval that seated this row can never re-seat it after\n -- the clear. `unique` alone did not do this \u2014 it only holds over LIVE rows, so a delete\n -- freed the stamp and the original never-expiring signature verified again. A legitimate\n -- re-register mints a FRESH StampId and a fresh signature, so it is unaffected. This\n -- matters more here than the stored-approval case (CadrePeer.VouchSig): a resurrected\n -- push token has NO freshness ceiling to retire it \u2014 cadre-node.ts:resolveDeviceToken\n -- defaults maxAgeMs to infinity by design \u2014 so retirement is the only thing that sticks.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'DeviceToken' and R.StampId = new.StampId)\n ),\n -- Retirement is MANDATORY: a delete must carry the matching Revocation row in the same\n -- transaction, or the stamp would free up again. Deferred (subquery), so the sibling\n -- insert is visible at commit regardless of statement order. The tombstone must also\n -- name the removed ROW, not just its stamp \u2014 see Revocation.RowKey.\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'DeviceToken' and R.StampId = old.StampId and R.RowKey = old.PeerId)\n ),\n constraint AuthorizedInsert check on insert (\n -- Authorized by an owner key (membership vouch), exactly like CadrePeer.\n -- The digest binds the WHOLE row behind the domain/action tags \u2014 every column,\n -- with the nullable UpdatedAt/Sig signing as '' when absent (the shape\n -- FormationInvite and Strand already use) \u2014 so a replayed approval can only ever\n -- reproduce the row it approved, never one carrying attacker-chosen\n -- Platform/Token/UpdatedAt; NotRevoked above then refuses even that exact row\n -- once it has been cleared. The DISTINCT 'remove'-tagged digest below keeps a\n -- captured insert approval from doubling as a delete (and vice versa).\n -- Mirrors cadre-core peer-authorization.ts:deviceTokenAddDigest.\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(\n digest(\n 'CadreControl.DeviceToken', 'add',\n new.PeerId,\n new.Platform,\n new.Token,\n coalesce(cast(new.UpdatedAt as text), ''),\n coalesce(new.Sig, ''),\n new.StampId\n ),\n context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n -- Bound to the STORED row's (PeerId, StampId) \u2014 cadre-core\n -- peer-authorization.ts:deviceTokenRemoveDigest \u2014 so the never-expiring insert\n -- approval can never be replayed as a clear, and a captured clear approval is\n -- dead once the stamp it names is retired.\n 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'))\n\n -- or REAP: a COMMITTED tombstone already retires this exact row incarnation, so a node\n -- that was offline at removal time may delete the stale row locally with no owner key.\n -- Why committed.* and why the stamp must be bound: stated in full on\n -- CadrePeer.AuthorizedDelete.\n or exists (select 1 from committed.Revocation R where R.TableName = 'DeviceToken' and R.RowKey = old.PeerId and R.StampId = old.StampId)\n ),\n constraint AuthorizedUpdate check on update (\n -- Peer self-updates its own token, signing with its OWN ed25519 key (the key\n -- behind PeerId). PeerId and StampId are immutable, UpdatedAt must strictly\n -- increase (replay guard), and Sig is verified against the stored\n -- CadrePeer.PublicKey over the signed payload (cadre-core\n -- device-token.ts:deviceTokenSignedPayload). Platform and Token may change on\n -- self-update (platform switch / reinstall / rotation).\n -- StampId is immutable for the reason CadrePeer spells out: an update that\n -- rotated it would leave the OLD stamp live-free and untombstoned, so retiring a\n -- stamp stays delete + Revocation row, never an update.\n -- This is the ONLY branch: there is deliberately NO owner re-touch. The branch\n -- that used to sit beside it verified an owner signature over the peer id alone\n -- and sat OUTSIDE the monotonicity requirement, so one captured owner approval\n -- rewrote Platform/Token and rolled UpdatedAt BACKWARDS \u2014 and seating a\n -- far-future UpdatedAt wedged the peer's own self-updates permanently. No writer\n -- used it. An owner that must correct a row deletes it (retiring the stamp) and\n -- inserts a fresh one, the same path it already takes for CadrePeer.\n new.PeerId = old.PeerId\n and new.StampId = old.StampId\n and new.UpdatedAt > coalesce(old.UpdatedAt, 0)\n and exists (select 1 from CadrePeer P where P.PeerId = new.PeerId and verify(\n digest('CadreControl.DeviceToken', 'publish', new.PeerId, new.Platform, new.Token, cast(new.UpdatedAt as text)),\n new.Sig, P.PublicKey, 'ed25519'))\n )\n ) with context (OwnerKey text null, Signature text);\n\n -- An open invitation to form a strand with this party\n table FormationInvite (\n Token text primary key, -- Just a random string\n sAppId text, -- The app for the strand that will be formed\n ExpiresAt datetime null,\n TotalUses int null check (TotalUses >= 0),\n ValidationUrl text null, -- Web hook - send disclosure, IP address...\n StrandId text null, -- Host strand this invite binds to (provision-then-record). Non-null => the responder records consent against this pre-existing strand; null => unbound invite: the responder provisions a fresh open strand and atomically records its one consent row.\n StampId text not null unique, -- single-use authorization nonce (anti-replay)\n constraint AuthorizedInsert check on insert (\n -- Authorized by an owner signing over THIS row\n -- (Token, sAppId, ExpiresAt, TotalUses, ValidationUrl, StrandId, StampId); single-use via unique StampId.\n -- Nullable bound fields (ExpiresAt/TotalUses/ValidationUrl/StrandId) sign as '' when absent.\n -- The 'remove'-tagged AuthorizedDelete digest below is DISTINCT, so a captured\n -- insert approval can never be replayed to revoke-then-reissue an invite (or vice versa).\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(\n digest(\n 'CadreControl.FormationInvite', 'add',\n new.Token,\n new.sAppId,\n coalesce(cast(new.ExpiresAt as text), ''),\n coalesce(cast(new.TotalUses as text), ''),\n coalesce(new.ValidationUrl, ''),\n coalesce(new.StrandId, ''),\n new.StampId\n ),\n context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey and verify(\n digest(\n 'CadreControl.FormationInvite', 'remove',\n old.Token,\n old.sAppId,\n coalesce(cast(old.ExpiresAt as text), ''),\n coalesce(cast(old.TotalUses as text), ''),\n coalesce(old.ValidationUrl, ''),\n coalesce(old.StrandId, ''),\n old.StampId\n ),\n context.Signature, A.Key, 'ed25519'))\n ),\n -- Invites are insert/delete only: forbid in-place mutation so the row-bound\n -- AuthorizedInsert signature cannot be sidestepped by updating consent\n -- parameters (TotalUses/ExpiresAt/...) after a legitimate insert. A bare check\n -- defaults to insert+update; the checks on insert / on delete above exclude update,\n -- so this guard is required. Mirrors FormationUsage.InsertOnly.\n constraint Immutable check on update (false)\n ) with context (OwnerKey text, Signature text);\n\n table FormationUsage (\n Token text not null, -- the FormationInvite this acceptance redeems. Stated explicitly because\n -- Token is no longer a primary-key prefix; Authorized below would refuse a\n -- null anyway (null = null is never true, so its FormationInvite\n -- exists-clause cannot match), but the column carries the invariant rather\n -- than leaving it to a CHECK.\n UsageStampId text not null, -- single-use nonce for THIS redemption, and this table's PRIMARY KEY.\n -- The JOINING peer mints it and sends it in its contact message, having\n -- signed it into its own 'consent' digest (PeerConsented below); the\n -- responder inserts that same value and asks the approver about it, so it\n -- is bound into the 'vouch' digest below too and one sign-off is spendable\n -- exactly once. Neither side can swap it: a substituted nonce fails the\n -- joiner's consent signature.\n -- As the row key, a verbatim replay of an approval collides on the\n -- primary key locally instead of on a column `unique`. Unlike every other\n -- StampId in this schema, this table is append-only (InsertOnly below),\n -- so the nonce is never freed by a delete: the key alone makes it\n -- permanent and there is deliberately NO NotRevoked / RevocationRecorded\n -- pair here \u2014 do not go looking for the missing one.\n -- NOTE: the key is evaluated against LOCALLY VISIBLE rows, so two nodes\n -- that have not yet converged could each admit the same nonce and both\n -- rows survive the merge. Same class as the NotRevoked convergence notes\n -- on OwnerKey / Strand / ValidationKey; the digest binding still holds on\n -- both nodes, so the outcome is a duplicated audit row, never a join\n -- nobody approved.\n PeerKey text not null, -- the joining peer's own ed25519 public key (base64url, 32 bytes), bound\n -- into BOTH the approver's 'vouch' digest and the joiner's 'consent'\n -- digest below, so an approval cannot be re-filed under a different\n -- joiner's name and the named joiner provably agreed (PeerConsented).\n -- The key IS the joiner's identity \u2014 its libp2p peer id is derivable\n -- (identity multihash of these bytes), never stored here.\n PeerSig text not null, -- the joining peer's signature over the 'consent' digest \u2014 see\n -- PeerConsented below for what it proves and why it is stored on the row.\n Disclosure text,\n StrandId text,\n StrandStampId text not null, -- the Strand.StampId this consent record authorizes. Consent is\n -- bound to ONE strand ROW, not to a strand id forever \u2014 see\n -- Strand.AuthorizedInsert's consent branch for why. NOT unique:\n -- in the bound (provision-then-record) path several invitees\n -- each write a usage row against the SAME host strand, so many\n -- usage rows legitimately share one stamp.\n primary key (UsageStampId),\n constraint InsertOnly check on update, delete (false),\n constraint Authorized check on insert (\n -- Satisfies an invitation\n exists (\n select 1 from FormationInvite FI\n where FI.Token = new.Token\n -- The use cap is COUNTED against the pre-transaction snapshot, never\n -- sequenced. This CHECK auto-defers to commit (it has a subquery), by\n -- which point the in-flight row is live; committed.* is what excludes\n -- it, so a sequentially exhausted invite \u2014 every seat already committed\n -- on this node \u2014 is still refused here. What is deliberately NOT\n -- refused: concurrent redeemers on separate nodes (or nodes that have\n -- not yet converged) each count the same committed snapshot and both\n -- land, over-admitting by at most the number of concurrent redeemers.\n -- Both rows survive in this append-only record, so the overage is\n -- auditable, and removal is owner-gated (member removal + Revocation).\n -- Same class as the convergence note on UsageStampId above.\n -- One rule for FUTURE writers: two FormationUsage rows for one token\n -- inserted in ONE transaction each read the same committed count, so\n -- they can jointly exceed the cap. No writer in this repo does that; it\n -- is a constraint on new writers, not a case to engineer for.\n -- Do not \"fix\" this into a per-token sequence number to restore a\n -- strict cap \u2014 that trade was weighed and rejected (2026-08-04): a\n -- fought-over sequence key turns a concurrent redemption into a silent,\n -- unrecoverable loss of a consented join, which is strictly worse than\n -- a visible, reversible over-admission.\n and (FI.TotalUses is null or FI.TotalUses > (select count(1) from committed.FormationUsage U where U.Token = new.Token))\n and (FI.ExpiresAt is null or FI.ExpiresAt > context.Now)\n -- An invite carrying a ValidationUrl demands a sign-off from a key the party\n -- ENROLLED in ValidationKey. The signature is verified against the STORED VK.Key,\n -- NOT against context.ValidationKey \u2014 that distinction is the whole point:\n -- context.ValidationKey is a plain insert parameter, so verifying against it asked\n -- only \"did the redeemer sign its own disclosure with SOME key it holds?\", which any\n -- redeemer answers by minting a throwaway keypair. context.ValidationKey survives\n -- purely to SELECT which enrolled row is being claimed; naming an enrolled key while\n -- signing with a different one fails the verify against VK.Key.\n --\n -- Deliberate: CHECKs run on write only, so removing a validation key later does NOT\n -- re-examine the FormationUsage rows it already approved. The sign-off was valid when\n -- given and the strand it authorized stays formed; removal narrows who may approve\n -- FUTURE redemptions, it is not a retroactive revocation of past ones.\n --\n -- What ONE sign-off buys: exactly ONE row. The digest covers\n -- (Token, UsageStampId, StrandId, PeerKey, Disclosure), so an approval is NOT\n -- transferable across invitations, redemptions, networks, joiners, or disclosure\n -- text. Replay is closed twice over, by two independent mechanisms: presenting an\n -- approval VERBATIM repeats its UsageStampId and is refused by this table's\n -- primary key; presenting it under any OTHER redemption changes a signed field\n -- and fails this verify.\n -- Every signed field is supplied by the redeeming side \u2014 nothing derived from\n -- the table's current state is bound \u2014 so no concurrent write can invalidate an\n -- approval between the sign-off and the row landing.\n -- Why StrandStampId is deliberately NOT bound: it names the strand ROW\n -- incarnation, which the unbound path (redeemInvitation) mints inside its own\n -- transaction, and it adds nothing on top of a strictly single-use approval \u2014\n -- StrandId already pins WHICH network the approver approved joining.\n and (FI.ValidationUrl is null or exists (\n select 1 from ValidationKey VK\n where VK.Key = context.ValidationKey\n and verify(digest('CadreControl.FormationUsage', 'vouch', new.Token, new.UsageStampId, new.StrandId, new.PeerKey, new.Disclosure), context.ValidationSignature, VK.Key, 'ed25519')))\n -- A bound invite (non-null StrandId) may only ever name its own host strand:\n -- without this, any holder of a bound token could record consent against an\n -- arbitrary strand id \u2014 annotating an unrelated strand, or (before\n -- Strand.AuthorizedInsert's consent branch was narrowed to unbound invites)\n -- consent-seating that id outright.\n -- NOTE: an UNBOUND invite is deliberately left free to name any strand, so a\n -- holder can spend a use appending a consent row to an unrelated existing\n -- strand. Harmless today (the row grants nothing, it only burns a use and\n -- forecloses that id's consent-seating, which is the safe direction); if\n -- unlimited-TotalUses invites ever become common, this is an append-only\n -- growth surface worth bounding.\n and (FI.StrandId is null or FI.StrandId = new.StrandId)\n )\n ),\n -- Matched on the (id, stamp) PAIR, the same key Strand.AuthorizedInsert's consent branch\n -- reads back: a usage row may only ever name a strand ROW that exists, so a consent record\n -- can never be filed against a stamp of the writer's choosing and held in reserve to\n -- re-seat the id after a removal.\n constraint StrandExists check (exists (select 1 from Strand S where S.Id = new.StrandId and S.StampId = new.StrandStampId)),\n -- The JOINING peer proves it consented to this redemption: PeerKey is its own ed25519\n -- public key and PeerSig is its signature over the 'consent'-tagged digest below.\n -- Unlike the approver's sign-off (context.ValidationSignature, checked against a STORED\n -- ValidationKey row), the identity here IS the key, so there is no enrolled row to look\n -- up and nothing for a writer to substitute: a forged joiner would need that joiner's\n -- private key. Stored rather than passed in context so any later reader can re-check it\n -- (verifyFormationConsent); the 'consent' action tag keeps this replicated signature\n -- useless against every other rule in this schema (notably the approver's 'vouch'\n -- digest over the same table).\n -- NOTE: StrandId is deliberately NOT in this digest \u2014 the joiner cannot know it when it\n -- signs (a bound invite's host strand arrives only in the result frame; an unbound\n -- strand is responder-minted). The responder cannot substitute a strand anyway: bound\n -- invites are pinned by Authorized's FI.StrandId check, unbound invites mint fresh.\n constraint PeerConsented check on insert (\n verify(digest('CadreControl.FormationUsage', 'consent',\n new.Token, new.UsageStampId, new.PeerKey, new.Disclosure),\n new.PeerSig, new.PeerKey, 'ed25519')\n ),\n -- Context here is only what the approver-side rules read: Now for expiry, and the\n -- ValidationKey/ValidationSignature pair for the 'vouch' check in Authorized. The joiner's\n -- signature is NOT context \u2014 it lives on the row (PeerSig, verified by PeerConsented above).\n ) with context (Now datetime, ValidationKey text null, ValidationSignature text null);\n\n -- Token is no longer a primary-key prefix (the key is the redemption nonce), so the\n -- per-token filters \u2014 the cap count in Authorized above, and cadre-core's\n -- countFormationUsage / isTokenUsed / hasOutstandingFormationInvite \u2014 are served by this\n -- index rather than by a full scan of a table that is append-only and grows for the life\n -- of the party.\n --\n -- The cap count is only ever as correct as this index's convergence across machines. That\n -- convergence failed once: from 2026-08-04 to 2026-08-25 a descent on a second machine\n -- returned only the rows THAT machine wrote, so the index was removed and the reads went\n -- back to the scan. The engine defect was fixed upstream and re-measured here on\n -- 2026-09-17, so the index is declared again. Its guard is the integration-tests scenario\n -- `strand-formation-concurrent-redemption`, which asserts BOTH machines' views of a raced\n -- redemption and therefore goes red if that convergence regresses.\n --\n -- NOTE: the write side has its own exposure. Every FormationUsage insert now maintains this\n -- sub-collection as well as the table, and an intermittent engine failure once hit exactly that\n -- step on other tables (a table's rows committed while its index did not; closed 2026-09-17 with\n -- the upstream sync fixes, `tickets/complete/strand-unique-index-sync-stale-revision`). Nothing\n -- has been observed here, and redemptions are rare writes; but if joins start failing\n -- intermittently with an index-sync error naming FormationUsage, this declaration is the first\n -- thing to suspect.\n index FormationUsageByToken on FormationUsage (Token);\n\n -- Append-only retirement record for the one-off StampId nonces of removed rows of every\n -- guarded table (listed on TableName below). Without it a removal was undoable: the add\n -- approval is a signature over\n -- (row key, stamp) that never expires, and deleting the row freed the stamp, so anyone who\n -- kept a copy of the approval could resurrect the row.\n -- Each tombstone also records WHICH row was retired (RowKey below): the consent branch of\n -- Strand.AuthorizedInsert reads it to refuse consent-seating any strand id that has ever\n -- been removed, whichever way it was seated.\n -- NOTE: the guarded tables' NotRevoked CHECK runs against locally visible rows, so a node\n -- that has not yet converged on a Revocation row can still accept the replayed add, and the\n -- resurrected row coexists with the tombstone after merge \u2014 same class as the MinOneOwner\n -- note on OwnerKey. The read-side mitigation is ControlDatabase.queryCadrePeers, which\n -- drops any CadrePeer row whose StampId appears here; every membership reader inherits it.\n -- NOTE: append-only, so this table only ever grows. Every append is owner-signed\n -- (Authorized below), so the growth surface is the owner keys, not every writer that can\n -- reach the control database. Cadres are a handful of peers and owner rotation is rare, so\n -- unbounded growth is fine today; revisit if either changes.\n -- A tombstone committed while the node was alone is local-only (never broadcast); the\n -- ReissuedAt counter below exists so an owner can re-write \u2014 and therefore re-broadcast \u2014\n -- such a tombstone once peers are reachable, without changing what it means.\n -- One row retires nothing: the singleton ledger marker ('Revocation', 'ledger', 'opened'),\n -- filed once by an owner's connected reconcile pass (ControlDatabase.openRevocationLedger).\n -- It exists only so this table is never a never-written block. The storage layer consults\n -- a block's cohort on EVERY read of a block it does not hold, and every membership lookup\n -- and every guarded insert (NotRevoked) reads this table; once any row exists the block is\n -- held and re-checked on the storage layer's normal read-repair schedule, like every other\n -- populated table. It cannot read as a retirement: every reader of this table filters on\n -- its own guarded TableName, 'Revocation' is not one, and ControlDatabase.queryRevocations\n -- skips the marker, so nothing reaps or re-issues it.\n table Revocation (\n TableName text, -- 'OwnerKey' | 'CadrePeer' | 'ValidationKey' | 'Strand' | 'StrandPartyKey' |\n -- 'JoinedStrand' | 'PendingJoin' | 'DeviceToken', or 'Revocation' for the\n -- ledger marker only (all confined by RowIsGone below)\n RowKey text not null, -- primary key of the removed row: OwnerKey.Key / ValidationKey.Key /\n -- CadrePeer.PeerId / DeviceToken.PeerId / Strand.Id / StrandPartyKey.Id /\n -- JoinedStrand.Id / PendingJoin.Id\n -- Every guarded table's RevocationRecorded CHECK requires the\n -- accompanying tombstone to carry the removed row's key here, so\n -- a REMOVAL cannot file a misnamed tombstone. A tombstone with no\n -- accompanying delete is not covered by that (see Authorized).\n StampId text, -- the retired nonce\n -- Bumped by an owner-signed re-issue so a tombstone written while the node was alone\n -- (committed local-only, never broadcast) can be re-written and therefore re-broadcast\n -- on cohort growth. Carries NO semantics: nothing reads it, and retirement is decided\n -- by the row's existence, not by this value.\n ReissuedAt integer not null default 0,\n -- Keyed on the stamp, not the RowKey: stamps are unique per row incarnation, and one\n -- name may legitimately carry several tombstones over its life (seat -> delete ->\n -- owner re-seat -> delete).\n primary key (TableName, StampId),\n -- Retirement is permanent: a tombstone may never be withdrawn.\n constraint NoDelete check on delete (false),\n -- Pinned at 0 on insert so an owner cannot seat a tombstone at a saturated counter and\n -- thereby freeze its own later re-issues (ReissueOnly below). Deliberately NOT folded\n -- into the Authorized digest: the value is fixed by this rule, so signing over it would\n -- only widen the signed surface for no gain, and would invalidate every existing\n -- insert-side digest.\n constraint FreshTombstone check on insert (new.ReissuedAt = 0),\n -- A re-issue may move NOTHING but the counter, and only upward. Without the identity\n -- clause an \"update\" would be a way to re-point a tombstone at a different row,\n -- restoring exactly the replay this table exists to stop.\n constraint ReissueOnly check on update (\n new.TableName = old.TableName and new.RowKey = old.RowKey\n and new.StampId = old.StampId and new.ReissuedAt > old.ReissuedAt\n ),\n -- A stamp may only be retired once its row is actually gone. Deferred (subquery), so a\n -- delete in the same transaction has already landed. Retiring a stamp that never\n -- existed is permitted and harmless: a stamp carries 128 bits of CSPRNG output\n -- (control-database.ts:generateStampId \u2014 16 bytes of sha256(PeerId) followed by 16\n -- random bytes), so a future legitimate one cannot be guessed and pre-planted.\n -- Deliberately keyed on the STAMP only, not RowKey: checking \"no live row named\n -- new.RowKey\" breaks under out-of-order convergence \u2014 a peer removed (tombstone names\n -- it, stamp1) then re-admitted (stamp2) would leave a node that converges on the\n -- re-add FIRST rejecting the stamp1 tombstone forever, never learning that stamp is\n -- retired. The stamp-only form passes there (stamp1 is not live).\n -- The last branch admits the ledger marker (see the table comment) and nothing else under\n -- TableName 'Revocation': the whole triple is pinned, so with the primary key\n -- (TableName, StampId) it is a singleton and the append-only growth surface is unchanged.\n -- 'opened' cannot collide with a real stamp (43 base64url characters, generateStampId),\n -- and the primary key includes TableName anyway.\n constraint RowIsGone check on insert (\n (new.TableName = 'OwnerKey' and not exists (select 1 from OwnerKey K where K.StampId = new.StampId))\n or (new.TableName = 'CadrePeer' and not exists (select 1 from CadrePeer P where P.StampId = new.StampId))\n or (new.TableName = 'ValidationKey' and not exists (select 1 from ValidationKey V where V.StampId = new.StampId))\n or (new.TableName = 'Strand' and not exists (select 1 from Strand S where S.StampId = new.StampId))\n or (new.TableName = 'StrandPartyKey' and not exists (select 1 from StrandPartyKey K where K.StampId = new.StampId))\n or (new.TableName = 'JoinedStrand' and not exists (select 1 from JoinedStrand J where J.StampId = new.StampId))\n or (new.TableName = 'PendingJoin' and not exists (select 1 from PendingJoin P where P.StampId = new.StampId))\n or (new.TableName = 'DeviceToken' and not exists (select 1 from DeviceToken D where D.StampId = new.StampId))\n or (new.TableName = 'Revocation' and new.RowKey = 'ledger' and new.StampId = 'opened')\n ),\n -- Appending a tombstone is an OWNER action, like every other write in this schema.\n -- Ungated, any writer that could reach the control database could retire a stamp:\n -- filing one against a CadrePeer row not visible locally (RowIsGone reads LOCALLY\n -- VISIBLE rows \u2014 see the convergence note above) evicted that peer party-wide AND\n -- permanently blocked the owner's own later re-admission of it (NotRevoked), and\n -- filing arbitrary stamps flooded a table whose rows never go away.\n -- The digest binds the WHOLE row (TableName, RowKey, StampId); the 'CadreControl.Revocation'\n -- domain tag keeps it disjoint from every other rule \u2014 including the\n -- 'CadreControl.CadrePeer' 'remove' digest the same owner signs in the SAME\n -- transaction for the delete this tombstone accompanies.\n -- RowKey is not cross-checked HERE against the retired row: positively binding it (e.g.\n -- requiring a committed.Strand row carrying the pair) would reject a tombstone re-issued\n -- in a LATER transaction \u2014 which the delete-while-alone durability path\n -- (docs/architecture.md) plans to do \u2014 and reject it outright on a node that never\n -- converged on the removed row. The binding lives on the other side instead: each\n -- guarded table's RevocationRecorded requires the tombstone accompanying a DELETE to\n -- name that row's key, which the re-issue path never trips (it files no delete).\n -- Residual: a STANDALONE tombstone \u2014 owner-signed, naming a stamp no live row holds \u2014\n -- is still accepted, so an owner can name an id that never existed and thereby\n -- permanently foreclose CONSENT-seating of that id (Strand.AuthorizedInsert).\n -- Owner-only, the owner already controls invite issuance, and unbound ids are 128\n -- random bytes minted at redemption \u2014 no escalation (same reasoning as the pre-plant\n -- note on RowIsGone).\n -- Reads LIVE OwnerKey (like ValidationKey / Strand / CadrePeer / DeviceToken), not\n -- committed.OwnerKey. The one difference that makes: a founding transaction on an\n -- owner-less database could seat an owner key and file a tombstone in one go. An\n -- owner-less control database is already a total loss, and a second transaction\n -- achieves the same thing under committed.*, so consistency with the siblings is\n -- worth more than the distinction \u2014 do not \"tighten\" this without a reason other\n -- than that one.\n -- RowIsGone and NoDelete are unchanged: they guard an owner retiring a stamp early\n -- or withdrawing one later, which authorization does not cover.\n -- The ledger marker is signed under this same rule, over\n -- digest('CadreControl.Revocation', 'remove', 'Revocation', 'ledger', 'opened'). The\n -- 'remove' tag on a row that retires nothing is deliberate: reusing the one append rule\n -- keeps every append owner-signed without adding an unsigned or differently tagged\n -- branch, and a captured marker signature can only re-file the identical row, whose\n -- primary key is already taken.\n constraint Authorized check on insert (\n 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'))\n ),\n -- A re-issue is an OWNER action, like the original append. Distinct 'reissue' action\n -- tag, so an append approval can never be replayed as a re-issue and vice versa. The\n -- digest adds ReissuedAt so a captured re-issue signature cannot bump the counter to\n -- any other value. Reads LIVE OwnerKey, matching Authorized above.\n constraint AuthorizedReissue check on update (\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey\n and verify(digest('CadreControl.Revocation', 'reissue',\n new.TableName, new.RowKey, new.StampId, cast(new.ReissuedAt as text)),\n context.Signature, A.Key, 'ed25519'))\n )\n ) with context (OwnerKey text, Signature text);\n}\n\napply schema CadreControl;";
|
|
12
|
+
export declare const CONTROL_SCHEMA = "-- A Sereus party's cadre (its nodes) and their participation in strands (networks).\n--\n-- Every write is authorized by a check: an owner signs an action-tagged digest of the row\n-- (cadre-core control-authorization.ts), or a peer signs its own record. Each digest leads\n-- with a 'CadreControl.<Table>' domain tag, an action tag and party_id(), the party this\n-- machine is configured for (a zero-argument function ControlDatabase registers on its own\n-- engine, never read from a context value or a replicated table), so an approval verifies\n-- only against the one rule, in the one party, it was minted for: two parties that share\n-- an owner key never accept each other's approvals. FormationUsage is the exception, its\n-- two digests scoped by the invitation token instead (FormationUsage.Authorized).\n--\n-- Rows of the guarded tables (OwnerKey, ValidationKey, Strand, StrandPartyKey, JoinedStrand,\n-- JoinRequest, CadrePeer, DeviceToken, CadreInvite) carry a one-off StampId bound into their\n-- add and remove digests. `unique` holds over live rows only, so a delete retires the stamp\n-- into Revocation in the same transaction (RevocationRecorded) and an insert refuses a retired\n-- stamp (NotRevoked): the never-expiring add approval cannot re-seat a removed row. A\n-- legitimate re-add mints a fresh stamp and a fresh signature. CadreInvite is the one guarded\n-- table that is never deleted: its tombstone withdraws the invitation while the row stays,\n-- because the rows it admitted prove their membership through it.\n--\n-- A check whose expression evaluates to null passes (SQL three-valued logic), so every\n-- comparison over a nullable column that is meant to pin a value is written null-safe\n-- (`coalesce(col, '')` or an explicit `is null`); a bare `new.Col = context.X` over a null\n-- column would pass with nothing pinned.\n--\n-- A check with a subquery defers to commit, so a sibling row written in the same transaction\n-- is visible to it; `committed.<Table>` reads the pre-transaction snapshot instead. Every\n-- check reads the rows this node holds: a node that has not converged on a Revocation row\n-- still accepts the replayed add, and the resurrected row then coexists with its tombstone.\n-- ControlDatabase drops retired stamps on the reads that matter (queryCadrePeers,\n-- queryPendingJoins, getOwnerKeys), and every owner lookup in the checks below drops them\n-- too (the `not exists ... Revocation` conjunct beside each OwnerKey read, reading live\n-- Revocation so a tombstone filed in the same transaction counts), so a removal is\n-- effective at the writer as soon as its tombstone arrives, whether or not the row's delete\n-- has. Only the founding count in OwnerKey.Authorized stays raw.\ndeclare schema CadreControl {\n -- A key that can authorize control changes. A row is seated one of three ways, told apart\n -- by the vouch columns: the founding row (all three null), an owner-signed add (VouchOwner\n -- and VouchSig pinned to the insert context, VouchUsage null), or an owner-granting\n -- invitation redeemed by consent (VouchOwner = the invitation's IssuerKey, VouchSig null,\n -- VouchUsage = the CadreInviteUsage row that admitted it). A reader judges the stored proof\n -- against its node-local anchor, never against this replicated table.\n table OwnerKey (\n Key text primary key,\n StampId text unique,\n VouchOwner text null,\n VouchSig text null,\n VouchUsage text null,\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = new.StampId)\n ),\n -- The tombstone must name the removed row, not just its stamp (Revocation.RowKey).\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = old.StampId and R.RowKey = old.Key)\n ),\n -- Every other table's checks require an owner, so an empty table is a permanent denial of\n -- the party's control plane. Counted post-delete, on this node's rows only: two partitioned\n -- nodes removing different owners can still converge to zero.\n constraint MinOneOwner check on delete (\n (select count(1) from OwnerKey) >= 1\n ),\n -- Rotation is add-then-remove. An update branch would let the sole owner be re-pointed at\n -- another key under a post-image count of one.\n constraint NoUpdate check on update (false),\n -- The authorizer is read from the pre-transaction snapshot: the check defers to commit, by\n -- which point the inserted row (and any sibling) is live, so a plain OwnerKey read would let\n -- a row authorize itself or two strangers seat each other. The founding transaction, whose\n -- pre-transaction owner set is empty, needs no authorization; gating on the pre-transaction\n -- count keeps a same-transaction swap of the sole owner off that branch. That count is\n -- deliberately raw, the one owner read here that ignores Revocation: a machine holding only\n -- a retired owner row must still be refused a second genesis, or a removed device could\n -- re-found the party on its own copy. An owner cannot sign its own removal.\n -- The consent branch seats an owner with no signature at all: a CadreInviteUsage row\n -- written in the same transaction names this exact row (Key and stamp), and the\n -- invitation it redeemed grants ownership and was issued by the stored VouchOwner. The\n -- invitation is read from committed.CadreInvite, so an invitation cannot be seated and\n -- redeemed in one transaction; the usage row carries the liveness conditions.\n constraint Authorized check on insert, delete (\n (old.Key is null and (select count(1) from committed.OwnerKey) = 0\n and new.VouchOwner is null and new.VouchSig is null and new.VouchUsage is null)\n 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, new.StampId), context.Signature, A.Key, 'ed25519'))\n and coalesce(new.VouchOwner, '') = context.OwnerKey\n and coalesce(new.VouchSig, '') = context.Signature\n and new.VouchUsage is null)\n or (old.Key is null and new.VouchSig is null and new.VouchUsage is not null\n and exists (\n select 1 from CadreInviteUsage U\n where U.UsageStampId = new.VouchUsage\n and U.PeerKey = new.Key\n and U.OwnerStampId = new.StampId\n and exists (select 1 from committed.CadreInvite I where I.Key = U.InviteKey and I.GrantsOwner = 1 and I.IssuerKey = new.VouchOwner)\n ))\n 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')))\n )\n ) with context (OwnerKey text null, Signature text null);\n\n -- A key that can validate a strand formation disclosure (FormationUsage.Authorized).\n table ValidationKey (\n Key text primary key,\n StampId text unique,\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'ValidationKey' and R.StampId = new.StampId)\n ),\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'ValidationKey' and R.StampId = old.StampId and R.RowKey = old.Key)\n ),\n constraint NoUpdate check on update (false),\n constraint AuthorizedInsert check on insert (\n 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'))\n ),\n -- Owner-signed over the stored row, or a reap: a committed tombstone naming this exact row\n -- incarnation lets a node that was offline at removal time delete the stale row unsigned\n -- (ControlDatabase.reapRevokedRow). committed.*, so a tombstone filed in this transaction\n -- cannot stand in for the signature; the stamp clause, so a tombstone of an earlier\n -- incarnation cannot remove the current one.\n constraint AuthorizedDelete check on delete (\n 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'))\n or exists (select 1 from committed.Revocation R where R.TableName = 'ValidationKey' and R.RowKey = old.Key and R.StampId = old.StampId)\n )\n ) with context (OwnerKey text, Signature text);\n\n -- A network of members sharing an sApp database, each contributing its cadre's peers. This\n -- party's own strands; a strand joined from another party is a JoinedStrand row.\n table Strand (\n Id text primary key, -- UUID\n MemberPrivateKey text null unique, -- the strand's shared read secret; closed strands only\n Type text, -- 'o' open | 'c' closed: open gates writes in the sApp, only closed gates reads\n FounderOwnerKey text null, -- owner key of the machine that published the row, the founding machine\n -- (cadre-node.ts launchStrand); null on a consent-seated strand, whose\n -- insert carries no signature. Provenance, not content (strandRowMismatches).\n StampId text unique,\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'Strand' and R.StampId = new.StampId)\n ),\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'Strand' and R.StampId = old.StampId and R.RowKey = old.Id)\n ),\n -- The consent branch below carries no signature, so an update rule would let anyone rewrite\n -- a consent-seated strand.\n constraint NoUpdate check on update (false),\n -- Owner-signed, with FounderOwnerKey pinned to the verified signer; or consent-seated by a\n -- FormationUsage row naming this exact row (id and stamp), written in the same transaction\n -- (ControlDatabase.redeemInvitation). Binding the stamp is what makes a removal stick:\n -- the usage row outlives the strand, and keyed on the id alone it would re-authorize an\n -- unsigned re-seat under a fresh stamp. The consent branch is narrow, each clause closing\n -- one door:\n -- * open and keyless: a closed strand with a caller-chosen read secret has no legitimate\n -- producer;\n -- * through an unbound invite only: a bound invite's host strand is owner-provisioned,\n -- and consent-seating its id would downgrade the real row on a node it has not reached;\n -- * no usage row under another stamp, and no tombstone for the id: an id is consent-seated\n -- once, ever, and never after any removal. Re-joining a removed id is owner-signed.\n -- A standalone tombstone (no accompanying delete, Revocation.Authorized) lets an owner\n -- foreclose consent-seating of an id that never existed: owner-only, and ids are random.\n constraint AuthorizedInsert check on insert (\n (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.StampId), context.Signature, A.Key, 'ed25519'))\n and new.FounderOwnerKey = context.OwnerKey)\n or (\n new.Type = 'o'\n and new.MemberPrivateKey is null\n and new.FounderOwnerKey is null\n and exists (\n select 1 from FormationUsage FU\n where FU.StrandId = new.Id\n and FU.StrandStampId = new.StampId\n and exists (select 1 from FormationInvite FI where FI.Token = FU.Token and FI.StrandId is null)\n )\n and not exists (\n select 1 from FormationUsage FU2\n where FU2.StrandId = new.Id and FU2.StrandStampId <> new.StampId\n )\n and not exists (\n select 1 from Revocation R\n where R.TableName = 'Strand' and R.RowKey = new.Id\n )\n )\n ),\n -- No consent branch (an invitation forms a strand, never destroys one) and no reap branch:\n -- MemberPrivateKey is stored nowhere else, so this delete is unrecoverable\n -- (tickets/backlog/debt-strand-tombstone-reap.md owns any change).\n constraint AuthorizedDelete check on delete (\n 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'))\n ),\n -- An open strand has no membership gate, so no member key.\n constraint MemberKeyClosedOnly check (\n new.MemberPrivateKey is null or new.Type = 'c'\n )\n ) with context (OwnerKey text, Signature text);\n\n -- This party's own membership identity for one strand: the private key whose public half\n -- seats its Strand.Member / Strand.Manager rows. Separate from Strand.MemberPrivateKey, which\n -- every joining party receives and so could forge (gotchoices/sereus#4). A side table because\n -- a joiner holds no Strand row. Replicated in plaintext to every machine the party owns\n -- (docs/strands.md \u2192 \"Closed-Strand Member Key Handling\") but never put on the formation wire.\n table StrandPartyKey (\n Id text primary key, -- the strand id\n PrivateKey text, -- ed25519, base64 protobuf, as Strand.MemberPrivateKey (cadre-core strandMemberKeyPair)\n StampId text unique,\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'StrandPartyKey' and R.StampId = new.StampId)\n ),\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'StrandPartyKey' and R.StampId = old.StampId and R.RowKey = old.Id)\n ),\n constraint NoUpdate check on update (false),\n -- Binding PrivateKey means a captured approval can only reproduce the key it approved.\n constraint AuthorizedInsert check on insert (\n 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'))\n ),\n -- No reap branch: the key is stored nowhere else (as Strand.AuthorizedDelete).\n constraint AuthorizedDelete check on delete (\n 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'))\n )\n ) with context (OwnerKey text, Signature text);\n\n -- A strand this party joined from another party, whose control database holds the Strand\n -- row. Every machine of the party reads it, so a replica host keeps a copy and the party's\n -- other machines can attach. A separate table because every reader of Strand takes it to\n -- mean this party's own strand. MemberPrivateKey is held by the founding party and every\n -- member, so a removed row is recoverable by re-forming, which is why this table has a reap\n -- branch (unlike Strand and StrandPartyKey).\n table JoinedStrand (\n Id text primary key, -- the founder's Strand.Id\n Type text, -- 'o' | 'c', as Strand.Type\n MemberPrivateKey text null, -- the closed strand's shared read secret\n StampId text unique,\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'JoinedStrand' and R.StampId = new.StampId)\n ),\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'JoinedStrand' and R.StampId = old.StampId and R.RowKey = old.Id)\n ),\n constraint NoUpdate check on update (false),\n -- Readers cast Type (ControlDatabase.queryJoinedStrands).\n constraint KnownType check (new.Type = 'o' or new.Type = 'c'),\n constraint MemberKeyClosedOnly check (new.MemberPrivateKey is null or new.Type = 'c'),\n -- Owner-signed only: every always-on machine of the party downloads the strands named\n -- here, so a machine that is not an owner keeps its joins machine-local.\n constraint AuthorizedInsert check on insert (\n 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'))\n ),\n constraint AuthorizedDelete check on delete (\n 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'))\n or exists (select 1 from committed.Revocation R where R.TableName = 'JoinedStrand' and R.RowKey = old.Id and R.StampId = old.StampId)\n )\n ) with context (OwnerKey text, Signature text);\n\n -- A join this party asked for by redeeming another party's invitation, kept party-wide so\n -- the request outlives the device that asked and any owner machine can carry it on\n -- (docs/strands.md \u2192 \"Joining while the inviter is offline\"). The row is the request alone\n -- and never changes; its outcome is a JoinSuccess or JoinFailure row keyed by this row's\n -- stamp, so asking again (a fresh stamp) starts clean and a dismissal's tombstone retires\n -- the outcome with the request. Invitation is a bearer credential, replicated in plaintext\n -- to every machine the party owns, under the same accepted risk as JoinedStrand.\n -- Owner-signed only; whether a machine that is not an owner may write here is\n -- tickets/blocked/decide-non-owner-machine-completes-a-pending-join.md.\n -- The three tables reference only tables declared before them, so an apply that fails\n -- midway can drop them in reverse order. The two rules that would close a cycle are the\n -- writer's (ControlDatabase): a request's delete takes its outcome row with it, and a join\n -- recorded over a failure deletes the failure. An outcome row left behind is unreadable,\n -- since readers start from the request.\n table JoinRequest (\n Id text primary key, -- base64url sha256 of the invitation token (cadre-core pendingJoinId),\n -- so the token never reaches Revocation\n Invitation text, -- CadreNode.encodeInvitation\n Disclosure text, -- canonicalJson of the disclosure the requester gave\n RequestedAt integer, -- epoch ms\n ExpiresAt integer, -- epoch ms; no attempt starts at or after it\n StampId text unique,\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'JoinRequest' and R.StampId = new.StampId)\n ),\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'JoinRequest' and R.StampId = old.StampId and R.RowKey = old.Id)\n ),\n constraint NoUpdate check on update (false),\n constraint AuthorizedInsert check on insert (\n 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(\n digest('CadreControl.JoinRequest', 'add', party_id(), new.Id, new.Invitation, new.Disclosure, cast(new.RequestedAt as text), cast(new.ExpiresAt as text), new.StampId),\n context.Signature, A.Key, 'ed25519'))\n ),\n -- Reapable: the inviting party and the user hold the invitation too.\n constraint AuthorizedDelete check on delete (\n 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'))\n or exists (select 1 from committed.Revocation R where R.TableName = 'JoinRequest' and R.RowKey = old.Id and R.StampId = old.StampId)\n )\n ) with context (OwnerKey text null, Signature text null);\n\n -- The outcome of a JoinRequest that joined: the strand the formation returned and, for a\n -- closed strand, the single-use membership invitation it delivered. Keyed by the request's\n -- stamp, so it names one request incarnation and a replayed approval can only re-seat the\n -- row it approved, against the request it approved. A join is final: it may be recorded\n -- over a failure (whose row the writer deletes with it), and nothing is recorded over it.\n table JoinSuccess (\n RequestStampId text primary key,\n RecordedAt integer, -- epoch ms\n StrandId text,\n MembershipInvite text null, -- JSON {inviteKey, invitePrivateKey}, the StrandMembershipInvite; closed strands only\n constraint RequestExists check on insert (\n exists (select 1 from JoinRequest R where R.StampId = new.RequestStampId)\n ),\n constraint NoUpdate check on update (false),\n constraint AuthorizedInsert check on insert (\n 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(\n digest('CadreControl.JoinSuccess', 'add', party_id(), new.RequestStampId, cast(new.RecordedAt as text), new.StrandId, coalesce(new.MembershipInvite, '')),\n context.Signature, A.Key, 'ed25519'))\n ),\n -- Removed only with its request: the tombstone retiring the request's stamp (owner-signed,\n -- or already committed for a reap) authorizes this delete.\n constraint AuthorizedDelete check on delete (\n exists (select 1 from Revocation R where R.TableName = 'JoinRequest' and R.StampId = old.RequestStampId)\n )\n ) with context (OwnerKey text null, Signature text null);\n\n -- The outcome of a JoinRequest that failed for good. Keyed as JoinSuccess is.\n table JoinFailure (\n RequestStampId text primary key,\n RecordedAt integer, -- epoch ms\n Code text, -- a FormationRejectionCode, 'expired' or 'local'\n Reason text, -- human-readable\n constraint RequestExists check on insert (\n exists (select 1 from JoinRequest R where R.StampId = new.RequestStampId)\n ),\n -- A join is final: nothing records a failure over it.\n constraint NotJoined check on insert (\n not exists (select 1 from JoinSuccess S where S.RequestStampId = new.RequestStampId)\n ),\n constraint NoUpdate check on update (false),\n constraint AuthorizedInsert check on insert (\n 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(\n digest('CadreControl.JoinFailure', 'add', party_id(), new.RequestStampId, cast(new.RecordedAt as text), new.Code, new.Reason),\n context.Signature, A.Key, 'ed25519'))\n ),\n -- Removed with its request (JoinSuccess.AuthorizedDelete), or superseded by a join\n -- recorded in the same transaction.\n constraint AuthorizedDelete check on delete (\n exists (select 1 from Revocation R where R.TableName = 'JoinRequest' and R.StampId = old.RequestStampId)\n or exists (select 1 from JoinSuccess S where S.RequestStampId = old.RequestStampId)\n )\n ) with context (OwnerKey text null, Signature text null);\n\n -- A node of the cadre, carrying its self-published, freshness-stamped, self-signed address\n -- record (cadre-core PeerAddressRecord): a resolver re-verifies Sig against PublicKey,\n -- checks UpdatedAt and trust, then dials Multiaddr.\n table CadrePeer (\n PeerId text primary key,\n PublicKey text null, -- ed25519 (base64url) behind PeerId; null if not ed25519\n Multiaddr text, -- comma-joined current addrs (signaling / p2p-circuit first)\n UpdatedAt int null, -- epoch ms; strictly increases per self-update\n Sig text null, -- self-signature over the 'publish' digest; null until self-published\n StampId text unique,\n VouchOwner text null, -- the owner key that vouched this membership (== insert context.OwnerKey), or\n -- the issuer of the invitation that admitted it (CadreInvite.IssuerKey)\n VouchSig text null, -- that owner's 'vouch' signature (== insert context.Signature); null on an\n -- invitation-admitted row. A reader checks VouchOwner against its node-local\n -- trusted-owner anchor, not against this replicated table, which a self-owner\n -- can pollute.\n VouchUsage text null, -- the CadreInviteUsage.UsageStampId that admitted this row; null on an\n -- owner-vouched row. A row carries exactly one proof: a signature or a usage.\n Profile text null, -- the machine's own node profile (cadre-core NodeProfile): 'transaction' is an\n -- app (phone, browser), 'storage' an always-on node; null until it self-publishes.\n -- Self-declared and covered by Sig. No insert rule constrains it: an owner could\n -- only mislabel a machine it already has full authority over, and that machine's\n -- next self-publish corrects it.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'CadrePeer' and R.StampId = new.StampId)\n ),\n constraint KnownProfile check (new.Profile is null or new.Profile in ('transaction', 'storage')),\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'CadrePeer' and R.StampId = old.StampId and R.RowKey = old.PeerId)\n ),\n -- The owner vouches membership and the PublicKey<->PeerId binding (cadre-core derives\n -- PublicKey from PeerId) over (PeerId, StampId); the stored voucher must be the pair\n -- verified here. The same 'vouch' digest serves the owner branch of AuthorizedUpdate:\n -- both mean \"this owner vouches this membership row\".\n -- Or admitted by consent: a CadreInviteUsage row written in the same transaction names\n -- this exact row incarnation (PeerId, StampId and PublicKey), and the invitation it\n -- redeemed, read from committed.CadreInvite, was issued by the stored VouchOwner. The\n -- usage row carries the liveness conditions (unexpired, not withdrawn, uses left,\n -- issuer still an owner); this branch only requires that it exists. A reader verifies\n -- the chain row -> usage -> invitation against its anchor (cadre-core\n -- verifyInvitationAdmission), so the invitation row must outlive the rows it admitted.\n -- A removed device may redeem a still-live invitation again and come back: keeping a\n -- device out is removing its row AND withdrawing the invitation.\n constraint AuthorizedInsert check on insert (\n (\n 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'))\n and coalesce(new.VouchOwner, '') = context.OwnerKey\n and coalesce(new.VouchSig, '') = context.Signature\n and new.VouchUsage is null\n )\n or (\n new.VouchSig is null\n and new.VouchOwner is not null\n and new.VouchUsage is not null\n and exists (\n select 1 from CadreInviteUsage U\n where U.UsageStampId = new.VouchUsage\n and U.PeerId = new.PeerId\n and U.PeerStampId = new.StampId\n and U.PeerKey = new.PublicKey\n and exists (select 1 from committed.CadreInvite I where I.Key = U.InviteKey and I.IssuerKey = new.VouchOwner)\n )\n )\n ),\n -- The stored 'vouch' voucher never authorizes a delete; the 'remove' signature rides in\n -- context and is never stored. Or a reap (ValidationKey.AuthorizedDelete).\n constraint AuthorizedDelete check on delete (\n 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'))\n or exists (select 1 from committed.Revocation R where R.TableName = 'CadrePeer' and R.RowKey = old.PeerId and R.StampId = old.StampId)\n ),\n -- A peer re-publishes its own addrs, profile and freshness under its own key (cadre-core\n -- peer-record.ts); everything else is immutable and UpdatedAt must increase. Or an owner\n -- re-vouches the row over its current stamp, which also clears VouchUsage: the row then\n -- stands on the signature and its invitation is no longer consulted for it. The owner\n -- branch keeps what the machine itself declares (PublicKey, Multiaddr, Sig, Profile): the\n -- row's stored VouchSig is a valid re-vouch signature, so any machine holding the row can\n -- take this branch. NOTE: it may still bump UpdatedAt (reauthorizeCadrePeer's re-broadcast\n -- needs it), which on a self-published row leaves Sig unverifiable until the machine's\n -- next heartbeat re-signs past it; if that window ever matters, pin UpdatedAt here when\n -- old.Sig is not null. StampId never\n -- changes on update: an update that rotated it would leave the old stamp free and\n -- untombstoned, so retiring a stamp is delete plus tombstone. The proof columns are\n -- compared null-safe: VouchSig and VouchUsage are null on one of the two row kinds, and a\n -- bare `new.X = old.X` over a null would let a self-publish fill the column in.\n constraint AuthorizedUpdate check on update (\n (\n new.PeerId = old.PeerId\n and new.PublicKey = old.PublicKey\n and new.StampId = old.StampId\n and new.VouchOwner = old.VouchOwner\n and coalesce(new.VouchSig, '') = coalesce(old.VouchSig, '')\n and coalesce(new.VouchUsage, '') = coalesce(old.VouchUsage, '')\n and new.UpdatedAt > coalesce(old.UpdatedAt, 0)\n and verify(\n digest('CadreControl.CadrePeer', 'publish', party_id(), new.PeerId, new.Multiaddr, cast(new.UpdatedAt as text), coalesce(new.Profile, '')),\n new.Sig, new.PublicKey, 'ed25519')\n )\n or (\n new.StampId = old.StampId\n 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'))\n and coalesce(new.VouchOwner, '') = context.OwnerKey\n and coalesce(new.VouchSig, '') = context.Signature\n and new.VouchUsage is null\n and coalesce(new.PublicKey, '') = coalesce(old.PublicKey, '')\n and coalesce(new.Multiaddr, '') = coalesce(old.Multiaddr, '')\n and coalesce(new.Sig, '') = coalesce(old.Sig, '')\n and coalesce(new.Profile, '') = coalesce(old.Profile, '')\n )\n )\n ) with context (OwnerKey text null, Signature text);\n\n -- A mobile peer's platform push token, self-published so a server peer can push-wake a\n -- suspended app. A resolver re-verifies Sig against the CadrePeer.PublicKey for PeerId\n -- (cadre-core device-token.ts), checks freshness, then hands the token to the push sender.\n table DeviceToken (\n PeerId text primary key,\n Platform text, -- 'fcm' | 'apns'\n Token text, -- opaque platform device/registration token\n UpdatedAt int null, -- epoch ms; strictly increases per self-update\n Sig text null, -- self-signature over the 'publish' digest\n StampId text unique,\n -- A resurrected token has no freshness ceiling to retire it (resolveDeviceToken defaults\n -- maxAgeMs to infinity), so stamp retirement is what makes a clear stick.\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'DeviceToken' and R.StampId = new.StampId)\n ),\n constraint RevocationRecorded check on delete (\n exists (select 1 from Revocation R where R.TableName = 'DeviceToken' and R.StampId = old.StampId and R.RowKey = old.PeerId)\n ),\n -- The owner signs the whole row, nullable columns as '', so a replayed approval can only\n -- reproduce the row it approved (cadre-core peer-authorization.ts deviceTokenAddDigest).\n constraint AuthorizedInsert check on insert (\n 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(\n digest(\n 'CadreControl.DeviceToken', 'add', party_id(),\n new.PeerId,\n new.Platform,\n new.Token,\n coalesce(cast(new.UpdatedAt as text), ''),\n coalesce(new.Sig, ''),\n new.StampId\n ),\n context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n 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'))\n or exists (select 1 from committed.Revocation R where R.TableName = 'DeviceToken' and R.RowKey = old.PeerId and R.StampId = old.StampId)\n ),\n -- Self-update only: Platform and Token may change, PeerId and StampId may not, UpdatedAt\n -- must increase. No owner re-touch branch: one outside the monotonicity rule would let a\n -- captured approval roll UpdatedAt back; an owner correcting a row deletes and re-inserts.\n constraint AuthorizedUpdate check on update (\n new.PeerId = old.PeerId\n and new.StampId = old.StampId\n and new.UpdatedAt > coalesce(old.UpdatedAt, 0)\n and exists (select 1 from CadrePeer P where P.PeerId = new.PeerId and verify(\n digest('CadreControl.DeviceToken', 'publish', party_id(), new.PeerId, new.Platform, new.Token, cast(new.UpdatedAt as text)),\n new.Sig, P.PublicKey, 'ed25519'))\n )\n ) with context (OwnerKey text null, Signature text);\n\n -- An open invitation to form a strand with this party.\n table FormationInvite (\n Token text primary key, -- a random string\n sAppId text, -- the app of the strand to be formed\n ExpiresAt datetime null,\n TotalUses int null check (TotalUses >= 0),\n ValidationUrl text null, -- web hook sent the disclosure; a ValidationKey then signs off each redemption\n StrandId text null, -- bound invite: the host strand consent is recorded against;\n -- null: the responder provisions a fresh open strand per redemption\n StampId text unique,\n -- The owner signs the whole row, nullable columns as ''.\n constraint AuthorizedInsert check on insert (\n 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(\n digest(\n 'CadreControl.FormationInvite', 'add', party_id(),\n new.Token,\n new.sAppId,\n coalesce(cast(new.ExpiresAt as text), ''),\n coalesce(cast(new.TotalUses as text), ''),\n coalesce(new.ValidationUrl, ''),\n coalesce(new.StrandId, ''),\n new.StampId\n ),\n context.Signature, A.Key, 'ed25519'))\n ),\n constraint AuthorizedDelete check on delete (\n 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(\n digest(\n 'CadreControl.FormationInvite', 'remove', party_id(),\n old.Token,\n old.sAppId,\n coalesce(cast(old.ExpiresAt as text), ''),\n coalesce(cast(old.TotalUses as text), ''),\n coalesce(old.ValidationUrl, ''),\n coalesce(old.StrandId, ''),\n old.StampId\n ),\n context.Signature, A.Key, 'ed25519'))\n ),\n -- Insert and delete only, so the consent parameters cannot change under a signature.\n constraint Immutable check on update (false)\n ) with context (OwnerKey text, Signature text);\n\n -- Append-only record of formation invite redemptions, one row per redemption.\n table FormationUsage (\n Token text, -- the FormationInvite redeemed\n UsageStampId text, -- single-use nonce minted by the joining peer, signed into its 'consent' digest\n -- and the approver's 'vouch' digest. The primary key: this table never\n -- deletes, so the key alone makes a nonce permanent and there is no\n -- NotRevoked pair here. Two nodes that have not converged can each admit\n -- the same nonce: a duplicated audit row, never a join nobody approved.\n PeerKey text, -- the joining peer's ed25519 public key (base64url); its peer id derives from it\n PeerSig text, -- the joiner's signature over the 'consent' digest (PeerConsented)\n Disclosure text,\n StrandId text,\n StrandStampId text, -- the Strand.StampId this consent names: one strand row, not an id forever\n -- (Strand.AuthorizedInsert). Not unique: a bound invite's redeemers share\n -- a host strand.\n primary key (UsageStampId),\n constraint InsertOnly check on update, delete (false),\n -- The use cap counts the pre-transaction snapshot, so concurrent redeemers on separate\n -- nodes can over-admit by their number; both rows survive and removal is owner-gated. A\n -- strict per-token sequence was rejected: a lost race would silently drop a consented\n -- join. Two usage rows for one token in one transaction read the same count; no writer\n -- does that.\n -- A ValidationUrl invite needs a sign-off verified against a STORED ValidationKey row;\n -- context.ValidationKey only selects which row, so a redeemer cannot approve itself with\n -- a throwaway key. The sign-off covers (Token, UsageStampId, StrandId, PeerKey,\n -- Disclosure), so it buys exactly one row; StrandStampId is not bound because the\n -- unbound path mints it inside the redeeming transaction. Removing the key later does\n -- not revisit rows it approved.\n -- A bound invite may only name its own host strand. An unbound invite may name any\n -- existing strand, which burns a use and forecloses that id's consent-seating: harmless.\n -- Neither digest of this table binds party_id(), alone in this schema: the joiner signs\n -- its consent before the responder's party id reaches it (it arrives in the result\n -- frame) and with a key made fresh for this one formation, and the outside approver\n -- behind ValidationUrl is sent only the five fields below. Both digests bind the\n -- invitation Token, a random secret seated in one party's FormationInvite table, so\n -- replaying either in another party needs that party's owner to seat the same token in\n -- its own database, and the only database harmed would be its own.\n constraint Authorized check on insert (\n exists (\n select 1 from FormationInvite FI\n where FI.Token = new.Token\n and (FI.TotalUses is null or FI.TotalUses > (select count(1) from committed.FormationUsage U where U.Token = new.Token))\n and (FI.ExpiresAt is null or FI.ExpiresAt > context.Now)\n and (FI.ValidationUrl is null or exists (\n select 1 from ValidationKey VK\n where VK.Key = context.ValidationKey\n and verify(digest('CadreControl.FormationUsage', 'vouch', new.Token, new.UsageStampId, new.StrandId, new.PeerKey, new.Disclosure), context.ValidationSignature, VK.Key, 'ed25519')))\n and (FI.StrandId is null or FI.StrandId = new.StrandId)\n )\n ),\n -- A usage row may only name a strand row that exists, so a consent record cannot be held\n -- in reserve to re-seat an id after its removal.\n constraint StrandExists check (exists (select 1 from Strand S where S.Id = new.StrandId and S.StampId = new.StrandStampId)),\n -- The joiner proves it agreed. PeerKey is its own key, so there is nothing for a writer to\n -- substitute; stored on the row so any reader can re-check it (verifyFormationConsent).\n -- StrandId and the party id are not signed: the joiner cannot know them when it signs\n -- (Authorized, above).\n constraint PeerConsented check on insert (\n verify(digest('CadreControl.FormationUsage', 'consent',\n new.Token, new.UsageStampId, new.PeerKey, new.Disclosure),\n new.PeerSig, new.PeerKey, 'ed25519')\n )\n ) with context (Now datetime, ValidationKey text null, ValidationSignature text null);\n\n -- Serves the per-token reads (the cap count above; cadre-core's countFormationUsage,\n -- isTokenUsed and hasOutstandingFormationInvite) on an append-only table. Its cross-machine\n -- convergence is guarded by the integration scenario strand-formation-concurrent-redemption.\n index FormationUsageByToken on FormationUsage (Token);\n\n -- An owner-signed invitation to join this cadre, redeemable on the owner's behalf by any\n -- member machine (ControlDatabase.redeemCadreInvite). The invitation is a keypair, not a\n -- bearer token: the row holds the public half and the holder proves possession by signing\n -- with the private half (CadreInviteUsage.InvitePossessed), so the member that redeems it\n -- can verify but never redeem it for itself. Rows are never deleted: a device admitted\n -- through one carries no owner signature of its own, and its membership is the chain\n -- invitation -> usage -> peer row, verified at read time, so the row must outlive every\n -- device it admitted. Withdrawing an invitation is an owner-signed Revocation tombstone\n -- over the row's stamp with the row kept (Revocation.RowIsGone); liveness is read as no\n -- tombstone, unexpired, uses left, issuer still an owner (CadreInviteUsage.Authorized).\n -- NOTE: expired and withdrawn rows accumulate for the life of the party; the same tripwire\n -- as hasOutstandingFormationInvite applies (ControlDatabase.hasLiveCadreInvite). An owner\n -- retires a device's dependency on its invitation by re-vouching the row (the owner branch\n -- of CadrePeer.AuthorizedUpdate).\n table CadreInvite (\n Key text primary key, -- the invitation's ed25519 public key (base64url)\n PeerId text null, -- the device this invitation is for; null: whoever redeems first designates it\n GrantsOwner integer check (GrantsOwner = 0 or GrantsOwner = 1), -- 1: redemption also seats an OwnerKey row\n ExpiresAt datetime null,\n TotalUses int null check (TotalUses >= 0),\n IssuerKey text, -- the owner that signed the row (== insert context.OwnerKey). A reader checks it\n -- against its node-local anchor, never against the replicated OwnerKey table.\n IssuerSig text, -- that owner's 'add' signature (== insert context.Signature), stored so any reader\n -- can re-verify the row from the holder's copy or the replicated one\n StampId text unique,\n -- A withdrawn invitation cannot be re-seated from the signed copy its holder keeps, on\n -- any node that holds the tombstone (schema header for the node that does not).\n constraint NotRevoked check on insert (\n not exists (select 1 from Revocation R where R.TableName = 'CadreInvite' and R.StampId = new.StampId)\n ),\n -- The owner signs the whole row, nullable columns as '' (cadre-core cadreInviteRowFields),\n -- and the stored issuer pair must be the pair verified here, as CadrePeer pins its voucher.\n constraint AuthorizedInsert check on insert (\n 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(\n digest(\n 'CadreControl.CadreInvite', 'add', party_id(),\n new.Key,\n coalesce(new.PeerId, ''),\n cast(new.GrantsOwner as text),\n coalesce(cast(new.ExpiresAt as text), ''),\n coalesce(cast(new.TotalUses as text), ''),\n new.StampId\n ),\n context.Signature, A.Key, 'ed25519'))\n and coalesce(new.IssuerKey, '') = context.OwnerKey\n and coalesce(new.IssuerSig, '') = context.Signature\n ),\n constraint NoUpdate check on update (false),\n -- Never deleted (table comment). Withdrawal is the tombstone alone.\n constraint NoDelete check on delete (false)\n ) with context (OwnerKey text, Signature text);\n\n -- Append-only record of cadre invitation redemptions, one row per redemption: the proof a\n -- CadrePeer row (and, for an owner-granting invitation, an OwnerKey row) was admitted by\n -- consent rather than by an owner signature.\n table CadreInviteUsage (\n UsageStampId text primary key, -- nonce minted by the redeeming device and signed into both signatures\n -- below. The primary key: this table never deletes, so the key alone\n -- makes a nonce permanent and there is no NotRevoked pair here. Two nodes\n -- that have not converged can each admit the same nonce (FormationUsage).\n InviteKey text, -- the CadreInvite redeemed\n PeerId text, -- the redeeming device: the identity multihash of PeerKey. The writer\n -- asserts the pair and a reader re-derives it (verifyInvitationAdmission);\n -- the schema cannot unwrap a multihash.\n PeerKey text, -- the redeeming device's ed25519 public key (base64url)\n PeerStampId text, -- the CadrePeer.StampId this usage seats: one row incarnation, not a peer id\n -- forever. Minted by the writer inside the redeeming transaction and not\n -- signed (FormationUsage.StrandStampId).\n OwnerStampId text null, -- the OwnerKey.StampId this usage seats when the invitation grants ownership\n InviteSig text, -- by the invitation's private key over the 'redeem' digest: proof of possession\n PeerSig text, -- by PeerKey over the 'consent' digest: the device agreed to join\n constraint InsertOnly check on update, delete (false),\n -- The invitation is read from the pre-transaction snapshot, so an invitation cannot be\n -- seated and redeemed in one transaction (the OwnerKey consent branch rests on that).\n -- NOTE: accepted tradeoff \u2014 the use cap counts committed usage, so two redeemers racing\n -- for a single-use invitation on different machines may both be admitted until merge,\n -- and after merge both rows stand (FormationUsage.Authorized), for owner grants too.\n -- Serializing would need cross-machine coordination the control plane does not have;\n -- the mitigations are the defaults the redemption protocol sets (untargeted owner\n -- invitations single-use with a short expiry), the targeted form for owner grants, and\n -- the owner seeing the extra owner and removing it. Revisit if the control plane gains\n -- a cross-machine sequencer. An issuer removed since issuing takes its outstanding\n -- invitations with it (the committed.OwnerKey clause, which a tombstone alone\n -- satisfies); devices it already admitted stay members.\n constraint Authorized check on insert (\n exists (\n select 1 from committed.CadreInvite I\n where I.Key = new.InviteKey\n and not exists (select 1 from Revocation R where R.TableName = 'CadreInvite' and R.StampId = I.StampId)\n and (I.ExpiresAt is null or I.ExpiresAt > context.Now)\n and (I.TotalUses is null or I.TotalUses > (select count(1) from committed.CadreInviteUsage U where U.InviteKey = new.InviteKey))\n and (I.PeerId is null or I.PeerId = new.PeerId)\n 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))\n )\n ),\n -- Verified against the invitation key itself: the member writing the row can check this\n -- signature but, holding only the public half, cannot produce it.\n constraint InvitePossessed check on insert (\n verify(digest('CadreControl.CadreInviteUsage', 'redeem', party_id(), new.InviteKey, new.UsageStampId, new.PeerKey),\n new.InviteSig, new.InviteKey, 'ed25519')\n ),\n -- The device proves it agreed (FormationUsage.PeerConsented).\n constraint PeerConsented check on insert (\n verify(digest('CadreControl.CadreInviteUsage', 'consent', party_id(), new.InviteKey, new.UsageStampId, new.PeerKey),\n new.PeerSig, new.PeerKey, 'ed25519')\n ),\n -- Deferred, so the same-transaction peer insert counts: a usage row can never be held in\n -- reserve to seat a row later (FormationUsage.StrandExists). PeerKey must be the key the\n -- peer row stores: a redemption that only completes an already-admitted device with its\n -- OwnerKey row (no peer insert to pin it) cannot name a key other than that device's.\n constraint PeerExists check (exists (\n select 1 from CadrePeer P where P.PeerId = new.PeerId and P.StampId = new.PeerStampId and P.PublicKey = new.PeerKey\n )),\n constraint OwnerExists check (\n new.OwnerStampId is null\n or exists (select 1 from OwnerKey K where K.Key = new.PeerKey and K.StampId = new.OwnerStampId)\n )\n ) with context (Now datetime);\n\n -- Serves the cap count above and the liveness reads (cadre-core countCadreInviteUsage,\n -- hasLiveCadreInvite) on an append-only table, as FormationUsageByToken does.\n index CadreInviteUsageByInvite on CadreInviteUsage (InviteKey);\n\n -- Append-only retirement record for the stamps of removed rows of every guarded table, with\n -- the removed row's key. Every append is owner-signed, so the growth surface is the owner\n -- keys. One singleton marker row, ('Revocation', 'ledger', 'opened'), retires nothing: an\n -- owner's connected reconcile pass files it (ControlDatabase.openRevocationLedger) so this\n -- table is never a never-written block, which the storage layer would consult the cohort\n -- for on every guarded insert and membership lookup. Readers filter on their own guarded\n -- TableName, and queryRevocations skips it. A 'CadreInvite' row withdraws an invitation\n -- whose row stays (CadreInvite table comment).\n table Revocation (\n TableName text, -- 'OwnerKey' | 'ValidationKey' | 'Strand' | 'StrandPartyKey' | 'JoinedStrand' |\n -- 'JoinRequest' | 'CadrePeer' | 'DeviceToken' | 'CadreInvite', or 'Revocation'\n -- for the marker\n RowKey text, -- primary key of the removed row\n StampId text, -- the retired stamp\n ReissuedAt integer default 0, -- bumped by an owner-signed re-issue so a tombstone committed while the\n -- node was alone can be re-written and so re-broadcast; nothing reads it\n SignerKey text null, -- the owner that filed the tombstone (== insert context.OwnerKey)\n SignerSig text null, -- that owner's 'remove' signature (== insert context.Signature). A node that\n -- received the row by replication re-verifies the pair and judges SignerKey\n -- against its node-local trusted-owner anchor (cadre-core\n -- verifyRevocationSigner), not against this replicated table.\n -- Keyed on the stamp: one row key may carry several tombstones over its life.\n primary key (TableName, StampId),\n -- Retirement is permanent.\n constraint NoDelete check on delete (false),\n -- Pinned at 0 so an owner cannot seat a tombstone at a counter its own re-issues cannot pass.\n constraint FreshTombstone check on insert (new.ReissuedAt = 0),\n -- A re-issue moves nothing but the counter, and only upward. The signer pair stays the\n -- filing owner's; the re-issuing owner's signature rides in context only.\n constraint ReissueOnly check on update (\n new.TableName = old.TableName and new.RowKey = old.RowKey\n and new.StampId = old.StampId and new.ReissuedAt > old.ReissuedAt\n and coalesce(new.SignerKey, '') = coalesce(old.SignerKey, '')\n and coalesce(new.SignerSig, '') = coalesce(old.SignerSig, '')\n ),\n -- A stamp is retired only once its row is gone (deferred, so the same-transaction delete\n -- counts). Keyed on the stamp, not RowKey: a node that converges on a re-admission before\n -- the earlier removal's tombstone must still accept that tombstone. Retiring a stamp that\n -- never existed is harmless: stamps carry 128 random bits (generateStampId). For\n -- 'CadreInvite' there is no row-gone test: a tombstone there is a withdrawal, and the\n -- row stays (CadreInvite table comment). The last branch admits the marker row and\n -- nothing else under 'Revocation'.\n constraint RowIsGone check on insert (\n (new.TableName = 'OwnerKey' and not exists (select 1 from OwnerKey K where K.StampId = new.StampId))\n or (new.TableName = 'CadrePeer' and not exists (select 1 from CadrePeer P where P.StampId = new.StampId))\n or (new.TableName = 'ValidationKey' and not exists (select 1 from ValidationKey V where V.StampId = new.StampId))\n or (new.TableName = 'Strand' and not exists (select 1 from Strand S where S.StampId = new.StampId))\n or (new.TableName = 'StrandPartyKey' and not exists (select 1 from StrandPartyKey K where K.StampId = new.StampId))\n or (new.TableName = 'JoinedStrand' and not exists (select 1 from JoinedStrand J where J.StampId = new.StampId))\n or (new.TableName = 'JoinRequest' and not exists (select 1 from JoinRequest J where J.StampId = new.StampId))\n or (new.TableName = 'DeviceToken' and not exists (select 1 from DeviceToken D where D.StampId = new.StampId))\n or (new.TableName = 'CadreInvite')\n or (new.TableName = 'Revocation' and new.RowKey = 'ledger' and new.StampId = 'opened')\n ),\n -- Owner-signed over the whole row under its own domain tag, so the delete's 'remove'\n -- signature filed in the same transaction never doubles as the tombstone's. Ungated, any\n -- writer could evict a peer party-wide and block its re-admission. RowKey is not checked\n -- against the retired row here (that would reject a tombstone re-issued later, or filed on\n -- a node that never held the row); each guarded table's RevocationRecorded binds it\n -- instead. Reads live OwnerKey like the sibling tables. The marker is signed under this\n -- rule too, over ('Revocation', 'ledger', 'opened'). The stored signer pair must be the\n -- pair verified here.\n constraint Authorized check on insert (\n 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'))\n and coalesce(new.SignerKey, '') = context.OwnerKey\n and coalesce(new.SignerSig, '') = context.Signature\n ),\n -- Distinct 'reissue' tag, binding ReissuedAt, so neither approval replays as the other.\n constraint AuthorizedReissue check on update (\n exists (select 1 from OwnerKey A where A.Key = context.OwnerKey\n and not exists (select 1 from Revocation R where R.TableName = 'OwnerKey' and R.StampId = A.StampId)\n and verify(digest('CadreControl.Revocation', 'reissue', party_id(),\n new.TableName, new.RowKey, new.StampId, cast(new.ReissuedAt as text)),\n context.Signature, A.Key, 'ed25519'))\n )\n ) with context (OwnerKey text, Signature text);\n}\n\napply schema CadreControl;\n";
|