@git-stunts/git-cas 3.1.0 → 4.0.1

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.
@@ -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
  }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Observability adapter that bridges metrics to an EventEmitter.
3
+ *
4
+ * Maps `metric('chunk', { action: 'stored', ... })` → `emit('chunk:stored', ...)`.
5
+ * Exposes `.on()`, `.removeListener()`, `.listenerCount()` for backward compatibility
6
+ * with code that previously subscribed directly to CasService events.
7
+ */
8
+ import { EventEmitter } from 'node:events';
9
+
10
+ export default class EventEmitterObserver {
11
+ #emitter = new EventEmitter();
12
+
13
+ /**
14
+ * Route a metric to the underlying EventEmitter.
15
+ *
16
+ * Error metrics are only emitted when listeners are attached (matching
17
+ * the previous CasService behavior that guarded `this.emit('error', ...)`).
18
+ *
19
+ * @param {string} channel
20
+ * @param {Object} data - Must include `action` to form the event name.
21
+ */
22
+ metric(channel, data) {
23
+ if (channel === 'error') {
24
+ if (this.#emitter.listenerCount('error') > 0) {
25
+ this.#emitter.emit('error', data);
26
+ }
27
+ return;
28
+ }
29
+ const eventName = `${channel}:${data.action}`;
30
+ const payload = Object.fromEntries(Object.entries(data).filter(([k]) => k !== 'action'));
31
+ this.#emitter.emit(eventName, payload);
32
+ }
33
+
34
+ log(_level, _msg, _meta) {}
35
+
36
+ span(_name) {
37
+ return { end() {} };
38
+ }
39
+
40
+ /**
41
+ * Subscribe to an event.
42
+ * @param {string} event
43
+ * @param {Function} listener
44
+ * @returns {this}
45
+ */
46
+ on(event, listener) {
47
+ this.#emitter.on(event, listener);
48
+ return this;
49
+ }
50
+
51
+ /**
52
+ * Remove a listener.
53
+ * @param {string} event
54
+ * @param {Function} listener
55
+ * @returns {this}
56
+ */
57
+ removeListener(event, listener) {
58
+ this.#emitter.removeListener(event, listener);
59
+ return this;
60
+ }
61
+
62
+ /**
63
+ * Return the number of listeners for an event.
64
+ * @param {string} event
65
+ * @returns {number}
66
+ */
67
+ listenerCount(event) {
68
+ return this.#emitter.listenerCount(event);
69
+ }
70
+ }
@@ -1,7 +1,6 @@
1
1
  import { createHash, createCipheriv, createDecipheriv, randomBytes, pbkdf2, scrypt } from 'node:crypto';
2
2
  import { promisify } from 'node:util';
3
3
  import CryptoPort from '../../ports/CryptoPort.js';
4
- import CasError from '../../domain/errors/CasError.js';
5
4
 
6
5
  /**
7
6
  * Node.js implementation of CryptoPort using node:crypto.
@@ -19,14 +18,14 @@ export default class NodeCryptoAdapter extends CryptoPort {
19
18
 
20
19
  /** @override */
21
20
  encryptBuffer(buffer, key) {
22
- this.#validateKey(key);
21
+ this._validateKey(key);
23
22
  const nonce = randomBytes(12);
24
23
  const cipher = createCipheriv('aes-256-gcm', key, nonce);
25
24
  const enc = Buffer.concat([cipher.update(buffer), cipher.final()]);
26
25
  const tag = cipher.getAuthTag();
27
26
  return {
28
27
  buf: enc,
29
- meta: this.#buildMeta(nonce, tag),
28
+ meta: this._buildMeta(nonce.toString('base64'), tag.toString('base64')),
30
29
  };
31
30
  }
32
31
 
@@ -41,7 +40,7 @@ export default class NodeCryptoAdapter extends CryptoPort {
41
40
 
42
41
  /** @override */
43
42
  createEncryptionStream(key) {
44
- this.#validateKey(key);
43
+ this._validateKey(key);
45
44
  const nonce = randomBytes(12);
46
45
  const cipher = createCipheriv('aes-256-gcm', key, nonce);
47
46
 
@@ -60,83 +59,21 @@ export default class NodeCryptoAdapter extends CryptoPort {
60
59
 
61
60
  const finalize = () => {
62
61
  const tag = cipher.getAuthTag();
63
- return this.#buildMeta(nonce, tag);
62
+ return this._buildMeta(nonce.toString('base64'), tag.toString('base64'));
64
63
  };
65
64
 
66
65
  return { encrypt, finalize };
67
66
  }
68
67
 
69
68
  /** @override */
70
- async deriveKey({
71
- passphrase,
72
- salt,
73
- algorithm = 'pbkdf2',
74
- iterations = 100_000,
75
- cost = 16384,
76
- blockSize = 8,
77
- parallelization = 1,
78
- keyLength = 32,
79
- }) {
80
- const saltBuf = salt || randomBytes(32);
81
- let key;
82
- const params = {
83
- algorithm,
84
- salt: Buffer.from(saltBuf).toString('base64'),
85
- keyLength,
86
- };
87
-
69
+ async _doDeriveKey(passphrase, saltBuf, { algorithm, iterations, cost, blockSize, parallelization, keyLength }) {
88
70
  if (algorithm === 'pbkdf2') {
89
- key = await promisify(pbkdf2)(passphrase, saltBuf, iterations, keyLength, 'sha512');
90
- params.iterations = iterations;
91
- } else if (algorithm === 'scrypt') {
92
- key = await promisify(scrypt)(passphrase, saltBuf, keyLength, {
93
- N: cost,
94
- r: blockSize,
95
- p: parallelization,
96
- });
97
- params.cost = cost;
98
- params.blockSize = blockSize;
99
- params.parallelization = parallelization;
100
- } else {
101
- throw new Error(`Unsupported KDF algorithm: ${algorithm}`);
102
- }
103
-
104
- return { key, salt: Buffer.from(saltBuf), params };
105
- }
106
-
107
- /**
108
- * Validates that a key is a 32-byte Buffer.
109
- * @param {Buffer} key
110
- * @throws {CasError} INVALID_KEY_TYPE | INVALID_KEY_LENGTH
111
- */
112
- #validateKey(key) {
113
- if (!Buffer.isBuffer(key)) {
114
- throw new CasError(
115
- 'Encryption key must be a Buffer',
116
- 'INVALID_KEY_TYPE',
117
- );
71
+ return await promisify(pbkdf2)(passphrase, saltBuf, iterations, keyLength, 'sha512');
118
72
  }
119
- if (key.length !== 32) {
120
- throw new CasError(
121
- `Encryption key must be 32 bytes, got ${key.length}`,
122
- 'INVALID_KEY_LENGTH',
123
- { expected: 32, actual: key.length },
124
- );
125
- }
126
- }
127
-
128
- /**
129
- * Builds the encryption metadata object.
130
- * @param {Buffer} nonce - 12-byte AES-GCM nonce.
131
- * @param {Buffer} tag - 16-byte GCM authentication tag.
132
- * @returns {{ algorithm: string, nonce: string, tag: string, encrypted: boolean }}
133
- */
134
- #buildMeta(nonce, tag) {
135
- return {
136
- algorithm: 'aes-256-gcm',
137
- nonce: nonce.toString('base64'),
138
- tag: tag.toString('base64'),
139
- encrypted: true,
140
- };
73
+ return await promisify(scrypt)(passphrase, saltBuf, keyLength, {
74
+ N: cost,
75
+ r: blockSize,
76
+ p: parallelization,
77
+ });
141
78
  }
142
79
  }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * No-op observability adapter. All methods are empty.
3
+ * Used as the default when no observability is configured.
4
+ */
5
+ export default class SilentObserver {
6
+ metric(_channel, _data) {}
7
+ log(_level, _msg, _meta) {}
8
+ span(_name) {
9
+ return { end() {} };
10
+ }
11
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Observability adapter that accumulates metrics for later retrieval.
3
+ */
4
+ export default class StatsCollector {
5
+ #chunksProcessed = 0;
6
+ #bytesTotal = 0;
7
+ #errors = 0;
8
+ #startTime = null;
9
+
10
+ metric(channel, data) {
11
+ if (!this.#startTime) {
12
+ this.#startTime = Date.now();
13
+ }
14
+ if (channel === 'chunk') {
15
+ this.#chunksProcessed++;
16
+ const size = Number.isFinite(data?.size) ? data.size : 0;
17
+ this.#bytesTotal += size;
18
+ }
19
+ if (channel === 'error') {
20
+ this.#errors++;
21
+ }
22
+ }
23
+
24
+ log(_level, _msg, _meta) {}
25
+
26
+ span(_name) {
27
+ return { end() {} };
28
+ }
29
+
30
+ /**
31
+ * Returns accumulated statistics.
32
+ * @returns {{ chunksProcessed: number, bytesTotal: number, elapsed: number, throughput: number, errors: number }}
33
+ */
34
+ summary() {
35
+ const elapsed = this.#startTime ? (Date.now() - this.#startTime) / 1000 : 0;
36
+ const throughput = elapsed > 0 ? this.#bytesTotal / elapsed : 0;
37
+ return {
38
+ chunksProcessed: this.#chunksProcessed,
39
+ bytesTotal: this.#bytesTotal,
40
+ elapsed,
41
+ throughput,
42
+ errors: this.#errors,
43
+ };
44
+ }
45
+ }
@@ -28,10 +28,10 @@ export default class WebCryptoAdapter extends CryptoPort {
28
28
 
29
29
  /** @override */
30
30
  async encryptBuffer(buffer, key) {
31
- this.#validateKey(key);
31
+ this._validateKey(key);
32
32
  const nonce = this.randomBytes(12);
33
33
  const cryptoKey = await this.#importKey(key);
34
-
34
+
35
35
  // AES-GCM in Web Crypto includes the tag at the end of the ciphertext
36
36
  const encrypted = await globalThis.crypto.subtle.encrypt(
37
37
  { name: 'AES-GCM', iv: nonce },
@@ -46,7 +46,7 @@ export default class WebCryptoAdapter extends CryptoPort {
46
46
 
47
47
  return {
48
48
  buf: Buffer.from(ciphertext),
49
- meta: this.#buildMeta(nonce, tag),
49
+ meta: this._buildMeta(this.#toBase64(nonce), this.#toBase64(tag)),
50
50
  };
51
51
  }
52
52
 
@@ -75,25 +75,23 @@ export default class WebCryptoAdapter extends CryptoPort {
75
75
 
76
76
  /** @override */
77
77
  createEncryptionStream(key) {
78
- this.#validateKey(key);
78
+ this._validateKey(key);
79
79
  const nonce = this.randomBytes(12);
80
80
  const cryptoKeyPromise = this.#importKey(key);
81
-
81
+
82
82
  // Web Crypto doesn't have a native streaming AES-GCM API like Node
83
83
  // We have to buffer for the one-shot call because GCM tag is computed over the whole thing.
84
- // NOTE: This limits the "stream" to memory capacity, matching the project's
84
+ // NOTE: This limits the "stream" to memory capacity, matching the project's
85
85
  // current CasService.restore limitation.
86
86
  const chunks = [];
87
87
  let finalTag = null;
88
+ let streamConsumed = false;
88
89
 
89
90
  const encrypt = async function* (source) {
90
91
  for await (const chunk of source) {
91
92
  chunks.push(chunk);
92
- // We can't yield partial encrypted chunks for GCM in Web Crypto
93
- // without complex chunk-chaining which would break compatibility
94
- // with the Node adapter's single-stream GCM.
95
93
  }
96
-
94
+
97
95
  const buffer = Buffer.concat(chunks);
98
96
  const cryptoKey = await cryptoKeyPromise;
99
97
  const encrypted = await globalThis.crypto.subtle.encrypt(
@@ -106,58 +104,45 @@ export default class WebCryptoAdapter extends CryptoPort {
106
104
  const tagLength = 16;
107
105
  const ciphertext = fullBuffer.slice(0, -tagLength);
108
106
  finalTag = fullBuffer.slice(-tagLength);
107
+ streamConsumed = true;
109
108
 
110
109
  yield Buffer.from(ciphertext);
111
110
  };
112
111
 
113
112
  const finalize = () => {
114
- return this.#buildMeta(nonce, finalTag);
113
+ if (!streamConsumed) {
114
+ throw new CasError(
115
+ 'Cannot finalize before the encrypt stream is fully consumed',
116
+ 'STREAM_NOT_CONSUMED',
117
+ );
118
+ }
119
+ return this._buildMeta(this.#toBase64(nonce), this.#toBase64(finalTag));
115
120
  };
116
121
 
117
122
  return { encrypt, finalize };
118
123
  }
119
124
 
120
125
  /** @override */
121
- async deriveKey({
122
- passphrase,
123
- salt,
124
- algorithm = 'pbkdf2',
125
- iterations = 100_000,
126
- cost = 16384,
127
- blockSize = 8,
128
- parallelization = 1,
129
- keyLength = 32,
130
- }) {
131
- const saltBuf = salt || this.randomBytes(32);
132
- const params = { algorithm, salt: this.#toBase64(saltBuf), keyLength };
133
-
134
- const opts = { passphrase, saltBuf, iterations, cost, blockSize, parallelization, keyLength, params };
135
- let key;
126
+ async _doDeriveKey(passphrase, saltBuf, { algorithm, iterations, cost, blockSize, parallelization, keyLength }) {
136
127
  if (algorithm === 'pbkdf2') {
137
- key = await this.#derivePbkdf2(opts);
138
- } else if (algorithm === 'scrypt') {
139
- key = await this.#deriveScrypt(opts);
140
- } else {
141
- throw new Error(`Unsupported KDF algorithm: ${algorithm}`);
128
+ return this.#derivePbkdf2(passphrase, saltBuf, { iterations, keyLength });
142
129
  }
143
-
144
- return { key: Buffer.from(key), salt: Buffer.from(saltBuf), params };
130
+ return this.#deriveScrypt(passphrase, saltBuf, { cost, blockSize, parallelization, keyLength });
145
131
  }
146
132
 
147
- async #derivePbkdf2({ passphrase, saltBuf, iterations, keyLength, params }) {
133
+ async #derivePbkdf2(passphrase, saltBuf, params) {
148
134
  const enc = new globalThis.TextEncoder();
149
135
  const baseKey = await globalThis.crypto.subtle.importKey(
150
136
  'raw', enc.encode(passphrase), 'PBKDF2', false, ['deriveBits'],
151
137
  );
152
138
  const bits = await globalThis.crypto.subtle.deriveBits(
153
- { name: 'PBKDF2', salt: saltBuf, iterations, hash: 'SHA-512' },
154
- baseKey, keyLength * 8,
139
+ { name: 'PBKDF2', salt: saltBuf, iterations: params.iterations, hash: 'SHA-512' },
140
+ baseKey, params.keyLength * 8,
155
141
  );
156
- params.iterations = iterations;
157
142
  return Buffer.from(bits);
158
143
  }
159
144
 
160
- async #deriveScrypt({ passphrase, saltBuf, cost, blockSize, parallelization, keyLength, params }) {
145
+ async #deriveScrypt(passphrase, saltBuf, params) {
161
146
  let scryptCb;
162
147
  let promisifyFn;
163
148
  try {
@@ -166,13 +151,9 @@ export default class WebCryptoAdapter extends CryptoPort {
166
151
  } catch {
167
152
  throw new Error('scrypt KDF requires a Node.js-compatible runtime (node:crypto unavailable)');
168
153
  }
169
- const key = await promisifyFn(scryptCb)(passphrase, saltBuf, keyLength, {
170
- N: cost, r: blockSize, p: parallelization,
154
+ return promisifyFn(scryptCb)(passphrase, saltBuf, params.keyLength, {
155
+ N: params.cost, r: params.blockSize, p: params.parallelization,
171
156
  });
172
- params.cost = cost;
173
- params.blockSize = blockSize;
174
- params.parallelization = parallelization;
175
- return key;
176
157
  }
177
158
 
178
159
  /**
@@ -190,42 +171,6 @@ export default class WebCryptoAdapter extends CryptoPort {
190
171
  );
191
172
  }
192
173
 
193
- /**
194
- * Validates that a key is a 32-byte Buffer or Uint8Array.
195
- * @param {Buffer|Uint8Array} key
196
- * @throws {CasError} INVALID_KEY_TYPE | INVALID_KEY_LENGTH
197
- */
198
- #validateKey(key) {
199
- if (!globalThis.Buffer?.isBuffer(key) && !(key instanceof Uint8Array)) {
200
- throw new CasError(
201
- 'Encryption key must be a Buffer or Uint8Array',
202
- 'INVALID_KEY_TYPE',
203
- );
204
- }
205
- if (key.length !== 32) {
206
- throw new CasError(
207
- `Encryption key must be 32 bytes, got ${key.length}`,
208
- 'INVALID_KEY_LENGTH',
209
- { expected: 32, actual: key.length },
210
- );
211
- }
212
- }
213
-
214
- /**
215
- * Builds the encryption metadata object.
216
- * @param {Uint8Array} nonce - 12-byte AES-GCM nonce.
217
- * @param {Uint8Array} tag - 16-byte GCM authentication tag.
218
- * @returns {{ algorithm: string, nonce: string, tag: string, encrypted: boolean }}
219
- */
220
- #buildMeta(nonce, tag) {
221
- return {
222
- algorithm: 'aes-256-gcm',
223
- nonce: this.#toBase64(nonce),
224
- tag: this.#toBase64(tag),
225
- encrypted: true,
226
- };
227
- }
228
-
229
174
  /**
230
175
  * Encodes binary data to base64, using Buffer when available.
231
176
  * @param {Uint8Array} buf
@@ -249,4 +194,4 @@ export default class WebCryptoAdapter extends CryptoPort {
249
194
  }
250
195
  return Uint8Array.from(globalThis.atob(str), c => c.charCodeAt(0));
251
196
  }
252
- }
197
+ }
@@ -1,3 +1,5 @@
1
+ import CasError from '../domain/errors/CasError.js';
2
+
1
3
  /**
2
4
  * Abstract port for cryptographic operations (hashing, random bytes, AES-256-GCM).
3
5
  * @abstract
@@ -54,6 +56,10 @@ export default class CryptoPort {
54
56
 
55
57
  /**
56
58
  * Derives an encryption key from a passphrase using a KDF.
59
+ *
60
+ * Normalizes parameters (defaults, salt generation), then delegates to the
61
+ * adapter-specific `_doDeriveKey()` template method.
62
+ *
57
63
  * @param {Object} options
58
64
  * @param {string} options.passphrase - The passphrase to derive a key from.
59
65
  * @param {Buffer} [options.salt] - Salt for the KDF (random if omitted).
@@ -65,7 +71,92 @@ export default class CryptoPort {
65
71
  * @param {number} [options.keyLength=32] - Derived key length in bytes.
66
72
  * @returns {Promise<{ key: Buffer, salt: Buffer, params: { algorithm: string, salt: string, iterations?: number, cost?: number, blockSize?: number, parallelization?: number, keyLength: number } }>}
67
73
  */
68
- deriveKey(_options) {
74
+ async deriveKey({
75
+ passphrase,
76
+ salt,
77
+ algorithm = 'pbkdf2',
78
+ iterations = 100_000,
79
+ cost = 16384,
80
+ blockSize = 8,
81
+ parallelization = 1,
82
+ keyLength = 32,
83
+ }) {
84
+ const saltBuf = salt || this.randomBytes(32);
85
+
86
+ const params = {
87
+ algorithm,
88
+ salt: Buffer.from(saltBuf).toString('base64'),
89
+ keyLength,
90
+ };
91
+
92
+ if (algorithm === 'pbkdf2') {
93
+ params.iterations = iterations;
94
+ } else if (algorithm === 'scrypt') {
95
+ params.cost = cost;
96
+ params.blockSize = blockSize;
97
+ params.parallelization = parallelization;
98
+ } else {
99
+ throw new Error(`Unsupported KDF algorithm: ${algorithm}`);
100
+ }
101
+
102
+ const key = await this._doDeriveKey(passphrase, saltBuf, {
103
+ algorithm,
104
+ iterations,
105
+ cost,
106
+ blockSize,
107
+ parallelization,
108
+ keyLength,
109
+ });
110
+
111
+ return { key: Buffer.from(key), salt: Buffer.from(saltBuf), params };
112
+ }
113
+
114
+ /**
115
+ * Adapter-specific key derivation. Override in subclasses.
116
+ * @abstract
117
+ * @param {string} passphrase
118
+ * @param {Buffer|Uint8Array} saltBuf
119
+ * @param {Object} params - Normalized KDF parameters.
120
+ * @returns {Promise<Buffer|Uint8Array>} Derived key bytes.
121
+ */
122
+ async _doDeriveKey(_passphrase, _saltBuf, _params) {
69
123
  throw new Error('Not implemented');
70
124
  }
125
+
126
+ /**
127
+ * Validates that a key is a 32-byte Buffer or Uint8Array.
128
+ * @param {Buffer|Uint8Array} key
129
+ * @throws {CasError} INVALID_KEY_TYPE if key is not a Buffer or Uint8Array
130
+ * @throws {CasError} INVALID_KEY_LENGTH if key is not 32 bytes
131
+ */
132
+ _validateKey(key) {
133
+ if (!globalThis.Buffer?.isBuffer(key) && !(key instanceof Uint8Array)) {
134
+ throw new CasError(
135
+ 'Encryption key must be a Buffer or Uint8Array',
136
+ 'INVALID_KEY_TYPE',
137
+ );
138
+ }
139
+ if (key.length !== 32) {
140
+ throw new CasError(
141
+ `Encryption key must be 32 bytes, got ${key.length}`,
142
+ 'INVALID_KEY_LENGTH',
143
+ { expected: 32, actual: key.length },
144
+ );
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Builds the encryption metadata object from base64-encoded nonce and tag.
150
+ * @param {string} nonce64 - Base64-encoded 12-byte AES-GCM nonce.
151
+ * @param {string} tag64 - Base64-encoded 16-byte GCM authentication tag.
152
+ * @returns {{ algorithm: string, nonce: string, tag: string, encrypted: boolean }}
153
+ */
154
+ _buildMeta(nonce64, tag64) {
155
+ return {
156
+ algorithm: 'aes-256-gcm',
157
+ nonce: nonce64,
158
+ tag: tag64,
159
+ encrypted: true,
160
+ };
161
+ }
71
162
  }