@git-stunts/git-cas 3.1.0 → 5.0.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.
@@ -3,12 +3,13 @@
3
3
  * @fileoverview Domain service for Content Addressable Storage operations.
4
4
  * @module
5
5
  */
6
- import { EventEmitter } from 'node:events';
7
6
  import { gunzip, createGzip } from 'node:zlib';
8
7
  import { Readable } from 'node:stream';
9
8
  import { promisify } from 'node:util';
10
9
  import Manifest from '../value-objects/Manifest.js';
11
10
  import CasError from '../errors/CasError.js';
11
+ import Semaphore from './Semaphore.js';
12
+ import FixedChunker from '../../infrastructure/chunkers/FixedChunker.js';
12
13
 
13
14
  const gunzipAsync = promisify(gunzip);
14
15
 
@@ -16,39 +17,56 @@ const gunzipAsync = promisify(gunzip);
16
17
  * Domain service for Content Addressable Storage operations.
17
18
  *
18
19
  * Provides chunking, encryption, and integrity verification for storing
19
- * arbitrary data in Git's object database. Extends {@link EventEmitter} to
20
- * emit progress events during store/restore operations.
21
- *
22
- * @fires CasService#chunk:stored
23
- * @fires CasService#chunk:restored
24
- * @fires CasService#file:stored
25
- * @fires CasService#file:restored
26
- * @fires CasService#integrity:pass
27
- * @fires CasService#integrity:fail
28
- * @fires CasService#error
20
+ * arbitrary data in Git's object database.
29
21
  */
30
- export default class CasService extends EventEmitter {
22
+ export default class CasService {
31
23
  /**
32
24
  * @param {Object} options
33
25
  * @param {import('../../ports/GitPersistencePort.js').default} options.persistence
34
26
  * @param {import('../../ports/CodecPort.js').default} options.codec
35
27
  * @param {import('../../ports/CryptoPort.js').default} options.crypto
28
+ * @param {import('../../ports/ObservabilityPort.js').default} options.observability
36
29
  * @param {number} [options.chunkSize=262144] - 256 KiB
37
30
  * @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
31
+ * @param {number} [options.concurrency=1] - Maximum parallel chunk I/O operations.
32
+ * @param {import('../../ports/ChunkingPort.js').default} [options.chunker] - Chunking strategy (default FixedChunker).
38
33
  */
39
- constructor({ persistence, codec, crypto, chunkSize = 256 * 1024, merkleThreshold = 1000 }) {
40
- super();
34
+ constructor({ persistence, codec, crypto, observability, chunkSize = 256 * 1024, merkleThreshold = 1000, concurrency = 1, chunker }) {
35
+ CasService._validateObservability(observability);
41
36
  if (chunkSize < 1024) {
42
37
  throw new Error('Chunk size must be at least 1024 bytes');
43
38
  }
44
39
  this.persistence = persistence;
45
40
  this.codec = codec;
46
41
  this.crypto = crypto;
42
+ this.observability = observability;
47
43
  this.chunkSize = chunkSize;
44
+ /** @type {import('../../ports/ChunkingPort.js').default} */
45
+ this.chunker = chunker || new FixedChunker({ chunkSize });
48
46
  if (!Number.isInteger(merkleThreshold) || merkleThreshold < 1) {
49
47
  throw new Error('Merkle threshold must be a positive integer');
50
48
  }
51
49
  this.merkleThreshold = merkleThreshold;
50
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
51
+ throw new Error('Concurrency must be a positive integer');
52
+ }
53
+ this.concurrency = concurrency;
54
+ }
55
+
56
+ /**
57
+ * Validates that observability implements ObservabilityPort.
58
+ * @private
59
+ * @param {*} observability
60
+ */
61
+ static _validateObservability(observability) {
62
+ if (
63
+ !observability ||
64
+ typeof observability.metric !== 'function' ||
65
+ typeof observability.log !== 'function' ||
66
+ typeof observability.span !== 'function'
67
+ ) {
68
+ throw new Error('observability must implement ObservabilityPort');
69
+ }
52
70
  }
53
71
 
54
72
  /**
@@ -62,76 +80,65 @@ export default class CasService extends EventEmitter {
62
80
  }
63
81
 
64
82
  /**
65
- * Stores a single buffer chunk in Git and appends its metadata to the manifest.
83
+ * Stores a single buffer chunk in Git, returning its metadata.
66
84
  * @private
67
85
  * @param {Buffer} buf - The chunk data to store.
68
- * @param {Object} manifestData - Mutable manifest accumulator.
86
+ * @param {number} index - Chunk index.
87
+ * @returns {Promise<{ index: number, size: number, digest: string, blob: string }>}
69
88
  */
70
- async _storeChunk(buf, manifestData) {
89
+ async _storeChunk(buf, index) {
71
90
  const digest = await this._sha256(buf);
72
91
  const blob = await this.persistence.writeBlob(buf);
73
- const entry = { index: manifestData.chunks.length, size: buf.length, digest, blob };
74
- manifestData.chunks.push(entry);
75
- manifestData.size += buf.length;
76
- this.emit('chunk:stored', { index: entry.index, size: entry.size, digest, blob });
92
+ this.observability.metric('chunk', { action: 'stored', index, size: buf.length, digest, blob });
93
+ return { index, size: buf.length, digest, blob };
77
94
  }
78
95
 
79
96
  /**
80
- * Reads an async iterable source, splits it into fixed-size chunks, and stores each in Git.
97
+ * Reads an async iterable source, splits it into chunks via the configured
98
+ * chunker, and stores each chunk in Git.
81
99
  * @private
82
100
  * @param {AsyncIterable<Buffer>} source - The data source to chunk.
83
101
  * @param {Object} manifestData - Mutable manifest accumulator.
84
102
  * @throws {CasError} STREAM_ERROR if the source stream fails.
85
103
  */
86
104
  async _chunkAndStore(source, manifestData) {
87
- let buffer = Buffer.alloc(0);
105
+ const sem = new Semaphore(this.concurrency);
106
+ const pending = [];
107
+ let nextIndex = 0;
108
+
109
+ const launchWrite = (buf, idx) => {
110
+ const p = sem.acquire().then(async () => {
111
+ try {
112
+ return await this._storeChunk(buf, idx);
113
+ } finally {
114
+ sem.release();
115
+ }
116
+ });
117
+ pending.push(p);
118
+ };
88
119
 
89
120
  try {
90
- for await (const chunk of source) {
91
- buffer = Buffer.concat([buffer, chunk]);
92
- while (buffer.length >= this.chunkSize) {
93
- await this._storeChunk(buffer.slice(0, this.chunkSize), manifestData);
94
- buffer = buffer.slice(this.chunkSize);
95
- }
121
+ for await (const chunk of this.chunker.chunk(source)) {
122
+ launchWrite(chunk, nextIndex++);
96
123
  }
97
124
  } catch (err) {
125
+ await Promise.allSettled(pending);
98
126
  if (err instanceof CasError) { throw err; }
99
127
  const casErr = new CasError(
100
128
  `Stream error during store: ${err.message}`,
101
129
  'STREAM_ERROR',
102
- { chunksWritten: manifestData.chunks.length, originalError: err },
130
+ { chunksDispatched: nextIndex, originalError: err },
103
131
  );
104
- if (this.listenerCount('error') > 0) {
105
- this.emit('error', { code: casErr.code, message: casErr.message });
106
- }
132
+ await Promise.allSettled(pending);
133
+ this.observability.metric('error', { code: casErr.code, message: casErr.message });
107
134
  throw casErr;
108
135
  }
109
136
 
110
- if (buffer.length > 0) {
111
- await this._storeChunk(buffer, manifestData);
112
- }
113
- }
114
-
115
- /**
116
- * Validates that an encryption key is a 32-byte Buffer or Uint8Array.
117
- * @private
118
- * @param {*} key
119
- * @throws {CasError} INVALID_KEY_TYPE if key is not a Buffer
120
- * @throws {CasError} INVALID_KEY_LENGTH if key is not 32 bytes
121
- */
122
- _validateKey(key) {
123
- if (!Buffer.isBuffer(key) && !(key instanceof Uint8Array)) {
124
- throw new CasError(
125
- 'Encryption key must be a Buffer or Uint8Array',
126
- 'INVALID_KEY_TYPE',
127
- );
128
- }
129
- if (key.length !== 32) {
130
- throw new CasError(
131
- `Encryption key must be 32 bytes, got ${key.length}`,
132
- 'INVALID_KEY_LENGTH',
133
- { expected: 32, actual: key.length },
134
- );
137
+ const results = await Promise.all(pending);
138
+ results.sort((a, b) => a.index - b.index);
139
+ for (const entry of results) {
140
+ manifestData.chunks.push(entry);
141
+ manifestData.size += entry.size;
135
142
  }
136
143
  }
137
144
 
@@ -144,7 +151,6 @@ export default class CasService extends EventEmitter {
144
151
  * @throws {CasError} INVALID_KEY_TYPE | INVALID_KEY_LENGTH if the key is invalid.
145
152
  */
146
153
  async encrypt({ buffer, key }) {
147
- this._validateKey(key);
148
154
  return await this.crypto.encryptBuffer(buffer, key);
149
155
  }
150
156
 
@@ -210,6 +216,24 @@ export default class CasService extends EventEmitter {
210
216
  }
211
217
  }
212
218
 
219
+ /**
220
+ * Validates that a chunking strategy is recognized.
221
+ * @param {Object} [chunking] - Chunking options from a manifest.
222
+ * @throws {CasError} INVALID_CHUNKING_STRATEGY if the strategy is unrecognized.
223
+ * @private
224
+ */
225
+ _validateChunking(chunking) {
226
+ if (!chunking) { return; }
227
+ const validStrategies = ['fixed', 'cdc'];
228
+ if (!validStrategies.includes(chunking.strategy)) {
229
+ throw new CasError(
230
+ `Unsupported chunking strategy: ${chunking.strategy}`,
231
+ 'INVALID_CHUNKING_STRATEGY',
232
+ { strategy: chunking.strategy },
233
+ );
234
+ }
235
+ }
236
+
213
237
  /**
214
238
  * Chunks an async iterable source and stores it in Git.
215
239
  *
@@ -238,11 +262,19 @@ export default class CasService extends EventEmitter {
238
262
  }
239
263
 
240
264
  if (encryptionKey) {
241
- this._validateKey(encryptionKey);
265
+ this.crypto._validateKey(encryptionKey);
242
266
  }
243
267
 
244
268
  const manifestData = { slug, filename, size: 0, chunks: [] };
245
269
 
270
+ // Record chunking metadata for non-default strategies
271
+ if (this.chunker.strategy !== 'fixed') {
272
+ manifestData.chunking = {
273
+ strategy: this.chunker.strategy,
274
+ params: this.chunker.params,
275
+ };
276
+ }
277
+
246
278
  let processedSource = source;
247
279
  if (compression) {
248
280
  processedSource = this._compressStream(processedSource);
@@ -262,8 +294,8 @@ export default class CasService extends EventEmitter {
262
294
  }
263
295
 
264
296
  const manifest = new Manifest(manifestData);
265
- this.emit('file:stored', {
266
- slug, size: manifest.size, chunkCount: manifest.chunks.length, encrypted: !!encryptionKey,
297
+ this.observability.metric('file', {
298
+ action: 'stored', slug, size: manifest.size, chunkCount: manifest.chunks.length, encrypted: !!encryptionKey,
267
299
  });
268
300
  return manifest;
269
301
  }
@@ -366,13 +398,11 @@ export default class CasService extends EventEmitter {
366
398
  'INTEGRITY_ERROR',
367
399
  { chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
368
400
  );
369
- if (this.listenerCount('error') > 0) {
370
- this.emit('error', { code: err.code, message: err.message });
371
- }
401
+ this.observability.metric('error', { code: err.code, message: err.message });
372
402
  throw err;
373
403
  }
374
404
  buffers.push(blob);
375
- this.emit('chunk:restored', { index: chunk.index, size: blob.length, digest: chunk.digest });
405
+ this.observability.metric('chunk', { action: 'restored', index: chunk.index, size: blob.length, digest: chunk.digest });
376
406
  }
377
407
  return buffers;
378
408
  }
@@ -414,7 +444,7 @@ export default class CasService extends EventEmitter {
414
444
  );
415
445
  }
416
446
  if (encryptionKey) {
417
- this._validateKey(encryptionKey);
447
+ this.crypto._validateKey(encryptionKey);
418
448
  } else if (manifest.encryption?.encrypted) {
419
449
  throw new CasError('Encryption key required to restore encrypted content', 'MISSING_KEY');
420
450
  }
@@ -436,12 +466,56 @@ export default class CasService extends EventEmitter {
436
466
  * @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
437
467
  */
438
468
  async restore({ manifest, encryptionKey, passphrase }) {
469
+ const chunks = [];
470
+ for await (const chunk of this.restoreStream({ manifest, encryptionKey, passphrase })) {
471
+ chunks.push(chunk);
472
+ }
473
+ const buffer = Buffer.concat(chunks);
474
+ return { buffer, bytesWritten: buffer.length };
475
+ }
476
+
477
+ /**
478
+ * Restores a file from its manifest as an async iterable of Buffer chunks.
479
+ *
480
+ * For unencrypted, uncompressed files this is true per-chunk streaming
481
+ * with O(chunkSize) memory. For encrypted or compressed files, all chunks
482
+ * are buffered internally for decryption/decompression, then yielded.
483
+ *
484
+ * @param {Object} options
485
+ * @param {import('../value-objects/Manifest.js').default} options.manifest - The file manifest.
486
+ * @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
487
+ * @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
488
+ * Note: For unencrypted files, each yielded buffer corresponds to an original
489
+ * stored chunk. For encrypted/compressed files, yielded buffers are
490
+ * chunkSize-sliced pieces of the decrypted/decompressed result and may not
491
+ * correspond 1:1 to the original chunks.
492
+ *
493
+ * @yields {Buffer}
494
+ * @throws {CasError} MISSING_KEY if manifest is encrypted but no key is provided.
495
+ * @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
496
+ */
497
+ async *restoreStream({ manifest, encryptionKey, passphrase }) {
439
498
  const key = await this._resolveEncryptionKey(manifest, encryptionKey, passphrase);
440
499
 
441
500
  if (manifest.chunks.length === 0) {
442
- return { buffer: Buffer.alloc(0), bytesWritten: 0 };
501
+ this.observability.metric('file', {
502
+ action: 'restored', slug: manifest.slug, size: 0, chunkCount: 0,
503
+ });
504
+ return;
505
+ }
506
+
507
+ if (manifest.encryption?.encrypted || manifest.compression) {
508
+ yield* this._restoreBuffered(manifest, key);
509
+ } else {
510
+ yield* this._restoreStreaming(manifest);
443
511
  }
512
+ }
444
513
 
514
+ /**
515
+ * Buffered restore path for encrypted/compressed manifests.
516
+ * @private
517
+ */
518
+ async *_restoreBuffered(manifest, key) {
445
519
  let buffer = Buffer.concat(await this._readAndVerifyChunks(manifest.chunks));
446
520
 
447
521
  if (manifest.encryption?.encrypted) {
@@ -449,18 +523,78 @@ export default class CasService extends EventEmitter {
449
523
  }
450
524
 
451
525
  if (manifest.compression) {
452
- try {
453
- buffer = await gunzipAsync(buffer);
454
- } catch (err) {
455
- if (err instanceof CasError) { throw err; }
456
- throw new CasError(`Decompression failed: ${err.message}`, 'INTEGRITY_ERROR', { originalError: err });
526
+ buffer = await this._decompress(buffer);
527
+ }
528
+
529
+ this.observability.metric('file', {
530
+ action: 'restored', slug: manifest.slug, size: buffer.length, chunkCount: manifest.chunks.length,
531
+ });
532
+
533
+ for (let offset = 0; offset < buffer.length; offset += this.chunkSize) {
534
+ yield buffer.subarray(offset, offset + this.chunkSize);
535
+ }
536
+ }
537
+
538
+ /**
539
+ * Per-chunk streaming restore with read-ahead.
540
+ * @private
541
+ */
542
+ async *_restoreStreaming(manifest) {
543
+ const chunks = manifest.chunks;
544
+ const readAhead = this.concurrency;
545
+ let totalSize = 0;
546
+
547
+ const readAndVerify = async (chunk) => {
548
+ const blob = await this.persistence.readBlob(chunk.blob);
549
+ const digest = await this._sha256(blob);
550
+ if (digest !== chunk.digest) {
551
+ const err = new CasError(
552
+ `Chunk ${chunk.index} integrity check failed`,
553
+ 'INTEGRITY_ERROR',
554
+ { chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
555
+ );
556
+ this.observability.metric('error', { code: err.code, message: err.message });
557
+ throw err;
558
+ }
559
+ return blob;
560
+ };
561
+
562
+ const ahead = [];
563
+ for (let i = 0; i < Math.min(readAhead, chunks.length); i++) {
564
+ ahead.push(readAndVerify(chunks[i]));
565
+ }
566
+
567
+ try {
568
+ for (let i = 0; i < chunks.length; i++) {
569
+ const blob = await ahead[i % readAhead];
570
+ this.observability.metric('chunk', { action: 'restored', index: chunks[i].index, size: blob.length, digest: chunks[i].digest });
571
+ totalSize += blob.length;
572
+ const nextIdx = i + readAhead;
573
+ if (nextIdx < chunks.length) {
574
+ ahead[i % readAhead] = readAndVerify(chunks[nextIdx]);
575
+ }
576
+ yield blob;
457
577
  }
578
+ } finally {
579
+ await Promise.allSettled(ahead);
458
580
  }
459
581
 
460
- this.emit('file:restored', {
461
- slug: manifest.slug, size: buffer.length, chunkCount: manifest.chunks.length,
582
+ this.observability.metric('file', {
583
+ action: 'restored', slug: manifest.slug, size: totalSize, chunkCount: chunks.length,
462
584
  });
463
- return { buffer, bytesWritten: buffer.length };
585
+ }
586
+
587
+ /**
588
+ * Decompresses a gzip buffer.
589
+ * @private
590
+ */
591
+ async _decompress(buffer) {
592
+ try {
593
+ return await gunzipAsync(buffer);
594
+ } catch (err) {
595
+ if (err instanceof CasError) { throw err; }
596
+ throw new CasError(`Decompression failed: ${err.message}`, 'INTEGRITY_ERROR', { originalError: err });
597
+ }
464
598
  }
465
599
 
466
600
  /**
@@ -619,13 +753,13 @@ export default class CasService extends EventEmitter {
619
753
  const blob = await this.persistence.readBlob(chunk.blob);
620
754
  const digest = await this._sha256(blob);
621
755
  if (digest !== chunk.digest) {
622
- this.emit('integrity:fail', {
623
- slug: manifest.slug, chunkIndex: chunk.index, expected: chunk.digest, actual: digest,
756
+ this.observability.metric('integrity', {
757
+ action: 'fail', slug: manifest.slug, chunkIndex: chunk.index, expected: chunk.digest, actual: digest,
624
758
  });
625
759
  return false;
626
760
  }
627
761
  }
628
- this.emit('integrity:pass', { slug: manifest.slug });
762
+ this.observability.metric('integrity', { action: 'pass', slug: manifest.slug });
629
763
  return true;
630
764
  }
631
765
  }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Counting semaphore for limiting concurrency.
3
+ */
4
+ export default class Semaphore {
5
+ #max;
6
+ #active = 0;
7
+ #queue = [];
8
+
9
+ /**
10
+ * @param {number} concurrency - Maximum concurrent permits.
11
+ */
12
+ constructor(concurrency) {
13
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
14
+ throw new Error('Semaphore concurrency must be a positive integer');
15
+ }
16
+ this.#max = concurrency;
17
+ }
18
+
19
+ /**
20
+ * Acquire a permit, waiting if necessary.
21
+ * @returns {Promise<void>}
22
+ */
23
+ acquire() {
24
+ if (this.#active < this.#max) {
25
+ this.#active++;
26
+ return Promise.resolve();
27
+ }
28
+ return new Promise((resolve) => {
29
+ this.#queue.push(resolve);
30
+ });
31
+ }
32
+
33
+ /**
34
+ * Release a permit.
35
+ */
36
+ release() {
37
+ if (this.#queue.length > 0) {
38
+ const next = this.#queue.shift();
39
+ next();
40
+ } else {
41
+ if (this.#active === 0) {
42
+ throw new Error('Semaphore release called without an active permit');
43
+ }
44
+ this.#active--;
45
+ }
46
+ }
47
+ }
@@ -29,6 +29,9 @@ export default class Manifest {
29
29
  this.chunks = data.chunks.map((c) => new Chunk(c));
30
30
  this.encryption = data.encryption ? { ...data.encryption } : undefined;
31
31
  this.compression = data.compression ? { ...data.compression } : undefined;
32
+ this.chunking = data.chunking
33
+ ? { strategy: data.chunking.strategy, params: { ...data.chunking.params } }
34
+ : undefined;
32
35
  this.subManifests = data.subManifests ? data.subManifests.map((s) => ({ ...s })) : undefined;
33
36
  Object.freeze(this);
34
37
  } catch (error) {
@@ -52,6 +55,7 @@ export default class Manifest {
52
55
  chunks: this.chunks,
53
56
  encryption: this.encryption,
54
57
  compression: this.compression,
58
+ chunking: this.chunking,
55
59
  subManifests: this.subManifests,
56
60
  };
57
61
  }
@@ -27,20 +27,20 @@ export default class BunCryptoAdapter extends CryptoPort {
27
27
 
28
28
  /** @override */
29
29
  async encryptBuffer(buffer, key) {
30
- this.#validateKey(key);
30
+ this._validateKey(key);
31
31
  const nonce = this.randomBytes(12);
32
32
  const cipher = createCipheriv('aes-256-gcm', key, nonce);
33
33
  const enc = Buffer.concat([cipher.update(buffer), cipher.final()]);
34
34
  const tag = cipher.getAuthTag();
35
35
  return {
36
36
  buf: enc,
37
- meta: this.#buildMeta(nonce, tag),
37
+ meta: this._buildMeta(nonce.toString('base64'), tag.toString('base64')),
38
38
  };
39
39
  }
40
40
 
41
41
  /** @override */
42
42
  async decryptBuffer(buffer, key, meta) {
43
- this.#validateKey(key);
43
+ this._validateKey(key);
44
44
  const nonce = Buffer.from(meta.nonce, 'base64');
45
45
  const tag = Buffer.from(meta.tag, 'base64');
46
46
  const decipher = createDecipheriv('aes-256-gcm', key, nonce);
@@ -50,7 +50,7 @@ export default class BunCryptoAdapter extends CryptoPort {
50
50
 
51
51
  /** @override */
52
52
  createEncryptionStream(key) {
53
- this.#validateKey(key);
53
+ this._validateKey(key);
54
54
  const nonce = this.randomBytes(12);
55
55
  const cipher = createCipheriv('aes-256-gcm', key, nonce);
56
56
  let streamFinalized = false;
@@ -77,77 +77,21 @@ export default class BunCryptoAdapter extends CryptoPort {
77
77
  );
78
78
  }
79
79
  const tag = cipher.getAuthTag();
80
- return this.#buildMeta(nonce, tag);
80
+ return this._buildMeta(nonce.toString('base64'), tag.toString('base64'));
81
81
  };
82
82
 
83
83
  return { encrypt, finalize };
84
84
  }
85
85
 
86
86
  /** @override */
87
- async deriveKey({
88
- passphrase,
89
- salt,
90
- algorithm = 'pbkdf2',
91
- iterations = 100_000,
92
- cost = 16384,
93
- blockSize = 8,
94
- parallelization = 1,
95
- keyLength = 32,
96
- }) {
97
- const saltBuf = salt || this.randomBytes(32);
98
- let key;
99
- const params = { algorithm, salt: Buffer.from(saltBuf).toString('base64'), keyLength };
100
-
87
+ async _doDeriveKey(passphrase, saltBuf, { algorithm, iterations, cost, blockSize, parallelization, keyLength }) {
101
88
  if (algorithm === 'pbkdf2') {
102
- key = await promisify(pbkdf2)(passphrase, saltBuf, iterations, keyLength, 'sha512');
103
- params.iterations = iterations;
104
- } else if (algorithm === 'scrypt') {
105
- key = await promisify(scrypt)(passphrase, saltBuf, keyLength, {
106
- N: cost, r: blockSize, p: parallelization,
107
- });
108
- params.cost = cost;
109
- params.blockSize = blockSize;
110
- params.parallelization = parallelization;
111
- } else {
112
- throw new Error(`Unsupported KDF algorithm: ${algorithm}`);
113
- }
114
-
115
- return { key, salt: Buffer.from(saltBuf), params };
116
- }
117
-
118
- /**
119
- * Validates that a key is a 32-byte Buffer or Uint8Array.
120
- * @param {Buffer|Uint8Array} key
121
- * @throws {CasError} INVALID_KEY_TYPE | INVALID_KEY_LENGTH
122
- */
123
- #validateKey(key) {
124
- if (!Buffer.isBuffer(key) && !(key instanceof Uint8Array)) {
125
- throw new CasError(
126
- 'Encryption key must be a Buffer or Uint8Array',
127
- 'INVALID_KEY_TYPE',
128
- );
89
+ return promisify(pbkdf2)(passphrase, saltBuf, iterations, keyLength, 'sha512');
129
90
  }
130
- if (key.length !== 32) {
131
- throw new CasError(
132
- `Encryption key must be 32 bytes, got ${key.length}`,
133
- 'INVALID_KEY_LENGTH',
134
- { expected: 32, actual: key.length },
135
- );
136
- }
137
- }
138
-
139
- /**
140
- * Builds the encryption metadata object.
141
- * @param {Buffer|Uint8Array} nonce - 12-byte AES-GCM nonce.
142
- * @param {Buffer} tag - 16-byte GCM authentication tag.
143
- * @returns {{ algorithm: string, nonce: string, tag: string, encrypted: boolean }}
144
- */
145
- #buildMeta(nonce, tag) {
146
- return {
147
- algorithm: 'aes-256-gcm',
148
- nonce: Buffer.from(nonce).toString('base64'),
149
- tag: tag.toString('base64'),
150
- encrypted: true,
151
- };
91
+ return promisify(scrypt)(passphrase, saltBuf, keyLength, {
92
+ N: cost,
93
+ r: blockSize,
94
+ p: parallelization,
95
+ });
152
96
  }
153
97
  }