@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,740 +1,741 @@
1
- /**
2
- * Cadre invitation redemption transport: `/sereus/cadre-invite/1.0.0`.
3
- *
4
- * A device holding a cadre invitation (an owner-signed `CadreInvite` row plus the private
5
- * half of the invitation keypair, see {@link CadreInvitation}) dials ANY member machine the
6
- * invitation names and proves possession; the member seats the row if it does not hold it
7
- * yet, writes the device's `CadrePeer` row (and `OwnerKey` row, when the invitation grants
8
- * ownership) through `ControlDatabase.redeemCadreInvite`, and answers with the party id,
9
- * the row and dial hints. The owner that minted the invitation need not be online.
10
- *
11
- * The exchange shape — one frame each way, the member's hardening and admission of the
12
- * device, the device's address-by-address dialing in passes — is `member-redemption.ts`'s,
13
- * shared with the owner-grant protocol; this module supplies the invitation's bundle, request,
14
- * checks, writes and refusal codes. Stranger-facing by design — the device is not a member
15
- * when it dials — so the connection gate admits a stranger while a live invitation exists
16
- * (`membership-connection-gater.ts`), and the handler's own trust decision is the proof of
17
- * possession: nothing touches the database for a caller that cannot prove it holds the
18
- * invitation and is the identity it names.
19
- *
20
- * The seed protocol is left untouched so `SeedMessage` can grow independently.
21
- */
22
-
23
- import debug from 'debug';
24
- import { multiaddr } from '@multiformats/multiaddr';
25
- import type { Libp2p } from '@libp2p/interface';
26
- import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
27
- import { sign } from '@optimystic/quereus-plugin-crypto';
28
- import {
29
- cadreInviteRedeemMessage,
30
- cadreInviteConsentMessage,
31
- CadreInviteIssuerUnknownError,
32
- InvitationExhaustedError,
33
- type ControlDatabase
34
- } from './control-database.js';
35
- import { verifyCadreInviteRow, verifyCadreInviteRedemption } from './peer-authorization.js';
36
- import { verifyPeerRecordSignature } from './peer-record.js';
37
- import { ed25519PublicKeyB64FromPeerId } from './ed25519-key.js';
38
- import { CADRE_INVITATION_PREFIX, CADRE_JOIN_REQUEST_PREFIX, OWNER_GRANT_PREFIX, OWNER_KEY_EXPORT_STEM } from './cadre-join-request.js';
39
- import {
40
- MemberRedemptionHandler,
41
- constraintRefusal,
42
- dialRedemption,
43
- dialRedemptionInPasses,
44
- isBoundedString,
45
- isEd25519KeyB64,
46
- isNullableBoundedString,
47
- isNullableUseCap,
48
- rejection,
49
- writeFailureRefusal,
50
- type ConstraintRefusalRow,
51
- type MemberRedemption,
52
- type MemberRedemptionHandlerOptions,
53
- type MemberRedemptionOptions,
54
- type MemberRedemptionPassOptions,
55
- type RedemptionAddressOutcome,
56
- type RedemptionRejection
57
- } from './member-redemption.js';
58
- import type { CadreInviteRow, CadreJoinProgress, PeerAddressRecord, SeedPeer } from './types.js';
59
-
60
- const log = debug('sereus:cadre:invite-proto');
61
-
62
- /** Protocol id for cadre invitation redemption (parallel to `/sereus/seed/1.0.0`). */
63
- export const CADRE_INVITE_PROTOCOL = '/sereus/cadre-invite/1.0.0';
64
-
65
- /** What the dialer calls the credential in log lines, deadline labels and error text. */
66
- const LABEL = 'Cadre invitation';
67
-
68
- /** Most addresses a request may carry for the device, and a reply per peer (`sanitizeAddrs`). */
69
- const MAX_ADDRS = 16;
70
-
71
- /** Most machines an invitation bundle may name; the issuer caps its own list far below this. */
72
- const MAX_BUNDLE_MEMBERS = 64;
73
-
74
- /** Most peers a reply may carry as dial hints. */
75
- const MAX_REPLY_PEERS = 256;
76
-
77
- // ── The invitation bundle ────────────────────────────────────────────────────
78
-
79
- /**
80
- * What an owner hands out (QR, paste, link) and a device redeems. An invitation is an
81
- * ed25519 keypair: the row holds the public half, `invitePrivateKey` is the proof of
82
- * possession, and whoever holds this bundle can redeem it — treat it as a bearer
83
- * credential for the row's lifetime. It admits a machine and grants nothing else; an owner
84
- * grant (`owner-grant-protocol.ts`) is the credential that makes a key an owner.
85
- *
86
- * Carrying the signed row is what makes redemption work at a member that has not received
87
- * the row by replication: the member seats it from the bundle under its stored issuer
88
- * signature. The row's own signature covers every column, so a bundle whose row was
89
- * altered cannot be seated anywhere.
90
- */
91
- export interface CadreInvitation {
92
- v: 1;
93
- /** The cadre the invitation joins; a device refuses one for another party. */
94
- partyId: string;
95
- /** The invitation's ed25519 seed, base64url: the proof of possession. */
96
- invitePrivateKey: string;
97
- /** The owner-signed row exactly as issued (`ControlDatabase.insertCadreInvite`). */
98
- invite: CadreInviteRow;
99
- /**
100
- * The issuer's anchored owner keys. The redeeming device pins them before it dials
101
- * (`CadreNode.trustOwnerKeys`) and checks the member's reply against them. Sourced from
102
- * the issuer's node-local anchor only, never the replicated `OwnerKey` table, for the
103
- * reason the seed invite gives: the device anchors whatever arrives here.
104
- */
105
- ownerKeys: string[];
106
- /**
107
- * Multiaddrs ending in `/p2p/<peerId>`: the issuer's own first, then other members', at
108
- * most `CADRE_INVITATION_MAX_ADDRS` in all (`selectCadreInvitationMembers` in
109
- * `invitation-bootstrap.ts`). The device tries them in order.
110
- */
111
- members: string[];
112
- }
113
-
114
- /**
115
- * Encode a bundle for out-of-band delivery: {@link CADRE_INVITATION_PREFIX}, then base64url
116
- * over JSON. The prefix lets an app tell an invitation from a join request
117
- * (`cadre-join-request.ts`) or an owner grant (`owner-grant-protocol.ts`) and name the mistake
118
- * when one is pasted for the other.
119
- */
120
- export function encodeCadreInvitation(invitation: CadreInvitation): string {
121
- return `${CADRE_INVITATION_PREFIX}${uint8ArrayToString(new TextEncoder().encode(JSON.stringify(invitation)), 'base64url')}`;
122
- }
123
-
124
- /**
125
- * Decode a bundle, refusing anything that is not a well-formed version-1
126
- * {@link CadreInvitation} behind {@link CADRE_INVITATION_PREFIX}. Standalone so a client
127
- * without a node (a settings screen that wants to show which cadre an invitation joins) can
128
- * decode one.
129
- *
130
- * @throws on an owner key, an owner grant or a join request, a string without the prefix or
131
- * that is not base64url JSON after it, or one that decodes to another shape or version.
132
- */
133
- export function decodeCadreInvitation(encoded: string): CadreInvitation {
134
- const trimmed = encoded.trim();
135
- if (trimmed.startsWith(OWNER_KEY_EXPORT_STEM)) {
136
- throw new Error('This is an owner key, not a cadre invitation; it is private, so import it only where the app asks for an owner key');
137
- }
138
- if (trimmed.startsWith(OWNER_GRANT_PREFIX)) {
139
- throw new Error('This is an owner grant, not a cadre invitation; paste it where the app asks for an owner grant');
140
- }
141
- if (trimmed.startsWith(CADRE_JOIN_REQUEST_PREFIX)) {
142
- throw new Error('This is a join request, not a cadre invitation; paste it into the app that manages your cadre');
143
- }
144
- if (!trimmed.startsWith(CADRE_INVITATION_PREFIX)) {
145
- throw new Error(`Cadre invitation must start with "${CADRE_INVITATION_PREFIX}" (this one starts with "${trimmed.slice(0, CADRE_INVITATION_PREFIX.length)}")`);
146
- }
147
- let parsed: unknown;
148
- try {
149
- parsed = JSON.parse(new TextDecoder().decode(uint8ArrayFromString(trimmed.slice(CADRE_INVITATION_PREFIX.length), 'base64url')));
150
- } catch (error) {
151
- throw new Error('Cadre invitation does not decode as base64url JSON', { cause: error });
152
- }
153
- if (!isWellFormedCadreInvitation(parsed)) {
154
- throw new Error('Cadre invitation is malformed or of an unsupported version');
155
- }
156
- return parsed;
157
- }
158
-
159
- function isWellFormedCadreInvitation(value: unknown): value is CadreInvitation {
160
- if (typeof value !== 'object' || value === null) return false;
161
- const { v, partyId, invitePrivateKey, invite, ownerKeys, members } = value as Record<string, unknown>;
162
- return v === 1
163
- && isBoundedString(partyId)
164
- && isEd25519KeyB64(invitePrivateKey)
165
- && isWellFormedCadreInviteRow(invite)
166
- && Array.isArray(ownerKeys) && ownerKeys.length > 0 && ownerKeys.every((key) => isEd25519KeyB64(key))
167
- && Array.isArray(members) && members.length <= MAX_BUNDLE_MEMBERS && members.every((addr) => isBoundedString(addr));
168
- }
169
-
170
- // ── Wire messages ────────────────────────────────────────────────────────────
171
-
172
- /**
173
- * The device's own address record as a request carries it: a {@link PeerAddressRecord} without
174
- * the peer id, which the connection gives, and the key, which is the request's `peerKey`.
175
- */
176
- export type RedeemSelfRecord = Pick<PeerAddressRecord, 'addrs' | 'updatedAt' | 'profile' | 'sig'>;
177
-
178
- /** Device → member: one frame, the whole redemption. */
179
- export interface CadreInviteRedeemRequest {
180
- v: 2;
181
- /** The cadre the device believes it is joining; a machine serving another party refuses by name. */
182
- partyId: string;
183
- /** The owner-signed row from the bundle. */
184
- invite: CadreInviteRow;
185
- /** The device's ed25519 public key, base64url; must be the key behind the connecting peer id. */
186
- peerKey: string;
187
- /**
188
- * The device's own address record for its `CadrePeer` row, self-signed for the invitation's
189
- * party as `CadreNode.registerSelf` signs it (`signPeerRecord`); `addrs` is empty for a phone.
190
- * The member stores `addrs` and, when the signature verifies over them, the rest of the
191
- * record too ({@link admittedRecord}), so the device's first publish is its admission.
192
- */
193
- record: RedeemSelfRecord;
194
- /** Single-use nonce the device minted (`generateStampId`); both signatures cover it. */
195
- usageStampId: string;
196
- /** By `invitePrivateKey` over the `'redeem'` digest. */
197
- inviteSig: string;
198
- /** By the device's identity key over the `'consent'` digest. */
199
- peerSig: string;
200
- }
201
-
202
- /**
203
- * Why a member refused a redemption. Retryability is {@link CADRE_INVITE_REJECTION_RETRYABLE}'s;
204
- * a retryable code moves the device to the next address the bundle names.
205
- */
206
- export type CadreInviteRejectionCode =
207
- /**
208
- * The issuer's `OwnerKey` row is not on this member (not replicated yet), or the issuer was
209
- * removed; the member cannot tell which, so the device tries the next address.
210
- */
211
- | 'issuer-unknown'
212
- /**
213
- * A signature does not verify, the peer key is not the connecting identity, the request or
214
- * the row is malformed, or the invitation names another device.
215
- */
216
- | 'invite-invalid'
217
- /** Expired, withdrawn, exhausted, or issued by a key that is no longer an owner here. */
218
- | 'invite-spent'
219
- /** This machine serves another cadre than the one the invitation names. */
220
- | 'party-mismatch'
221
- /** The member is at its cap on concurrent redemptions. */
222
- | 'busy'
223
- /** The write failed transiently (the write retry gave up), or the member has not synced the invitation row the cadre holds; nothing was recorded. */
224
- | 'conflict'
225
- /**
226
- * An unexpected member-side failure, or a request frame the member could not read (timed
227
- * out, oversized, not JSON): nothing was proved either way, so the device tries the next
228
- * address, as the formation responder's `internal` is read.
229
- */
230
- | 'internal';
231
-
232
- /** Which refusals are worth repeating at the next address — the one place that says so. */
233
- export const CADRE_INVITE_REJECTION_RETRYABLE: Readonly<Record<CadreInviteRejectionCode, boolean>> = {
234
- 'issuer-unknown': true,
235
- 'invite-invalid': false,
236
- 'invite-spent': false,
237
- 'party-mismatch': false,
238
- 'busy': true,
239
- 'conflict': true,
240
- 'internal': true
241
- };
242
-
243
- /** Is `value` a code this build knows? Own keys only, so a peer's `'constructor'` does not pass. */
244
- export function isCadreInviteRejectionCode(value: unknown): value is CadreInviteRejectionCode {
245
- return typeof value === 'string' && Object.prototype.hasOwnProperty.call(CADRE_INVITE_REJECTION_RETRYABLE, value);
246
- }
247
-
248
- /** Member → device. */
249
- export interface CadreInviteRedeemReply {
250
- accepted: boolean;
251
- /** Present iff `!accepted`. */
252
- code?: CadreInviteRejectionCode;
253
- /** Human-facing text; present iff `!accepted`. */
254
- reason?: string;
255
- /** The member's party id; present iff `accepted`. */
256
- partyId?: string;
257
- /** The invitation row as this member holds it; present iff `accepted`. */
258
- invite?: CadreInviteRow;
259
- /**
260
- * Dial hints for the rest of the cadre, unsigned: the member's own projection of its
261
- * `CadrePeer` rows (`ControlDatabase.querySeedPeers`), the answering member and every
262
- * always-on machine marked `preferred`. The device derives trust from its anchor, never
263
- * from this.
264
- */
265
- peers?: SeedPeer[];
266
- }
267
-
268
- /** An accepting reply, every optional field present. */
269
- export interface CadreInviteAccepted extends CadreInviteRedeemReply {
270
- accepted: true;
271
- partyId: string;
272
- invite: CadreInviteRow;
273
- peers: SeedPeer[];
274
- }
275
-
276
- /** A refusal as the member sends it: a code, a reason, nothing else. */
277
- type CadreInviteRejection = RedemptionRejection<CadreInviteRejectionCode>;
278
-
279
- // ── Errors the device sees ───────────────────────────────────────────────────
280
-
281
- /**
282
- * A member answered and refused. `code` is `'unrecognized'` when the frame carried none this
283
- * build knows (the two machines may run different versions), and such a refusal counts as
284
- * retryable: trying the next address on an unknown answer is safe, giving up is not.
285
- */
286
- export class CadreInviteRejectedError extends Error {
287
- readonly code: CadreInviteRejectionCode | 'unrecognized';
288
- readonly reason: string;
289
- readonly retryable: boolean;
290
-
291
- /** Both arguments come straight off the wire, so neither is trusted to have its declared type. */
292
- constructor(code: unknown, reason: unknown) {
293
- const text = typeof reason === 'string' ? reason : 'no reason provided';
294
- super(`Cadre invitation refused: ${text}`);
295
- this.name = 'CadreInviteRejectedError';
296
- this.code = isCadreInviteRejectionCode(code) ? code : 'unrecognized';
297
- this.reason = text;
298
- this.retryable = this.code === 'unrecognized' || CADRE_INVITE_REJECTION_RETRYABLE[this.code];
299
- }
300
- }
301
-
302
- /** What one address the bundle named came to; the owner-grant redemption reports the same shape. */
303
- export type CadreInviteAddressOutcome = RedemptionAddressOutcome;
304
-
305
- /**
306
- * Every address the bundle names was tried and none accepted: each failed to dial, answered
307
- * malformed, or refused retryably. Always retryable; `outcomes` says what each address did.
308
- */
309
- export class CadreInviteUnreachableError extends Error {
310
- readonly retryable = true;
311
-
312
- constructor(readonly outcomes: readonly CadreInviteAddressOutcome[]) {
313
- super(outcomes.length === 0
314
- ? 'Cadre invitation names no dialable member'
315
- : `Cadre invitation could not be redeemed at any of its ${outcomes.length} address(es): `
316
- + outcomes.map((outcome) => `${outcome.addr}: ${outcome.error.message}`).join('; '));
317
- this.name = 'CadreInviteUnreachableError';
318
- }
319
- }
320
-
321
- /**
322
- * A member accepted but its reply does not check out: another party id, another invitation
323
- * key, or a row not signed by one of the pinned owner keys. Final: a machine that answers
324
- * like this is not a member of the cadre the invitation names, and the row it wrote (if any)
325
- * is in a database the device will never trust.
326
- */
327
- export class CadreInviteReplyInvalidError extends Error {
328
- readonly retryable = false;
329
-
330
- constructor(message: string) {
331
- super(`Cadre invitation reply refused: ${message}`);
332
- this.name = 'CadreInviteReplyInvalidError';
333
- }
334
- }
335
-
336
- // ── Shape checks (both directions) ───────────────────────────────────────────
337
-
338
- /** Is `value` a {@link CadreInviteRow} with every column in its stored form and bounded? */
339
- export function isWellFormedCadreInviteRow(value: unknown): value is CadreInviteRow {
340
- if (typeof value !== 'object' || value === null) return false;
341
- const row = value as Record<string, unknown>;
342
- return isEd25519KeyB64(row.key)
343
- && isNullableBoundedString(row.peerId)
344
- && isNullableBoundedString(row.expiresAt)
345
- && isNullableUseCap(row.totalUses)
346
- && isBoundedString(row.stampId)
347
- && isEd25519KeyB64(row.issuerKey)
348
- && isBoundedString(row.issuerSig);
349
- }
350
-
351
- /**
352
- * The record's other fields are left to {@link admittedRecord}: a bad value there costs the
353
- * device its signature on the row, not its admission.
354
- */
355
- function isWellFormedRedeemRequest(value: unknown): value is CadreInviteRedeemRequest {
356
- if (typeof value !== 'object' || value === null) return false;
357
- const { v, partyId, invite, peerKey, record, usageStampId, inviteSig, peerSig } = value as Record<string, unknown>;
358
- return v === 2
359
- && isBoundedString(partyId)
360
- && isWellFormedCadreInviteRow(invite)
361
- && isEd25519KeyB64(peerKey)
362
- && typeof record === 'object' && record !== null && Array.isArray((record as Record<string, unknown>).addrs)
363
- && isBoundedString(usageStampId)
364
- && isBoundedString(inviteSig)
365
- && isBoundedString(peerSig);
366
- }
367
-
368
- /** What the member writes on the device's `CadrePeer` row from the request's record. */
369
- interface AdmittedRecord {
370
- /** The record's addresses, sanitized ({@link sanitizeAddrs}): stored whether or not the rest is. */
371
- addrs: string[];
372
- /** The record's freshness, profile and signature, or null when they cannot be stored as the device's own. */
373
- signed: Pick<PeerAddressRecord, 'updatedAt' | 'profile' | 'sig'> | null;
374
- /** Why `signed` is null; absent when it is not. */
375
- unsignedBecause?: string;
376
- }
377
-
378
- /**
379
- * Judge the device's record (`request.record`) for its admission row. The signature covers the
380
- * exact address list, so it is kept only when sanitizing dropped nothing, the profile is one the
381
- * schema's `KnownProfile` check admits, the stamp and signature are in their stored forms, and
382
- * the signature verifies for `partyId` under the device's key. Anything less admits the device
383
- * with its addresses and no signature, as an owner-written row is, and the device's next
384
- * publish fills it in. No clock check: a stamp in the future or the past is one the device's own
385
- * self-publish could write too.
386
- */
387
- function admittedRecord(partyId: string, remotePeerId: string, request: Pick<CadreInviteRedeemRequest, 'peerKey' | 'record'>): AdmittedRecord {
388
- const { addrs: offered, updatedAt, profile, sig } = request.record as Partial<Record<keyof RedeemSelfRecord, unknown>>;
389
- const addrs = sanitizeAddrs(offered);
390
- const unsigned = (because: string): AdmittedRecord => ({ addrs, signed: null, unsignedBecause: because });
391
- // Sanitizing only drops entries, so an unchanged length is an unchanged list.
392
- if (!Array.isArray(offered) || addrs.length !== offered.length) {
393
- return unsigned('sanitizing changed the signed address list');
394
- }
395
- if (profile !== null && profile !== 'transaction' && profile !== 'storage') {
396
- return unsigned('unknown profile');
397
- }
398
- if (typeof updatedAt !== 'number' || !Number.isSafeInteger(updatedAt) || updatedAt <= 0 || !isBoundedString(sig)) {
399
- return unsigned('malformed stamp or signature');
400
- }
401
- if (!verifyPeerRecordSignature(partyId, { peerId: remotePeerId, publicKey: request.peerKey, addrs, updatedAt, profile, sig })) {
402
- return unsigned('signature does not verify');
403
- }
404
- return { addrs, signed: { updatedAt, profile, sig } };
405
- }
406
-
407
- /**
408
- * Keep only parsable, distinct multiaddr strings, capped at {@link MAX_ADDRS}, order kept.
409
- * Applied on both sides: the member bounds what it stores on the device's row, the device
410
- * bounds what it merges into its peer store. A malformed entry is skipped, not fatal.
411
- */
412
- export function sanitizeAddrs(addrs: unknown): string[] {
413
- if (!Array.isArray(addrs)) return [];
414
- const out: string[] = [];
415
- const seen = new Set<string>();
416
- for (const entry of addrs) {
417
- if (out.length >= MAX_ADDRS) break;
418
- if (!isBoundedString(entry) || seen.has(entry)) continue;
419
- try {
420
- multiaddr(entry);
421
- } catch (error) {
422
- log('addrs: skipping unparsable entry: %o', error);
423
- continue;
424
- }
425
- seen.add(entry);
426
- out.push(entry);
427
- }
428
- return out;
429
- }
430
-
431
- /** The reply's peer list, bounded and each entry's addresses sanitized; anything else dropped. */
432
- function sanitizePeers(peers: unknown): SeedPeer[] {
433
- if (!Array.isArray(peers)) return [];
434
- const out: SeedPeer[] = [];
435
- for (const entry of peers) {
436
- if (out.length >= MAX_REPLY_PEERS) break;
437
- if (typeof entry !== 'object' || entry === null) continue;
438
- const { peerId, multiaddrs, preferred } = entry as Record<string, unknown>;
439
- if (!isBoundedString(peerId)) continue;
440
- out.push({ peerId, multiaddrs: sanitizeAddrs(multiaddrs), preferred: preferred === true });
441
- }
442
- return out;
443
- }
444
-
445
- /** An acceptance frame's fields, the attacker-influenced ones sanitized. Throws on a malformed one. */
446
- function decodeAccepted(reply: Record<string, unknown>): CadreInviteAccepted {
447
- if (!isBoundedString(reply.partyId) || !isWellFormedCadreInviteRow(reply.invite)) {
448
- throw new Error('Cadre invitation acceptance is missing its party id or a well-formed row');
449
- }
450
- return { accepted: true, partyId: reply.partyId, invite: reply.invite, peers: sanitizePeers(reply.peers) };
451
- }
452
-
453
- // ── Request construction (device side) ───────────────────────────────────────
454
-
455
- /** What the device signs with: its identity keypair in the crypto plugin's base64url form. */
456
- export interface RedeemSigner {
457
- /** The device's ed25519 public key, base64url — the key behind its peer id. */
458
- peerKey: string;
459
- /** The device's ed25519 seed, base64url. */
460
- peerPrivateKey: string;
461
- }
462
-
463
- /**
464
- * Build and sign the request for `invitation`: the holder's `'redeem'` signature with the
465
- * invitation's private key and the device's `'consent'` signature with its own, both over
466
- * (invitation key, `usageStampId`, device key) for the invitation's party. The same bytes
467
- * the schema verifies at the member (`cadreInviteRedeemMessage` / `cadreInviteConsentMessage`),
468
- * whose own `party_id()` must therefore be the party the bundle names.
469
- *
470
- * @param record - the device's address record, already signed for the invitation's party over
471
- * sanitized addresses ({@link sanitizeAddrs}); copied in unchanged, since the signature
472
- * covers the exact list.
473
- */
474
- export function signRedeemRequest(
475
- invitation: CadreInvitation,
476
- signer: RedeemSigner,
477
- usageStampId: string,
478
- record: RedeemSelfRecord
479
- ): CadreInviteRedeemRequest {
480
- const fields = { inviteKey: invitation.invite.key, usageStampId, peerKey: signer.peerKey };
481
- const signB64 = (message: Uint8Array, privateKey: string): string =>
482
- sign(message, privateKey, 'ed25519', 'bytes', 'base64url', 'base64url') as string;
483
- return {
484
- v: 2,
485
- partyId: invitation.partyId,
486
- invite: invitation.invite,
487
- peerKey: signer.peerKey,
488
- record: { addrs: [...record.addrs], updatedAt: record.updatedAt, profile: record.profile, sig: record.sig },
489
- usageStampId,
490
- inviteSig: signB64(cadreInviteRedeemMessage(invitation.partyId, fields), invitation.invitePrivateKey),
491
- peerSig: signB64(cadreInviteConsentMessage(invitation.partyId, fields), signer.peerPrivateKey)
492
- };
493
- }
494
-
495
- /**
496
- * The device's check on an acceptance: the same party, the same invitation key, and a row
497
- * signed by an issuer the device pinned from the bundle. Throws
498
- * {@link CadreInviteReplyInvalidError} naming the first failure.
499
- *
500
- * What it proves is bounded: the request already carried the owner-signed row, so a machine
501
- * that is not a member can echo it. The check catches a reply for another party or
502
- * invitation and a row the pinned owners never signed; whether the answering machine is a
503
- * member is settled afterwards, when the device syncs the control database and judges every
504
- * row against its anchor (`CadreNode.listAuthorizedMembers`).
505
- */
506
- export function verifyRedeemReply(
507
- reply: CadreInviteAccepted,
508
- invitation: CadreInvitation,
509
- isTrustedIssuer: (ownerKey: string) => boolean
510
- ): void {
511
- if (reply.partyId !== invitation.partyId) {
512
- throw new CadreInviteReplyInvalidError(`the member serves party ${reply.partyId}, the invitation names ${invitation.partyId}`);
513
- }
514
- if (reply.invite.key !== invitation.invite.key) {
515
- throw new CadreInviteReplyInvalidError('the member answered for a different invitation');
516
- }
517
- if (!isTrustedIssuer(reply.invite.issuerKey)) {
518
- throw new CadreInviteReplyInvalidError('the row the member holds is not issued by one of the invitation\'s owner keys');
519
- }
520
- if (!verifyCadreInviteRow(invitation.partyId, reply.invite)) {
521
- throw new CadreInviteReplyInvalidError('the row the member holds is not signed by its issuer');
522
- }
523
- }
524
-
525
- // ── Member side (handler) ────────────────────────────────────────────────────
526
-
527
- /** The control-database surface a redemption needs; a `ControlDatabase` satisfies it. */
528
- export type CadreInviteStore = Pick<ControlDatabase, 'queryCadreInvite' | 'seatCadreInvite' | 'isCadreInviteLive' | 'redeemCadreInvite' | 'querySeedPeers'>;
529
-
530
- export interface CadreInviteHandlerOptions extends MemberRedemptionHandlerOptions {
531
- /** This member's peer id: the reply's peer list marks it preferred, since the device just reached it. */
532
- peerId: string;
533
- store: CadreInviteStore;
534
- }
535
-
536
- /** Constraint names the schema refuses a redemption with, and the code each maps to. */
537
- const REDEEM_CONSTRAINT_CODES: ReadonlyArray<ConstraintRefusalRow<CadreInviteRejectionCode>> = [
538
- [/CHECK constraint failed: Authorized\b/, 'invite-spent', 'The invitation is expired, withdrawn, exhausted, or its issuer is no longer an owner'],
539
- [/CHECK constraint failed: (InvitePossessed|PeerConsented|PeerExists)\b/, 'invite-invalid', 'The redemption does not satisfy the invitation'],
540
- [/CHECK constraint failed: NotRevoked\b/, 'invite-spent', 'The invitation was withdrawn'],
541
- ];
542
-
543
- /**
544
- * Member side of the invitation protocol (`MemberRedemptionHandler` has the shape): after the
545
- * request's shape, it checks the party, the connecting identity (an ed25519 peer id is an
546
- * identity multihash of the very key, and this is the only layer that can check the pair),
547
- * both signatures and a targeted invitation's device, then seats the row from the bundle when
548
- * this member holds none and redeems. An issuer this member does not know as an owner is the
549
- * one retryable refusal left: the device tries the next address, which may hold the issuer's row.
550
- */
551
- export class CadreInviteHandler extends MemberRedemptionHandler<CadreInviteRedeemRequest, CadreInviteRedeemReply, CadreInviteRow> {
552
- private readonly peerId: string;
553
- private readonly store: CadreInviteStore;
554
- protected readonly busyRefusal = rejection('busy', 'Too many concurrent redemptions');
555
- protected readonly internalRefusal = rejection('internal', 'Internal redemption error');
556
- protected readonly malformedRefusal = rejection('invite-invalid', 'Malformed redemption request');
557
-
558
- constructor(options: CadreInviteHandlerOptions) {
559
- super('Cadre invite', CADRE_INVITE_PROTOCOL, options);
560
- this.peerId = options.peerId;
561
- this.store = options.store;
562
- }
563
-
564
- protected isWellFormedRequest(value: unknown): value is CadreInviteRedeemRequest {
565
- return isWellFormedRedeemRequest(value);
566
- }
567
-
568
- protected checkRequest(request: CadreInviteRedeemRequest, remotePeerId: string): CadreInviteRejection | null {
569
- if (request.partyId !== this.partyId) {
570
- return rejection('party-mismatch', 'This machine serves another cadre');
571
- }
572
- if (ed25519PublicKeyB64FromPeerId(remotePeerId) !== request.peerKey) {
573
- return rejection('invite-invalid', 'The peer key is not the connecting identity');
574
- }
575
- const fields = { inviteKey: request.invite.key, usageStampId: request.usageStampId, peerKey: request.peerKey };
576
- if (!verifyCadreInviteRedemption(this.partyId, fields, request.inviteSig, request.peerSig)) {
577
- return rejection('invite-invalid', 'The redemption signatures do not verify');
578
- }
579
- if (request.invite.peerId !== null && request.invite.peerId !== remotePeerId) {
580
- return rejection('invite-invalid', 'The invitation names another device');
581
- }
582
- return null;
583
- }
584
-
585
- protected readHeld(request: CadreInviteRedeemRequest): Promise<CadreInviteRow | null> {
586
- return this.store.queryCadreInvite(request.invite.key);
587
- }
588
-
589
- protected isLive(request: CadreInviteRedeemRequest, held: CadreInviteRow | null): Promise<boolean> {
590
- return this.store.isCadreInviteLive(request.invite, held);
591
- }
592
-
593
- /**
594
- * The two writes — the seat (its own transaction), only when this member holds no row, and
595
- * the redemption — each answered by name when it fails. The held row is carried into the
596
- * redemption so it is not read again in the write lock; after a fresh seat nothing is carried
597
- * and the redemption reads the row it seated, since the bundle's copy is the requester's.
598
- */
599
- protected async redeemAdmitted(request: CadreInviteRedeemRequest, remotePeerId: string, held: CadreInviteRow | null): Promise<CadreInviteRedeemReply> {
600
- if (held === null) {
601
- const refused = await this.seat(request, remotePeerId);
602
- if (refused) return refused;
603
- }
604
- // Built before the write: the `CadrePeer` membership view is normally warm then (the
605
- // connection gate read it when the device connected), and the redemption's commit drops it.
606
- // The list lacks the device's own row, which the device drops from it anyway.
607
- const peers = await this.peersBestEffort();
608
- const record = admittedRecord(this.partyId, remotePeerId, request);
609
- if (record.signed === null) {
610
- log('admitting %s without its own record signature: %s', remotePeerId, record.unsignedBecause);
611
- }
612
- try {
613
- const result = await this.store.redeemCadreInvite({
614
- inviteKey: request.invite.key,
615
- ...(held ? { held } : {}),
616
- peerId: remotePeerId,
617
- peerKey: request.peerKey,
618
- multiaddrs: record.addrs,
619
- ...(record.signed ? { record: record.signed } : {}),
620
- usageStampId: request.usageStampId,
621
- inviteSig: request.inviteSig,
622
- peerSig: request.peerSig
623
- });
624
- log('invitation %s redeemed by %s (alreadyMember=%s)', request.invite.key, remotePeerId, result.alreadyMember);
625
- } catch (error) {
626
- if (error instanceof InvitationExhaustedError) {
627
- return rejection('invite-spent', 'The invitation has no uses left');
628
- }
629
- log('redeeming invitation %s for %s failed: %o', request.invite.key, remotePeerId, error);
630
- return constraintRefusal(error, REDEEM_CONSTRAINT_CODES) ?? writeFailureRefusal(error);
631
- }
632
- // The row as held: read before the write, or the bundle's copy the seat inserted verbatim
633
- // or found already held (its key is the primary key and every column is under the issuer's
634
- // signature).
635
- return { accepted: true, partyId: this.partyId, invite: held ?? request.invite, peers };
636
- }
637
-
638
- /** Seat the bundle's copy of the row; a refusal answered by name, or null once it is held. */
639
- private async seat(request: CadreInviteRedeemRequest, remotePeerId: string): Promise<CadreInviteRejection | null> {
640
- try {
641
- await this.store.seatCadreInvite(request.invite);
642
- return null;
643
- } catch (error) {
644
- if (error instanceof CadreInviteIssuerUnknownError) {
645
- return rejection('issuer-unknown', 'The invitation\'s issuer is not known as an owner here');
646
- }
647
- log('seating invitation %s from %s failed: %o', request.invite.key, remotePeerId, error);
648
- return constraintRefusal(error, REDEEM_CONSTRAINT_CODES) ?? writeFailureRefusal(error);
649
- }
650
- }
651
-
652
- /** Dial hints are an optimization; a failed read costs the device its hints, not its membership. */
653
- private async peersBestEffort(): Promise<SeedPeer[]> {
654
- try {
655
- return await this.store.querySeedPeers(this.peerId);
656
- } catch (error) {
657
- log('peer projection for the reply failed (continuing without hints): %o', error);
658
- return [];
659
- }
660
- }
661
- }
662
-
663
- // ── Device side (dialer) ─────────────────────────────────────────────────────
664
-
665
- export interface RedeemAtMembersOptions {
666
- /** The bundle: its `members` are dialed in order. */
667
- invitation: CadreInvitation;
668
- /** The signed request ({@link signRedeemRequest}); the same one goes to every address. */
669
- request: CadreInviteRedeemRequest;
670
- /** Is this owner key one the device pinned from the bundle? The reply check's input. */
671
- isTrustedIssuer: (ownerKey: string) => boolean;
672
- /** See `MemberRedemptionOptions.linkRoundTripMs`. */
673
- linkRoundTripMs?: number;
674
- /** Per-address deadline override; default derived from `linkRoundTripMs`. */
675
- addressBudgetMs?: number;
676
- protocolId?: string;
677
- /** Cancels the dial or stream in flight and ends the pass; the call throws the signal's reason. */
678
- signal?: AbortSignal;
679
- }
680
-
681
- /** What a successful redemption yields the device. */
682
- export type CadreInviteRedemption = MemberRedemption<CadreInviteAccepted>;
683
-
684
- /** The invitation's half of the shared dial loop: its label, protocol, bundle, codec, checks and errors. */
685
- function inviteRedemption(options: RedeemAtMembersOptions): MemberRedemptionOptions<CadreInviteAccepted> {
686
- return {
687
- label: LABEL,
688
- protocolId: options.protocolId ?? CADRE_INVITE_PROTOCOL,
689
- members: options.invitation.members,
690
- request: options.request,
691
- decodeAccepted,
692
- refusal: (code, reason) => new CadreInviteRejectedError(code, reason),
693
- verifyAccepted: (reply) => verifyRedeemReply(reply, options.invitation, options.isTrustedIssuer),
694
- unreachable: (outcomes) => new CadreInviteUnreachableError(outcomes),
695
- ...(options.linkRoundTripMs !== undefined ? { linkRoundTripMs: options.linkRoundTripMs } : {}),
696
- ...(options.addressBudgetMs !== undefined ? { addressBudgetMs: options.addressBudgetMs } : {}),
697
- ...(options.signal ? { signal: options.signal } : {}),
698
- };
699
- }
700
-
701
- /**
702
- * Device side: try the bundle's addresses one at a time, each under its own deadline, and
703
- * stop at the first acceptance or the first final refusal (`dialRedemption` in
704
- * `member-redemption.ts`). Every address gets the SAME request, with one `usageStampId`:
705
- * `CadreInviteUsage` is keyed by it, so a member the device gave up on that was still
706
- * committing cannot admit it twice, and a retry at the next member after a dropped reply is
707
- * answered as already a member.
708
- *
709
- * @throws {CadreInviteRejectedError} on a final refusal (its `retryable` is false).
710
- * @throws {CadreInviteReplyInvalidError} on an acceptance that fails {@link verifyRedeemReply}.
711
- * @throws {CadreInviteUnreachableError} when every address was tried and none accepted.
712
- * @throws the reason of `options.signal` once it aborts.
713
- */
714
- export function redeemAtMembers(node: Libp2p, options: RedeemAtMembersOptions): Promise<CadreInviteRedemption> {
715
- return dialRedemption(node, inviteRedemption(options));
716
- }
717
-
718
- export interface RedeemInPassesOptions extends RedeemAtMembersOptions {
719
- /** Keep making passes while every answer is retryable; false makes exactly one. */
720
- waitForMember: boolean;
721
- /** Called at each pass and each pause; an exception it throws is logged and ignored. */
722
- onProgress?: (progress: CadreJoinProgress) => void;
723
- }
724
-
725
- /**
726
- * Device side, in passes (`dialRedemptionInPasses` in `member-redemption.ts`): one
727
- * {@link redeemAtMembers} pass, or, with `waitForMember`, as many as it takes, pausing between
728
- * them and never past the invitation's expiry, which by this device's clock is thrown as the
729
- * `invite-spent` refusal a member would give.
730
- */
731
- export function redeemInPasses(node: Libp2p, options: RedeemInPassesOptions): Promise<CadreInviteRedemption> {
732
- const passes: MemberRedemptionPassOptions<CadreInviteAccepted> = {
733
- ...inviteRedemption(options),
734
- waitForMember: options.waitForMember,
735
- expiresAt: options.invitation.invite.expiresAt,
736
- expired: () => new CadreInviteRejectedError('invite-spent', 'the invitation expired before a member accepted it'),
737
- ...(options.onProgress ? { onProgress: options.onProgress } : {}),
738
- };
739
- return dialRedemptionInPasses(node, passes);
740
- }
1
+ /**
2
+ * Cadre invitation redemption transport: `/sereus/cadre-invite/1.0.0`.
3
+ *
4
+ * A device holding a cadre invitation (an owner-signed `CadreInvite` row plus the private
5
+ * half of the invitation keypair, see {@link CadreInvitation}) dials ANY member machine the
6
+ * invitation names and proves possession; the member seats the row if it does not hold it
7
+ * yet, writes the device's `CadrePeer` row (and `OwnerKey` row, when the invitation grants
8
+ * ownership) through `ControlDatabase.redeemCadreInvite`, and answers with the party id,
9
+ * the row and dial hints. The owner that minted the invitation need not be online.
10
+ *
11
+ * The exchange shape — one frame each way, the member's hardening and admission of the
12
+ * device, the device's address-by-address dialing in passes — is `member-redemption.ts`'s,
13
+ * shared with the owner-grant protocol; this module supplies the invitation's bundle, request,
14
+ * checks, writes and refusal codes. Stranger-facing by design — the device is not a member
15
+ * when it dials — so the connection gate admits a stranger while a live invitation exists
16
+ * (`membership-connection-gater.ts`), and the handler's own trust decision is the proof of
17
+ * possession: nothing touches the database for a caller that cannot prove it holds the
18
+ * invitation and is the identity it names.
19
+ *
20
+ * The seed protocol is left untouched so `SeedMessage` can grow independently.
21
+ */
22
+
23
+ import debug from 'debug';
24
+ import { multiaddr } from '@multiformats/multiaddr';
25
+ import type { Libp2p } from '@libp2p/interface';
26
+ import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
27
+ import { sign } from '@optimystic/quereus-plugin-crypto';
28
+ import {
29
+ cadreInviteRedeemMessage,
30
+ cadreInviteConsentMessage,
31
+ CadreInviteIssuerUnknownError,
32
+ InvitationExhaustedError,
33
+ type ControlDatabase
34
+ } from './control-database.js';
35
+ import { verifyCadreInviteRow, verifyCadreInviteRedemption } from './peer-authorization.js';
36
+ import { verifyPeerRecordSignature } from './peer-record.js';
37
+ import { isPublishedProfile } from './node-class.js';
38
+ import { ed25519PublicKeyB64FromPeerId } from './ed25519-key.js';
39
+ import { CADRE_INVITATION_PREFIX, CADRE_JOIN_REQUEST_PREFIX, OWNER_GRANT_PREFIX, OWNER_KEY_EXPORT_STEM } from './cadre-join-request.js';
40
+ import {
41
+ MemberRedemptionHandler,
42
+ constraintRefusal,
43
+ dialRedemption,
44
+ dialRedemptionInPasses,
45
+ isBoundedString,
46
+ isEd25519KeyB64,
47
+ isNullableBoundedString,
48
+ isNullableUseCap,
49
+ rejection,
50
+ writeFailureRefusal,
51
+ type ConstraintRefusalRow,
52
+ type MemberRedemption,
53
+ type MemberRedemptionHandlerOptions,
54
+ type MemberRedemptionOptions,
55
+ type MemberRedemptionPassOptions,
56
+ type RedemptionAddressOutcome,
57
+ type RedemptionRejection
58
+ } from './member-redemption.js';
59
+ import type { CadreInviteRow, CadreJoinProgress, PeerAddressRecord, SeedPeer } from './types.js';
60
+
61
+ const log = debug('sereus:cadre:invite-proto');
62
+
63
+ /** Protocol id for cadre invitation redemption (parallel to `/sereus/seed/1.0.0`). */
64
+ export const CADRE_INVITE_PROTOCOL = '/sereus/cadre-invite/1.0.0';
65
+
66
+ /** What the dialer calls the credential in log lines, deadline labels and error text. */
67
+ const LABEL = 'Cadre invitation';
68
+
69
+ /** Most addresses a request may carry for the device, and a reply per peer (`sanitizeAddrs`). */
70
+ const MAX_ADDRS = 16;
71
+
72
+ /** Most machines an invitation bundle may name; the issuer caps its own list far below this. */
73
+ const MAX_BUNDLE_MEMBERS = 64;
74
+
75
+ /** Most peers a reply may carry as dial hints. */
76
+ const MAX_REPLY_PEERS = 256;
77
+
78
+ // ── The invitation bundle ────────────────────────────────────────────────────
79
+
80
+ /**
81
+ * What an owner hands out (QR, paste, link) and a device redeems. An invitation is an
82
+ * ed25519 keypair: the row holds the public half, `invitePrivateKey` is the proof of
83
+ * possession, and whoever holds this bundle can redeem it — treat it as a bearer
84
+ * credential for the row's lifetime. It admits a machine and grants nothing else; an owner
85
+ * grant (`owner-grant-protocol.ts`) is the credential that makes a key an owner.
86
+ *
87
+ * Carrying the signed row is what makes redemption work at a member that has not received
88
+ * the row by replication: the member seats it from the bundle under its stored issuer
89
+ * signature. The row's own signature covers every column, so a bundle whose row was
90
+ * altered cannot be seated anywhere.
91
+ */
92
+ export interface CadreInvitation {
93
+ v: 1;
94
+ /** The cadre the invitation joins; a device refuses one for another party. */
95
+ partyId: string;
96
+ /** The invitation's ed25519 seed, base64url: the proof of possession. */
97
+ invitePrivateKey: string;
98
+ /** The owner-signed row exactly as issued (`ControlDatabase.insertCadreInvite`). */
99
+ invite: CadreInviteRow;
100
+ /**
101
+ * The issuer's anchored owner keys. The redeeming device pins them before it dials
102
+ * (`CadreNode.trustOwnerKeys`) and checks the member's reply against them. Sourced from
103
+ * the issuer's node-local anchor only, never the replicated `OwnerKey` table, for the
104
+ * reason the seed invite gives: the device anchors whatever arrives here.
105
+ */
106
+ ownerKeys: string[];
107
+ /**
108
+ * Multiaddrs ending in `/p2p/<peerId>`: the issuer's own first, then other members', at
109
+ * most `CADRE_INVITATION_MAX_ADDRS` in all (`selectCadreInvitationMembers` in
110
+ * `invitation-bootstrap.ts`). The device tries them in order.
111
+ */
112
+ members: string[];
113
+ }
114
+
115
+ /**
116
+ * Encode a bundle for out-of-band delivery: {@link CADRE_INVITATION_PREFIX}, then base64url
117
+ * over JSON. The prefix lets an app tell an invitation from a join request
118
+ * (`cadre-join-request.ts`) or an owner grant (`owner-grant-protocol.ts`) and name the mistake
119
+ * when one is pasted for the other.
120
+ */
121
+ export function encodeCadreInvitation(invitation: CadreInvitation): string {
122
+ return `${CADRE_INVITATION_PREFIX}${uint8ArrayToString(new TextEncoder().encode(JSON.stringify(invitation)), 'base64url')}`;
123
+ }
124
+
125
+ /**
126
+ * Decode a bundle, refusing anything that is not a well-formed version-1
127
+ * {@link CadreInvitation} behind {@link CADRE_INVITATION_PREFIX}. Standalone so a client
128
+ * without a node (a settings screen that wants to show which cadre an invitation joins) can
129
+ * decode one.
130
+ *
131
+ * @throws on an owner key, an owner grant or a join request, a string without the prefix or
132
+ * that is not base64url JSON after it, or one that decodes to another shape or version.
133
+ */
134
+ export function decodeCadreInvitation(encoded: string): CadreInvitation {
135
+ const trimmed = encoded.trim();
136
+ if (trimmed.startsWith(OWNER_KEY_EXPORT_STEM)) {
137
+ throw new Error('This is an owner key, not a cadre invitation; it is private, so import it only where the app asks for an owner key');
138
+ }
139
+ if (trimmed.startsWith(OWNER_GRANT_PREFIX)) {
140
+ throw new Error('This is an owner grant, not a cadre invitation; paste it where the app asks for an owner grant');
141
+ }
142
+ if (trimmed.startsWith(CADRE_JOIN_REQUEST_PREFIX)) {
143
+ throw new Error('This is a join request, not a cadre invitation; paste it into the app that manages your cadre');
144
+ }
145
+ if (!trimmed.startsWith(CADRE_INVITATION_PREFIX)) {
146
+ throw new Error(`Cadre invitation must start with "${CADRE_INVITATION_PREFIX}" (this one starts with "${trimmed.slice(0, CADRE_INVITATION_PREFIX.length)}")`);
147
+ }
148
+ let parsed: unknown;
149
+ try {
150
+ parsed = JSON.parse(new TextDecoder().decode(uint8ArrayFromString(trimmed.slice(CADRE_INVITATION_PREFIX.length), 'base64url')));
151
+ } catch (error) {
152
+ throw new Error('Cadre invitation does not decode as base64url JSON', { cause: error });
153
+ }
154
+ if (!isWellFormedCadreInvitation(parsed)) {
155
+ throw new Error('Cadre invitation is malformed or of an unsupported version');
156
+ }
157
+ return parsed;
158
+ }
159
+
160
+ function isWellFormedCadreInvitation(value: unknown): value is CadreInvitation {
161
+ if (typeof value !== 'object' || value === null) return false;
162
+ const { v, partyId, invitePrivateKey, invite, ownerKeys, members } = value as Record<string, unknown>;
163
+ return v === 1
164
+ && isBoundedString(partyId)
165
+ && isEd25519KeyB64(invitePrivateKey)
166
+ && isWellFormedCadreInviteRow(invite)
167
+ && Array.isArray(ownerKeys) && ownerKeys.length > 0 && ownerKeys.every((key) => isEd25519KeyB64(key))
168
+ && Array.isArray(members) && members.length <= MAX_BUNDLE_MEMBERS && members.every((addr) => isBoundedString(addr));
169
+ }
170
+
171
+ // ── Wire messages ────────────────────────────────────────────────────────────
172
+
173
+ /**
174
+ * The device's own address record as a request carries it: a {@link PeerAddressRecord} without
175
+ * the peer id, which the connection gives, and the key, which is the request's `peerKey`.
176
+ */
177
+ export type RedeemSelfRecord = Pick<PeerAddressRecord, 'addrs' | 'updatedAt' | 'profile' | 'sig'>;
178
+
179
+ /** Device → member: one frame, the whole redemption. */
180
+ export interface CadreInviteRedeemRequest {
181
+ v: 2;
182
+ /** The cadre the device believes it is joining; a machine serving another party refuses by name. */
183
+ partyId: string;
184
+ /** The owner-signed row from the bundle. */
185
+ invite: CadreInviteRow;
186
+ /** The device's ed25519 public key, base64url; must be the key behind the connecting peer id. */
187
+ peerKey: string;
188
+ /**
189
+ * The device's own address record for its `CadrePeer` row, self-signed for the invitation's
190
+ * party as `CadreNode.registerSelf` signs it (`signPeerRecord`); `addrs` is empty for a phone.
191
+ * The member stores `addrs` and, when the signature verifies over them, the rest of the
192
+ * record too ({@link admittedRecord}), so the device's first publish is its admission.
193
+ */
194
+ record: RedeemSelfRecord;
195
+ /** Single-use nonce the device minted (`generateStampId`); both signatures cover it. */
196
+ usageStampId: string;
197
+ /** By `invitePrivateKey` over the `'redeem'` digest. */
198
+ inviteSig: string;
199
+ /** By the device's identity key over the `'consent'` digest. */
200
+ peerSig: string;
201
+ }
202
+
203
+ /**
204
+ * Why a member refused a redemption. Retryability is {@link CADRE_INVITE_REJECTION_RETRYABLE}'s;
205
+ * a retryable code moves the device to the next address the bundle names.
206
+ */
207
+ export type CadreInviteRejectionCode =
208
+ /**
209
+ * The issuer's `OwnerKey` row is not on this member (not replicated yet), or the issuer was
210
+ * removed; the member cannot tell which, so the device tries the next address.
211
+ */
212
+ | 'issuer-unknown'
213
+ /**
214
+ * A signature does not verify, the peer key is not the connecting identity, the request or
215
+ * the row is malformed, or the invitation names another device.
216
+ */
217
+ | 'invite-invalid'
218
+ /** Expired, withdrawn, exhausted, or issued by a key that is no longer an owner here. */
219
+ | 'invite-spent'
220
+ /** This machine serves another cadre than the one the invitation names. */
221
+ | 'party-mismatch'
222
+ /** The member is at its cap on concurrent redemptions. */
223
+ | 'busy'
224
+ /** The write failed transiently (the write retry gave up), or the member has not synced the invitation row the cadre holds; nothing was recorded. */
225
+ | 'conflict'
226
+ /**
227
+ * An unexpected member-side failure, or a request frame the member could not read (timed
228
+ * out, oversized, not JSON): nothing was proved either way, so the device tries the next
229
+ * address, as the formation responder's `internal` is read.
230
+ */
231
+ | 'internal';
232
+
233
+ /** Which refusals are worth repeating at the next address — the one place that says so. */
234
+ export const CADRE_INVITE_REJECTION_RETRYABLE: Readonly<Record<CadreInviteRejectionCode, boolean>> = {
235
+ 'issuer-unknown': true,
236
+ 'invite-invalid': false,
237
+ 'invite-spent': false,
238
+ 'party-mismatch': false,
239
+ 'busy': true,
240
+ 'conflict': true,
241
+ 'internal': true
242
+ };
243
+
244
+ /** Is `value` a code this build knows? Own keys only, so a peer's `'constructor'` does not pass. */
245
+ export function isCadreInviteRejectionCode(value: unknown): value is CadreInviteRejectionCode {
246
+ return typeof value === 'string' && Object.prototype.hasOwnProperty.call(CADRE_INVITE_REJECTION_RETRYABLE, value);
247
+ }
248
+
249
+ /** Member → device. */
250
+ export interface CadreInviteRedeemReply {
251
+ accepted: boolean;
252
+ /** Present iff `!accepted`. */
253
+ code?: CadreInviteRejectionCode;
254
+ /** Human-facing text; present iff `!accepted`. */
255
+ reason?: string;
256
+ /** The member's party id; present iff `accepted`. */
257
+ partyId?: string;
258
+ /** The invitation row as this member holds it; present iff `accepted`. */
259
+ invite?: CadreInviteRow;
260
+ /**
261
+ * Dial hints for the rest of the cadre, unsigned: the member's own projection of its
262
+ * `CadrePeer` rows (`ControlDatabase.querySeedPeers`), the answering member and every
263
+ * always-on machine marked `preferred`. The device derives trust from its anchor, never
264
+ * from this.
265
+ */
266
+ peers?: SeedPeer[];
267
+ }
268
+
269
+ /** An accepting reply, every optional field present. */
270
+ export interface CadreInviteAccepted extends CadreInviteRedeemReply {
271
+ accepted: true;
272
+ partyId: string;
273
+ invite: CadreInviteRow;
274
+ peers: SeedPeer[];
275
+ }
276
+
277
+ /** A refusal as the member sends it: a code, a reason, nothing else. */
278
+ type CadreInviteRejection = RedemptionRejection<CadreInviteRejectionCode>;
279
+
280
+ // ── Errors the device sees ───────────────────────────────────────────────────
281
+
282
+ /**
283
+ * A member answered and refused. `code` is `'unrecognized'` when the frame carried none this
284
+ * build knows (the two machines may run different versions), and such a refusal counts as
285
+ * retryable: trying the next address on an unknown answer is safe, giving up is not.
286
+ */
287
+ export class CadreInviteRejectedError extends Error {
288
+ readonly code: CadreInviteRejectionCode | 'unrecognized';
289
+ readonly reason: string;
290
+ readonly retryable: boolean;
291
+
292
+ /** Both arguments come straight off the wire, so neither is trusted to have its declared type. */
293
+ constructor(code: unknown, reason: unknown) {
294
+ const text = typeof reason === 'string' ? reason : 'no reason provided';
295
+ super(`Cadre invitation refused: ${text}`);
296
+ this.name = 'CadreInviteRejectedError';
297
+ this.code = isCadreInviteRejectionCode(code) ? code : 'unrecognized';
298
+ this.reason = text;
299
+ this.retryable = this.code === 'unrecognized' || CADRE_INVITE_REJECTION_RETRYABLE[this.code];
300
+ }
301
+ }
302
+
303
+ /** What one address the bundle named came to; the owner-grant redemption reports the same shape. */
304
+ export type CadreInviteAddressOutcome = RedemptionAddressOutcome;
305
+
306
+ /**
307
+ * Every address the bundle names was tried and none accepted: each failed to dial, answered
308
+ * malformed, or refused retryably. Always retryable; `outcomes` says what each address did.
309
+ */
310
+ export class CadreInviteUnreachableError extends Error {
311
+ readonly retryable = true;
312
+
313
+ constructor(readonly outcomes: readonly CadreInviteAddressOutcome[]) {
314
+ super(outcomes.length === 0
315
+ ? 'Cadre invitation names no dialable member'
316
+ : `Cadre invitation could not be redeemed at any of its ${outcomes.length} address(es): `
317
+ + outcomes.map((outcome) => `${outcome.addr}: ${outcome.error.message}`).join('; '));
318
+ this.name = 'CadreInviteUnreachableError';
319
+ }
320
+ }
321
+
322
+ /**
323
+ * A member accepted but its reply does not check out: another party id, another invitation
324
+ * key, or a row not signed by one of the pinned owner keys. Final: a machine that answers
325
+ * like this is not a member of the cadre the invitation names, and the row it wrote (if any)
326
+ * is in a database the device will never trust.
327
+ */
328
+ export class CadreInviteReplyInvalidError extends Error {
329
+ readonly retryable = false;
330
+
331
+ constructor(message: string) {
332
+ super(`Cadre invitation reply refused: ${message}`);
333
+ this.name = 'CadreInviteReplyInvalidError';
334
+ }
335
+ }
336
+
337
+ // ── Shape checks (both directions) ───────────────────────────────────────────
338
+
339
+ /** Is `value` a {@link CadreInviteRow} with every column in its stored form and bounded? */
340
+ export function isWellFormedCadreInviteRow(value: unknown): value is CadreInviteRow {
341
+ if (typeof value !== 'object' || value === null) return false;
342
+ const row = value as Record<string, unknown>;
343
+ return isEd25519KeyB64(row.key)
344
+ && isNullableBoundedString(row.peerId)
345
+ && isNullableBoundedString(row.expiresAt)
346
+ && isNullableUseCap(row.totalUses)
347
+ && isBoundedString(row.stampId)
348
+ && isEd25519KeyB64(row.issuerKey)
349
+ && isBoundedString(row.issuerSig);
350
+ }
351
+
352
+ /**
353
+ * The record's other fields are left to {@link admittedRecord}: a bad value there costs the
354
+ * device its signature on the row, not its admission.
355
+ */
356
+ function isWellFormedRedeemRequest(value: unknown): value is CadreInviteRedeemRequest {
357
+ if (typeof value !== 'object' || value === null) return false;
358
+ const { v, partyId, invite, peerKey, record, usageStampId, inviteSig, peerSig } = value as Record<string, unknown>;
359
+ return v === 2
360
+ && isBoundedString(partyId)
361
+ && isWellFormedCadreInviteRow(invite)
362
+ && isEd25519KeyB64(peerKey)
363
+ && typeof record === 'object' && record !== null && Array.isArray((record as Record<string, unknown>).addrs)
364
+ && isBoundedString(usageStampId)
365
+ && isBoundedString(inviteSig)
366
+ && isBoundedString(peerSig);
367
+ }
368
+
369
+ /** What the member writes on the device's `CadrePeer` row from the request's record. */
370
+ interface AdmittedRecord {
371
+ /** The record's addresses, sanitized ({@link sanitizeAddrs}): stored whether or not the rest is. */
372
+ addrs: string[];
373
+ /** The record's freshness, stored `Profile` code and signature, or null when they cannot be stored as the device's own. */
374
+ signed: Pick<PeerAddressRecord, 'updatedAt' | 'profile' | 'sig'> | null;
375
+ /** Why `signed` is null; absent when it is not. */
376
+ unsignedBecause?: string;
377
+ }
378
+
379
+ /**
380
+ * Judge the device's record (`request.record`) for its admission row. The signature covers the
381
+ * exact address list, so it is kept only when sanitizing dropped nothing, the stored `Profile`
382
+ * code is one the schema's `KnownProfile` check admits, the stamp and signature are in their
383
+ * stored forms, and the signature verifies for `partyId` under the device's key. Anything less admits the device
384
+ * with its addresses and no signature, as an owner-written row is, and the device's next
385
+ * publish fills it in. No clock check: a stamp in the future or the past is one the device's own
386
+ * self-publish could write too.
387
+ */
388
+ function admittedRecord(partyId: string, remotePeerId: string, request: Pick<CadreInviteRedeemRequest, 'peerKey' | 'record'>): AdmittedRecord {
389
+ const { addrs: offered, updatedAt, profile, sig } = request.record as Partial<Record<keyof RedeemSelfRecord, unknown>>;
390
+ const addrs = sanitizeAddrs(offered);
391
+ const unsigned = (because: string): AdmittedRecord => ({ addrs, signed: null, unsignedBecause: because });
392
+ // Sanitizing only drops entries, so an unchanged length is an unchanged list.
393
+ if (!Array.isArray(offered) || addrs.length !== offered.length) {
394
+ return unsigned('sanitizing changed the signed address list');
395
+ }
396
+ if (profile !== null && !isPublishedProfile(profile)) {
397
+ return unsigned('unknown profile');
398
+ }
399
+ if (typeof updatedAt !== 'number' || !Number.isSafeInteger(updatedAt) || updatedAt <= 0 || !isBoundedString(sig)) {
400
+ return unsigned('malformed stamp or signature');
401
+ }
402
+ if (!verifyPeerRecordSignature(partyId, { peerId: remotePeerId, publicKey: request.peerKey, addrs, updatedAt, profile, sig })) {
403
+ return unsigned('signature does not verify');
404
+ }
405
+ return { addrs, signed: { updatedAt, profile, sig } };
406
+ }
407
+
408
+ /**
409
+ * Keep only parsable, distinct multiaddr strings, capped at {@link MAX_ADDRS}, order kept.
410
+ * Applied on both sides: the member bounds what it stores on the device's row, the device
411
+ * bounds what it merges into its peer store. A malformed entry is skipped, not fatal.
412
+ */
413
+ export function sanitizeAddrs(addrs: unknown): string[] {
414
+ if (!Array.isArray(addrs)) return [];
415
+ const out: string[] = [];
416
+ const seen = new Set<string>();
417
+ for (const entry of addrs) {
418
+ if (out.length >= MAX_ADDRS) break;
419
+ if (!isBoundedString(entry) || seen.has(entry)) continue;
420
+ try {
421
+ multiaddr(entry);
422
+ } catch (error) {
423
+ log('addrs: skipping unparsable entry: %o', error);
424
+ continue;
425
+ }
426
+ seen.add(entry);
427
+ out.push(entry);
428
+ }
429
+ return out;
430
+ }
431
+
432
+ /** The reply's peer list, bounded and each entry's addresses sanitized; anything else dropped. */
433
+ function sanitizePeers(peers: unknown): SeedPeer[] {
434
+ if (!Array.isArray(peers)) return [];
435
+ const out: SeedPeer[] = [];
436
+ for (const entry of peers) {
437
+ if (out.length >= MAX_REPLY_PEERS) break;
438
+ if (typeof entry !== 'object' || entry === null) continue;
439
+ const { peerId, multiaddrs, preferred } = entry as Record<string, unknown>;
440
+ if (!isBoundedString(peerId)) continue;
441
+ out.push({ peerId, multiaddrs: sanitizeAddrs(multiaddrs), preferred: preferred === true });
442
+ }
443
+ return out;
444
+ }
445
+
446
+ /** An acceptance frame's fields, the attacker-influenced ones sanitized. Throws on a malformed one. */
447
+ function decodeAccepted(reply: Record<string, unknown>): CadreInviteAccepted {
448
+ if (!isBoundedString(reply.partyId) || !isWellFormedCadreInviteRow(reply.invite)) {
449
+ throw new Error('Cadre invitation acceptance is missing its party id or a well-formed row');
450
+ }
451
+ return { accepted: true, partyId: reply.partyId, invite: reply.invite, peers: sanitizePeers(reply.peers) };
452
+ }
453
+
454
+ // ── Request construction (device side) ───────────────────────────────────────
455
+
456
+ /** What the device signs with: its identity keypair in the crypto plugin's base64url form. */
457
+ export interface RedeemSigner {
458
+ /** The device's ed25519 public key, base64url — the key behind its peer id. */
459
+ peerKey: string;
460
+ /** The device's ed25519 seed, base64url. */
461
+ peerPrivateKey: string;
462
+ }
463
+
464
+ /**
465
+ * Build and sign the request for `invitation`: the holder's `'redeem'` signature with the
466
+ * invitation's private key and the device's `'consent'` signature with its own, both over
467
+ * (invitation key, `usageStampId`, device key) for the invitation's party. The same bytes
468
+ * the schema verifies at the member (`cadreInviteRedeemMessage` / `cadreInviteConsentMessage`),
469
+ * whose own `party_id()` must therefore be the party the bundle names.
470
+ *
471
+ * @param record - the device's address record, already signed for the invitation's party over
472
+ * sanitized addresses ({@link sanitizeAddrs}); copied in unchanged, since the signature
473
+ * covers the exact list.
474
+ */
475
+ export function signRedeemRequest(
476
+ invitation: CadreInvitation,
477
+ signer: RedeemSigner,
478
+ usageStampId: string,
479
+ record: RedeemSelfRecord
480
+ ): CadreInviteRedeemRequest {
481
+ const fields = { inviteKey: invitation.invite.key, usageStampId, peerKey: signer.peerKey };
482
+ const signB64 = (message: Uint8Array, privateKey: string): string =>
483
+ sign(message, privateKey, 'ed25519', 'bytes', 'base64url', 'base64url') as string;
484
+ return {
485
+ v: 2,
486
+ partyId: invitation.partyId,
487
+ invite: invitation.invite,
488
+ peerKey: signer.peerKey,
489
+ record: { addrs: [...record.addrs], updatedAt: record.updatedAt, profile: record.profile, sig: record.sig },
490
+ usageStampId,
491
+ inviteSig: signB64(cadreInviteRedeemMessage(invitation.partyId, fields), invitation.invitePrivateKey),
492
+ peerSig: signB64(cadreInviteConsentMessage(invitation.partyId, fields), signer.peerPrivateKey)
493
+ };
494
+ }
495
+
496
+ /**
497
+ * The device's check on an acceptance: the same party, the same invitation key, and a row
498
+ * signed by an issuer the device pinned from the bundle. Throws
499
+ * {@link CadreInviteReplyInvalidError} naming the first failure.
500
+ *
501
+ * What it proves is bounded: the request already carried the owner-signed row, so a machine
502
+ * that is not a member can echo it. The check catches a reply for another party or
503
+ * invitation and a row the pinned owners never signed; whether the answering machine is a
504
+ * member is settled afterwards, when the device syncs the control database and judges every
505
+ * row against its anchor (`CadreNode.listAuthorizedMembers`).
506
+ */
507
+ export function verifyRedeemReply(
508
+ reply: CadreInviteAccepted,
509
+ invitation: CadreInvitation,
510
+ isTrustedIssuer: (ownerKey: string) => boolean
511
+ ): void {
512
+ if (reply.partyId !== invitation.partyId) {
513
+ throw new CadreInviteReplyInvalidError(`the member serves party ${reply.partyId}, the invitation names ${invitation.partyId}`);
514
+ }
515
+ if (reply.invite.key !== invitation.invite.key) {
516
+ throw new CadreInviteReplyInvalidError('the member answered for a different invitation');
517
+ }
518
+ if (!isTrustedIssuer(reply.invite.issuerKey)) {
519
+ throw new CadreInviteReplyInvalidError('the row the member holds is not issued by one of the invitation\'s owner keys');
520
+ }
521
+ if (!verifyCadreInviteRow(invitation.partyId, reply.invite)) {
522
+ throw new CadreInviteReplyInvalidError('the row the member holds is not signed by its issuer');
523
+ }
524
+ }
525
+
526
+ // ── Member side (handler) ────────────────────────────────────────────────────
527
+
528
+ /** The control-database surface a redemption needs; a `ControlDatabase` satisfies it. */
529
+ export type CadreInviteStore = Pick<ControlDatabase, 'queryCadreInvite' | 'seatCadreInvite' | 'isCadreInviteLive' | 'redeemCadreInvite' | 'querySeedPeers'>;
530
+
531
+ export interface CadreInviteHandlerOptions extends MemberRedemptionHandlerOptions {
532
+ /** This member's peer id: the reply's peer list marks it preferred, since the device just reached it. */
533
+ peerId: string;
534
+ store: CadreInviteStore;
535
+ }
536
+
537
+ /** Constraint names the schema refuses a redemption with, and the code each maps to. */
538
+ const REDEEM_CONSTRAINT_CODES: ReadonlyArray<ConstraintRefusalRow<CadreInviteRejectionCode>> = [
539
+ [/CHECK constraint failed: Authorized\b/, 'invite-spent', 'The invitation is expired, withdrawn, exhausted, or its issuer is no longer an owner'],
540
+ [/CHECK constraint failed: (InvitePossessed|PeerConsented|PeerExists)\b/, 'invite-invalid', 'The redemption does not satisfy the invitation'],
541
+ [/CHECK constraint failed: NotRevoked\b/, 'invite-spent', 'The invitation was withdrawn'],
542
+ ];
543
+
544
+ /**
545
+ * Member side of the invitation protocol (`MemberRedemptionHandler` has the shape): after the
546
+ * request's shape, it checks the party, the connecting identity (an ed25519 peer id is an
547
+ * identity multihash of the very key, and this is the only layer that can check the pair),
548
+ * both signatures and a targeted invitation's device, then seats the row from the bundle when
549
+ * this member holds none and redeems. An issuer this member does not know as an owner is the
550
+ * one retryable refusal left: the device tries the next address, which may hold the issuer's row.
551
+ */
552
+ export class CadreInviteHandler extends MemberRedemptionHandler<CadreInviteRedeemRequest, CadreInviteRedeemReply, CadreInviteRow> {
553
+ private readonly peerId: string;
554
+ private readonly store: CadreInviteStore;
555
+ protected readonly busyRefusal = rejection('busy', 'Too many concurrent redemptions');
556
+ protected readonly internalRefusal = rejection('internal', 'Internal redemption error');
557
+ protected readonly malformedRefusal = rejection('invite-invalid', 'Malformed redemption request');
558
+
559
+ constructor(options: CadreInviteHandlerOptions) {
560
+ super('Cadre invite', CADRE_INVITE_PROTOCOL, options);
561
+ this.peerId = options.peerId;
562
+ this.store = options.store;
563
+ }
564
+
565
+ protected isWellFormedRequest(value: unknown): value is CadreInviteRedeemRequest {
566
+ return isWellFormedRedeemRequest(value);
567
+ }
568
+
569
+ protected checkRequest(request: CadreInviteRedeemRequest, remotePeerId: string): CadreInviteRejection | null {
570
+ if (request.partyId !== this.partyId) {
571
+ return rejection('party-mismatch', 'This machine serves another cadre');
572
+ }
573
+ if (ed25519PublicKeyB64FromPeerId(remotePeerId) !== request.peerKey) {
574
+ return rejection('invite-invalid', 'The peer key is not the connecting identity');
575
+ }
576
+ const fields = { inviteKey: request.invite.key, usageStampId: request.usageStampId, peerKey: request.peerKey };
577
+ if (!verifyCadreInviteRedemption(this.partyId, fields, request.inviteSig, request.peerSig)) {
578
+ return rejection('invite-invalid', 'The redemption signatures do not verify');
579
+ }
580
+ if (request.invite.peerId !== null && request.invite.peerId !== remotePeerId) {
581
+ return rejection('invite-invalid', 'The invitation names another device');
582
+ }
583
+ return null;
584
+ }
585
+
586
+ protected readHeld(request: CadreInviteRedeemRequest): Promise<CadreInviteRow | null> {
587
+ return this.store.queryCadreInvite(request.invite.key);
588
+ }
589
+
590
+ protected isLive(request: CadreInviteRedeemRequest, held: CadreInviteRow | null): Promise<boolean> {
591
+ return this.store.isCadreInviteLive(request.invite, held);
592
+ }
593
+
594
+ /**
595
+ * The two writes — the seat (its own transaction), only when this member holds no row, and
596
+ * the redemption — each answered by name when it fails. The held row is carried into the
597
+ * redemption so it is not read again in the write lock; after a fresh seat nothing is carried
598
+ * and the redemption reads the row it seated, since the bundle's copy is the requester's.
599
+ */
600
+ protected async redeemAdmitted(request: CadreInviteRedeemRequest, remotePeerId: string, held: CadreInviteRow | null): Promise<CadreInviteRedeemReply> {
601
+ if (held === null) {
602
+ const refused = await this.seat(request, remotePeerId);
603
+ if (refused) return refused;
604
+ }
605
+ // Built before the write: the `CadrePeer` membership view is normally warm then (the
606
+ // connection gate read it when the device connected), and the redemption's commit drops it.
607
+ // The list lacks the device's own row, which the device drops from it anyway.
608
+ const peers = await this.peersBestEffort();
609
+ const record = admittedRecord(this.partyId, remotePeerId, request);
610
+ if (record.signed === null) {
611
+ log('admitting %s without its own record signature: %s', remotePeerId, record.unsignedBecause);
612
+ }
613
+ try {
614
+ const result = await this.store.redeemCadreInvite({
615
+ inviteKey: request.invite.key,
616
+ ...(held ? { held } : {}),
617
+ peerId: remotePeerId,
618
+ peerKey: request.peerKey,
619
+ multiaddrs: record.addrs,
620
+ ...(record.signed ? { record: record.signed } : {}),
621
+ usageStampId: request.usageStampId,
622
+ inviteSig: request.inviteSig,
623
+ peerSig: request.peerSig
624
+ });
625
+ log('invitation %s redeemed by %s (alreadyMember=%s)', request.invite.key, remotePeerId, result.alreadyMember);
626
+ } catch (error) {
627
+ if (error instanceof InvitationExhaustedError) {
628
+ return rejection('invite-spent', 'The invitation has no uses left');
629
+ }
630
+ log('redeeming invitation %s for %s failed: %o', request.invite.key, remotePeerId, error);
631
+ return constraintRefusal(error, REDEEM_CONSTRAINT_CODES) ?? writeFailureRefusal(error);
632
+ }
633
+ // The row as held: read before the write, or the bundle's copy the seat inserted verbatim
634
+ // or found already held (its key is the primary key and every column is under the issuer's
635
+ // signature).
636
+ return { accepted: true, partyId: this.partyId, invite: held ?? request.invite, peers };
637
+ }
638
+
639
+ /** Seat the bundle's copy of the row; a refusal answered by name, or null once it is held. */
640
+ private async seat(request: CadreInviteRedeemRequest, remotePeerId: string): Promise<CadreInviteRejection | null> {
641
+ try {
642
+ await this.store.seatCadreInvite(request.invite);
643
+ return null;
644
+ } catch (error) {
645
+ if (error instanceof CadreInviteIssuerUnknownError) {
646
+ return rejection('issuer-unknown', 'The invitation\'s issuer is not known as an owner here');
647
+ }
648
+ log('seating invitation %s from %s failed: %o', request.invite.key, remotePeerId, error);
649
+ return constraintRefusal(error, REDEEM_CONSTRAINT_CODES) ?? writeFailureRefusal(error);
650
+ }
651
+ }
652
+
653
+ /** Dial hints are an optimization; a failed read costs the device its hints, not its membership. */
654
+ private async peersBestEffort(): Promise<SeedPeer[]> {
655
+ try {
656
+ return await this.store.querySeedPeers(this.peerId);
657
+ } catch (error) {
658
+ log('peer projection for the reply failed (continuing without hints): %o', error);
659
+ return [];
660
+ }
661
+ }
662
+ }
663
+
664
+ // ── Device side (dialer) ─────────────────────────────────────────────────────
665
+
666
+ export interface RedeemAtMembersOptions {
667
+ /** The bundle: its `members` are dialed in order. */
668
+ invitation: CadreInvitation;
669
+ /** The signed request ({@link signRedeemRequest}); the same one goes to every address. */
670
+ request: CadreInviteRedeemRequest;
671
+ /** Is this owner key one the device pinned from the bundle? The reply check's input. */
672
+ isTrustedIssuer: (ownerKey: string) => boolean;
673
+ /** See `MemberRedemptionOptions.linkRoundTripMs`. */
674
+ linkRoundTripMs?: number;
675
+ /** Per-address deadline override; default derived from `linkRoundTripMs`. */
676
+ addressBudgetMs?: number;
677
+ protocolId?: string;
678
+ /** Cancels the dial or stream in flight and ends the pass; the call throws the signal's reason. */
679
+ signal?: AbortSignal;
680
+ }
681
+
682
+ /** What a successful redemption yields the device. */
683
+ export type CadreInviteRedemption = MemberRedemption<CadreInviteAccepted>;
684
+
685
+ /** The invitation's half of the shared dial loop: its label, protocol, bundle, codec, checks and errors. */
686
+ function inviteRedemption(options: RedeemAtMembersOptions): MemberRedemptionOptions<CadreInviteAccepted> {
687
+ return {
688
+ label: LABEL,
689
+ protocolId: options.protocolId ?? CADRE_INVITE_PROTOCOL,
690
+ members: options.invitation.members,
691
+ request: options.request,
692
+ decodeAccepted,
693
+ refusal: (code, reason) => new CadreInviteRejectedError(code, reason),
694
+ verifyAccepted: (reply) => verifyRedeemReply(reply, options.invitation, options.isTrustedIssuer),
695
+ unreachable: (outcomes) => new CadreInviteUnreachableError(outcomes),
696
+ ...(options.linkRoundTripMs !== undefined ? { linkRoundTripMs: options.linkRoundTripMs } : {}),
697
+ ...(options.addressBudgetMs !== undefined ? { addressBudgetMs: options.addressBudgetMs } : {}),
698
+ ...(options.signal ? { signal: options.signal } : {}),
699
+ };
700
+ }
701
+
702
+ /**
703
+ * Device side: try the bundle's addresses one at a time, each under its own deadline, and
704
+ * stop at the first acceptance or the first final refusal (`dialRedemption` in
705
+ * `member-redemption.ts`). Every address gets the SAME request, with one `usageStampId`:
706
+ * `CadreInviteUsage` is keyed by it, so a member the device gave up on that was still
707
+ * committing cannot admit it twice, and a retry at the next member after a dropped reply is
708
+ * answered as already a member.
709
+ *
710
+ * @throws {CadreInviteRejectedError} on a final refusal (its `retryable` is false).
711
+ * @throws {CadreInviteReplyInvalidError} on an acceptance that fails {@link verifyRedeemReply}.
712
+ * @throws {CadreInviteUnreachableError} when every address was tried and none accepted.
713
+ * @throws the reason of `options.signal` once it aborts.
714
+ */
715
+ export function redeemAtMembers(node: Libp2p, options: RedeemAtMembersOptions): Promise<CadreInviteRedemption> {
716
+ return dialRedemption(node, inviteRedemption(options));
717
+ }
718
+
719
+ export interface RedeemInPassesOptions extends RedeemAtMembersOptions {
720
+ /** Keep making passes while every answer is retryable; false makes exactly one. */
721
+ waitForMember: boolean;
722
+ /** Called at each pass and each pause; an exception it throws is logged and ignored. */
723
+ onProgress?: (progress: CadreJoinProgress) => void;
724
+ }
725
+
726
+ /**
727
+ * Device side, in passes (`dialRedemptionInPasses` in `member-redemption.ts`): one
728
+ * {@link redeemAtMembers} pass, or, with `waitForMember`, as many as it takes, pausing between
729
+ * them and never past the invitation's expiry, which by this device's clock is thrown as the
730
+ * `invite-spent` refusal a member would give.
731
+ */
732
+ export function redeemInPasses(node: Libp2p, options: RedeemInPassesOptions): Promise<CadreInviteRedemption> {
733
+ const passes: MemberRedemptionPassOptions<CadreInviteAccepted> = {
734
+ ...inviteRedemption(options),
735
+ waitForMember: options.waitForMember,
736
+ expiresAt: options.invitation.invite.expiresAt,
737
+ expired: () => new CadreInviteRejectedError('invite-spent', 'the invitation expired before a member accepted it'),
738
+ ...(options.onProgress ? { onProgress: options.onProgress } : {}),
739
+ };
740
+ return dialRedemptionInPasses(node, passes);
741
+ }