@git-stunts/git-cas 5.2.4 → 5.3.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 +56 -1
- package/README.md +60 -13
- package/bin/actions.js +14 -1
- package/bin/config.js +203 -0
- package/bin/git-cas.js +125 -27
- package/bin/ui/passphrase-prompt.js +100 -0
- package/index.d.ts +15 -0
- package/index.js +29 -5
- package/package.json +1 -1
- package/src/domain/errors/CasError.js +3 -1
- package/src/domain/services/CasService.d.ts +20 -0
- package/src/domain/services/CasService.js +127 -25
- package/src/domain/services/VaultService.js +23 -2
- package/src/infrastructure/adapters/NodeCryptoAdapter.js +12 -2
- package/src/infrastructure/adapters/WebCryptoAdapter.js +57 -29
- package/src/infrastructure/chunkers/CdcChunker.js +5 -0
- package/src/infrastructure/chunkers/FixedChunker.js +23 -7
|
@@ -34,28 +34,48 @@ export default class CasService {
|
|
|
34
34
|
* @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
|
|
35
35
|
* @param {number} [options.concurrency=1] - Maximum parallel chunk I/O operations.
|
|
36
36
|
* @param {import('../../ports/ChunkingPort.js').default} [options.chunker] - Chunking strategy (default FixedChunker).
|
|
37
|
+
* @param {number} [options.maxRestoreBufferSize=536870912] - Max bytes for buffered restore (default 512 MiB).
|
|
37
38
|
*/
|
|
38
|
-
constructor({ persistence, codec, crypto, observability, chunkSize = 256 * 1024, merkleThreshold = 1000, concurrency = 1, chunker }) {
|
|
39
|
+
constructor({ persistence, codec, crypto, observability, chunkSize = 256 * 1024, merkleThreshold = 1000, concurrency = 1, chunker, maxRestoreBufferSize = 512 * 1024 * 1024 }) {
|
|
39
40
|
CasService._validateObservability(observability);
|
|
40
|
-
|
|
41
|
-
throw new Error('Chunk size must be at least 1024 bytes');
|
|
42
|
-
}
|
|
41
|
+
CasService.#validateConstructorArgs({ chunkSize, merkleThreshold, concurrency, maxRestoreBufferSize });
|
|
43
42
|
this.persistence = persistence;
|
|
44
43
|
this.codec = codec;
|
|
45
44
|
this.crypto = crypto;
|
|
46
45
|
this.observability = observability;
|
|
47
46
|
this.chunkSize = chunkSize;
|
|
47
|
+
if (chunkSize > 10 * 1024 * 1024) {
|
|
48
|
+
observability.log('warn', `Chunk size ${chunkSize} exceeds 10 MiB — consider a smaller value`, { chunkSize });
|
|
49
|
+
}
|
|
48
50
|
/** @type {import('../../ports/ChunkingPort.js').default} */
|
|
49
51
|
this.chunker = chunker || new FixedChunker({ chunkSize });
|
|
52
|
+
this.merkleThreshold = merkleThreshold;
|
|
53
|
+
this.concurrency = concurrency;
|
|
54
|
+
this.maxRestoreBufferSize = maxRestoreBufferSize;
|
|
55
|
+
this.#keyResolver = new KeyResolver(crypto);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Validates constructor numeric arguments.
|
|
60
|
+
* @private
|
|
61
|
+
*/
|
|
62
|
+
static #validateConstructorArgs({ chunkSize, merkleThreshold, concurrency, maxRestoreBufferSize }) {
|
|
63
|
+
if (!Number.isInteger(chunkSize) || chunkSize < 1024) {
|
|
64
|
+
throw new Error('Chunk size must be an integer >= 1024 bytes');
|
|
65
|
+
}
|
|
66
|
+
const MAX_CHUNK_SIZE = 100 * 1024 * 1024;
|
|
67
|
+
if (chunkSize > MAX_CHUNK_SIZE) {
|
|
68
|
+
throw new Error(`Chunk size must not exceed ${MAX_CHUNK_SIZE} bytes (100 MiB)`);
|
|
69
|
+
}
|
|
50
70
|
if (!Number.isInteger(merkleThreshold) || merkleThreshold < 1) {
|
|
51
71
|
throw new Error('Merkle threshold must be a positive integer');
|
|
52
72
|
}
|
|
53
|
-
this.merkleThreshold = merkleThreshold;
|
|
54
73
|
if (!Number.isInteger(concurrency) || concurrency < 1) {
|
|
55
74
|
throw new Error('Concurrency must be a positive integer');
|
|
56
75
|
}
|
|
57
|
-
|
|
58
|
-
|
|
76
|
+
if (!Number.isInteger(maxRestoreBufferSize) || maxRestoreBufferSize < 1024) {
|
|
77
|
+
throw new Error('maxRestoreBufferSize must be a positive integer >= 1024');
|
|
78
|
+
}
|
|
59
79
|
}
|
|
60
80
|
|
|
61
81
|
/**
|
|
@@ -127,15 +147,23 @@ export default class CasService {
|
|
|
127
147
|
launchWrite(chunk, nextIndex++);
|
|
128
148
|
}
|
|
129
149
|
} catch (err) {
|
|
130
|
-
await Promise.allSettled(pending);
|
|
131
|
-
|
|
150
|
+
const settled = await Promise.allSettled(pending);
|
|
151
|
+
const orphanedBlobs = settled
|
|
152
|
+
.filter((r) => r.status === 'fulfilled')
|
|
153
|
+
.map((r) => r.value.blob);
|
|
154
|
+
if (err instanceof CasError) {
|
|
155
|
+
err.meta = { ...err.meta, orphanedBlobs };
|
|
156
|
+
throw err;
|
|
157
|
+
}
|
|
132
158
|
const casErr = new CasError(
|
|
133
159
|
`Stream error during store: ${err.message}`,
|
|
134
160
|
'STREAM_ERROR',
|
|
135
|
-
{ chunksDispatched: nextIndex, originalError: err },
|
|
161
|
+
{ chunksDispatched: nextIndex, orphanedBlobs, originalError: err },
|
|
136
162
|
);
|
|
137
|
-
|
|
138
|
-
|
|
163
|
+
this.observability.metric('error', {
|
|
164
|
+
code: casErr.code, message: casErr.message,
|
|
165
|
+
orphanedBlobs: orphanedBlobs.length,
|
|
166
|
+
});
|
|
139
167
|
throw casErr;
|
|
140
168
|
}
|
|
141
169
|
|
|
@@ -257,6 +285,13 @@ export default class CasService {
|
|
|
257
285
|
const manifestData = this._buildManifestData(slug, filename, compression);
|
|
258
286
|
const processedSource = compression ? this._compressStream(source) : source;
|
|
259
287
|
|
|
288
|
+
if (keyInfo.key && this.chunker.strategy === 'cdc') {
|
|
289
|
+
this.observability.log(
|
|
290
|
+
'warn',
|
|
291
|
+
'CDC deduplication is ineffective with encryption — ciphertext is pseudorandom',
|
|
292
|
+
{ strategy: 'cdc' },
|
|
293
|
+
);
|
|
294
|
+
}
|
|
260
295
|
if (keyInfo.key) {
|
|
261
296
|
const { encrypt, finalize } = this.crypto.createEncryptionStream(keyInfo.key);
|
|
262
297
|
await this._chunkAndStore(encrypt(processedSource), manifestData);
|
|
@@ -285,11 +320,37 @@ export default class CasService {
|
|
|
285
320
|
return data;
|
|
286
321
|
}
|
|
287
322
|
|
|
323
|
+
/**
|
|
324
|
+
* Builds unique chunk blob tree entries in first-seen order.
|
|
325
|
+
*
|
|
326
|
+
* Tree entries keep chunk blobs reachable in Git. The manifest remains the
|
|
327
|
+
* authoritative ordered list of chunk occurrences, so repeated digests only
|
|
328
|
+
* need one tree entry.
|
|
329
|
+
*
|
|
330
|
+
* @private
|
|
331
|
+
* @param {import('../value-objects/Chunk.js').default[]} chunks
|
|
332
|
+
* @returns {string[]}
|
|
333
|
+
*/
|
|
334
|
+
_createChunkTreeEntries(chunks) {
|
|
335
|
+
const treeEntries = [];
|
|
336
|
+
const seenDigests = new Set();
|
|
337
|
+
|
|
338
|
+
for (const chunk of chunks) {
|
|
339
|
+
if (seenDigests.has(chunk.digest)) {
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
seenDigests.add(chunk.digest);
|
|
343
|
+
treeEntries.push(`100644 blob ${chunk.blob}\t${chunk.digest}`);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
return treeEntries;
|
|
347
|
+
}
|
|
348
|
+
|
|
288
349
|
/**
|
|
289
350
|
* Creates a Git tree object from a manifest.
|
|
290
351
|
*
|
|
291
|
-
* The tree contains the serialized manifest file and one blob entry per
|
|
292
|
-
*
|
|
352
|
+
* The tree contains the serialized manifest file and one blob entry per
|
|
353
|
+
* unique chunk digest, preserving first-seen order.
|
|
293
354
|
*
|
|
294
355
|
* @param {Object} options
|
|
295
356
|
* @param {import('../value-objects/Manifest.js').default} options.manifest - The file manifest.
|
|
@@ -307,7 +368,7 @@ export default class CasService {
|
|
|
307
368
|
|
|
308
369
|
const treeEntries = [
|
|
309
370
|
`100644 blob ${manifestOid}\tmanifest.${this.codec.extension}`,
|
|
310
|
-
...
|
|
371
|
+
...this._createChunkTreeEntries(chunks),
|
|
311
372
|
];
|
|
312
373
|
|
|
313
374
|
return await this.persistence.writeTree(treeEntries);
|
|
@@ -323,7 +384,6 @@ export default class CasService {
|
|
|
323
384
|
async _createMerkleTree({ manifest }) {
|
|
324
385
|
const chunks = [...manifest.chunks];
|
|
325
386
|
const subManifestRefs = [];
|
|
326
|
-
const chunkBlobEntries = [];
|
|
327
387
|
|
|
328
388
|
for (let i = 0; i < chunks.length; i += this.merkleThreshold) {
|
|
329
389
|
const group = chunks.slice(i, i + this.merkleThreshold);
|
|
@@ -336,10 +396,6 @@ export default class CasService {
|
|
|
336
396
|
chunkCount: group.length,
|
|
337
397
|
startIndex: i,
|
|
338
398
|
});
|
|
339
|
-
|
|
340
|
-
for (const c of group) {
|
|
341
|
-
chunkBlobEntries.push(`100644 blob ${c.blob}\t${c.digest}`);
|
|
342
|
-
}
|
|
343
399
|
}
|
|
344
400
|
|
|
345
401
|
const rootManifestData = {
|
|
@@ -359,7 +415,7 @@ export default class CasService {
|
|
|
359
415
|
const treeEntries = [
|
|
360
416
|
`100644 blob ${rootOid}\tmanifest.${this.codec.extension}`,
|
|
361
417
|
...subManifestEntries,
|
|
362
|
-
...
|
|
418
|
+
...this._createChunkTreeEntries(chunks),
|
|
363
419
|
];
|
|
364
420
|
|
|
365
421
|
return await this.persistence.writeTree(treeEntries);
|
|
@@ -469,14 +525,38 @@ export default class CasService {
|
|
|
469
525
|
* @private
|
|
470
526
|
*/
|
|
471
527
|
async *_restoreBuffered(manifest, key) {
|
|
528
|
+
const totalSize = manifest.chunks.reduce((acc, c) => acc + c.size, 0);
|
|
529
|
+
if (totalSize > this.maxRestoreBufferSize) {
|
|
530
|
+
throw new CasError(
|
|
531
|
+
`Encrypted/compressed restore would buffer ${totalSize} bytes ` +
|
|
532
|
+
`(limit: ${this.maxRestoreBufferSize}). Increase maxRestoreBufferSize ` +
|
|
533
|
+
'or store without encryption.',
|
|
534
|
+
'RESTORE_TOO_LARGE',
|
|
535
|
+
{ size: totalSize, limit: this.maxRestoreBufferSize },
|
|
536
|
+
);
|
|
537
|
+
}
|
|
472
538
|
let buffer = Buffer.concat(await this._readAndVerifyChunks(manifest.chunks));
|
|
473
539
|
|
|
474
540
|
if (manifest.encryption?.encrypted) {
|
|
475
|
-
|
|
541
|
+
try {
|
|
542
|
+
buffer = await this.decrypt({ buffer, key, meta: manifest.encryption });
|
|
543
|
+
} catch (err) {
|
|
544
|
+
if (err instanceof CasError && err.code === 'INTEGRITY_ERROR') {
|
|
545
|
+
this.observability.metric('error', { action: 'decryption_failed', slug: manifest.slug });
|
|
546
|
+
}
|
|
547
|
+
throw err;
|
|
548
|
+
}
|
|
476
549
|
}
|
|
477
550
|
|
|
478
551
|
if (manifest.compression) {
|
|
479
552
|
buffer = await this._decompress(buffer);
|
|
553
|
+
if (buffer.length > this.maxRestoreBufferSize) {
|
|
554
|
+
throw new CasError(
|
|
555
|
+
`Decompressed restore is ${buffer.length} bytes (limit: ${this.maxRestoreBufferSize})`,
|
|
556
|
+
'RESTORE_TOO_LARGE',
|
|
557
|
+
{ size: buffer.length, limit: this.maxRestoreBufferSize },
|
|
558
|
+
);
|
|
559
|
+
}
|
|
480
560
|
}
|
|
481
561
|
|
|
482
562
|
this.observability.metric('file', {
|
|
@@ -626,7 +706,7 @@ export default class CasService {
|
|
|
626
706
|
}
|
|
627
707
|
|
|
628
708
|
/**
|
|
629
|
-
*
|
|
709
|
+
* Reads a manifest from a Git tree and returns inspection metadata.
|
|
630
710
|
* Does not perform any destructive Git operations.
|
|
631
711
|
*
|
|
632
712
|
* @param {Object} options
|
|
@@ -634,7 +714,7 @@ export default class CasService {
|
|
|
634
714
|
* @returns {Promise<{ chunksOrphaned: number, slug: string }>}
|
|
635
715
|
* @throws {CasError} MANIFEST_NOT_FOUND if the tree has no manifest
|
|
636
716
|
*/
|
|
637
|
-
async
|
|
717
|
+
async inspectAsset({ treeOid }) {
|
|
638
718
|
const manifest = await this.readManifest({ treeOid });
|
|
639
719
|
return {
|
|
640
720
|
slug: manifest.slug,
|
|
@@ -642,6 +722,17 @@ export default class CasService {
|
|
|
642
722
|
};
|
|
643
723
|
}
|
|
644
724
|
|
|
725
|
+
/**
|
|
726
|
+
* @deprecated Use {@link inspectAsset} instead.
|
|
727
|
+
* @param {Object} options
|
|
728
|
+
* @param {string} options.treeOid - Git tree OID of the asset
|
|
729
|
+
* @returns {Promise<{ chunksOrphaned: number, slug: string }>}
|
|
730
|
+
*/
|
|
731
|
+
async deleteAsset(options) {
|
|
732
|
+
this.observability.log('warn', 'deleteAsset() is deprecated — use inspectAsset()');
|
|
733
|
+
return await this.inspectAsset(options);
|
|
734
|
+
}
|
|
735
|
+
|
|
645
736
|
/**
|
|
646
737
|
* Aggregates referenced chunk blob OIDs across multiple stored assets.
|
|
647
738
|
* Analysis only — does not delete or modify anything.
|
|
@@ -651,7 +742,7 @@ export default class CasService {
|
|
|
651
742
|
* @returns {Promise<{ referenced: Set<string>, total: number }>}
|
|
652
743
|
* @throws {CasError} MANIFEST_NOT_FOUND if any treeOid lacks a manifest
|
|
653
744
|
*/
|
|
654
|
-
async
|
|
745
|
+
async collectReferencedChunks({ treeOids }) {
|
|
655
746
|
const referenced = new Set();
|
|
656
747
|
let total = 0;
|
|
657
748
|
|
|
@@ -666,6 +757,17 @@ export default class CasService {
|
|
|
666
757
|
return { referenced, total };
|
|
667
758
|
}
|
|
668
759
|
|
|
760
|
+
/**
|
|
761
|
+
* @deprecated Use {@link collectReferencedChunks} instead.
|
|
762
|
+
* @param {Object} options
|
|
763
|
+
* @param {string[]} options.treeOids - Git tree OIDs to analyze
|
|
764
|
+
* @returns {Promise<{ referenced: Set<string>, total: number }>}
|
|
765
|
+
*/
|
|
766
|
+
async findOrphanedChunks(options) {
|
|
767
|
+
this.observability.log('warn', 'findOrphanedChunks() is deprecated — use collectReferencedChunks()');
|
|
768
|
+
return await this.collectReferencedChunks(options);
|
|
769
|
+
}
|
|
770
|
+
|
|
669
771
|
/**
|
|
670
772
|
* Derives an encryption key from a passphrase using PBKDF2 or scrypt.
|
|
671
773
|
* @param {Object} options
|
|
@@ -80,16 +80,22 @@ function hasControlChars(str) {
|
|
|
80
80
|
export default class VaultService {
|
|
81
81
|
static VAULT_REF = VAULT_REF;
|
|
82
82
|
|
|
83
|
+
/** @type {number} Nonce usage warning threshold (2^31). */
|
|
84
|
+
static ENCRYPTION_COUNT_WARN = 2 ** 31;
|
|
85
|
+
|
|
83
86
|
/**
|
|
84
87
|
* @param {Object} options
|
|
85
88
|
* @param {import('../../ports/GitPersistencePort.js').default} options.persistence
|
|
86
89
|
* @param {import('../../ports/GitRefPort.js').default} options.ref
|
|
87
90
|
* @param {import('../../ports/CryptoPort.js').default} options.crypto
|
|
91
|
+
* @param {import('../../ports/ObservabilityPort.js').default} [options.observability]
|
|
88
92
|
*/
|
|
89
|
-
constructor({ persistence, ref, crypto }) {
|
|
93
|
+
constructor({ persistence, ref, crypto, observability }) {
|
|
90
94
|
this.persistence = persistence;
|
|
91
95
|
this.ref = ref;
|
|
92
96
|
this.crypto = crypto;
|
|
97
|
+
/** @type {import('../../ports/ObservabilityPort.js').default} */
|
|
98
|
+
this.observability = observability || { metric() {}, log() {}, span: () => ({ end() {} }) };
|
|
93
99
|
}
|
|
94
100
|
|
|
95
101
|
// ---------------------------------------------------------------------------
|
|
@@ -389,9 +395,24 @@ export default class VaultService {
|
|
|
389
395
|
}
|
|
390
396
|
const isUpdate = state.entries.has(slug);
|
|
391
397
|
state.entries.set(slug, treeOid);
|
|
398
|
+
// Shallow copy to avoid mutating readState()'s object on CAS retries.
|
|
399
|
+
const metadata = { ...(state.metadata || { version: 1 }) };
|
|
400
|
+
if (metadata.encryption) {
|
|
401
|
+
// Tracks nonce-relevant operations: every addToVault on an encrypted
|
|
402
|
+
// vault implies an encryption occurred at the store layer.
|
|
403
|
+
metadata.encryptionCount = (metadata.encryptionCount || 0) + 1;
|
|
404
|
+
if (metadata.encryptionCount >= VaultService.ENCRYPTION_COUNT_WARN) {
|
|
405
|
+
this.observability.log(
|
|
406
|
+
'warn',
|
|
407
|
+
`Vault encryption count (${metadata.encryptionCount}) exceeds ` +
|
|
408
|
+
`${VaultService.ENCRYPTION_COUNT_WARN} — rotate your key`,
|
|
409
|
+
{ encryptionCount: metadata.encryptionCount },
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
392
413
|
return {
|
|
393
414
|
entries: state.entries,
|
|
394
|
-
metadata
|
|
415
|
+
metadata,
|
|
395
416
|
message: isUpdate ? `vault: update ${slug}` : `vault: add ${slug}`,
|
|
396
417
|
};
|
|
397
418
|
});
|
|
@@ -1,6 +1,7 @@
|
|
|
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';
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* Node.js implementation of CryptoPort using node:crypto.
|
|
@@ -28,9 +29,9 @@ export default class NodeCryptoAdapter extends CryptoPort {
|
|
|
28
29
|
* @override
|
|
29
30
|
* @param {Buffer|Uint8Array} buffer - Plaintext to encrypt.
|
|
30
31
|
* @param {Buffer|Uint8Array} key - 32-byte encryption key.
|
|
31
|
-
* @returns {{ buf: Buffer, meta: import('../../ports/CryptoPort.js').EncryptionMeta }}
|
|
32
|
+
* @returns {Promise<{ buf: Buffer, meta: import('../../ports/CryptoPort.js').EncryptionMeta }>}
|
|
32
33
|
*/
|
|
33
|
-
encryptBuffer(buffer, key) {
|
|
34
|
+
async encryptBuffer(buffer, key) {
|
|
34
35
|
this._validateKey(key);
|
|
35
36
|
const nonce = randomBytes(12);
|
|
36
37
|
const cipher = createCipheriv('aes-256-gcm', key, nonce);
|
|
@@ -50,6 +51,7 @@ export default class NodeCryptoAdapter extends CryptoPort {
|
|
|
50
51
|
* @returns {Buffer}
|
|
51
52
|
*/
|
|
52
53
|
decryptBuffer(buffer, key, meta) {
|
|
54
|
+
this._validateKey(key);
|
|
53
55
|
const nonce = Buffer.from(meta.nonce, 'base64');
|
|
54
56
|
const tag = Buffer.from(meta.tag, 'base64');
|
|
55
57
|
const decipher = createDecipheriv('aes-256-gcm', key, nonce);
|
|
@@ -66,6 +68,7 @@ export default class NodeCryptoAdapter extends CryptoPort {
|
|
|
66
68
|
this._validateKey(key);
|
|
67
69
|
const nonce = randomBytes(12);
|
|
68
70
|
const cipher = createCipheriv('aes-256-gcm', key, nonce);
|
|
71
|
+
let streamFinalized = false;
|
|
69
72
|
|
|
70
73
|
/** @param {AsyncIterable<Buffer>} source */
|
|
71
74
|
const encrypt = async function* (source) {
|
|
@@ -79,9 +82,16 @@ export default class NodeCryptoAdapter extends CryptoPort {
|
|
|
79
82
|
if (final.length > 0) {
|
|
80
83
|
yield final;
|
|
81
84
|
}
|
|
85
|
+
streamFinalized = true;
|
|
82
86
|
};
|
|
83
87
|
|
|
84
88
|
const finalize = () => {
|
|
89
|
+
if (!streamFinalized) {
|
|
90
|
+
throw new CasError(
|
|
91
|
+
'Cannot finalize before the encrypt stream is fully consumed',
|
|
92
|
+
'STREAM_NOT_CONSUMED',
|
|
93
|
+
);
|
|
94
|
+
}
|
|
85
95
|
const tag = cipher.getAuthTag();
|
|
86
96
|
return this._buildMeta(nonce.toString('base64'), tag.toString('base64'));
|
|
87
97
|
};
|
|
@@ -9,6 +9,21 @@ import CasError from '../../domain/errors/CasError.js';
|
|
|
9
9
|
* AES-GCM is a one-shot API (the GCM tag is computed over the entire plaintext).
|
|
10
10
|
*/
|
|
11
11
|
export default class WebCryptoAdapter extends CryptoPort {
|
|
12
|
+
/** @type {number} */
|
|
13
|
+
#maxEncryptionBufferSize;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {Object} [options]
|
|
17
|
+
* @param {number} [options.maxEncryptionBufferSize=536870912] - Max bytes to buffer during streaming encryption (default 512 MiB).
|
|
18
|
+
*/
|
|
19
|
+
constructor({ maxEncryptionBufferSize = 512 * 1024 * 1024 } = {}) {
|
|
20
|
+
super();
|
|
21
|
+
if (!Number.isFinite(maxEncryptionBufferSize) || maxEncryptionBufferSize <= 0) {
|
|
22
|
+
throw new RangeError('maxEncryptionBufferSize must be a finite positive number');
|
|
23
|
+
}
|
|
24
|
+
this.#maxEncryptionBufferSize = maxEncryptionBufferSize;
|
|
25
|
+
}
|
|
26
|
+
|
|
12
27
|
/**
|
|
13
28
|
* @override
|
|
14
29
|
* @param {Buffer|Uint8Array} buf - Data to hash.
|
|
@@ -73,6 +88,7 @@ export default class WebCryptoAdapter extends CryptoPort {
|
|
|
73
88
|
* @returns {Promise<Buffer>}
|
|
74
89
|
*/
|
|
75
90
|
async decryptBuffer(buffer, key, meta) {
|
|
91
|
+
this._validateKey(key);
|
|
76
92
|
const nonce = this.#fromBase64(meta.nonce);
|
|
77
93
|
const tag = this.#fromBase64(meta.tag);
|
|
78
94
|
const cryptoKey = await this.#importKey(key);
|
|
@@ -104,49 +120,61 @@ export default class WebCryptoAdapter extends CryptoPort {
|
|
|
104
120
|
this._validateKey(key);
|
|
105
121
|
const nonce = this.randomBytes(12);
|
|
106
122
|
const cryptoKeyPromise = this.#importKey(key);
|
|
123
|
+
const maxBuf = this.#maxEncryptionBufferSize;
|
|
124
|
+
const state = { /** @type {Uint8Array|null} */ tag: null, consumed: false };
|
|
107
125
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
const
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
126
|
+
const encrypt = WebCryptoAdapter.#makeEncryptGenerator({ cryptoKeyPromise, nonce, maxBuf, state });
|
|
127
|
+
|
|
128
|
+
const finalize = () => {
|
|
129
|
+
if (!state.consumed) {
|
|
130
|
+
throw new CasError('Cannot finalize before the encrypt stream is fully consumed', 'STREAM_NOT_CONSUMED');
|
|
131
|
+
}
|
|
132
|
+
return this._buildMeta(this.#toBase64(nonce), this.#toBase64(/** @type {Uint8Array} */ (state.tag)));
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
return { encrypt, finalize };
|
|
136
|
+
}
|
|
114
137
|
|
|
115
|
-
|
|
116
|
-
|
|
138
|
+
/**
|
|
139
|
+
* Builds the encrypt async generator for createEncryptionStream.
|
|
140
|
+
*
|
|
141
|
+
* A static method is used (rather than closures) because `async function*`
|
|
142
|
+
* cannot be an arrow function — `this` binding would be lost. The `state`
|
|
143
|
+
* object bridges mutable data between the generator and `finalize()`.
|
|
144
|
+
*
|
|
145
|
+
* @param {{ cryptoKeyPromise: Promise<CryptoKey>, nonce: Buffer|Uint8Array, maxBuf: number, state: { tag: Uint8Array|null, consumed: boolean } }} ctx
|
|
146
|
+
* @returns {(source: AsyncIterable<Buffer>) => AsyncGenerator<Buffer>}
|
|
147
|
+
*/
|
|
148
|
+
static #makeEncryptGenerator({ cryptoKeyPromise, nonce, maxBuf, state }) {
|
|
149
|
+
return async function* (source) {
|
|
150
|
+
/** @type {Buffer[]} */
|
|
151
|
+
const chunks = [];
|
|
152
|
+
let accumulatedBytes = 0;
|
|
117
153
|
for await (const chunk of source) {
|
|
154
|
+
accumulatedBytes += chunk.length;
|
|
155
|
+
if (accumulatedBytes > maxBuf) {
|
|
156
|
+
throw new CasError(
|
|
157
|
+
`Streaming encryption buffered ${accumulatedBytes} bytes (limit: ${maxBuf}). ` +
|
|
158
|
+
'Web Crypto AES-GCM buffers all data. Use Node.js/Bun or store without encryption for large files.',
|
|
159
|
+
'ENCRYPTION_BUFFER_EXCEEDED',
|
|
160
|
+
{ accumulated: accumulatedBytes, limit: maxBuf },
|
|
161
|
+
);
|
|
162
|
+
}
|
|
118
163
|
chunks.push(chunk);
|
|
119
164
|
}
|
|
120
|
-
|
|
121
165
|
const buffer = Buffer.concat(chunks);
|
|
122
166
|
const cryptoKey = await cryptoKeyPromise;
|
|
123
167
|
const encrypted = await globalThis.crypto.subtle.encrypt(
|
|
124
168
|
// @ts-ignore -- Uint8Array satisfies BufferSource at runtime
|
|
125
169
|
{ name: 'AES-GCM', iv: /** @type {Uint8Array} */ (nonce) },
|
|
126
|
-
cryptoKey,
|
|
127
|
-
buffer
|
|
170
|
+
cryptoKey, buffer,
|
|
128
171
|
);
|
|
129
|
-
|
|
130
172
|
const fullBuffer = new Uint8Array(encrypted);
|
|
131
173
|
const tagLength = 16;
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
yield Buffer.from(ciphertext);
|
|
174
|
+
state.tag = fullBuffer.slice(-tagLength);
|
|
175
|
+
state.consumed = true;
|
|
176
|
+
yield Buffer.from(fullBuffer.slice(0, -tagLength));
|
|
137
177
|
};
|
|
138
|
-
|
|
139
|
-
const finalize = () => {
|
|
140
|
-
if (!streamConsumed) {
|
|
141
|
-
throw new CasError(
|
|
142
|
-
'Cannot finalize before the encrypt stream is fully consumed',
|
|
143
|
-
'STREAM_NOT_CONSUMED',
|
|
144
|
-
);
|
|
145
|
-
}
|
|
146
|
-
return this._buildMeta(this.#toBase64(nonce), this.#toBase64(/** @type {Uint8Array} */ (finalTag)));
|
|
147
|
-
};
|
|
148
|
-
|
|
149
|
-
return { encrypt, finalize };
|
|
150
178
|
}
|
|
151
179
|
|
|
152
180
|
/**
|
|
@@ -277,6 +277,11 @@ export default class CdcChunker extends ChunkingPort {
|
|
|
277
277
|
`targetChunkSize (${targetChunkSize}) must be in [${minChunkSize}, ${maxChunkSize}]`,
|
|
278
278
|
);
|
|
279
279
|
}
|
|
280
|
+
if (maxChunkSize > 100 * 1024 * 1024) {
|
|
281
|
+
throw new RangeError(
|
|
282
|
+
`maxChunkSize must not exceed 104857600 bytes (100 MiB), got ${maxChunkSize}`,
|
|
283
|
+
);
|
|
284
|
+
}
|
|
280
285
|
|
|
281
286
|
this.#minChunkSize = minChunkSize;
|
|
282
287
|
this.#maxChunkSize = maxChunkSize;
|
|
@@ -17,6 +17,14 @@ export default class FixedChunker extends ChunkingPort {
|
|
|
17
17
|
*/
|
|
18
18
|
constructor({ chunkSize = 262144 } = {}) {
|
|
19
19
|
super();
|
|
20
|
+
if (!Number.isInteger(chunkSize) || chunkSize < 1) {
|
|
21
|
+
throw new RangeError(`chunkSize must be a positive integer, got ${chunkSize}`);
|
|
22
|
+
}
|
|
23
|
+
if (chunkSize > 100 * 1024 * 1024) {
|
|
24
|
+
throw new RangeError(
|
|
25
|
+
`Chunk size must not exceed 104857600 bytes (100 MiB), got ${chunkSize}`,
|
|
26
|
+
);
|
|
27
|
+
}
|
|
20
28
|
this.#chunkSize = chunkSize;
|
|
21
29
|
}
|
|
22
30
|
|
|
@@ -36,18 +44,26 @@ export default class FixedChunker extends ChunkingPort {
|
|
|
36
44
|
* @yields {Buffer}
|
|
37
45
|
*/
|
|
38
46
|
async *chunk(source) {
|
|
39
|
-
|
|
47
|
+
const cs = this.#chunkSize;
|
|
48
|
+
const buf = Buffer.allocUnsafe(cs);
|
|
49
|
+
let offset = 0;
|
|
40
50
|
|
|
41
51
|
for await (const data of source) {
|
|
42
|
-
|
|
43
|
-
while (
|
|
44
|
-
|
|
45
|
-
|
|
52
|
+
let srcPos = 0;
|
|
53
|
+
while (srcPos < data.length) {
|
|
54
|
+
const n = Math.min(cs - offset, data.length - srcPos);
|
|
55
|
+
data.copy(buf, offset, srcPos, srcPos + n);
|
|
56
|
+
offset += n;
|
|
57
|
+
srcPos += n;
|
|
58
|
+
if (offset === cs) {
|
|
59
|
+
yield Buffer.from(buf);
|
|
60
|
+
offset = 0;
|
|
61
|
+
}
|
|
46
62
|
}
|
|
47
63
|
}
|
|
48
64
|
|
|
49
|
-
if (
|
|
50
|
-
yield
|
|
65
|
+
if (offset > 0) {
|
|
66
|
+
yield Buffer.from(buf.subarray(0, offset));
|
|
51
67
|
}
|
|
52
68
|
}
|
|
53
69
|
}
|