@git-stunts/git-cas 3.0.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.
- package/CHANGELOG.md +77 -0
- package/README.md +54 -14
- package/bin/actions.js +54 -0
- package/bin/git-cas.js +254 -134
- package/bin/ui/context.js +54 -0
- package/bin/ui/dashboard-cmds.js +34 -0
- package/bin/ui/dashboard-view.js +132 -0
- package/bin/ui/dashboard.js +204 -0
- package/bin/ui/encryption-card.js +49 -0
- package/bin/ui/heatmap.js +103 -0
- package/bin/ui/history-timeline.js +84 -0
- package/bin/ui/manifest-view.js +135 -0
- package/bin/ui/progress.js +126 -0
- package/bin/ui/vault-list.js +63 -0
- package/index.d.ts +41 -1
- package/index.js +42 -8
- package/package.json +10 -1
- package/src/domain/services/CasService.d.ts +18 -2
- package/src/domain/services/CasService.js +181 -69
- package/src/domain/services/Semaphore.js +47 -0
- package/src/infrastructure/adapters/BunCryptoAdapter.js +12 -68
- package/src/infrastructure/adapters/EventEmitterObserver.js +70 -0
- package/src/infrastructure/adapters/NodeCryptoAdapter.js +11 -74
- package/src/infrastructure/adapters/SilentObserver.js +11 -0
- package/src/infrastructure/adapters/StatsCollector.js +45 -0
- package/src/infrastructure/adapters/WebCryptoAdapter.js +26 -81
- package/src/ports/CryptoPort.js +92 -1
- package/src/ports/ObservabilityPort.js +33 -0
|
@@ -3,12 +3,12 @@
|
|
|
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
12
|
|
|
13
13
|
const gunzipAsync = promisify(gunzip);
|
|
14
14
|
|
|
@@ -16,39 +16,53 @@ const gunzipAsync = promisify(gunzip);
|
|
|
16
16
|
* Domain service for Content Addressable Storage operations.
|
|
17
17
|
*
|
|
18
18
|
* Provides chunking, encryption, and integrity verification for storing
|
|
19
|
-
* arbitrary data in Git's object database.
|
|
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
|
|
19
|
+
* arbitrary data in Git's object database.
|
|
29
20
|
*/
|
|
30
|
-
export default class CasService
|
|
21
|
+
export default class CasService {
|
|
31
22
|
/**
|
|
32
23
|
* @param {Object} options
|
|
33
24
|
* @param {import('../../ports/GitPersistencePort.js').default} options.persistence
|
|
34
25
|
* @param {import('../../ports/CodecPort.js').default} options.codec
|
|
35
26
|
* @param {import('../../ports/CryptoPort.js').default} options.crypto
|
|
27
|
+
* @param {import('../../ports/ObservabilityPort.js').default} options.observability
|
|
36
28
|
* @param {number} [options.chunkSize=262144] - 256 KiB
|
|
37
29
|
* @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
|
|
30
|
+
* @param {number} [options.concurrency=1] - Maximum parallel chunk I/O operations.
|
|
38
31
|
*/
|
|
39
|
-
constructor({ persistence, codec, crypto, chunkSize = 256 * 1024, merkleThreshold = 1000 }) {
|
|
40
|
-
|
|
32
|
+
constructor({ persistence, codec, crypto, observability, chunkSize = 256 * 1024, merkleThreshold = 1000, concurrency = 1 }) {
|
|
33
|
+
CasService._validateObservability(observability);
|
|
41
34
|
if (chunkSize < 1024) {
|
|
42
35
|
throw new Error('Chunk size must be at least 1024 bytes');
|
|
43
36
|
}
|
|
44
37
|
this.persistence = persistence;
|
|
45
38
|
this.codec = codec;
|
|
46
39
|
this.crypto = crypto;
|
|
40
|
+
this.observability = observability;
|
|
47
41
|
this.chunkSize = chunkSize;
|
|
48
42
|
if (!Number.isInteger(merkleThreshold) || merkleThreshold < 1) {
|
|
49
43
|
throw new Error('Merkle threshold must be a positive integer');
|
|
50
44
|
}
|
|
51
45
|
this.merkleThreshold = merkleThreshold;
|
|
46
|
+
if (!Number.isInteger(concurrency) || concurrency < 1) {
|
|
47
|
+
throw new Error('Concurrency must be a positive integer');
|
|
48
|
+
}
|
|
49
|
+
this.concurrency = concurrency;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Validates that observability implements ObservabilityPort.
|
|
54
|
+
* @private
|
|
55
|
+
* @param {*} observability
|
|
56
|
+
*/
|
|
57
|
+
static _validateObservability(observability) {
|
|
58
|
+
if (
|
|
59
|
+
!observability ||
|
|
60
|
+
typeof observability.metric !== 'function' ||
|
|
61
|
+
typeof observability.log !== 'function' ||
|
|
62
|
+
typeof observability.span !== 'function'
|
|
63
|
+
) {
|
|
64
|
+
throw new Error('observability must implement ObservabilityPort');
|
|
65
|
+
}
|
|
52
66
|
}
|
|
53
67
|
|
|
54
68
|
/**
|
|
@@ -62,18 +76,17 @@ export default class CasService extends EventEmitter {
|
|
|
62
76
|
}
|
|
63
77
|
|
|
64
78
|
/**
|
|
65
|
-
* Stores a single buffer chunk in Git
|
|
79
|
+
* Stores a single buffer chunk in Git, returning its metadata.
|
|
66
80
|
* @private
|
|
67
81
|
* @param {Buffer} buf - The chunk data to store.
|
|
68
|
-
* @param {
|
|
82
|
+
* @param {number} index - Chunk index.
|
|
83
|
+
* @returns {Promise<{ index: number, size: number, digest: string, blob: string }>}
|
|
69
84
|
*/
|
|
70
|
-
async _storeChunk(buf,
|
|
85
|
+
async _storeChunk(buf, index) {
|
|
71
86
|
const digest = await this._sha256(buf);
|
|
72
87
|
const blob = await this.persistence.writeBlob(buf);
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
manifestData.size += buf.length;
|
|
76
|
-
this.emit('chunk:stored', { index: entry.index, size: entry.size, digest, blob });
|
|
88
|
+
this.observability.metric('chunk', { action: 'stored', index, size: buf.length, digest, blob });
|
|
89
|
+
return { index, size: buf.length, digest, blob };
|
|
77
90
|
}
|
|
78
91
|
|
|
79
92
|
/**
|
|
@@ -85,53 +98,51 @@ export default class CasService extends EventEmitter {
|
|
|
85
98
|
*/
|
|
86
99
|
async _chunkAndStore(source, manifestData) {
|
|
87
100
|
let buffer = Buffer.alloc(0);
|
|
101
|
+
const sem = new Semaphore(this.concurrency);
|
|
102
|
+
const pending = [];
|
|
103
|
+
let nextIndex = 0;
|
|
104
|
+
|
|
105
|
+
const launchWrite = (buf, idx) => {
|
|
106
|
+
const p = sem.acquire().then(async () => {
|
|
107
|
+
try {
|
|
108
|
+
return await this._storeChunk(buf, idx);
|
|
109
|
+
} finally {
|
|
110
|
+
sem.release();
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
pending.push(p);
|
|
114
|
+
};
|
|
88
115
|
|
|
89
116
|
try {
|
|
90
117
|
for await (const chunk of source) {
|
|
91
118
|
buffer = Buffer.concat([buffer, chunk]);
|
|
92
119
|
while (buffer.length >= this.chunkSize) {
|
|
93
|
-
|
|
120
|
+
launchWrite(buffer.slice(0, this.chunkSize), nextIndex++);
|
|
94
121
|
buffer = buffer.slice(this.chunkSize);
|
|
95
122
|
}
|
|
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
|
-
{
|
|
130
|
+
{ chunksDispatched: nextIndex, originalError: err },
|
|
103
131
|
);
|
|
104
|
-
|
|
105
|
-
|
|
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
137
|
if (buffer.length > 0) {
|
|
111
|
-
|
|
138
|
+
launchWrite(buffer, nextIndex++);
|
|
112
139
|
}
|
|
113
|
-
}
|
|
114
140
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
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
|
-
);
|
|
141
|
+
const results = await Promise.all(pending);
|
|
142
|
+
results.sort((a, b) => a.index - b.index);
|
|
143
|
+
for (const entry of results) {
|
|
144
|
+
manifestData.chunks.push(entry);
|
|
145
|
+
manifestData.size += entry.size;
|
|
135
146
|
}
|
|
136
147
|
}
|
|
137
148
|
|
|
@@ -144,7 +155,6 @@ export default class CasService extends EventEmitter {
|
|
|
144
155
|
* @throws {CasError} INVALID_KEY_TYPE | INVALID_KEY_LENGTH if the key is invalid.
|
|
145
156
|
*/
|
|
146
157
|
async encrypt({ buffer, key }) {
|
|
147
|
-
this._validateKey(key);
|
|
148
158
|
return await this.crypto.encryptBuffer(buffer, key);
|
|
149
159
|
}
|
|
150
160
|
|
|
@@ -238,7 +248,7 @@ export default class CasService extends EventEmitter {
|
|
|
238
248
|
}
|
|
239
249
|
|
|
240
250
|
if (encryptionKey) {
|
|
241
|
-
this._validateKey(encryptionKey);
|
|
251
|
+
this.crypto._validateKey(encryptionKey);
|
|
242
252
|
}
|
|
243
253
|
|
|
244
254
|
const manifestData = { slug, filename, size: 0, chunks: [] };
|
|
@@ -262,8 +272,8 @@ export default class CasService extends EventEmitter {
|
|
|
262
272
|
}
|
|
263
273
|
|
|
264
274
|
const manifest = new Manifest(manifestData);
|
|
265
|
-
this.
|
|
266
|
-
slug, size: manifest.size, chunkCount: manifest.chunks.length, encrypted: !!encryptionKey,
|
|
275
|
+
this.observability.metric('file', {
|
|
276
|
+
action: 'stored', slug, size: manifest.size, chunkCount: manifest.chunks.length, encrypted: !!encryptionKey,
|
|
267
277
|
});
|
|
268
278
|
return manifest;
|
|
269
279
|
}
|
|
@@ -366,13 +376,11 @@ export default class CasService extends EventEmitter {
|
|
|
366
376
|
'INTEGRITY_ERROR',
|
|
367
377
|
{ chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
|
|
368
378
|
);
|
|
369
|
-
|
|
370
|
-
this.emit('error', { code: err.code, message: err.message });
|
|
371
|
-
}
|
|
379
|
+
this.observability.metric('error', { code: err.code, message: err.message });
|
|
372
380
|
throw err;
|
|
373
381
|
}
|
|
374
382
|
buffers.push(blob);
|
|
375
|
-
this.
|
|
383
|
+
this.observability.metric('chunk', { action: 'restored', index: chunk.index, size: blob.length, digest: chunk.digest });
|
|
376
384
|
}
|
|
377
385
|
return buffers;
|
|
378
386
|
}
|
|
@@ -414,7 +422,7 @@ export default class CasService extends EventEmitter {
|
|
|
414
422
|
);
|
|
415
423
|
}
|
|
416
424
|
if (encryptionKey) {
|
|
417
|
-
this._validateKey(encryptionKey);
|
|
425
|
+
this.crypto._validateKey(encryptionKey);
|
|
418
426
|
} else if (manifest.encryption?.encrypted) {
|
|
419
427
|
throw new CasError('Encryption key required to restore encrypted content', 'MISSING_KEY');
|
|
420
428
|
}
|
|
@@ -436,12 +444,56 @@ export default class CasService extends EventEmitter {
|
|
|
436
444
|
* @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
|
|
437
445
|
*/
|
|
438
446
|
async restore({ manifest, encryptionKey, passphrase }) {
|
|
447
|
+
const chunks = [];
|
|
448
|
+
for await (const chunk of this.restoreStream({ manifest, encryptionKey, passphrase })) {
|
|
449
|
+
chunks.push(chunk);
|
|
450
|
+
}
|
|
451
|
+
const buffer = Buffer.concat(chunks);
|
|
452
|
+
return { buffer, bytesWritten: buffer.length };
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Restores a file from its manifest as an async iterable of Buffer chunks.
|
|
457
|
+
*
|
|
458
|
+
* For unencrypted, uncompressed files this is true per-chunk streaming
|
|
459
|
+
* with O(chunkSize) memory. For encrypted or compressed files, all chunks
|
|
460
|
+
* are buffered internally for decryption/decompression, then yielded.
|
|
461
|
+
*
|
|
462
|
+
* @param {Object} options
|
|
463
|
+
* @param {import('../value-objects/Manifest.js').default} options.manifest - The file manifest.
|
|
464
|
+
* @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
|
|
465
|
+
* @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
|
|
466
|
+
* Note: For unencrypted files, each yielded buffer corresponds to an original
|
|
467
|
+
* stored chunk. For encrypted/compressed files, yielded buffers are
|
|
468
|
+
* chunkSize-sliced pieces of the decrypted/decompressed result and may not
|
|
469
|
+
* correspond 1:1 to the original chunks.
|
|
470
|
+
*
|
|
471
|
+
* @yields {Buffer}
|
|
472
|
+
* @throws {CasError} MISSING_KEY if manifest is encrypted but no key is provided.
|
|
473
|
+
* @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
|
|
474
|
+
*/
|
|
475
|
+
async *restoreStream({ manifest, encryptionKey, passphrase }) {
|
|
439
476
|
const key = await this._resolveEncryptionKey(manifest, encryptionKey, passphrase);
|
|
440
477
|
|
|
441
478
|
if (manifest.chunks.length === 0) {
|
|
442
|
-
|
|
479
|
+
this.observability.metric('file', {
|
|
480
|
+
action: 'restored', slug: manifest.slug, size: 0, chunkCount: 0,
|
|
481
|
+
});
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
if (manifest.encryption?.encrypted || manifest.compression) {
|
|
486
|
+
yield* this._restoreBuffered(manifest, key);
|
|
487
|
+
} else {
|
|
488
|
+
yield* this._restoreStreaming(manifest);
|
|
443
489
|
}
|
|
490
|
+
}
|
|
444
491
|
|
|
492
|
+
/**
|
|
493
|
+
* Buffered restore path for encrypted/compressed manifests.
|
|
494
|
+
* @private
|
|
495
|
+
*/
|
|
496
|
+
async *_restoreBuffered(manifest, key) {
|
|
445
497
|
let buffer = Buffer.concat(await this._readAndVerifyChunks(manifest.chunks));
|
|
446
498
|
|
|
447
499
|
if (manifest.encryption?.encrypted) {
|
|
@@ -449,18 +501,78 @@ export default class CasService extends EventEmitter {
|
|
|
449
501
|
}
|
|
450
502
|
|
|
451
503
|
if (manifest.compression) {
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
504
|
+
buffer = await this._decompress(buffer);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
this.observability.metric('file', {
|
|
508
|
+
action: 'restored', slug: manifest.slug, size: buffer.length, chunkCount: manifest.chunks.length,
|
|
509
|
+
});
|
|
510
|
+
|
|
511
|
+
for (let offset = 0; offset < buffer.length; offset += this.chunkSize) {
|
|
512
|
+
yield buffer.subarray(offset, offset + this.chunkSize);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Per-chunk streaming restore with read-ahead.
|
|
518
|
+
* @private
|
|
519
|
+
*/
|
|
520
|
+
async *_restoreStreaming(manifest) {
|
|
521
|
+
const chunks = manifest.chunks;
|
|
522
|
+
const readAhead = this.concurrency;
|
|
523
|
+
let totalSize = 0;
|
|
524
|
+
|
|
525
|
+
const readAndVerify = async (chunk) => {
|
|
526
|
+
const blob = await this.persistence.readBlob(chunk.blob);
|
|
527
|
+
const digest = await this._sha256(blob);
|
|
528
|
+
if (digest !== chunk.digest) {
|
|
529
|
+
const err = new CasError(
|
|
530
|
+
`Chunk ${chunk.index} integrity check failed`,
|
|
531
|
+
'INTEGRITY_ERROR',
|
|
532
|
+
{ chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
|
|
533
|
+
);
|
|
534
|
+
this.observability.metric('error', { code: err.code, message: err.message });
|
|
535
|
+
throw err;
|
|
536
|
+
}
|
|
537
|
+
return blob;
|
|
538
|
+
};
|
|
539
|
+
|
|
540
|
+
const ahead = [];
|
|
541
|
+
for (let i = 0; i < Math.min(readAhead, chunks.length); i++) {
|
|
542
|
+
ahead.push(readAndVerify(chunks[i]));
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
try {
|
|
546
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
547
|
+
const blob = await ahead[i % readAhead];
|
|
548
|
+
this.observability.metric('chunk', { action: 'restored', index: chunks[i].index, size: blob.length, digest: chunks[i].digest });
|
|
549
|
+
totalSize += blob.length;
|
|
550
|
+
const nextIdx = i + readAhead;
|
|
551
|
+
if (nextIdx < chunks.length) {
|
|
552
|
+
ahead[i % readAhead] = readAndVerify(chunks[nextIdx]);
|
|
553
|
+
}
|
|
554
|
+
yield blob;
|
|
457
555
|
}
|
|
556
|
+
} finally {
|
|
557
|
+
await Promise.allSettled(ahead);
|
|
458
558
|
}
|
|
459
559
|
|
|
460
|
-
this.
|
|
461
|
-
slug: manifest.slug, size:
|
|
560
|
+
this.observability.metric('file', {
|
|
561
|
+
action: 'restored', slug: manifest.slug, size: totalSize, chunkCount: chunks.length,
|
|
462
562
|
});
|
|
463
|
-
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Decompresses a gzip buffer.
|
|
567
|
+
* @private
|
|
568
|
+
*/
|
|
569
|
+
async _decompress(buffer) {
|
|
570
|
+
try {
|
|
571
|
+
return await gunzipAsync(buffer);
|
|
572
|
+
} catch (err) {
|
|
573
|
+
if (err instanceof CasError) { throw err; }
|
|
574
|
+
throw new CasError(`Decompression failed: ${err.message}`, 'INTEGRITY_ERROR', { originalError: err });
|
|
575
|
+
}
|
|
464
576
|
}
|
|
465
577
|
|
|
466
578
|
/**
|
|
@@ -619,13 +731,13 @@ export default class CasService extends EventEmitter {
|
|
|
619
731
|
const blob = await this.persistence.readBlob(chunk.blob);
|
|
620
732
|
const digest = await this._sha256(blob);
|
|
621
733
|
if (digest !== chunk.digest) {
|
|
622
|
-
this.
|
|
623
|
-
slug: manifest.slug, chunkIndex: chunk.index, expected: chunk.digest, actual: digest,
|
|
734
|
+
this.observability.metric('integrity', {
|
|
735
|
+
action: 'fail', slug: manifest.slug, chunkIndex: chunk.index, expected: chunk.digest, actual: digest,
|
|
624
736
|
});
|
|
625
737
|
return false;
|
|
626
738
|
}
|
|
627
739
|
}
|
|
628
|
-
this.
|
|
740
|
+
this.observability.metric('integrity', { action: 'pass', slug: manifest.slug });
|
|
629
741
|
return true;
|
|
630
742
|
}
|
|
631
743
|
}
|
|
@@ -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
|
+
}
|
|
@@ -27,20 +27,20 @@ export default class BunCryptoAdapter extends CryptoPort {
|
|
|
27
27
|
|
|
28
28
|
/** @override */
|
|
29
29
|
async encryptBuffer(buffer, key) {
|
|
30
|
-
this
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
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
|
+
}
|