@git-stunts/git-cas 5.2.1 → 5.3.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 (46) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/README.md +67 -5
  3. package/bin/actions.js +38 -8
  4. package/bin/config.js +203 -0
  5. package/bin/git-cas.js +200 -54
  6. package/bin/ui/context.js +13 -0
  7. package/bin/ui/dashboard-cmds.js +14 -6
  8. package/bin/ui/dashboard-view.js +55 -6
  9. package/bin/ui/dashboard.js +109 -7
  10. package/bin/ui/encryption-card.js +2 -2
  11. package/bin/ui/heatmap.js +20 -2
  12. package/bin/ui/history-timeline.js +8 -6
  13. package/bin/ui/manifest-view.js +37 -8
  14. package/bin/ui/passphrase-prompt.js +100 -0
  15. package/bin/ui/progress.js +60 -38
  16. package/index.d.ts +20 -1
  17. package/index.js +74 -218
  18. package/package.json +2 -1
  19. package/src/domain/errors/CasError.js +3 -1
  20. package/src/domain/helpers/buildKdfMetadata.js +18 -0
  21. package/src/domain/services/CasService.d.ts +21 -1
  22. package/src/domain/services/CasService.js +134 -228
  23. package/src/domain/services/KeyResolver.js +220 -0
  24. package/src/domain/services/Semaphore.js +2 -2
  25. package/src/domain/services/VaultService.js +72 -29
  26. package/src/domain/services/rotateVaultPassphrase.js +143 -0
  27. package/src/infrastructure/adapters/BunCryptoAdapter.js +38 -6
  28. package/src/infrastructure/adapters/EventEmitterObserver.js +19 -7
  29. package/src/infrastructure/adapters/FileIOHelper.js +64 -0
  30. package/src/infrastructure/adapters/GitPersistenceAdapter.js +21 -5
  31. package/src/infrastructure/adapters/GitRefAdapter.js +27 -5
  32. package/src/infrastructure/adapters/NodeCryptoAdapter.js +49 -8
  33. package/src/infrastructure/adapters/SilentObserver.js +15 -0
  34. package/src/infrastructure/adapters/StatsCollector.js +15 -1
  35. package/src/infrastructure/adapters/WebCryptoAdapter.js +120 -42
  36. package/src/infrastructure/adapters/createCryptoAdapter.js +25 -0
  37. package/src/infrastructure/chunkers/CdcChunker.js +5 -0
  38. package/src/infrastructure/chunkers/FixedChunker.js +28 -8
  39. package/src/infrastructure/chunkers/resolveChunker.js +45 -0
  40. package/src/infrastructure/codecs/CborCodec.js +11 -3
  41. package/src/infrastructure/codecs/JsonCodec.js +10 -2
  42. package/src/ports/CodecPort.js +3 -3
  43. package/src/ports/CryptoPort.js +56 -23
  44. package/src/ports/GitPersistencePort.js +4 -4
  45. package/src/ports/GitRefPort.js +10 -10
  46. package/src/types/ambient.d.ts +37 -0
@@ -0,0 +1,220 @@
1
+ /**
2
+ * @fileoverview Key resolution service extracted from CasService.
3
+ *
4
+ * Handles all key-related logic: validation, wrapping/unwrapping DEKs,
5
+ * resolving encryption keys from passphrases, and envelope recipient management.
6
+ */
7
+ import CasError from '../errors/CasError.js';
8
+
9
+ /**
10
+ * Resolves encryption keys for store and restore operations.
11
+ *
12
+ * Encapsulates the key resolution responsibility that was previously
13
+ * spread across ~170 lines of CasService. Receives a CryptoPort via
14
+ * constructor injection.
15
+ *
16
+ * **Design note:** KeyResolver calls `CryptoPort.deriveKey()` directly
17
+ * rather than going through `CasService.deriveKey()`. If CasService ever
18
+ * adds validation or observability around its `deriveKey()` wrapper,
19
+ * KeyResolver will need updating to route through the service instead.
20
+ */
21
+ export default class KeyResolver {
22
+ /** @type {import('../../ports/CryptoPort.js').default} */
23
+ #crypto;
24
+
25
+ /**
26
+ * @param {import('../../ports/CryptoPort.js').default} crypto - CryptoPort adapter.
27
+ */
28
+ constructor(crypto) {
29
+ this.#crypto = crypto;
30
+ }
31
+
32
+ /**
33
+ * Validates that passphrase and encryptionKey are not both provided.
34
+ * @param {Buffer} [encryptionKey]
35
+ * @param {string} [passphrase]
36
+ * @throws {CasError} INVALID_OPTIONS if both are provided.
37
+ */
38
+ static validateKeySourceExclusive(encryptionKey, passphrase) {
39
+ if (passphrase && encryptionKey) {
40
+ throw new CasError(
41
+ 'Provide either encryptionKey or passphrase, not both',
42
+ 'INVALID_OPTIONS',
43
+ );
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Wraps a DEK with a KEK using AES-256-GCM.
49
+ * @param {Buffer} dek - 32-byte data encryption key.
50
+ * @param {Buffer} kek - 32-byte key encryption key.
51
+ * @returns {Promise<{ wrappedDek: string, nonce: string, tag: string }>}
52
+ */
53
+ async wrapDek(dek, kek) {
54
+ const { buf, meta } = await this.#crypto.encryptBuffer(dek, kek);
55
+ return {
56
+ wrappedDek: buf.toString('base64'),
57
+ nonce: meta.nonce,
58
+ tag: meta.tag,
59
+ };
60
+ }
61
+
62
+ /**
63
+ * Unwraps a DEK from a recipient entry using the given KEK.
64
+ * @param {{ wrappedDek: string, nonce: string, tag: string }} recipientEntry
65
+ * @param {Buffer} kek - 32-byte key encryption key.
66
+ * @returns {Promise<Buffer>} The unwrapped DEK.
67
+ * @throws {CasError} DEK_UNWRAP_FAILED if decryption fails.
68
+ */
69
+ async unwrapDek(recipientEntry, kek) {
70
+ try {
71
+ const ciphertext = Buffer.from(recipientEntry.wrappedDek, 'base64');
72
+ const meta = {
73
+ algorithm: 'aes-256-gcm',
74
+ nonce: recipientEntry.nonce,
75
+ tag: recipientEntry.tag,
76
+ encrypted: true,
77
+ };
78
+ return await this.#crypto.decryptBuffer(ciphertext, kek, meta);
79
+ } catch (err) {
80
+ if (err instanceof CasError && err.code === 'DEK_UNWRAP_FAILED') { throw err; }
81
+ throw new CasError(
82
+ 'Failed to unwrap DEK: authentication failed',
83
+ 'DEK_UNWRAP_FAILED',
84
+ { originalError: err },
85
+ );
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Resolves the decryption key from a manifest, handling both legacy and
91
+ * envelope (multi-recipient) encrypted manifests.
92
+ * @param {import('../value-objects/Manifest.js').default} manifest
93
+ * @param {Buffer} [encryptionKey]
94
+ * @param {string} [passphrase]
95
+ * @returns {Promise<Buffer|undefined>}
96
+ */
97
+ async resolveForDecryption(manifest, encryptionKey, passphrase) {
98
+ KeyResolver.validateKeySourceExclusive(encryptionKey, passphrase);
99
+
100
+ const key = passphrase
101
+ ? await this.#resolvePassphraseForDecryption(manifest, passphrase)
102
+ : encryptionKey;
103
+
104
+ if (!key) {
105
+ if (manifest.encryption?.encrypted) {
106
+ throw new CasError('Encryption key required to restore encrypted content', 'MISSING_KEY');
107
+ }
108
+ return undefined;
109
+ }
110
+
111
+ this.#crypto._validateKey(key);
112
+ return await this.resolveKeyForRecipients(manifest, key);
113
+ }
114
+
115
+ /**
116
+ * Resolves encryptionKey/passphrase into a key and optional KDF params for store().
117
+ * @param {Buffer} [encryptionKey]
118
+ * @param {string} [passphrase]
119
+ * @param {Object} [kdfOptions] - KDF options when using passphrase.
120
+ * @returns {Promise<{ key: Buffer|undefined, encExtra: Object }>}
121
+ */
122
+ async resolveForStore(encryptionKey, passphrase, kdfOptions) {
123
+ let kdfParams;
124
+ if (passphrase) {
125
+ const derived = await this.#crypto.deriveKey({ passphrase, ...kdfOptions });
126
+ encryptionKey = derived.key;
127
+ kdfParams = derived.params;
128
+ }
129
+ if (encryptionKey) { this.#crypto._validateKey(encryptionKey); }
130
+ return { key: encryptionKey, encExtra: kdfParams ? { kdf: kdfParams } : {} };
131
+ }
132
+
133
+ /**
134
+ * Resolves envelope recipients into a DEK and wrapped entries for store().
135
+ * @param {Array<{label: string, key: Buffer}>} recipients
136
+ * @returns {Promise<{ key: Buffer, encExtra: { recipients: Array } }>}
137
+ * @throws {CasError} INVALID_OPTIONS if recipients is empty, non-array, or has duplicate labels.
138
+ */
139
+ async resolveRecipients(recipients) {
140
+ if (!Array.isArray(recipients) || recipients.length === 0) {
141
+ throw new CasError('At least one recipient is required', 'INVALID_OPTIONS');
142
+ }
143
+ const labels = recipients.map((r) => r.label);
144
+ if (new Set(labels).size !== labels.length) {
145
+ throw new CasError('Duplicate recipient labels are not allowed', 'INVALID_OPTIONS');
146
+ }
147
+ const dek = this.#crypto.randomBytes(32);
148
+ const entries = [];
149
+ for (const r of recipients) {
150
+ this.#crypto._validateKey(r.key);
151
+ entries.push({ label: r.label, ...(await this.wrapDek(dek, r.key)) });
152
+ }
153
+ return { key: dek, encExtra: { recipients: entries } };
154
+ }
155
+
156
+ /**
157
+ * If manifest uses envelope encryption, unwraps the DEK. Otherwise returns key directly.
158
+ * @param {import('../value-objects/Manifest.js').default} manifest
159
+ * @param {Buffer} key
160
+ * @returns {Promise<Buffer>}
161
+ * @throws {CasError} NO_MATCHING_RECIPIENT if no recipient entry can be unwrapped.
162
+ */
163
+ async resolveKeyForRecipients(manifest, key) {
164
+ const recipients = manifest.encryption?.recipients;
165
+ if (!recipients || recipients.length === 0) {
166
+ return key;
167
+ }
168
+
169
+ for (const entry of recipients) {
170
+ try {
171
+ return await this.unwrapDek(entry, key);
172
+ } catch (err) {
173
+ if (!(err instanceof CasError && err.code === 'DEK_UNWRAP_FAILED')) { throw err; }
174
+ // Not this recipient's KEK, try next
175
+ }
176
+ }
177
+
178
+ throw new CasError(
179
+ 'No recipient entry could be unwrapped with the provided key',
180
+ 'NO_MATCHING_RECIPIENT',
181
+ );
182
+ }
183
+
184
+ /**
185
+ * Resolves passphrase to a key for decryption.
186
+ * @param {import('../value-objects/Manifest.js').default} manifest
187
+ * @param {string} passphrase
188
+ * @returns {Promise<Buffer>}
189
+ * @throws {CasError} MISSING_KEY if manifest has no KDF params.
190
+ */
191
+ async #resolvePassphraseForDecryption(manifest, passphrase) {
192
+ if (!manifest.encryption?.kdf) {
193
+ throw new CasError(
194
+ 'Manifest was not stored with passphrase-based encryption; provide encryptionKey instead',
195
+ 'MISSING_KEY',
196
+ );
197
+ }
198
+ return this.#resolveKeyFromPassphrase(passphrase, manifest.encryption.kdf);
199
+ }
200
+
201
+ /**
202
+ * Derives a key from a passphrase using stored KDF params.
203
+ * @param {string} passphrase
204
+ * @param {Object} kdf - KDF params from manifest.encryption.kdf.
205
+ * @returns {Promise<Buffer>}
206
+ */
207
+ async #resolveKeyFromPassphrase(passphrase, kdf) {
208
+ const { key } = await this.#crypto.deriveKey({
209
+ passphrase,
210
+ salt: Buffer.from(kdf.salt, 'base64'),
211
+ algorithm: kdf.algorithm,
212
+ iterations: kdf.iterations,
213
+ cost: kdf.cost,
214
+ blockSize: kdf.blockSize,
215
+ parallelization: kdf.parallelization,
216
+ keyLength: kdf.keyLength,
217
+ });
218
+ return key;
219
+ }
220
+ }
@@ -4,6 +4,7 @@
4
4
  export default class Semaphore {
5
5
  #max;
6
6
  #active = 0;
7
+ /** @type {Array<() => void>} */
7
8
  #queue = [];
8
9
 
9
10
  /**
@@ -35,8 +36,7 @@ export default class Semaphore {
35
36
  */
36
37
  release() {
37
38
  if (this.#queue.length > 0) {
38
- const next = this.#queue.shift();
39
- next();
39
+ /** @type {() => void} */ (this.#queue.shift())();
40
40
  } else {
41
41
  if (this.#active === 0) {
42
42
  throw new Error('Semaphore release called without an active permit');
@@ -2,11 +2,34 @@
2
2
  * @fileoverview Domain service for vault (GC-safe ref-based asset index) operations.
3
3
  */
4
4
  import CasError from '../errors/CasError.js';
5
+ import buildKdfMetadata from '../helpers/buildKdfMetadata.js';
5
6
 
6
7
  const VAULT_REF = 'refs/cas/vault';
7
8
  const MAX_CAS_RETRIES = 3;
8
9
  const CAS_RETRY_BASE_MS = 50;
9
10
 
11
+ /**
12
+ * Vault encryption metadata stored in .vault.json.
13
+ * @typedef {Object} VaultEncryptionMeta
14
+ * @property {string} cipher - Cipher algorithm (e.g. 'aes-256-gcm').
15
+ * @property {{ algorithm: string, salt: string, iterations?: number, cost?: number, blockSize?: number, parallelization?: number, keyLength: number }} kdf - KDF parameters.
16
+ */
17
+
18
+ /**
19
+ * Vault metadata stored in .vault.json.
20
+ * @typedef {Object} VaultMetadata
21
+ * @property {number} version - Metadata version (currently 1).
22
+ * @property {VaultEncryptionMeta} [encryption] - Encryption configuration.
23
+ */
24
+
25
+ /**
26
+ * Vault state read from refs/cas/vault.
27
+ * @typedef {Object} VaultState
28
+ * @property {Map<string, string>} entries - Slug→treeOid map.
29
+ * @property {string|null} parentCommitOid - Parent commit OID.
30
+ * @property {VaultMetadata|null} metadata - Vault metadata.
31
+ */
32
+
10
33
  /**
11
34
  * Percent-encodes a vault slug for use as a git tree entry name.
12
35
  * Git tree entry names cannot contain '/'.
@@ -57,16 +80,22 @@ function hasControlChars(str) {
57
80
  export default class VaultService {
58
81
  static VAULT_REF = VAULT_REF;
59
82
 
83
+ /** @type {number} Nonce usage warning threshold (2^31). */
84
+ static ENCRYPTION_COUNT_WARN = 2 ** 31;
85
+
60
86
  /**
61
87
  * @param {Object} options
62
- * @param {import('../../../src/ports/GitPersistencePort.js').default} options.persistence
63
- * @param {import('../../../src/ports/GitRefPort.js').default} options.ref
64
- * @param {import('../../../src/ports/CryptoPort.js').default} options.crypto
88
+ * @param {import('../../ports/GitPersistencePort.js').default} options.persistence
89
+ * @param {import('../../ports/GitRefPort.js').default} options.ref
90
+ * @param {import('../../ports/CryptoPort.js').default} options.crypto
91
+ * @param {import('../../ports/ObservabilityPort.js').default} [options.observability]
65
92
  */
66
- constructor({ persistence, ref, crypto }) {
93
+ constructor({ persistence, ref, crypto, observability }) {
67
94
  this.persistence = persistence;
68
95
  this.ref = ref;
69
96
  this.crypto = crypto;
97
+ /** @type {import('../../ports/ObservabilityPort.js').default} */
98
+ this.observability = observability || { metric() {}, log() {}, span: () => ({ end() {} }) };
70
99
  }
71
100
 
72
101
  // ---------------------------------------------------------------------------
@@ -75,7 +104,8 @@ export default class VaultService {
75
104
 
76
105
  /**
77
106
  * Validates a single slug segment.
78
- * @private
107
+ * @param {string} seg - Segment to validate.
108
+ * @param {string} slug - Full slug (for error context).
79
109
  */
80
110
  static #validateSegment(seg, slug) {
81
111
  if (seg.length === 0) {
@@ -118,7 +148,8 @@ export default class VaultService {
118
148
 
119
149
  /**
120
150
  * Validates encryption-specific metadata fields.
121
- * @private
151
+ * @param {VaultEncryptionMeta} encryption - Encryption metadata.
152
+ * @param {VaultMetadata} metadata - Full metadata (for error context).
122
153
  */
123
154
  static #validateEncryption(encryption, metadata) {
124
155
  const { cipher, kdf } = encryption;
@@ -133,7 +164,7 @@ export default class VaultService {
133
164
 
134
165
  /**
135
166
  * Validates vault metadata object structure.
136
- * @private
167
+ * @param {VaultMetadata} metadata - Metadata to validate.
137
168
  */
138
169
  static #validateMetadata(metadata) {
139
170
  if (typeof metadata.version !== 'number' || metadata.version !== 1) {
@@ -150,7 +181,8 @@ export default class VaultService {
150
181
 
151
182
  /**
152
183
  * Reads and validates vault metadata from a blob OID.
153
- * @private
184
+ * @param {string} blobOid - Git blob OID of the .vault.json file.
185
+ * @returns {Promise<VaultMetadata>}
154
186
  */
155
187
  async #readMetadataBlob(blobOid) {
156
188
  try {
@@ -161,7 +193,7 @@ export default class VaultService {
161
193
  } catch (err) {
162
194
  if (err instanceof CasError) { throw err; }
163
195
  throw new CasError(
164
- `Failed to parse .vault.json: ${err.message}`,
196
+ `Failed to parse .vault.json: ${/** @type {Error} */ (err).message}`,
165
197
  'VAULT_METADATA_INVALID',
166
198
  { originalError: err },
167
199
  );
@@ -174,8 +206,8 @@ export default class VaultService {
174
206
 
175
207
  /**
176
208
  * Separates vault tree entries into slug→OID map and metadata blob OID.
177
- * @private
178
209
  * @param {Array<{ mode: string, type: string, oid: string, name: string }>} treeEntries
210
+ * @returns {{ entries: Map<string, string>, metadataBlobOid: string|null }}
179
211
  */
180
212
  static #parseTreeEntries(treeEntries) {
181
213
  const entries = new Map();
@@ -192,7 +224,7 @@ export default class VaultService {
192
224
 
193
225
  /**
194
226
  * Reads the current vault state from refs/cas/vault.
195
- * @returns {Promise<{ entries: Map<string, string>, parentCommitOid: string|null, metadata: object|null }>}
227
+ * @returns {Promise<VaultState>}
196
228
  */
197
229
  async readState() {
198
230
  let commitOid;
@@ -216,7 +248,7 @@ export default class VaultService {
216
248
  * Writes a new vault commit and updates the ref atomically.
217
249
  * @param {Object} options
218
250
  * @param {Map<string, string>} options.entries - Slug→treeOid map.
219
- * @param {object} options.metadata - Vault metadata (.vault.json contents).
251
+ * @param {VaultMetadata} options.metadata - Vault metadata (.vault.json contents).
220
252
  * @param {string|null} options.parentCommitOid - Parent commit OID (null for first commit).
221
253
  * @param {string} options.message - Commit message.
222
254
  * @returns {Promise<{ commitOid: string }>}
@@ -244,7 +276,8 @@ export default class VaultService {
244
276
 
245
277
  /**
246
278
  * Atomically updates the vault ref with CAS semantics.
247
- * @private
279
+ * @param {string} newOid - New commit OID.
280
+ * @param {string|null} expectedOldOid - Expected current commit OID.
248
281
  */
249
282
  async #casUpdateRef(newOid, expectedOldOid) {
250
283
  try {
@@ -264,8 +297,7 @@ export default class VaultService {
264
297
 
265
298
  /**
266
299
  * Wraps a vault mutation with CAS retry logic.
267
- * @private
268
- * @param {function} mutationFn - Async function(state) → { entries, metadata, message }
300
+ * @param {(state: VaultState) => { entries: Map<string, string>, metadata: VaultMetadata, message: string }|Promise<{ entries: Map<string, string>, metadata: VaultMetadata, message: string }>} mutationFn - Mutation function (sync or async).
269
301
  * @returns {Promise<{ commitOid: string }>}
270
302
  */
271
303
  async #retryMutation(mutationFn) {
@@ -295,20 +327,14 @@ export default class VaultService {
295
327
 
296
328
  /**
297
329
  * Builds vault encryption metadata from KDF result.
298
- * @private
330
+ * @param {Buffer} salt - KDF salt.
331
+ * @param {import('../../ports/CryptoPort.js').KdfParamSet} params - KDF parameters.
332
+ * @returns {VaultEncryptionMeta}
299
333
  */
300
334
  static #buildEncryptionMeta(salt, params) {
301
335
  return {
302
336
  cipher: 'aes-256-gcm',
303
- kdf: {
304
- algorithm: params.algorithm,
305
- salt: salt.toString('base64'),
306
- ...('iterations' in params && { iterations: params.iterations }),
307
- ...('cost' in params && { cost: params.cost }),
308
- ...('blockSize' in params && { blockSize: params.blockSize }),
309
- ...('parallelization' in params && { parallelization: params.parallelization }),
310
- keyLength: params.keyLength,
311
- },
337
+ kdf: buildKdfMetadata(salt, params),
312
338
  };
313
339
  }
314
340
 
@@ -333,6 +359,7 @@ export default class VaultService {
333
359
  );
334
360
  }
335
361
 
362
+ /** @type {VaultMetadata} */
336
363
  const metadata = { version: 1 };
337
364
  if (passphrase) {
338
365
  const { salt, params } = await this.crypto.deriveKey({ passphrase, ...kdfOptions });
@@ -368,9 +395,24 @@ export default class VaultService {
368
395
  }
369
396
  const isUpdate = state.entries.has(slug);
370
397
  state.entries.set(slug, treeOid);
398
+ // Shallow copy to avoid mutating readState()'s object on CAS retries.
399
+ const metadata = { ...(state.metadata || { version: 1 }) };
400
+ if (metadata.encryption) {
401
+ // Tracks nonce-relevant operations: every addToVault on an encrypted
402
+ // vault implies an encryption occurred at the store layer.
403
+ metadata.encryptionCount = (metadata.encryptionCount || 0) + 1;
404
+ if (metadata.encryptionCount >= VaultService.ENCRYPTION_COUNT_WARN) {
405
+ this.observability.log(
406
+ 'warn',
407
+ `Vault encryption count (${metadata.encryptionCount}) exceeds ` +
408
+ `${VaultService.ENCRYPTION_COUNT_WARN} — rotate your key`,
409
+ { encryptionCount: metadata.encryptionCount },
410
+ );
411
+ }
412
+ }
371
413
  return {
372
414
  entries: state.entries,
373
- metadata: state.metadata || { version: 1 },
415
+ metadata,
374
416
  message: isUpdate ? `vault: update ${slug}` : `vault: add ${slug}`,
375
417
  };
376
418
  });
@@ -394,6 +436,7 @@ export default class VaultService {
394
436
  * @returns {Promise<{ commitOid: string, removedTreeOid: string }>}
395
437
  */
396
438
  async removeFromVault({ slug }) {
439
+ /** @type {string|undefined} */
397
440
  let removedTreeOid;
398
441
 
399
442
  const result = await this.#retryMutation((state) => {
@@ -413,7 +456,7 @@ export default class VaultService {
413
456
  };
414
457
  });
415
458
 
416
- return { commitOid: result.commitOid, removedTreeOid };
459
+ return { commitOid: result.commitOid, removedTreeOid: /** @type {string} */ (removedTreeOid) };
417
460
  }
418
461
 
419
462
  /**
@@ -431,12 +474,12 @@ export default class VaultService {
431
474
  { slug },
432
475
  );
433
476
  }
434
- return entries.get(slug);
477
+ return /** @type {string} */ (entries.get(slug));
435
478
  }
436
479
 
437
480
  /**
438
481
  * Returns the vault metadata, or null if no vault exists.
439
- * @returns {Promise<object|null>}
482
+ * @returns {Promise<VaultMetadata|null>}
440
483
  */
441
484
  async getVaultMetadata() {
442
485
  const { metadata } = await this.readState();
@@ -0,0 +1,143 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import buildKdfMetadata from '../helpers/buildKdfMetadata.js';
3
+
4
+ const DEFAULT_MAX_RETRIES = 3;
5
+ const DEFAULT_RETRY_BASE_MS = 50;
6
+
7
+ /**
8
+ * Derives a KEK from a passphrase using stored KDF params.
9
+ *
10
+ * @param {import('./CasService.js').default} service - CasService instance.
11
+ * @param {string} passphrase - The passphrase.
12
+ * @param {Object} kdf - Stored KDF params (algorithm, salt, iterations, etc.).
13
+ * @returns {Promise<Buffer>} The derived KEK.
14
+ */
15
+ async function deriveKekFromKdf(service, passphrase, kdf) {
16
+ const { key } = await service.deriveKey({
17
+ passphrase,
18
+ salt: Buffer.from(kdf.salt, 'base64'),
19
+ algorithm: kdf.algorithm,
20
+ iterations: kdf.iterations,
21
+ cost: kdf.cost,
22
+ blockSize: kdf.blockSize,
23
+ parallelization: kdf.parallelization,
24
+ keyLength: kdf.keyLength,
25
+ });
26
+ return key;
27
+ }
28
+
29
+ /**
30
+ * Iterates vault entries, rotating envelope-encrypted ones and skipping others.
31
+ *
32
+ * @param {Object} options
33
+ * @param {import('./CasService.js').default} options.service - CasService instance.
34
+ * @param {Map<string, string>} options.entries - Vault entries (slug → treeOid).
35
+ * @param {Buffer} options.oldKek - Old key-encryption key.
36
+ * @param {Buffer} options.newKek - New key-encryption key.
37
+ * @returns {Promise<{ updatedEntries: Map<string, string>, rotatedSlugs: string[], skippedSlugs: string[] }>}
38
+ */
39
+ async function rotateEntries({ service, entries, oldKek, newKek }) {
40
+ const rotatedSlugs = [];
41
+ const skippedSlugs = [];
42
+ const updatedEntries = new Map(entries);
43
+
44
+ for (const [slug, treeOid] of entries) {
45
+ const manifest = await service.readManifest({ treeOid });
46
+ if (!manifest.encryption?.recipients?.length) {
47
+ skippedSlugs.push(slug);
48
+ continue;
49
+ }
50
+ const rotated = await service.rotateKey({ manifest, oldKey: oldKek, newKey: newKek });
51
+ updatedEntries.set(slug, await service.createTree({ manifest: rotated }));
52
+ rotatedSlugs.push(slug);
53
+ }
54
+
55
+ return { updatedEntries, rotatedSlugs, skippedSlugs };
56
+ }
57
+
58
+ /**
59
+ * Returns true if the error is a retryable VAULT_CONFLICT and there are attempts remaining.
60
+ *
61
+ * @param {Error} err - Caught error.
62
+ * @param {number} attempt - Zero-based current attempt index.
63
+ * @param {number} maxRetries - Maximum number of attempts.
64
+ * @returns {boolean}
65
+ */
66
+ function isRetryableConflict(err, attempt, maxRetries) {
67
+ return err instanceof CasError && err.code === 'VAULT_CONFLICT' && attempt < maxRetries - 1;
68
+ }
69
+
70
+ /**
71
+ * Builds updated vault metadata with new KDF params.
72
+ *
73
+ * @param {Object} metadata - Existing vault metadata.
74
+ * @param {Buffer} newSalt - New KDF salt.
75
+ * @param {Object} newParams - New KDF parameters.
76
+ * @returns {Object} Updated metadata.
77
+ */
78
+ function buildRotatedMetadata(metadata, newSalt, newParams) {
79
+ return {
80
+ ...metadata,
81
+ encryption: {
82
+ cipher: metadata.encryption.cipher,
83
+ kdf: buildKdfMetadata(newSalt, newParams),
84
+ },
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Rotates the vault-level passphrase. Re-wraps every envelope-encrypted
90
+ * entry's DEK with a new KEK derived from `newPassphrase`. Entries using
91
+ * direct-key encryption are skipped.
92
+ *
93
+ * Uses optimistic concurrency with retry/backoff on VAULT_CONFLICT.
94
+ *
95
+ * @param {Object} deps
96
+ * @param {import('./CasService.js').default} deps.service - CasService instance.
97
+ * @param {import('./VaultService.js').default} deps.vault - VaultService instance.
98
+ * @param {Object} options
99
+ * @param {string} options.oldPassphrase - Current vault passphrase.
100
+ * @param {string} options.newPassphrase - New vault passphrase.
101
+ * @param {Object} [options.kdfOptions] - KDF options for new passphrase.
102
+ * @param {number} [options.maxRetries=3] - Maximum optimistic-concurrency retries on VAULT_CONFLICT.
103
+ * @param {number} [options.retryBaseMs=50] - Base delay in ms for exponential backoff between retries.
104
+ * @returns {Promise<{ commitOid: string, rotatedSlugs: string[], skippedSlugs: string[] }>}
105
+ */
106
+ export default async function rotateVaultPassphrase(
107
+ { service, vault },
108
+ { oldPassphrase, newPassphrase, kdfOptions, maxRetries = DEFAULT_MAX_RETRIES, retryBaseMs = DEFAULT_RETRY_BASE_MS },
109
+ ) {
110
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
111
+ const state = await vault.readState();
112
+ if (!state.metadata?.encryption) {
113
+ throw new CasError('Vault is not encrypted — nothing to rotate', 'VAULT_METADATA_INVALID');
114
+ }
115
+
116
+ const { kdf } = state.metadata.encryption;
117
+ const oldKek = await deriveKekFromKdf(service, oldPassphrase, kdf);
118
+ const { key: newKek, salt: newSalt, params: newParams } = await service.deriveKey({
119
+ passphrase: newPassphrase, ...kdfOptions, algorithm: kdfOptions?.algorithm || kdf.algorithm,
120
+ });
121
+
122
+ const result = await rotateEntries({ service, entries: state.entries, oldKek, newKek });
123
+ const newMetadata = buildRotatedMetadata(state.metadata, newSalt, newParams);
124
+
125
+ try {
126
+ const { commitOid } = await vault.writeCommit({
127
+ entries: result.updatedEntries,
128
+ metadata: newMetadata,
129
+ parentCommitOid: state.parentCommitOid,
130
+ message: `vault: rotate passphrase (${result.rotatedSlugs.length} rotated, ${result.skippedSlugs.length} skipped)`,
131
+ });
132
+ return { commitOid, rotatedSlugs: result.rotatedSlugs, skippedSlugs: result.skippedSlugs };
133
+ } catch (err) {
134
+ if (isRetryableConflict(err, attempt, maxRetries)) {
135
+ await new Promise((r) => setTimeout(r, retryBaseMs * (2 ** attempt)));
136
+ continue;
137
+ }
138
+ throw err;
139
+ }
140
+ }
141
+ /* c8 ignore next 2 */
142
+ throw new CasError('Vault CAS retries exhausted', 'VAULT_CONFLICT');
143
+ }