@git-stunts/git-cas 4.0.1 → 5.1.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 +47 -0
- package/README.md +15 -0
- package/bin/actions.js +5 -0
- package/bin/git-cas.js +137 -26
- package/bin/ui/progress.js +4 -4
- package/index.d.ts +54 -2
- package/index.js +85 -2
- package/package.json +1 -1
- package/src/domain/schemas/ManifestSchema.d.ts +35 -0
- package/src/domain/schemas/ManifestSchema.js +35 -0
- package/src/domain/services/CasService.d.ts +15 -0
- package/src/domain/services/CasService.js +321 -66
- package/src/domain/value-objects/Manifest.d.ts +10 -0
- package/src/domain/value-objects/Manifest.js +7 -1
- package/src/infrastructure/chunkers/CdcChunker.js +339 -0
- package/src/infrastructure/chunkers/FixedChunker.js +49 -0
- package/src/ports/ChunkingPort.js +45 -0
|
@@ -24,6 +24,15 @@ export const KdfSchema = z.object({
|
|
|
24
24
|
keyLength: z.number().int().positive().default(32),
|
|
25
25
|
});
|
|
26
26
|
|
|
27
|
+
/** Validates a single recipient entry in an envelope-encrypted manifest. */
|
|
28
|
+
export const RecipientSchema = z.object({
|
|
29
|
+
label: z.string().min(1),
|
|
30
|
+
wrappedDek: z.string().min(1),
|
|
31
|
+
nonce: z.string().min(1),
|
|
32
|
+
tag: z.string().min(1),
|
|
33
|
+
kekType: z.string().optional(),
|
|
34
|
+
});
|
|
35
|
+
|
|
27
36
|
/** Validates the encryption metadata attached to an encrypted manifest. */
|
|
28
37
|
export const EncryptionSchema = z.object({
|
|
29
38
|
algorithm: z.string(),
|
|
@@ -31,6 +40,7 @@ export const EncryptionSchema = z.object({
|
|
|
31
40
|
tag: z.string(),
|
|
32
41
|
encrypted: z.boolean().default(true),
|
|
33
42
|
kdf: KdfSchema.optional(),
|
|
43
|
+
recipients: z.array(RecipientSchema).min(1).optional(),
|
|
34
44
|
});
|
|
35
45
|
|
|
36
46
|
/** Validates compression metadata. */
|
|
@@ -38,6 +48,30 @@ export const CompressionSchema = z.object({
|
|
|
38
48
|
algorithm: z.enum(['gzip']),
|
|
39
49
|
});
|
|
40
50
|
|
|
51
|
+
/** Validates fixed-size chunking parameters. */
|
|
52
|
+
export const FixedChunkingSchema = z.object({
|
|
53
|
+
strategy: z.literal('fixed'),
|
|
54
|
+
params: z.object({
|
|
55
|
+
chunkSize: z.number().int().positive(),
|
|
56
|
+
}),
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
/** Validates content-defined chunking (CDC) parameters. */
|
|
60
|
+
export const CdcChunkingSchema = z.object({
|
|
61
|
+
strategy: z.literal('cdc'),
|
|
62
|
+
params: z.object({
|
|
63
|
+
target: z.number().int().positive(),
|
|
64
|
+
min: z.number().int().positive(),
|
|
65
|
+
max: z.number().int().positive(),
|
|
66
|
+
}),
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
/** Validates chunking metadata (fixed or CDC). */
|
|
70
|
+
export const ChunkingSchema = z.discriminatedUnion('strategy', [
|
|
71
|
+
FixedChunkingSchema,
|
|
72
|
+
CdcChunkingSchema,
|
|
73
|
+
]);
|
|
74
|
+
|
|
41
75
|
/** Validates a sub-manifest reference in a v2 Merkle manifest. */
|
|
42
76
|
export const SubManifestRefSchema = z.object({
|
|
43
77
|
oid: z.string().min(1),
|
|
@@ -54,5 +88,6 @@ export const ManifestSchema = z.object({
|
|
|
54
88
|
chunks: z.array(ChunkSchema),
|
|
55
89
|
encryption: EncryptionSchema.optional(),
|
|
56
90
|
compression: CompressionSchema.optional(),
|
|
91
|
+
chunking: ChunkingSchema.optional(),
|
|
57
92
|
subManifests: z.array(SubManifestRefSchema).optional(),
|
|
58
93
|
});
|
|
@@ -112,6 +112,7 @@ export default class CasService {
|
|
|
112
112
|
passphrase?: string;
|
|
113
113
|
kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
|
|
114
114
|
compression?: { algorithm: "gzip" };
|
|
115
|
+
recipients?: Array<{ label: string; key: Buffer }>;
|
|
115
116
|
}): Promise<Manifest>;
|
|
116
117
|
|
|
117
118
|
createTree(options: { manifest: Manifest }): Promise<string>;
|
|
@@ -138,6 +139,20 @@ export default class CasService {
|
|
|
138
139
|
treeOids: string[];
|
|
139
140
|
}): Promise<{ referenced: Set<string>; total: number }>;
|
|
140
141
|
|
|
142
|
+
addRecipient(options: {
|
|
143
|
+
manifest: Manifest;
|
|
144
|
+
existingKey: Buffer;
|
|
145
|
+
newRecipientKey: Buffer;
|
|
146
|
+
label: string;
|
|
147
|
+
}): Promise<Manifest>;
|
|
148
|
+
|
|
149
|
+
removeRecipient(options: {
|
|
150
|
+
manifest: Manifest;
|
|
151
|
+
label: string;
|
|
152
|
+
}): Promise<Manifest>;
|
|
153
|
+
|
|
154
|
+
listRecipients(manifest: Manifest): string[];
|
|
155
|
+
|
|
141
156
|
verifyIntegrity(manifest: Manifest): Promise<boolean>;
|
|
142
157
|
|
|
143
158
|
deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
|
|
@@ -9,6 +9,7 @@ import { promisify } from 'node:util';
|
|
|
9
9
|
import Manifest from '../value-objects/Manifest.js';
|
|
10
10
|
import CasError from '../errors/CasError.js';
|
|
11
11
|
import Semaphore from './Semaphore.js';
|
|
12
|
+
import FixedChunker from '../../infrastructure/chunkers/FixedChunker.js';
|
|
12
13
|
|
|
13
14
|
const gunzipAsync = promisify(gunzip);
|
|
14
15
|
|
|
@@ -28,8 +29,9 @@ export default class CasService {
|
|
|
28
29
|
* @param {number} [options.chunkSize=262144] - 256 KiB
|
|
29
30
|
* @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
|
|
30
31
|
* @param {number} [options.concurrency=1] - Maximum parallel chunk I/O operations.
|
|
32
|
+
* @param {import('../../ports/ChunkingPort.js').default} [options.chunker] - Chunking strategy (default FixedChunker).
|
|
31
33
|
*/
|
|
32
|
-
constructor({ persistence, codec, crypto, observability, chunkSize = 256 * 1024, merkleThreshold = 1000, concurrency = 1 }) {
|
|
34
|
+
constructor({ persistence, codec, crypto, observability, chunkSize = 256 * 1024, merkleThreshold = 1000, concurrency = 1, chunker }) {
|
|
33
35
|
CasService._validateObservability(observability);
|
|
34
36
|
if (chunkSize < 1024) {
|
|
35
37
|
throw new Error('Chunk size must be at least 1024 bytes');
|
|
@@ -39,6 +41,8 @@ export default class CasService {
|
|
|
39
41
|
this.crypto = crypto;
|
|
40
42
|
this.observability = observability;
|
|
41
43
|
this.chunkSize = chunkSize;
|
|
44
|
+
/** @type {import('../../ports/ChunkingPort.js').default} */
|
|
45
|
+
this.chunker = chunker || new FixedChunker({ chunkSize });
|
|
42
46
|
if (!Number.isInteger(merkleThreshold) || merkleThreshold < 1) {
|
|
43
47
|
throw new Error('Merkle threshold must be a positive integer');
|
|
44
48
|
}
|
|
@@ -90,14 +94,14 @@ export default class CasService {
|
|
|
90
94
|
}
|
|
91
95
|
|
|
92
96
|
/**
|
|
93
|
-
* Reads an async iterable source, splits it into
|
|
97
|
+
* Reads an async iterable source, splits it into chunks via the configured
|
|
98
|
+
* chunker, and stores each chunk in Git.
|
|
94
99
|
* @private
|
|
95
100
|
* @param {AsyncIterable<Buffer>} source - The data source to chunk.
|
|
96
101
|
* @param {Object} manifestData - Mutable manifest accumulator.
|
|
97
102
|
* @throws {CasError} STREAM_ERROR if the source stream fails.
|
|
98
103
|
*/
|
|
99
104
|
async _chunkAndStore(source, manifestData) {
|
|
100
|
-
let buffer = Buffer.alloc(0);
|
|
101
105
|
const sem = new Semaphore(this.concurrency);
|
|
102
106
|
const pending = [];
|
|
103
107
|
let nextIndex = 0;
|
|
@@ -114,12 +118,8 @@ export default class CasService {
|
|
|
114
118
|
};
|
|
115
119
|
|
|
116
120
|
try {
|
|
117
|
-
for await (const chunk of source) {
|
|
118
|
-
|
|
119
|
-
while (buffer.length >= this.chunkSize) {
|
|
120
|
-
launchWrite(buffer.slice(0, this.chunkSize), nextIndex++);
|
|
121
|
-
buffer = buffer.slice(this.chunkSize);
|
|
122
|
-
}
|
|
121
|
+
for await (const chunk of this.chunker.chunk(source)) {
|
|
122
|
+
launchWrite(chunk, nextIndex++);
|
|
123
123
|
}
|
|
124
124
|
} catch (err) {
|
|
125
125
|
await Promise.allSettled(pending);
|
|
@@ -134,10 +134,6 @@ export default class CasService {
|
|
|
134
134
|
throw casErr;
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
-
if (buffer.length > 0) {
|
|
138
|
-
launchWrite(buffer, nextIndex++);
|
|
139
|
-
}
|
|
140
|
-
|
|
141
137
|
const results = await Promise.all(pending);
|
|
142
138
|
results.sort((a, b) => a.index - b.index);
|
|
143
139
|
for (const entry of results) {
|
|
@@ -194,6 +190,116 @@ export default class CasService {
|
|
|
194
190
|
}
|
|
195
191
|
}
|
|
196
192
|
|
|
193
|
+
/**
|
|
194
|
+
* Wraps a DEK with a KEK using AES-256-GCM.
|
|
195
|
+
* @private
|
|
196
|
+
* @param {Buffer} dek - 32-byte data encryption key.
|
|
197
|
+
* @param {Buffer} kek - 32-byte key encryption key.
|
|
198
|
+
* @returns {Promise<{ wrappedDek: string, nonce: string, tag: string }>}
|
|
199
|
+
*/
|
|
200
|
+
async _wrapDek(dek, kek) {
|
|
201
|
+
const { buf, meta } = await this.crypto.encryptBuffer(dek, kek);
|
|
202
|
+
return {
|
|
203
|
+
wrappedDek: buf.toString('base64'),
|
|
204
|
+
nonce: meta.nonce,
|
|
205
|
+
tag: meta.tag,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Unwraps a DEK from a recipient entry using the given KEK.
|
|
211
|
+
* @private
|
|
212
|
+
* @param {{ wrappedDek: string, nonce: string, tag: string }} recipientEntry
|
|
213
|
+
* @param {Buffer} kek - 32-byte key encryption key.
|
|
214
|
+
* @returns {Promise<Buffer>} The unwrapped DEK.
|
|
215
|
+
* @throws {CasError} DEK_UNWRAP_FAILED if decryption fails.
|
|
216
|
+
*/
|
|
217
|
+
async _unwrapDek(recipientEntry, kek) {
|
|
218
|
+
try {
|
|
219
|
+
const ciphertext = Buffer.from(recipientEntry.wrappedDek, 'base64');
|
|
220
|
+
const meta = {
|
|
221
|
+
algorithm: 'aes-256-gcm',
|
|
222
|
+
nonce: recipientEntry.nonce,
|
|
223
|
+
tag: recipientEntry.tag,
|
|
224
|
+
encrypted: true,
|
|
225
|
+
};
|
|
226
|
+
return await this.crypto.decryptBuffer(ciphertext, kek, meta);
|
|
227
|
+
} catch (err) {
|
|
228
|
+
if (err instanceof CasError && err.code === 'DEK_UNWRAP_FAILED') { throw err; }
|
|
229
|
+
throw new CasError(
|
|
230
|
+
'Failed to unwrap DEK: authentication failed',
|
|
231
|
+
'DEK_UNWRAP_FAILED',
|
|
232
|
+
{ originalError: err },
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Resolves the decryption key from a manifest, handling both legacy and
|
|
239
|
+
* envelope (multi-recipient) encrypted manifests.
|
|
240
|
+
* @private
|
|
241
|
+
* @param {import('../value-objects/Manifest.js').default} manifest
|
|
242
|
+
* @param {Buffer} [encryptionKey]
|
|
243
|
+
* @param {string} [passphrase]
|
|
244
|
+
* @returns {Promise<Buffer|undefined>}
|
|
245
|
+
*/
|
|
246
|
+
async _resolveDecryptionKey(manifest, encryptionKey, passphrase) {
|
|
247
|
+
this._validateKeySourceExclusive(encryptionKey, passphrase);
|
|
248
|
+
|
|
249
|
+
const key = passphrase
|
|
250
|
+
? await this._resolvePassphraseForDecryption(manifest, passphrase)
|
|
251
|
+
: encryptionKey;
|
|
252
|
+
|
|
253
|
+
if (!key) {
|
|
254
|
+
if (manifest.encryption?.encrypted) {
|
|
255
|
+
throw new CasError('Encryption key required to restore encrypted content', 'MISSING_KEY');
|
|
256
|
+
}
|
|
257
|
+
return undefined;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
this.crypto._validateKey(key);
|
|
261
|
+
return await this._resolveKeyForRecipients(manifest, key);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Resolves passphrase to a key for decryption.
|
|
266
|
+
* @private
|
|
267
|
+
*/
|
|
268
|
+
async _resolvePassphraseForDecryption(manifest, passphrase) {
|
|
269
|
+
if (!manifest.encryption?.kdf) {
|
|
270
|
+
throw new CasError(
|
|
271
|
+
'Manifest was not stored with passphrase-based encryption; provide encryptionKey instead',
|
|
272
|
+
'MISSING_KEY',
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
return this._resolveKeyFromPassphrase(passphrase, manifest.encryption.kdf);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* If manifest uses envelope encryption, unwraps the DEK. Otherwise returns key directly.
|
|
280
|
+
* @private
|
|
281
|
+
*/
|
|
282
|
+
async _resolveKeyForRecipients(manifest, key) {
|
|
283
|
+
const recipients = manifest.encryption?.recipients;
|
|
284
|
+
if (!recipients || recipients.length === 0) {
|
|
285
|
+
return key;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
for (const entry of recipients) {
|
|
289
|
+
try {
|
|
290
|
+
return await this._unwrapDek(entry, key);
|
|
291
|
+
} catch (err) {
|
|
292
|
+
if (!(err instanceof CasError && err.code === 'DEK_UNWRAP_FAILED')) { throw err; }
|
|
293
|
+
// Not this recipient's KEK, try next
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
throw new CasError(
|
|
298
|
+
'No recipient entry could be unwrapped with the provided key',
|
|
299
|
+
'NO_MATCHING_RECIPIENT',
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
|
|
197
303
|
/**
|
|
198
304
|
* Validates that passphrase and encryptionKey are not both provided.
|
|
199
305
|
* @private
|
|
@@ -220,11 +326,29 @@ export default class CasService {
|
|
|
220
326
|
}
|
|
221
327
|
}
|
|
222
328
|
|
|
329
|
+
/**
|
|
330
|
+
* Validates that a chunking strategy is recognized.
|
|
331
|
+
* @param {Object} [chunking] - Chunking options from a manifest.
|
|
332
|
+
* @throws {CasError} INVALID_CHUNKING_STRATEGY if the strategy is unrecognized.
|
|
333
|
+
* @private
|
|
334
|
+
*/
|
|
335
|
+
_validateChunking(chunking) {
|
|
336
|
+
if (!chunking) { return; }
|
|
337
|
+
const validStrategies = ['fixed', 'cdc'];
|
|
338
|
+
if (!validStrategies.includes(chunking.strategy)) {
|
|
339
|
+
throw new CasError(
|
|
340
|
+
`Unsupported chunking strategy: ${chunking.strategy}`,
|
|
341
|
+
'INVALID_CHUNKING_STRATEGY',
|
|
342
|
+
{ strategy: chunking.strategy },
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
223
347
|
/**
|
|
224
348
|
* Chunks an async iterable source and stores it in Git.
|
|
225
349
|
*
|
|
226
|
-
*
|
|
227
|
-
*
|
|
350
|
+
* Supports two encryption modes: direct key/passphrase or envelope encryption
|
|
351
|
+
* via `recipients` (DEK/KEK model). The modes are mutually exclusive.
|
|
228
352
|
*
|
|
229
353
|
* @param {Object} options
|
|
230
354
|
* @param {AsyncIterable<Buffer>} options.source
|
|
@@ -234,50 +358,87 @@ export default class CasService {
|
|
|
234
358
|
* @param {string} [options.passphrase] - Derive encryption key from passphrase instead.
|
|
235
359
|
* @param {Object} [options.kdfOptions] - KDF options when using passphrase.
|
|
236
360
|
* @param {{ algorithm: 'gzip' }} [options.compression] - Enable compression.
|
|
361
|
+
* @param {Array<{label: string, key: Buffer}>} [options.recipients] - Envelope recipients (mutually exclusive with encryptionKey/passphrase).
|
|
237
362
|
* @returns {Promise<import('../value-objects/Manifest.js').default>}
|
|
238
363
|
*/
|
|
239
|
-
async store({ source, slug, filename, encryptionKey, passphrase, kdfOptions, compression }) {
|
|
364
|
+
async store({ source, slug, filename, encryptionKey, passphrase, kdfOptions, compression, recipients }) {
|
|
365
|
+
if (recipients && (encryptionKey || passphrase)) {
|
|
366
|
+
throw new CasError('Provide recipients or encryptionKey/passphrase, not both', 'INVALID_OPTIONS');
|
|
367
|
+
}
|
|
240
368
|
this._validateKeySourceExclusive(encryptionKey, passphrase);
|
|
241
369
|
this._validateCompression(compression);
|
|
242
370
|
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
encryptionKey = derived.key;
|
|
247
|
-
kdfParams = derived.params;
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
if (encryptionKey) {
|
|
251
|
-
this.crypto._validateKey(encryptionKey);
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
const manifestData = { slug, filename, size: 0, chunks: [] };
|
|
371
|
+
const keyInfo = recipients
|
|
372
|
+
? await this._resolveRecipientsForStore(recipients)
|
|
373
|
+
: await this._resolveKeyForStore(encryptionKey, passphrase, kdfOptions);
|
|
255
374
|
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
processedSource = this._compressStream(processedSource);
|
|
259
|
-
manifestData.compression = { algorithm: 'gzip' };
|
|
260
|
-
}
|
|
375
|
+
const manifestData = this._buildManifestData(slug, filename, compression);
|
|
376
|
+
const processedSource = compression ? this._compressStream(source) : source;
|
|
261
377
|
|
|
262
|
-
if (
|
|
263
|
-
const { encrypt, finalize } = this.crypto.createEncryptionStream(
|
|
378
|
+
if (keyInfo.key) {
|
|
379
|
+
const { encrypt, finalize } = this.crypto.createEncryptionStream(keyInfo.key);
|
|
264
380
|
await this._chunkAndStore(encrypt(processedSource), manifestData);
|
|
265
|
-
|
|
266
|
-
if (kdfParams) {
|
|
267
|
-
encMeta.kdf = kdfParams;
|
|
268
|
-
}
|
|
269
|
-
manifestData.encryption = encMeta;
|
|
381
|
+
manifestData.encryption = { ...finalize(), ...keyInfo.encExtra };
|
|
270
382
|
} else {
|
|
271
383
|
await this._chunkAndStore(processedSource, manifestData);
|
|
272
384
|
}
|
|
273
385
|
|
|
274
386
|
const manifest = new Manifest(manifestData);
|
|
275
387
|
this.observability.metric('file', {
|
|
276
|
-
action: 'stored', slug, size: manifest.size, chunkCount: manifest.chunks.length, encrypted: !!
|
|
388
|
+
action: 'stored', slug, size: manifest.size, chunkCount: manifest.chunks.length, encrypted: !!keyInfo.key,
|
|
277
389
|
});
|
|
278
390
|
return manifest;
|
|
279
391
|
}
|
|
280
392
|
|
|
393
|
+
/**
|
|
394
|
+
* Resolves envelope recipients into a DEK and wrapped entries for store().
|
|
395
|
+
* @private
|
|
396
|
+
*/
|
|
397
|
+
async _resolveRecipientsForStore(recipients) {
|
|
398
|
+
if (!Array.isArray(recipients) || recipients.length === 0) {
|
|
399
|
+
throw new CasError('At least one recipient is required', 'INVALID_OPTIONS');
|
|
400
|
+
}
|
|
401
|
+
const labels = recipients.map((r) => r.label);
|
|
402
|
+
if (new Set(labels).size !== labels.length) {
|
|
403
|
+
throw new CasError('Duplicate recipient labels are not allowed', 'INVALID_OPTIONS');
|
|
404
|
+
}
|
|
405
|
+
const dek = this.crypto.randomBytes(32);
|
|
406
|
+
const entries = [];
|
|
407
|
+
for (const r of recipients) {
|
|
408
|
+
this.crypto._validateKey(r.key);
|
|
409
|
+
entries.push({ label: r.label, ...(await this._wrapDek(dek, r.key)) });
|
|
410
|
+
}
|
|
411
|
+
return { key: dek, encExtra: { recipients: entries } };
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Resolves encryptionKey/passphrase into a key and optional KDF params for store().
|
|
416
|
+
* @private
|
|
417
|
+
*/
|
|
418
|
+
async _resolveKeyForStore(encryptionKey, passphrase, kdfOptions) {
|
|
419
|
+
let kdfParams;
|
|
420
|
+
if (passphrase) {
|
|
421
|
+
const derived = await this.deriveKey({ passphrase, ...kdfOptions });
|
|
422
|
+
encryptionKey = derived.key;
|
|
423
|
+
kdfParams = derived.params;
|
|
424
|
+
}
|
|
425
|
+
if (encryptionKey) { this.crypto._validateKey(encryptionKey); }
|
|
426
|
+
return { key: encryptionKey, encExtra: kdfParams ? { kdf: kdfParams } : {} };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Builds initial manifest data with optional chunking and compression metadata.
|
|
431
|
+
* @private
|
|
432
|
+
*/
|
|
433
|
+
_buildManifestData(slug, filename, compression) {
|
|
434
|
+
const data = { slug, filename, size: 0, chunks: [] };
|
|
435
|
+
if (this.chunker.strategy !== 'fixed') {
|
|
436
|
+
data.chunking = { strategy: this.chunker.strategy, params: this.chunker.params };
|
|
437
|
+
}
|
|
438
|
+
if (compression) { data.compression = { algorithm: 'gzip' }; }
|
|
439
|
+
return data;
|
|
440
|
+
}
|
|
441
|
+
|
|
281
442
|
/**
|
|
282
443
|
* Creates a Git tree object from a manifest.
|
|
283
444
|
*
|
|
@@ -405,30 +566,6 @@ export default class CasService {
|
|
|
405
566
|
return key;
|
|
406
567
|
}
|
|
407
568
|
|
|
408
|
-
/**
|
|
409
|
-
* Resolves the encryption key from passphrase or validates the provided key.
|
|
410
|
-
* @private
|
|
411
|
-
*/
|
|
412
|
-
async _resolveEncryptionKey(manifest, encryptionKey, passphrase) {
|
|
413
|
-
this._validateKeySourceExclusive(encryptionKey, passphrase);
|
|
414
|
-
|
|
415
|
-
if (passphrase) {
|
|
416
|
-
if (manifest.encryption?.kdf) {
|
|
417
|
-
return this._resolveKeyFromPassphrase(passphrase, manifest.encryption.kdf);
|
|
418
|
-
}
|
|
419
|
-
throw new CasError(
|
|
420
|
-
'Manifest was not stored with passphrase-based encryption; provide encryptionKey instead',
|
|
421
|
-
'MISSING_KEY',
|
|
422
|
-
);
|
|
423
|
-
}
|
|
424
|
-
if (encryptionKey) {
|
|
425
|
-
this.crypto._validateKey(encryptionKey);
|
|
426
|
-
} else if (manifest.encryption?.encrypted) {
|
|
427
|
-
throw new CasError('Encryption key required to restore encrypted content', 'MISSING_KEY');
|
|
428
|
-
}
|
|
429
|
-
return encryptionKey;
|
|
430
|
-
}
|
|
431
|
-
|
|
432
569
|
/**
|
|
433
570
|
* Restores a file from its manifest by reading and reassembling chunks.
|
|
434
571
|
*
|
|
@@ -473,7 +610,7 @@ export default class CasService {
|
|
|
473
610
|
* @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
|
|
474
611
|
*/
|
|
475
612
|
async *restoreStream({ manifest, encryptionKey, passphrase }) {
|
|
476
|
-
const key = await this.
|
|
613
|
+
const key = await this._resolveDecryptionKey(manifest, encryptionKey, passphrase);
|
|
477
614
|
|
|
478
615
|
if (manifest.chunks.length === 0) {
|
|
479
616
|
this.observability.metric('file', {
|
|
@@ -721,6 +858,124 @@ export default class CasService {
|
|
|
721
858
|
return await this.crypto.deriveKey(options);
|
|
722
859
|
}
|
|
723
860
|
|
|
861
|
+
/**
|
|
862
|
+
* Adds a new recipient to an envelope-encrypted manifest.
|
|
863
|
+
*
|
|
864
|
+
* Unwraps the DEK using `existingKey`, wraps it with `newRecipientKey`,
|
|
865
|
+
* and returns a new Manifest with the appended recipient entry.
|
|
866
|
+
*
|
|
867
|
+
* @param {Object} options
|
|
868
|
+
* @param {import('../value-objects/Manifest.js').default} options.manifest
|
|
869
|
+
* @param {Buffer} options.existingKey - KEK of an existing recipient.
|
|
870
|
+
* @param {Buffer} options.newRecipientKey - KEK for the new recipient.
|
|
871
|
+
* @param {string} options.label - Label for the new recipient.
|
|
872
|
+
* @returns {Promise<import('../value-objects/Manifest.js').default>}
|
|
873
|
+
* @throws {CasError} INVALID_OPTIONS if manifest has no recipients.
|
|
874
|
+
* @throws {CasError} RECIPIENT_ALREADY_EXISTS if label is a duplicate.
|
|
875
|
+
* @throws {CasError} DEK_UNWRAP_FAILED if existingKey doesn't match any recipient.
|
|
876
|
+
*/
|
|
877
|
+
async addRecipient({ manifest, existingKey, newRecipientKey, label }) {
|
|
878
|
+
const recipients = manifest.encryption?.recipients;
|
|
879
|
+
if (!recipients || recipients.length === 0) {
|
|
880
|
+
throw new CasError(
|
|
881
|
+
'Manifest does not use envelope encryption (no recipients)',
|
|
882
|
+
'INVALID_OPTIONS',
|
|
883
|
+
);
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
if (recipients.some((r) => r.label === label)) {
|
|
887
|
+
throw new CasError(
|
|
888
|
+
`Recipient "${label}" already exists`,
|
|
889
|
+
'RECIPIENT_ALREADY_EXISTS',
|
|
890
|
+
{ label },
|
|
891
|
+
);
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
this.crypto._validateKey(existingKey);
|
|
895
|
+
this.crypto._validateKey(newRecipientKey);
|
|
896
|
+
|
|
897
|
+
// Unwrap DEK using the existing key
|
|
898
|
+
let dek;
|
|
899
|
+
try {
|
|
900
|
+
dek = await this._resolveKeyForRecipients(manifest, existingKey);
|
|
901
|
+
} catch (err) {
|
|
902
|
+
if (err instanceof CasError && err.code === 'NO_MATCHING_RECIPIENT') {
|
|
903
|
+
throw new CasError('Failed to unwrap DEK: authentication failed', 'DEK_UNWRAP_FAILED', { originalError: err });
|
|
904
|
+
}
|
|
905
|
+
throw err;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// Wrap DEK for the new recipient
|
|
909
|
+
const newEntry = { label, ...(await this._wrapDek(dek, newRecipientKey)) };
|
|
910
|
+
|
|
911
|
+
const json = manifest.toJSON();
|
|
912
|
+
const updatedEncryption = {
|
|
913
|
+
...json.encryption,
|
|
914
|
+
recipients: [...recipients.map((r) => ({ ...r })), newEntry],
|
|
915
|
+
};
|
|
916
|
+
|
|
917
|
+
return new Manifest({ ...json, encryption: updatedEncryption });
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
/**
|
|
921
|
+
* Removes a recipient from an envelope-encrypted manifest.
|
|
922
|
+
*
|
|
923
|
+
* Returns a new Manifest with the recipient entry removed. Does not
|
|
924
|
+
* require a key — this is a manifest-only mutation.
|
|
925
|
+
*
|
|
926
|
+
* @param {Object} options
|
|
927
|
+
* @param {import('../value-objects/Manifest.js').default} options.manifest
|
|
928
|
+
* @param {string} options.label - Label of the recipient to remove.
|
|
929
|
+
* @returns {Promise<import('../value-objects/Manifest.js').default>}
|
|
930
|
+
* @throws {CasError} RECIPIENT_NOT_FOUND if label doesn't exist.
|
|
931
|
+
* @throws {CasError} CANNOT_REMOVE_LAST_RECIPIENT if only one recipient remains.
|
|
932
|
+
*/
|
|
933
|
+
async removeRecipient({ manifest, label }) {
|
|
934
|
+
const recipients = manifest.encryption?.recipients;
|
|
935
|
+
if (!recipients || recipients.length === 0) {
|
|
936
|
+
throw new CasError(
|
|
937
|
+
'Manifest does not use envelope encryption (no recipients)',
|
|
938
|
+
'INVALID_OPTIONS',
|
|
939
|
+
);
|
|
940
|
+
}
|
|
941
|
+
if (!recipients.some((r) => r.label === label)) {
|
|
942
|
+
throw new CasError(
|
|
943
|
+
`Recipient "${label}" not found`,
|
|
944
|
+
'RECIPIENT_NOT_FOUND',
|
|
945
|
+
{ label },
|
|
946
|
+
);
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
if (recipients.length === 1) {
|
|
950
|
+
throw new CasError(
|
|
951
|
+
'Cannot remove the last recipient',
|
|
952
|
+
'CANNOT_REMOVE_LAST_RECIPIENT',
|
|
953
|
+
);
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
const filtered = recipients.filter((r) => r.label !== label).map((r) => ({ ...r }));
|
|
957
|
+
if (filtered.length === 0) {
|
|
958
|
+
throw new CasError(
|
|
959
|
+
'Cannot remove the last recipient',
|
|
960
|
+
'CANNOT_REMOVE_LAST_RECIPIENT',
|
|
961
|
+
);
|
|
962
|
+
}
|
|
963
|
+
const json = manifest.toJSON();
|
|
964
|
+
const updatedEncryption = { ...json.encryption, recipients: filtered };
|
|
965
|
+
|
|
966
|
+
return new Manifest({ ...json, encryption: updatedEncryption });
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
/**
|
|
970
|
+
* Lists recipient labels from an envelope-encrypted manifest.
|
|
971
|
+
*
|
|
972
|
+
* @param {import('../value-objects/Manifest.js').default} manifest
|
|
973
|
+
* @returns {string[]} Recipient labels, or empty array if not envelope-encrypted.
|
|
974
|
+
*/
|
|
975
|
+
listRecipients(manifest) {
|
|
976
|
+
return (manifest.encryption?.recipients || []).map((r) => r.label);
|
|
977
|
+
}
|
|
978
|
+
|
|
724
979
|
/**
|
|
725
980
|
* Verifies the integrity of a stored file by re-hashing its chunks.
|
|
726
981
|
* @param {import('../value-objects/Manifest.js').default} manifest
|
|
@@ -11,6 +11,15 @@ export interface KdfParams {
|
|
|
11
11
|
keyLength: number;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
+
/** A single recipient entry in an envelope-encrypted manifest. */
|
|
15
|
+
export interface RecipientEntry {
|
|
16
|
+
label: string;
|
|
17
|
+
wrappedDek: string;
|
|
18
|
+
nonce: string;
|
|
19
|
+
tag: string;
|
|
20
|
+
kekType?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
14
23
|
/** AES-256-GCM encryption metadata attached to an encrypted manifest. */
|
|
15
24
|
export interface EncryptionMeta {
|
|
16
25
|
algorithm: string;
|
|
@@ -18,6 +27,7 @@ export interface EncryptionMeta {
|
|
|
18
27
|
tag: string;
|
|
19
28
|
encrypted: boolean;
|
|
20
29
|
kdf?: KdfParams;
|
|
30
|
+
recipients?: RecipientEntry[];
|
|
21
31
|
}
|
|
22
32
|
|
|
23
33
|
/** Compression metadata. */
|
|
@@ -27,8 +27,13 @@ export default class Manifest {
|
|
|
27
27
|
this.filename = data.filename;
|
|
28
28
|
this.size = data.size;
|
|
29
29
|
this.chunks = data.chunks.map((c) => new Chunk(c));
|
|
30
|
-
this.encryption = data.encryption
|
|
30
|
+
this.encryption = data.encryption
|
|
31
|
+
? { ...data.encryption, recipients: data.encryption.recipients?.map((r) => ({ ...r })) }
|
|
32
|
+
: undefined;
|
|
31
33
|
this.compression = data.compression ? { ...data.compression } : undefined;
|
|
34
|
+
this.chunking = data.chunking
|
|
35
|
+
? { strategy: data.chunking.strategy, params: { ...data.chunking.params } }
|
|
36
|
+
: undefined;
|
|
32
37
|
this.subManifests = data.subManifests ? data.subManifests.map((s) => ({ ...s })) : undefined;
|
|
33
38
|
Object.freeze(this);
|
|
34
39
|
} catch (error) {
|
|
@@ -52,6 +57,7 @@ export default class Manifest {
|
|
|
52
57
|
chunks: this.chunks,
|
|
53
58
|
encryption: this.encryption,
|
|
54
59
|
compression: this.compression,
|
|
60
|
+
chunking: this.chunking,
|
|
55
61
|
subManifests: this.subManifests,
|
|
56
62
|
};
|
|
57
63
|
}
|