@serfab/cadre-core 1.22.0 → 1.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (314) hide show
  1. package/README.md +216 -294
  2. package/dist/arachnode-stub.d.ts +12 -4
  3. package/dist/arachnode-stub.js +15 -8
  4. package/dist/arachnode-stub.js.map +1 -1
  5. package/dist/cadre-invite-protocol.js +5 -4
  6. package/dist/cadre-invite-protocol.js.map +1 -1
  7. package/dist/cadre-node.d.ts +159 -53
  8. package/dist/cadre-node.js +276 -89
  9. package/dist/cadre-node.js.map +1 -1
  10. package/dist/control-authorization.d.ts +14 -2
  11. package/dist/control-authorization.js +8 -3
  12. package/dist/control-authorization.js.map +1 -1
  13. package/dist/control-cohort.d.ts +27 -13
  14. package/dist/control-cohort.js +21 -14
  15. package/dist/control-cohort.js.map +1 -1
  16. package/dist/control-database.d.ts +18 -16
  17. package/dist/control-database.js +57 -22
  18. package/dist/control-database.js.map +1 -1
  19. package/dist/control-protocol-guard.d.ts +1 -1
  20. package/dist/control-protocol-guard.js +7 -3
  21. package/dist/control-protocol-guard.js.map +1 -1
  22. package/dist/control-read-retry.d.ts +49 -11
  23. package/dist/control-read-retry.js +56 -15
  24. package/dist/control-read-retry.js.map +1 -1
  25. package/dist/control-retry.d.ts +32 -3
  26. package/dist/control-retry.js +35 -4
  27. package/dist/control-retry.js.map +1 -1
  28. package/dist/control-schema-version.d.ts +5 -5
  29. package/dist/control-schema-version.js +5 -5
  30. package/dist/control-schema-version.js.map +1 -1
  31. package/dist/control-schema.d.ts +5 -5
  32. package/dist/control-schema.js +1032 -1011
  33. package/dist/control-schema.js.map +1 -1
  34. package/dist/control-write-retry.d.ts +54 -65
  35. package/dist/control-write-retry.js +134 -158
  36. package/dist/control-write-retry.js.map +1 -1
  37. package/dist/delegate-admission.d.ts +1 -1
  38. package/dist/delegate-admission.js +1 -1
  39. package/dist/edge-node/config.d.ts +4 -3
  40. package/dist/edge-node/config.js +11 -9
  41. package/dist/edge-node/config.js.map +1 -1
  42. package/dist/edge-node/dissolve.d.ts +4 -4
  43. package/dist/edge-node/dissolve.js +4 -4
  44. package/dist/edge-node/edge-join.d.ts +1 -1
  45. package/dist/edge-node/edge-join.js +1 -1
  46. package/dist/edge-node/edge-node.js +2 -2
  47. package/dist/edge-node/edge-node.js.map +1 -1
  48. package/dist/edge-node/index.d.ts +1 -0
  49. package/dist/edge-node/index.js +1 -0
  50. package/dist/edge-node/index.js.map +1 -1
  51. package/dist/edge-node/join-credential.d.ts +1 -1
  52. package/dist/edge-node/join-credential.js +1 -1
  53. package/dist/edge-node/lazy-raw-storage.js +12 -0
  54. package/dist/edge-node/lazy-raw-storage.js.map +1 -1
  55. package/dist/edge-node/listen-addrs.d.ts +21 -0
  56. package/dist/edge-node/listen-addrs.js +25 -0
  57. package/dist/edge-node/listen-addrs.js.map +1 -0
  58. package/dist/edge-node/owner-grant.d.ts +1 -1
  59. package/dist/edge-node/owner-grant.js +1 -1
  60. package/dist/edge-node/platform.d.ts +5 -4
  61. package/dist/edge-node/platform.js.map +1 -1
  62. package/dist/edge-node/strand-move.d.ts +1 -1
  63. package/dist/edge-node/strand-move.js +1 -1
  64. package/dist/edge-node/strands.js +27 -11
  65. package/dist/edge-node/strands.js.map +1 -1
  66. package/dist/index.d.ts +7 -5
  67. package/dist/index.js +18 -7
  68. package/dist/index.js.map +1 -1
  69. package/dist/invitation-bootstrap.d.ts +28 -5
  70. package/dist/invitation-bootstrap.js +41 -8
  71. package/dist/invitation-bootstrap.js.map +1 -1
  72. package/dist/link-budget.d.ts +53 -4
  73. package/dist/link-budget.js +58 -5
  74. package/dist/link-budget.js.map +1 -1
  75. package/dist/machine-removal.d.ts +2 -2
  76. package/dist/machine-removal.js +4 -3
  77. package/dist/machine-removal.js.map +1 -1
  78. package/dist/membership-connection-gater.d.ts +2 -2
  79. package/dist/membership-connection-gater.js +2 -2
  80. package/dist/membership-view.d.ts +2 -2
  81. package/dist/membership-view.js +6 -3
  82. package/dist/membership-view.js.map +1 -1
  83. package/dist/node-claim-payload.d.ts +15 -7
  84. package/dist/node-claim-payload.js +25 -9
  85. package/dist/node-claim-payload.js.map +1 -1
  86. package/dist/node-class.d.ts +36 -0
  87. package/dist/node-class.js +26 -0
  88. package/dist/node-class.js.map +1 -0
  89. package/dist/node-default-transports.d.ts +50 -3
  90. package/dist/node-default-transports.js +48 -3
  91. package/dist/node-default-transports.js.map +1 -1
  92. package/dist/node-roles.d.ts +118 -0
  93. package/dist/node-roles.js +142 -0
  94. package/dist/node-roles.js.map +1 -0
  95. package/dist/node-transports.d.ts +6 -2
  96. package/dist/node-transports.js +39 -7
  97. package/dist/node-transports.js.map +1 -1
  98. package/dist/owner-anchor-sync.js +1 -1
  99. package/dist/owner-key-export.js +1 -1
  100. package/dist/owner-key-flows.d.ts +1 -1
  101. package/dist/owner-key-store.js +1 -1
  102. package/dist/owner-signer.js +1 -1
  103. package/dist/peer-authorization.d.ts +3 -1
  104. package/dist/peer-authorization.js +3 -1
  105. package/dist/peer-authorization.js.map +1 -1
  106. package/dist/peer-dial.d.ts +74 -10
  107. package/dist/peer-dial.js +89 -17
  108. package/dist/peer-dial.js.map +1 -1
  109. package/dist/peer-join-backfill.js +4 -4
  110. package/dist/peer-join-backfill.js.map +1 -1
  111. package/dist/peer-record.d.ts +34 -9
  112. package/dist/peer-record.js +66 -13
  113. package/dist/peer-record.js.map +1 -1
  114. package/dist/pending-join-runner.d.ts +1 -1
  115. package/dist/pending-join-runner.js +1 -1
  116. package/dist/provider/client.d.ts +6 -5
  117. package/dist/provider/client.js +3 -3
  118. package/dist/provider/client.js.map +1 -1
  119. package/dist/provider/descriptor.d.ts +1 -1
  120. package/dist/provider/descriptor.js +1 -1
  121. package/dist/provider/oauth.d.ts +1 -1
  122. package/dist/provider/oauth.js +1 -1
  123. package/dist/provider/rent-node.d.ts +4 -3
  124. package/dist/provider/rent-node.js +3 -3
  125. package/dist/provider/rent-node.js.map +1 -1
  126. package/dist/relay-addrs.d.ts +62 -7
  127. package/dist/relay-addrs.js +74 -11
  128. package/dist/relay-addrs.js.map +1 -1
  129. package/dist/relay-reservation.d.ts +1 -1
  130. package/dist/relay-reservation.js +1 -1
  131. package/dist/relay-server.d.ts +6 -5
  132. package/dist/relay-server.js +5 -5
  133. package/dist/relay-server.js.map +1 -1
  134. package/dist/schema-verification.d.ts +13 -10
  135. package/dist/schema-verification.js +32 -24
  136. package/dist/schema-verification.js.map +1 -1
  137. package/dist/sealed-party-key.js +1 -1
  138. package/dist/seed-bootstrap.d.ts +4 -3
  139. package/dist/seed-bootstrap.js +6 -7
  140. package/dist/seed-bootstrap.js.map +1 -1
  141. package/dist/strand-addr-protocol.d.ts +8 -6
  142. package/dist/strand-addr-protocol.js +12 -10
  143. package/dist/strand-addr-protocol.js.map +1 -1
  144. package/dist/strand-app-schema-report.d.ts +16 -2
  145. package/dist/strand-app-schema-report.js +15 -0
  146. package/dist/strand-app-schema-report.js.map +1 -1
  147. package/dist/strand-cohort.d.ts +1 -4
  148. package/dist/strand-cohort.js.map +1 -1
  149. package/dist/strand-commit-durability.d.ts +1 -1
  150. package/dist/strand-database.d.ts +13 -6
  151. package/dist/strand-database.js +17 -9
  152. package/dist/strand-database.js.map +1 -1
  153. package/dist/strand-first-sync-gate.d.ts +3 -2
  154. package/dist/strand-first-sync-gate.js +3 -2
  155. package/dist/strand-first-sync-gate.js.map +1 -1
  156. package/dist/strand-formation-deadlines.d.ts +2 -2
  157. package/dist/strand-formation-deadlines.js +2 -2
  158. package/dist/strand-formation-protocol.d.ts +1 -1
  159. package/dist/strand-formation-protocol.js +51 -16
  160. package/dist/strand-formation-protocol.js.map +1 -1
  161. package/dist/strand-instance-manager.d.ts +134 -42
  162. package/dist/strand-instance-manager.js +331 -76
  163. package/dist/strand-instance-manager.js.map +1 -1
  164. package/dist/strand-membership-reconciler.d.ts +8 -3
  165. package/dist/strand-membership-reconciler.js +8 -3
  166. package/dist/strand-membership-reconciler.js.map +1 -1
  167. package/dist/strand-membership-writer.d.ts +2 -2
  168. package/dist/strand-membership-writer.js +41 -39
  169. package/dist/strand-membership-writer.js.map +1 -1
  170. package/dist/strand-move.js +1 -1
  171. package/dist/strand-network-config.d.ts +15 -5
  172. package/dist/strand-network-config.js +7 -6
  173. package/dist/strand-network-config.js.map +1 -1
  174. package/dist/strand-party-key-rotation.d.ts +7 -3
  175. package/dist/strand-party-key-rotation.js +7 -3
  176. package/dist/strand-party-key-rotation.js.map +1 -1
  177. package/dist/strand-party-machines.d.ts +19 -8
  178. package/dist/strand-party-machines.js +26 -11
  179. package/dist/strand-party-machines.js.map +1 -1
  180. package/dist/strand-party-peers.d.ts +36 -14
  181. package/dist/strand-party-peers.js +24 -15
  182. package/dist/strand-party-peers.js.map +1 -1
  183. package/dist/strand-peer-redial.d.ts +1 -1
  184. package/dist/strand-peer-redial.js +1 -1
  185. package/dist/strand-reactivity.d.ts +20 -17
  186. package/dist/strand-reactivity.js +31 -18
  187. package/dist/strand-reactivity.js.map +1 -1
  188. package/dist/strand-revocation-enforcer.d.ts +3 -3
  189. package/dist/strand-revocation-enforcer.js +3 -3
  190. package/dist/strand-wake-protocol.d.ts +19 -7
  191. package/dist/strand-wake-protocol.js +22 -10
  192. package/dist/strand-wake-protocol.js.map +1 -1
  193. package/dist/strand-watcher.d.ts +1 -1
  194. package/dist/strand-watcher.js +1 -1
  195. package/dist/table-change-watch.js +1 -1
  196. package/dist/types.d.ts +127 -57
  197. package/dist/types.js.map +1 -1
  198. package/dist/webrtc-upgrade.d.ts +254 -0
  199. package/dist/webrtc-upgrade.js +355 -0
  200. package/dist/webrtc-upgrade.js.map +1 -0
  201. package/package.json +9 -9
  202. package/src/announce-addrs.ts +93 -93
  203. package/src/arachnode-stub.ts +18 -10
  204. package/src/bootstrap-peer-store-file.ts +44 -44
  205. package/src/bootstrap-peer-store.ts +214 -214
  206. package/src/cadre-invite-protocol.ts +741 -740
  207. package/src/cadre-node.ts +12462 -12252
  208. package/src/claim-proof.ts +147 -147
  209. package/src/control-authorization.ts +290 -276
  210. package/src/control-cohort.ts +223 -204
  211. package/src/control-database.ts +72 -28
  212. package/src/control-formation-recorder.ts +359 -359
  213. package/src/control-protocol-guard.ts +370 -366
  214. package/src/control-read-retry.ts +222 -180
  215. package/src/control-retry.ts +36 -4
  216. package/src/control-schema-version.ts +301 -301
  217. package/src/control-schema.ts +1108 -1087
  218. package/src/control-write-retry.ts +639 -669
  219. package/src/delegate-admission.ts +351 -351
  220. package/src/describe-thrown.ts +60 -60
  221. package/src/ed25519-key.ts +185 -185
  222. package/src/edge-node/config.ts +13 -10
  223. package/src/edge-node/dissolve.ts +252 -252
  224. package/src/edge-node/edge-join.ts +320 -320
  225. package/src/edge-node/edge-node.ts +1095 -1095
  226. package/src/edge-node/index.ts +60 -59
  227. package/src/edge-node/join-credential.ts +16 -16
  228. package/src/edge-node/lazy-raw-storage.ts +194 -178
  229. package/src/edge-node/listen-addrs.ts +26 -0
  230. package/src/edge-node/node-local.ts +84 -84
  231. package/src/edge-node/options.ts +195 -195
  232. package/src/edge-node/owner-grant.ts +63 -63
  233. package/src/edge-node/platform.ts +5 -4
  234. package/src/edge-node/strand-move.ts +266 -266
  235. package/src/edge-node/strands.ts +27 -12
  236. package/src/enrolled-machine-store-file.ts +43 -43
  237. package/src/enrolled-machine-store.ts +280 -280
  238. package/src/fetch-impl.ts +23 -23
  239. package/src/file-durable-slot.ts +64 -64
  240. package/src/file-safe-name.ts +32 -32
  241. package/src/formation-approval.ts +604 -604
  242. package/src/formation-token.ts +63 -63
  243. package/src/fs-atomic.ts +92 -92
  244. package/src/index.ts +987 -957
  245. package/src/invitation-bootstrap.ts +152 -118
  246. package/src/joined-strand-store.ts +553 -553
  247. package/src/key-store-file.ts +142 -142
  248. package/src/link-budget.ts +61 -5
  249. package/src/machine-removal.ts +211 -210
  250. package/src/member-redemption.ts +643 -643
  251. package/src/membership-connection-gater.ts +650 -650
  252. package/src/membership-view.ts +147 -144
  253. package/src/node-claim-payload.ts +34 -12
  254. package/src/node-class.ts +47 -0
  255. package/src/node-default-transports.ts +65 -3
  256. package/src/node-roles.ts +220 -0
  257. package/src/node-transports.ts +86 -49
  258. package/src/owner-anchor-sync.ts +172 -172
  259. package/src/owner-grant-protocol.ts +547 -547
  260. package/src/owner-key-export.ts +348 -348
  261. package/src/owner-key-flows.ts +109 -109
  262. package/src/owner-key-store.ts +1 -1
  263. package/src/owner-keys.ts +179 -179
  264. package/src/owner-signer.ts +92 -92
  265. package/src/peer-addr-book.ts +252 -252
  266. package/src/peer-authorization.ts +584 -582
  267. package/src/peer-dial.ts +698 -605
  268. package/src/peer-join-backfill.ts +961 -961
  269. package/src/peer-record.ts +71 -16
  270. package/src/pending-join-runner.ts +798 -798
  271. package/src/primary-lan-address.ts +47 -47
  272. package/src/provider/client.ts +327 -326
  273. package/src/provider/descriptor.ts +129 -129
  274. package/src/provider/index.ts +59 -59
  275. package/src/provider/oauth.ts +285 -285
  276. package/src/provider/rent-node.ts +276 -275
  277. package/src/relay-addrs.ts +90 -12
  278. package/src/relay-reservation.ts +1 -1
  279. package/src/relay-server.ts +99 -98
  280. package/src/schema-verification.ts +38 -23
  281. package/src/sealed-party-key.ts +190 -190
  282. package/src/seed-bootstrap.ts +8 -11
  283. package/src/seed-trust-policy.ts +353 -353
  284. package/src/self-address-update.ts +19 -19
  285. package/src/strand-addr-protocol.ts +17 -14
  286. package/src/strand-app-schema-report.ts +147 -122
  287. package/src/strand-cohort.ts +1 -5
  288. package/src/strand-commit-durability.ts +165 -165
  289. package/src/strand-database.ts +522 -510
  290. package/src/strand-first-sync-gate.ts +3 -2
  291. package/src/strand-formation-deadlines.ts +227 -227
  292. package/src/strand-formation-manager.ts +731 -731
  293. package/src/strand-formation-protocol.ts +1174 -1138
  294. package/src/strand-fret-addrs.ts +179 -179
  295. package/src/strand-instance-manager.ts +381 -85
  296. package/src/strand-membership-reconciler.ts +1315 -1310
  297. package/src/strand-membership-writer.ts +2152 -2150
  298. package/src/strand-move.ts +1 -1
  299. package/src/strand-network-config.ts +16 -6
  300. package/src/strand-offline.ts +178 -178
  301. package/src/strand-party-key-rotation.ts +440 -436
  302. package/src/strand-party-machines.ts +308 -293
  303. package/src/strand-party-peers.ts +151 -129
  304. package/src/strand-peer-redial.ts +1 -1
  305. package/src/strand-reactivity.ts +36 -19
  306. package/src/strand-revocation-enforcer.ts +758 -758
  307. package/src/strand-wake-protocol.ts +406 -394
  308. package/src/strand-watcher.ts +1 -1
  309. package/src/table-change-watch.ts +285 -285
  310. package/src/timed-step.ts +28 -28
  311. package/src/timeout-scheduler.ts +29 -29
  312. package/src/trusted-owner-store.ts +242 -242
  313. package/src/types.ts +3182 -3112
  314. package/src/webrtc-upgrade.ts +439 -0
@@ -1,582 +1,584 @@
1
- import debug from 'debug';
2
- import { digest, verify } from '@optimystic/quereus-plugin-crypto';
3
- import { controlAuthorizationFields, unboundAuthorizationFields, cadreInviteRowFields, ownerGrantRowFields, strandPeerRowFields } from './control-authorization.js';
4
- import type { BoundControlDomain, CadreInviteSignedFields, ControlAction, OwnerGrantSignedFields, RevocableTable, StrandPeerSignedFields, UnboundControlDomain } from './control-authorization.js';
5
- import { ed25519PublicKeyB64FromPeerId } from './ed25519-key.js';
6
- import type { CadreInviteRow, CadreInviteUsageRow, CadrePeerVoucherFields, OwnerGrantRow, OwnerGrantUsageRow, OwnerKeyRow, RevocationRow, StrandPeerRow } from './types.js';
7
-
8
- const log = debug('sereus:cadre:peer-authorization');
9
-
10
- /**
11
- * base64url SHA-256 digest over the shared domain-tagged, party-bound field vector (see
12
- * control-authorization.ts). The base64url twin of
13
- * control-database.ts:buildAuthorizationMessage (which returns the same digest as raw
14
- * bytes): sign either encoding with input encoding to match and the signed bytes agree.
15
- * `partyId` is the party the verifier is configured for: a stored proof minted for
16
- * another party fails here exactly as it fails the schema's `party_id()`-bound check.
17
- */
18
- function taggedDigest(domain: BoundControlDomain, action: ControlAction, partyId: string, rowFields: string[]): string {
19
- return digest(controlAuthorizationFields(domain, action, partyId, rowFields), 'sha256', 'base64url') as string;
20
- }
21
-
22
- /** {@link taggedDigest} for the two party-free digests (`UnboundControlDomain`). */
23
- function unboundTaggedDigest(domain: UnboundControlDomain, action: ControlAction, rowFields: string[]): string {
24
- return digest(unboundAuthorizationFields(domain, action, rowFields), 'sha256', 'base64url') as string;
25
- }
26
-
27
- /**
28
- * Canonical digest an owner signs to vouch a peer's ENROLLMENT — the offline
29
- * credential `cadre enroll register` verifies. No table checks this digest, so it
30
- * carries its own `'Cadre.Enrollment'` domain tag to stay disjoint from every
31
- * CadreControl table rule (pre-tag it collided with the `DeviceToken` owner digests,
32
- * so an enrollment vouch doubled as a push-token delete approval).
33
- *
34
- * Factored into one place so the producer (owner signing) and the verifier (the
35
- * offline `cadre enroll register` check) can never drift apart — change the digest
36
- * here and both move together.
37
- */
38
- export function peerAuthorizationDigest(peerId: string): string {
39
- return unboundTaggedDigest('Cadre.Enrollment', 'vouch', [peerId]);
40
- }
41
-
42
- /**
43
- * The `CadreControl.DeviceToken` columns {@link deviceTokenAddDigest} binds, in the
44
- * schema's order. A whole-row struct rather than six positional strings, so a caller
45
- * cannot silently transpose `platform` and `token` (both opaque strings) and mint a
46
- * signature over a row it did not mean to approve.
47
- *
48
- * Structurally satisfied by a `DeviceTokenRecord` spread with the row's `stampId`;
49
- * `types.ts:DeviceTokenRecord` deliberately does NOT carry the stamp — it is the
50
- * SELF-signed record shape, and the peer's own `Sig` does not cover `StampId`.
51
- * `updatedAt` / `sig` are nullable because the columns are: both sign as `''` when
52
- * absent, mirroring the schema's `coalesce(...)`.
53
- */
54
- export interface DeviceTokenAuthorizedRow {
55
- peerId: string;
56
- platform: string;
57
- token: string;
58
- updatedAt: number | null;
59
- sig: string | null;
60
- stampId: string;
61
- }
62
-
63
- /**
64
- * Canonical digest an owner signs to authorize a `DeviceToken` INSERT — the WHOLE row,
65
- * ending in its single-use `StampId` nonce. SQL mirror:
66
- * `digest('CadreControl.DeviceToken', 'add', party_id(), new.PeerId, new.Platform, new.Token,
67
- * coalesce(cast(new.UpdatedAt as text), ''), coalesce(new.Sig, ''), new.StampId)` in
68
- * `DeviceToken.AuthorizedInsert`.
69
- *
70
- * Binding every column means a captured approval can only ever reproduce the exact row
71
- * it approved — never one carrying attacker-chosen `Platform`/`Token`/`UpdatedAt` — and
72
- * binding the stamp makes it single-use: while the row lives the `unique` column blocks
73
- * a replay, and after a clear the stamp is retired permanently into
74
- * `CadreControl.Revocation` (`DeviceToken.NotRevoked`). This matters more here than for
75
- * `CadrePeer`: a resurrected push token has NO freshness ceiling to retire it
76
- * (`CadreNode.resolveDeviceToken` defaults `maxAgeMs` to infinity by design), so stamp
77
- * retirement is the only thing that sticks.
78
- *
79
- * Distinct from {@link deviceTokenRemoveDigest} so a captured insert approval can never
80
- * be replayed to delete the token, and vice versa.
81
- */
82
- export function deviceTokenAddDigest(partyId: string, row: DeviceTokenAuthorizedRow): string {
83
- return taggedDigest('CadreControl.DeviceToken', 'add', partyId, [
84
- row.peerId,
85
- row.platform,
86
- row.token,
87
- row.updatedAt === null ? '' : String(row.updatedAt),
88
- row.sig ?? '',
89
- row.stampId,
90
- ]);
91
- }
92
-
93
- /**
94
- * Canonical digest an owner signs to authorize a `DeviceToken` DELETE, bound to the
95
- * STORED row's (PeerId, StampId). SQL mirror:
96
- * `digest('CadreControl.DeviceToken', 'remove', party_id(), old.PeerId, old.StampId)` in
97
- * `DeviceToken.AuthorizedDelete`.
98
- *
99
- * A narrower vector than {@link deviceTokenAddDigest} on purpose (the same split
100
- * `CadrePeer` makes): the clear approval names only which row is being retired, so it
101
- * cannot be re-cut into an insert approval, and it is dead the moment the stamp it
102
- * names is tombstoned.
103
- */
104
- export function deviceTokenRemoveDigest(partyId: string, peerId: string, stampId: string): string {
105
- return taggedDigest('CadreControl.DeviceToken', 'remove', partyId, [peerId, stampId]);
106
- }
107
-
108
- /**
109
- * Canonical digest an owner signs to VOUCH a `CadrePeer` membership row (insert
110
- * and the owner re-touch update — same semantics, deliberately the same digest).
111
- * Binds the peer id to the row's single-use `StampId` nonce, so a captured signed
112
- * insert cannot be replayed — while the row lives the `unique` column blocks it, and
113
- * after a removal the stamp is retired permanently into `CadreControl.Revocation`
114
- * (`CadrePeer.NotRevoked`) — and, because {@link cadrePeerRemoveDigest} scopes a
115
- * DIFFERENT payload, the stored voucher (`VouchSig`) cannot be replayed to authorize
116
- * a delete. The domain tag keeps the stored, replicated `VouchSig` useless against
117
- * every OTHER table's rules.
118
- *
119
- * SQL mirror: `digest('CadreControl.CadrePeer', 'vouch', party_id(), new.PeerId, new.StampId)`.
120
- */
121
- export function cadrePeerVoucherDigest(partyId: string, peerId: string, stampId: string): string {
122
- return taggedDigest('CadreControl.CadrePeer', 'vouch', partyId, [peerId, stampId]);
123
- }
124
-
125
- /**
126
- * Canonical digest an owner signs to REMOVE a `CadrePeer` row. Deliberately a
127
- * distinct payload from {@link cadrePeerVoucherDigest} (the `'remove'` action tag)
128
- * so the row's stored voucher — a signature over the voucher digest — can never
129
- * satisfy this delete check. The signature is supplied in write context and never
130
- * stored, so no reader can replay it; a captured remove is also dead after the
131
- * delete lands, because a re-added row carries a FRESH `StampId` (the removed row's
132
- * stamp is retired into `CadreControl.Revocation` and never reused).
133
- *
134
- * SQL mirror: `digest('CadreControl.CadrePeer', 'remove', party_id(), old.PeerId, old.StampId)`.
135
- */
136
- export function cadrePeerRemoveDigest(partyId: string, peerId: string, stampId: string): string {
137
- return taggedDigest('CadreControl.CadrePeer', 'remove', partyId, [peerId, stampId]);
138
- }
139
-
140
- /**
141
- * Canonical digest an owner signs to APPEND a `CadreControl.Revocation` tombstone —
142
- * the row retiring `stampId` for the named guarded table, and recording `rowKey`
143
- * (the removed row's primary key: OwnerKey.Key / ValidationKey.Key /
144
- * CadrePeer.PeerId / DeviceToken.PeerId / Strand.Id) as which row was retired.
145
- * SQL mirror:
146
- * `digest('CadreControl.Revocation', 'remove', party_id(), new.TableName, new.RowKey, new.StampId)`
147
- * in `Revocation.Authorized`.
148
- *
149
- * Its own `'CadreControl.Revocation'` domain tag makes it disjoint from the
150
- * `'CadreControl.CadrePeer'` (or `OwnerKey` / `ValidationKey` / `Strand`)
151
- * `'remove'` digest the same owner signs in the SAME transaction for the delete
152
- * this tombstone accompanies — a removal signature is not a retirement
153
- * signature and cannot be replayed as one.
154
- */
155
- export function revocationDigest(partyId: string, tableName: RevocableTable, rowKey: string, stampId: string): string {
156
- return taggedDigest('CadreControl.Revocation', 'remove', partyId, [tableName, rowKey, stampId]);
157
- }
158
-
159
- /**
160
- * Does a `Revocation` row's stored signer pair (`SignerKey` / `SignerSig`) verify over the
161
- * tombstone's own triple, for `partyId`? The read-side mirror of `Revocation.Authorized`,
162
- * for a node that received the row by replication and must decide whether to honour it.
163
- * Whether `row.signerKey` is an owner this node trusts is the caller's question, as for
164
- * {@link verifyCadrePeerVoucher}. Never throws: a malformed row verifies as `false`.
165
- */
166
- export function verifyRevocationSigner(partyId: string, row: RevocationRow): boolean {
167
- try {
168
- return verifyB64(revocationDigest(partyId, row.tableName, row.rowKey, row.stampId), row.signerSig, row.signerKey);
169
- } catch (error) {
170
- log('verifyRevocationSigner failed: %o', error);
171
- return false;
172
- }
173
- }
174
-
175
- /**
176
- * Canonical digest an owner signs to seat a further `OwnerKey` row — the signed-add branch
177
- * of `OwnerKey.Authorized`, which stores the pair as `VouchOwner` / `VouchSig`. SQL mirror:
178
- * `digest('CadreControl.OwnerKey', 'add', party_id(), new.Key, coalesce(new.Label, ''), new.StampId)`.
179
- * The removal digest needs no builder here: it is the generic guarded `'remove'` digest over
180
- * (Key, StampId).
181
- */
182
- export function ownerKeyAddDigest(partyId: string, key: string, label: string | null, stampId: string): string {
183
- return taggedDigest('CadreControl.OwnerKey', 'add', partyId, [key, label ?? '', stampId]);
184
- }
185
-
186
- /**
187
- * Does an owner-signed `OwnerKey` row's stored voucher verify — `vouchSig` by `vouchOwner`
188
- * over {@link ownerKeyAddDigest} for (`partyId`, `key`, `label`, `stampId`)? Whether
189
- * `vouchOwner` is anchored is the caller's question, as for {@link verifyCadrePeerVoucher}.
190
- * Never throws.
191
- */
192
- export function verifyOwnerKeyVoucher(partyId: string, key: string, label: string | null, stampId: string, vouchOwner: string, vouchSig: string): boolean {
193
- try {
194
- return verifyB64(ownerKeyAddDigest(partyId, key, label, stampId), vouchSig, vouchOwner);
195
- } catch (error) {
196
- log('verifyOwnerKeyVoucher failed: %o', error);
197
- return false;
198
- }
199
- }
200
-
201
- /**
202
- * Verify that `signature` is a valid owner ed25519 signature over `peerId`'s
203
- * authorization digest, using `ownerPublicKey` (base64url).
204
- *
205
- * This is the mirror of the signing done in
206
- * {@link SeedBootstrapService.authorizePeer}: it checks the signature against
207
- * {@link peerAuthorizationDigest}. A `true` result means the holder of the
208
- * owner private key vouched for this peer ID — it does NOT mean the peer is
209
- * registered anywhere.
210
- *
211
- * Returns a boolean and never throws: malformed base64url, a bad/garbage key, or
212
- * any crypto failure resolves to `false` (callers want a verdict, not an
213
- * exception). The catch is logged at debug.
214
- */
215
- export function verifyPeerAuthorization(
216
- peerId: string,
217
- ownerPublicKey: string,
218
- signature: string
219
- ): boolean {
220
- try {
221
- return verify(
222
- peerAuthorizationDigest(peerId),
223
- signature,
224
- ownerPublicKey,
225
- 'ed25519',
226
- 'base64url',
227
- 'base64url',
228
- 'base64url'
229
- );
230
- } catch (error) {
231
- log('verifyPeerAuthorization failed: %o', error);
232
- return false;
233
- }
234
- }
235
-
236
- /**
237
- * Verify that `signature` is a valid owner ed25519 signature over the
238
- * `CadrePeer` voucher digest for (`partyId`, `peerId`, `stampId`) — the read-side
239
- * mirror of the voucher {@link ControlDatabase.insertCadrePeer} signs and persists into
240
- * `VouchOwner`/`VouchSig` (see {@link cadrePeerVoucherDigest}).
241
- *
242
- * A `true` result means the holder of `ownerPublicKey` vouched THIS membership
243
- * row (the peer id bound to the row's single-use `StampId` nonce) in THIS party: a
244
- * voucher copied from another party's table that shares the owner key fails. It says
245
- * nothing about whether that owner key is itself trustworthy — the caller must
246
- * separately check the key against the node-local trusted-owner anchor
247
- * (`TrustedOwnerStore`), never the replicated `OwnerKey` table.
248
- *
249
- * Returns a boolean and never throws (same contract as
250
- * {@link verifyPeerAuthorization}): malformed input or any crypto failure
251
- * resolves to `false`, logged at debug.
252
- */
253
- export function verifyCadrePeerVoucher(
254
- partyId: string,
255
- peerId: string,
256
- stampId: string,
257
- ownerPublicKey: string,
258
- signature: string
259
- ): boolean {
260
- try {
261
- return verify(
262
- cadrePeerVoucherDigest(partyId, peerId, stampId),
263
- signature,
264
- ownerPublicKey,
265
- 'ed25519',
266
- 'base64url',
267
- 'base64url',
268
- 'base64url'
269
- );
270
- } catch (error) {
271
- log('verifyCadrePeerVoucher failed: %o', error);
272
- return false;
273
- }
274
- }
275
-
276
- /**
277
- * Canonical digest a JOINING peer signs to consent to ONE `FormationUsage`
278
- * redemption — the read-side mirror of `formationConsentMessage` in
279
- * control-database.ts, base64url-encoded instead of raw bytes (see
280
- * {@link unboundTaggedDigest}). That doc comment carries the field-vector rationale
281
- * (notably why neither `strandId` nor the party id is signed); the two vectors must not
282
- * drift, which peer-authorization.spec.ts pins by signing one form and verifying the other.
283
- */
284
- export function formationConsentDigest(
285
- token: string, usageStampId: string, peerKey: string, disclosure: string
286
- ): string {
287
- return unboundTaggedDigest('CadreControl.FormationUsage', 'consent', [token, usageStampId, peerKey, disclosure]);
288
- }
289
-
290
- /**
291
- * Verify that `row.peerSig` is a valid ed25519 signature over the joining peer's
292
- * consent digest (see {@link formationConsentDigest}) — the row's OWN `peerKey`.
293
- *
294
- * Unlike {@link verifyCadrePeerVoucher} there is no separate enrolled/owner row to
295
- * look up: the identity IS the key carried on the row, so a forged consent would
296
- * need that joiner's own private key. Returns a boolean and never throws (same
297
- * contract as the siblings above): malformed input or any crypto failure resolves
298
- * to `false`, logged at debug.
299
- */
300
- export function verifyFormationConsent(row: {
301
- token: string; usageStampId: string; peerKey: string; disclosure: string; peerSig: string;
302
- }): boolean {
303
- try {
304
- return verify(
305
- formationConsentDigest(row.token, row.usageStampId, row.peerKey, row.disclosure),
306
- row.peerSig, row.peerKey, 'ed25519', 'base64url', 'base64url', 'base64url'
307
- );
308
- } catch (error) {
309
- log('verifyFormationConsent failed: %o', error);
310
- return false;
311
- }
312
- }
313
-
314
- /**
315
- * Canonical digest an owner signs to seat a `CadreInvite` row — the read-side mirror
316
- * of `cadreInviteAddMessage` in control-database.ts, base64url instead of raw bytes
317
- * (see {@link taggedDigest}). The whole row is bound, nullable columns as `''` and
318
- * `ExpiresAt` in its stored canonical form, through the one field builder both sides
319
- * share (`cadreInviteRowFields`). SQL mirror: `CadreInvite.AuthorizedInsert`.
320
- */
321
- export function cadreInviteAddDigest(partyId: string, row: CadreInviteSignedFields): string {
322
- return taggedDigest('CadreControl.CadreInvite', 'add', partyId, cadreInviteRowFields(row));
323
- }
324
-
325
- /**
326
- * Canonical digest the HOLDER of a `CadreInvite`'s private key signs to redeem it once:
327
- * proof of possession, verified against the invitation key itself
328
- * (`CadreInviteUsage.InvitePossessed`). Binds the redemption's single-use nonce and the
329
- * device being admitted, so one redemption cannot be re-presented for another device
330
- * or another use. Mirror of `cadreInviteRedeemMessage` in control-database.ts.
331
- */
332
- export function cadreInviteRedeemDigest(partyId: string, inviteKey: string, usageStampId: string, peerKey: string): string {
333
- return taggedDigest('CadreControl.CadreInviteUsage', 'redeem', partyId, [inviteKey, usageStampId, peerKey]);
334
- }
335
-
336
- /**
337
- * Canonical digest the DEVICE signs to consent to being admitted by one redemption
338
- * (`CadreInviteUsage.PeerConsented`), over the same fields as
339
- * {@link cadreInviteRedeemDigest} under a distinct action tag, so the holder's and
340
- * the device's signatures are never interchangeable. Mirror of
341
- * `cadreInviteConsentMessage` in control-database.ts.
342
- */
343
- export function cadreInviteConsentDigest(partyId: string, inviteKey: string, usageStampId: string, peerKey: string): string {
344
- return taggedDigest('CadreControl.CadreInviteUsage', 'consent', partyId, [inviteKey, usageStampId, peerKey]);
345
- }
346
-
347
- /** ed25519 verify over a base64url digest, with the siblings' never-throws contract left to the caller. */
348
- function verifyB64(digestB64: string, signature: string, publicKey: string): boolean {
349
- return verify(digestB64, signature, publicKey, 'ed25519', 'base64url', 'base64url', 'base64url');
350
- }
351
-
352
- /**
353
- * Does a `CadreInvite` row carry a valid `'add'` signature by its own `issuerKey`, for
354
- * `partyId`? The redeeming device runs this over the row a member replies with, after
355
- * checking the issuer against its pinned owner keys and the reply's party against the
356
- * invitation's, and a member over a bundle's copy it does not hold yet
357
- * (`ControlDatabase.isCadreInviteLive`); whether that issuer IS an owner is the caller's question.
358
- * Never throws: a malformed row verifies as `false`.
359
- */
360
- export function verifyCadreInviteRow(partyId: string, invite: CadreInviteRow): boolean {
361
- try {
362
- return verifyB64(cadreInviteAddDigest(partyId, invite), invite.issuerSig, invite.issuerKey);
363
- } catch (error) {
364
- log('verifyCadreInviteRow failed: %o', error);
365
- return false;
366
- }
367
- }
368
-
369
- /**
370
- * The two signatures a redemption carries, checked before any database work: the holder's
371
- * `'redeem'` signature with the invitation key, and the device's `'consent'` signature with
372
- * its own key, both over (`inviteKey`, `usageStampId`, `peerKey`). The pre-check twin of
373
- * `CadreInviteUsage.InvitePossessed` / `PeerConsented`, as `verifyFormationConsent` is for
374
- * formation: the schema stays the authority, this turns a bad signature into a clean
375
- * refusal instead of a constraint failure at commit. Never throws.
376
- */
377
- export function verifyCadreInviteRedemption(
378
- partyId: string,
379
- fields: { inviteKey: string; usageStampId: string; peerKey: string },
380
- inviteSig: string,
381
- peerSig: string,
382
- ): boolean {
383
- try {
384
- return verifyB64(cadreInviteRedeemDigest(partyId, fields.inviteKey, fields.usageStampId, fields.peerKey), inviteSig, fields.inviteKey)
385
- && verifyB64(cadreInviteConsentDigest(partyId, fields.inviteKey, fields.usageStampId, fields.peerKey), peerSig, fields.peerKey);
386
- } catch (error) {
387
- log('verifyCadreInviteRedemption failed: %o', error);
388
- return false;
389
- }
390
- }
391
-
392
- /**
393
- * Is an invitation-admitted `CadrePeer` row (`vouchSig` null, `vouchUsage` set) a
394
- * member this node should trust? The read-side mirror of the consent branch of
395
- * `CadrePeer.AuthorizedInsert`, re-checked against THIS node's anchor because the
396
- * replicated `OwnerKey` table can be polluted. The chain is
397
- *
398
- * row --vouchUsage--> usage --inviteKey--> invitation --issuerKey--> anchored owner
399
- *
400
- * and every link is verified: the issuer is anchored (`isAnchored`) and is the row's
401
- * `vouchOwner`; the usage is the row's `vouchUsage`, names this peer id and this exact row
402
- * incarnation (`peerStampId`), and names this invitation; a targeted invitation names the
403
- * redeeming device; the stored `peerKey` really is the key behind the usage's `peerId` (the
404
- * schema cannot unwrap a multihash, so a writer could assert any pair); the invitation's
405
- * stored `'add'` signature verifies over the row rebuilt from its columns; the holder's
406
- * `'redeem'` signature verifies with the invitation key and the device's `'consent'`
407
- * signature with its own key. All three signatures are judged for `partyId`. A machine
408
- * invitation admits a machine and nothing else, so no `OwnerKey` row is ever verified
409
- * through this chain; a grant-seated owner row is {@link verifyOwnerGrantAdmission}'s.
410
- *
411
- * Expiry, use count and withdrawal are deliberately NOT re-checked: they were conditions
412
- * at redemption (`CadreInviteUsage.Authorized`), and membership persists until an owner
413
- * removes the row — exactly as an owner-vouched row's membership does. Keeping a device
414
- * out is removing its row AND withdrawing the invitation.
415
- *
416
- * Returns a boolean and never throws (the siblings' contract): malformed input or any
417
- * crypto failure resolves to `false`, logged at debug.
418
- */
419
- export function verifyInvitationAdmission(
420
- partyId: string,
421
- row: CadrePeerVoucherFields,
422
- usage: CadreInviteUsageRow,
423
- invite: CadreInviteRow,
424
- isAnchored: (ownerKey: string) => boolean,
425
- ): boolean {
426
- try {
427
- return row.stampId !== null
428
- && row.vouchOwner !== null
429
- && row.vouchUsage !== null
430
- && isAnchored(row.vouchOwner)
431
- && invite.issuerKey === row.vouchOwner
432
- && usage.usageStampId === row.vouchUsage
433
- && usage.peerStampId === row.stampId
434
- && usage.peerId === row.peerId
435
- && usage.inviteKey === invite.key
436
- && (invite.peerId === null || invite.peerId === usage.peerId)
437
- && ed25519PublicKeyB64FromPeerId(usage.peerId) === usage.peerKey
438
- && verifyB64(cadreInviteAddDigest(partyId, invite), invite.issuerSig, invite.issuerKey)
439
- && verifyB64(cadreInviteRedeemDigest(partyId, invite.key, usage.usageStampId, usage.peerKey), usage.inviteSig, invite.key)
440
- && verifyB64(cadreInviteConsentDigest(partyId, invite.key, usage.usageStampId, usage.peerKey), usage.peerSig, usage.peerKey);
441
- } catch (error) {
442
- log('verifyInvitationAdmission failed: %o', error);
443
- return false;
444
- }
445
- }
446
-
447
- /**
448
- * Canonical digest a machine signs to state its own peer id in one strand, with its own
449
- * identity key rather than an owner key. SQL mirror: `StrandPeer.Authorized`.
450
- */
451
- export function strandPeerAddDigest(partyId: string, row: StrandPeerSignedFields): string {
452
- return taggedDigest('CadreControl.StrandPeer', 'add', partyId, strandPeerRowFields(row));
453
- }
454
-
455
- /**
456
- * Was a `StrandPeer` row signed by the machine it names, in `partyId`? Verified against the key
457
- * derived from `peerId`, not against `CadrePeer.PublicKey` as the schema's check does, because
458
- * that column is written by whoever seated the row and a replicated row never meets the check.
459
- * Whether `peerId` is a machine of this party is the caller's question. Never throws.
460
- */
461
- export function verifyStrandPeerRow(partyId: string, row: StrandPeerRow): boolean {
462
- try {
463
- const publicKey = ed25519PublicKeyB64FromPeerId(row.peerId);
464
- return publicKey !== null && verifyB64(strandPeerAddDigest(partyId, row), row.sig, publicKey);
465
- } catch (error) {
466
- log('verifyStrandPeerRow failed: %o', error);
467
- return false;
468
- }
469
- }
470
-
471
- /**
472
- * Canonical digest an owner signs to seat an `OwnerGrant` row — the read-side mirror of
473
- * `ownerGrantAddMessage` in control-database.ts, base64url instead of raw bytes. The whole
474
- * row is bound, the label included, through the one field builder both sides share
475
- * (`ownerGrantRowFields`). SQL mirror: `OwnerGrant.AuthorizedInsert`.
476
- */
477
- export function ownerGrantAddDigest(partyId: string, row: OwnerGrantSignedFields): string {
478
- return taggedDigest('CadreControl.OwnerGrant', 'add', partyId, ownerGrantRowFields(row));
479
- }
480
-
481
- /**
482
- * Canonical digest the HOLDER of an `OwnerGrant`'s private key signs to redeem it once:
483
- * proof of possession, verified against the grant key itself
484
- * (`OwnerGrantUsage.GrantPossessed`). Binds the redemption's nonce and the key being seated,
485
- * so one redemption cannot be re-presented for another key or another use. Mirror of
486
- * `ownerGrantRedeemMessage` in control-database.ts.
487
- */
488
- export function ownerGrantRedeemDigest(partyId: string, grantKey: string, usageStampId: string, seatedKey: string): string {
489
- return taggedDigest('CadreControl.OwnerGrantUsage', 'redeem', partyId, [grantKey, usageStampId, seatedKey]);
490
- }
491
-
492
- /**
493
- * Canonical digest the key being SEATED signs to prove it is held by the redeemer
494
- * (`OwnerGrantUsage.OwnerConsented`), over the same fields as {@link ownerGrantRedeemDigest}
495
- * under a distinct action tag, so the holder's and the key's signatures are never
496
- * interchangeable. Mirror of `ownerGrantConsentMessage` in control-database.ts.
497
- */
498
- export function ownerGrantConsentDigest(partyId: string, grantKey: string, usageStampId: string, seatedKey: string): string {
499
- return taggedDigest('CadreControl.OwnerGrantUsage', 'consent', partyId, [grantKey, usageStampId, seatedKey]);
500
- }
501
-
502
- /**
503
- * Does an `OwnerGrant` row carry a valid `'add'` signature by its own `issuerKey`, for
504
- * `partyId`? The grant twin of {@link verifyCadreInviteRow}, with the same contract: whether
505
- * that issuer IS an owner is the caller's question, and a malformed row verifies as `false`.
506
- */
507
- export function verifyOwnerGrantRow(partyId: string, grant: OwnerGrantRow): boolean {
508
- try {
509
- return verifyB64(ownerGrantAddDigest(partyId, grant), grant.issuerSig, grant.issuerKey);
510
- } catch (error) {
511
- log('verifyOwnerGrantRow failed: %o', error);
512
- return false;
513
- }
514
- }
515
-
516
- /**
517
- * The two signatures an owner-grant redemption carries, checked before any database work:
518
- * the holder's `'redeem'` signature with the grant key and the seated key's `'consent'`
519
- * signature with itself, both over (`grantKey`, `usageStampId`, `seatedKey`). The grant twin
520
- * of {@link verifyCadreInviteRedemption}, with the same contract: the schema
521
- * (`OwnerGrantUsage.GrantPossessed` / `OwnerConsented`) stays the authority, this turns a bad
522
- * signature into a clean refusal instead of a constraint failure at commit. Never throws.
523
- */
524
- export function verifyOwnerGrantRedemption(
525
- partyId: string,
526
- fields: { grantKey: string; usageStampId: string; seatedKey: string },
527
- grantSig: string,
528
- ownerSig: string,
529
- ): boolean {
530
- try {
531
- return verifyB64(ownerGrantRedeemDigest(partyId, fields.grantKey, fields.usageStampId, fields.seatedKey), grantSig, fields.grantKey)
532
- && verifyB64(ownerGrantConsentDigest(partyId, fields.grantKey, fields.usageStampId, fields.seatedKey), ownerSig, fields.seatedKey);
533
- } catch (error) {
534
- log('verifyOwnerGrantRedemption failed: %o', error);
535
- return false;
536
- }
537
- }
538
-
539
- /**
540
- * Is a grant-seated `OwnerKey` row (`vouchSig` null, `vouchUsage` naming an `OwnerGrantUsage`
541
- * row) an owner this node should derive into its anchor? The read-side mirror of the grant
542
- * branch of `OwnerKey.Authorized` (`owner-anchor-sync.ts` → `deriveOwnerAnchor`). The chain is
543
- *
544
- * row --vouchUsage--> usage --grantKey--> grant --issuerKey--> anchored owner
545
- *
546
- * and every link is verified: the issuer is anchored and is the row's `vouchOwner`; the usage
547
- * is the row's `vouchUsage` and names this key and this exact row incarnation
548
- * (`seatedStampId`); the usage names this grant; the row carries the grant's label; the
549
- * grant's stored `'add'` signature verifies over the row rebuilt from its columns; the
550
- * holder's `'redeem'` signature verifies with the grant key and the seated key's `'consent'`
551
- * signature with itself. All three signatures are judged for `partyId`.
552
- *
553
- * Expiry, use count and withdrawal are deliberately NOT re-checked, as
554
- * {@link verifyInvitationAdmission} omits them: they were conditions at redemption
555
- * (`OwnerGrantUsage.Authorized`), and ownership persists until an owner removes the row.
556
- * Same never-throws contract as the siblings.
557
- */
558
- export function verifyOwnerGrantAdmission(
559
- partyId: string,
560
- row: OwnerKeyRow,
561
- usage: OwnerGrantUsageRow,
562
- grant: OwnerGrantRow,
563
- isAnchored: (ownerKey: string) => boolean,
564
- ): boolean {
565
- try {
566
- return row.vouchOwner !== null
567
- && row.vouchUsage !== null
568
- && isAnchored(row.vouchOwner)
569
- && grant.issuerKey === row.vouchOwner
570
- && usage.usageStampId === row.vouchUsage
571
- && usage.seatedKey === row.key
572
- && usage.seatedStampId === row.stampId
573
- && usage.grantKey === grant.key
574
- && (grant.label ?? '') === (row.label ?? '')
575
- && verifyB64(ownerGrantAddDigest(partyId, grant), grant.issuerSig, grant.issuerKey)
576
- && verifyB64(ownerGrantRedeemDigest(partyId, grant.key, usage.usageStampId, usage.seatedKey), usage.grantSig, grant.key)
577
- && verifyB64(ownerGrantConsentDigest(partyId, grant.key, usage.usageStampId, usage.seatedKey), usage.ownerSig, usage.seatedKey);
578
- } catch (error) {
579
- log('verifyOwnerGrantAdmission failed: %o', error);
580
- return false;
581
- }
582
- }
1
+ import debug from 'debug';
2
+ import { digest, verify } from '@optimystic/quereus-plugin-crypto';
3
+ import { controlAuthorizationFields, unboundAuthorizationFields, cadreInviteRowFields, ownerGrantRowFields, strandPeerRowFields } from './control-authorization.js';
4
+ import type { BoundControlDomain, CadreInviteSignedFields, ControlAction, OwnerGrantSignedFields, RevocableTable, StrandPeerSignedFields, UnboundControlDomain } from './control-authorization.js';
5
+ import { ed25519PublicKeyB64FromPeerId } from './ed25519-key.js';
6
+ import type { CadreInviteRow, CadreInviteUsageRow, CadrePeerVoucherFields, OwnerGrantRow, OwnerGrantUsageRow, OwnerKeyRow, RevocationRow, StrandPeerRow } from './types.js';
7
+
8
+ const log = debug('sereus:cadre:peer-authorization');
9
+
10
+ /**
11
+ * base64url SHA-256 digest over the shared domain-tagged, party-bound field vector (see
12
+ * control-authorization.ts). The base64url twin of
13
+ * control-database.ts:buildAuthorizationMessage (which returns the same digest as raw
14
+ * bytes): sign either encoding with input encoding to match and the signed bytes agree.
15
+ * `partyId` is the party the verifier is configured for: a stored proof minted for
16
+ * another party fails here exactly as it fails the schema's `party_id()`-bound check.
17
+ */
18
+ function taggedDigest(domain: BoundControlDomain, action: ControlAction, partyId: string, rowFields: string[]): string {
19
+ return digest(controlAuthorizationFields(domain, action, partyId, rowFields), 'sha256', 'base64url') as string;
20
+ }
21
+
22
+ /** {@link taggedDigest} for the two party-free digests (`UnboundControlDomain`). */
23
+ function unboundTaggedDigest(domain: UnboundControlDomain, action: ControlAction, rowFields: string[]): string {
24
+ return digest(unboundAuthorizationFields(domain, action, rowFields), 'sha256', 'base64url') as string;
25
+ }
26
+
27
+ /**
28
+ * Canonical digest an owner signs to vouch a peer's ENROLLMENT — the offline
29
+ * credential `cadre enroll register` verifies. No table checks this digest, so it
30
+ * carries its own `'Cadre.Enrollment'` domain tag to stay disjoint from every
31
+ * CadreControl table rule (pre-tag it collided with the `DeviceToken` owner digests,
32
+ * so an enrollment vouch doubled as a push-token delete approval).
33
+ *
34
+ * Factored into one place so the producer (owner signing) and the verifier (the
35
+ * offline `cadre enroll register` check) can never drift apart — change the digest
36
+ * here and both move together.
37
+ */
38
+ export function peerAuthorizationDigest(peerId: string): string {
39
+ return unboundTaggedDigest('Cadre.Enrollment', 'vouch', [peerId]);
40
+ }
41
+
42
+ /**
43
+ * The `CadreControl.DeviceToken` columns {@link deviceTokenAddDigest} binds, in the
44
+ * schema's order. A whole-row struct rather than six positional strings, so a caller
45
+ * cannot silently transpose `platform` and `token` (both opaque strings) and mint a
46
+ * signature over a row it did not mean to approve.
47
+ *
48
+ * Structurally satisfied by a `DeviceTokenRecord` spread with the row's `stampId`;
49
+ * `types.ts:DeviceTokenRecord` deliberately does NOT carry the stamp — it is the
50
+ * SELF-signed record shape, and the peer's own `Sig` does not cover `StampId`.
51
+ * `updatedAt` / `sig` are nullable because the columns are: both sign as `''` when
52
+ * absent, mirroring the schema's `coalesce(...)`.
53
+ */
54
+ export interface DeviceTokenAuthorizedRow {
55
+ peerId: string;
56
+ platform: string;
57
+ token: string;
58
+ updatedAt: number | null;
59
+ sig: string | null;
60
+ stampId: string;
61
+ }
62
+
63
+ /**
64
+ * Canonical digest an owner signs to authorize a `DeviceToken` INSERT — the WHOLE row,
65
+ * ending in its single-use `StampId` nonce. SQL mirror:
66
+ * `digest('CadreControl.DeviceToken', 'add', party_id(), new.PeerId, new.Platform, new.Token,
67
+ * coalesce(cast(new.UpdatedAt as text), ''), coalesce(new.Sig, ''), new.StampId)` in
68
+ * `DeviceToken.AuthorizedInsert`.
69
+ *
70
+ * Binding every column means a captured approval can only ever reproduce the exact row
71
+ * it approved — never one carrying attacker-chosen `Platform`/`Token`/`UpdatedAt` — and
72
+ * binding the stamp makes it single-use: while the row lives the `unique` column blocks
73
+ * a replay, and after a clear the stamp is retired permanently into
74
+ * `CadreControl.Revocation` (`DeviceToken.NotRevoked`). This matters more here than for
75
+ * `CadrePeer`: a resurrected push token has NO freshness ceiling to retire it
76
+ * (`CadreNode.resolveDeviceToken` defaults `maxAgeMs` to infinity by design), so stamp
77
+ * retirement is the only thing that sticks.
78
+ *
79
+ * Distinct from {@link deviceTokenRemoveDigest} so a captured insert approval can never
80
+ * be replayed to delete the token, and vice versa.
81
+ */
82
+ export function deviceTokenAddDigest(partyId: string, row: DeviceTokenAuthorizedRow): string {
83
+ return taggedDigest('CadreControl.DeviceToken', 'add', partyId, [
84
+ row.peerId,
85
+ row.platform,
86
+ row.token,
87
+ row.updatedAt === null ? '' : String(row.updatedAt),
88
+ row.sig ?? '',
89
+ row.stampId,
90
+ ]);
91
+ }
92
+
93
+ /**
94
+ * Canonical digest an owner signs to authorize a `DeviceToken` DELETE, bound to the
95
+ * STORED row's (PeerId, StampId). SQL mirror:
96
+ * `digest('CadreControl.DeviceToken', 'remove', party_id(), old.PeerId, old.StampId)` in
97
+ * `DeviceToken.AuthorizedDelete`.
98
+ *
99
+ * A narrower vector than {@link deviceTokenAddDigest} on purpose (the same split
100
+ * `CadrePeer` makes): the clear approval names only which row is being retired, so it
101
+ * cannot be re-cut into an insert approval, and it is dead the moment the stamp it
102
+ * names is tombstoned.
103
+ */
104
+ export function deviceTokenRemoveDigest(partyId: string, peerId: string, stampId: string): string {
105
+ return taggedDigest('CadreControl.DeviceToken', 'remove', partyId, [peerId, stampId]);
106
+ }
107
+
108
+ /**
109
+ * Canonical digest an owner signs to VOUCH a `CadrePeer` membership row (insert
110
+ * and the owner re-touch update — same semantics, deliberately the same digest).
111
+ * Binds the peer id to the row's single-use `StampId` nonce, so a captured signed
112
+ * insert cannot be replayed — while the row lives the `unique` column blocks it, and
113
+ * after a removal the stamp is retired permanently into `CadreControl.Revocation`
114
+ * (`CadrePeer.NotRevoked`) — and, because {@link cadrePeerRemoveDigest} scopes a
115
+ * DIFFERENT payload, the stored voucher (`VouchSig`) cannot be replayed to authorize
116
+ * a delete. The domain tag keeps the stored, replicated `VouchSig` useless against
117
+ * every OTHER table's rules.
118
+ *
119
+ * SQL mirror: `digest('CadreControl.CadrePeer', 'vouch', party_id(), new.PeerId, new.StampId)`.
120
+ */
121
+ export function cadrePeerVoucherDigest(partyId: string, peerId: string, stampId: string): string {
122
+ return taggedDigest('CadreControl.CadrePeer', 'vouch', partyId, [peerId, stampId]);
123
+ }
124
+
125
+ /**
126
+ * Canonical digest an owner signs to REMOVE a `CadrePeer` row. Deliberately a
127
+ * distinct payload from {@link cadrePeerVoucherDigest} (the `'remove'` action tag)
128
+ * so the row's stored voucher — a signature over the voucher digest — can never
129
+ * satisfy this delete check. The signature is supplied in write context and never
130
+ * stored, so no reader can replay it; a captured remove is also dead after the
131
+ * delete lands, because a re-added row carries a FRESH `StampId` (the removed row's
132
+ * stamp is retired into `CadreControl.Revocation` and never reused).
133
+ *
134
+ * SQL mirror: `digest('CadreControl.CadrePeer', 'remove', party_id(), old.PeerId, old.StampId)`.
135
+ */
136
+ export function cadrePeerRemoveDigest(partyId: string, peerId: string, stampId: string): string {
137
+ return taggedDigest('CadreControl.CadrePeer', 'remove', partyId, [peerId, stampId]);
138
+ }
139
+
140
+ /**
141
+ * Canonical digest an owner signs to APPEND a `CadreControl.Revocation` tombstone —
142
+ * the row retiring `stampId` for the named guarded table, and recording `rowKey`
143
+ * (the removed row's primary key: OwnerKey.Key / ValidationKey.Key /
144
+ * CadrePeer.PeerId / DeviceToken.PeerId / Strand.Id) as which row was retired.
145
+ * SQL mirror:
146
+ * `digest('CadreControl.Revocation', 'remove', party_id(), new.TableName, new.RowKey, new.StampId)`
147
+ * in `Revocation.Authorized`.
148
+ *
149
+ * Its own `'CadreControl.Revocation'` domain tag makes it disjoint from the
150
+ * `'CadreControl.CadrePeer'` (or `OwnerKey` / `ValidationKey` / `Strand`)
151
+ * `'remove'` digest the same owner signs in the SAME transaction for the delete
152
+ * this tombstone accompanies — a removal signature is not a retirement
153
+ * signature and cannot be replayed as one.
154
+ */
155
+ export function revocationDigest(partyId: string, tableName: RevocableTable, rowKey: string, stampId: string): string {
156
+ return taggedDigest('CadreControl.Revocation', 'remove', partyId, [tableName, rowKey, stampId]);
157
+ }
158
+
159
+ /**
160
+ * Does a `Revocation` row's stored signer pair (`SignerKey` / `SignerSig`) verify over the
161
+ * tombstone's own triple, for `partyId`? The read-side mirror of `Revocation.Authorized`,
162
+ * for a node that received the row by replication and must decide whether to honour it.
163
+ * Whether `row.signerKey` is an owner this node trusts is the caller's question, as for
164
+ * {@link verifyCadrePeerVoucher}. Never throws: a malformed row verifies as `false`.
165
+ */
166
+ export function verifyRevocationSigner(partyId: string, row: RevocationRow): boolean {
167
+ try {
168
+ return verifyB64(revocationDigest(partyId, row.tableName, row.rowKey, row.stampId), row.signerSig, row.signerKey);
169
+ } catch (error) {
170
+ log('verifyRevocationSigner failed: %o', error);
171
+ return false;
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Canonical digest an owner signs to seat a further `OwnerKey` row — the signed-add branch
177
+ * of `OwnerKey.Authorized`, which stores the pair as `VouchOwner` / `VouchSig`. SQL mirror:
178
+ * `digest('CadreControl.OwnerKey', 'add', party_id(), new.Key, coalesce(new.Label, ''), new.StampId)`.
179
+ * The removal digest needs no builder here: it is the generic guarded `'remove'` digest over
180
+ * (Key, StampId).
181
+ */
182
+ export function ownerKeyAddDigest(partyId: string, key: string, label: string | null, stampId: string): string {
183
+ return taggedDigest('CadreControl.OwnerKey', 'add', partyId, [key, label ?? '', stampId]);
184
+ }
185
+
186
+ /**
187
+ * Does an owner-signed `OwnerKey` row's stored voucher verify — `vouchSig` by `vouchOwner`
188
+ * over {@link ownerKeyAddDigest} for (`partyId`, `key`, `label`, `stampId`)? Whether
189
+ * `vouchOwner` is anchored is the caller's question, as for {@link verifyCadrePeerVoucher}.
190
+ * Never throws.
191
+ */
192
+ export function verifyOwnerKeyVoucher(partyId: string, key: string, label: string | null, stampId: string, vouchOwner: string, vouchSig: string): boolean {
193
+ try {
194
+ return verifyB64(ownerKeyAddDigest(partyId, key, label, stampId), vouchSig, vouchOwner);
195
+ } catch (error) {
196
+ log('verifyOwnerKeyVoucher failed: %o', error);
197
+ return false;
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Verify that `signature` is a valid owner ed25519 signature over `peerId`'s
203
+ * authorization digest, using `ownerPublicKey` (base64url).
204
+ *
205
+ * This is the mirror of the signing done in
206
+ * {@link SeedBootstrapService.authorizePeer}: it checks the signature against
207
+ * {@link peerAuthorizationDigest}. A `true` result means the holder of the
208
+ * owner private key vouched for this peer ID — it does NOT mean the peer is
209
+ * registered anywhere.
210
+ *
211
+ * Returns a boolean and never throws: malformed base64url, a bad/garbage key, or
212
+ * any crypto failure resolves to `false` (callers want a verdict, not an
213
+ * exception). The catch is logged at debug.
214
+ */
215
+ export function verifyPeerAuthorization(
216
+ peerId: string,
217
+ ownerPublicKey: string,
218
+ signature: string
219
+ ): boolean {
220
+ try {
221
+ return verify(
222
+ peerAuthorizationDigest(peerId),
223
+ signature,
224
+ ownerPublicKey,
225
+ 'ed25519',
226
+ 'base64url',
227
+ 'base64url',
228
+ 'base64url'
229
+ );
230
+ } catch (error) {
231
+ log('verifyPeerAuthorization failed: %o', error);
232
+ return false;
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Verify that `signature` is a valid owner ed25519 signature over the
238
+ * `CadrePeer` voucher digest for (`partyId`, `peerId`, `stampId`) — the read-side
239
+ * mirror of the voucher {@link ControlDatabase.insertCadrePeer} signs and persists into
240
+ * `VouchOwner`/`VouchSig` (see {@link cadrePeerVoucherDigest}).
241
+ *
242
+ * A `true` result means the holder of `ownerPublicKey` vouched THIS membership
243
+ * row (the peer id bound to the row's single-use `StampId` nonce) in THIS party: a
244
+ * voucher copied from another party's table that shares the owner key fails. It says
245
+ * nothing about whether that owner key is itself trustworthy — the caller must
246
+ * separately check the key against the node-local trusted-owner anchor
247
+ * (`TrustedOwnerStore`), never the replicated `OwnerKey` table.
248
+ *
249
+ * Returns a boolean and never throws (same contract as
250
+ * {@link verifyPeerAuthorization}): malformed input or any crypto failure
251
+ * resolves to `false`, logged at debug.
252
+ */
253
+ export function verifyCadrePeerVoucher(
254
+ partyId: string,
255
+ peerId: string,
256
+ stampId: string,
257
+ ownerPublicKey: string,
258
+ signature: string
259
+ ): boolean {
260
+ try {
261
+ return verify(
262
+ cadrePeerVoucherDigest(partyId, peerId, stampId),
263
+ signature,
264
+ ownerPublicKey,
265
+ 'ed25519',
266
+ 'base64url',
267
+ 'base64url',
268
+ 'base64url'
269
+ );
270
+ } catch (error) {
271
+ log('verifyCadrePeerVoucher failed: %o', error);
272
+ return false;
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Canonical digest a JOINING peer signs to consent to ONE `FormationUsage`
278
+ * redemption — the read-side mirror of `formationConsentMessage` in
279
+ * control-database.ts, base64url-encoded instead of raw bytes (see
280
+ * {@link unboundTaggedDigest}). That doc comment carries the field-vector rationale
281
+ * (notably why neither `strandId` nor the party id is signed); the two vectors must not
282
+ * drift, which peer-authorization.spec.ts pins by signing one form and verifying the other.
283
+ */
284
+ export function formationConsentDigest(
285
+ token: string, usageStampId: string, peerKey: string, disclosure: string
286
+ ): string {
287
+ return unboundTaggedDigest('CadreControl.FormationUsage', 'consent', [token, usageStampId, peerKey, disclosure]);
288
+ }
289
+
290
+ /**
291
+ * Verify that `row.peerSig` is a valid ed25519 signature over the joining peer's
292
+ * consent digest (see {@link formationConsentDigest}) — the row's OWN `peerKey`.
293
+ *
294
+ * Unlike {@link verifyCadrePeerVoucher} there is no separate enrolled/owner row to
295
+ * look up: the identity IS the key carried on the row, so a forged consent would
296
+ * need that joiner's own private key. Returns a boolean and never throws (same
297
+ * contract as the siblings above): malformed input or any crypto failure resolves
298
+ * to `false`, logged at debug.
299
+ */
300
+ export function verifyFormationConsent(row: {
301
+ token: string; usageStampId: string; peerKey: string; disclosure: string; peerSig: string;
302
+ }): boolean {
303
+ try {
304
+ return verify(
305
+ formationConsentDigest(row.token, row.usageStampId, row.peerKey, row.disclosure),
306
+ row.peerSig, row.peerKey, 'ed25519', 'base64url', 'base64url', 'base64url'
307
+ );
308
+ } catch (error) {
309
+ log('verifyFormationConsent failed: %o', error);
310
+ return false;
311
+ }
312
+ }
313
+
314
+ /**
315
+ * Canonical digest an owner signs to seat a `CadreInvite` row — the read-side mirror
316
+ * of `cadreInviteAddMessage` in control-database.ts, base64url instead of raw bytes
317
+ * (see {@link taggedDigest}). The whole row is bound, nullable columns as `''` and
318
+ * `ExpiresAt` in its stored canonical form, through the one field builder both sides
319
+ * share (`cadreInviteRowFields`). SQL mirror: `CadreInvite.AuthorizedInsert`.
320
+ */
321
+ export function cadreInviteAddDigest(partyId: string, row: CadreInviteSignedFields): string {
322
+ return taggedDigest('CadreControl.CadreInvite', 'add', partyId, cadreInviteRowFields(row));
323
+ }
324
+
325
+ /**
326
+ * Canonical digest the HOLDER of a `CadreInvite`'s private key signs to redeem it once:
327
+ * proof of possession, verified against the invitation key itself
328
+ * (`CadreInviteUsage.InvitePossessed`). Binds the redemption's single-use nonce and the
329
+ * device being admitted, so one redemption cannot be re-presented for another device
330
+ * or another use. Mirror of `cadreInviteRedeemMessage` in control-database.ts.
331
+ */
332
+ export function cadreInviteRedeemDigest(partyId: string, inviteKey: string, usageStampId: string, peerKey: string): string {
333
+ return taggedDigest('CadreControl.CadreInviteUsage', 'redeem', partyId, [inviteKey, usageStampId, peerKey]);
334
+ }
335
+
336
+ /**
337
+ * Canonical digest the DEVICE signs to consent to being admitted by one redemption
338
+ * (`CadreInviteUsage.PeerConsented`), over the same fields as
339
+ * {@link cadreInviteRedeemDigest} under a distinct action tag, so the holder's and
340
+ * the device's signatures are never interchangeable. Mirror of
341
+ * `cadreInviteConsentMessage` in control-database.ts.
342
+ */
343
+ export function cadreInviteConsentDigest(partyId: string, inviteKey: string, usageStampId: string, peerKey: string): string {
344
+ return taggedDigest('CadreControl.CadreInviteUsage', 'consent', partyId, [inviteKey, usageStampId, peerKey]);
345
+ }
346
+
347
+ /** ed25519 verify over a base64url digest, with the siblings' never-throws contract left to the caller. */
348
+ function verifyB64(digestB64: string, signature: string, publicKey: string): boolean {
349
+ return verify(digestB64, signature, publicKey, 'ed25519', 'base64url', 'base64url', 'base64url');
350
+ }
351
+
352
+ /**
353
+ * Does a `CadreInvite` row carry a valid `'add'` signature by its own `issuerKey`, for
354
+ * `partyId`? The redeeming device runs this over the row a member replies with, after
355
+ * checking the issuer against its pinned owner keys and the reply's party against the
356
+ * invitation's, and a member over a bundle's copy it does not hold yet
357
+ * (`ControlDatabase.isCadreInviteLive`); whether that issuer IS an owner is the caller's question.
358
+ * Never throws: a malformed row verifies as `false`.
359
+ */
360
+ export function verifyCadreInviteRow(partyId: string, invite: CadreInviteRow): boolean {
361
+ try {
362
+ return verifyB64(cadreInviteAddDigest(partyId, invite), invite.issuerSig, invite.issuerKey);
363
+ } catch (error) {
364
+ log('verifyCadreInviteRow failed: %o', error);
365
+ return false;
366
+ }
367
+ }
368
+
369
+ /**
370
+ * The two signatures a redemption carries, checked before any database work: the holder's
371
+ * `'redeem'` signature with the invitation key, and the device's `'consent'` signature with
372
+ * its own key, both over (`inviteKey`, `usageStampId`, `peerKey`). The pre-check twin of
373
+ * `CadreInviteUsage.InvitePossessed` / `PeerConsented`, as `verifyFormationConsent` is for
374
+ * formation: the schema stays the authority, this turns a bad signature into a clean
375
+ * refusal instead of a constraint failure at commit. Never throws.
376
+ */
377
+ export function verifyCadreInviteRedemption(
378
+ partyId: string,
379
+ fields: { inviteKey: string; usageStampId: string; peerKey: string },
380
+ inviteSig: string,
381
+ peerSig: string,
382
+ ): boolean {
383
+ try {
384
+ return verifyB64(cadreInviteRedeemDigest(partyId, fields.inviteKey, fields.usageStampId, fields.peerKey), inviteSig, fields.inviteKey)
385
+ && verifyB64(cadreInviteConsentDigest(partyId, fields.inviteKey, fields.usageStampId, fields.peerKey), peerSig, fields.peerKey);
386
+ } catch (error) {
387
+ log('verifyCadreInviteRedemption failed: %o', error);
388
+ return false;
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Is an invitation-admitted `CadrePeer` row (`vouchSig` null, `vouchUsage` set) a
394
+ * member this node should trust? The read-side mirror of the consent branch of
395
+ * `CadrePeer.AuthorizedInsert`, re-checked against THIS node's anchor because the
396
+ * replicated `OwnerKey` table can be polluted. The chain is
397
+ *
398
+ * row --vouchUsage--> usage --inviteKey--> invitation --issuerKey--> anchored owner
399
+ *
400
+ * and every link is verified: the issuer is anchored (`isAnchored`) and is the row's
401
+ * `vouchOwner`; the usage is the row's `vouchUsage`, names this peer id and this exact row
402
+ * incarnation (`peerStampId`), and names this invitation; a targeted invitation names the
403
+ * redeeming device; the stored `peerKey` really is the key behind the usage's `peerId` (the
404
+ * schema cannot unwrap a multihash, so a writer could assert any pair); the invitation's
405
+ * stored `'add'` signature verifies over the row rebuilt from its columns; the holder's
406
+ * `'redeem'` signature verifies with the invitation key and the device's `'consent'`
407
+ * signature with its own key. All three signatures are judged for `partyId`. A machine
408
+ * invitation admits a machine and nothing else, so no `OwnerKey` row is ever verified
409
+ * through this chain; a grant-seated owner row is {@link verifyOwnerGrantAdmission}'s.
410
+ *
411
+ * Expiry, use count and withdrawal are deliberately NOT re-checked: they were conditions
412
+ * at redemption (`CadreInviteUsage.Authorized`), and membership persists until an owner
413
+ * removes the row — exactly as an owner-vouched row's membership does. Keeping a device
414
+ * out is removing its row AND withdrawing the invitation.
415
+ *
416
+ * Returns a boolean and never throws (the siblings' contract): malformed input or any
417
+ * crypto failure resolves to `false`, logged at debug.
418
+ */
419
+ export function verifyInvitationAdmission(
420
+ partyId: string,
421
+ row: CadrePeerVoucherFields,
422
+ usage: CadreInviteUsageRow,
423
+ invite: CadreInviteRow,
424
+ isAnchored: (ownerKey: string) => boolean,
425
+ ): boolean {
426
+ try {
427
+ return row.stampId !== null
428
+ && row.vouchOwner !== null
429
+ && row.vouchUsage !== null
430
+ && isAnchored(row.vouchOwner)
431
+ && invite.issuerKey === row.vouchOwner
432
+ && usage.usageStampId === row.vouchUsage
433
+ && usage.peerStampId === row.stampId
434
+ && usage.peerId === row.peerId
435
+ && usage.inviteKey === invite.key
436
+ && (invite.peerId === null || invite.peerId === usage.peerId)
437
+ && ed25519PublicKeyB64FromPeerId(usage.peerId) === usage.peerKey
438
+ && verifyB64(cadreInviteAddDigest(partyId, invite), invite.issuerSig, invite.issuerKey)
439
+ && verifyB64(cadreInviteRedeemDigest(partyId, invite.key, usage.usageStampId, usage.peerKey), usage.inviteSig, invite.key)
440
+ && verifyB64(cadreInviteConsentDigest(partyId, invite.key, usage.usageStampId, usage.peerKey), usage.peerSig, usage.peerKey);
441
+ } catch (error) {
442
+ log('verifyInvitationAdmission failed: %o', error);
443
+ return false;
444
+ }
445
+ }
446
+
447
+ /**
448
+ * Canonical digest a machine signs to state its own peer id in one strand, with its own
449
+ * identity key rather than an owner key. The field list follows the row's role
450
+ * (`strandPeerRowFields`), so a stored row signed over the other form fails
451
+ * {@link verifyStrandPeerRow} and is dropped like any forged row. SQL mirror: `StrandPeer.Authorized`.
452
+ */
453
+ export function strandPeerAddDigest(partyId: string, row: StrandPeerSignedFields): string {
454
+ return taggedDigest('CadreControl.StrandPeer', 'add', partyId, strandPeerRowFields(row));
455
+ }
456
+
457
+ /**
458
+ * Was a `StrandPeer` row signed by the machine it names, in `partyId`? Verified against the key
459
+ * derived from `peerId`, not against `CadrePeer.PublicKey` as the schema's check does, because
460
+ * that column is written by whoever seated the row and a replicated row never meets the check.
461
+ * Whether `peerId` is a machine of this party is the caller's question. Never throws.
462
+ */
463
+ export function verifyStrandPeerRow(partyId: string, row: StrandPeerRow): boolean {
464
+ try {
465
+ const publicKey = ed25519PublicKeyB64FromPeerId(row.peerId);
466
+ return publicKey !== null && verifyB64(strandPeerAddDigest(partyId, row), row.sig, publicKey);
467
+ } catch (error) {
468
+ log('verifyStrandPeerRow failed: %o', error);
469
+ return false;
470
+ }
471
+ }
472
+
473
+ /**
474
+ * Canonical digest an owner signs to seat an `OwnerGrant` row — the read-side mirror of
475
+ * `ownerGrantAddMessage` in control-database.ts, base64url instead of raw bytes. The whole
476
+ * row is bound, the label included, through the one field builder both sides share
477
+ * (`ownerGrantRowFields`). SQL mirror: `OwnerGrant.AuthorizedInsert`.
478
+ */
479
+ export function ownerGrantAddDigest(partyId: string, row: OwnerGrantSignedFields): string {
480
+ return taggedDigest('CadreControl.OwnerGrant', 'add', partyId, ownerGrantRowFields(row));
481
+ }
482
+
483
+ /**
484
+ * Canonical digest the HOLDER of an `OwnerGrant`'s private key signs to redeem it once:
485
+ * proof of possession, verified against the grant key itself
486
+ * (`OwnerGrantUsage.GrantPossessed`). Binds the redemption's nonce and the key being seated,
487
+ * so one redemption cannot be re-presented for another key or another use. Mirror of
488
+ * `ownerGrantRedeemMessage` in control-database.ts.
489
+ */
490
+ export function ownerGrantRedeemDigest(partyId: string, grantKey: string, usageStampId: string, seatedKey: string): string {
491
+ return taggedDigest('CadreControl.OwnerGrantUsage', 'redeem', partyId, [grantKey, usageStampId, seatedKey]);
492
+ }
493
+
494
+ /**
495
+ * Canonical digest the key being SEATED signs to prove it is held by the redeemer
496
+ * (`OwnerGrantUsage.OwnerConsented`), over the same fields as {@link ownerGrantRedeemDigest}
497
+ * under a distinct action tag, so the holder's and the key's signatures are never
498
+ * interchangeable. Mirror of `ownerGrantConsentMessage` in control-database.ts.
499
+ */
500
+ export function ownerGrantConsentDigest(partyId: string, grantKey: string, usageStampId: string, seatedKey: string): string {
501
+ return taggedDigest('CadreControl.OwnerGrantUsage', 'consent', partyId, [grantKey, usageStampId, seatedKey]);
502
+ }
503
+
504
+ /**
505
+ * Does an `OwnerGrant` row carry a valid `'add'` signature by its own `issuerKey`, for
506
+ * `partyId`? The grant twin of {@link verifyCadreInviteRow}, with the same contract: whether
507
+ * that issuer IS an owner is the caller's question, and a malformed row verifies as `false`.
508
+ */
509
+ export function verifyOwnerGrantRow(partyId: string, grant: OwnerGrantRow): boolean {
510
+ try {
511
+ return verifyB64(ownerGrantAddDigest(partyId, grant), grant.issuerSig, grant.issuerKey);
512
+ } catch (error) {
513
+ log('verifyOwnerGrantRow failed: %o', error);
514
+ return false;
515
+ }
516
+ }
517
+
518
+ /**
519
+ * The two signatures an owner-grant redemption carries, checked before any database work:
520
+ * the holder's `'redeem'` signature with the grant key and the seated key's `'consent'`
521
+ * signature with itself, both over (`grantKey`, `usageStampId`, `seatedKey`). The grant twin
522
+ * of {@link verifyCadreInviteRedemption}, with the same contract: the schema
523
+ * (`OwnerGrantUsage.GrantPossessed` / `OwnerConsented`) stays the authority, this turns a bad
524
+ * signature into a clean refusal instead of a constraint failure at commit. Never throws.
525
+ */
526
+ export function verifyOwnerGrantRedemption(
527
+ partyId: string,
528
+ fields: { grantKey: string; usageStampId: string; seatedKey: string },
529
+ grantSig: string,
530
+ ownerSig: string,
531
+ ): boolean {
532
+ try {
533
+ return verifyB64(ownerGrantRedeemDigest(partyId, fields.grantKey, fields.usageStampId, fields.seatedKey), grantSig, fields.grantKey)
534
+ && verifyB64(ownerGrantConsentDigest(partyId, fields.grantKey, fields.usageStampId, fields.seatedKey), ownerSig, fields.seatedKey);
535
+ } catch (error) {
536
+ log('verifyOwnerGrantRedemption failed: %o', error);
537
+ return false;
538
+ }
539
+ }
540
+
541
+ /**
542
+ * Is a grant-seated `OwnerKey` row (`vouchSig` null, `vouchUsage` naming an `OwnerGrantUsage`
543
+ * row) an owner this node should derive into its anchor? The read-side mirror of the grant
544
+ * branch of `OwnerKey.Authorized` (`owner-anchor-sync.ts` → `deriveOwnerAnchor`). The chain is
545
+ *
546
+ * row --vouchUsage--> usage --grantKey--> grant --issuerKey--> anchored owner
547
+ *
548
+ * and every link is verified: the issuer is anchored and is the row's `vouchOwner`; the usage
549
+ * is the row's `vouchUsage` and names this key and this exact row incarnation
550
+ * (`seatedStampId`); the usage names this grant; the row carries the grant's label; the
551
+ * grant's stored `'add'` signature verifies over the row rebuilt from its columns; the
552
+ * holder's `'redeem'` signature verifies with the grant key and the seated key's `'consent'`
553
+ * signature with itself. All three signatures are judged for `partyId`.
554
+ *
555
+ * Expiry, use count and withdrawal are deliberately NOT re-checked, as
556
+ * {@link verifyInvitationAdmission} omits them: they were conditions at redemption
557
+ * (`OwnerGrantUsage.Authorized`), and ownership persists until an owner removes the row.
558
+ * Same never-throws contract as the siblings.
559
+ */
560
+ export function verifyOwnerGrantAdmission(
561
+ partyId: string,
562
+ row: OwnerKeyRow,
563
+ usage: OwnerGrantUsageRow,
564
+ grant: OwnerGrantRow,
565
+ isAnchored: (ownerKey: string) => boolean,
566
+ ): boolean {
567
+ try {
568
+ return row.vouchOwner !== null
569
+ && row.vouchUsage !== null
570
+ && isAnchored(row.vouchOwner)
571
+ && grant.issuerKey === row.vouchOwner
572
+ && usage.usageStampId === row.vouchUsage
573
+ && usage.seatedKey === row.key
574
+ && usage.seatedStampId === row.stampId
575
+ && usage.grantKey === grant.key
576
+ && (grant.label ?? '') === (row.label ?? '')
577
+ && verifyB64(ownerGrantAddDigest(partyId, grant), grant.issuerSig, grant.issuerKey)
578
+ && verifyB64(ownerGrantRedeemDigest(partyId, grant.key, usage.usageStampId, usage.seatedKey), usage.grantSig, grant.key)
579
+ && verifyB64(ownerGrantConsentDigest(partyId, grant.key, usage.usageStampId, usage.seatedKey), usage.ownerSig, usage.seatedKey);
580
+ } catch (error) {
581
+ log('verifyOwnerGrantAdmission failed: %o', error);
582
+ return false;
583
+ }
584
+ }