@git-stunts/git-cas 5.1.0 → 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 (45) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +144 -7
  3. package/bin/actions.js +25 -7
  4. package/bin/git-cas.js +150 -26
  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 +22 -1
  15. package/index.js +80 -114
  16. package/package.json +2 -1
  17. package/src/domain/helpers/buildKdfMetadata.js +18 -0
  18. package/src/domain/schemas/ManifestSchema.d.ts +2 -0
  19. package/src/domain/schemas/ManifestSchema.js +2 -0
  20. package/src/domain/services/CasService.d.ts +8 -1
  21. package/src/domain/services/CasService.js +123 -210
  22. package/src/domain/services/KeyResolver.js +220 -0
  23. package/src/domain/services/Semaphore.js +2 -2
  24. package/src/domain/services/VaultService.js +49 -27
  25. package/src/domain/services/rotateVaultPassphrase.js +143 -0
  26. package/src/domain/value-objects/Manifest.d.ts +2 -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 +38 -7
  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 +68 -18
  36. package/src/infrastructure/adapters/createCryptoAdapter.js +25 -0
  37. package/src/infrastructure/chunkers/FixedChunker.js +5 -1
  38. package/src/infrastructure/chunkers/resolveChunker.js +45 -0
  39. package/src/infrastructure/codecs/CborCodec.js +11 -3
  40. package/src/infrastructure/codecs/JsonCodec.js +10 -2
  41. package/src/ports/CodecPort.js +3 -3
  42. package/src/ports/CryptoPort.js +56 -23
  43. package/src/ports/GitPersistencePort.js +4 -4
  44. package/src/ports/GitRefPort.js +10 -10
  45. package/src/types/ambient.d.ts +37 -0
package/index.js CHANGED
@@ -3,63 +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';
11
+ import rotateVaultPassphrase from './src/domain/services/rotateVaultPassphrase.js';
12
12
  import GitPersistenceAdapter from './src/infrastructure/adapters/GitPersistenceAdapter.js';
13
13
  import GitRefAdapter from './src/infrastructure/adapters/GitRefAdapter.js';
14
- import NodeCryptoAdapter from './src/infrastructure/adapters/NodeCryptoAdapter.js';
15
- import Manifest from './src/domain/value-objects/Manifest.js';
16
- import Chunk from './src/domain/value-objects/Chunk.js';
17
- import CryptoPort from './src/ports/CryptoPort.js';
18
- import ChunkingPort from './src/ports/ChunkingPort.js';
19
- 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';
20
16
  import JsonCodec from './src/infrastructure/codecs/JsonCodec.js';
21
17
  import CborCodec from './src/infrastructure/codecs/CborCodec.js';
22
18
  import SilentObserver from './src/infrastructure/adapters/SilentObserver.js';
23
- import EventEmitterObserver from './src/infrastructure/adapters/EventEmitterObserver.js';
24
- import StatsCollector from './src/infrastructure/adapters/StatsCollector.js';
25
- import FixedChunker from './src/infrastructure/chunkers/FixedChunker.js';
26
- import CdcChunker from './src/infrastructure/chunkers/CdcChunker.js';
19
+ import resolveChunker from './src/infrastructure/chunkers/resolveChunker.js';
27
20
 
21
+ // ---------------------------------------------------------------------------
22
+ // Re-exports — modules used in the class body
23
+ // ---------------------------------------------------------------------------
28
24
  export {
29
25
  CasService,
30
26
  VaultService,
31
27
  GitPersistenceAdapter,
32
28
  GitRefAdapter,
33
- NodeCryptoAdapter,
34
- CryptoPort,
35
- ChunkingPort,
36
- ObservabilityPort,
37
- Manifest,
38
- Chunk,
39
29
  JsonCodec,
40
30
  CborCodec,
41
31
  SilentObserver,
42
- EventEmitterObserver,
43
- StatsCollector,
44
- FixedChunker,
45
- CdcChunker,
46
32
  };
47
33
 
48
- /**
49
- * Detects the best crypto adapter for the current runtime.
50
- * @returns {Promise<import('./src/ports/CryptoPort.js').default>} A runtime-appropriate CryptoPort implementation.
51
- */
52
- async function getDefaultCryptoAdapter() {
53
- if (globalThis.Bun) {
54
- const { default: BunCryptoAdapter } = await import('./src/infrastructure/adapters/BunCryptoAdapter.js');
55
- return new BunCryptoAdapter();
56
- }
57
- if (globalThis.Deno) {
58
- const { default: WebCryptoAdapter } = await import('./src/infrastructure/adapters/WebCryptoAdapter.js');
59
- return new WebCryptoAdapter();
60
- }
61
- return new NodeCryptoAdapter();
62
- }
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';
63
47
 
64
48
  /**
65
49
  * High-level facade for the Content Addressable Store library.
@@ -82,20 +66,13 @@ export default class ContentAddressableStore {
82
66
  * @param {import('./src/ports/ChunkingPort.js').default} [options.chunker] - Pre-built ChunkingPort instance (advanced).
83
67
  */
84
68
  constructor({ plumbing, chunkSize, codec, policy, crypto, observability, merkleThreshold, concurrency, chunking, chunker }) {
85
- this.plumbing = plumbing;
86
- this.chunkSizeConfig = chunkSize;
87
- this.codecConfig = codec;
88
- this.policyConfig = policy;
89
- this.cryptoConfig = crypto;
90
- this.observabilityConfig = observability;
91
- this.merkleThresholdConfig = merkleThreshold;
92
- this.concurrencyConfig = concurrency;
93
- this.chunkingConfig = chunking;
94
- this.chunkerConfig = chunker;
69
+ this.#config = { plumbing, chunkSize, codec, policy, crypto, observability, merkleThreshold, concurrency, chunking, chunker };
95
70
  this.service = null;
96
71
  this.#servicePromise = null;
97
72
  }
98
73
 
74
+ /** @type {{ plumbing: *, chunkSize?: number, codec?: *, policy?: *, crypto?: *, observability?: *, merkleThreshold?: number, concurrency?: number, chunking?: *, chunker?: * }} */
75
+ #config;
99
76
  /** @type {VaultService|null} */
100
77
  #vault = null;
101
78
  #servicePromise = null;
@@ -112,60 +89,33 @@ export default class ContentAddressableStore {
112
89
  return await this.#servicePromise;
113
90
  }
114
91
 
115
- /**
116
- * Resolves the chunker from config options.
117
- * @private
118
- * @returns {import('./src/ports/ChunkingPort.js').default|undefined}
119
- */
120
- #resolveChunker() {
121
- // Direct ChunkingPort instance takes precedence
122
- if (this.chunkerConfig) {
123
- return this.chunkerConfig;
124
- }
125
- // Build from declarative chunking config
126
- if (this.chunkingConfig) {
127
- if (this.chunkingConfig.strategy === 'cdc') {
128
- return new CdcChunker({
129
- targetChunkSize: this.chunkingConfig.targetChunkSize,
130
- minChunkSize: this.chunkingConfig.minChunkSize,
131
- maxChunkSize: this.chunkingConfig.maxChunkSize,
132
- });
133
- }
134
- // 'fixed' or unrecognized — fall through to default (FixedChunker via CasService)
135
- if (this.chunkingConfig.strategy === 'fixed' && this.chunkingConfig.chunkSize) {
136
- return new FixedChunker({ chunkSize: this.chunkingConfig.chunkSize });
137
- }
138
- }
139
- // undefined → CasService will default to FixedChunker
140
- return undefined;
141
- }
142
-
143
92
  /**
144
93
  * Constructs adapters, resolves crypto, and creates CasService + VaultService.
145
94
  * @private
146
95
  * @returns {Promise<CasService>}
147
96
  */
148
97
  async #initService() {
98
+ const cfg = this.#config;
149
99
  const persistence = new GitPersistenceAdapter({
150
- plumbing: this.plumbing,
151
- policy: this.policyConfig
100
+ plumbing: cfg.plumbing,
101
+ policy: cfg.policy,
152
102
  });
153
- const crypto = this.cryptoConfig || await getDefaultCryptoAdapter();
154
- const chunker = this.#resolveChunker();
103
+ const crypto = cfg.crypto || await createCryptoAdapter();
104
+ const chunker = resolveChunker({ chunker: cfg.chunker, chunking: cfg.chunking });
155
105
  this.service = new CasService({
156
106
  persistence,
157
- chunkSize: this.chunkSizeConfig,
158
- codec: this.codecConfig || new JsonCodec(),
107
+ chunkSize: cfg.chunkSize,
108
+ codec: cfg.codec || new JsonCodec(),
159
109
  crypto,
160
- observability: this.observabilityConfig || new SilentObserver(),
161
- merkleThreshold: this.merkleThresholdConfig,
162
- concurrency: this.concurrencyConfig,
110
+ observability: cfg.observability || new SilentObserver(),
111
+ merkleThreshold: cfg.merkleThreshold,
112
+ concurrency: cfg.concurrency,
163
113
  chunker,
164
114
  });
165
115
 
166
116
  const ref = new GitRefAdapter({
167
- plumbing: this.plumbing,
168
- policy: this.policyConfig,
117
+ plumbing: cfg.plumbing,
118
+ policy: cfg.policy,
169
119
  });
170
120
  this.#vault = new VaultService({ persistence, ref, crypto });
171
121
 
@@ -227,7 +177,7 @@ export default class ContentAddressableStore {
227
177
  * @returns {number}
228
178
  */
229
179
  get chunkSize() {
230
- return this.service?.chunkSize || this.chunkSizeConfig || 256 * 1024;
180
+ return this.service?.chunkSize || this.#config.chunkSize || 256 * 1024;
231
181
  }
232
182
 
233
183
  /**
@@ -268,19 +218,9 @@ export default class ContentAddressableStore {
268
218
  * @param {Array<{label: string, key: Buffer}>} [options.recipients] - Envelope recipients (mutually exclusive with encryptionKey/passphrase).
269
219
  * @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>} The resulting manifest.
270
220
  */
271
- async storeFile({ filePath, slug, filename, encryptionKey, passphrase, kdfOptions, compression, recipients }) {
272
- const source = createReadStream(filePath);
221
+ async storeFile(options) {
273
222
  const service = await this.#getService();
274
- return await service.store({
275
- source,
276
- slug,
277
- filename: filename || path.basename(filePath),
278
- encryptionKey,
279
- passphrase,
280
- kdfOptions,
281
- compression,
282
- recipients,
283
- });
223
+ return await storeFile(service, options);
284
224
  }
285
225
 
286
226
  /**
@@ -310,20 +250,9 @@ export default class ContentAddressableStore {
310
250
  * @param {string} options.outputPath - Destination file path.
311
251
  * @returns {Promise<{ bytesWritten: number }>}
312
252
  */
313
- async restoreFile({ manifest, encryptionKey, passphrase, outputPath }) {
253
+ async restoreFile(options) {
314
254
  const service = await this.#getService();
315
- const iterable = service.restoreStream({ manifest, encryptionKey, passphrase });
316
- const readable = Readable.from(iterable);
317
- const writable = createWriteStream(outputPath);
318
- let bytesWritten = 0;
319
- const counter = new Transform({
320
- transform(chunk, _encoding, cb) {
321
- bytesWritten += chunk.length;
322
- cb(null, chunk);
323
- },
324
- });
325
- await pipeline(readable, counter, writable);
326
- return { bytesWritten };
255
+ return await restoreFile(service, options);
327
256
  }
328
257
 
329
258
  /**
@@ -464,6 +393,20 @@ export default class ContentAddressableStore {
464
393
  return service.listRecipients(manifest);
465
394
  }
466
395
 
396
+ /**
397
+ * Rotates a recipient's key without re-encrypting data blobs.
398
+ * @param {Object} options
399
+ * @param {import('./src/domain/value-objects/Manifest.js').default} options.manifest
400
+ * @param {Buffer} options.oldKey - Current KEK of the recipient to rotate.
401
+ * @param {Buffer} options.newKey - New KEK to wrap the DEK with.
402
+ * @param {string} [options.label] - If provided, only rotate the named recipient.
403
+ * @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>}
404
+ */
405
+ async rotateKey(options) {
406
+ const service = await this.#getService();
407
+ return await service.rotateKey(options);
408
+ }
409
+
467
410
  // ---------------------------------------------------------------------------
468
411
  // Vault — delegates to VaultService
469
412
  // ---------------------------------------------------------------------------
@@ -505,4 +448,27 @@ export default class ContentAddressableStore {
505
448
  const vault = await this.#getVault();
506
449
  return vault.getVaultMetadata();
507
450
  }
451
+
452
+ // ---------------------------------------------------------------------------
453
+ // Key rotation — orchestrates CasService + VaultService
454
+ // ---------------------------------------------------------------------------
455
+
456
+ /**
457
+ * Rotates the vault-level passphrase. Re-wraps every envelope-encrypted
458
+ * entry's DEK with a new KEK derived from `newPassphrase`. Entries using
459
+ * direct-key encryption are skipped.
460
+ *
461
+ * @param {Object} options
462
+ * @param {string} options.oldPassphrase - Current vault passphrase.
463
+ * @param {string} options.newPassphrase - New vault passphrase.
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.
467
+ * @returns {Promise<{ commitOid: string, rotatedSlugs: string[], skippedSlugs: string[] }>}
468
+ */
469
+ async rotateVaultPassphrase(options) {
470
+ const service = await this.#getService();
471
+ const vault = await this.#getVault();
472
+ return await rotateVaultPassphrase({ service, vault }, options);
473
+ }
508
474
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "5.1.0",
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
+ }
@@ -31,6 +31,7 @@ export declare const RecipientSchema: z.ZodObject<{
31
31
  nonce: z.ZodString;
32
32
  tag: z.ZodString;
33
33
  kekType: z.ZodOptional<z.ZodString>;
34
+ keyVersion: z.ZodOptional<z.ZodNumber>;
34
35
  }>;
35
36
 
36
37
  /** Validates the encryption metadata attached to an encrypted manifest. */
@@ -41,6 +42,7 @@ export declare const EncryptionSchema: z.ZodObject<{
41
42
  encrypted: z.ZodDefault<z.ZodBoolean>;
42
43
  kdf: z.ZodOptional<typeof KdfSchema>;
43
44
  recipients: z.ZodOptional<z.ZodArray<typeof RecipientSchema>>;
45
+ keyVersion: z.ZodOptional<z.ZodNumber>;
44
46
  }>;
45
47
 
46
48
  /** Validates compression metadata. */
@@ -31,6 +31,7 @@ export const RecipientSchema = z.object({
31
31
  nonce: z.string().min(1),
32
32
  tag: z.string().min(1),
33
33
  kekType: z.string().optional(),
34
+ keyVersion: z.number().int().min(0).optional(),
34
35
  });
35
36
 
36
37
  /** Validates the encryption metadata attached to an encrypted manifest. */
@@ -41,6 +42,7 @@ export const EncryptionSchema = z.object({
41
42
  encrypted: z.boolean().default(true),
42
43
  kdf: KdfSchema.optional(),
43
44
  recipients: z.array(RecipientSchema).min(1).optional(),
45
+ keyVersion: z.number().int().min(0).optional(),
44
46
  });
45
47
 
46
48
  /** Validates compression metadata. */
@@ -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,
@@ -153,6 +153,13 @@ export default class CasService {
153
153
 
154
154
  listRecipients(manifest: Manifest): string[];
155
155
 
156
+ rotateKey(options: {
157
+ manifest: Manifest;
158
+ oldKey: Buffer;
159
+ newKey: Buffer;
160
+ label?: string;
161
+ }): Promise<Manifest>;
162
+
156
163
  verifyIntegrity(manifest: Manifest): Promise<boolean>;
157
164
 
158
165
  deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;