@git-stunts/git-cas 5.2.1 → 5.3.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 +100 -0
- package/README.md +67 -5
- package/bin/actions.js +38 -8
- package/bin/config.js +203 -0
- package/bin/git-cas.js +200 -54
- package/bin/ui/context.js +13 -0
- package/bin/ui/dashboard-cmds.js +14 -6
- package/bin/ui/dashboard-view.js +55 -6
- package/bin/ui/dashboard.js +109 -7
- package/bin/ui/encryption-card.js +2 -2
- package/bin/ui/heatmap.js +20 -2
- package/bin/ui/history-timeline.js +8 -6
- package/bin/ui/manifest-view.js +37 -8
- package/bin/ui/passphrase-prompt.js +100 -0
- package/bin/ui/progress.js +60 -38
- package/index.d.ts +20 -1
- package/index.js +74 -218
- package/package.json +2 -1
- package/src/domain/errors/CasError.js +3 -1
- package/src/domain/helpers/buildKdfMetadata.js +18 -0
- package/src/domain/services/CasService.d.ts +21 -1
- package/src/domain/services/CasService.js +134 -228
- package/src/domain/services/KeyResolver.js +220 -0
- package/src/domain/services/Semaphore.js +2 -2
- package/src/domain/services/VaultService.js +72 -29
- package/src/domain/services/rotateVaultPassphrase.js +143 -0
- package/src/infrastructure/adapters/BunCryptoAdapter.js +38 -6
- package/src/infrastructure/adapters/EventEmitterObserver.js +19 -7
- package/src/infrastructure/adapters/FileIOHelper.js +64 -0
- package/src/infrastructure/adapters/GitPersistenceAdapter.js +21 -5
- package/src/infrastructure/adapters/GitRefAdapter.js +27 -5
- package/src/infrastructure/adapters/NodeCryptoAdapter.js +49 -8
- package/src/infrastructure/adapters/SilentObserver.js +15 -0
- package/src/infrastructure/adapters/StatsCollector.js +15 -1
- package/src/infrastructure/adapters/WebCryptoAdapter.js +120 -42
- package/src/infrastructure/adapters/createCryptoAdapter.js +25 -0
- package/src/infrastructure/chunkers/CdcChunker.js +5 -0
- package/src/infrastructure/chunkers/FixedChunker.js +28 -8
- package/src/infrastructure/chunkers/resolveChunker.js +45 -0
- package/src/infrastructure/codecs/CborCodec.js +11 -3
- package/src/infrastructure/codecs/JsonCodec.js +10 -2
- package/src/ports/CodecPort.js +3 -3
- package/src/ports/CryptoPort.js +56 -23
- package/src/ports/GitPersistencePort.js +4 -4
- package/src/ports/GitRefPort.js +10 -10
- package/src/types/ambient.d.ts +37 -0
|
@@ -8,7 +8,7 @@ import type { EncryptionMeta, CompressionMeta, KdfParams } from "../value-object
|
|
|
8
8
|
|
|
9
9
|
/** Port interface for cryptographic operations (hashing, encryption, random bytes). */
|
|
10
10
|
export interface CryptoPort {
|
|
11
|
-
sha256(buf: Buffer):
|
|
11
|
+
sha256(buf: Buffer): Promise<string>;
|
|
12
12
|
randomBytes(n: number): Buffer;
|
|
13
13
|
encryptBuffer(
|
|
14
14
|
buffer: Buffer,
|
|
@@ -46,6 +46,13 @@ export interface ObservabilityPort {
|
|
|
46
46
|
span(name: string): { end(meta?: Record<string, unknown>): void };
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
/** Port interface for chunking strategies (fixed, CDC, etc.). */
|
|
50
|
+
export interface ChunkingPort {
|
|
51
|
+
chunk(source: AsyncIterable<Buffer>): AsyncIterable<Buffer>;
|
|
52
|
+
readonly strategy: string;
|
|
53
|
+
readonly params: Record<string, unknown>;
|
|
54
|
+
}
|
|
55
|
+
|
|
49
56
|
/** Constructor options for {@link CasService}. */
|
|
50
57
|
export interface CasServiceOptions {
|
|
51
58
|
persistence: GitPersistencePort;
|
|
@@ -55,6 +62,8 @@ export interface CasServiceOptions {
|
|
|
55
62
|
chunkSize?: number;
|
|
56
63
|
merkleThreshold?: number;
|
|
57
64
|
concurrency?: number;
|
|
65
|
+
chunker?: ChunkingPort;
|
|
66
|
+
maxRestoreBufferSize?: number;
|
|
58
67
|
}
|
|
59
68
|
|
|
60
69
|
/** Options for key derivation. */
|
|
@@ -90,6 +99,7 @@ export default class CasService {
|
|
|
90
99
|
readonly chunkSize: number;
|
|
91
100
|
readonly merkleThreshold: number;
|
|
92
101
|
readonly concurrency: number;
|
|
102
|
+
readonly maxRestoreBufferSize: number;
|
|
93
103
|
|
|
94
104
|
constructor(options: CasServiceOptions);
|
|
95
105
|
|
|
@@ -131,10 +141,20 @@ export default class CasService {
|
|
|
131
141
|
|
|
132
142
|
readManifest(options: { treeOid: string }): Promise<Manifest>;
|
|
133
143
|
|
|
144
|
+
inspectAsset(options: {
|
|
145
|
+
treeOid: string;
|
|
146
|
+
}): Promise<{ slug: string; chunksOrphaned: number }>;
|
|
147
|
+
|
|
148
|
+
/** @deprecated Use {@link inspectAsset} instead. */
|
|
134
149
|
deleteAsset(options: {
|
|
135
150
|
treeOid: string;
|
|
136
151
|
}): Promise<{ slug: string; chunksOrphaned: number }>;
|
|
137
152
|
|
|
153
|
+
collectReferencedChunks(options: {
|
|
154
|
+
treeOids: string[];
|
|
155
|
+
}): Promise<{ referenced: Set<string>; total: number }>;
|
|
156
|
+
|
|
157
|
+
/** @deprecated Use {@link collectReferencedChunks} instead. */
|
|
138
158
|
findOrphanedChunks(options: {
|
|
139
159
|
treeOids: string[];
|
|
140
160
|
}): Promise<{ referenced: Set<string>; total: number }>;
|
|
@@ -10,6 +10,7 @@ import Manifest from '../value-objects/Manifest.js';
|
|
|
10
10
|
import CasError from '../errors/CasError.js';
|
|
11
11
|
import Semaphore from './Semaphore.js';
|
|
12
12
|
import FixedChunker from '../../infrastructure/chunkers/FixedChunker.js';
|
|
13
|
+
import KeyResolver from './KeyResolver.js';
|
|
13
14
|
|
|
14
15
|
const gunzipAsync = promisify(gunzip);
|
|
15
16
|
|
|
@@ -20,6 +21,9 @@ const gunzipAsync = promisify(gunzip);
|
|
|
20
21
|
* arbitrary data in Git's object database.
|
|
21
22
|
*/
|
|
22
23
|
export default class CasService {
|
|
24
|
+
/** @type {KeyResolver} */
|
|
25
|
+
#keyResolver;
|
|
26
|
+
|
|
23
27
|
/**
|
|
24
28
|
* @param {Object} options
|
|
25
29
|
* @param {import('../../ports/GitPersistencePort.js').default} options.persistence
|
|
@@ -30,27 +34,48 @@ export default class CasService {
|
|
|
30
34
|
* @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
|
|
31
35
|
* @param {number} [options.concurrency=1] - Maximum parallel chunk I/O operations.
|
|
32
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).
|
|
33
38
|
*/
|
|
34
|
-
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 }) {
|
|
35
40
|
CasService._validateObservability(observability);
|
|
36
|
-
|
|
37
|
-
throw new Error('Chunk size must be at least 1024 bytes');
|
|
38
|
-
}
|
|
41
|
+
CasService.#validateConstructorArgs({ chunkSize, merkleThreshold, concurrency, maxRestoreBufferSize });
|
|
39
42
|
this.persistence = persistence;
|
|
40
43
|
this.codec = codec;
|
|
41
44
|
this.crypto = crypto;
|
|
42
45
|
this.observability = observability;
|
|
43
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
|
+
}
|
|
44
50
|
/** @type {import('../../ports/ChunkingPort.js').default} */
|
|
45
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
|
+
}
|
|
46
70
|
if (!Number.isInteger(merkleThreshold) || merkleThreshold < 1) {
|
|
47
71
|
throw new Error('Merkle threshold must be a positive integer');
|
|
48
72
|
}
|
|
49
|
-
this.merkleThreshold = merkleThreshold;
|
|
50
73
|
if (!Number.isInteger(concurrency) || concurrency < 1) {
|
|
51
74
|
throw new Error('Concurrency must be a positive integer');
|
|
52
75
|
}
|
|
53
|
-
|
|
76
|
+
if (!Number.isInteger(maxRestoreBufferSize) || maxRestoreBufferSize < 1024) {
|
|
77
|
+
throw new Error('maxRestoreBufferSize must be a positive integer >= 1024');
|
|
78
|
+
}
|
|
54
79
|
}
|
|
55
80
|
|
|
56
81
|
/**
|
|
@@ -122,15 +147,23 @@ export default class CasService {
|
|
|
122
147
|
launchWrite(chunk, nextIndex++);
|
|
123
148
|
}
|
|
124
149
|
} catch (err) {
|
|
125
|
-
await Promise.allSettled(pending);
|
|
126
|
-
|
|
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
|
+
}
|
|
127
158
|
const casErr = new CasError(
|
|
128
159
|
`Stream error during store: ${err.message}`,
|
|
129
160
|
'STREAM_ERROR',
|
|
130
|
-
{ chunksDispatched: nextIndex, originalError: err },
|
|
161
|
+
{ chunksDispatched: nextIndex, orphanedBlobs, originalError: err },
|
|
131
162
|
);
|
|
132
|
-
|
|
133
|
-
|
|
163
|
+
this.observability.metric('error', {
|
|
164
|
+
code: casErr.code, message: casErr.message,
|
|
165
|
+
orphanedBlobs: orphanedBlobs.length,
|
|
166
|
+
});
|
|
134
167
|
throw casErr;
|
|
135
168
|
}
|
|
136
169
|
|
|
@@ -190,129 +223,6 @@ export default class CasService {
|
|
|
190
223
|
}
|
|
191
224
|
}
|
|
192
225
|
|
|
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
|
-
|
|
303
|
-
/**
|
|
304
|
-
* Validates that passphrase and encryptionKey are not both provided.
|
|
305
|
-
* @private
|
|
306
|
-
*/
|
|
307
|
-
_validateKeySourceExclusive(encryptionKey, passphrase) {
|
|
308
|
-
if (passphrase && encryptionKey) {
|
|
309
|
-
throw new CasError(
|
|
310
|
-
'Provide either encryptionKey or passphrase, not both',
|
|
311
|
-
'INVALID_OPTIONS',
|
|
312
|
-
);
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
|
|
316
226
|
/**
|
|
317
227
|
* Validates and normalizes compression options.
|
|
318
228
|
* @private
|
|
@@ -365,16 +275,23 @@ export default class CasService {
|
|
|
365
275
|
if (recipients && (encryptionKey || passphrase)) {
|
|
366
276
|
throw new CasError('Provide recipients or encryptionKey/passphrase, not both', 'INVALID_OPTIONS');
|
|
367
277
|
}
|
|
368
|
-
|
|
278
|
+
KeyResolver.validateKeySourceExclusive(encryptionKey, passphrase);
|
|
369
279
|
this._validateCompression(compression);
|
|
370
280
|
|
|
371
281
|
const keyInfo = recipients
|
|
372
|
-
? await this.
|
|
373
|
-
: await this.
|
|
282
|
+
? await this.#keyResolver.resolveRecipients(recipients)
|
|
283
|
+
: await this.#keyResolver.resolveForStore(encryptionKey, passphrase, kdfOptions);
|
|
374
284
|
|
|
375
285
|
const manifestData = this._buildManifestData(slug, filename, compression);
|
|
376
286
|
const processedSource = compression ? this._compressStream(source) : source;
|
|
377
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
|
+
}
|
|
378
295
|
if (keyInfo.key) {
|
|
379
296
|
const { encrypt, finalize } = this.crypto.createEncryptionStream(keyInfo.key);
|
|
380
297
|
await this._chunkAndStore(encrypt(processedSource), manifestData);
|
|
@@ -390,42 +307,6 @@ export default class CasService {
|
|
|
390
307
|
return manifest;
|
|
391
308
|
}
|
|
392
309
|
|
|
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
310
|
/**
|
|
430
311
|
* Builds initial manifest data with optional chunking and compression metadata.
|
|
431
312
|
* @private
|
|
@@ -519,6 +400,28 @@ export default class CasService {
|
|
|
519
400
|
return await this.persistence.writeTree(treeEntries);
|
|
520
401
|
}
|
|
521
402
|
|
|
403
|
+
/**
|
|
404
|
+
* Reads a single chunk blob from Git and verifies its SHA-256 digest.
|
|
405
|
+
* @private
|
|
406
|
+
* @param {{ index: number, size: number, digest: string, blob: string }} chunk - Chunk metadata.
|
|
407
|
+
* @returns {Promise<Buffer>} Verified chunk buffer.
|
|
408
|
+
* @throws {CasError} INTEGRITY_ERROR if the chunk digest does not match.
|
|
409
|
+
*/
|
|
410
|
+
async _readAndVerifyChunk(chunk) {
|
|
411
|
+
const blob = await this.persistence.readBlob(chunk.blob);
|
|
412
|
+
const digest = await this._sha256(blob);
|
|
413
|
+
if (digest !== chunk.digest) {
|
|
414
|
+
const err = new CasError(
|
|
415
|
+
`Chunk ${chunk.index} integrity check failed`,
|
|
416
|
+
'INTEGRITY_ERROR',
|
|
417
|
+
{ chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
|
|
418
|
+
);
|
|
419
|
+
this.observability.metric('error', { code: err.code, message: err.message });
|
|
420
|
+
throw err;
|
|
421
|
+
}
|
|
422
|
+
return blob;
|
|
423
|
+
}
|
|
424
|
+
|
|
522
425
|
/**
|
|
523
426
|
* Reads chunk blobs from Git and verifies their SHA-256 digests.
|
|
524
427
|
* @private
|
|
@@ -529,43 +432,13 @@ export default class CasService {
|
|
|
529
432
|
async _readAndVerifyChunks(chunks) {
|
|
530
433
|
const buffers = [];
|
|
531
434
|
for (const chunk of chunks) {
|
|
532
|
-
const blob = await this.
|
|
533
|
-
const digest = await this._sha256(blob);
|
|
534
|
-
if (digest !== chunk.digest) {
|
|
535
|
-
const err = new CasError(
|
|
536
|
-
`Chunk ${chunk.index} integrity check failed`,
|
|
537
|
-
'INTEGRITY_ERROR',
|
|
538
|
-
{ chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
|
|
539
|
-
);
|
|
540
|
-
this.observability.metric('error', { code: err.code, message: err.message });
|
|
541
|
-
throw err;
|
|
542
|
-
}
|
|
435
|
+
const blob = await this._readAndVerifyChunk(chunk);
|
|
543
436
|
buffers.push(blob);
|
|
544
437
|
this.observability.metric('chunk', { action: 'restored', index: chunk.index, size: blob.length, digest: chunk.digest });
|
|
545
438
|
}
|
|
546
439
|
return buffers;
|
|
547
440
|
}
|
|
548
441
|
|
|
549
|
-
/**
|
|
550
|
-
* Resolves the encryption key from a passphrase using KDF params from the manifest.
|
|
551
|
-
* @private
|
|
552
|
-
* @param {string} passphrase
|
|
553
|
-
* @param {Object} kdf - KDF params from manifest.encryption.kdf.
|
|
554
|
-
* @returns {Promise<Buffer>}
|
|
555
|
-
*/
|
|
556
|
-
async _resolveKeyFromPassphrase(passphrase, kdf) {
|
|
557
|
-
const { key } = await this.deriveKey({
|
|
558
|
-
passphrase,
|
|
559
|
-
salt: Buffer.from(kdf.salt, 'base64'),
|
|
560
|
-
algorithm: kdf.algorithm,
|
|
561
|
-
iterations: kdf.iterations,
|
|
562
|
-
cost: kdf.cost,
|
|
563
|
-
blockSize: kdf.blockSize,
|
|
564
|
-
parallelization: kdf.parallelization,
|
|
565
|
-
});
|
|
566
|
-
return key;
|
|
567
|
-
}
|
|
568
|
-
|
|
569
442
|
/**
|
|
570
443
|
* Restores a file from its manifest by reading and reassembling chunks.
|
|
571
444
|
*
|
|
@@ -610,7 +483,7 @@ export default class CasService {
|
|
|
610
483
|
* @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
|
|
611
484
|
*/
|
|
612
485
|
async *restoreStream({ manifest, encryptionKey, passphrase }) {
|
|
613
|
-
const key = await this.
|
|
486
|
+
const key = await this.#keyResolver.resolveForDecryption(manifest, encryptionKey, passphrase);
|
|
614
487
|
|
|
615
488
|
if (manifest.chunks.length === 0) {
|
|
616
489
|
this.observability.metric('file', {
|
|
@@ -631,14 +504,38 @@ export default class CasService {
|
|
|
631
504
|
* @private
|
|
632
505
|
*/
|
|
633
506
|
async *_restoreBuffered(manifest, key) {
|
|
507
|
+
const totalSize = manifest.chunks.reduce((acc, c) => acc + c.size, 0);
|
|
508
|
+
if (totalSize > this.maxRestoreBufferSize) {
|
|
509
|
+
throw new CasError(
|
|
510
|
+
`Encrypted/compressed restore would buffer ${totalSize} bytes ` +
|
|
511
|
+
`(limit: ${this.maxRestoreBufferSize}). Increase maxRestoreBufferSize ` +
|
|
512
|
+
'or store without encryption.',
|
|
513
|
+
'RESTORE_TOO_LARGE',
|
|
514
|
+
{ size: totalSize, limit: this.maxRestoreBufferSize },
|
|
515
|
+
);
|
|
516
|
+
}
|
|
634
517
|
let buffer = Buffer.concat(await this._readAndVerifyChunks(manifest.chunks));
|
|
635
518
|
|
|
636
519
|
if (manifest.encryption?.encrypted) {
|
|
637
|
-
|
|
520
|
+
try {
|
|
521
|
+
buffer = await this.decrypt({ buffer, key, meta: manifest.encryption });
|
|
522
|
+
} catch (err) {
|
|
523
|
+
if (err instanceof CasError && err.code === 'INTEGRITY_ERROR') {
|
|
524
|
+
this.observability.metric('error', { action: 'decryption_failed', slug: manifest.slug });
|
|
525
|
+
}
|
|
526
|
+
throw err;
|
|
527
|
+
}
|
|
638
528
|
}
|
|
639
529
|
|
|
640
530
|
if (manifest.compression) {
|
|
641
531
|
buffer = await this._decompress(buffer);
|
|
532
|
+
if (buffer.length > this.maxRestoreBufferSize) {
|
|
533
|
+
throw new CasError(
|
|
534
|
+
`Decompressed restore is ${buffer.length} bytes (limit: ${this.maxRestoreBufferSize})`,
|
|
535
|
+
'RESTORE_TOO_LARGE',
|
|
536
|
+
{ size: buffer.length, limit: this.maxRestoreBufferSize },
|
|
537
|
+
);
|
|
538
|
+
}
|
|
642
539
|
}
|
|
643
540
|
|
|
644
541
|
this.observability.metric('file', {
|
|
@@ -659,20 +556,7 @@ export default class CasService {
|
|
|
659
556
|
const readAhead = this.concurrency;
|
|
660
557
|
let totalSize = 0;
|
|
661
558
|
|
|
662
|
-
const readAndVerify =
|
|
663
|
-
const blob = await this.persistence.readBlob(chunk.blob);
|
|
664
|
-
const digest = await this._sha256(blob);
|
|
665
|
-
if (digest !== chunk.digest) {
|
|
666
|
-
const err = new CasError(
|
|
667
|
-
`Chunk ${chunk.index} integrity check failed`,
|
|
668
|
-
'INTEGRITY_ERROR',
|
|
669
|
-
{ chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
|
|
670
|
-
);
|
|
671
|
-
this.observability.metric('error', { code: err.code, message: err.message });
|
|
672
|
-
throw err;
|
|
673
|
-
}
|
|
674
|
-
return blob;
|
|
675
|
-
};
|
|
559
|
+
const readAndVerify = (chunk) => this._readAndVerifyChunk(chunk);
|
|
676
560
|
|
|
677
561
|
const ahead = [];
|
|
678
562
|
for (let i = 0; i < Math.min(readAhead, chunks.length); i++) {
|
|
@@ -801,7 +685,7 @@ export default class CasService {
|
|
|
801
685
|
}
|
|
802
686
|
|
|
803
687
|
/**
|
|
804
|
-
*
|
|
688
|
+
* Reads a manifest from a Git tree and returns inspection metadata.
|
|
805
689
|
* Does not perform any destructive Git operations.
|
|
806
690
|
*
|
|
807
691
|
* @param {Object} options
|
|
@@ -809,7 +693,7 @@ export default class CasService {
|
|
|
809
693
|
* @returns {Promise<{ chunksOrphaned: number, slug: string }>}
|
|
810
694
|
* @throws {CasError} MANIFEST_NOT_FOUND if the tree has no manifest
|
|
811
695
|
*/
|
|
812
|
-
async
|
|
696
|
+
async inspectAsset({ treeOid }) {
|
|
813
697
|
const manifest = await this.readManifest({ treeOid });
|
|
814
698
|
return {
|
|
815
699
|
slug: manifest.slug,
|
|
@@ -817,6 +701,17 @@ export default class CasService {
|
|
|
817
701
|
};
|
|
818
702
|
}
|
|
819
703
|
|
|
704
|
+
/**
|
|
705
|
+
* @deprecated Use {@link inspectAsset} instead.
|
|
706
|
+
* @param {Object} options
|
|
707
|
+
* @param {string} options.treeOid - Git tree OID of the asset
|
|
708
|
+
* @returns {Promise<{ chunksOrphaned: number, slug: string }>}
|
|
709
|
+
*/
|
|
710
|
+
async deleteAsset(options) {
|
|
711
|
+
this.observability.log('warn', 'deleteAsset() is deprecated — use inspectAsset()');
|
|
712
|
+
return await this.inspectAsset(options);
|
|
713
|
+
}
|
|
714
|
+
|
|
820
715
|
/**
|
|
821
716
|
* Aggregates referenced chunk blob OIDs across multiple stored assets.
|
|
822
717
|
* Analysis only — does not delete or modify anything.
|
|
@@ -826,7 +721,7 @@ export default class CasService {
|
|
|
826
721
|
* @returns {Promise<{ referenced: Set<string>, total: number }>}
|
|
827
722
|
* @throws {CasError} MANIFEST_NOT_FOUND if any treeOid lacks a manifest
|
|
828
723
|
*/
|
|
829
|
-
async
|
|
724
|
+
async collectReferencedChunks({ treeOids }) {
|
|
830
725
|
const referenced = new Set();
|
|
831
726
|
let total = 0;
|
|
832
727
|
|
|
@@ -841,6 +736,17 @@ export default class CasService {
|
|
|
841
736
|
return { referenced, total };
|
|
842
737
|
}
|
|
843
738
|
|
|
739
|
+
/**
|
|
740
|
+
* @deprecated Use {@link collectReferencedChunks} instead.
|
|
741
|
+
* @param {Object} options
|
|
742
|
+
* @param {string[]} options.treeOids - Git tree OIDs to analyze
|
|
743
|
+
* @returns {Promise<{ referenced: Set<string>, total: number }>}
|
|
744
|
+
*/
|
|
745
|
+
async findOrphanedChunks(options) {
|
|
746
|
+
this.observability.log('warn', 'findOrphanedChunks() is deprecated — use collectReferencedChunks()');
|
|
747
|
+
return await this.collectReferencedChunks(options);
|
|
748
|
+
}
|
|
749
|
+
|
|
844
750
|
/**
|
|
845
751
|
* Derives an encryption key from a passphrase using PBKDF2 or scrypt.
|
|
846
752
|
* @param {Object} options
|
|
@@ -897,7 +803,7 @@ export default class CasService {
|
|
|
897
803
|
// Unwrap DEK using the existing key
|
|
898
804
|
let dek;
|
|
899
805
|
try {
|
|
900
|
-
dek = await this.
|
|
806
|
+
dek = await this.#keyResolver.resolveKeyForRecipients(manifest, existingKey);
|
|
901
807
|
} catch (err) {
|
|
902
808
|
if (err instanceof CasError && err.code === 'NO_MATCHING_RECIPIENT') {
|
|
903
809
|
throw new CasError('Failed to unwrap DEK: authentication failed', 'DEK_UNWRAP_FAILED', { originalError: err });
|
|
@@ -906,7 +812,7 @@ export default class CasService {
|
|
|
906
812
|
}
|
|
907
813
|
|
|
908
814
|
// Wrap DEK for the new recipient
|
|
909
|
-
const newEntry = { label, ...(await this.
|
|
815
|
+
const newEntry = { label, ...(await this.#keyResolver.wrapDek(dek, newRecipientKey)) };
|
|
910
816
|
|
|
911
817
|
const json = manifest.toJSON();
|
|
912
818
|
const updatedEncryption = {
|
|
@@ -1020,7 +926,7 @@ export default class CasService {
|
|
|
1020
926
|
if (matchIndex === -1) {
|
|
1021
927
|
throw new CasError(`Recipient "${label}" not found`, 'RECIPIENT_NOT_FOUND', { label });
|
|
1022
928
|
}
|
|
1023
|
-
const dek = await this.
|
|
929
|
+
const dek = await this.#keyResolver.unwrapDek(recipients[matchIndex], oldKey);
|
|
1024
930
|
return { matchIndex, dek };
|
|
1025
931
|
}
|
|
1026
932
|
|
|
@@ -1030,7 +936,7 @@ export default class CasService {
|
|
|
1030
936
|
async #findRecipientByKey(recipients, oldKey) {
|
|
1031
937
|
for (let i = 0; i < recipients.length; i++) {
|
|
1032
938
|
try {
|
|
1033
|
-
const dek = await this.
|
|
939
|
+
const dek = await this.#keyResolver.unwrapDek(recipients[i], oldKey);
|
|
1034
940
|
return { matchIndex: i, dek };
|
|
1035
941
|
} catch (err) {
|
|
1036
942
|
if (!(err instanceof CasError && err.code === 'DEK_UNWRAP_FAILED')) { throw err; }
|
|
@@ -1046,7 +952,7 @@ export default class CasService {
|
|
|
1046
952
|
* Builds a new Manifest with the rotated recipient entry and updated keyVersions.
|
|
1047
953
|
*/
|
|
1048
954
|
async #buildRotatedManifest({ manifest, recipients, matchIndex, dek, newKey }) {
|
|
1049
|
-
const newWrapped = await this.
|
|
955
|
+
const newWrapped = await this.#keyResolver.wrapDek(dek, newKey);
|
|
1050
956
|
const manifestKeyVersion = (manifest.encryption.keyVersion || 0) + 1;
|
|
1051
957
|
const recipientKeyVersion = (recipients[matchIndex].keyVersion || 0) + 1;
|
|
1052
958
|
|