@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
@@ -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,
@@ -171,6 +171,8 @@ export interface ContentAddressableStoreOptions {
171
171
  concurrency?: number;
172
172
  chunking?: ChunkingConfig;
173
173
  chunker?: ChunkingPort;
174
+ /** Maximum bytes to buffer during encrypted/compressed restore. @default 536870912 (512 MiB) */
175
+ maxRestoreBufferSize?: number;
174
176
  }
175
177
 
176
178
  /** A single vault entry. */
@@ -182,6 +184,8 @@ export interface VaultEntry {
182
184
  /** Vault metadata stored in .vault.json. */
183
185
  export interface VaultMetadata {
184
186
  version: number;
187
+ /** Number of encrypted store operations performed with this vault key. */
188
+ encryptionCount?: number;
185
189
  encryption?: {
186
190
  cipher: string;
187
191
  kdf: {
@@ -213,6 +217,7 @@ export declare class VaultService {
213
217
  persistence: GitPersistencePortBase;
214
218
  ref: GitRefPortBase;
215
219
  crypto: CryptoPortBase;
220
+ observability?: ObservabilityPort;
216
221
  });
217
222
 
218
223
  /** Validates a vault slug. Throws CasError with code INVALID_SLUG on failure. */
@@ -341,10 +346,20 @@ export default class ContentAddressableStore {
341
346
 
342
347
  readManifest(options: { treeOid: string }): Promise<Manifest>;
343
348
 
349
+ inspectAsset(options: {
350
+ treeOid: string;
351
+ }): Promise<{ slug: string; chunksOrphaned: number }>;
352
+
353
+ /** @deprecated Use {@link inspectAsset} instead. */
344
354
  deleteAsset(options: {
345
355
  treeOid: string;
346
356
  }): Promise<{ slug: string; chunksOrphaned: number }>;
347
357
 
358
+ collectReferencedChunks(options: {
359
+ treeOids: string[];
360
+ }): Promise<{ referenced: Set<string>; total: number }>;
361
+
362
+ /** @deprecated Use {@link collectReferencedChunks} instead. */
348
363
  findOrphanedChunks(options: {
349
364
  treeOids: string[];
350
365
  }): Promise<{ referenced: Set<string>; total: number }>;
@@ -401,6 +416,10 @@ export default class ContentAddressableStore {
401
416
  oldPassphrase: string;
402
417
  newPassphrase: string;
403
418
  kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
419
+ /** Maximum optimistic-concurrency retries on VAULT_CONFLICT. @default 3 */
420
+ maxRetries?: number;
421
+ /** Base delay in ms for exponential backoff between retries. @default 50 */
422
+ retryBaseMs?: number;
404
423
  }): Promise<{
405
424
  commitOid: string;
406
425
  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.
@@ -81,22 +64,16 @@ export default class ContentAddressableStore {
81
64
  * @param {number} [options.concurrency=1] - Maximum parallel chunk I/O operations.
82
65
  * @param {{ strategy: string, chunkSize?: number, targetChunkSize?: number, minChunkSize?: number, maxChunkSize?: number }} [options.chunking] - Chunking strategy config.
83
66
  * @param {import('./src/ports/ChunkingPort.js').default} [options.chunker] - Pre-built ChunkingPort instance (advanced).
67
+ * @param {number} [options.maxRestoreBufferSize=536870912] - Max buffered restore size in bytes for encrypted/compressed restores (default 512 MiB).
84
68
  */
85
- 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
+ constructor({ plumbing, chunkSize, codec, policy, crypto, observability, merkleThreshold, concurrency, chunking, chunker, maxRestoreBufferSize }) {
70
+ this.#config = { plumbing, chunkSize, codec, policy, crypto, observability, merkleThreshold, concurrency, chunking, chunker, maxRestoreBufferSize };
96
71
  this.service = null;
97
72
  this.#servicePromise = null;
98
73
  }
99
74
 
75
+ /** @type {{ plumbing: *, chunkSize?: number, codec?: *, policy?: *, crypto?: *, observability?: *, merkleThreshold?: number, concurrency?: number, chunking?: *, chunker?: *, maxRestoreBufferSize?: number }} */
76
+ #config;
100
77
  /** @type {VaultService|null} */
101
78
  #vault = null;
102
79
  #servicePromise = null;
@@ -113,62 +90,36 @@ export default class ContentAddressableStore {
113
90
  return await this.#servicePromise;
114
91
  }
115
92
 
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
93
  /**
145
94
  * Constructs adapters, resolves crypto, and creates CasService + VaultService.
146
95
  * @private
147
96
  * @returns {Promise<CasService>}
148
97
  */
149
98
  async #initService() {
99
+ const cfg = this.#config;
150
100
  const persistence = new GitPersistenceAdapter({
151
- plumbing: this.plumbing,
152
- policy: this.policyConfig
101
+ plumbing: cfg.plumbing,
102
+ policy: cfg.policy,
153
103
  });
154
- const crypto = this.cryptoConfig || await getDefaultCryptoAdapter();
155
- const chunker = this.#resolveChunker();
104
+ const crypto = cfg.crypto || await createCryptoAdapter();
105
+ const chunker = resolveChunker({ chunker: cfg.chunker, chunking: cfg.chunking });
156
106
  this.service = new CasService({
157
107
  persistence,
158
- chunkSize: this.chunkSizeConfig,
159
- codec: this.codecConfig || new JsonCodec(),
108
+ chunkSize: cfg.chunkSize,
109
+ codec: cfg.codec || new JsonCodec(),
160
110
  crypto,
161
- observability: this.observabilityConfig || new SilentObserver(),
162
- merkleThreshold: this.merkleThresholdConfig,
163
- concurrency: this.concurrencyConfig,
111
+ observability: cfg.observability || new SilentObserver(),
112
+ merkleThreshold: cfg.merkleThreshold,
113
+ concurrency: cfg.concurrency,
164
114
  chunker,
115
+ maxRestoreBufferSize: cfg.maxRestoreBufferSize,
165
116
  });
166
117
 
167
118
  const ref = new GitRefAdapter({
168
- plumbing: this.plumbing,
169
- policy: this.policyConfig,
119
+ plumbing: cfg.plumbing,
120
+ policy: cfg.policy,
170
121
  });
171
- this.#vault = new VaultService({ persistence, ref, crypto });
122
+ this.#vault = new VaultService({ persistence, ref, crypto, observability: this.service.observability });
172
123
 
173
124
  return this.service;
174
125
  }
@@ -228,7 +179,7 @@ export default class ContentAddressableStore {
228
179
  * @returns {number}
229
180
  */
230
181
  get chunkSize() {
231
- return this.service?.chunkSize || this.chunkSizeConfig || 256 * 1024;
182
+ return this.service?.chunkSize || this.#config.chunkSize || 256 * 1024;
232
183
  }
233
184
 
234
185
  /**
@@ -269,19 +220,9 @@ export default class ContentAddressableStore {
269
220
  * @param {Array<{label: string, key: Buffer}>} [options.recipients] - Envelope recipients (mutually exclusive with encryptionKey/passphrase).
270
221
  * @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>} The resulting manifest.
271
222
  */
272
- async storeFile({ filePath, slug, filename, encryptionKey, passphrase, kdfOptions, compression, recipients }) {
273
- const source = createReadStream(filePath);
223
+ async storeFile(options) {
274
224
  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
- });
225
+ return await storeFile(service, options);
285
226
  }
286
227
 
287
228
  /**
@@ -311,20 +252,9 @@ export default class ContentAddressableStore {
311
252
  * @param {string} options.outputPath - Destination file path.
312
253
  * @returns {Promise<{ bytesWritten: number }>}
313
254
  */
314
- async restoreFile({ manifest, encryptionKey, passphrase, outputPath }) {
255
+ async restoreFile(options) {
315
256
  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 };
257
+ return await restoreFile(service, options);
328
258
  }
329
259
 
330
260
  /**
@@ -386,7 +316,18 @@ export default class ContentAddressableStore {
386
316
  }
387
317
 
388
318
  /**
389
- * Returns deletion metadata for an asset stored in a Git tree.
319
+ * Reads a manifest from a Git tree and returns inspection metadata.
320
+ * @param {Object} options
321
+ * @param {string} options.treeOid - Git tree OID of the asset.
322
+ * @returns {Promise<{ slug: string, chunksOrphaned: number }>}
323
+ */
324
+ async inspectAsset(options) {
325
+ const service = await this.#getService();
326
+ return await service.inspectAsset(options);
327
+ }
328
+
329
+ /**
330
+ * @deprecated Use {@link inspectAsset} instead.
390
331
  * @param {Object} options
391
332
  * @param {string} options.treeOid - Git tree OID of the asset.
392
333
  * @returns {Promise<{ slug: string, chunksOrphaned: number }>}
@@ -402,6 +343,17 @@ export default class ContentAddressableStore {
402
343
  * @param {string[]} options.treeOids - Git tree OIDs to analyze.
403
344
  * @returns {Promise<{ referenced: Set<string>, total: number }>}
404
345
  */
346
+ async collectReferencedChunks(options) {
347
+ const service = await this.#getService();
348
+ return await service.collectReferencedChunks(options);
349
+ }
350
+
351
+ /**
352
+ * @deprecated Use {@link collectReferencedChunks} instead.
353
+ * @param {Object} options
354
+ * @param {string[]} options.treeOids - Git tree OIDs to analyze.
355
+ * @returns {Promise<{ referenced: Set<string>, total: number }>}
356
+ */
405
357
  async findOrphanedChunks(options) {
406
358
  const service = await this.#getService();
407
359
  return await service.findOrphanedChunks(options);
@@ -534,109 +486,13 @@ export default class ContentAddressableStore {
534
486
  * @param {string} options.oldPassphrase - Current vault passphrase.
535
487
  * @param {string} options.newPassphrase - New vault passphrase.
536
488
  * @param {Object} [options.kdfOptions] - KDF options for new passphrase.
489
+ * @param {number} [options.maxRetries=3] - Maximum optimistic-concurrency retries on VAULT_CONFLICT.
490
+ * @param {number} [options.retryBaseMs=50] - Base delay in ms for exponential backoff between retries.
537
491
  * @returns {Promise<{ commitOid: string, rotatedSlugs: string[], skippedSlugs: string[] }>}
538
492
  */
539
- async rotateVaultPassphrase({ oldPassphrase, newPassphrase, kdfOptions }) {
493
+ async rotateVaultPassphrase(options) {
540
494
  const service = await this.#getService();
541
495
  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
- };
496
+ return await rotateVaultPassphrase({ service, vault }, options);
641
497
  }
642
498
  }
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.3.0",
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",
@@ -15,6 +15,8 @@ export default class CasError extends Error {
15
15
  this.name = this.constructor.name;
16
16
  this.code = code;
17
17
  this.meta = meta;
18
- Error.captureStackTrace(this, this.constructor);
18
+ if (Error.captureStackTrace) {
19
+ Error.captureStackTrace(this, this.constructor);
20
+ }
19
21
  }
20
22
  }
@@ -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
+ }