@git-stunts/git-cas 1.6.2 → 3.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.
- package/CHANGELOG.md +75 -1
- package/README.md +56 -8
- package/bin/git-cas.js +205 -38
- package/index.d.ts +149 -4
- package/index.js +112 -12
- package/package.json +1 -1
- package/src/domain/schemas/ManifestSchema.d.ts +27 -0
- package/src/domain/schemas/ManifestSchema.js +27 -0
- package/src/domain/services/CasService.d.ts +29 -1
- package/src/domain/services/CasService.js +253 -30
- package/src/domain/services/VaultService.js +445 -0
- package/src/domain/value-objects/Manifest.d.ts +30 -0
- package/src/domain/value-objects/Manifest.js +6 -0
- package/src/infrastructure/adapters/BunCryptoAdapter.js +35 -2
- package/src/infrastructure/adapters/GitPersistenceAdapter.js +11 -11
- package/src/infrastructure/adapters/GitRefAdapter.js +67 -0
- package/src/infrastructure/adapters/NodeCryptoAdapter.js +40 -1
- package/src/infrastructure/adapters/WebCryptoAdapter.js +58 -0
- package/src/ports/CryptoPort.js +17 -0
- package/src/ports/GitRefPort.js +48 -0
|
@@ -4,9 +4,14 @@
|
|
|
4
4
|
* @module
|
|
5
5
|
*/
|
|
6
6
|
import { EventEmitter } from 'node:events';
|
|
7
|
+
import { gunzip, createGzip } from 'node:zlib';
|
|
8
|
+
import { Readable } from 'node:stream';
|
|
9
|
+
import { promisify } from 'node:util';
|
|
7
10
|
import Manifest from '../value-objects/Manifest.js';
|
|
8
11
|
import CasError from '../errors/CasError.js';
|
|
9
12
|
|
|
13
|
+
const gunzipAsync = promisify(gunzip);
|
|
14
|
+
|
|
10
15
|
/**
|
|
11
16
|
* Domain service for Content Addressable Storage operations.
|
|
12
17
|
*
|
|
@@ -29,8 +34,9 @@ export default class CasService extends EventEmitter {
|
|
|
29
34
|
* @param {import('../../ports/CodecPort.js').default} options.codec
|
|
30
35
|
* @param {import('../../ports/CryptoPort.js').default} options.crypto
|
|
31
36
|
* @param {number} [options.chunkSize=262144] - 256 KiB
|
|
37
|
+
* @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
|
|
32
38
|
*/
|
|
33
|
-
constructor({ persistence, codec, crypto, chunkSize = 256 * 1024 }) {
|
|
39
|
+
constructor({ persistence, codec, crypto, chunkSize = 256 * 1024, merkleThreshold = 1000 }) {
|
|
34
40
|
super();
|
|
35
41
|
if (chunkSize < 1024) {
|
|
36
42
|
throw new Error('Chunk size must be at least 1024 bytes');
|
|
@@ -39,6 +45,10 @@ export default class CasService extends EventEmitter {
|
|
|
39
45
|
this.codec = codec;
|
|
40
46
|
this.crypto = crypto;
|
|
41
47
|
this.chunkSize = chunkSize;
|
|
48
|
+
if (!Number.isInteger(merkleThreshold) || merkleThreshold < 1) {
|
|
49
|
+
throw new Error('Merkle threshold must be a positive integer');
|
|
50
|
+
}
|
|
51
|
+
this.merkleThreshold = merkleThreshold;
|
|
42
52
|
}
|
|
43
53
|
|
|
44
54
|
/**
|
|
@@ -159,6 +169,47 @@ export default class CasService extends EventEmitter {
|
|
|
159
169
|
}
|
|
160
170
|
}
|
|
161
171
|
|
|
172
|
+
/**
|
|
173
|
+
* Wraps an async iterable through gzip compression.
|
|
174
|
+
* @private
|
|
175
|
+
* @param {AsyncIterable<Buffer>} source
|
|
176
|
+
* @returns {AsyncIterable<Buffer>}
|
|
177
|
+
*/
|
|
178
|
+
async *_compressStream(source) {
|
|
179
|
+
const gz = createGzip();
|
|
180
|
+
const input = Readable.from(source);
|
|
181
|
+
const compressed = input.pipe(gz);
|
|
182
|
+
for await (const chunk of compressed) {
|
|
183
|
+
yield chunk;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Validates that passphrase and encryptionKey are not both provided.
|
|
189
|
+
* @private
|
|
190
|
+
*/
|
|
191
|
+
_validateKeySourceExclusive(encryptionKey, passphrase) {
|
|
192
|
+
if (passphrase && encryptionKey) {
|
|
193
|
+
throw new CasError(
|
|
194
|
+
'Provide either encryptionKey or passphrase, not both',
|
|
195
|
+
'INVALID_OPTIONS',
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Validates and normalizes compression options.
|
|
202
|
+
* @private
|
|
203
|
+
*/
|
|
204
|
+
_validateCompression(compression) {
|
|
205
|
+
if (compression?.algorithm && compression.algorithm !== 'gzip') {
|
|
206
|
+
throw new CasError(
|
|
207
|
+
`Unsupported compression algorithm: ${compression.algorithm}`,
|
|
208
|
+
'INVALID_OPTIONS',
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
162
213
|
/**
|
|
163
214
|
* Chunks an async iterable source and stores it in Git.
|
|
164
215
|
*
|
|
@@ -170,26 +221,44 @@ export default class CasService extends EventEmitter {
|
|
|
170
221
|
* @param {string} options.slug
|
|
171
222
|
* @param {string} options.filename
|
|
172
223
|
* @param {Buffer} [options.encryptionKey]
|
|
224
|
+
* @param {string} [options.passphrase] - Derive encryption key from passphrase instead.
|
|
225
|
+
* @param {Object} [options.kdfOptions] - KDF options when using passphrase.
|
|
226
|
+
* @param {{ algorithm: 'gzip' }} [options.compression] - Enable compression.
|
|
173
227
|
* @returns {Promise<import('../value-objects/Manifest.js').default>}
|
|
174
228
|
*/
|
|
175
|
-
async store({ source, slug, filename, encryptionKey }) {
|
|
229
|
+
async store({ source, slug, filename, encryptionKey, passphrase, kdfOptions, compression }) {
|
|
230
|
+
this._validateKeySourceExclusive(encryptionKey, passphrase);
|
|
231
|
+
this._validateCompression(compression);
|
|
232
|
+
|
|
233
|
+
let kdfParams;
|
|
234
|
+
if (passphrase) {
|
|
235
|
+
const derived = await this.deriveKey({ passphrase, ...kdfOptions });
|
|
236
|
+
encryptionKey = derived.key;
|
|
237
|
+
kdfParams = derived.params;
|
|
238
|
+
}
|
|
239
|
+
|
|
176
240
|
if (encryptionKey) {
|
|
177
241
|
this._validateKey(encryptionKey);
|
|
178
242
|
}
|
|
179
243
|
|
|
180
|
-
const manifestData = {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
244
|
+
const manifestData = { slug, filename, size: 0, chunks: [] };
|
|
245
|
+
|
|
246
|
+
let processedSource = source;
|
|
247
|
+
if (compression) {
|
|
248
|
+
processedSource = this._compressStream(processedSource);
|
|
249
|
+
manifestData.compression = { algorithm: 'gzip' };
|
|
250
|
+
}
|
|
186
251
|
|
|
187
252
|
if (encryptionKey) {
|
|
188
253
|
const { encrypt, finalize } = this.crypto.createEncryptionStream(encryptionKey);
|
|
189
|
-
await this._chunkAndStore(encrypt(
|
|
190
|
-
|
|
254
|
+
await this._chunkAndStore(encrypt(processedSource), manifestData);
|
|
255
|
+
const encMeta = finalize();
|
|
256
|
+
if (kdfParams) {
|
|
257
|
+
encMeta.kdf = kdfParams;
|
|
258
|
+
}
|
|
259
|
+
manifestData.encryption = encMeta;
|
|
191
260
|
} else {
|
|
192
|
-
await this._chunkAndStore(
|
|
261
|
+
await this._chunkAndStore(processedSource, manifestData);
|
|
193
262
|
}
|
|
194
263
|
|
|
195
264
|
const manifest = new Manifest(manifestData);
|
|
@@ -210,12 +279,70 @@ export default class CasService extends EventEmitter {
|
|
|
210
279
|
* @returns {Promise<string>} Git OID of the created tree.
|
|
211
280
|
*/
|
|
212
281
|
async createTree({ manifest }) {
|
|
282
|
+
const chunks = manifest.chunks;
|
|
283
|
+
|
|
284
|
+
if (chunks.length > this.merkleThreshold) {
|
|
285
|
+
return await this._createMerkleTree({ manifest });
|
|
286
|
+
}
|
|
287
|
+
|
|
213
288
|
const serializedManifest = this.codec.encode(manifest.toJSON());
|
|
214
289
|
const manifestOid = await this.persistence.writeBlob(serializedManifest);
|
|
215
290
|
|
|
216
291
|
const treeEntries = [
|
|
217
292
|
`100644 blob ${manifestOid}\tmanifest.${this.codec.extension}`,
|
|
218
|
-
...
|
|
293
|
+
...chunks.map((c) => `100644 blob ${c.blob}\t${c.digest}`),
|
|
294
|
+
];
|
|
295
|
+
|
|
296
|
+
return await this.persistence.writeTree(treeEntries);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Creates a Merkle tree by splitting chunks into sub-manifests.
|
|
301
|
+
* @private
|
|
302
|
+
* @param {Object} options
|
|
303
|
+
* @param {import('../value-objects/Manifest.js').default} options.manifest
|
|
304
|
+
* @returns {Promise<string>} Git tree OID.
|
|
305
|
+
*/
|
|
306
|
+
async _createMerkleTree({ manifest }) {
|
|
307
|
+
const chunks = [...manifest.chunks];
|
|
308
|
+
const subManifestRefs = [];
|
|
309
|
+
const chunkBlobEntries = [];
|
|
310
|
+
|
|
311
|
+
for (let i = 0; i < chunks.length; i += this.merkleThreshold) {
|
|
312
|
+
const group = chunks.slice(i, i + this.merkleThreshold);
|
|
313
|
+
const subManifestData = { chunks: group.map((c) => ({ index: c.index, size: c.size, digest: c.digest, blob: c.blob })) };
|
|
314
|
+
const serialized = this.codec.encode(subManifestData);
|
|
315
|
+
const oid = await this.persistence.writeBlob(serialized);
|
|
316
|
+
|
|
317
|
+
subManifestRefs.push({
|
|
318
|
+
oid,
|
|
319
|
+
chunkCount: group.length,
|
|
320
|
+
startIndex: i,
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
for (const c of group) {
|
|
324
|
+
chunkBlobEntries.push(`100644 blob ${c.blob}\t${c.digest}`);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const rootManifestData = {
|
|
329
|
+
...manifest.toJSON(),
|
|
330
|
+
version: 2,
|
|
331
|
+
chunks: [],
|
|
332
|
+
subManifests: subManifestRefs,
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
const serializedRoot = this.codec.encode(rootManifestData);
|
|
336
|
+
const rootOid = await this.persistence.writeBlob(serializedRoot);
|
|
337
|
+
|
|
338
|
+
const subManifestEntries = subManifestRefs.map(
|
|
339
|
+
(ref, idx) => `100644 blob ${ref.oid}\tsub-manifest-${idx}.${this.codec.extension}`,
|
|
340
|
+
);
|
|
341
|
+
|
|
342
|
+
const treeEntries = [
|
|
343
|
+
`100644 blob ${rootOid}\tmanifest.${this.codec.extension}`,
|
|
344
|
+
...subManifestEntries,
|
|
345
|
+
...chunkBlobEntries,
|
|
219
346
|
];
|
|
220
347
|
|
|
221
348
|
return await this.persistence.writeTree(treeEntries);
|
|
@@ -250,6 +377,50 @@ export default class CasService extends EventEmitter {
|
|
|
250
377
|
return buffers;
|
|
251
378
|
}
|
|
252
379
|
|
|
380
|
+
/**
|
|
381
|
+
* Resolves the encryption key from a passphrase using KDF params from the manifest.
|
|
382
|
+
* @private
|
|
383
|
+
* @param {string} passphrase
|
|
384
|
+
* @param {Object} kdf - KDF params from manifest.encryption.kdf.
|
|
385
|
+
* @returns {Promise<Buffer>}
|
|
386
|
+
*/
|
|
387
|
+
async _resolveKeyFromPassphrase(passphrase, kdf) {
|
|
388
|
+
const { key } = await this.deriveKey({
|
|
389
|
+
passphrase,
|
|
390
|
+
salt: Buffer.from(kdf.salt, 'base64'),
|
|
391
|
+
algorithm: kdf.algorithm,
|
|
392
|
+
iterations: kdf.iterations,
|
|
393
|
+
cost: kdf.cost,
|
|
394
|
+
blockSize: kdf.blockSize,
|
|
395
|
+
parallelization: kdf.parallelization,
|
|
396
|
+
});
|
|
397
|
+
return key;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Resolves the encryption key from passphrase or validates the provided key.
|
|
402
|
+
* @private
|
|
403
|
+
*/
|
|
404
|
+
async _resolveEncryptionKey(manifest, encryptionKey, passphrase) {
|
|
405
|
+
this._validateKeySourceExclusive(encryptionKey, passphrase);
|
|
406
|
+
|
|
407
|
+
if (passphrase) {
|
|
408
|
+
if (manifest.encryption?.kdf) {
|
|
409
|
+
return this._resolveKeyFromPassphrase(passphrase, manifest.encryption.kdf);
|
|
410
|
+
}
|
|
411
|
+
throw new CasError(
|
|
412
|
+
'Manifest was not stored with passphrase-based encryption; provide encryptionKey instead',
|
|
413
|
+
'MISSING_KEY',
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
if (encryptionKey) {
|
|
417
|
+
this._validateKey(encryptionKey);
|
|
418
|
+
} else if (manifest.encryption?.encrypted) {
|
|
419
|
+
throw new CasError('Encryption key required to restore encrypted content', 'MISSING_KEY');
|
|
420
|
+
}
|
|
421
|
+
return encryptionKey;
|
|
422
|
+
}
|
|
423
|
+
|
|
253
424
|
/**
|
|
254
425
|
* Restores a file from its manifest by reading and reassembling chunks.
|
|
255
426
|
*
|
|
@@ -259,35 +430,31 @@ export default class CasService extends EventEmitter {
|
|
|
259
430
|
* @param {Object} options
|
|
260
431
|
* @param {import('../value-objects/Manifest.js').default} options.manifest - The file manifest.
|
|
261
432
|
* @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
|
|
433
|
+
* @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
|
|
262
434
|
* @returns {Promise<{ buffer: Buffer, bytesWritten: number }>}
|
|
263
435
|
* @throws {CasError} MISSING_KEY if manifest is encrypted but no key is provided.
|
|
264
436
|
* @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
|
|
265
437
|
*/
|
|
266
|
-
async restore({ manifest, encryptionKey }) {
|
|
267
|
-
|
|
268
|
-
this._validateKey(encryptionKey);
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
if (manifest.encryption?.encrypted && !encryptionKey) {
|
|
272
|
-
throw new CasError(
|
|
273
|
-
'Encryption key required to restore encrypted content',
|
|
274
|
-
'MISSING_KEY',
|
|
275
|
-
);
|
|
276
|
-
}
|
|
438
|
+
async restore({ manifest, encryptionKey, passphrase }) {
|
|
439
|
+
const key = await this._resolveEncryptionKey(manifest, encryptionKey, passphrase);
|
|
277
440
|
|
|
278
441
|
if (manifest.chunks.length === 0) {
|
|
279
442
|
return { buffer: Buffer.alloc(0), bytesWritten: 0 };
|
|
280
443
|
}
|
|
281
444
|
|
|
282
|
-
|
|
283
|
-
let buffer = Buffer.concat(chunks);
|
|
445
|
+
let buffer = Buffer.concat(await this._readAndVerifyChunks(manifest.chunks));
|
|
284
446
|
|
|
285
447
|
if (manifest.encryption?.encrypted) {
|
|
286
|
-
buffer = await this.decrypt({
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
448
|
+
buffer = await this.decrypt({ buffer, key, meta: manifest.encryption });
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
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 });
|
|
457
|
+
}
|
|
291
458
|
}
|
|
292
459
|
|
|
293
460
|
this.emit('file:restored', {
|
|
@@ -342,9 +509,48 @@ export default class CasService extends EventEmitter {
|
|
|
342
509
|
}
|
|
343
510
|
|
|
344
511
|
const decoded = this.codec.decode(blob);
|
|
512
|
+
|
|
513
|
+
if (decoded.version === 2 && decoded.subManifests?.length > 0) {
|
|
514
|
+
decoded.chunks = await this._resolveSubManifests(decoded.subManifests, treeOid);
|
|
515
|
+
}
|
|
516
|
+
|
|
345
517
|
return new Manifest(decoded);
|
|
346
518
|
}
|
|
347
519
|
|
|
520
|
+
/**
|
|
521
|
+
* Reads and flattens sub-manifest blobs into a single chunk array.
|
|
522
|
+
* @private
|
|
523
|
+
* @param {Array<{ oid: string }>} subManifests - Sub-manifest references.
|
|
524
|
+
* @param {string} treeOid - Parent tree OID (for error context).
|
|
525
|
+
* @returns {Promise<Array>} Flattened chunk entries.
|
|
526
|
+
*/
|
|
527
|
+
async _resolveSubManifests(subManifests, treeOid) {
|
|
528
|
+
const allChunks = [];
|
|
529
|
+
for (const ref of subManifests) {
|
|
530
|
+
const subBlob = await this._readSubManifestBlob(ref.oid, treeOid);
|
|
531
|
+
const subDecoded = this.codec.decode(subBlob);
|
|
532
|
+
allChunks.push(...subDecoded.chunks);
|
|
533
|
+
}
|
|
534
|
+
return allChunks;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Reads a sub-manifest blob, wrapping errors as GIT_ERROR.
|
|
539
|
+
* @private
|
|
540
|
+
*/
|
|
541
|
+
async _readSubManifestBlob(oid, treeOid) {
|
|
542
|
+
try {
|
|
543
|
+
return await this.persistence.readBlob(oid);
|
|
544
|
+
} catch (err) {
|
|
545
|
+
if (err instanceof CasError) { throw err; }
|
|
546
|
+
throw new CasError(
|
|
547
|
+
`Failed to read sub-manifest blob ${oid}: ${err.message}`,
|
|
548
|
+
'GIT_ERROR',
|
|
549
|
+
{ treeOid, subManifestOid: oid, originalError: err },
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
348
554
|
/**
|
|
349
555
|
* Returns deletion metadata for an asset stored in a Git tree.
|
|
350
556
|
* Does not perform any destructive Git operations.
|
|
@@ -386,6 +592,23 @@ export default class CasService extends EventEmitter {
|
|
|
386
592
|
return { referenced, total };
|
|
387
593
|
}
|
|
388
594
|
|
|
595
|
+
/**
|
|
596
|
+
* Derives an encryption key from a passphrase using PBKDF2 or scrypt.
|
|
597
|
+
* @param {Object} options
|
|
598
|
+
* @param {string} options.passphrase - The passphrase to derive a key from.
|
|
599
|
+
* @param {Buffer} [options.salt] - Salt (random if omitted).
|
|
600
|
+
* @param {'pbkdf2'|'scrypt'} [options.algorithm='pbkdf2'] - KDF algorithm.
|
|
601
|
+
* @param {number} [options.iterations] - PBKDF2 iterations.
|
|
602
|
+
* @param {number} [options.cost] - scrypt cost (N).
|
|
603
|
+
* @param {number} [options.blockSize] - scrypt block size (r).
|
|
604
|
+
* @param {number} [options.parallelization] - scrypt parallelization (p).
|
|
605
|
+
* @param {number} [options.keyLength=32] - Derived key length.
|
|
606
|
+
* @returns {Promise<{ key: Buffer, salt: Buffer, params: Object }>}
|
|
607
|
+
*/
|
|
608
|
+
async deriveKey(options) {
|
|
609
|
+
return await this.crypto.deriveKey(options);
|
|
610
|
+
}
|
|
611
|
+
|
|
389
612
|
/**
|
|
390
613
|
* Verifies the integrity of a stored file by re-hashing its chunks.
|
|
391
614
|
* @param {import('../value-objects/Manifest.js').default} manifest
|