@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.
@@ -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
+ }