@git-stunts/git-cas 5.2.1 → 5.2.4

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 (42) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +24 -0
  3. package/bin/actions.js +24 -7
  4. package/bin/git-cas.js +78 -30
  5. package/bin/ui/context.js +13 -0
  6. package/bin/ui/dashboard-cmds.js +14 -6
  7. package/bin/ui/dashboard-view.js +55 -6
  8. package/bin/ui/dashboard.js +109 -7
  9. package/bin/ui/encryption-card.js +2 -2
  10. package/bin/ui/heatmap.js +20 -2
  11. package/bin/ui/history-timeline.js +8 -6
  12. package/bin/ui/manifest-view.js +37 -8
  13. package/bin/ui/progress.js +60 -38
  14. package/index.d.ts +5 -1
  15. package/index.js +47 -215
  16. package/package.json +2 -1
  17. package/src/domain/helpers/buildKdfMetadata.js +18 -0
  18. package/src/domain/services/CasService.d.ts +1 -1
  19. package/src/domain/services/CasService.js +38 -213
  20. package/src/domain/services/KeyResolver.js +220 -0
  21. package/src/domain/services/Semaphore.js +2 -2
  22. package/src/domain/services/VaultService.js +49 -27
  23. package/src/domain/services/rotateVaultPassphrase.js +143 -0
  24. package/src/infrastructure/adapters/BunCryptoAdapter.js +38 -6
  25. package/src/infrastructure/adapters/EventEmitterObserver.js +19 -7
  26. package/src/infrastructure/adapters/FileIOHelper.js +64 -0
  27. package/src/infrastructure/adapters/GitPersistenceAdapter.js +21 -5
  28. package/src/infrastructure/adapters/GitRefAdapter.js +27 -5
  29. package/src/infrastructure/adapters/NodeCryptoAdapter.js +38 -7
  30. package/src/infrastructure/adapters/SilentObserver.js +15 -0
  31. package/src/infrastructure/adapters/StatsCollector.js +15 -1
  32. package/src/infrastructure/adapters/WebCryptoAdapter.js +68 -18
  33. package/src/infrastructure/adapters/createCryptoAdapter.js +25 -0
  34. package/src/infrastructure/chunkers/FixedChunker.js +5 -1
  35. package/src/infrastructure/chunkers/resolveChunker.js +45 -0
  36. package/src/infrastructure/codecs/CborCodec.js +11 -3
  37. package/src/infrastructure/codecs/JsonCodec.js +10 -2
  38. package/src/ports/CodecPort.js +3 -3
  39. package/src/ports/CryptoPort.js +56 -23
  40. package/src/ports/GitPersistencePort.js +4 -4
  41. package/src/ports/GitRefPort.js +10 -10
  42. package/src/types/ambient.d.ts +37 -0
@@ -9,6 +9,9 @@ import { getCliContext } from './context.js';
9
9
 
10
10
  /**
11
11
  * Format bytes as human-readable string.
12
+ *
13
+ * @param {number} bytes
14
+ * @returns {string}
12
15
  */
13
16
  function formatBytes(bytes) {
14
17
  if (bytes < 1024) {
@@ -23,6 +26,12 @@ function formatBytes(bytes) {
23
26
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GiB`;
24
27
  }
25
28
 
29
+ /**
30
+ * @typedef {import('../actions.js')} ActionsModule
31
+ * @typedef {{ on(event: string, fn: Function): void, removeListener(event: string, fn: Function): void }} Observer
32
+ * @typedef {{ attach(observer: Observer): void, detach(): void }} ProgressTracker
33
+ */
34
+
26
35
  /**
27
36
  * Create a progress tracker for store operations.
28
37
  *
@@ -30,7 +39,9 @@ function formatBytes(bytes) {
30
39
  * @param {string} options.filePath - Path to the file being stored.
31
40
  * @param {number} options.chunkSize - Chunk size in bytes.
32
41
  * @param {boolean} [options.quiet] - Suppress all progress output.
33
- * @returns {{ attach(observer: { on(event: string, fn: Function): void, removeListener(event: string, fn: Function): void }): void, detach(): void }}
42
+ * @param {number} [options.fileSize] - Pre-computed file size (avoids stat).
43
+ * @param {import('@flyingrobots/bijou').BijouContext} [options.ctx] - Context override.
44
+ * @returns {ProgressTracker}
34
45
  */
35
46
  export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: providedSize, ctx: providedCtx }) {
36
47
  if (quiet) {
@@ -58,7 +69,8 @@ export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: prov
58
69
  * @param {Object} options
59
70
  * @param {number} options.totalChunks - Number of chunks to restore.
60
71
  * @param {boolean} [options.quiet] - Suppress all progress output.
61
- * @returns {{ attach(observer: { on(event: string, fn: Function): void, removeListener(event: string, fn: Function): void }): void, detach(): void }}
72
+ * @param {import('@flyingrobots/bijou').BijouContext} [options.ctx] - Context override.
73
+ * @returns {ProgressTracker}
62
74
  */
63
75
  export function createRestoreProgress({ totalChunks, quiet, ctx: providedCtx }) {
64
76
  if (quiet || totalChunks === 0) {
@@ -73,54 +85,64 @@ export function createRestoreProgress({ totalChunks, quiet, ctx: providedCtx })
73
85
  return createProgressTracker({ ctx, totalChunks, event: 'chunk:restored', label: 'Restoring' });
74
86
  }
75
87
 
88
+ /**
89
+ * @typedef {Object} TrackerState
90
+ * @property {number} chunksProcessed
91
+ * @property {number} bytesProcessed
92
+ * @property {number | null} startTime
93
+ * @property {Observer | null} service
94
+ * @property {((evt: { size: number }) => void) | null} handler
95
+ */
96
+
97
+ /**
98
+ * Handle a single chunk event (shared by store/restore).
99
+ *
100
+ * @param {{ size: number }} evt
101
+ * @param {TrackerState} state
102
+ * @param {{ ctx: import('@flyingrobots/bijou').BijouContext, totalChunks: number, label: string, bar: { update(pct: number): void } }} deps
103
+ */
104
+ function handleChunkEvent({ size }, state, deps) {
105
+ if (!state.startTime) { state.startTime = Date.now(); }
106
+ state.chunksProcessed++;
107
+ state.bytesProcessed += size;
108
+ const pct = (state.chunksProcessed / deps.totalChunks) * 100;
109
+ const elapsed = (Date.now() - state.startTime) / 1000;
110
+ const throughput = elapsed > 0 ? state.bytesProcessed / elapsed : 0;
111
+ if (deps.ctx.mode === 'interactive') {
112
+ const status = ` ${deps.label} ${state.chunksProcessed}/${deps.totalChunks} ${formatBytes(throughput)}/s `;
113
+ deps.ctx.io.write(`\r\x1b[K${status}`);
114
+ deps.bar.update(pct);
115
+ } else if (state.chunksProcessed === 1 || state.chunksProcessed === deps.totalChunks || state.chunksProcessed % 10 === 0) {
116
+ deps.ctx.io.write(`${deps.label} ${state.chunksProcessed}/${deps.totalChunks} ${Math.round(pct)}%\n`);
117
+ }
118
+ }
119
+
76
120
  /**
77
121
  * Internal: builds the progress tracker object.
122
+ *
123
+ * @param {{ ctx: import('@flyingrobots/bijou').BijouContext, totalChunks: number, event: string, label: string }} params
124
+ * @returns {ProgressTracker}
78
125
  */
79
126
  function createProgressTracker({ ctx, totalChunks, event, label }) {
80
127
  const width = Math.min(40, (ctx.runtime.columns || 80) - 30);
81
128
  const bar = createAnimatedProgressBar({ width, showPercent: false, ctx });
82
-
83
- let chunksProcessed = 0;
84
- let bytesProcessed = 0;
85
- let startTime = null;
86
- let service = null;
87
- let handler = null;
88
-
89
- function onChunk({ size }) {
90
- if (!startTime) {
91
- startTime = Date.now();
92
- }
93
- chunksProcessed++;
94
- bytesProcessed += size;
95
-
96
- const pct = (chunksProcessed / totalChunks) * 100;
97
- const elapsed = (Date.now() - startTime) / 1000;
98
- const throughput = elapsed > 0 ? bytesProcessed / elapsed : 0;
99
-
100
- if (ctx.mode === 'interactive') {
101
- const status = ` ${label} ${chunksProcessed}/${totalChunks} ${formatBytes(throughput)}/s `;
102
- process.stderr.write(`\r\x1b[K${status}`);
103
- bar.update(pct);
104
- } else if (chunksProcessed === 1 || chunksProcessed === totalChunks || chunksProcessed % 10 === 0) {
105
- ctx.io.write(`${label} ${chunksProcessed}/${totalChunks} ${Math.round(pct)}%\n`);
106
- }
107
- }
129
+ /** @type {TrackerState} */
130
+ const state = { chunksProcessed: 0, bytesProcessed: 0, startTime: null, service: null, handler: null };
131
+ const deps = { ctx, totalChunks, label, bar };
108
132
 
109
133
  return {
134
+ /** @param {Observer} svc */
110
135
  attach(svc) {
111
- service = svc;
112
- handler = onChunk;
136
+ state.service = svc;
137
+ state.handler = (/** @type {{ size: number }} */ evt) => handleChunkEvent(evt, state, deps);
113
138
  bar.start();
114
- service.on(event, handler);
139
+ state.service.on(event, state.handler);
115
140
  },
116
141
  detach() {
117
- if (service && handler) {
118
- service.removeListener(event, handler);
119
- }
120
- const elapsed = startTime ? (Date.now() - startTime) / 1000 : 0;
121
- const throughput = elapsed > 0 ? bytesProcessed / elapsed : 0;
122
- const msg = ` ${label} ${chunksProcessed}/${totalChunks} done ${formatBytes(throughput)}/s`;
123
- bar.stop(msg);
142
+ if (state.service && state.handler) { state.service.removeListener(event, state.handler); }
143
+ const elapsed = state.startTime ? (Date.now() - state.startTime) / 1000 : 0;
144
+ const throughput = elapsed > 0 ? state.bytesProcessed / elapsed : 0;
145
+ bar.stop(` ${label} ${state.chunksProcessed}/${totalChunks} done ${formatBytes(throughput)}/s`);
124
146
  },
125
147
  };
126
148
  }
package/index.d.ts CHANGED
@@ -47,7 +47,7 @@ export declare class CdcChunker extends ChunkingPort {
47
47
 
48
48
  /** Abstract port for cryptographic operations. */
49
49
  export declare class CryptoPortBase {
50
- sha256(buf: Buffer): string | Promise<string>;
50
+ sha256(buf: Buffer): Promise<string>;
51
51
  randomBytes(n: number): Buffer;
52
52
  encryptBuffer(
53
53
  buffer: Buffer,
@@ -401,6 +401,10 @@ export default class ContentAddressableStore {
401
401
  oldPassphrase: string;
402
402
  newPassphrase: string;
403
403
  kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
404
+ /** Maximum optimistic-concurrency retries on VAULT_CONFLICT. @default 3 */
405
+ maxRetries?: number;
406
+ /** Base delay in ms for exponential backoff between retries. @default 50 */
407
+ retryBaseMs?: number;
404
408
  }): Promise<{
405
409
  commitOid: string;
406
410
  rotatedSlugs: string[];
package/index.js CHANGED
@@ -3,64 +3,47 @@
3
3
  * @fileoverview Content Addressable Store - Managed blob storage in Git.
4
4
  */
5
5
 
6
- import { createReadStream, createWriteStream } from 'node:fs';
7
- import path from 'node:path';
8
- import { Readable, Transform } from 'node:stream';
9
- import { pipeline } from 'node:stream/promises';
6
+ // ---------------------------------------------------------------------------
7
+ // Imports used in the class body
8
+ // ---------------------------------------------------------------------------
10
9
  import CasService from './src/domain/services/CasService.js';
11
10
  import VaultService from './src/domain/services/VaultService.js';
12
- import CasError from './src/domain/errors/CasError.js';
11
+ import rotateVaultPassphrase from './src/domain/services/rotateVaultPassphrase.js';
13
12
  import GitPersistenceAdapter from './src/infrastructure/adapters/GitPersistenceAdapter.js';
14
13
  import GitRefAdapter from './src/infrastructure/adapters/GitRefAdapter.js';
15
- import NodeCryptoAdapter from './src/infrastructure/adapters/NodeCryptoAdapter.js';
16
- import Manifest from './src/domain/value-objects/Manifest.js';
17
- import Chunk from './src/domain/value-objects/Chunk.js';
18
- import CryptoPort from './src/ports/CryptoPort.js';
19
- import ChunkingPort from './src/ports/ChunkingPort.js';
20
- import ObservabilityPort from './src/ports/ObservabilityPort.js';
14
+ import createCryptoAdapter from './src/infrastructure/adapters/createCryptoAdapter.js';
15
+ import { storeFile, restoreFile } from './src/infrastructure/adapters/FileIOHelper.js';
21
16
  import JsonCodec from './src/infrastructure/codecs/JsonCodec.js';
22
17
  import CborCodec from './src/infrastructure/codecs/CborCodec.js';
23
18
  import SilentObserver from './src/infrastructure/adapters/SilentObserver.js';
24
- import EventEmitterObserver from './src/infrastructure/adapters/EventEmitterObserver.js';
25
- import StatsCollector from './src/infrastructure/adapters/StatsCollector.js';
26
- import FixedChunker from './src/infrastructure/chunkers/FixedChunker.js';
27
- import CdcChunker from './src/infrastructure/chunkers/CdcChunker.js';
19
+ import resolveChunker from './src/infrastructure/chunkers/resolveChunker.js';
28
20
 
21
+ // ---------------------------------------------------------------------------
22
+ // Re-exports — modules used in the class body
23
+ // ---------------------------------------------------------------------------
29
24
  export {
30
25
  CasService,
31
26
  VaultService,
32
27
  GitPersistenceAdapter,
33
28
  GitRefAdapter,
34
- NodeCryptoAdapter,
35
- CryptoPort,
36
- ChunkingPort,
37
- ObservabilityPort,
38
- Manifest,
39
- Chunk,
40
29
  JsonCodec,
41
30
  CborCodec,
42
31
  SilentObserver,
43
- EventEmitterObserver,
44
- StatsCollector,
45
- FixedChunker,
46
- CdcChunker,
47
32
  };
48
33
 
49
- /**
50
- * Detects the best crypto adapter for the current runtime.
51
- * @returns {Promise<import('./src/ports/CryptoPort.js').default>} A runtime-appropriate CryptoPort implementation.
52
- */
53
- async function getDefaultCryptoAdapter() {
54
- if (globalThis.Bun) {
55
- const { default: BunCryptoAdapter } = await import('./src/infrastructure/adapters/BunCryptoAdapter.js');
56
- return new BunCryptoAdapter();
57
- }
58
- if (globalThis.Deno) {
59
- const { default: WebCryptoAdapter } = await import('./src/infrastructure/adapters/WebCryptoAdapter.js');
60
- return new WebCryptoAdapter();
61
- }
62
- return new NodeCryptoAdapter();
63
- }
34
+ // ---------------------------------------------------------------------------
35
+ // Re-exports — barrel-only (no local binding needed)
36
+ // ---------------------------------------------------------------------------
37
+ export { default as NodeCryptoAdapter } from './src/infrastructure/adapters/NodeCryptoAdapter.js';
38
+ export { default as CryptoPort } from './src/ports/CryptoPort.js';
39
+ export { default as ChunkingPort } from './src/ports/ChunkingPort.js';
40
+ export { default as ObservabilityPort } from './src/ports/ObservabilityPort.js';
41
+ export { default as Manifest } from './src/domain/value-objects/Manifest.js';
42
+ export { default as Chunk } from './src/domain/value-objects/Chunk.js';
43
+ export { default as EventEmitterObserver } from './src/infrastructure/adapters/EventEmitterObserver.js';
44
+ export { default as StatsCollector } from './src/infrastructure/adapters/StatsCollector.js';
45
+ export { default as FixedChunker } from './src/infrastructure/chunkers/FixedChunker.js';
46
+ export { default as CdcChunker } from './src/infrastructure/chunkers/CdcChunker.js';
64
47
 
65
48
  /**
66
49
  * High-level facade for the Content Addressable Store library.
@@ -83,20 +66,13 @@ export default class ContentAddressableStore {
83
66
  * @param {import('./src/ports/ChunkingPort.js').default} [options.chunker] - Pre-built ChunkingPort instance (advanced).
84
67
  */
85
68
  constructor({ plumbing, chunkSize, codec, policy, crypto, observability, merkleThreshold, concurrency, chunking, chunker }) {
86
- this.plumbing = plumbing;
87
- this.chunkSizeConfig = chunkSize;
88
- this.codecConfig = codec;
89
- this.policyConfig = policy;
90
- this.cryptoConfig = crypto;
91
- this.observabilityConfig = observability;
92
- this.merkleThresholdConfig = merkleThreshold;
93
- this.concurrencyConfig = concurrency;
94
- this.chunkingConfig = chunking;
95
- this.chunkerConfig = chunker;
69
+ this.#config = { plumbing, chunkSize, codec, policy, crypto, observability, merkleThreshold, concurrency, chunking, chunker };
96
70
  this.service = null;
97
71
  this.#servicePromise = null;
98
72
  }
99
73
 
74
+ /** @type {{ plumbing: *, chunkSize?: number, codec?: *, policy?: *, crypto?: *, observability?: *, merkleThreshold?: number, concurrency?: number, chunking?: *, chunker?: * }} */
75
+ #config;
100
76
  /** @type {VaultService|null} */
101
77
  #vault = null;
102
78
  #servicePromise = null;
@@ -113,60 +89,33 @@ export default class ContentAddressableStore {
113
89
  return await this.#servicePromise;
114
90
  }
115
91
 
116
- /**
117
- * Resolves the chunker from config options.
118
- * @private
119
- * @returns {import('./src/ports/ChunkingPort.js').default|undefined}
120
- */
121
- #resolveChunker() {
122
- // Direct ChunkingPort instance takes precedence
123
- if (this.chunkerConfig) {
124
- return this.chunkerConfig;
125
- }
126
- // Build from declarative chunking config
127
- if (this.chunkingConfig) {
128
- if (this.chunkingConfig.strategy === 'cdc') {
129
- return new CdcChunker({
130
- targetChunkSize: this.chunkingConfig.targetChunkSize,
131
- minChunkSize: this.chunkingConfig.minChunkSize,
132
- maxChunkSize: this.chunkingConfig.maxChunkSize,
133
- });
134
- }
135
- // 'fixed' or unrecognized — fall through to default (FixedChunker via CasService)
136
- if (this.chunkingConfig.strategy === 'fixed' && this.chunkingConfig.chunkSize) {
137
- return new FixedChunker({ chunkSize: this.chunkingConfig.chunkSize });
138
- }
139
- }
140
- // undefined → CasService will default to FixedChunker
141
- return undefined;
142
- }
143
-
144
92
  /**
145
93
  * Constructs adapters, resolves crypto, and creates CasService + VaultService.
146
94
  * @private
147
95
  * @returns {Promise<CasService>}
148
96
  */
149
97
  async #initService() {
98
+ const cfg = this.#config;
150
99
  const persistence = new GitPersistenceAdapter({
151
- plumbing: this.plumbing,
152
- policy: this.policyConfig
100
+ plumbing: cfg.plumbing,
101
+ policy: cfg.policy,
153
102
  });
154
- const crypto = this.cryptoConfig || await getDefaultCryptoAdapter();
155
- const chunker = this.#resolveChunker();
103
+ const crypto = cfg.crypto || await createCryptoAdapter();
104
+ const chunker = resolveChunker({ chunker: cfg.chunker, chunking: cfg.chunking });
156
105
  this.service = new CasService({
157
106
  persistence,
158
- chunkSize: this.chunkSizeConfig,
159
- codec: this.codecConfig || new JsonCodec(),
107
+ chunkSize: cfg.chunkSize,
108
+ codec: cfg.codec || new JsonCodec(),
160
109
  crypto,
161
- observability: this.observabilityConfig || new SilentObserver(),
162
- merkleThreshold: this.merkleThresholdConfig,
163
- concurrency: this.concurrencyConfig,
110
+ observability: cfg.observability || new SilentObserver(),
111
+ merkleThreshold: cfg.merkleThreshold,
112
+ concurrency: cfg.concurrency,
164
113
  chunker,
165
114
  });
166
115
 
167
116
  const ref = new GitRefAdapter({
168
- plumbing: this.plumbing,
169
- policy: this.policyConfig,
117
+ plumbing: cfg.plumbing,
118
+ policy: cfg.policy,
170
119
  });
171
120
  this.#vault = new VaultService({ persistence, ref, crypto });
172
121
 
@@ -228,7 +177,7 @@ export default class ContentAddressableStore {
228
177
  * @returns {number}
229
178
  */
230
179
  get chunkSize() {
231
- return this.service?.chunkSize || this.chunkSizeConfig || 256 * 1024;
180
+ return this.service?.chunkSize || this.#config.chunkSize || 256 * 1024;
232
181
  }
233
182
 
234
183
  /**
@@ -269,19 +218,9 @@ export default class ContentAddressableStore {
269
218
  * @param {Array<{label: string, key: Buffer}>} [options.recipients] - Envelope recipients (mutually exclusive with encryptionKey/passphrase).
270
219
  * @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>} The resulting manifest.
271
220
  */
272
- async storeFile({ filePath, slug, filename, encryptionKey, passphrase, kdfOptions, compression, recipients }) {
273
- const source = createReadStream(filePath);
221
+ async storeFile(options) {
274
222
  const service = await this.#getService();
275
- return await service.store({
276
- source,
277
- slug,
278
- filename: filename || path.basename(filePath),
279
- encryptionKey,
280
- passphrase,
281
- kdfOptions,
282
- compression,
283
- recipients,
284
- });
223
+ return await storeFile(service, options);
285
224
  }
286
225
 
287
226
  /**
@@ -311,20 +250,9 @@ export default class ContentAddressableStore {
311
250
  * @param {string} options.outputPath - Destination file path.
312
251
  * @returns {Promise<{ bytesWritten: number }>}
313
252
  */
314
- async restoreFile({ manifest, encryptionKey, passphrase, outputPath }) {
253
+ async restoreFile(options) {
315
254
  const service = await this.#getService();
316
- const iterable = service.restoreStream({ manifest, encryptionKey, passphrase });
317
- const readable = Readable.from(iterable);
318
- const writable = createWriteStream(outputPath);
319
- let bytesWritten = 0;
320
- const counter = new Transform({
321
- transform(chunk, _encoding, cb) {
322
- bytesWritten += chunk.length;
323
- cb(null, chunk);
324
- },
325
- });
326
- await pipeline(readable, counter, writable);
327
- return { bytesWritten };
255
+ return await restoreFile(service, options);
328
256
  }
329
257
 
330
258
  /**
@@ -534,109 +462,13 @@ export default class ContentAddressableStore {
534
462
  * @param {string} options.oldPassphrase - Current vault passphrase.
535
463
  * @param {string} options.newPassphrase - New vault passphrase.
536
464
  * @param {Object} [options.kdfOptions] - KDF options for new passphrase.
465
+ * @param {number} [options.maxRetries=3] - Maximum optimistic-concurrency retries on VAULT_CONFLICT.
466
+ * @param {number} [options.retryBaseMs=50] - Base delay in ms for exponential backoff between retries.
537
467
  * @returns {Promise<{ commitOid: string, rotatedSlugs: string[], skippedSlugs: string[] }>}
538
468
  */
539
- async rotateVaultPassphrase({ oldPassphrase, newPassphrase, kdfOptions }) {
469
+ async rotateVaultPassphrase(options) {
540
470
  const service = await this.#getService();
541
471
  const vault = await this.#getVault();
542
-
543
- const MAX_RETRIES = 3;
544
- const RETRY_BASE_MS = 50;
545
-
546
- for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
547
- const state = await vault.readState();
548
- if (!state.metadata?.encryption) {
549
- throw new CasError('Vault is not encrypted — nothing to rotate', 'VAULT_METADATA_INVALID');
550
- }
551
-
552
- const { kdf } = state.metadata.encryption;
553
- const oldKek = await ContentAddressableStore.#deriveKekFromKdf(service, oldPassphrase, kdf);
554
- const { key: newKek, salt: newSalt, params: newParams } = await service.deriveKey({
555
- passphrase: newPassphrase, ...kdfOptions, algorithm: kdfOptions?.algorithm || kdf.algorithm,
556
- });
557
-
558
- const result = await ContentAddressableStore.#rotateEntries({ service, entries: state.entries, oldKek, newKek });
559
- const newMetadata = ContentAddressableStore.#buildRotatedMetadata(state.metadata, newSalt, newParams);
560
-
561
- try {
562
- const { commitOid } = await vault.writeCommit({
563
- entries: result.updatedEntries,
564
- metadata: newMetadata,
565
- parentCommitOid: state.parentCommitOid,
566
- message: `vault: rotate passphrase (${result.rotatedSlugs.length} rotated, ${result.skippedSlugs.length} skipped)`,
567
- });
568
- return { commitOid, rotatedSlugs: result.rotatedSlugs, skippedSlugs: result.skippedSlugs };
569
- } catch (err) {
570
- if (err instanceof CasError && err.code === 'VAULT_CONFLICT' && attempt < MAX_RETRIES - 1) {
571
- await new Promise((r) => setTimeout(r, RETRY_BASE_MS * (2 ** attempt)));
572
- continue;
573
- }
574
- throw err;
575
- }
576
- }
577
- /* c8 ignore next 2 */
578
- throw new CasError('Vault CAS retries exhausted', 'VAULT_CONFLICT');
579
- }
580
-
581
- /**
582
- * Derives a KEK from a passphrase using stored KDF params.
583
- * @private
584
- */
585
- static async #deriveKekFromKdf(service, passphrase, kdf) {
586
- const { key } = await service.deriveKey({
587
- passphrase,
588
- salt: Buffer.from(kdf.salt, 'base64'),
589
- algorithm: kdf.algorithm,
590
- iterations: kdf.iterations,
591
- cost: kdf.cost,
592
- blockSize: kdf.blockSize,
593
- parallelization: kdf.parallelization,
594
- });
595
- return key;
596
- }
597
-
598
- /**
599
- * Iterates vault entries, rotating envelope-encrypted ones and skipping others.
600
- * @private
601
- */
602
- static async #rotateEntries({ service, entries, oldKek, newKek }) {
603
- const rotatedSlugs = [];
604
- const skippedSlugs = [];
605
- const updatedEntries = new Map(entries);
606
-
607
- for (const [slug, treeOid] of entries) {
608
- const manifest = await service.readManifest({ treeOid });
609
- if (!manifest.encryption?.recipients?.length) {
610
- skippedSlugs.push(slug);
611
- continue;
612
- }
613
- const rotated = await service.rotateKey({ manifest, oldKey: oldKek, newKey: newKek });
614
- updatedEntries.set(slug, await service.createTree({ manifest: rotated }));
615
- rotatedSlugs.push(slug);
616
- }
617
-
618
- return { updatedEntries, rotatedSlugs, skippedSlugs };
619
- }
620
-
621
- /**
622
- * Builds updated vault metadata with new KDF params.
623
- * @private
624
- */
625
- static #buildRotatedMetadata(metadata, newSalt, newParams) {
626
- return {
627
- ...metadata,
628
- encryption: {
629
- cipher: metadata.encryption.cipher,
630
- kdf: {
631
- algorithm: newParams.algorithm,
632
- salt: newSalt.toString('base64'),
633
- ...('iterations' in newParams && { iterations: newParams.iterations }),
634
- ...('cost' in newParams && { cost: newParams.cost }),
635
- ...('blockSize' in newParams && { blockSize: newParams.blockSize }),
636
- ...('parallelization' in newParams && { parallelization: newParams.parallelization }),
637
- keyLength: newParams.keyLength,
638
- },
639
- },
640
- };
472
+ return await rotateVaultPassphrase({ service, vault }, options);
641
473
  }
642
474
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "5.2.1",
3
+ "version": "5.2.4",
4
4
  "description": "Content-addressed storage backed by Git's object database, with optional encryption and pluggable codecs",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -83,6 +83,7 @@
83
83
  },
84
84
  "devDependencies": {
85
85
  "@eslint/js": "^9.17.0",
86
+ "@types/node": "^25.3.2",
86
87
  "eslint": "^9.17.0",
87
88
  "jsr": "^0.14.2",
88
89
  "prettier": "^3.4.2",
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Builds the KDF metadata object for vault/manifest encryption metadata.
3
+ *
4
+ * @param {Buffer} salt - KDF salt.
5
+ * @param {{ algorithm: string, keyLength: number, iterations?: number, cost?: number, blockSize?: number, parallelization?: number }} params - KDF parameters.
6
+ * @returns {{ algorithm: string, salt: string, keyLength: number, iterations?: number, cost?: number, blockSize?: number, parallelization?: number }}
7
+ */
8
+ export default function buildKdfMetadata(salt, params) {
9
+ return {
10
+ algorithm: params.algorithm,
11
+ salt: salt.toString('base64'),
12
+ ...('iterations' in params && { iterations: params.iterations }),
13
+ ...('cost' in params && { cost: params.cost }),
14
+ ...('blockSize' in params && { blockSize: params.blockSize }),
15
+ ...('parallelization' in params && { parallelization: params.parallelization }),
16
+ keyLength: params.keyLength,
17
+ };
18
+ }
@@ -8,7 +8,7 @@ import type { EncryptionMeta, CompressionMeta, KdfParams } from "../value-object
8
8
 
9
9
  /** Port interface for cryptographic operations (hashing, encryption, random bytes). */
10
10
  export interface CryptoPort {
11
- sha256(buf: Buffer): string | Promise<string>;
11
+ sha256(buf: Buffer): Promise<string>;
12
12
  randomBytes(n: number): Buffer;
13
13
  encryptBuffer(
14
14
  buffer: Buffer,