@serfab/cadre-core 0.10.0 → 0.11.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 (105) hide show
  1. package/README.md +255 -255
  2. package/dist/cadre-node.d.ts +203 -28
  3. package/dist/cadre-node.js +445 -84
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-cohort.d.ts +26 -0
  6. package/dist/control-cohort.js +26 -0
  7. package/dist/control-cohort.js.map +1 -1
  8. package/dist/control-database.d.ts +82 -117
  9. package/dist/control-database.js +217 -295
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-formation-recorder.d.ts +8 -7
  12. package/dist/control-formation-recorder.js +8 -7
  13. package/dist/control-formation-recorder.js.map +1 -1
  14. package/dist/control-schema.d.ts +1 -1
  15. package/dist/control-schema.js +789 -774
  16. package/dist/control-schema.js.map +1 -1
  17. package/dist/control-write-retry.d.ts +15 -5
  18. package/dist/control-write-retry.js +19 -18
  19. package/dist/control-write-retry.js.map +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/peer-addr-book.d.ts +92 -0
  24. package/dist/peer-addr-book.js +220 -0
  25. package/dist/peer-addr-book.js.map +1 -0
  26. package/dist/seed-bootstrap.d.ts +7 -0
  27. package/dist/seed-bootstrap.js +15 -13
  28. package/dist/seed-bootstrap.js.map +1 -1
  29. package/dist/strand-cohort.d.ts +4 -37
  30. package/dist/strand-cohort.js +4 -15
  31. package/dist/strand-cohort.js.map +1 -1
  32. package/dist/strand-database.d.ts +11 -16
  33. package/dist/strand-database.js +19 -7
  34. package/dist/strand-database.js.map +1 -1
  35. package/dist/strand-formation-manager.d.ts +8 -8
  36. package/dist/strand-formation-manager.js +15 -18
  37. package/dist/strand-formation-manager.js.map +1 -1
  38. package/dist/strand-instance-manager.d.ts +52 -21
  39. package/dist/strand-instance-manager.js +100 -34
  40. package/dist/strand-instance-manager.js.map +1 -1
  41. package/dist/strand-membership-writer.d.ts +6 -4
  42. package/dist/strand-membership-writer.js +38 -36
  43. package/dist/strand-membership-writer.js.map +1 -1
  44. package/dist/types.d.ts +39 -31
  45. package/dist/types.js.map +1 -1
  46. package/package.json +8 -7
  47. package/src/arachnode-stub.ts +159 -159
  48. package/src/bootstrap-peer-store-file.ts +44 -44
  49. package/src/bootstrap-peer-store.ts +172 -172
  50. package/src/cadre-node.ts +5158 -4771
  51. package/src/canonical-json.ts +30 -30
  52. package/src/control-authorization.ts +114 -114
  53. package/src/control-cohort.ts +130 -103
  54. package/src/control-database.ts +2406 -2506
  55. package/src/control-formation-recorder.ts +305 -304
  56. package/src/control-schema.ts +801 -786
  57. package/src/control-stream.ts +205 -205
  58. package/src/control-write-retry.ts +483 -473
  59. package/src/delegate-admission.ts +302 -302
  60. package/src/device-token.ts +94 -94
  61. package/src/diagnostics/connection-path.ts +277 -277
  62. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  63. package/src/ed25519-key.ts +134 -134
  64. package/src/enrollment.ts +199 -199
  65. package/src/file-durable-slot.ts +61 -61
  66. package/src/formation-approval.ts +604 -604
  67. package/src/fs-atomic.ts +107 -107
  68. package/src/hibernation-manager.ts +437 -437
  69. package/src/identity-key.ts +109 -109
  70. package/src/index.ts +1 -0
  71. package/src/key-store-file.ts +132 -132
  72. package/src/key-store.ts +99 -99
  73. package/src/membership-connection-gater.ts +204 -204
  74. package/src/node-local-snapshot.ts +260 -260
  75. package/src/peer-addr-book.ts +250 -0
  76. package/src/peer-authorization.ts +259 -259
  77. package/src/peer-record.ts +164 -164
  78. package/src/push-credentials.ts +84 -84
  79. package/src/push-node.ts +64 -64
  80. package/src/push-notifier-apns.ts +247 -247
  81. package/src/push-notifier-fcm.ts +220 -220
  82. package/src/push-notifier-shared.ts +28 -28
  83. package/src/push-notifier.ts +52 -52
  84. package/src/relay-addrs.ts +111 -111
  85. package/src/relay-reservation.ts +823 -823
  86. package/src/seed-bootstrap.ts +15 -15
  87. package/src/seed-trust-policy.ts +140 -140
  88. package/src/strand-addr-protocol.ts +441 -441
  89. package/src/strand-backfill.ts +366 -366
  90. package/src/strand-cohort.ts +38 -77
  91. package/src/strand-database.ts +202 -204
  92. package/src/strand-formation-manager.ts +491 -494
  93. package/src/strand-formation-protocol.ts +692 -692
  94. package/src/strand-instance-manager.ts +108 -50
  95. package/src/strand-member-key.ts +39 -39
  96. package/src/strand-member-registry.ts +182 -182
  97. package/src/strand-membership-writer.ts +1432 -1430
  98. package/src/strand-solicitation.ts +472 -472
  99. package/src/strand-transport-key.ts +58 -58
  100. package/src/strand-wake-payload.ts +32 -32
  101. package/src/strand-wake-protocol.ts +314 -314
  102. package/src/strand-watcher.ts +314 -314
  103. package/src/trusted-owner-store-file.ts +41 -41
  104. package/src/trusted-owner-store.ts +171 -171
  105. package/src/types.ts +1309 -1303
@@ -1,109 +1,109 @@
1
- /**
2
- * identity-key — the load-or-create rule for a {@link KeyStore}-backed node
3
- * identity, plus the "prove you hold this node key" signer built on top of it.
4
- *
5
- * Both live here because both are needed *outside* `CadreNode`: an embedding app
6
- * (the React Native reference app) has to resolve its identity key before the node
7
- * is constructed, so it can sign an out-of-band HTTP request with the same key the
8
- * node will then load. Keeping one copy of the load-or-create rule is load-bearing
9
- * — a second copy that drifted could generate a fresh key and orphan the real
10
- * identity.
11
- *
12
- * Dependency-free beyond `@libp2p/crypto` + `uint8arrays` (both already core
13
- * dependencies), so this module is safe in every (RN / browser / Node) entry graph.
14
- */
15
- import debug from 'debug';
16
- import { generateKeyPair, privateKeyToProtobuf, privateKeyFromProtobuf, publicKeyToProtobuf } from '@libp2p/crypto/keys';
17
- import { toString as uint8ArrayToString } from 'uint8arrays';
18
- import type { PrivateKey } from '@libp2p/interface';
19
- import { DEFAULT_IDENTITY_KEY_ID, type KeyId, type KeyStore } from './key-store.js';
20
-
21
- const log = debug('sereus:cadre:identity-key');
22
-
23
- /**
24
- * Load the node identity key from `keyStore`, generating and persisting a fresh
25
- * Ed25519 key when the slot is empty.
26
- *
27
- * A rejected `get` (e.g. {@link KeyStoreAccessError} from a cancelled biometric
28
- * prompt) **propagates** — we never fall through to generation on a read error,
29
- * because that would silently orphan an existing but momentarily unreadable
30
- * identity. Corrupt bytes in the slot likewise throw rather than regenerate.
31
- *
32
- * Idempotent in effect: a second call on a populated store loads the stored key
33
- * and writes nothing.
34
- *
35
- * @param keyStore - Backend the identity is read from / persisted to.
36
- * @param keyId - Slot id; defaults to {@link DEFAULT_IDENTITY_KEY_ID}.
37
- * @returns The resolved libp2p private key.
38
- */
39
- export async function loadOrCreateIdentityKey(
40
- keyStore: KeyStore,
41
- keyId: KeyId = DEFAULT_IDENTITY_KEY_ID
42
- ): Promise<PrivateKey> {
43
- // A rejection here (e.g. KeyStoreAccessError) must propagate — do NOT fall
44
- // through to generation, which would orphan an existing but unreadable key.
45
- const bytes = await keyStore.get(keyId);
46
- if (bytes) {
47
- // Corrupt/garbage bytes throw here; surface loudly rather than
48
- // regenerating (which would orphan the real identity).
49
- const loaded = privateKeyFromProtobuf(bytes);
50
- log('Identity key loaded from key store (slot present)');
51
- return loaded;
52
- }
53
-
54
- const generated = await generateKeyPair('Ed25519');
55
- await keyStore.set(keyId, privateKeyToProtobuf(generated));
56
- log('Identity key generated and persisted to key store (first run)');
57
- return generated;
58
- }
59
-
60
- /**
61
- * Proof-of-possession signer for a node key, for out-of-band HTTP services that
62
- * want to attribute a request to a peer id.
63
- *
64
- * Deliberately generic — it carries no ICE/TURN vocabulary, and the message it
65
- * signs is the caller's business. The one consumer today is the reference apps'
66
- * `loadIceConfig`, which signs the TURN credential issuer's peer assertion; those
67
- * files mirror this interface structurally rather than importing it, so they stay
68
- * dependency-free.
69
- */
70
- export interface PeerKeySigner {
71
- /** base58btc peer id — the same string libp2p reports for this node. */
72
- readonly peerId: string;
73
- /** base64url of the libp2p protobuf-encoded public key. */
74
- readonly publicKeyB64: string;
75
- /** Sign the UTF-8 bytes of `message`; resolves to a base64url signature. */
76
- sign(message: string): Promise<string>;
77
- }
78
-
79
- /**
80
- * Wrap a libp2p private key as a {@link PeerKeySigner}.
81
- *
82
- * Ed25519 only: the peer id is derived as an identity multihash (so
83
- * `publicKey.toString()` already *is* the base58btc peer id — no `@libp2p/peer-id`
84
- * round trip needed), and verifiers of this proof accept nothing else.
85
- *
86
- * @param privateKey - The node's libp2p Ed25519 private key.
87
- * @returns A signer exposing the peer id, the encoded public key, and `sign`.
88
- * @throws If the key is not Ed25519.
89
- */
90
- export function peerKeySigner(privateKey: PrivateKey): PeerKeySigner {
91
- if (privateKey.type !== 'Ed25519') {
92
- throw new Error(`peerKeySigner requires an Ed25519 key, got ${privateKey.type}`);
93
- }
94
-
95
- const publicKey = privateKey.publicKey;
96
- // For Ed25519 the public key's digest is an identity multihash, so its string
97
- // form is the peer id itself — the same value `peerIdFromPrivateKey` produces.
98
- const peerId = publicKey.toString();
99
- const publicKeyB64 = uint8ArrayToString(publicKeyToProtobuf(publicKey), 'base64url');
100
-
101
- return {
102
- peerId,
103
- publicKeyB64,
104
- async sign(message: string): Promise<string> {
105
- const signature = await privateKey.sign(new TextEncoder().encode(message));
106
- return uint8ArrayToString(signature, 'base64url');
107
- }
108
- };
109
- }
1
+ /**
2
+ * identity-key — the load-or-create rule for a {@link KeyStore}-backed node
3
+ * identity, plus the "prove you hold this node key" signer built on top of it.
4
+ *
5
+ * Both live here because both are needed *outside* `CadreNode`: an embedding app
6
+ * (the React Native reference app) has to resolve its identity key before the node
7
+ * is constructed, so it can sign an out-of-band HTTP request with the same key the
8
+ * node will then load. Keeping one copy of the load-or-create rule is load-bearing
9
+ * — a second copy that drifted could generate a fresh key and orphan the real
10
+ * identity.
11
+ *
12
+ * Dependency-free beyond `@libp2p/crypto` + `uint8arrays` (both already core
13
+ * dependencies), so this module is safe in every (RN / browser / Node) entry graph.
14
+ */
15
+ import debug from 'debug';
16
+ import { generateKeyPair, privateKeyToProtobuf, privateKeyFromProtobuf, publicKeyToProtobuf } from '@libp2p/crypto/keys';
17
+ import { toString as uint8ArrayToString } from 'uint8arrays';
18
+ import type { PrivateKey } from '@libp2p/interface';
19
+ import { DEFAULT_IDENTITY_KEY_ID, type KeyId, type KeyStore } from './key-store.js';
20
+
21
+ const log = debug('sereus:cadre:identity-key');
22
+
23
+ /**
24
+ * Load the node identity key from `keyStore`, generating and persisting a fresh
25
+ * Ed25519 key when the slot is empty.
26
+ *
27
+ * A rejected `get` (e.g. {@link KeyStoreAccessError} from a cancelled biometric
28
+ * prompt) **propagates** — we never fall through to generation on a read error,
29
+ * because that would silently orphan an existing but momentarily unreadable
30
+ * identity. Corrupt bytes in the slot likewise throw rather than regenerate.
31
+ *
32
+ * Idempotent in effect: a second call on a populated store loads the stored key
33
+ * and writes nothing.
34
+ *
35
+ * @param keyStore - Backend the identity is read from / persisted to.
36
+ * @param keyId - Slot id; defaults to {@link DEFAULT_IDENTITY_KEY_ID}.
37
+ * @returns The resolved libp2p private key.
38
+ */
39
+ export async function loadOrCreateIdentityKey(
40
+ keyStore: KeyStore,
41
+ keyId: KeyId = DEFAULT_IDENTITY_KEY_ID
42
+ ): Promise<PrivateKey> {
43
+ // A rejection here (e.g. KeyStoreAccessError) must propagate — do NOT fall
44
+ // through to generation, which would orphan an existing but unreadable key.
45
+ const bytes = await keyStore.get(keyId);
46
+ if (bytes) {
47
+ // Corrupt/garbage bytes throw here; surface loudly rather than
48
+ // regenerating (which would orphan the real identity).
49
+ const loaded = privateKeyFromProtobuf(bytes);
50
+ log('Identity key loaded from key store (slot present)');
51
+ return loaded;
52
+ }
53
+
54
+ const generated = await generateKeyPair('Ed25519');
55
+ await keyStore.set(keyId, privateKeyToProtobuf(generated));
56
+ log('Identity key generated and persisted to key store (first run)');
57
+ return generated;
58
+ }
59
+
60
+ /**
61
+ * Proof-of-possession signer for a node key, for out-of-band HTTP services that
62
+ * want to attribute a request to a peer id.
63
+ *
64
+ * Deliberately generic — it carries no ICE/TURN vocabulary, and the message it
65
+ * signs is the caller's business. The one consumer today is the reference apps'
66
+ * `loadIceConfig`, which signs the TURN credential issuer's peer assertion; those
67
+ * files mirror this interface structurally rather than importing it, so they stay
68
+ * dependency-free.
69
+ */
70
+ export interface PeerKeySigner {
71
+ /** base58btc peer id — the same string libp2p reports for this node. */
72
+ readonly peerId: string;
73
+ /** base64url of the libp2p protobuf-encoded public key. */
74
+ readonly publicKeyB64: string;
75
+ /** Sign the UTF-8 bytes of `message`; resolves to a base64url signature. */
76
+ sign(message: string): Promise<string>;
77
+ }
78
+
79
+ /**
80
+ * Wrap a libp2p private key as a {@link PeerKeySigner}.
81
+ *
82
+ * Ed25519 only: the peer id is derived as an identity multihash (so
83
+ * `publicKey.toString()` already *is* the base58btc peer id — no `@libp2p/peer-id`
84
+ * round trip needed), and verifiers of this proof accept nothing else.
85
+ *
86
+ * @param privateKey - The node's libp2p Ed25519 private key.
87
+ * @returns A signer exposing the peer id, the encoded public key, and `sign`.
88
+ * @throws If the key is not Ed25519.
89
+ */
90
+ export function peerKeySigner(privateKey: PrivateKey): PeerKeySigner {
91
+ if (privateKey.type !== 'Ed25519') {
92
+ throw new Error(`peerKeySigner requires an Ed25519 key, got ${privateKey.type}`);
93
+ }
94
+
95
+ const publicKey = privateKey.publicKey;
96
+ // For Ed25519 the public key's digest is an identity multihash, so its string
97
+ // form is the peer id itself — the same value `peerIdFromPrivateKey` produces.
98
+ const peerId = publicKey.toString();
99
+ const publicKeyB64 = uint8ArrayToString(publicKeyToProtobuf(publicKey), 'base64url');
100
+
101
+ return {
102
+ peerId,
103
+ publicKeyB64,
104
+ async sign(message: string): Promise<string> {
105
+ const signature = await privateKey.sign(new TextEncoder().encode(message));
106
+ return uint8ArrayToString(signature, 'base64url');
107
+ }
108
+ };
109
+ }
package/src/index.ts CHANGED
@@ -317,6 +317,7 @@ export {
317
317
  // the cadence/degree defaults the proactive reconcile routine reads.
318
318
  export {
319
319
  selectControlCohortDials,
320
+ DEFAULT_CONTROL_COHORT_DIAL_TIMEOUT_MS,
320
321
  DEFAULT_CONTROL_COHORT_RECONCILE_MS,
321
322
  DEFAULT_CONTROL_COHORT_TARGET_DEGREE,
322
323
  type ControlCohortSelection
@@ -1,132 +1,132 @@
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 { encodeFileSafeComponent, isNotFound, writeFileAtomically } from './fs-atomic.js';
23
-
24
- const log = debug('sereus:cadre:key-store-file');
25
-
26
- /** Suffix appended to the encoded keyId to form a slot filename. */
27
- const SLOT_SUFFIX = '.key';
28
-
29
- /**
30
- * Suffix for the transient file written then atomically renamed over the slot.
31
- * Distinct from {@link SLOT_SUFFIX}, so {@link FileKeyStore.list} (which matches
32
- * only `.key`) never surfaces an in-flight or crash-orphaned temp file.
33
- */
34
- const TEMP_SUFFIX = '.tmp';
35
-
36
- /**
37
- * Percent-encode a keyId into a filesystem-safe filename component (see
38
- * {@link encodeFileSafeComponent} — `.` is escaped so the `.key` suffix is the
39
- * only literal dot, making suffix-stripping in {@link decodeKeyId} unambiguous;
40
- * {@link decodeKeyId} reverses every escape via `decodeURIComponent`).
41
- */
42
- function encodeKeyId(keyId: KeyId): string {
43
- return encodeFileSafeComponent(keyId);
44
- }
45
-
46
- /**
47
- * Reverse {@link encodeKeyId}: strip the slot suffix and percent-decode. Returns
48
- * `undefined` for a `.key` filename this store did not write (a foreign file
49
- * with an invalid percent-sequence), so {@link FileKeyStore.list} can skip it
50
- * rather than letting one undecodable entry throw and break enumeration of every
51
- * real slot.
52
- */
53
- function decodeKeyId(fileName: string): KeyId | undefined {
54
- const encoded = fileName.slice(0, -SLOT_SUFFIX.length);
55
- try {
56
- return decodeURIComponent(encoded);
57
- } catch (error) {
58
- log('FileKeyStore: skipping undecodable slot filename %s: %o', fileName, error);
59
- return undefined;
60
- }
61
- }
62
-
63
- /**
64
- * File-backed {@link KeyStore}. Each slot is `<dir>/<encoded keyId>.key`
65
- * containing the raw material bytes. The directory is created lazily on first
66
- * {@link set}. Suitable for headless Node cadre nodes and tests; for mobile use
67
- * a platform secure-enclave backend instead.
68
- */
69
- export class FileKeyStore implements KeyStore {
70
- constructor(private readonly dir: string) {}
71
-
72
- private slotPath(keyId: KeyId): string {
73
- return join(this.dir, `${encodeKeyId(keyId)}${SLOT_SUFFIX}`);
74
- }
75
-
76
- /**
77
- * Sibling path for the temp file written before the atomic rename. The random
78
- * component makes concurrent {@link set}s to the same slot (and crash-orphaned
79
- * leftovers) collide-free; it lives in the same directory as the slot so the
80
- * final {@link rename} stays within one filesystem and is therefore atomic.
81
- */
82
- private tempPath(keyId: KeyId): string {
83
- const unique = randomBytes(6).toString('hex');
84
- return join(this.dir, `${encodeKeyId(keyId)}.${unique}${TEMP_SUFFIX}`);
85
- }
86
-
87
- async get(keyId: KeyId): Promise<Uint8Array | undefined> {
88
- try {
89
- const buf = await readFile(this.slotPath(keyId));
90
- // Copy into a plain Uint8Array decoupled from Node's Buffer pool.
91
- return new Uint8Array(buf);
92
- } catch (error) {
93
- // A missing slot is "empty" (undefined), NOT an error — so a
94
- // load-or-create caller generates a key rather than mistaking a
95
- // permission failure for absence. Any other failure (e.g. EACCES) is
96
- // surfaced as access-denied so callers do not clobber an existing key.
97
- if (isNotFound(error)) return undefined;
98
- throw new KeyStoreAccessError(keyId, `FileKeyStore: failed to read key slot ${keyId}`, { cause: error });
99
- }
100
- }
101
-
102
- /**
103
- * Crash-atomic write: a concurrent reader sees either the complete previous
104
- * bytes or the complete new bytes, never a torn slot. The new material is
105
- * written to a sibling temp file, fsync'd, then atomically renamed over the
106
- * slot (see {@link writeFileAtomically}). A failure at any point removes the
107
- * temp file and leaves the previous slot untouched.
108
- */
109
- async set(keyId: KeyId, keyMaterial: Uint8Array): Promise<void> {
110
- await writeFileAtomically(this.dir, this.tempPath(keyId), this.slotPath(keyId), keyMaterial);
111
- }
112
-
113
- async delete(keyId: KeyId): Promise<void> {
114
- // force:true makes removing an absent slot a no-op (idempotent).
115
- await rm(this.slotPath(keyId), { force: true });
116
- }
117
-
118
- async list(): Promise<KeyId[]> {
119
- let entries: string[];
120
- try {
121
- entries = await readdir(this.dir);
122
- } catch (error) {
123
- // An absent directory means no slots yet — not a failure.
124
- if (isNotFound(error)) return [];
125
- throw new Error('FileKeyStore: failed to list key directory', { cause: error });
126
- }
127
- return entries
128
- .filter((name) => name.endsWith(SLOT_SUFFIX))
129
- .map(decodeKeyId)
130
- .filter((id): id is KeyId => id !== undefined);
131
- }
132
- }
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 { encodeFileSafeComponent, isNotFound, writeFileAtomically } from './fs-atomic.js';
23
+
24
+ const log = debug('sereus:cadre:key-store-file');
25
+
26
+ /** Suffix appended to the encoded keyId to form a slot filename. */
27
+ const SLOT_SUFFIX = '.key';
28
+
29
+ /**
30
+ * Suffix for the transient file written then atomically renamed over the slot.
31
+ * Distinct from {@link SLOT_SUFFIX}, so {@link FileKeyStore.list} (which matches
32
+ * only `.key`) never surfaces an in-flight or crash-orphaned temp file.
33
+ */
34
+ const TEMP_SUFFIX = '.tmp';
35
+
36
+ /**
37
+ * Percent-encode a keyId into a filesystem-safe filename component (see
38
+ * {@link encodeFileSafeComponent} — `.` is escaped so the `.key` suffix is the
39
+ * only literal dot, making suffix-stripping in {@link decodeKeyId} unambiguous;
40
+ * {@link decodeKeyId} reverses every escape via `decodeURIComponent`).
41
+ */
42
+ function encodeKeyId(keyId: KeyId): string {
43
+ return encodeFileSafeComponent(keyId);
44
+ }
45
+
46
+ /**
47
+ * Reverse {@link encodeKeyId}: strip the slot suffix and percent-decode. Returns
48
+ * `undefined` for a `.key` filename this store did not write (a foreign file
49
+ * with an invalid percent-sequence), so {@link FileKeyStore.list} can skip it
50
+ * rather than letting one undecodable entry throw and break enumeration of every
51
+ * real slot.
52
+ */
53
+ function decodeKeyId(fileName: string): KeyId | undefined {
54
+ const encoded = fileName.slice(0, -SLOT_SUFFIX.length);
55
+ try {
56
+ return decodeURIComponent(encoded);
57
+ } catch (error) {
58
+ log('FileKeyStore: skipping undecodable slot filename %s: %o', fileName, error);
59
+ return undefined;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * File-backed {@link KeyStore}. Each slot is `<dir>/<encoded keyId>.key`
65
+ * containing the raw material bytes. The directory is created lazily on first
66
+ * {@link set}. Suitable for headless Node cadre nodes and tests; for mobile use
67
+ * a platform secure-enclave backend instead.
68
+ */
69
+ export class FileKeyStore implements KeyStore {
70
+ constructor(private readonly dir: string) {}
71
+
72
+ private slotPath(keyId: KeyId): string {
73
+ return join(this.dir, `${encodeKeyId(keyId)}${SLOT_SUFFIX}`);
74
+ }
75
+
76
+ /**
77
+ * Sibling path for the temp file written before the atomic rename. The random
78
+ * component makes concurrent {@link set}s to the same slot (and crash-orphaned
79
+ * leftovers) collide-free; it lives in the same directory as the slot so the
80
+ * final {@link rename} stays within one filesystem and is therefore atomic.
81
+ */
82
+ private tempPath(keyId: KeyId): string {
83
+ const unique = randomBytes(6).toString('hex');
84
+ return join(this.dir, `${encodeKeyId(keyId)}.${unique}${TEMP_SUFFIX}`);
85
+ }
86
+
87
+ async get(keyId: KeyId): Promise<Uint8Array | undefined> {
88
+ try {
89
+ const buf = await readFile(this.slotPath(keyId));
90
+ // Copy into a plain Uint8Array decoupled from Node's Buffer pool.
91
+ return new Uint8Array(buf);
92
+ } catch (error) {
93
+ // A missing slot is "empty" (undefined), NOT an error — so a
94
+ // load-or-create caller generates a key rather than mistaking a
95
+ // permission failure for absence. Any other failure (e.g. EACCES) is
96
+ // surfaced as access-denied so callers do not clobber an existing key.
97
+ if (isNotFound(error)) return undefined;
98
+ throw new KeyStoreAccessError(keyId, `FileKeyStore: failed to read key slot ${keyId}`, { cause: error });
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Crash-atomic write: a concurrent reader sees either the complete previous
104
+ * bytes or the complete new bytes, never a torn slot. The new material is
105
+ * written to a sibling temp file, fsync'd, then atomically renamed over the
106
+ * slot (see {@link writeFileAtomically}). A failure at any point removes the
107
+ * temp file and leaves the previous slot untouched.
108
+ */
109
+ async set(keyId: KeyId, keyMaterial: Uint8Array): Promise<void> {
110
+ await writeFileAtomically(this.dir, this.tempPath(keyId), this.slotPath(keyId), keyMaterial);
111
+ }
112
+
113
+ async delete(keyId: KeyId): Promise<void> {
114
+ // force:true makes removing an absent slot a no-op (idempotent).
115
+ await rm(this.slotPath(keyId), { force: true });
116
+ }
117
+
118
+ async list(): Promise<KeyId[]> {
119
+ let entries: string[];
120
+ try {
121
+ entries = await readdir(this.dir);
122
+ } catch (error) {
123
+ // An absent directory means no slots yet — not a failure.
124
+ if (isNotFound(error)) return [];
125
+ throw new Error('FileKeyStore: failed to list key directory', { cause: error });
126
+ }
127
+ return entries
128
+ .filter((name) => name.endsWith(SLOT_SUFFIX))
129
+ .map(decodeKeyId)
130
+ .filter((id): id is KeyId => id !== undefined);
131
+ }
132
+ }