@serfab/cadre-core 1.23.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 (313) 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 +145 -44
  8. package/dist/cadre-node.js +239 -79
  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 +2 -2
  82. package/dist/node-claim-payload.d.ts +15 -7
  83. package/dist/node-claim-payload.js +25 -9
  84. package/dist/node-claim-payload.js.map +1 -1
  85. package/dist/node-class.d.ts +36 -0
  86. package/dist/node-class.js +26 -0
  87. package/dist/node-class.js.map +1 -0
  88. package/dist/node-default-transports.d.ts +50 -3
  89. package/dist/node-default-transports.js +48 -3
  90. package/dist/node-default-transports.js.map +1 -1
  91. package/dist/node-roles.d.ts +118 -0
  92. package/dist/node-roles.js +142 -0
  93. package/dist/node-roles.js.map +1 -0
  94. package/dist/node-transports.d.ts +6 -2
  95. package/dist/node-transports.js +39 -7
  96. package/dist/node-transports.js.map +1 -1
  97. package/dist/owner-anchor-sync.js +1 -1
  98. package/dist/owner-key-export.js +1 -1
  99. package/dist/owner-key-flows.d.ts +1 -1
  100. package/dist/owner-key-store.js +1 -1
  101. package/dist/owner-signer.js +1 -1
  102. package/dist/peer-authorization.d.ts +3 -1
  103. package/dist/peer-authorization.js +3 -1
  104. package/dist/peer-authorization.js.map +1 -1
  105. package/dist/peer-dial.d.ts +74 -10
  106. package/dist/peer-dial.js +89 -17
  107. package/dist/peer-dial.js.map +1 -1
  108. package/dist/peer-join-backfill.js +4 -4
  109. package/dist/peer-join-backfill.js.map +1 -1
  110. package/dist/peer-record.d.ts +34 -9
  111. package/dist/peer-record.js +66 -13
  112. package/dist/peer-record.js.map +1 -1
  113. package/dist/pending-join-runner.d.ts +1 -1
  114. package/dist/pending-join-runner.js +1 -1
  115. package/dist/provider/client.d.ts +6 -5
  116. package/dist/provider/client.js +3 -3
  117. package/dist/provider/client.js.map +1 -1
  118. package/dist/provider/descriptor.d.ts +1 -1
  119. package/dist/provider/descriptor.js +1 -1
  120. package/dist/provider/oauth.d.ts +1 -1
  121. package/dist/provider/oauth.js +1 -1
  122. package/dist/provider/rent-node.d.ts +4 -3
  123. package/dist/provider/rent-node.js +3 -3
  124. package/dist/provider/rent-node.js.map +1 -1
  125. package/dist/relay-addrs.d.ts +62 -7
  126. package/dist/relay-addrs.js +74 -11
  127. package/dist/relay-addrs.js.map +1 -1
  128. package/dist/relay-reservation.d.ts +1 -1
  129. package/dist/relay-reservation.js +1 -1
  130. package/dist/relay-server.d.ts +6 -5
  131. package/dist/relay-server.js +5 -5
  132. package/dist/relay-server.js.map +1 -1
  133. package/dist/schema-verification.d.ts +13 -10
  134. package/dist/schema-verification.js +32 -24
  135. package/dist/schema-verification.js.map +1 -1
  136. package/dist/sealed-party-key.js +1 -1
  137. package/dist/seed-bootstrap.d.ts +4 -3
  138. package/dist/seed-bootstrap.js +6 -7
  139. package/dist/seed-bootstrap.js.map +1 -1
  140. package/dist/strand-addr-protocol.d.ts +8 -6
  141. package/dist/strand-addr-protocol.js +12 -10
  142. package/dist/strand-addr-protocol.js.map +1 -1
  143. package/dist/strand-app-schema-report.d.ts +16 -2
  144. package/dist/strand-app-schema-report.js +15 -0
  145. package/dist/strand-app-schema-report.js.map +1 -1
  146. package/dist/strand-cohort.d.ts +1 -4
  147. package/dist/strand-cohort.js.map +1 -1
  148. package/dist/strand-commit-durability.d.ts +1 -1
  149. package/dist/strand-database.d.ts +13 -6
  150. package/dist/strand-database.js +17 -9
  151. package/dist/strand-database.js.map +1 -1
  152. package/dist/strand-first-sync-gate.d.ts +3 -2
  153. package/dist/strand-first-sync-gate.js +3 -2
  154. package/dist/strand-first-sync-gate.js.map +1 -1
  155. package/dist/strand-formation-deadlines.d.ts +2 -2
  156. package/dist/strand-formation-deadlines.js +2 -2
  157. package/dist/strand-formation-protocol.d.ts +1 -1
  158. package/dist/strand-formation-protocol.js +51 -16
  159. package/dist/strand-formation-protocol.js.map +1 -1
  160. package/dist/strand-instance-manager.d.ts +67 -33
  161. package/dist/strand-instance-manager.js +164 -55
  162. package/dist/strand-instance-manager.js.map +1 -1
  163. package/dist/strand-membership-reconciler.d.ts +8 -3
  164. package/dist/strand-membership-reconciler.js +8 -3
  165. package/dist/strand-membership-reconciler.js.map +1 -1
  166. package/dist/strand-membership-writer.d.ts +2 -2
  167. package/dist/strand-membership-writer.js +41 -39
  168. package/dist/strand-membership-writer.js.map +1 -1
  169. package/dist/strand-move.js +1 -1
  170. package/dist/strand-network-config.d.ts +15 -5
  171. package/dist/strand-network-config.js +7 -6
  172. package/dist/strand-network-config.js.map +1 -1
  173. package/dist/strand-party-key-rotation.d.ts +7 -3
  174. package/dist/strand-party-key-rotation.js +7 -3
  175. package/dist/strand-party-key-rotation.js.map +1 -1
  176. package/dist/strand-party-machines.d.ts +19 -8
  177. package/dist/strand-party-machines.js +26 -11
  178. package/dist/strand-party-machines.js.map +1 -1
  179. package/dist/strand-party-peers.d.ts +36 -14
  180. package/dist/strand-party-peers.js +24 -15
  181. package/dist/strand-party-peers.js.map +1 -1
  182. package/dist/strand-peer-redial.d.ts +1 -1
  183. package/dist/strand-peer-redial.js +1 -1
  184. package/dist/strand-reactivity.d.ts +20 -17
  185. package/dist/strand-reactivity.js +31 -18
  186. package/dist/strand-reactivity.js.map +1 -1
  187. package/dist/strand-revocation-enforcer.d.ts +3 -3
  188. package/dist/strand-revocation-enforcer.js +3 -3
  189. package/dist/strand-wake-protocol.d.ts +19 -7
  190. package/dist/strand-wake-protocol.js +22 -10
  191. package/dist/strand-wake-protocol.js.map +1 -1
  192. package/dist/strand-watcher.d.ts +1 -1
  193. package/dist/strand-watcher.js +1 -1
  194. package/dist/table-change-watch.js +1 -1
  195. package/dist/types.d.ts +116 -55
  196. package/dist/types.js.map +1 -1
  197. package/dist/webrtc-upgrade.d.ts +254 -0
  198. package/dist/webrtc-upgrade.js +355 -0
  199. package/dist/webrtc-upgrade.js.map +1 -0
  200. package/package.json +9 -9
  201. package/src/announce-addrs.ts +93 -93
  202. package/src/arachnode-stub.ts +18 -10
  203. package/src/bootstrap-peer-store-file.ts +44 -44
  204. package/src/bootstrap-peer-store.ts +214 -214
  205. package/src/cadre-invite-protocol.ts +741 -740
  206. package/src/cadre-node.ts +12462 -12280
  207. package/src/claim-proof.ts +147 -147
  208. package/src/control-authorization.ts +290 -276
  209. package/src/control-cohort.ts +223 -204
  210. package/src/control-database.ts +72 -28
  211. package/src/control-formation-recorder.ts +359 -359
  212. package/src/control-protocol-guard.ts +370 -366
  213. package/src/control-read-retry.ts +222 -180
  214. package/src/control-retry.ts +36 -4
  215. package/src/control-schema-version.ts +301 -301
  216. package/src/control-schema.ts +1108 -1087
  217. package/src/control-write-retry.ts +639 -669
  218. package/src/delegate-admission.ts +351 -351
  219. package/src/describe-thrown.ts +60 -60
  220. package/src/ed25519-key.ts +185 -185
  221. package/src/edge-node/config.ts +13 -10
  222. package/src/edge-node/dissolve.ts +252 -252
  223. package/src/edge-node/edge-join.ts +320 -320
  224. package/src/edge-node/edge-node.ts +1095 -1095
  225. package/src/edge-node/index.ts +60 -59
  226. package/src/edge-node/join-credential.ts +16 -16
  227. package/src/edge-node/lazy-raw-storage.ts +194 -178
  228. package/src/edge-node/listen-addrs.ts +26 -0
  229. package/src/edge-node/node-local.ts +84 -84
  230. package/src/edge-node/options.ts +195 -195
  231. package/src/edge-node/owner-grant.ts +63 -63
  232. package/src/edge-node/platform.ts +5 -4
  233. package/src/edge-node/strand-move.ts +266 -266
  234. package/src/edge-node/strands.ts +27 -12
  235. package/src/enrolled-machine-store-file.ts +43 -43
  236. package/src/enrolled-machine-store.ts +280 -280
  237. package/src/fetch-impl.ts +23 -23
  238. package/src/file-durable-slot.ts +64 -64
  239. package/src/file-safe-name.ts +32 -32
  240. package/src/formation-approval.ts +604 -604
  241. package/src/formation-token.ts +63 -63
  242. package/src/fs-atomic.ts +92 -92
  243. package/src/index.ts +987 -957
  244. package/src/invitation-bootstrap.ts +152 -118
  245. package/src/joined-strand-store.ts +553 -553
  246. package/src/key-store-file.ts +142 -142
  247. package/src/link-budget.ts +61 -5
  248. package/src/machine-removal.ts +211 -210
  249. package/src/member-redemption.ts +643 -643
  250. package/src/membership-connection-gater.ts +650 -650
  251. package/src/membership-view.ts +147 -147
  252. package/src/node-claim-payload.ts +34 -12
  253. package/src/node-class.ts +47 -0
  254. package/src/node-default-transports.ts +65 -3
  255. package/src/node-roles.ts +220 -0
  256. package/src/node-transports.ts +86 -49
  257. package/src/owner-anchor-sync.ts +172 -172
  258. package/src/owner-grant-protocol.ts +547 -547
  259. package/src/owner-key-export.ts +348 -348
  260. package/src/owner-key-flows.ts +109 -109
  261. package/src/owner-key-store.ts +1 -1
  262. package/src/owner-keys.ts +179 -179
  263. package/src/owner-signer.ts +92 -92
  264. package/src/peer-addr-book.ts +252 -252
  265. package/src/peer-authorization.ts +584 -582
  266. package/src/peer-dial.ts +698 -605
  267. package/src/peer-join-backfill.ts +961 -961
  268. package/src/peer-record.ts +71 -16
  269. package/src/pending-join-runner.ts +798 -798
  270. package/src/primary-lan-address.ts +47 -47
  271. package/src/provider/client.ts +327 -326
  272. package/src/provider/descriptor.ts +129 -129
  273. package/src/provider/index.ts +59 -59
  274. package/src/provider/oauth.ts +285 -285
  275. package/src/provider/rent-node.ts +276 -275
  276. package/src/relay-addrs.ts +90 -12
  277. package/src/relay-reservation.ts +1 -1
  278. package/src/relay-server.ts +99 -98
  279. package/src/schema-verification.ts +38 -23
  280. package/src/sealed-party-key.ts +190 -190
  281. package/src/seed-bootstrap.ts +8 -11
  282. package/src/seed-trust-policy.ts +353 -353
  283. package/src/self-address-update.ts +19 -19
  284. package/src/strand-addr-protocol.ts +17 -14
  285. package/src/strand-app-schema-report.ts +147 -122
  286. package/src/strand-cohort.ts +1 -5
  287. package/src/strand-commit-durability.ts +165 -165
  288. package/src/strand-database.ts +522 -510
  289. package/src/strand-first-sync-gate.ts +3 -2
  290. package/src/strand-formation-deadlines.ts +227 -227
  291. package/src/strand-formation-manager.ts +731 -731
  292. package/src/strand-formation-protocol.ts +1174 -1138
  293. package/src/strand-fret-addrs.ts +179 -179
  294. package/src/strand-instance-manager.ts +188 -63
  295. package/src/strand-membership-reconciler.ts +1315 -1310
  296. package/src/strand-membership-writer.ts +2152 -2150
  297. package/src/strand-move.ts +1 -1
  298. package/src/strand-network-config.ts +16 -6
  299. package/src/strand-offline.ts +178 -178
  300. package/src/strand-party-key-rotation.ts +440 -436
  301. package/src/strand-party-machines.ts +308 -293
  302. package/src/strand-party-peers.ts +151 -129
  303. package/src/strand-peer-redial.ts +1 -1
  304. package/src/strand-reactivity.ts +36 -19
  305. package/src/strand-revocation-enforcer.ts +758 -758
  306. package/src/strand-wake-protocol.ts +406 -394
  307. package/src/strand-watcher.ts +1 -1
  308. package/src/table-change-watch.ts +285 -285
  309. package/src/timed-step.ts +28 -28
  310. package/src/timeout-scheduler.ts +29 -29
  311. package/src/trusted-owner-store.ts +242 -242
  312. package/src/types.ts +3182 -3121
  313. package/src/webrtc-upgrade.ts +439 -0
@@ -1,348 +1,348 @@
1
- /**
2
- * Owner-key export and import: the text (or QR code) a user keeps as a backup of an owner key or
3
- * carries to another device (`docs/architecture.md` → Owner Keys → Exporting and importing an
4
- * owner key). Whoever holds a plain export is an owner.
5
- *
6
- * - Plain: {@link OWNER_KEY_EXPORT_PREFIX}, then base64url of the canonical JSON
7
- * `{ key, label?, v: 1 }`, `key` being the 32-byte Ed25519 seed in base64url.
8
- * - Locked: {@link LOCKED_OWNER_KEY_EXPORT_PREFIX}, then base64url of the canonical JSON
9
- * `{ kdf: { N, name: 'scrypt', p, r, salt }, nonce, sealed, v: 1 }`, `sealed` being the plain
10
- * JSON under XChaCha20-Poly1305 with the 32-byte key scrypt derives from the passphrase. The
11
- * scrypt parameters ride in the text, so a later default still reads an old export.
12
- *
13
- * No error carries key material. `@noble/hashes` and `@noble/ciphers` are pure JS and random
14
- * bytes come from `crypto.getRandomValues`, so this loads on React Native and in the browser.
15
- */
16
- import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
17
- import { scryptAsync } from '@noble/hashes/scrypt.js';
18
- import { randomBytes } from '@noble/hashes/utils.js';
19
- import { fromString as uint8ArrayFromString, toString as uint8ArrayToString } from 'uint8arrays';
20
- import { canonicalJson } from './canonical-json.js';
21
- import { CADRE_INVITATION_PREFIX, CADRE_JOIN_REQUEST_PREFIX, OWNER_GRANT_PREFIX, OWNER_KEY_EXPORT_STEM } from './cadre-join-request.js';
22
- import { NODE_CLAIM_PAYLOAD_PREFIX } from './node-claim-payload.js';
23
- import { ed25519PublicKeyFromPrivate, requireEd25519PrivateKeyB64 } from './ed25519-key.js';
24
-
25
- /** Version 1 of the plain export. */
26
- export const OWNER_KEY_EXPORT_PREFIX = `${OWNER_KEY_EXPORT_STEM}:1.`;
27
-
28
- /** Version 1 of the passphrase-locked export. */
29
- export const LOCKED_OWNER_KEY_EXPORT_PREFIX = `${OWNER_KEY_EXPORT_STEM}-locked:1.`;
30
-
31
- /** Longest label an owner key carries, the user's name for it ("phone", "paper backup"): in an export and on its `OwnerKey` row (the control schema's `LabelLength` check). */
32
- export const OWNER_KEY_MAX_LABEL = 64;
33
-
34
- /**
35
- * The encoder's scrypt cost: about 140 ms and 64 MiB on Node 24 (x64, measured with
36
- * `scryptAsync`).
37
- * NOTE: unmeasured on Hermes; if a device run shows locking or unlocking is slow, lower N for the
38
- * locked form or move the KDF to native.
39
- */
40
- const DEFAULT_SCRYPT_COST: ScryptCost = { N: 2 ** 16, r: 8, p: 1 };
41
-
42
- /**
43
- * The most scrypt work the decoder runs, checked before deriving so a hostile file cannot keep a
44
- * device busy for minutes: N at most 2^20 and r·p at most 8, sixteen times the default's work.
45
- * At the cap scrypt takes about 2.5 s and 1 GiB on Node 24.
46
- * NOTE: unmeasured on Hermes; if a device run shows the cap runs for minutes or exhausts memory,
47
- * lower these two.
48
- */
49
- const MAX_SCRYPT_N = 2 ** 20;
50
- const MAX_SCRYPT_R_TIMES_P = 8;
51
-
52
- /** noble's `maxmem` for {@link MAX_SCRYPT_N}: its default (1 GiB + 1 KiB) is below what the cap itself needs, `128·r·(N + p + 1)` bytes. */
53
- const SCRYPT_MAXMEM = 128 * MAX_SCRYPT_R_TIMES_P * (MAX_SCRYPT_N + MAX_SCRYPT_R_TIMES_P + 1);
54
-
55
- const SCRYPT_SALT_BYTES = 16;
56
- const MAX_SCRYPT_SALT_BYTES = 64;
57
- const XCHACHA_NONCE_BYTES = 24;
58
- const POLY1305_TAG_BYTES = 16;
59
- /** A sealed plain export is under 200 bytes; this bounds what a hostile file makes the decoder decrypt. */
60
- const MAX_SEALED_BYTES = 1024;
61
-
62
- interface ScryptCost {
63
- N: number;
64
- r: number;
65
- p: number;
66
- }
67
-
68
- interface LockedEnvelope extends ScryptCost {
69
- salt: Uint8Array;
70
- nonce: Uint8Array;
71
- sealed: Uint8Array;
72
- }
73
-
74
- export type OwnerKeyExportErrorCode =
75
- /** Owner-key text whose body does not decode, or a version this build does not read. */
76
- | 'malformed'
77
- /** The passphrase does not open a locked export, or the locked text was altered. */
78
- | 'wrong-passphrase'
79
- /** A locked export given with no passphrase (`importOwnerKeyInto` in `owner-key-flows.ts`). */
80
- | 'passphrase-required'
81
- /** Not owner-key text; the message names an invitation, an owner grant, a join request or a join code. */
82
- | 'not-an-owner-key'
83
- /** A locked export asks for more scrypt work than {@link MAX_SCRYPT_N} and {@link MAX_SCRYPT_R_TIMES_P} allow. */
84
- | 'cost-too-high';
85
-
86
- /** Every refusal from this module. The message is for the user and never includes key material. */
87
- export class OwnerKeyExportError extends Error {
88
- readonly code: OwnerKeyExportErrorCode;
89
-
90
- constructor(code: OwnerKeyExportErrorCode, message: string, options?: { cause?: unknown }) {
91
- super(message, options);
92
- this.name = 'OwnerKeyExportError';
93
- this.code = code;
94
- }
95
- }
96
-
97
- /** What an export holds once read. */
98
- export interface OwnerKeyExportContents {
99
- /** The 32-byte Ed25519 seed, base64url: the input to `importOwnerKey`. */
100
- privateKeyB64: string;
101
- /** The matching public key, base64url: the `OwnerKey.Key` it signs for. */
102
- publicKey: string;
103
- label?: string;
104
- }
105
-
106
- /** {@link decodeOwnerKeyExport}'s answer: the key, or word that a passphrase is needed ({@link unlockOwnerKeyExport}). */
107
- export type DecodedOwnerKeyExport = ({ locked: false } & OwnerKeyExportContents) | { locked: true };
108
-
109
- export interface OwnerKeyExportInput {
110
- /** The 32-byte Ed25519 seed, base64url (`readOwnerPrivateKey`). */
111
- privateKeyB64: string;
112
- /** Trimmed; at most {@link OWNER_KEY_MAX_LABEL} characters; a blank one is left out. */
113
- label?: string;
114
- /** Locks the export when present; must not be empty. */
115
- passphrase?: string;
116
- }
117
-
118
- /**
119
- * Encode an owner key as text, locked under `passphrase` when one is given.
120
- *
121
- * @throws {OwnerKeyExportError} `malformed` for a key that is not a 32-byte seed, an over-long
122
- * label or an empty passphrase.
123
- */
124
- export async function encodeOwnerKeyExport(input: OwnerKeyExportInput): Promise<string> {
125
- const plainJson = plainExportJson(input.privateKeyB64, input.label);
126
- if (input.passphrase === undefined) {
127
- return withPrefix(OWNER_KEY_EXPORT_PREFIX, plainJson);
128
- }
129
- return withPrefix(LOCKED_OWNER_KEY_EXPORT_PREFIX, await lockedExportJson(plainJson, input.passphrase));
130
- }
131
-
132
- /**
133
- * Read owner-key text without a passphrase: a plain export's key, or `{ locked: true }` for a
134
- * locked one whose envelope is well formed and whose scrypt cost is within the cap, so an app
135
- * refuses a hostile file before asking for the passphrase.
136
- *
137
- * @throws {OwnerKeyExportError} `not-an-owner-key` (naming an invitation, an owner grant, a join
138
- * request or a join code), `malformed` or `cost-too-high`.
139
- */
140
- export function decodeOwnerKeyExport(text: string): DecodedOwnerKeyExport {
141
- const trimmed = text.trim();
142
- if (exportPrefix(trimmed) === LOCKED_OWNER_KEY_EXPORT_PREFIX) {
143
- lockedEnvelope(decodeBody(trimmed, LOCKED_OWNER_KEY_EXPORT_PREFIX));
144
- return { locked: true };
145
- }
146
- return { locked: false, ...exportContents(decodeBody(trimmed, OWNER_KEY_EXPORT_PREFIX)) };
147
- }
148
-
149
- /**
150
- * Read owner-key text with its passphrase. A plain export is read as {@link decodeOwnerKeyExport}
151
- * reads it, the passphrase unused.
152
- *
153
- * @throws {OwnerKeyExportError} as {@link decodeOwnerKeyExport}, and `wrong-passphrase` when the
154
- * passphrase does not open it or the sealed part, nonce or scrypt parameters were altered.
155
- */
156
- export async function unlockOwnerKeyExport(text: string, passphrase: string): Promise<OwnerKeyExportContents> {
157
- const trimmed = text.trim();
158
- const prefix = exportPrefix(trimmed);
159
- if (prefix === OWNER_KEY_EXPORT_PREFIX) {
160
- return exportContents(decodeBody(trimmed, prefix));
161
- }
162
- const envelope = lockedEnvelope(decodeBody(trimmed, prefix));
163
- const key = await deriveKey(passphrase, envelope, envelope.salt);
164
- let plain: Uint8Array;
165
- try {
166
- plain = xchacha20poly1305(key, envelope.nonce).decrypt(envelope.sealed);
167
- } catch (error) {
168
- throw new OwnerKeyExportError('wrong-passphrase', 'The passphrase does not unlock this owner key, or the text was altered', { cause: error });
169
- }
170
- return exportContents(parseJsonObject(new TextDecoder().decode(plain)));
171
- }
172
-
173
- // ── Encoding ─────────────────────────────────────────────────────────────────
174
-
175
- function plainExportJson(privateKeyB64: string, label: string | undefined): string {
176
- const key = requireKey(privateKeyB64);
177
- const trimmedLabel = label?.trim();
178
- return canonicalJson({ key, label: trimmedLabel ? requireLabel(trimmedLabel) : undefined, v: 1 });
179
- }
180
-
181
- async function lockedExportJson(plainJson: string, passphrase: string): Promise<string> {
182
- if (passphrase.length === 0) {
183
- throw new OwnerKeyExportError('malformed', 'A passphrase must not be empty; leave it out for an unlocked export');
184
- }
185
- const salt = randomBytes(SCRYPT_SALT_BYTES);
186
- const nonce = randomBytes(XCHACHA_NONCE_BYTES);
187
- const key = await deriveKey(passphrase, DEFAULT_SCRYPT_COST, salt);
188
- const sealed = xchacha20poly1305(key, nonce).encrypt(new TextEncoder().encode(plainJson));
189
- return canonicalJson({
190
- kdf: { ...DEFAULT_SCRYPT_COST, name: 'scrypt', salt: toBase64url(salt) },
191
- nonce: toBase64url(nonce),
192
- sealed: toBase64url(sealed),
193
- v: 1,
194
- });
195
- }
196
-
197
- function withPrefix(prefix: string, json: string): string {
198
- return `${prefix}${toBase64url(new TextEncoder().encode(json))}`;
199
- }
200
-
201
- /** scrypt's async form yields to the event loop every few milliseconds, so a phone's UI keeps drawing while it runs. */
202
- function deriveKey(passphrase: string, cost: ScryptCost, salt: Uint8Array): Promise<Uint8Array> {
203
- // NFKC, so one passphrase typed on keyboards that compose its characters differently derives one key.
204
- const password = new TextEncoder().encode(passphrase.normalize('NFKC'));
205
- return scryptAsync(password, salt, { N: cost.N, r: cost.r, p: cost.p, dkLen: 32, maxmem: SCRYPT_MAXMEM });
206
- }
207
-
208
- // ── Decoding ─────────────────────────────────────────────────────────────────
209
-
210
- /** Which of the two prefixes `text` starts with; refuses, by name where it can, anything else. */
211
- function exportPrefix(text: string): string {
212
- if (text.startsWith(LOCKED_OWNER_KEY_EXPORT_PREFIX)) return LOCKED_OWNER_KEY_EXPORT_PREFIX;
213
- if (text.startsWith(OWNER_KEY_EXPORT_PREFIX)) return OWNER_KEY_EXPORT_PREFIX;
214
- if (text.startsWith(OWNER_KEY_EXPORT_STEM)) {
215
- throw new OwnerKeyExportError('malformed', 'This owner key was exported by a newer version of the app; update this app to import it');
216
- }
217
- throw new OwnerKeyExportError('not-an-owner-key', notAnOwnerKeyMessage(text));
218
- }
219
-
220
- /** No prefix of the text is echoed: whatever was pasted may be a key in some other form. */
221
- function notAnOwnerKeyMessage(text: string): string {
222
- if (text.startsWith(CADRE_INVITATION_PREFIX)) {
223
- return 'This is a cadre invitation, not an owner key; paste it where the app asks for an invitation';
224
- }
225
- if (text.startsWith(OWNER_GRANT_PREFIX)) {
226
- return 'This is an owner grant, not an owner key; paste it where the app asks for an owner grant';
227
- }
228
- if (text.startsWith(CADRE_JOIN_REQUEST_PREFIX)) {
229
- return 'This is a join request, not an owner key; paste it into the app that manages your cadre';
230
- }
231
- if (text.startsWith(NODE_CLAIM_PAYLOAD_PREFIX)) {
232
- return 'This is a machine\'s join code, not an owner key; scan it where the app adds a machine';
233
- }
234
- return `An owner key must start with "${OWNER_KEY_EXPORT_PREFIX}" or "${LOCKED_OWNER_KEY_EXPORT_PREFIX}"`;
235
- }
236
-
237
- function decodeBody(text: string, prefix: string): Record<string, unknown> {
238
- let json: string;
239
- try {
240
- json = new TextDecoder().decode(uint8ArrayFromString(text.slice(prefix.length), 'base64url'));
241
- } catch (error) {
242
- throw new OwnerKeyExportError('malformed', 'An owner key export must carry base64url after its prefix', { cause: error });
243
- }
244
- return parseJsonObject(json);
245
- }
246
-
247
- /** A version-1 JSON object, the shape of both the export body and a locked export's sealed plaintext. */
248
- function parseJsonObject(json: string): Record<string, unknown> {
249
- let parsed: unknown;
250
- try {
251
- parsed = JSON.parse(json);
252
- } catch {
253
- // No cause: JSON.parse's message can quote the input, which may hold the key.
254
- throw new OwnerKeyExportError('malformed', 'An owner key export must carry JSON after its prefix');
255
- }
256
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
257
- throw new OwnerKeyExportError('malformed', 'An owner key export must decode to a JSON object');
258
- }
259
- const record = parsed as Record<string, unknown>;
260
- if (record.v !== 1) {
261
- throw new OwnerKeyExportError('malformed', `An owner key export must be version 1 (this one says ${JSON.stringify(record.v)})`);
262
- }
263
- return record;
264
- }
265
-
266
- function exportContents(record: Record<string, unknown>): OwnerKeyExportContents {
267
- const { key, label } = record;
268
- if (typeof key !== 'string') {
269
- throw new OwnerKeyExportError('malformed', 'An owner key export must carry its key');
270
- }
271
- if (label !== undefined && (typeof label !== 'string' || label.trim().length === 0)) {
272
- throw new OwnerKeyExportError('malformed', 'An owner key export\'s label must be non-empty text');
273
- }
274
- const privateKeyB64 = requireKey(key);
275
- return {
276
- privateKeyB64,
277
- publicKey: ed25519PublicKeyFromPrivate(privateKeyB64),
278
- ...(label === undefined ? {} : { label: requireLabel(label.trim()) }),
279
- };
280
- }
281
-
282
- function lockedEnvelope(record: Record<string, unknown>): LockedEnvelope {
283
- const { kdf, nonce, sealed } = record;
284
- if (typeof kdf !== 'object' || kdf === null || Array.isArray(kdf)) {
285
- throw new OwnerKeyExportError('malformed', 'A locked owner key must name its key derivation');
286
- }
287
- const { name, N, r, p, salt } = kdf as Record<string, unknown>;
288
- if (name !== 'scrypt') {
289
- throw new OwnerKeyExportError('malformed', `A locked owner key must use scrypt (this one names ${JSON.stringify(name)})`);
290
- }
291
- const cost = requireScryptCost(N, r, p);
292
- return {
293
- ...cost,
294
- salt: requireBytes(salt, 'salt', 1, MAX_SCRYPT_SALT_BYTES),
295
- nonce: requireBytes(nonce, 'nonce', XCHACHA_NONCE_BYTES, XCHACHA_NONCE_BYTES),
296
- sealed: requireBytes(sealed, 'sealed key', POLY1305_TAG_BYTES, MAX_SEALED_BYTES),
297
- };
298
- }
299
-
300
- function requireScryptCost(N: unknown, r: unknown, p: unknown): ScryptCost {
301
- if (!isPositiveInteger(N) || N < 2 || (N & (N - 1)) !== 0 || !isPositiveInteger(r) || !isPositiveInteger(p)) {
302
- throw new OwnerKeyExportError('malformed', 'A locked owner key\'s scrypt parameters must be positive integers, N a power of two');
303
- }
304
- if (N > MAX_SCRYPT_N || r * p > MAX_SCRYPT_R_TIMES_P) {
305
- throw new OwnerKeyExportError('cost-too-high', `This locked owner key asks for more work to unlock than this app allows (scrypt N ${N}, r ${r}, p ${p})`);
306
- }
307
- return { N, r, p };
308
- }
309
-
310
- function isPositiveInteger(value: unknown): value is number {
311
- return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
312
- }
313
-
314
- function requireBytes(value: unknown, field: string, minBytes: number, maxBytes: number): Uint8Array {
315
- let bytes: Uint8Array | undefined;
316
- if (typeof value === 'string') {
317
- try {
318
- bytes = uint8ArrayFromString(value, 'base64url');
319
- } catch (error) {
320
- throw new OwnerKeyExportError('malformed', `A locked owner key's ${field} must be base64url`, { cause: error });
321
- }
322
- }
323
- if (bytes === undefined || bytes.length < minBytes || bytes.length > maxBytes) {
324
- throw new OwnerKeyExportError('malformed', `A locked owner key's ${field} must be ${minBytes === maxBytes ? minBytes : `${minBytes} to ${maxBytes}`} bytes of base64url`);
325
- }
326
- return bytes;
327
- }
328
-
329
- // ── Shared field rules ───────────────────────────────────────────────────────
330
-
331
- function requireKey(privateKeyB64: string): string {
332
- try {
333
- return requireEd25519PrivateKeyB64(privateKeyB64, 'owner key');
334
- } catch (error) {
335
- throw new OwnerKeyExportError('malformed', error instanceof Error ? error.message : 'The owner key must be a 32-byte Ed25519 private key', { cause: error });
336
- }
337
- }
338
-
339
- function requireLabel(label: string): string {
340
- if (label.length > OWNER_KEY_MAX_LABEL) {
341
- throw new OwnerKeyExportError('malformed', `An owner key's label must be at most ${OWNER_KEY_MAX_LABEL} characters (this one has ${label.length})`);
342
- }
343
- return label;
344
- }
345
-
346
- function toBase64url(bytes: Uint8Array): string {
347
- return uint8ArrayToString(bytes, 'base64url');
348
- }
1
+ /**
2
+ * Owner-key export and import: the text (or QR code) a user keeps as a backup of an owner key or
3
+ * carries to another device (`docs/cadre/owner-keys.md` → Exporting and importing an
4
+ * owner key). Whoever holds a plain export is an owner.
5
+ *
6
+ * - Plain: {@link OWNER_KEY_EXPORT_PREFIX}, then base64url of the canonical JSON
7
+ * `{ key, label?, v: 1 }`, `key` being the 32-byte Ed25519 seed in base64url.
8
+ * - Locked: {@link LOCKED_OWNER_KEY_EXPORT_PREFIX}, then base64url of the canonical JSON
9
+ * `{ kdf: { N, name: 'scrypt', p, r, salt }, nonce, sealed, v: 1 }`, `sealed` being the plain
10
+ * JSON under XChaCha20-Poly1305 with the 32-byte key scrypt derives from the passphrase. The
11
+ * scrypt parameters ride in the text, so a later default still reads an old export.
12
+ *
13
+ * No error carries key material. `@noble/hashes` and `@noble/ciphers` are pure JS and random
14
+ * bytes come from `crypto.getRandomValues`, so this loads on React Native and in the browser.
15
+ */
16
+ import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
17
+ import { scryptAsync } from '@noble/hashes/scrypt.js';
18
+ import { randomBytes } from '@noble/hashes/utils.js';
19
+ import { fromString as uint8ArrayFromString, toString as uint8ArrayToString } from 'uint8arrays';
20
+ import { canonicalJson } from './canonical-json.js';
21
+ import { CADRE_INVITATION_PREFIX, CADRE_JOIN_REQUEST_PREFIX, OWNER_GRANT_PREFIX, OWNER_KEY_EXPORT_STEM } from './cadre-join-request.js';
22
+ import { NODE_CLAIM_PAYLOAD_PREFIX } from './node-claim-payload.js';
23
+ import { ed25519PublicKeyFromPrivate, requireEd25519PrivateKeyB64 } from './ed25519-key.js';
24
+
25
+ /** Version 1 of the plain export. */
26
+ export const OWNER_KEY_EXPORT_PREFIX = `${OWNER_KEY_EXPORT_STEM}:1.`;
27
+
28
+ /** Version 1 of the passphrase-locked export. */
29
+ export const LOCKED_OWNER_KEY_EXPORT_PREFIX = `${OWNER_KEY_EXPORT_STEM}-locked:1.`;
30
+
31
+ /** Longest label an owner key carries, the user's name for it ("phone", "paper backup"): in an export and on its `OwnerKey` row (the control schema's `LabelLength` check). */
32
+ export const OWNER_KEY_MAX_LABEL = 64;
33
+
34
+ /**
35
+ * The encoder's scrypt cost: about 140 ms and 64 MiB on Node 24 (x64, measured with
36
+ * `scryptAsync`).
37
+ * NOTE: unmeasured on Hermes; if a device run shows locking or unlocking is slow, lower N for the
38
+ * locked form or move the KDF to native.
39
+ */
40
+ const DEFAULT_SCRYPT_COST: ScryptCost = { N: 2 ** 16, r: 8, p: 1 };
41
+
42
+ /**
43
+ * The most scrypt work the decoder runs, checked before deriving so a hostile file cannot keep a
44
+ * device busy for minutes: N at most 2^20 and r·p at most 8, sixteen times the default's work.
45
+ * At the cap scrypt takes about 2.5 s and 1 GiB on Node 24.
46
+ * NOTE: unmeasured on Hermes; if a device run shows the cap runs for minutes or exhausts memory,
47
+ * lower these two.
48
+ */
49
+ const MAX_SCRYPT_N = 2 ** 20;
50
+ const MAX_SCRYPT_R_TIMES_P = 8;
51
+
52
+ /** noble's `maxmem` for {@link MAX_SCRYPT_N}: its default (1 GiB + 1 KiB) is below what the cap itself needs, `128·r·(N + p + 1)` bytes. */
53
+ const SCRYPT_MAXMEM = 128 * MAX_SCRYPT_R_TIMES_P * (MAX_SCRYPT_N + MAX_SCRYPT_R_TIMES_P + 1);
54
+
55
+ const SCRYPT_SALT_BYTES = 16;
56
+ const MAX_SCRYPT_SALT_BYTES = 64;
57
+ const XCHACHA_NONCE_BYTES = 24;
58
+ const POLY1305_TAG_BYTES = 16;
59
+ /** A sealed plain export is under 200 bytes; this bounds what a hostile file makes the decoder decrypt. */
60
+ const MAX_SEALED_BYTES = 1024;
61
+
62
+ interface ScryptCost {
63
+ N: number;
64
+ r: number;
65
+ p: number;
66
+ }
67
+
68
+ interface LockedEnvelope extends ScryptCost {
69
+ salt: Uint8Array;
70
+ nonce: Uint8Array;
71
+ sealed: Uint8Array;
72
+ }
73
+
74
+ export type OwnerKeyExportErrorCode =
75
+ /** Owner-key text whose body does not decode, or a version this build does not read. */
76
+ | 'malformed'
77
+ /** The passphrase does not open a locked export, or the locked text was altered. */
78
+ | 'wrong-passphrase'
79
+ /** A locked export given with no passphrase (`importOwnerKeyInto` in `owner-key-flows.ts`). */
80
+ | 'passphrase-required'
81
+ /** Not owner-key text; the message names an invitation, an owner grant, a join request or a join code. */
82
+ | 'not-an-owner-key'
83
+ /** A locked export asks for more scrypt work than {@link MAX_SCRYPT_N} and {@link MAX_SCRYPT_R_TIMES_P} allow. */
84
+ | 'cost-too-high';
85
+
86
+ /** Every refusal from this module. The message is for the user and never includes key material. */
87
+ export class OwnerKeyExportError extends Error {
88
+ readonly code: OwnerKeyExportErrorCode;
89
+
90
+ constructor(code: OwnerKeyExportErrorCode, message: string, options?: { cause?: unknown }) {
91
+ super(message, options);
92
+ this.name = 'OwnerKeyExportError';
93
+ this.code = code;
94
+ }
95
+ }
96
+
97
+ /** What an export holds once read. */
98
+ export interface OwnerKeyExportContents {
99
+ /** The 32-byte Ed25519 seed, base64url: the input to `importOwnerKey`. */
100
+ privateKeyB64: string;
101
+ /** The matching public key, base64url: the `OwnerKey.Key` it signs for. */
102
+ publicKey: string;
103
+ label?: string;
104
+ }
105
+
106
+ /** {@link decodeOwnerKeyExport}'s answer: the key, or word that a passphrase is needed ({@link unlockOwnerKeyExport}). */
107
+ export type DecodedOwnerKeyExport = ({ locked: false } & OwnerKeyExportContents) | { locked: true };
108
+
109
+ export interface OwnerKeyExportInput {
110
+ /** The 32-byte Ed25519 seed, base64url (`readOwnerPrivateKey`). */
111
+ privateKeyB64: string;
112
+ /** Trimmed; at most {@link OWNER_KEY_MAX_LABEL} characters; a blank one is left out. */
113
+ label?: string;
114
+ /** Locks the export when present; must not be empty. */
115
+ passphrase?: string;
116
+ }
117
+
118
+ /**
119
+ * Encode an owner key as text, locked under `passphrase` when one is given.
120
+ *
121
+ * @throws {OwnerKeyExportError} `malformed` for a key that is not a 32-byte seed, an over-long
122
+ * label or an empty passphrase.
123
+ */
124
+ export async function encodeOwnerKeyExport(input: OwnerKeyExportInput): Promise<string> {
125
+ const plainJson = plainExportJson(input.privateKeyB64, input.label);
126
+ if (input.passphrase === undefined) {
127
+ return withPrefix(OWNER_KEY_EXPORT_PREFIX, plainJson);
128
+ }
129
+ return withPrefix(LOCKED_OWNER_KEY_EXPORT_PREFIX, await lockedExportJson(plainJson, input.passphrase));
130
+ }
131
+
132
+ /**
133
+ * Read owner-key text without a passphrase: a plain export's key, or `{ locked: true }` for a
134
+ * locked one whose envelope is well formed and whose scrypt cost is within the cap, so an app
135
+ * refuses a hostile file before asking for the passphrase.
136
+ *
137
+ * @throws {OwnerKeyExportError} `not-an-owner-key` (naming an invitation, an owner grant, a join
138
+ * request or a join code), `malformed` or `cost-too-high`.
139
+ */
140
+ export function decodeOwnerKeyExport(text: string): DecodedOwnerKeyExport {
141
+ const trimmed = text.trim();
142
+ if (exportPrefix(trimmed) === LOCKED_OWNER_KEY_EXPORT_PREFIX) {
143
+ lockedEnvelope(decodeBody(trimmed, LOCKED_OWNER_KEY_EXPORT_PREFIX));
144
+ return { locked: true };
145
+ }
146
+ return { locked: false, ...exportContents(decodeBody(trimmed, OWNER_KEY_EXPORT_PREFIX)) };
147
+ }
148
+
149
+ /**
150
+ * Read owner-key text with its passphrase. A plain export is read as {@link decodeOwnerKeyExport}
151
+ * reads it, the passphrase unused.
152
+ *
153
+ * @throws {OwnerKeyExportError} as {@link decodeOwnerKeyExport}, and `wrong-passphrase` when the
154
+ * passphrase does not open it or the sealed part, nonce or scrypt parameters were altered.
155
+ */
156
+ export async function unlockOwnerKeyExport(text: string, passphrase: string): Promise<OwnerKeyExportContents> {
157
+ const trimmed = text.trim();
158
+ const prefix = exportPrefix(trimmed);
159
+ if (prefix === OWNER_KEY_EXPORT_PREFIX) {
160
+ return exportContents(decodeBody(trimmed, prefix));
161
+ }
162
+ const envelope = lockedEnvelope(decodeBody(trimmed, prefix));
163
+ const key = await deriveKey(passphrase, envelope, envelope.salt);
164
+ let plain: Uint8Array;
165
+ try {
166
+ plain = xchacha20poly1305(key, envelope.nonce).decrypt(envelope.sealed);
167
+ } catch (error) {
168
+ throw new OwnerKeyExportError('wrong-passphrase', 'The passphrase does not unlock this owner key, or the text was altered', { cause: error });
169
+ }
170
+ return exportContents(parseJsonObject(new TextDecoder().decode(plain)));
171
+ }
172
+
173
+ // ── Encoding ─────────────────────────────────────────────────────────────────
174
+
175
+ function plainExportJson(privateKeyB64: string, label: string | undefined): string {
176
+ const key = requireKey(privateKeyB64);
177
+ const trimmedLabel = label?.trim();
178
+ return canonicalJson({ key, label: trimmedLabel ? requireLabel(trimmedLabel) : undefined, v: 1 });
179
+ }
180
+
181
+ async function lockedExportJson(plainJson: string, passphrase: string): Promise<string> {
182
+ if (passphrase.length === 0) {
183
+ throw new OwnerKeyExportError('malformed', 'A passphrase must not be empty; leave it out for an unlocked export');
184
+ }
185
+ const salt = randomBytes(SCRYPT_SALT_BYTES);
186
+ const nonce = randomBytes(XCHACHA_NONCE_BYTES);
187
+ const key = await deriveKey(passphrase, DEFAULT_SCRYPT_COST, salt);
188
+ const sealed = xchacha20poly1305(key, nonce).encrypt(new TextEncoder().encode(plainJson));
189
+ return canonicalJson({
190
+ kdf: { ...DEFAULT_SCRYPT_COST, name: 'scrypt', salt: toBase64url(salt) },
191
+ nonce: toBase64url(nonce),
192
+ sealed: toBase64url(sealed),
193
+ v: 1,
194
+ });
195
+ }
196
+
197
+ function withPrefix(prefix: string, json: string): string {
198
+ return `${prefix}${toBase64url(new TextEncoder().encode(json))}`;
199
+ }
200
+
201
+ /** scrypt's async form yields to the event loop every few milliseconds, so a phone's UI keeps drawing while it runs. */
202
+ function deriveKey(passphrase: string, cost: ScryptCost, salt: Uint8Array): Promise<Uint8Array> {
203
+ // NFKC, so one passphrase typed on keyboards that compose its characters differently derives one key.
204
+ const password = new TextEncoder().encode(passphrase.normalize('NFKC'));
205
+ return scryptAsync(password, salt, { N: cost.N, r: cost.r, p: cost.p, dkLen: 32, maxmem: SCRYPT_MAXMEM });
206
+ }
207
+
208
+ // ── Decoding ─────────────────────────────────────────────────────────────────
209
+
210
+ /** Which of the two prefixes `text` starts with; refuses, by name where it can, anything else. */
211
+ function exportPrefix(text: string): string {
212
+ if (text.startsWith(LOCKED_OWNER_KEY_EXPORT_PREFIX)) return LOCKED_OWNER_KEY_EXPORT_PREFIX;
213
+ if (text.startsWith(OWNER_KEY_EXPORT_PREFIX)) return OWNER_KEY_EXPORT_PREFIX;
214
+ if (text.startsWith(OWNER_KEY_EXPORT_STEM)) {
215
+ throw new OwnerKeyExportError('malformed', 'This owner key was exported by a newer version of the app; update this app to import it');
216
+ }
217
+ throw new OwnerKeyExportError('not-an-owner-key', notAnOwnerKeyMessage(text));
218
+ }
219
+
220
+ /** No prefix of the text is echoed: whatever was pasted may be a key in some other form. */
221
+ function notAnOwnerKeyMessage(text: string): string {
222
+ if (text.startsWith(CADRE_INVITATION_PREFIX)) {
223
+ return 'This is a cadre invitation, not an owner key; paste it where the app asks for an invitation';
224
+ }
225
+ if (text.startsWith(OWNER_GRANT_PREFIX)) {
226
+ return 'This is an owner grant, not an owner key; paste it where the app asks for an owner grant';
227
+ }
228
+ if (text.startsWith(CADRE_JOIN_REQUEST_PREFIX)) {
229
+ return 'This is a join request, not an owner key; paste it into the app that manages your cadre';
230
+ }
231
+ if (text.startsWith(NODE_CLAIM_PAYLOAD_PREFIX)) {
232
+ return 'This is a machine\'s join code, not an owner key; scan it where the app adds a machine';
233
+ }
234
+ return `An owner key must start with "${OWNER_KEY_EXPORT_PREFIX}" or "${LOCKED_OWNER_KEY_EXPORT_PREFIX}"`;
235
+ }
236
+
237
+ function decodeBody(text: string, prefix: string): Record<string, unknown> {
238
+ let json: string;
239
+ try {
240
+ json = new TextDecoder().decode(uint8ArrayFromString(text.slice(prefix.length), 'base64url'));
241
+ } catch (error) {
242
+ throw new OwnerKeyExportError('malformed', 'An owner key export must carry base64url after its prefix', { cause: error });
243
+ }
244
+ return parseJsonObject(json);
245
+ }
246
+
247
+ /** A version-1 JSON object, the shape of both the export body and a locked export's sealed plaintext. */
248
+ function parseJsonObject(json: string): Record<string, unknown> {
249
+ let parsed: unknown;
250
+ try {
251
+ parsed = JSON.parse(json);
252
+ } catch {
253
+ // No cause: JSON.parse's message can quote the input, which may hold the key.
254
+ throw new OwnerKeyExportError('malformed', 'An owner key export must carry JSON after its prefix');
255
+ }
256
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
257
+ throw new OwnerKeyExportError('malformed', 'An owner key export must decode to a JSON object');
258
+ }
259
+ const record = parsed as Record<string, unknown>;
260
+ if (record.v !== 1) {
261
+ throw new OwnerKeyExportError('malformed', `An owner key export must be version 1 (this one says ${JSON.stringify(record.v)})`);
262
+ }
263
+ return record;
264
+ }
265
+
266
+ function exportContents(record: Record<string, unknown>): OwnerKeyExportContents {
267
+ const { key, label } = record;
268
+ if (typeof key !== 'string') {
269
+ throw new OwnerKeyExportError('malformed', 'An owner key export must carry its key');
270
+ }
271
+ if (label !== undefined && (typeof label !== 'string' || label.trim().length === 0)) {
272
+ throw new OwnerKeyExportError('malformed', 'An owner key export\'s label must be non-empty text');
273
+ }
274
+ const privateKeyB64 = requireKey(key);
275
+ return {
276
+ privateKeyB64,
277
+ publicKey: ed25519PublicKeyFromPrivate(privateKeyB64),
278
+ ...(label === undefined ? {} : { label: requireLabel(label.trim()) }),
279
+ };
280
+ }
281
+
282
+ function lockedEnvelope(record: Record<string, unknown>): LockedEnvelope {
283
+ const { kdf, nonce, sealed } = record;
284
+ if (typeof kdf !== 'object' || kdf === null || Array.isArray(kdf)) {
285
+ throw new OwnerKeyExportError('malformed', 'A locked owner key must name its key derivation');
286
+ }
287
+ const { name, N, r, p, salt } = kdf as Record<string, unknown>;
288
+ if (name !== 'scrypt') {
289
+ throw new OwnerKeyExportError('malformed', `A locked owner key must use scrypt (this one names ${JSON.stringify(name)})`);
290
+ }
291
+ const cost = requireScryptCost(N, r, p);
292
+ return {
293
+ ...cost,
294
+ salt: requireBytes(salt, 'salt', 1, MAX_SCRYPT_SALT_BYTES),
295
+ nonce: requireBytes(nonce, 'nonce', XCHACHA_NONCE_BYTES, XCHACHA_NONCE_BYTES),
296
+ sealed: requireBytes(sealed, 'sealed key', POLY1305_TAG_BYTES, MAX_SEALED_BYTES),
297
+ };
298
+ }
299
+
300
+ function requireScryptCost(N: unknown, r: unknown, p: unknown): ScryptCost {
301
+ if (!isPositiveInteger(N) || N < 2 || (N & (N - 1)) !== 0 || !isPositiveInteger(r) || !isPositiveInteger(p)) {
302
+ throw new OwnerKeyExportError('malformed', 'A locked owner key\'s scrypt parameters must be positive integers, N a power of two');
303
+ }
304
+ if (N > MAX_SCRYPT_N || r * p > MAX_SCRYPT_R_TIMES_P) {
305
+ throw new OwnerKeyExportError('cost-too-high', `This locked owner key asks for more work to unlock than this app allows (scrypt N ${N}, r ${r}, p ${p})`);
306
+ }
307
+ return { N, r, p };
308
+ }
309
+
310
+ function isPositiveInteger(value: unknown): value is number {
311
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
312
+ }
313
+
314
+ function requireBytes(value: unknown, field: string, minBytes: number, maxBytes: number): Uint8Array {
315
+ let bytes: Uint8Array | undefined;
316
+ if (typeof value === 'string') {
317
+ try {
318
+ bytes = uint8ArrayFromString(value, 'base64url');
319
+ } catch (error) {
320
+ throw new OwnerKeyExportError('malformed', `A locked owner key's ${field} must be base64url`, { cause: error });
321
+ }
322
+ }
323
+ if (bytes === undefined || bytes.length < minBytes || bytes.length > maxBytes) {
324
+ throw new OwnerKeyExportError('malformed', `A locked owner key's ${field} must be ${minBytes === maxBytes ? minBytes : `${minBytes} to ${maxBytes}`} bytes of base64url`);
325
+ }
326
+ return bytes;
327
+ }
328
+
329
+ // ── Shared field rules ───────────────────────────────────────────────────────
330
+
331
+ function requireKey(privateKeyB64: string): string {
332
+ try {
333
+ return requireEd25519PrivateKeyB64(privateKeyB64, 'owner key');
334
+ } catch (error) {
335
+ throw new OwnerKeyExportError('malformed', error instanceof Error ? error.message : 'The owner key must be a 32-byte Ed25519 private key', { cause: error });
336
+ }
337
+ }
338
+
339
+ function requireLabel(label: string): string {
340
+ if (label.length > OWNER_KEY_MAX_LABEL) {
341
+ throw new OwnerKeyExportError('malformed', `An owner key's label must be at most ${OWNER_KEY_MAX_LABEL} characters (this one has ${label.length})`);
342
+ }
343
+ return label;
344
+ }
345
+
346
+ function toBase64url(bytes: Uint8Array): string {
347
+ return uint8ArrayToString(bytes, 'base64url');
348
+ }