@did-btcr2/cli 0.15.0 → 0.16.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 (71) hide show
  1. package/README.md +47 -6
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/cjs/index.js +563 -117
  4. package/dist/esm/src/cli.js +7 -4
  5. package/dist/esm/src/cli.js.map +1 -1
  6. package/dist/esm/src/commands/config.js +11 -15
  7. package/dist/esm/src/commands/config.js.map +1 -1
  8. package/dist/esm/src/commands/create.js +4 -1
  9. package/dist/esm/src/commands/create.js.map +1 -1
  10. package/dist/esm/src/commands/deactivate.js +3 -1
  11. package/dist/esm/src/commands/deactivate.js.map +1 -1
  12. package/dist/esm/src/commands/index.js +2 -0
  13. package/dist/esm/src/commands/index.js.map +1 -1
  14. package/dist/esm/src/commands/init.js +63 -0
  15. package/dist/esm/src/commands/init.js.map +1 -0
  16. package/dist/esm/src/commands/keystore.js +81 -0
  17. package/dist/esm/src/commands/keystore.js.map +1 -0
  18. package/dist/esm/src/commands/profile.js +1 -1
  19. package/dist/esm/src/commands/profile.js.map +1 -1
  20. package/dist/esm/src/commands/update.js +3 -1
  21. package/dist/esm/src/commands/update.js.map +1 -1
  22. package/dist/esm/src/config.js +85 -28
  23. package/dist/esm/src/config.js.map +1 -1
  24. package/dist/esm/src/keystore/file-key-store.js +340 -32
  25. package/dist/esm/src/keystore/file-key-store.js.map +1 -1
  26. package/dist/esm/src/keystore/passphrase.js +40 -10
  27. package/dist/esm/src/keystore/passphrase.js.map +1 -1
  28. package/dist/esm/src/keystore/paths.js +6 -18
  29. package/dist/esm/src/keystore/paths.js.map +1 -1
  30. package/dist/esm/src/paths.js +59 -0
  31. package/dist/esm/src/paths.js.map +1 -0
  32. package/dist/esm/src/types.js.map +1 -1
  33. package/dist/types/src/cli.d.ts.map +1 -1
  34. package/dist/types/src/commands/config.d.ts.map +1 -1
  35. package/dist/types/src/commands/create.d.ts.map +1 -1
  36. package/dist/types/src/commands/deactivate.d.ts.map +1 -1
  37. package/dist/types/src/commands/index.d.ts +2 -0
  38. package/dist/types/src/commands/index.d.ts.map +1 -1
  39. package/dist/types/src/commands/init.d.ts +13 -0
  40. package/dist/types/src/commands/init.d.ts.map +1 -0
  41. package/dist/types/src/commands/keystore.d.ts +10 -0
  42. package/dist/types/src/commands/keystore.d.ts.map +1 -0
  43. package/dist/types/src/commands/update.d.ts.map +1 -1
  44. package/dist/types/src/config.d.ts +38 -14
  45. package/dist/types/src/config.d.ts.map +1 -1
  46. package/dist/types/src/keystore/file-key-store.d.ts +86 -10
  47. package/dist/types/src/keystore/file-key-store.d.ts.map +1 -1
  48. package/dist/types/src/keystore/passphrase.d.ts +16 -1
  49. package/dist/types/src/keystore/passphrase.d.ts.map +1 -1
  50. package/dist/types/src/keystore/paths.d.ts +6 -10
  51. package/dist/types/src/keystore/paths.d.ts.map +1 -1
  52. package/dist/types/src/paths.d.ts +54 -0
  53. package/dist/types/src/paths.d.ts.map +1 -0
  54. package/dist/types/src/types.d.ts +38 -0
  55. package/dist/types/src/types.d.ts.map +1 -1
  56. package/package.json +3 -3
  57. package/src/cli.ts +8 -3
  58. package/src/commands/config.ts +12 -14
  59. package/src/commands/create.ts +4 -1
  60. package/src/commands/deactivate.ts +3 -1
  61. package/src/commands/index.ts +2 -0
  62. package/src/commands/init.ts +74 -0
  63. package/src/commands/keystore.ts +98 -0
  64. package/src/commands/profile.ts +1 -1
  65. package/src/commands/update.ts +3 -1
  66. package/src/config.ts +93 -32
  67. package/src/keystore/file-key-store.ts +455 -43
  68. package/src/keystore/passphrase.ts +48 -8
  69. package/src/keystore/paths.ts +6 -19
  70. package/src/paths.ts +79 -0
  71. package/src/types.ts +13 -1
@@ -1,7 +1,9 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { dirname } from 'node:path';
3
3
  import type { KeyEntry, KeyIdentifier, KeyValueStore } from '@did-btcr2/key-manager';
4
+ import { utf8ToBytes } from '@noble/hashes/utils.js';
4
5
  import { base64urlnopad } from '@scure/base';
6
+ import type { KeystoreProtectionLabel } from '../types.js';
5
7
  import { assertSecurePerms, ensureDir, writeFileAtomic } from './atomic.js';
6
8
  import { DEFAULT_ARGON_PARAMS, decryptSecret, encryptSecret } from './envelope.js';
7
9
  import type { ArgonParams, SecretEnvelope } from './envelope.js';
@@ -12,18 +14,56 @@ import { defaultKeystorePath } from './paths.js';
12
14
  /** Current on-disk keystore file format version. */
13
15
  export const KEYSTORE_VERSION = 1 as const;
14
16
 
15
- /** One key as stored on disk: public material in clear, secret sealed (or absent for watch-only). */
17
+ /**
18
+ * How a keystore protects its secrets on disk:
19
+ * - `passphrase`: each secret is sealed in its own argon2id + XChaCha20-Poly1305
20
+ * envelope, all opened by one shared, verifier-checked passphrase.
21
+ * - `none`: a dev keystore; secrets are stored as plaintext bytes. Never prompts;
22
+ * refused for mainnet (ADR 080). For disposable testnet material only.
23
+ */
24
+ export type KeystoreProtection = 'passphrase' | 'none';
25
+
26
+ /**
27
+ * Fixed sentinel sealed under the keystore passphrase and stored as the file's
28
+ * `verifier`. Decrypting it checks a candidate passphrase before any real secret
29
+ * is sealed or opened, so a typo fails loudly instead of corrupting the store.
30
+ */
31
+ const VERIFIER_PLAINTEXT = utf8ToBytes('did-btcr2-keystore-verifier-v1');
32
+
33
+ /** Constant-length-independent byte compare for the verifier sentinel. */
34
+ function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
35
+ if (a.length !== b.length) return false;
36
+ let diff = 0;
37
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
38
+ return diff === 0;
39
+ }
40
+
41
+ /** Whether two secret envelopes are byte-identical (structural JSON compare). */
42
+ function sameEnvelope(a: SecretEnvelope | undefined, b: SecretEnvelope | undefined): boolean {
43
+ return JSON.stringify(a) === JSON.stringify(b);
44
+ }
45
+
46
+ /**
47
+ * One key as stored on disk: public material in clear, and the secret either
48
+ * sealed (`secret`, encrypted keystore), stored in the clear (`plainSecret`, dev
49
+ * keystore), or absent (watch-only).
50
+ */
16
51
  type StoredKey = {
17
- publicKey : string;
18
- tags? : Record<string, string>;
19
- secret? : SecretEnvelope;
52
+ publicKey : string;
53
+ tags? : Record<string, string>;
54
+ secret? : SecretEnvelope;
55
+ plainSecret? : string;
20
56
  };
21
57
 
22
58
  /** The whole keystore file. */
23
59
  type KeystoreFile = {
24
- v : typeof KEYSTORE_VERSION;
25
- active? : string;
26
- keys : Record<string, StoredKey>;
60
+ v : typeof KEYSTORE_VERSION;
61
+ /** Protection mode, present on every keystore this CLI writes: `passphrase` (encrypted) or `none` (dev). */
62
+ protection? : KeystoreProtection;
63
+ /** Passphrase verifier, present once an encrypted keystore's passphrase is established. */
64
+ verifier? : SecretEnvelope;
65
+ active? : string;
66
+ keys : Record<string, StoredKey>;
27
67
  };
28
68
 
29
69
  /** One key in the in-memory cache; the materialized secret is retained per session once decrypted. */
@@ -31,6 +71,8 @@ type CacheEntry = {
31
71
  publicKey : Uint8Array;
32
72
  tags? : Record<string, string>;
33
73
  secret? : SecretEnvelope;
74
+ /** True for a dev-keystore entry whose `decrypted` bytes are stored plaintext, not sealed. */
75
+ plaintext? : boolean;
34
76
  decrypted? : Uint8Array;
35
77
  };
36
78
 
@@ -38,28 +80,45 @@ type CacheEntry = {
38
80
  export type FileKeyStoreOptions = {
39
81
  /** Keystore file path. Defaults to {@link defaultKeystorePath}. */
40
82
  path?: string;
41
- /** Supplies the passphrase lazily, called only when a secret must be sealed or opened. */
42
- getPassphrase: () => string;
83
+ /**
84
+ * Supplies the passphrase lazily, called only when a secret must be sealed or
85
+ * opened. `confirm` is passed as `true` only while establishing a fresh
86
+ * encrypted keystore's passphrase, so the provider prompts twice and requires
87
+ * a match; it is a no-op for non-interactive sources.
88
+ */
89
+ getPassphrase: (opts?: { confirm?: boolean }) => string;
43
90
  /** argon2id cost parameters used when sealing new secrets. Defaults to {@link DEFAULT_ARGON_PARAMS}. */
44
91
  argonParams?: ArgonParams;
45
92
  /** Tuning for the cross-process write lock. Defaults documented on {@link LockOptions}. */
46
93
  lock?: LockOptions;
94
+ /**
95
+ * Protection mode to use when *establishing* a fresh keystore. Defaults to
96
+ * `passphrase` (encrypted). Ignored for an existing keystore, whose on-disk
97
+ * `protection` always wins.
98
+ */
99
+ protection?: KeystoreProtection;
47
100
  };
48
101
 
49
102
  /**
50
- * A Node-only, file-backed {@link KeyValueStore} that encrypts secret keys at
103
+ * A Node-only, file-backed {@link KeyValueStore} that protects secret keys at
51
104
  * rest. It satisfies the synchronous store contract by caching the parsed file
52
105
  * in memory at construction and flushing the whole file atomically on every
53
106
  * mutation.
54
107
  *
108
+ * Encrypted keystores seal each secret in its own argon2id + XChaCha20-Poly1305
109
+ * envelope under one shared passphrase, and store a `verifier` sentinel so a
110
+ * candidate passphrase is checked before it is used (ADR 080): the first
111
+ * passphrase is established with a confirm prompt, and every later use is
112
+ * verified, so a typo is a loud failure rather than a key sealed under an
113
+ * unknown or divergent passphrase. Dev keystores (`protection: 'none'`) store
114
+ * secrets as plaintext and never prompt; they are refused for mainnet by the
115
+ * command layer.
116
+ *
55
117
  * Every mutation runs under an exclusive cross-process lock and, inside that
56
- * lock, reloads the file from disk before applying its change and flushing.
57
- * Caching at construction and flushing the whole file is otherwise a lost-update
58
- * race: two `btcr2` processes that each load, then each write, would have the
59
- * second overwrite the first. The lock serializes the writers and the reload
60
- * merges any change the other made, so concurrent invocations compose instead of
61
- * clobbering. Reads stay lock-free: an atomic rename means a concurrent reader
62
- * always sees a complete file, old or new.
118
+ * lock, reloads the file from disk before applying its change and flushing, so
119
+ * concurrent `btcr2` invocations compose instead of clobbering. Reads stay
120
+ * lock-free: an atomic rename means a concurrent reader always sees a complete
121
+ * file, old or new.
63
122
  *
64
123
  * Secrets are materialized only through {@link FileKeyStore.get}. The
65
124
  * {@link FileKeyStore.list} and {@link FileKeyStore.entries} projections omit
@@ -70,10 +129,12 @@ export class FileKeyStore implements KeyValueStore<KeyIdentifier, KeyEntry> {
70
129
  readonly #path: string;
71
130
  readonly #lockPath: string;
72
131
  readonly #lockOptions: LockOptions;
73
- readonly #getPassphrase: () => string;
132
+ readonly #getPassphrase: (opts?: { confirm?: boolean }) => string;
74
133
  readonly #argonParams: ArgonParams;
75
134
  readonly #cache: Map<KeyIdentifier, CacheEntry> = new Map();
76
135
  #active: string | undefined;
136
+ #protection: KeystoreProtection;
137
+ #verifier: SecretEnvelope | undefined;
77
138
 
78
139
  constructor(options: FileKeyStoreOptions) {
79
140
  this.#path = options.path ?? defaultKeystorePath();
@@ -81,6 +142,9 @@ export class FileKeyStore implements KeyValueStore<KeyIdentifier, KeyEntry> {
81
142
  this.#lockOptions = options.lock ?? {};
82
143
  this.#getPassphrase = options.getPassphrase;
83
144
  this.#argonParams = options.argonParams ?? DEFAULT_ARGON_PARAMS;
145
+ // The requested mode applies only when establishing a fresh keystore; an
146
+ // existing file's on-disk protection overrides it in #loadFromDisk.
147
+ this.#protection = options.protection ?? 'passphrase';
84
148
  ensureDir(dirname(this.#path), 0o700);
85
149
  this.#loadFromDisk();
86
150
  }
@@ -105,7 +169,34 @@ export class FileKeyStore implements KeyValueStore<KeyIdentifier, KeyEntry> {
105
169
  { version: parsed.v },
106
170
  );
107
171
  }
172
+ // Every keystore this CLI writes carries a recognized protection header. A
173
+ // file without one was not written by this CLI (there is no pre-header
174
+ // format to accommodate); refuse it rather than guess how its secrets are
175
+ // protected.
176
+ if (parsed.protection !== 'none' && parsed.protection !== 'passphrase') {
177
+ throw new KeyStoreError(
178
+ `Keystore at ${this.#path} has no recognized protection header; it was not written by this CLI.`,
179
+ 'KEYSTORE_CORRUPT_ERROR',
180
+ { path: this.#path },
181
+ );
182
+ }
183
+ this.#protection = parsed.protection;
184
+ this.#verifier = parsed.verifier;
108
185
  this.#active = parsed.active;
186
+ // An encrypted keystore that holds sealed keys must carry the verifier that
187
+ // established its passphrase. Without it, the verify-or-establish decision in
188
+ // #sealPassphrase could take the establish path over existing sealed keys and
189
+ // seal a new key under a divergent passphrase; refuse the file instead.
190
+ const sealedPresent = Object.values(parsed.keys ?? {}).some(
191
+ k => k && typeof k === 'object' && (k as StoredKey).secret !== undefined,
192
+ );
193
+ if (this.#protection === 'passphrase' && sealedPresent && this.#verifier === undefined) {
194
+ throw new KeyStoreError(
195
+ `Keystore at ${this.#path} holds sealed keys but no passphrase verifier; it is corrupt or was tampered with.`,
196
+ 'KEYSTORE_CORRUPT_ERROR',
197
+ { path: this.#path },
198
+ );
199
+ }
109
200
  for (const [ id, stored ] of Object.entries(parsed.keys ?? {})) {
110
201
  let publicKey: Uint8Array;
111
202
  try {
@@ -125,25 +216,75 @@ export class FileKeyStore implements KeyValueStore<KeyIdentifier, KeyEntry> {
125
216
  { path: this.#path, keyId: id },
126
217
  );
127
218
  }
128
- this.#cache.set(id, {
129
- publicKey,
130
- ...(stored.tags && { tags: stored.tags }),
131
- ...(stored.secret && { secret: stored.secret }),
132
- });
219
+ const entry: CacheEntry = { publicKey, ...(stored.tags && { tags: stored.tags }) };
220
+ // A secret's storage form must match the keystore's protection mode: a dev
221
+ // keystore holds plaintext, an encrypted keystore holds sealed envelopes. A
222
+ // mismatch is a tampered or foreign file, not something to open blindly.
223
+ if (stored.plainSecret !== undefined) {
224
+ if (this.#protection !== 'none') {
225
+ throw new KeyStoreError(
226
+ `Keystore entry ${id} holds a plaintext secret in an encrypted keystore at ${this.#path}.`,
227
+ 'KEYSTORE_CORRUPT_ERROR',
228
+ { path: this.#path, keyId: id },
229
+ );
230
+ }
231
+ entry.plaintext = true;
232
+ entry.decrypted = this.#decodePlainSecret(stored.plainSecret, id);
233
+ } else if (stored.secret) {
234
+ if (this.#protection !== 'passphrase') {
235
+ throw new KeyStoreError(
236
+ `Keystore entry ${id} holds a sealed secret in a dev keystore at ${this.#path}.`,
237
+ 'KEYSTORE_CORRUPT_ERROR',
238
+ { path: this.#path, keyId: id },
239
+ );
240
+ }
241
+ entry.secret = stored.secret;
242
+ }
243
+ this.#cache.set(id, entry);
133
244
  }
134
245
  }
135
246
 
247
+ /** Decodes and length-checks a dev-keystore plaintext secret. */
248
+ #decodePlainSecret(encoded: string, id: KeyIdentifier): Uint8Array {
249
+ let secret: Uint8Array;
250
+ try {
251
+ secret = base64urlnopad.decode(encoded);
252
+ } catch {
253
+ throw new KeyStoreError(
254
+ `Keystore entry ${id} has a malformed plaintext secret.`,
255
+ 'KEYSTORE_CORRUPT_ERROR',
256
+ { path: this.#path, keyId: id },
257
+ );
258
+ }
259
+ if (secret.length !== 32) {
260
+ throw new KeyStoreError(
261
+ `Keystore entry ${id} has a ${secret.length}-byte secret; expected 32.`,
262
+ 'KEYSTORE_CORRUPT_ERROR',
263
+ { path: this.#path, keyId: id },
264
+ );
265
+ }
266
+ return secret;
267
+ }
268
+
136
269
  #flush(): void {
137
270
  const keys: Record<string, StoredKey> = {};
138
271
  for (const [ id, entry ] of this.#cache) {
139
- keys[id] = {
140
- publicKey : base64urlnopad.encode(entry.publicKey),
141
- ...(entry.tags && { tags: entry.tags }),
142
- ...(entry.secret && { secret: entry.secret }),
143
- };
272
+ const stored: StoredKey = { publicKey: base64urlnopad.encode(entry.publicKey) };
273
+ if (entry.tags) stored.tags = entry.tags;
274
+ if (entry.plaintext && entry.decrypted) {
275
+ stored.plainSecret = base64urlnopad.encode(entry.decrypted);
276
+ } else if (entry.secret) {
277
+ stored.secret = entry.secret;
278
+ }
279
+ keys[id] = stored;
144
280
  }
281
+ // Every keystore this CLI writes self-describes: the protection header is
282
+ // always present (`passphrase` for encrypted, `none` for dev), so a file is
283
+ // never ambiguous about how its secrets are protected.
145
284
  const file: KeystoreFile = {
146
- v : KEYSTORE_VERSION,
285
+ v : KEYSTORE_VERSION,
286
+ protection : this.#protection,
287
+ ...(this.#verifier && { verifier: this.#verifier }),
147
288
  ...(this.#active && { active: this.#active }),
148
289
  keys,
149
290
  };
@@ -155,7 +296,8 @@ export class FileKeyStore implements KeyValueStore<KeyIdentifier, KeyEntry> {
155
296
  * mutation applies on top of whatever other processes have written. Secrets
156
297
  * already decrypted this session are carried over for entries whose sealed
157
298
  * envelope is byte-identical on disk, so a mid-session write does not force a
158
- * re-prompt for keys it did not touch.
299
+ * re-prompt for keys it did not touch. (Dev-keystore plaintext secrets are
300
+ * reloaded from disk, so they need no carry.)
159
301
  */
160
302
  #reload(): void {
161
303
  const carried = new Map<KeyIdentifier, { secret: SecretEnvelope; decrypted: Uint8Array }>();
@@ -188,6 +330,56 @@ export class FileKeyStore implements KeyValueStore<KeyIdentifier, KeyEntry> {
188
330
  }, this.#lockOptions);
189
331
  }
190
332
 
333
+ /**
334
+ * Verifies a candidate passphrase against the keystore verifier, throwing when
335
+ * it does not open the sentinel. A no-op only on a fresh keystore whose
336
+ * passphrase has not been established yet (no verifier to check against).
337
+ */
338
+ #assertPassphrase(passphrase: string): void {
339
+ if (!this.#verifier) return;
340
+ let plain: Uint8Array;
341
+ try {
342
+ plain = decryptSecret(this.#verifier, passphrase);
343
+ } catch {
344
+ throw new KeyStoreError(
345
+ `Incorrect passphrase for the keystore at ${this.#path}.`,
346
+ 'DECRYPT_ERROR',
347
+ { path: this.#path },
348
+ );
349
+ }
350
+ if (!bytesEqual(plain, VERIFIER_PLAINTEXT)) {
351
+ throw new KeyStoreError(
352
+ `Keystore verifier at ${this.#path} did not match; the file may be corrupt.`,
353
+ 'KEYSTORE_CORRUPT_ERROR',
354
+ { path: this.#path },
355
+ );
356
+ }
357
+ }
358
+
359
+ /** Passphrase for opening an existing secret: verified when a verifier exists. */
360
+ #openPassphrase(): string {
361
+ const passphrase = this.#getPassphrase();
362
+ this.#assertPassphrase(passphrase);
363
+ return passphrase;
364
+ }
365
+
366
+ /**
367
+ * Passphrase for sealing a secret. When the keystore's passphrase is already
368
+ * established (a verifier exists), prompt once and verify it. Otherwise this is
369
+ * establishment on a fresh keystore: prompt with confirm and mint a verifier for
370
+ * the caller to persist alongside the first sealed key.
371
+ */
372
+ #sealPassphrase(): { passphrase: string; newVerifier?: SecretEnvelope } {
373
+ if (this.#verifier) {
374
+ const passphrase = this.#getPassphrase();
375
+ this.#assertPassphrase(passphrase);
376
+ return { passphrase };
377
+ }
378
+ const passphrase = this.#getPassphrase({ confirm: true });
379
+ const newVerifier = encryptSecret(VERIFIER_PLAINTEXT, passphrase, this.#argonParams);
380
+ return { passphrase, newVerifier };
381
+ }
382
+
191
383
  get(id: KeyIdentifier): KeyEntry | undefined {
192
384
  const entry = this.#cache.get(id);
193
385
  if (!entry) return undefined;
@@ -195,18 +387,25 @@ export class FileKeyStore implements KeyValueStore<KeyIdentifier, KeyEntry> {
195
387
  publicKey : entry.publicKey,
196
388
  ...(entry.tags && { tags: entry.tags }),
197
389
  };
198
- if (entry.secret) {
199
- // Materialize the secret lazily, only when it is actually accessed, so
200
- // reads that need just public material (an active-key existence check,
201
- // getPublicKey, getEntry) never trigger a passphrase prompt. The property
202
- // is non-enumerable so spreading or serializing the entry cannot silently
203
- // decrypt the secret.
390
+ if (entry.plaintext && entry.decrypted) {
391
+ // Dev keystore: plaintext already materialized; expose without a prompt.
392
+ const secret = entry.decrypted;
393
+ Object.defineProperty(result, 'secretKey', {
394
+ configurable : true,
395
+ enumerable : false,
396
+ get : (): Uint8Array => secret,
397
+ });
398
+ } else if (entry.secret) {
399
+ // Materialize the sealed secret lazily, only when it is actually accessed,
400
+ // so reads that need just public material never trigger a passphrase
401
+ // prompt. The property is non-enumerable so spreading or serializing the
402
+ // entry cannot silently decrypt the secret.
204
403
  const sealed = entry.secret;
205
404
  Object.defineProperty(result, 'secretKey', {
206
405
  configurable : true,
207
406
  enumerable : false,
208
407
  get : (): Uint8Array => {
209
- entry.decrypted ??= decryptSecret(sealed, this.#getPassphrase());
408
+ entry.decrypted ??= decryptSecret(sealed, this.#openPassphrase());
210
409
  return entry.decrypted;
211
410
  },
212
411
  });
@@ -219,16 +418,59 @@ export class FileKeyStore implements KeyValueStore<KeyIdentifier, KeyEntry> {
219
418
  }
220
419
 
221
420
  set(id: KeyIdentifier, value: KeyEntry): void {
222
- // Seal the secret before taking the lock: argon2id is deliberately slow and
223
- // must not extend the critical section that blocks other processes.
224
- const secret = value.secretKey
225
- ? encryptSecret(value.secretKey, this.#getPassphrase(), this.#argonParams)
226
- : undefined;
421
+ if (this.#protection === 'none') {
422
+ // Dev keystore: store the secret in the clear, never prompt.
423
+ this.#mutate(() => {
424
+ this.#cache.set(id, {
425
+ publicKey : value.publicKey,
426
+ ...(value.tags && { tags: value.tags }),
427
+ ...(value.secretKey && { plaintext: true, decrypted: value.secretKey }),
428
+ });
429
+ });
430
+ return;
431
+ }
432
+
433
+ // Encrypted keystore. Resolve (and, if establishing, confirm) the passphrase
434
+ // and seal the secret before taking the lock: argon2id is deliberately slow
435
+ // and must not extend the critical section that blocks other processes.
436
+ const verifierAtSeal = this.#verifier;
437
+ let sealed: SecretEnvelope | undefined;
438
+ let newVerifier: SecretEnvelope | undefined;
439
+ let passphrase: string | undefined;
440
+ if (value.secretKey) {
441
+ const resolved = this.#sealPassphrase();
442
+ passphrase = resolved.passphrase;
443
+ newVerifier = resolved.newVerifier;
444
+ sealed = encryptSecret(value.secretKey, passphrase, this.#argonParams);
445
+ }
227
446
  this.#mutate(() => {
447
+ // A secret sealed outside the lock must never be persisted under a
448
+ // passphrase that diverges from the keystore verifier (the key-loss class
449
+ // ADR 080 exists to prevent). Reconcile our seal-time view with whatever the
450
+ // reload sees before committing.
451
+ if (value.secretKey) {
452
+ if (this.#verifier === undefined && newVerifier !== undefined) {
453
+ // Establishing, and no concurrent writer beat us to it: record our verifier.
454
+ this.#verifier = newVerifier;
455
+ } else if (this.#verifier !== undefined && passphrase !== undefined) {
456
+ // A verifier exists: it pre-existed, was established concurrently while we
457
+ // sealed, or was rotated by a concurrent change-passphrase. If it was
458
+ // rotated out from under our seal, abort with a clear message; otherwise
459
+ // assert our passphrase still opens it before persisting the key.
460
+ if (verifierAtSeal !== undefined && !sameEnvelope(this.#verifier, verifierAtSeal)) {
461
+ throw new KeyStoreError(
462
+ `The keystore passphrase at ${this.#path} changed concurrently; re-run the command.`,
463
+ 'KEYSTORE_CONCURRENT_CHANGE_ERROR',
464
+ { path: this.#path },
465
+ );
466
+ }
467
+ this.#assertPassphrase(passphrase);
468
+ }
469
+ }
228
470
  this.#cache.set(id, {
229
471
  publicKey : value.publicKey,
230
472
  ...(value.tags && { tags: value.tags }),
231
- ...(secret && { secret }),
473
+ ...(sealed && { secret: sealed }),
232
474
  ...(value.secretKey && { decrypted: value.secretKey }),
233
475
  });
234
476
  });
@@ -302,4 +544,174 @@ export class FileKeyStore implements KeyValueStore<KeyIdentifier, KeyEntry> {
302
544
  this.#active = id;
303
545
  });
304
546
  }
547
+
548
+ /** The keystore's protection mode. */
549
+ get protection(): KeystoreProtection {
550
+ return this.#protection;
551
+ }
552
+
553
+ /**
554
+ * Re-seals every sealed secret and the verifier under a new passphrase (ADR
555
+ * 080), returning the number of secrets re-sealed. Verifies the current
556
+ * passphrase against the verifier first. Refused on a dev keystore, which has
557
+ * no passphrase.
558
+ */
559
+ changePassphrase(oldPassphrase: string, newPassphrase: string): number {
560
+ if (this.#protection === 'none') {
561
+ throw new KeyStoreError(
562
+ `The keystore at ${this.#path} is an unencrypted dev keystore; it has no passphrase to change.`,
563
+ 'KEYSTORE_PROTECTION_ERROR',
564
+ { path: this.#path },
565
+ );
566
+ }
567
+ // Fail a wrong current passphrase up front (when a verifier exists) so a typo
568
+ // does not pay for a full re-seal before failing.
569
+ if (this.#verifier) this.#assertPassphrase(oldPassphrase);
570
+ // Precompute every re-seal and the new verifier BEFORE taking the lock:
571
+ // argon2id is deliberately slow, and holding the exclusive lock across many
572
+ // derivations could exceed the lock's stale threshold and let a concurrent
573
+ // process break a still-live lock. Each re-seal records the source envelope
574
+ // it derived from, so the locked section can abort on any concurrent change
575
+ // instead of corrupting. This follows the same do-expensive-work-before-the-
576
+ // lock contract as set().
577
+ const resealed = new Map<KeyIdentifier, { from: SecretEnvelope; to: SecretEnvelope; plain: Uint8Array }>();
578
+ for (const [ id, entry ] of this.#cache) {
579
+ if (!entry.secret) continue;
580
+ let plain: Uint8Array;
581
+ try {
582
+ plain = decryptSecret(entry.secret, oldPassphrase);
583
+ } catch {
584
+ throw new KeyStoreError(
585
+ `Incorrect current passphrase for the keystore at ${this.#path}.`,
586
+ 'DECRYPT_ERROR',
587
+ { path: this.#path },
588
+ );
589
+ }
590
+ resealed.set(id, { from: entry.secret, to: encryptSecret(plain, newPassphrase, this.#argonParams), plain });
591
+ }
592
+ const newVerifier = encryptSecret(VERIFIER_PLAINTEXT, newPassphrase, this.#argonParams);
593
+ let rekeyed = 0;
594
+ this.#mutate(() => {
595
+ // The reload reflects any concurrent writer. Apply a precomputed re-seal
596
+ // only where the on-disk envelope still matches what it was derived from;
597
+ // abort if any sealed key changed or a new sealed key appeared that was not
598
+ // re-sealed, rather than leave a key under the old passphrase.
599
+ for (const [ id, entry ] of this.#cache) {
600
+ if (!entry.secret) continue;
601
+ const pre = resealed.get(id);
602
+ if (!pre || !sameEnvelope(pre.from, entry.secret)) {
603
+ throw new KeyStoreError(
604
+ `The keystore at ${this.#path} changed while its passphrase was being changed; re-run the command.`,
605
+ 'KEYSTORE_CONCURRENT_CHANGE_ERROR',
606
+ { path: this.#path },
607
+ );
608
+ }
609
+ entry.secret = pre.to;
610
+ entry.decrypted = pre.plain;
611
+ rekeyed++;
612
+ }
613
+ this.#verifier = newVerifier;
614
+ });
615
+ return rekeyed;
616
+ }
617
+ }
618
+
619
+ /** A no-decrypt, no-prompt summary of a keystore file for `keystore status`. */
620
+ export interface KeystoreSummary {
621
+ protection : KeystoreProtectionLabel;
622
+ established : boolean;
623
+ keyCount : number;
624
+ active : string | undefined;
625
+ }
626
+
627
+ /**
628
+ * Summarizes a keystore file by structure alone: protection mode, whether a
629
+ * passphrase is established, key count, and active key. Never decrypts, never
630
+ * prompts, and never throws (a missing or unreadable file reports `absent`), so
631
+ * it is safe for `keystore status`, `config path`, and the mainnet dev-keystore
632
+ * guard.
633
+ */
634
+ export function keystoreSummary(path: string): KeystoreSummary {
635
+ const absent: KeystoreSummary = { protection: 'absent', established: false, keyCount: 0, active: undefined };
636
+ if (!existsSync(path)) return absent;
637
+ let parsed: KeystoreFile;
638
+ try {
639
+ parsed = JSON.parse(readFileSync(path, 'utf-8')) as KeystoreFile;
640
+ } catch {
641
+ return absent;
642
+ }
643
+ const keys = (parsed.keys && typeof parsed.keys === 'object') ? parsed.keys : {};
644
+ const keyCount = Object.keys(keys).length;
645
+ const active = typeof parsed.active === 'string' ? parsed.active : undefined;
646
+
647
+ if (parsed.protection === 'none') {
648
+ return { protection: 'dev', established: true, keyCount, active };
649
+ }
650
+ if (parsed.protection === 'passphrase') {
651
+ // An encrypted keystore is "established" once its passphrase verifier exists
652
+ // (written by `init` or the first key-seal). Without it the passphrase has not
653
+ // been set yet: a freshly-created, still-empty encrypted keystore.
654
+ return { protection: 'encrypted', established: parsed.verifier !== undefined, keyCount, active };
655
+ }
656
+ // No recognized protection header: not a keystore this CLI wrote. Report absent
657
+ // (never throw) so `keystore status` stays a safe, no-decrypt introspection; an
658
+ // actual open of such a file is refused by FileKeyStore.
659
+ return absent;
660
+ }
661
+
662
+ /** The protection label of a keystore file, without decrypting or prompting. */
663
+ export function keystoreProtection(path: string): KeystoreProtectionLabel {
664
+ return keystoreSummary(path).protection;
665
+ }
666
+
667
+ /** Options for {@link initKeystore}. */
668
+ export interface InitKeystoreOptions {
669
+ protection : KeystoreProtection;
670
+ getPassphrase : (opts?: { confirm?: boolean }) => string;
671
+ argonParams? : ArgonParams;
672
+ }
673
+
674
+ /**
675
+ * Establishes a fresh keystore file (ADR 080). An encrypted keystore prompts
676
+ * (with confirm) for the passphrase and writes the verifier; a dev keystore
677
+ * writes a plaintext-mode header with no passphrase. The caller is responsible
678
+ * for refusing to overwrite an existing keystore; this always writes the file.
679
+ */
680
+ export function initKeystore(path: string, options: InitKeystoreOptions): void {
681
+ ensureDir(dirname(path), 0o700);
682
+ let file: KeystoreFile;
683
+ if (options.protection === 'none') {
684
+ file = { v: KEYSTORE_VERSION, protection: 'none', keys: {} };
685
+ } else {
686
+ const passphrase = options.getPassphrase({ confirm: true });
687
+ const verifier = encryptSecret(VERIFIER_PLAINTEXT, passphrase, options.argonParams ?? DEFAULT_ARGON_PARAMS);
688
+ file = { v: KEYSTORE_VERSION, protection: 'passphrase', verifier, keys: {} };
689
+ }
690
+ writeFileAtomic(path, `${JSON.stringify(file, null, 2)}\n`, 0o600);
691
+ }
692
+
693
+ /**
694
+ * Re-seals every secret in an encrypted keystore under a new passphrase (ADR
695
+ * 080), returning the count re-sealed. The old and new passphrases are supplied
696
+ * explicitly, so the store's own passphrase provider is never invoked (a wrong
697
+ * current passphrase is caught by the verifier). Refused on a dev keystore.
698
+ */
699
+ export function changeKeystorePassphrase(
700
+ path : string,
701
+ oldPassphrase : string,
702
+ newPassphrase : string,
703
+ argonParams? : ArgonParams,
704
+ ): number {
705
+ const store = new FileKeyStore({
706
+ path,
707
+ ...(argonParams && { argonParams }),
708
+ getPassphrase : () => {
709
+ throw new KeyStoreError(
710
+ `Unexpected passphrase prompt while changing the passphrase for ${path}.`,
711
+ 'KEYSTORE_INTERNAL_ERROR',
712
+ { path },
713
+ );
714
+ },
715
+ });
716
+ return store.changePassphrase(oldPassphrase, newPassphrase);
305
717
  }