@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
@@ -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 '/'.
@@ -59,9 +82,9 @@ export default class VaultService {
59
82
 
60
83
  /**
61
84
  * @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
85
+ * @param {import('../../ports/GitPersistencePort.js').default} options.persistence
86
+ * @param {import('../../ports/GitRefPort.js').default} options.ref
87
+ * @param {import('../../ports/CryptoPort.js').default} options.crypto
65
88
  */
66
89
  constructor({ persistence, ref, crypto }) {
67
90
  this.persistence = persistence;
@@ -75,7 +98,8 @@ export default class VaultService {
75
98
 
76
99
  /**
77
100
  * Validates a single slug segment.
78
- * @private
101
+ * @param {string} seg - Segment to validate.
102
+ * @param {string} slug - Full slug (for error context).
79
103
  */
80
104
  static #validateSegment(seg, slug) {
81
105
  if (seg.length === 0) {
@@ -118,7 +142,8 @@ export default class VaultService {
118
142
 
119
143
  /**
120
144
  * Validates encryption-specific metadata fields.
121
- * @private
145
+ * @param {VaultEncryptionMeta} encryption - Encryption metadata.
146
+ * @param {VaultMetadata} metadata - Full metadata (for error context).
122
147
  */
123
148
  static #validateEncryption(encryption, metadata) {
124
149
  const { cipher, kdf } = encryption;
@@ -133,7 +158,7 @@ export default class VaultService {
133
158
 
134
159
  /**
135
160
  * Validates vault metadata object structure.
136
- * @private
161
+ * @param {VaultMetadata} metadata - Metadata to validate.
137
162
  */
138
163
  static #validateMetadata(metadata) {
139
164
  if (typeof metadata.version !== 'number' || metadata.version !== 1) {
@@ -150,7 +175,8 @@ export default class VaultService {
150
175
 
151
176
  /**
152
177
  * Reads and validates vault metadata from a blob OID.
153
- * @private
178
+ * @param {string} blobOid - Git blob OID of the .vault.json file.
179
+ * @returns {Promise<VaultMetadata>}
154
180
  */
155
181
  async #readMetadataBlob(blobOid) {
156
182
  try {
@@ -161,7 +187,7 @@ export default class VaultService {
161
187
  } catch (err) {
162
188
  if (err instanceof CasError) { throw err; }
163
189
  throw new CasError(
164
- `Failed to parse .vault.json: ${err.message}`,
190
+ `Failed to parse .vault.json: ${/** @type {Error} */ (err).message}`,
165
191
  'VAULT_METADATA_INVALID',
166
192
  { originalError: err },
167
193
  );
@@ -174,8 +200,8 @@ export default class VaultService {
174
200
 
175
201
  /**
176
202
  * Separates vault tree entries into slug→OID map and metadata blob OID.
177
- * @private
178
203
  * @param {Array<{ mode: string, type: string, oid: string, name: string }>} treeEntries
204
+ * @returns {{ entries: Map<string, string>, metadataBlobOid: string|null }}
179
205
  */
180
206
  static #parseTreeEntries(treeEntries) {
181
207
  const entries = new Map();
@@ -192,7 +218,7 @@ export default class VaultService {
192
218
 
193
219
  /**
194
220
  * Reads the current vault state from refs/cas/vault.
195
- * @returns {Promise<{ entries: Map<string, string>, parentCommitOid: string|null, metadata: object|null }>}
221
+ * @returns {Promise<VaultState>}
196
222
  */
197
223
  async readState() {
198
224
  let commitOid;
@@ -216,7 +242,7 @@ export default class VaultService {
216
242
  * Writes a new vault commit and updates the ref atomically.
217
243
  * @param {Object} options
218
244
  * @param {Map<string, string>} options.entries - Slug→treeOid map.
219
- * @param {object} options.metadata - Vault metadata (.vault.json contents).
245
+ * @param {VaultMetadata} options.metadata - Vault metadata (.vault.json contents).
220
246
  * @param {string|null} options.parentCommitOid - Parent commit OID (null for first commit).
221
247
  * @param {string} options.message - Commit message.
222
248
  * @returns {Promise<{ commitOid: string }>}
@@ -244,7 +270,8 @@ export default class VaultService {
244
270
 
245
271
  /**
246
272
  * Atomically updates the vault ref with CAS semantics.
247
- * @private
273
+ * @param {string} newOid - New commit OID.
274
+ * @param {string|null} expectedOldOid - Expected current commit OID.
248
275
  */
249
276
  async #casUpdateRef(newOid, expectedOldOid) {
250
277
  try {
@@ -264,8 +291,7 @@ export default class VaultService {
264
291
 
265
292
  /**
266
293
  * Wraps a vault mutation with CAS retry logic.
267
- * @private
268
- * @param {function} mutationFn - Async function(state) → { entries, metadata, message }
294
+ * @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
295
  * @returns {Promise<{ commitOid: string }>}
270
296
  */
271
297
  async #retryMutation(mutationFn) {
@@ -295,20 +321,14 @@ export default class VaultService {
295
321
 
296
322
  /**
297
323
  * Builds vault encryption metadata from KDF result.
298
- * @private
324
+ * @param {Buffer} salt - KDF salt.
325
+ * @param {import('../../ports/CryptoPort.js').KdfParamSet} params - KDF parameters.
326
+ * @returns {VaultEncryptionMeta}
299
327
  */
300
328
  static #buildEncryptionMeta(salt, params) {
301
329
  return {
302
330
  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
- },
331
+ kdf: buildKdfMetadata(salt, params),
312
332
  };
313
333
  }
314
334
 
@@ -333,6 +353,7 @@ export default class VaultService {
333
353
  );
334
354
  }
335
355
 
356
+ /** @type {VaultMetadata} */
336
357
  const metadata = { version: 1 };
337
358
  if (passphrase) {
338
359
  const { salt, params } = await this.crypto.deriveKey({ passphrase, ...kdfOptions });
@@ -394,6 +415,7 @@ export default class VaultService {
394
415
  * @returns {Promise<{ commitOid: string, removedTreeOid: string }>}
395
416
  */
396
417
  async removeFromVault({ slug }) {
418
+ /** @type {string|undefined} */
397
419
  let removedTreeOid;
398
420
 
399
421
  const result = await this.#retryMutation((state) => {
@@ -413,7 +435,7 @@ export default class VaultService {
413
435
  };
414
436
  });
415
437
 
416
- return { commitOid: result.commitOid, removedTreeOid };
438
+ return { commitOid: result.commitOid, removedTreeOid: /** @type {string} */ (removedTreeOid) };
417
439
  }
418
440
 
419
441
  /**
@@ -431,12 +453,12 @@ export default class VaultService {
431
453
  { slug },
432
454
  );
433
455
  }
434
- return entries.get(slug);
456
+ return /** @type {string} */ (entries.get(slug));
435
457
  }
436
458
 
437
459
  /**
438
460
  * Returns the vault metadata, or null if no vault exists.
439
- * @returns {Promise<object|null>}
461
+ * @returns {Promise<VaultMetadata|null>}
440
462
  */
441
463
  async getVaultMetadata() {
442
464
  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
+ }
@@ -1,3 +1,4 @@
1
+ // @ts-ignore -- 'bun' module only available in Bun runtime
1
2
  import { CryptoHasher } from 'bun';
2
3
  import CryptoPort from '../../ports/CryptoPort.js';
3
4
  import CasError from '../../domain/errors/CasError.js';
@@ -14,18 +15,31 @@ import { promisify } from 'node:util';
14
15
  * AES-256-GCM (Bun's Node compat layer is heavily optimized for these APIs).
15
16
  */
16
17
  export default class BunCryptoAdapter extends CryptoPort {
17
- /** @override */
18
+ /**
19
+ * @override
20
+ * @param {Buffer|Uint8Array} buf - Data to hash.
21
+ * @returns {Promise<string>} 64-char hex digest.
22
+ */
18
23
  async sha256(buf) {
19
24
  return new CryptoHasher('sha256').update(buf).digest('hex');
20
25
  }
21
26
 
22
- /** @override */
27
+ /**
28
+ * @override
29
+ * @param {number} n - Number of random bytes.
30
+ * @returns {Buffer}
31
+ */
23
32
  randomBytes(n) {
24
33
  const uint8 = globalThis.crypto.getRandomValues(new Uint8Array(n));
25
34
  return Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength);
26
35
  }
27
36
 
28
- /** @override */
37
+ /**
38
+ * @override
39
+ * @param {Buffer|Uint8Array} buffer - Plaintext to encrypt.
40
+ * @param {Buffer|Uint8Array} key - 32-byte encryption key.
41
+ * @returns {Promise<{ buf: Buffer, meta: import('../../ports/CryptoPort.js').EncryptionMeta }>}
42
+ */
29
43
  async encryptBuffer(buffer, key) {
30
44
  this._validateKey(key);
31
45
  const nonce = this.randomBytes(12);
@@ -38,7 +52,13 @@ export default class BunCryptoAdapter extends CryptoPort {
38
52
  };
39
53
  }
40
54
 
41
- /** @override */
55
+ /**
56
+ * @override
57
+ * @param {Buffer|Uint8Array} buffer - Ciphertext to decrypt.
58
+ * @param {Buffer|Uint8Array} key - 32-byte encryption key.
59
+ * @param {import('../../ports/CryptoPort.js').EncryptionMeta} meta - Encryption metadata.
60
+ * @returns {Promise<Buffer>}
61
+ */
42
62
  async decryptBuffer(buffer, key, meta) {
43
63
  this._validateKey(key);
44
64
  const nonce = Buffer.from(meta.nonce, 'base64');
@@ -48,13 +68,18 @@ export default class BunCryptoAdapter extends CryptoPort {
48
68
  return Buffer.concat([decipher.update(buffer), decipher.final()]);
49
69
  }
50
70
 
51
- /** @override */
71
+ /**
72
+ * @override
73
+ * @param {Buffer|Uint8Array} key - 32-byte encryption key.
74
+ * @returns {{ encrypt: (source: AsyncIterable<Buffer>) => AsyncIterable<Buffer>, finalize: () => import('../../ports/CryptoPort.js').EncryptionMeta }}
75
+ */
52
76
  createEncryptionStream(key) {
53
77
  this._validateKey(key);
54
78
  const nonce = this.randomBytes(12);
55
79
  const cipher = createCipheriv('aes-256-gcm', key, nonce);
56
80
  let streamFinalized = false;
57
81
 
82
+ /** @param {AsyncIterable<Buffer>} source */
58
83
  const encrypt = async function* (source) {
59
84
  for await (const chunk of source) {
60
85
  const encrypted = cipher.update(chunk);
@@ -83,11 +108,18 @@ export default class BunCryptoAdapter extends CryptoPort {
83
108
  return { encrypt, finalize };
84
109
  }
85
110
 
86
- /** @override */
111
+ /**
112
+ * @override
113
+ * @param {string} passphrase - The passphrase.
114
+ * @param {Buffer|Uint8Array} saltBuf - Salt bytes.
115
+ * @param {import('../../ports/CryptoPort.js').DeriveKeyParams} params - KDF parameters.
116
+ * @returns {Promise<Buffer>}
117
+ */
87
118
  async _doDeriveKey(passphrase, saltBuf, { algorithm, iterations, cost, blockSize, parallelization, keyLength }) {
88
119
  if (algorithm === 'pbkdf2') {
89
120
  return promisify(pbkdf2)(passphrase, saltBuf, iterations, keyLength, 'sha512');
90
121
  }
122
+ // @ts-ignore -- promisify(scrypt) accepts options as 4th arg at runtime
91
123
  return promisify(scrypt)(passphrase, saltBuf, keyLength, {
92
124
  N: cost,
93
125
  r: blockSize,
@@ -16,8 +16,8 @@ export default class EventEmitterObserver {
16
16
  * Error metrics are only emitted when listeners are attached (matching
17
17
  * the previous CasService behavior that guarded `this.emit('error', ...)`).
18
18
  *
19
- * @param {string} channel
20
- * @param {Object} data - Must include `action` to form the event name.
19
+ * @param {string} channel - Metric channel.
20
+ * @param {Record<string, unknown> & { action: string }} data - Must include `action` to form the event name.
21
21
  */
22
22
  metric(channel, data) {
23
23
  if (channel === 'error') {
@@ -26,21 +26,33 @@ export default class EventEmitterObserver {
26
26
  }
27
27
  return;
28
28
  }
29
+ if (typeof data.action !== 'string') {
30
+ return;
31
+ }
29
32
  const eventName = `${channel}:${data.action}`;
30
33
  const payload = Object.fromEntries(Object.entries(data).filter(([k]) => k !== 'action'));
31
34
  this.#emitter.emit(eventName, payload);
32
35
  }
33
36
 
37
+ /**
38
+ * @param {'debug'|'info'|'warn'|'error'} _level - Log level.
39
+ * @param {string} _msg - Log message.
40
+ * @param {Record<string, unknown>} [_meta] - Optional metadata.
41
+ */
34
42
  log(_level, _msg, _meta) {}
35
43
 
44
+ /**
45
+ * @param {string} _name - Span name.
46
+ * @returns {{ end(meta?: Record<string, unknown>): void }}
47
+ */
36
48
  span(_name) {
37
49
  return { end() {} };
38
50
  }
39
51
 
40
52
  /**
41
53
  * Subscribe to an event.
42
- * @param {string} event
43
- * @param {Function} listener
54
+ * @param {string} event - Event name.
55
+ * @param {(...args: unknown[]) => void} listener - Event listener.
44
56
  * @returns {this}
45
57
  */
46
58
  on(event, listener) {
@@ -50,8 +62,8 @@ export default class EventEmitterObserver {
50
62
 
51
63
  /**
52
64
  * Remove a listener.
53
- * @param {string} event
54
- * @param {Function} listener
65
+ * @param {string} event - Event name.
66
+ * @param {(...args: unknown[]) => void} listener - Event listener.
55
67
  * @returns {this}
56
68
  */
57
69
  removeListener(event, listener) {
@@ -61,7 +73,7 @@ export default class EventEmitterObserver {
61
73
 
62
74
  /**
63
75
  * Return the number of listeners for an event.
64
- * @param {string} event
76
+ * @param {string} event - Event name.
65
77
  * @returns {number}
66
78
  */
67
79
  listenerCount(event) {
@@ -0,0 +1,64 @@
1
+ /**
2
+ * @fileoverview File I/O helpers for storing and restoring files via CasService.
3
+ */
4
+ import { createReadStream, createWriteStream } from 'node:fs';
5
+ import path from 'node:path';
6
+ import { Readable, Transform } from 'node:stream';
7
+ import { pipeline } from 'node:stream/promises';
8
+
9
+ /**
10
+ * Reads a file from disk and stores it in Git as chunked blobs via
11
+ * the given {@link import('../../domain/services/CasService.js').default CasService}.
12
+ *
13
+ * @param {import('../../domain/services/CasService.js').default} service - Initialized CasService.
14
+ * @param {Object} options
15
+ * @param {string} options.filePath - Absolute or relative path to the file.
16
+ * @param {string} options.slug - Logical identifier for the stored asset.
17
+ * @param {string} [options.filename] - Override filename (defaults to basename of filePath).
18
+ * @param {Buffer} [options.encryptionKey] - 32-byte key for AES-256-GCM encryption.
19
+ * @param {string} [options.passphrase] - Derive encryption key from passphrase.
20
+ * @param {Object} [options.kdfOptions] - KDF options when using passphrase.
21
+ * @param {{ algorithm: 'gzip' }} [options.compression] - Enable compression.
22
+ * @param {Array<{label: string, key: Buffer}>} [options.recipients] - Envelope recipients.
23
+ * @returns {Promise<import('../../domain/value-objects/Manifest.js').default>} The resulting manifest.
24
+ */
25
+ export async function storeFile(service, { filePath, slug, filename, encryptionKey, passphrase, kdfOptions, compression, recipients }) {
26
+ const source = createReadStream(filePath);
27
+ return await service.store({
28
+ source,
29
+ slug,
30
+ filename: filename || path.basename(filePath),
31
+ encryptionKey,
32
+ passphrase,
33
+ kdfOptions,
34
+ compression,
35
+ recipients,
36
+ });
37
+ }
38
+
39
+ /**
40
+ * Restores a file from its manifest and writes it to disk via the given
41
+ * {@link import('../../domain/services/CasService.js').default CasService}.
42
+ *
43
+ * @param {import('../../domain/services/CasService.js').default} service - Initialized CasService.
44
+ * @param {Object} options
45
+ * @param {import('../../domain/value-objects/Manifest.js').default} options.manifest - The file manifest.
46
+ * @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
47
+ * @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
48
+ * @param {string} options.outputPath - Destination file path.
49
+ * @returns {Promise<{ bytesWritten: number }>}
50
+ */
51
+ export async function restoreFile(service, { manifest, encryptionKey, passphrase, outputPath }) {
52
+ const iterable = service.restoreStream({ manifest, encryptionKey, passphrase });
53
+ const readable = Readable.from(iterable);
54
+ const writable = createWriteStream(outputPath);
55
+ let bytesWritten = 0;
56
+ const counter = new Transform({
57
+ transform(chunk, _encoding, cb) {
58
+ bytesWritten += chunk.length;
59
+ cb(null, chunk);
60
+ },
61
+ });
62
+ await pipeline(readable, counter, writable);
63
+ return { bytesWritten };
64
+ }
@@ -30,7 +30,11 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
30
30
  this.policy = policy ?? DEFAULT_POLICY;
31
31
  }
32
32
 
33
- /** @override */
33
+ /**
34
+ * @override
35
+ * @param {Buffer|string} content - Data to store.
36
+ * @returns {Promise<string>} The Git OID of the stored blob.
37
+ */
34
38
  async writeBlob(content) {
35
39
  return this.policy.execute(() =>
36
40
  this.plumbing.execute({
@@ -40,7 +44,11 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
40
44
  );
41
45
  }
42
46
 
43
- /** @override */
47
+ /**
48
+ * @override
49
+ * @param {string[]} entries - Lines in `git mktree` format.
50
+ * @returns {Promise<string>} The Git OID of the created tree.
51
+ */
44
52
  async writeTree(entries) {
45
53
  return this.policy.execute(() =>
46
54
  this.plumbing.execute({
@@ -50,7 +58,11 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
50
58
  );
51
59
  }
52
60
 
53
- /** @override */
61
+ /**
62
+ * @override
63
+ * @param {string} oid - Git object ID.
64
+ * @returns {Promise<Buffer>} The blob content.
65
+ */
54
66
  async readBlob(oid) {
55
67
  return this.policy.execute(async () => {
56
68
  const stream = await this.plumbing.executeStream({
@@ -62,7 +74,11 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
62
74
  });
63
75
  }
64
76
 
65
- /** @override */
77
+ /**
78
+ * @override
79
+ * @param {string} treeOid - Git tree OID.
80
+ * @returns {Promise<Array<{ mode: string, type: string, oid: string, name: string }>>}
81
+ */
66
82
  async readTree(treeOid) {
67
83
  return this.policy.execute(async () => {
68
84
  const output = await this.plumbing.execute({
@@ -73,7 +89,7 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
73
89
  return [];
74
90
  }
75
91
 
76
- return output.split('\0').filter(Boolean).map((entry) => {
92
+ return output.split('\0').filter(Boolean).map((/** @type {string} */ entry) => {
77
93
  // Format: <mode> <type> <oid>\t<name>
78
94
  const tabIndex = entry.indexOf('\t');
79
95
  if (tabIndex === -1) {