@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,142 +1,142 @@
1
- /**
2
- * Node-only file-backed {@link KeyStore}: one file per slot under a configured
3
- * directory, holding the raw key material bytes.
4
- *
5
- * This module imports `node:fs/promises`, `node:path`, and `node:crypto`, so it
6
- * is deliberately kept OUT of the package's cross-platform default entry
7
- * (`./index.js`). Import it from the dedicated subpath instead:
8
- *
9
- * ```ts
10
- * import { FileKeyStore } from '@serfab/cadre-core/key-store-file';
11
- * ```
12
- *
13
- * A React Native / browser entry graph never resolves this path, so the
14
- * `node:fs` edge never reaches a bundler that cannot satisfy it.
15
- */
16
- import debug from 'debug';
17
- import { readFile, rm, readdir } from 'node:fs/promises';
18
- import { join } from 'node:path';
19
- import { randomBytes } from 'node:crypto';
20
- import type { KeyId, KeyStore } from './key-store.js';
21
- import { KeyStoreAccessError } from './key-store.js';
22
- import { isNotFound, writeFileAtomically } from './fs-atomic.js';
23
- import { encodeFileSafeComponent } from './file-safe-name.js';
24
-
25
- const log = debug('sereus:cadre:key-store-file');
26
-
27
- /** Suffix appended to the encoded keyId to form a slot filename. */
28
- const SLOT_SUFFIX = '.key';
29
-
30
- /**
31
- * Suffix for the transient file written then atomically renamed over the slot.
32
- * Distinct from {@link SLOT_SUFFIX}, so {@link FileKeyStore.list} (which matches
33
- * only `.key`) never surfaces an in-flight or crash-orphaned temp file.
34
- */
35
- const TEMP_SUFFIX = '.tmp';
36
-
37
- /**
38
- * Percent-encode a keyId into a filesystem-safe filename component (see
39
- * {@link encodeFileSafeComponent} — `.` is escaped so the `.key` suffix is the
40
- * only literal dot, making suffix-stripping in {@link decodeKeyId} unambiguous;
41
- * {@link decodeKeyId} reverses every escape via `decodeURIComponent`).
42
- */
43
- function encodeKeyId(keyId: KeyId): string {
44
- return encodeFileSafeComponent(keyId);
45
- }
46
-
47
- /**
48
- * Reverse {@link encodeKeyId}: strip the slot suffix and percent-decode. Returns
49
- * `undefined` for a `.key` filename this store did not write, so
50
- * {@link FileKeyStore.list} can skip it rather than letting one undecodable
51
- * entry throw and break enumeration of every real slot. That includes a name
52
- * that decodes but is not the one {@link encodeKeyId} produces for the result
53
- * (e.g. a slot written before uppercase letters were escaped):
54
- * {@link FileKeyStore.get} looks only at the canonical name, so listing it
55
- * would name a key id that reads back as absent.
56
- */
57
- function decodeKeyId(fileName: string): KeyId | undefined {
58
- const encoded = fileName.slice(0, -SLOT_SUFFIX.length);
59
- let keyId: KeyId;
60
- try {
61
- keyId = decodeURIComponent(encoded);
62
- } catch (error) {
63
- log('FileKeyStore: skipping undecodable slot filename %s: %o', fileName, error);
64
- return undefined;
65
- }
66
- if (encodeKeyId(keyId) !== encoded) {
67
- log('FileKeyStore: skipping non-canonical slot filename %s', fileName);
68
- return undefined;
69
- }
70
- return keyId;
71
- }
72
-
73
- /**
74
- * File-backed {@link KeyStore}. Each slot is `<dir>/<encoded keyId>.key`
75
- * containing the raw material bytes. The directory is created lazily on first
76
- * {@link set}. Suitable for headless Node cadre nodes and tests; for mobile use
77
- * a platform secure-enclave backend instead.
78
- */
79
- export class FileKeyStore implements KeyStore {
80
- constructor(private readonly dir: string) {}
81
-
82
- private slotPath(keyId: KeyId): string {
83
- return join(this.dir, `${encodeKeyId(keyId)}${SLOT_SUFFIX}`);
84
- }
85
-
86
- /**
87
- * Sibling path for the temp file written before the atomic rename. The random
88
- * component makes concurrent {@link set}s to the same slot (and crash-orphaned
89
- * leftovers) collide-free; it lives in the same directory as the slot so the
90
- * final {@link rename} stays within one filesystem and is therefore atomic.
91
- */
92
- private tempPath(keyId: KeyId): string {
93
- const unique = randomBytes(6).toString('hex');
94
- return join(this.dir, `${encodeKeyId(keyId)}.${unique}${TEMP_SUFFIX}`);
95
- }
96
-
97
- async get(keyId: KeyId): Promise<Uint8Array | undefined> {
98
- try {
99
- const buf = await readFile(this.slotPath(keyId));
100
- // Copy into a plain Uint8Array decoupled from Node's Buffer pool.
101
- return new Uint8Array(buf);
102
- } catch (error) {
103
- // A missing slot is "empty" (undefined), NOT an error — so a
104
- // load-or-create caller generates a key rather than mistaking a
105
- // permission failure for absence. Any other failure (e.g. EACCES) is
106
- // surfaced as access-denied so callers do not clobber an existing key.
107
- if (isNotFound(error)) return undefined;
108
- throw new KeyStoreAccessError(keyId, `FileKeyStore: failed to read key slot ${keyId}`, { cause: error });
109
- }
110
- }
111
-
112
- /**
113
- * Crash-atomic write: a concurrent reader sees either the complete previous
114
- * bytes or the complete new bytes, never a torn slot. The new material is
115
- * written to a sibling temp file, fsync'd, then atomically renamed over the
116
- * slot (see {@link writeFileAtomically}). A failure at any point removes the
117
- * temp file and leaves the previous slot untouched.
118
- */
119
- async set(keyId: KeyId, keyMaterial: Uint8Array): Promise<void> {
120
- await writeFileAtomically(this.dir, this.tempPath(keyId), this.slotPath(keyId), keyMaterial);
121
- }
122
-
123
- async delete(keyId: KeyId): Promise<void> {
124
- // force:true makes removing an absent slot a no-op (idempotent).
125
- await rm(this.slotPath(keyId), { force: true });
126
- }
127
-
128
- async list(): Promise<KeyId[]> {
129
- let entries: string[];
130
- try {
131
- entries = await readdir(this.dir);
132
- } catch (error) {
133
- // An absent directory means no slots yet — not a failure.
134
- if (isNotFound(error)) return [];
135
- throw new Error('FileKeyStore: failed to list key directory', { cause: error });
136
- }
137
- return entries
138
- .filter((name) => name.endsWith(SLOT_SUFFIX))
139
- .map(decodeKeyId)
140
- .filter((id): id is KeyId => id !== undefined);
141
- }
142
- }
1
+ /**
2
+ * Node-only file-backed {@link KeyStore}: one file per slot under a configured
3
+ * directory, holding the raw key material bytes.
4
+ *
5
+ * This module imports `node:fs/promises`, `node:path`, and `node:crypto`, so it
6
+ * is deliberately kept OUT of the package's cross-platform default entry
7
+ * (`./index.js`). Import it from the dedicated subpath instead:
8
+ *
9
+ * ```ts
10
+ * import { FileKeyStore } from '@serfab/cadre-core/key-store-file';
11
+ * ```
12
+ *
13
+ * A React Native / browser entry graph never resolves this path, so the
14
+ * `node:fs` edge never reaches a bundler that cannot satisfy it.
15
+ */
16
+ import debug from 'debug';
17
+ import { readFile, rm, readdir } from 'node:fs/promises';
18
+ import { join } from 'node:path';
19
+ import { randomBytes } from 'node:crypto';
20
+ import type { KeyId, KeyStore } from './key-store.js';
21
+ import { KeyStoreAccessError } from './key-store.js';
22
+ import { isNotFound, writeFileAtomically } from './fs-atomic.js';
23
+ import { encodeFileSafeComponent } from './file-safe-name.js';
24
+
25
+ const log = debug('sereus:cadre:key-store-file');
26
+
27
+ /** Suffix appended to the encoded keyId to form a slot filename. */
28
+ const SLOT_SUFFIX = '.key';
29
+
30
+ /**
31
+ * Suffix for the transient file written then atomically renamed over the slot.
32
+ * Distinct from {@link SLOT_SUFFIX}, so {@link FileKeyStore.list} (which matches
33
+ * only `.key`) never surfaces an in-flight or crash-orphaned temp file.
34
+ */
35
+ const TEMP_SUFFIX = '.tmp';
36
+
37
+ /**
38
+ * Percent-encode a keyId into a filesystem-safe filename component (see
39
+ * {@link encodeFileSafeComponent} — `.` is escaped so the `.key` suffix is the
40
+ * only literal dot, making suffix-stripping in {@link decodeKeyId} unambiguous;
41
+ * {@link decodeKeyId} reverses every escape via `decodeURIComponent`).
42
+ */
43
+ function encodeKeyId(keyId: KeyId): string {
44
+ return encodeFileSafeComponent(keyId);
45
+ }
46
+
47
+ /**
48
+ * Reverse {@link encodeKeyId}: strip the slot suffix and percent-decode. Returns
49
+ * `undefined` for a `.key` filename this store did not write, so
50
+ * {@link FileKeyStore.list} can skip it rather than letting one undecodable
51
+ * entry throw and break enumeration of every real slot. That includes a name
52
+ * that decodes but is not the one {@link encodeKeyId} produces for the result
53
+ * (e.g. a slot written before uppercase letters were escaped):
54
+ * {@link FileKeyStore.get} looks only at the canonical name, so listing it
55
+ * would name a key id that reads back as absent.
56
+ */
57
+ function decodeKeyId(fileName: string): KeyId | undefined {
58
+ const encoded = fileName.slice(0, -SLOT_SUFFIX.length);
59
+ let keyId: KeyId;
60
+ try {
61
+ keyId = decodeURIComponent(encoded);
62
+ } catch (error) {
63
+ log('FileKeyStore: skipping undecodable slot filename %s: %o', fileName, error);
64
+ return undefined;
65
+ }
66
+ if (encodeKeyId(keyId) !== encoded) {
67
+ log('FileKeyStore: skipping non-canonical slot filename %s', fileName);
68
+ return undefined;
69
+ }
70
+ return keyId;
71
+ }
72
+
73
+ /**
74
+ * File-backed {@link KeyStore}. Each slot is `<dir>/<encoded keyId>.key`
75
+ * containing the raw material bytes. The directory is created lazily on first
76
+ * {@link set}. Suitable for headless Node cadre nodes and tests; for mobile use
77
+ * a platform secure-enclave backend instead.
78
+ */
79
+ export class FileKeyStore implements KeyStore {
80
+ constructor(private readonly dir: string) {}
81
+
82
+ private slotPath(keyId: KeyId): string {
83
+ return join(this.dir, `${encodeKeyId(keyId)}${SLOT_SUFFIX}`);
84
+ }
85
+
86
+ /**
87
+ * Sibling path for the temp file written before the atomic rename. The random
88
+ * component makes concurrent {@link set}s to the same slot (and crash-orphaned
89
+ * leftovers) collide-free; it lives in the same directory as the slot so the
90
+ * final {@link rename} stays within one filesystem and is therefore atomic.
91
+ */
92
+ private tempPath(keyId: KeyId): string {
93
+ const unique = randomBytes(6).toString('hex');
94
+ return join(this.dir, `${encodeKeyId(keyId)}.${unique}${TEMP_SUFFIX}`);
95
+ }
96
+
97
+ async get(keyId: KeyId): Promise<Uint8Array | undefined> {
98
+ try {
99
+ const buf = await readFile(this.slotPath(keyId));
100
+ // Copy into a plain Uint8Array decoupled from Node's Buffer pool.
101
+ return new Uint8Array(buf);
102
+ } catch (error) {
103
+ // A missing slot is "empty" (undefined), NOT an error — so a
104
+ // load-or-create caller generates a key rather than mistaking a
105
+ // permission failure for absence. Any other failure (e.g. EACCES) is
106
+ // surfaced as access-denied so callers do not clobber an existing key.
107
+ if (isNotFound(error)) return undefined;
108
+ throw new KeyStoreAccessError(keyId, `FileKeyStore: failed to read key slot ${keyId}`, { cause: error });
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Crash-atomic write: a concurrent reader sees either the complete previous
114
+ * bytes or the complete new bytes, never a torn slot. The new material is
115
+ * written to a sibling temp file, fsync'd, then atomically renamed over the
116
+ * slot (see {@link writeFileAtomically}). A failure at any point removes the
117
+ * temp file and leaves the previous slot untouched.
118
+ */
119
+ async set(keyId: KeyId, keyMaterial: Uint8Array): Promise<void> {
120
+ await writeFileAtomically(this.dir, this.tempPath(keyId), this.slotPath(keyId), keyMaterial);
121
+ }
122
+
123
+ async delete(keyId: KeyId): Promise<void> {
124
+ // force:true makes removing an absent slot a no-op (idempotent).
125
+ await rm(this.slotPath(keyId), { force: true });
126
+ }
127
+
128
+ async list(): Promise<KeyId[]> {
129
+ let entries: string[];
130
+ try {
131
+ entries = await readdir(this.dir);
132
+ } catch (error) {
133
+ // An absent directory means no slots yet — not a failure.
134
+ if (isNotFound(error)) return [];
135
+ throw new Error('FileKeyStore: failed to list key directory', { cause: error });
136
+ }
137
+ return entries
138
+ .filter((name) => name.endsWith(SLOT_SUFFIX))
139
+ .map(decodeKeyId)
140
+ .filter((id): id is KeyId => id !== undefined);
141
+ }
142
+ }
@@ -18,7 +18,7 @@
18
18
  * deadline that never waits on the link; `-- link-bound, not yet derived: <ticket slug>` marks
19
19
  * one that does and names the ticket that owns converting it. Grep for the second to list the
20
20
  * deadlines this module does not yet cover. `-- cuts off by design: <why>; see
21
- * docs/cadre-consistency.md → "Deadlines Over Optimystic's Reads and Commits"` keeps a deadline
21
+ * docs/network/deadlines.md → "Deadlines over Optimystic's reads and commits"` keeps a deadline
22
22
  * that does wait on the link, through an Optimystic read or commit, but whose value is what its
23
23
  * caller can tolerate: it gives up on purpose and must not grow with the link. That doc section
24
24
  * lists every such site. `-- measured, not derived: <where the measurement lives>` keeps a
@@ -150,8 +150,8 @@
150
150
  * to a peer that never completes a connection waits up to the 42 500 ms dial deadline, each of
151
151
  * that peer's addresses up to 39 000 ms inside it, and one that connects and never answers
152
152
  * waits 10 500. A control write against a connected, silent member fails after about 84 s
153
- * (one pend round and three cancel rounds; `docs/cadre-consistency.md` → "Deadlines Over
154
- * Optimystic's Reads and Commits"). The dial case was not measured. cadre's cut-off budgets
153
+ * (one pend round and three cancel rounds; `docs/network/deadlines.md` → "Deadlines over
154
+ * Optimystic's reads and commits"). The dial case was not measured. cadre's cut-off budgets
155
155
  * (`CONTROL_WRITE_RETRY_BUDGET_MS`, `CONTROL_READ_RETRY_BUDGET_MS`) are checked between
156
156
  * attempts, so one attempt can outlast them by that much. If writes on a fast link are seen
157
157
  * waiting out the dial deadline against an unreachable machine, declare that deployment's real
@@ -210,7 +210,7 @@ import { resolveLinkDeadlines, type Libp2pConnectionTimeouts, type RpcDeadlineDe
210
210
  *
211
211
  * **Why 3 500.** Sereus supports two machines that reach each other only through a relay up to
212
212
  * a **3-second link round trip** (1 500 ms each way — a congested mobile or satellite link;
213
- * `docs/architecture.md` → "Relay Integration"). The worst relayed dial measured at that link,
213
+ * `docs/network/deadlines.md` → "The declared link"). The worst relayed dial measured at that link,
214
214
  * opening the relay connection first, was 15 113 ms, above the 15 000 ms a declaration of
215
215
  * exactly 3 000 would derive, so the declaration rounds the supported link up to the next half
216
216
  * second. 3 500 derives 17 500 ms of link time and leaves about 2.4 s over that dial: room for a
@@ -346,6 +346,25 @@ export const COMMIT_ROUND_TRIPS = 20;
346
346
  */
347
347
  export const RELAYED_REQUEST_ROUND_TRIPS = RELAYED_DIAL_ROUND_TRIPS + CIRCUIT_REQUEST_ROUND_TRIPS;
348
348
 
349
+ /**
350
+ * Link round trips the SIGNALLING half of a WebRTC upgrade dial costs, over the relay that
351
+ * carries it ({@link webrtcUpgradeDialBudgetMs}): {@link RELAYED_DIAL_ROUND_TRIPS} to open the
352
+ * connection the signalling runs on, then two request-and-answer exchanges over it
353
+ * ({@link CIRCUIT_REQUEST_ROUND_TRIPS} each) — the offer and its answer, then the ICE candidates
354
+ * each side trickles to the other.
355
+ *
356
+ * Counted from `@libp2p/webrtc`'s `initiateConnection`, which opens ONE signalling stream and
357
+ * writes those messages on it. The dial leg is normally not spent at all: an upgrade is
358
+ * attempted only for a peer already reachable over a relay, and that function reuses an open
359
+ * connection to the peer rather than dialing. It is counted because an upgrade attempt races
360
+ * the connection it was triggered by, which can close first.
361
+ *
362
+ * The ICE connectivity checks that follow cross the two networks' own candidate addresses
363
+ * rather than the relay, so they are not link time counted here; they get a flat allowance
364
+ * ({@link ICE_NEGOTIATION_ALLOWANCE_MS}).
365
+ */
366
+ export const WEBRTC_SIGNALING_ROUND_TRIPS = RELAYED_DIAL_ROUND_TRIPS + 2 * CIRCUIT_REQUEST_ROUND_TRIPS;
367
+
349
368
  /**
350
369
  * What a block-transfer push message's BYTES get to cross, on top of the latency
351
370
  * {@link CIRCUIT_REQUEST_ROUND_TRIPS} covers, in milliseconds.
@@ -363,6 +382,24 @@ export const RELAYED_REQUEST_ROUND_TRIPS = RELAYED_DIAL_ROUND_TRIPS + CIRCUIT_RE
363
382
  */
364
383
  export const PUSH_TRANSFER_ALLOWANCE_MS = 6000;
365
384
 
385
+ /**
386
+ * What ICE — WebRTC's connectivity check — gets on top of the signalling exchanges
387
+ * {@link WEBRTC_SIGNALING_ROUND_TRIPS} covers, in milliseconds: gathering each side's candidates
388
+ * (which includes asking a STUN server for the address it is seen at outside its NAT —
389
+ * `ops/docs/ice-servers.md`) and then the checks between candidate pairs. Those checks cross the
390
+ * two networks' own paths, not the relay, so this part does not scale with the declared relay
391
+ * round trip, any more than a push's bytes do.
392
+ *
393
+ * 25 000 ms is deliberately LONGER than the roughly 23 s the WebRTC stack takes to give up by
394
+ * itself when no candidate pair works (gotchoices/sereus#61), so the upgrade dial's deadline is
395
+ * a backstop rather than the thing that normally ends an attempt. That is the right way round
396
+ * here because nothing waits on an upgrade dial — it runs in the background while the relayed
397
+ * connection carries everything (`docs/network/relay.md` → "Direct connections over WebRTC") —
398
+ * so cutting a slow but working negotiation off would lose a direct path for nothing, while
399
+ * erring long costs one timer.
400
+ */
401
+ export const ICE_NEGOTIATION_ALLOWANCE_MS = 25_000;
402
+
366
403
  /**
367
404
  * Deadline for one admission decision, after which the fail-open outcome is
368
405
  * used (connection admitted / reservation admitted). Both inbound gaters use
@@ -418,7 +455,7 @@ export const PUSH_TRANSFER_ALLOWANCE_MS = 6000;
418
455
  * `CONTROL_READ_RETRY_BUDGET_MS` must stay below this, which
419
456
  * `control-read-retry.spec.ts` pins.
420
457
  */
421
- // eslint-disable-next-line no-restricted-syntax -- cuts off by design: an expired decision admits a connection only, and the dial budgets add it as a flat allowance; see docs/cadre-consistency.md → "Deadlines Over Optimystic's Reads and Commits"
458
+ // eslint-disable-next-line no-restricted-syntax -- cuts off by design: an expired decision admits a connection only, and the dial budgets add it as a flat allowance; see docs/network/deadlines.md → "Deadlines over Optimystic's reads and commits"
422
459
  export const ADMISSION_DECISION_TIMEOUT_MS = 2_000;
423
460
 
424
461
  /**
@@ -545,6 +582,25 @@ export function relayedRequestBudgetMs(linkRoundTripMs?: number): number {
545
582
  return relayedDialBudgetMs(linkRoundTripMs) + CIRCUIT_REQUEST_ROUND_TRIPS * resolveLinkRoundTripMs(linkRoundTripMs);
546
583
  }
547
584
 
585
+ /**
586
+ * Deadline for ONE background WebRTC upgrade dial of a peer this node already reaches through a
587
+ * relay (`webrtc-upgrade.ts`): the signalling over that relay
588
+ * ({@link WEBRTC_SIGNALING_ROUND_TRIPS} at the declared link round trip, plus one
589
+ * {@link ADMISSION_DECISION_TIMEOUT_MS} for each of the {@link DIAL_ADMISSION_DECISIONS} gates
590
+ * the signalling connection can pass) and then {@link ICE_NEGOTIATION_ALLOWANCE_MS} for ICE.
591
+ * 9 x 3 500 + 2 x 2 000 + 25 000 = 60 500 ms at the default declaration.
592
+ *
593
+ * The longest budget in this module and the one with the least riding on it: no caller waits for
594
+ * an upgrade dial, and while it runs the relayed connection carries everything. The two
595
+ * constants say why each half is shaped the way it is — in particular why erring long is right
596
+ * here and wrong for every other budget above.
597
+ */
598
+ export function webrtcUpgradeDialBudgetMs(linkRoundTripMs?: number): number {
599
+ return WEBRTC_SIGNALING_ROUND_TRIPS * resolveLinkRoundTripMs(linkRoundTripMs)
600
+ + DIAL_ADMISSION_DECISIONS * ADMISSION_DECISION_TIMEOUT_MS
601
+ + ICE_NEGOTIATION_ALLOWANCE_MS;
602
+ }
603
+
548
604
  /**
549
605
  * How long ONE cohort peer gets to answer ONE read-path request — Optimystic's
550
606
  * `clusterPolicy.cohortQueryTimeoutMs`, which bounds the latest-revision query a read runs when