@git-stunts/git-cas 5.3.2 → 6.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/ADVANCED_GUIDE.md +1006 -0
- package/ARCHITECTURE.md +514 -0
- package/CHANGELOG.md +393 -5
- package/CODE_OF_CONDUCT.md +33 -0
- package/GUIDE.md +872 -0
- package/README.md +219 -325
- package/SECURITY.md +993 -0
- package/SUPPORT.md +54 -0
- package/UPGRADING.md +299 -0
- package/bin/actions.js +70 -21
- package/bin/agent/cli.js +51 -0
- package/bin/agent/commands/doctor.js +99 -0
- package/bin/agent/commands/index.js +1489 -0
- package/bin/agent/input.js +619 -0
- package/bin/agent/passphrase-source.js +123 -0
- package/bin/agent/protocol.js +193 -0
- package/bin/build-version.js +64 -0
- package/bin/credentials.js +425 -0
- package/bin/git-cas.js +595 -449
- package/bin/passphrase-source.js +266 -0
- package/bin/restore-output-target.js +28 -0
- package/bin/ui/blocks/asset-card.js +109 -0
- package/bin/ui/blocks/health-dashboard.js +149 -0
- package/bin/ui/blocks/heatmap-block.js +67 -0
- package/bin/ui/blocks/merkle-explorer.js +163 -0
- package/bin/ui/blocks/operation-feed.js +176 -0
- package/bin/ui/blocks/wizard-block.js +168 -0
- package/bin/ui/components/short-sha.js +36 -0
- package/bin/ui/context.js +56 -1
- package/bin/ui/dashboard-cmds.js +1578 -13
- package/bin/ui/dashboard-view.js +612 -145
- package/bin/ui/dashboard.js +998 -214
- package/bin/ui/encryption-card.js +69 -26
- package/bin/ui/heatmap.js +26 -54
- package/bin/ui/history-timeline.js +51 -19
- package/bin/ui/manifest-view.js +115 -60
- package/bin/ui/merkle-dag.js +83 -0
- package/bin/ui/progress.js +15 -9
- package/bin/ui/repo-treemap.js +328 -0
- package/bin/ui/shaders/bak-sneppen.js +180 -0
- package/bin/ui/shaders/fractal-zoom.js +99 -0
- package/bin/ui/shaders/merkle-tree.js +142 -0
- package/bin/ui/shaders/organic-flow.js +96 -0
- package/bin/ui/shaders/phase-portrait.js +93 -0
- package/bin/ui/store-wizard.js +296 -0
- package/bin/ui/theme.js +155 -0
- package/bin/ui/vault-report.js +495 -0
- package/build-info.json +4 -0
- package/docs/API.md +2224 -0
- package/docs/ENCRYPTION_MODES.md +33 -0
- package/docs/EXTENDING.md +174 -0
- package/docs/STORE_RESTORE_PIPELINE.md +199 -0
- package/docs/THREAT_MODEL.md +269 -0
- package/docs/VAULT_INTERNALS.md +251 -0
- package/docs/WALKTHROUGH.md +1868 -0
- package/docs/demo.gif +0 -0
- package/docs/releases/v6.0.0.md +104 -0
- package/examples/README.md +260 -0
- package/index.d.ts +208 -65
- package/index.js +163 -54
- package/package.json +35 -6
- package/scripts/migrate-encryption.js +680 -0
- package/src/domain/bytes/ByteLayout.js +96 -0
- package/src/domain/encoding/base64.js +91 -0
- package/src/domain/encoding/hex.js +14 -0
- package/src/domain/encoding/utf8.js +123 -0
- package/src/domain/encryption/schemes.js +132 -0
- package/src/domain/errors/CannotRemoveLastRecipientError.js +10 -0
- package/src/domain/errors/CasError.d.ts +28 -0
- package/src/domain/errors/CasError.js +43 -6
- package/src/domain/errors/Codes.js +54 -0
- package/src/domain/errors/DekUnwrapFailedError.js +10 -0
- package/src/domain/errors/GitError.js +10 -0
- package/src/domain/errors/GitPlumbingInitializationError.js +10 -0
- package/src/domain/errors/IntegrityError.js +10 -0
- package/src/domain/errors/InvalidChunkingStrategyError.js +10 -0
- package/src/domain/errors/InvalidOidError.js +10 -0
- package/src/domain/errors/InvalidOptionsError.js +10 -0
- package/src/domain/errors/ManifestIntegrityError.js +10 -0
- package/src/domain/errors/ManifestNotFoundError.js +10 -0
- package/src/domain/errors/NoMatchingRecipientError.js +10 -0
- package/src/domain/errors/PersistenceCapabilityRequiredError.js +10 -0
- package/src/domain/errors/PortNotImplementedError.js +10 -0
- package/src/domain/errors/RecipientAlreadyExistsError.js +10 -0
- package/src/domain/errors/RecipientNotFoundError.js +10 -0
- package/src/domain/errors/RestoreTooLargeError.js +10 -0
- package/src/domain/errors/RotationNotSupportedError.js +10 -0
- package/src/domain/errors/createCasError.js +68 -0
- package/src/domain/errors/index.js +20 -0
- package/src/domain/helpers/buildKdfMetadata.js +4 -2
- package/src/domain/helpers/codecBytes.js +34 -0
- package/src/domain/helpers/gitRefErrors.js +84 -0
- package/src/domain/helpers/scryptMaxmem.js +22 -0
- package/src/domain/outcomes/RestoreFailure.js +15 -0
- package/src/domain/outcomes/RestoreOutcome.js +11 -0
- package/src/domain/outcomes/RestoreSuccess.js +34 -0
- package/src/domain/outcomes/StoreFailure.js +15 -0
- package/src/domain/outcomes/StoreOutcome.js +11 -0
- package/src/domain/outcomes/StoreSuccess.js +17 -0
- package/src/domain/schemas/ManifestSchema.d.ts +40 -9
- package/src/domain/schemas/ManifestSchema.js +67 -13
- package/src/domain/services/CasService.d.ts +123 -38
- package/src/domain/services/CasService.js +298 -834
- package/src/domain/services/ChunkRepository.js +230 -0
- package/src/domain/services/CompressionStreams.js +72 -0
- package/src/domain/services/ConvergentEncryption.js +128 -0
- package/src/domain/services/GitTreeBuilder.js +86 -0
- package/src/domain/services/IntegrityVerifier.js +199 -0
- package/src/domain/services/KeyResolver.js +49 -42
- package/src/domain/services/ManifestDiff.js +56 -0
- package/src/domain/services/ManifestRepository.js +286 -0
- package/src/domain/services/PrefetchWindow.js +48 -0
- package/src/domain/services/RecipientService.js +157 -0
- package/src/domain/services/RedactingObservability.js +169 -0
- package/src/domain/services/RestorePipeline.js +68 -0
- package/src/domain/services/StorePipeline.js +201 -0
- package/src/domain/services/VaultKeyVerifier.js +101 -0
- package/src/domain/services/VaultMetadataCodec.js +206 -0
- package/src/domain/services/VaultMutationRetryPolicy.js +105 -0
- package/src/domain/services/VaultPersistence.js +410 -0
- package/src/domain/services/VaultPrivacyIndex.js +191 -0
- package/src/domain/services/VaultService.js +749 -251
- package/src/domain/services/VaultStateCache.js +225 -0
- package/src/domain/services/VaultTreeCodec.js +121 -0
- package/src/domain/services/rotateVaultPassphrase.js +37 -20
- package/src/domain/strategies/Aad.js +39 -0
- package/src/domain/strategies/FramedRecordCodec.js +204 -0
- package/src/domain/strategies/RestoreCompressed.js +40 -0
- package/src/domain/strategies/RestoreConvergent.js +44 -0
- package/src/domain/strategies/RestoreFramed.js +55 -0
- package/src/domain/strategies/RestorePlain.js +37 -0
- package/src/domain/strategies/RestoreStrategy.js +35 -0
- package/src/domain/strategies/RestoreWhole.js +135 -0
- package/src/domain/strategies/StoreConvergent.js +28 -0
- package/src/domain/strategies/StoreFramed.js +39 -0
- package/src/domain/strategies/StorePlain.js +20 -0
- package/src/domain/strategies/StoreStrategy.js +61 -0
- package/src/domain/strategies/StoreWhole.js +34 -0
- package/src/domain/value-objects/Chunk.js +1 -2
- package/src/domain/value-objects/EncryptionMetadata.js +87 -0
- package/src/domain/value-objects/Manifest.d.ts +40 -4
- package/src/domain/value-objects/Manifest.js +61 -20
- package/src/domain/value-objects/Oid.js +45 -0
- package/src/domain/value-objects/Slug.js +124 -0
- package/src/domain/value-objects/StoreEncryptionConfig.js +114 -0
- package/src/helpers/aesGcmMeta.js +55 -0
- package/src/helpers/canonicalBase64.js +1 -0
- package/src/helpers/kdfPolicy.js +194 -0
- package/src/infrastructure/adapters/BunCryptoAdapter.js +124 -8
- package/src/infrastructure/adapters/FileIOHelper.js +178 -13
- package/src/infrastructure/adapters/GitPersistenceAdapter.js +235 -42
- package/src/infrastructure/adapters/GitPlumbingFactoryAdapter.js +62 -0
- package/src/infrastructure/adapters/GitRefAdapter.js +19 -6
- package/src/infrastructure/adapters/NodeCompressionAdapter.js +64 -0
- package/src/infrastructure/adapters/NodeCryptoAdapter.js +130 -10
- package/src/infrastructure/adapters/WebCryptoAdapter.js +187 -77
- package/src/infrastructure/chunkers/CdcChunker.js +53 -19
- package/src/infrastructure/chunkers/FixedChunker.js +15 -7
- package/src/infrastructure/chunkers/resolveChunker.js +3 -1
- package/src/infrastructure/codecs/CborCodec.js +3 -3
- package/src/infrastructure/codecs/JsonCodec.js +5 -5
- package/src/infrastructure/createGitPlumbing.js +22 -0
- package/src/package-version.js +1 -0
- package/src/ports/ChunkingPort.js +3 -3
- package/src/ports/CodecPort.js +4 -4
- package/src/ports/CompressionPort.js +57 -0
- package/src/ports/CryptoPort.js +138 -50
- package/src/ports/GitPersistencePort.js +32 -2
- package/src/ports/GitPlumbingFactoryPort.js +16 -0
- package/src/ports/GitRefPort.js +1 -1
- package/src/types/ambient.d.ts +10 -5
- package/test/CONVENTIONS.md +94 -0
- package/test/cycles/README.md +13 -0
|
@@ -1,28 +1,52 @@
|
|
|
1
1
|
/* @ts-self-types="./CasService.d.ts" */
|
|
2
2
|
/**
|
|
3
|
-
* @fileoverview
|
|
3
|
+
* @fileoverview Lean domain facade for Content Addressable Storage operations.
|
|
4
4
|
* @module
|
|
5
5
|
*/
|
|
6
|
-
import { gunzip, createGzip } from 'node:zlib';
|
|
7
|
-
import { Readable } from 'node:stream';
|
|
8
|
-
import { promisify } from 'node:util';
|
|
9
6
|
import Manifest from '../value-objects/Manifest.js';
|
|
10
7
|
import CasError from '../errors/CasError.js';
|
|
11
|
-
import
|
|
12
|
-
import
|
|
8
|
+
import createCasError from '../errors/createCasError.js';
|
|
9
|
+
import { ErrorCodes } from '../errors/index.js';
|
|
10
|
+
import EncryptionMetadata from '../value-objects/EncryptionMetadata.js';
|
|
11
|
+
import StoreEncryptionConfig from '../value-objects/StoreEncryptionConfig.js';
|
|
13
12
|
import KeyResolver from './KeyResolver.js';
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
import ConvergentEncryption from './ConvergentEncryption.js';
|
|
14
|
+
import ChunkRepository from './ChunkRepository.js';
|
|
15
|
+
import CompressionStreams from './CompressionStreams.js';
|
|
16
|
+
import FramedRecordCodec from '../strategies/FramedRecordCodec.js';
|
|
17
|
+
import StorePlain from '../strategies/StorePlain.js';
|
|
18
|
+
import StoreConvergent from '../strategies/StoreConvergent.js';
|
|
19
|
+
import StoreFramed from '../strategies/StoreFramed.js';
|
|
20
|
+
import StoreWhole from '../strategies/StoreWhole.js';
|
|
21
|
+
import StoreStrategy from '../strategies/StoreStrategy.js';
|
|
22
|
+
import RestorePlain from '../strategies/RestorePlain.js';
|
|
23
|
+
import RestoreCompressed from '../strategies/RestoreCompressed.js';
|
|
24
|
+
import RestoreConvergent from '../strategies/RestoreConvergent.js';
|
|
25
|
+
import RestoreFramed from '../strategies/RestoreFramed.js';
|
|
26
|
+
import RestoreWhole from '../strategies/RestoreWhole.js';
|
|
27
|
+
import RestoreStrategy from '../strategies/RestoreStrategy.js';
|
|
28
|
+
import ManifestRepository from './ManifestRepository.js';
|
|
29
|
+
import RecipientService from './RecipientService.js';
|
|
30
|
+
import IntegrityVerifier from './IntegrityVerifier.js';
|
|
31
|
+
import RestoreSuccess from '../outcomes/RestoreSuccess.js';
|
|
32
|
+
import StoreSuccess from '../outcomes/StoreSuccess.js';
|
|
33
|
+
import diffManifests from './ManifestDiff.js';
|
|
34
|
+
import RedactingObservability from './RedactingObservability.js';
|
|
16
35
|
|
|
17
36
|
/**
|
|
18
37
|
* Domain service for Content Addressable Storage operations.
|
|
19
|
-
*
|
|
20
|
-
* Provides chunking, encryption, and integrity verification for storing
|
|
21
|
-
* arbitrary data in Git's object database.
|
|
22
38
|
*/
|
|
23
39
|
export default class CasService {
|
|
24
|
-
|
|
40
|
+
#chunkRepository;
|
|
41
|
+
#compression;
|
|
42
|
+
#framed;
|
|
43
|
+
#integrityVerifier;
|
|
25
44
|
#keyResolver;
|
|
45
|
+
#manifestRepository;
|
|
46
|
+
#merkleThresholdByManifest = new WeakMap();
|
|
47
|
+
#recipientService;
|
|
48
|
+
#restoreStrategies;
|
|
49
|
+
#storeStrategies;
|
|
26
50
|
|
|
27
51
|
/**
|
|
28
52
|
* @param {Object} options
|
|
@@ -30,722 +54,377 @@ export default class CasService {
|
|
|
30
54
|
* @param {import('../../ports/CodecPort.js').default} options.codec
|
|
31
55
|
* @param {import('../../ports/CryptoPort.js').default} options.crypto
|
|
32
56
|
* @param {import('../../ports/ObservabilityPort.js').default} options.observability
|
|
33
|
-
* @param {number} [options.chunkSize=262144]
|
|
34
|
-
* @param {number} [options.merkleThreshold=1000]
|
|
35
|
-
* @param {number} [options.concurrency=1]
|
|
36
|
-
* @param {import('../../ports/ChunkingPort.js').default}
|
|
37
|
-
* @param {number} [options.maxRestoreBufferSize=536870912]
|
|
57
|
+
* @param {number} [options.chunkSize=262144]
|
|
58
|
+
* @param {number} [options.merkleThreshold=1000]
|
|
59
|
+
* @param {number} [options.concurrency=1]
|
|
60
|
+
* @param {import('../../ports/ChunkingPort.js').default} options.chunker
|
|
61
|
+
* @param {number} [options.maxRestoreBufferSize=536870912]
|
|
62
|
+
* @param {number} [options.maxBlobSize=10485760]
|
|
63
|
+
* @param {import('../../ports/CompressionPort.js').default} options.compressionAdapter
|
|
64
|
+
* @param {string} [options.formatVersion]
|
|
65
|
+
* @param {boolean} [options.legacyMode=false]
|
|
38
66
|
*/
|
|
39
|
-
constructor({ persistence, codec, crypto, observability, chunkSize = 256 * 1024, merkleThreshold = 1000, concurrency = 1, chunker, maxRestoreBufferSize = 512 * 1024 * 1024 }) {
|
|
67
|
+
constructor({ persistence, codec, crypto, observability, chunkSize = 256 * 1024, merkleThreshold = 1000, concurrency = 1, chunker, maxRestoreBufferSize = 512 * 1024 * 1024, maxBlobSize = 10 * 1024 * 1024, compressionAdapter, formatVersion, legacyMode = false }) {
|
|
68
|
+
this.#init({ persistence, codec, crypto, observability, chunkSize, merkleThreshold, concurrency, chunker, maxRestoreBufferSize, maxBlobSize, compressionAdapter, formatVersion, legacyMode });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
#init({ persistence, codec, crypto, observability, chunkSize, merkleThreshold, concurrency, chunker, maxRestoreBufferSize, maxBlobSize, compressionAdapter, formatVersion, legacyMode }) {
|
|
40
72
|
CasService._validateObservability(observability);
|
|
41
|
-
CasService.#validateConstructorArgs({ chunkSize, merkleThreshold, concurrency, maxRestoreBufferSize });
|
|
73
|
+
CasService.#validateConstructorArgs({ chunkSize, merkleThreshold, concurrency, maxRestoreBufferSize, maxBlobSize, chunker, compressionAdapter });
|
|
74
|
+
const safeObservability = RedactingObservability.wrap(observability);
|
|
75
|
+
|
|
42
76
|
this.persistence = persistence;
|
|
43
77
|
this.codec = codec;
|
|
44
78
|
this.crypto = crypto;
|
|
45
|
-
this.observability =
|
|
79
|
+
this.observability = safeObservability;
|
|
46
80
|
this.chunkSize = chunkSize;
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
/** @type {import('../../ports/ChunkingPort.js').default} */
|
|
51
|
-
this.chunker = chunker || new FixedChunker({ chunkSize });
|
|
81
|
+
this.chunker = chunker;
|
|
82
|
+
this.compressionAdapter = compressionAdapter;
|
|
83
|
+
this.formatVersion = formatVersion;
|
|
52
84
|
this.merkleThreshold = merkleThreshold;
|
|
53
85
|
this.concurrency = concurrency;
|
|
54
86
|
this.maxRestoreBufferSize = maxRestoreBufferSize;
|
|
87
|
+
this.maxBlobSize = maxBlobSize;
|
|
88
|
+
|
|
89
|
+
if (chunkSize > 10 * 1024 * 1024) {
|
|
90
|
+
safeObservability.log('warn', `Chunk size ${chunkSize} exceeds 10 MiB — consider a smaller value`, { chunkSize });
|
|
91
|
+
}
|
|
92
|
+
if (typeof persistence.setMaxBlobSize === 'function') {
|
|
93
|
+
persistence.setMaxBlobSize(maxBlobSize);
|
|
94
|
+
}
|
|
95
|
+
|
|
55
96
|
this.#keyResolver = new KeyResolver(crypto);
|
|
97
|
+
const convergent = new ConvergentEncryption(crypto);
|
|
98
|
+
this.#compression = new CompressionStreams(compressionAdapter);
|
|
99
|
+
this.#chunkRepository = new ChunkRepository({
|
|
100
|
+
chunker,
|
|
101
|
+
concurrency,
|
|
102
|
+
convergent,
|
|
103
|
+
hashBytes: (buf) => this._sha256(buf),
|
|
104
|
+
observability: safeObservability,
|
|
105
|
+
persistence,
|
|
106
|
+
});
|
|
107
|
+
this.#framed = new FramedRecordCodec({ crypto, observability: safeObservability });
|
|
108
|
+
this.#manifestRepository = new ManifestRepository({ codec, crypto, legacyMode, merkleThreshold, persistence });
|
|
109
|
+
this.#storeStrategies = this.#buildStoreStrategies({ crypto });
|
|
110
|
+
this.#restoreStrategies = this.#buildRestoreStrategies({ crypto, maxRestoreBufferSize });
|
|
111
|
+
this.#recipientService = new RecipientService({ crypto, keyResolver: this.#keyResolver });
|
|
112
|
+
this.#initIntegrity({ safeObservability });
|
|
56
113
|
}
|
|
57
114
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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)`);
|
|
115
|
+
static #assertIntRange({ value, min, max, label }) {
|
|
116
|
+
if (!Number.isInteger(value) || value < min || value > max) {
|
|
117
|
+
throw createCasError(`${label} must be an integer in [${min}, ${max}]`, ErrorCodes.INVALID_OPTIONS, { label, value, min, max });
|
|
69
118
|
}
|
|
70
|
-
|
|
71
|
-
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
static #validateConstructorArgs({ chunkSize, merkleThreshold, concurrency, maxRestoreBufferSize, maxBlobSize, chunker, compressionAdapter }) {
|
|
122
|
+
CasService.#assertIntRange({ value: maxBlobSize, min: 1024, max: Number.MAX_SAFE_INTEGER, label: 'maxBlobSize' });
|
|
123
|
+
CasService.#assertIntRange({ value: chunkSize, min: 1024, max: 100 * 1024 * 1024, label: 'chunkSize' });
|
|
124
|
+
CasService.#assertIntRange({ value: merkleThreshold, min: 1, max: Number.MAX_SAFE_INTEGER, label: 'merkleThreshold' });
|
|
125
|
+
CasService.#assertIntRange({ value: concurrency, min: 1, max: 64, label: 'concurrency' });
|
|
126
|
+
CasService.#assertIntRange({ value: maxRestoreBufferSize, min: 1024, max: Number.MAX_SAFE_INTEGER, label: 'maxRestoreBufferSize' });
|
|
127
|
+
if (!chunker) {
|
|
128
|
+
throw createCasError('chunker is required — inject a ChunkingPort instance', ErrorCodes.INVALID_OPTIONS);
|
|
72
129
|
}
|
|
73
|
-
if (!
|
|
74
|
-
throw
|
|
130
|
+
if (!compressionAdapter) {
|
|
131
|
+
throw createCasError('compressionAdapter is required — inject a CompressionPort instance', ErrorCodes.INVALID_OPTIONS);
|
|
75
132
|
}
|
|
76
|
-
|
|
77
|
-
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
static #validateMerkleThreshold(merkleThreshold) {
|
|
136
|
+
if (merkleThreshold !== undefined) {
|
|
137
|
+
CasService.#assertIntRange({
|
|
138
|
+
value: merkleThreshold,
|
|
139
|
+
min: 1,
|
|
140
|
+
max: Number.MAX_SAFE_INTEGER,
|
|
141
|
+
label: 'merkleThreshold',
|
|
142
|
+
});
|
|
78
143
|
}
|
|
79
144
|
}
|
|
80
145
|
|
|
81
|
-
/**
|
|
82
|
-
* Validates that observability implements ObservabilityPort.
|
|
83
|
-
* @private
|
|
84
|
-
* @param {*} observability
|
|
85
|
-
*/
|
|
86
146
|
static _validateObservability(observability) {
|
|
87
|
-
if (
|
|
88
|
-
|
|
89
|
-
typeof observability.metric !== 'function' ||
|
|
90
|
-
typeof observability.log !== 'function' ||
|
|
91
|
-
typeof observability.span !== 'function'
|
|
92
|
-
) {
|
|
93
|
-
throw new Error('observability must implement ObservabilityPort');
|
|
147
|
+
if (!observability || typeof observability.metric !== 'function' || typeof observability.log !== 'function' || typeof observability.span !== 'function') {
|
|
148
|
+
throw createCasError('observability must implement ObservabilityPort', ErrorCodes.INVALID_OPTIONS);
|
|
94
149
|
}
|
|
95
150
|
}
|
|
96
151
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
152
|
+
#buildStoreStrategies({ crypto }) {
|
|
153
|
+
return Object.freeze({
|
|
154
|
+
plain: new StorePlain(this.#chunkRepository),
|
|
155
|
+
convergent: new StoreConvergent(this.#chunkRepository),
|
|
156
|
+
framed: new StoreFramed({ chunks: this.#chunkRepository, framed: this.#framed }),
|
|
157
|
+
whole: new StoreWhole({ chunks: this.#chunkRepository, crypto }),
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
#buildRestoreStrategies({ crypto, maxRestoreBufferSize }) {
|
|
162
|
+
return Object.freeze({
|
|
163
|
+
plain: new RestorePlain({ chunks: this.#chunkRepository, observability: this.observability }),
|
|
164
|
+
compressed: new RestoreCompressed({ chunks: this.#chunkRepository, compression: this.#compression, observability: this.observability }),
|
|
165
|
+
convergent: new RestoreConvergent({ chunks: this.#chunkRepository, compression: this.#compression, observability: this.observability }),
|
|
166
|
+
framed: new RestoreFramed({
|
|
167
|
+
chunks: this.#chunkRepository,
|
|
168
|
+
compression: this.#compression,
|
|
169
|
+
framed: this.#framed,
|
|
170
|
+
isLegacyNoAad: (manifest) => this._isLegacyNoAad(manifest),
|
|
171
|
+
observability: this.observability,
|
|
172
|
+
}),
|
|
173
|
+
whole: new RestoreWhole({
|
|
174
|
+
chunkSize: this.chunkSize,
|
|
175
|
+
chunks: this.#chunkRepository,
|
|
176
|
+
compression: this.#compression,
|
|
177
|
+
crypto,
|
|
178
|
+
isLegacyNoAad: (manifest) => this._isLegacyNoAad(manifest),
|
|
179
|
+
maxRestoreBufferSize,
|
|
180
|
+
observability: this.observability,
|
|
181
|
+
}),
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
103
185
|
async _sha256(buf) {
|
|
104
186
|
return await this.crypto.sha256(buf);
|
|
105
187
|
}
|
|
106
188
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
* @private
|
|
110
|
-
* @param {Buffer} buf - The chunk data to store.
|
|
111
|
-
* @param {number} index - Chunk index.
|
|
112
|
-
* @returns {Promise<{ index: number, size: number, digest: string, blob: string }>}
|
|
113
|
-
*/
|
|
114
|
-
async _storeChunk(buf, index) {
|
|
115
|
-
const digest = await this._sha256(buf);
|
|
116
|
-
const blob = await this.persistence.writeBlob(buf);
|
|
117
|
-
this.observability.metric('chunk', { action: 'stored', index, size: buf.length, digest, blob });
|
|
118
|
-
return { index, size: buf.length, digest, blob };
|
|
189
|
+
async encrypt({ buffer, key }) {
|
|
190
|
+
return await this.crypto.encryptBuffer(buffer, key);
|
|
119
191
|
}
|
|
120
192
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
* @throws {CasError} STREAM_ERROR if the source stream fails.
|
|
128
|
-
*/
|
|
129
|
-
async _chunkAndStore(source, manifestData) {
|
|
130
|
-
const sem = new Semaphore(this.concurrency);
|
|
131
|
-
const pending = [];
|
|
132
|
-
let nextIndex = 0;
|
|
133
|
-
|
|
134
|
-
const launchWrite = (buf, idx) => {
|
|
135
|
-
const p = sem.acquire().then(async () => {
|
|
136
|
-
try {
|
|
137
|
-
return await this._storeChunk(buf, idx);
|
|
138
|
-
} finally {
|
|
139
|
-
sem.release();
|
|
140
|
-
}
|
|
141
|
-
});
|
|
142
|
-
pending.push(p);
|
|
143
|
-
};
|
|
193
|
+
async decrypt({ buffer, key, meta }) {
|
|
194
|
+
if (!meta?.encrypted) {
|
|
195
|
+
return buffer;
|
|
196
|
+
}
|
|
197
|
+
return await this._decryptWithAad({ buffer, key, meta });
|
|
198
|
+
}
|
|
144
199
|
|
|
200
|
+
async _decryptWithAad({ buffer, key, meta, aad }) {
|
|
201
|
+
if (!meta?.encrypted) {
|
|
202
|
+
return buffer;
|
|
203
|
+
}
|
|
145
204
|
try {
|
|
146
|
-
|
|
147
|
-
launchWrite(chunk, nextIndex++);
|
|
148
|
-
}
|
|
205
|
+
return await this.crypto.decryptBuffer(buffer, key, meta, aad);
|
|
149
206
|
} catch (err) {
|
|
150
|
-
const settled = await Promise.allSettled(pending);
|
|
151
|
-
const orphanedBlobs = settled
|
|
152
|
-
.filter((r) => r.status === 'fulfilled')
|
|
153
|
-
.map((r) => r.value.blob);
|
|
154
207
|
if (err instanceof CasError) {
|
|
155
|
-
err.meta = { ...err.meta, orphanedBlobs };
|
|
156
208
|
throw err;
|
|
157
209
|
}
|
|
158
|
-
|
|
159
|
-
`Stream error during store: ${err.message}`,
|
|
160
|
-
'STREAM_ERROR',
|
|
161
|
-
{ chunksDispatched: nextIndex, orphanedBlobs, originalError: err },
|
|
162
|
-
);
|
|
163
|
-
this.observability.metric('error', {
|
|
164
|
-
code: casErr.code, message: casErr.message,
|
|
165
|
-
orphanedBlobs: orphanedBlobs.length,
|
|
166
|
-
});
|
|
167
|
-
throw casErr;
|
|
210
|
+
throw createCasError('Decryption failed: Integrity check error', ErrorCodes.INTEGRITY_ERROR, { originalError: err });
|
|
168
211
|
}
|
|
212
|
+
}
|
|
169
213
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
214
|
+
_resolveStoreEncryptionConfig(encryption, hasEncryptionKey) {
|
|
215
|
+
return StoreEncryptionConfig.resolve({
|
|
216
|
+
encryption,
|
|
217
|
+
hasEncryptionKey,
|
|
218
|
+
chunker: this.chunker,
|
|
219
|
+
observability: this.observability,
|
|
220
|
+
});
|
|
176
221
|
}
|
|
177
222
|
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
* @param {Object} options
|
|
181
|
-
* @param {Buffer} options.buffer - Plaintext data to encrypt.
|
|
182
|
-
* @param {Buffer} options.key - 32-byte encryption key.
|
|
183
|
-
* @returns {Promise<{ buf: Buffer, meta: { algorithm: string, nonce: string, tag: string, encrypted: boolean } }>}
|
|
184
|
-
* @throws {CasError} INVALID_KEY_TYPE | INVALID_KEY_LENGTH if the key is invalid.
|
|
185
|
-
*/
|
|
186
|
-
async encrypt({ buffer, key }) {
|
|
187
|
-
return await this.crypto.encryptBuffer(buffer, key);
|
|
223
|
+
_resolveFramedStoreEncryptionConfig(frameBytes) {
|
|
224
|
+
return StoreEncryptionConfig.resolveFramed(frameBytes);
|
|
188
225
|
}
|
|
189
226
|
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
* @param {Object} options
|
|
193
|
-
* @param {Buffer} options.buffer - Ciphertext to decrypt.
|
|
194
|
-
* @param {Buffer} options.key - 32-byte encryption key.
|
|
195
|
-
* @param {{ encrypted: boolean, algorithm: string, nonce: string, tag: string }} options.meta - Encryption metadata from the manifest.
|
|
196
|
-
* @returns {Promise<Buffer>} Decrypted plaintext.
|
|
197
|
-
* @throws {CasError} INTEGRITY_ERROR if authentication tag verification fails.
|
|
198
|
-
*/
|
|
199
|
-
async decrypt({ buffer, key, meta }) {
|
|
200
|
-
if (!meta?.encrypted) {
|
|
201
|
-
return buffer;
|
|
202
|
-
}
|
|
203
|
-
try {
|
|
204
|
-
return await this.crypto.decryptBuffer(buffer, key, meta);
|
|
205
|
-
} catch (err) {
|
|
206
|
-
if (err instanceof CasError) {throw err;}
|
|
207
|
-
throw new CasError('Decryption failed: Integrity check error', 'INTEGRITY_ERROR', { originalError: err });
|
|
208
|
-
}
|
|
227
|
+
_validatedEncryptionMeta(manifest) {
|
|
228
|
+
return EncryptionMetadata.fromManifest(manifest);
|
|
209
229
|
}
|
|
210
230
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
* @private
|
|
214
|
-
* @param {AsyncIterable<Buffer>} source
|
|
215
|
-
* @returns {AsyncIterable<Buffer>}
|
|
216
|
-
*/
|
|
217
|
-
async *_compressStream(source) {
|
|
218
|
-
const gz = createGzip();
|
|
219
|
-
const input = Readable.from(source);
|
|
220
|
-
const compressed = input.pipe(gz);
|
|
221
|
-
for await (const chunk of compressed) {
|
|
222
|
-
yield chunk;
|
|
223
|
-
}
|
|
231
|
+
_emitIntegrityFail(manifest, extra = {}) {
|
|
232
|
+
this.observability.metric('integrity', { action: 'fail', slug: manifest.slug, ...extra });
|
|
224
233
|
}
|
|
225
234
|
|
|
226
|
-
/**
|
|
227
|
-
* Validates and normalizes compression options.
|
|
228
|
-
* @private
|
|
229
|
-
*/
|
|
230
235
|
_validateCompression(compression) {
|
|
231
236
|
if (compression?.algorithm && compression.algorithm !== 'gzip') {
|
|
232
|
-
throw
|
|
233
|
-
`Unsupported compression algorithm: ${compression.algorithm}`,
|
|
234
|
-
'INVALID_OPTIONS',
|
|
235
|
-
);
|
|
237
|
+
throw createCasError(`Unsupported compression algorithm: ${compression.algorithm}`, ErrorCodes.INVALID_OPTIONS);
|
|
236
238
|
}
|
|
237
239
|
}
|
|
238
240
|
|
|
239
|
-
/**
|
|
240
|
-
* Validates that a chunking strategy is recognized.
|
|
241
|
-
* @param {Object} [chunking] - Chunking options from a manifest.
|
|
242
|
-
* @throws {CasError} INVALID_CHUNKING_STRATEGY if the strategy is unrecognized.
|
|
243
|
-
* @private
|
|
244
|
-
*/
|
|
245
241
|
_validateChunking(chunking) {
|
|
246
|
-
if (!chunking) {
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
242
|
+
if (!chunking) {
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
if (!['fixed', 'cdc'].includes(chunking.strategy)) {
|
|
246
|
+
throw createCasError(
|
|
250
247
|
`Unsupported chunking strategy: ${chunking.strategy}`,
|
|
251
|
-
|
|
248
|
+
ErrorCodes.INVALID_CHUNKING_STRATEGY,
|
|
252
249
|
{ strategy: chunking.strategy },
|
|
253
250
|
);
|
|
254
251
|
}
|
|
255
252
|
}
|
|
256
253
|
|
|
257
254
|
/**
|
|
258
|
-
* Chunks an async iterable source and stores it in Git.
|
|
259
|
-
*
|
|
260
|
-
* Supports two encryption modes: direct key/passphrase or envelope encryption
|
|
261
|
-
* via `recipients` (DEK/KEK model). The modes are mutually exclusive.
|
|
262
|
-
*
|
|
263
255
|
* @param {Object} options
|
|
264
|
-
* @param {AsyncIterable<
|
|
256
|
+
* @param {AsyncIterable<Uint8Array>} options.source
|
|
265
257
|
* @param {string} options.slug
|
|
266
258
|
* @param {string} options.filename
|
|
267
|
-
* @param {
|
|
268
|
-
* @param {string} [options.passphrase]
|
|
269
|
-
* @param {
|
|
270
|
-
* @param {
|
|
271
|
-
* @param {
|
|
272
|
-
* @
|
|
273
|
-
|
|
274
|
-
|
|
259
|
+
* @param {Uint8Array} [options.encryptionKey]
|
|
260
|
+
* @param {string} [options.passphrase]
|
|
261
|
+
* @param {{ scheme?: 'whole'|'framed'|'convergent', frameBytes?: number, convergent?: boolean }} [options.encryption]
|
|
262
|
+
* @param {Object} [options.kdfOptions]
|
|
263
|
+
* @param {{ algorithm: 'gzip' }} [options.compression]
|
|
264
|
+
* @param {Array<{label: string, key: Uint8Array}>} [options.recipients]
|
|
265
|
+
* @param {number} [options.merkleThreshold]
|
|
266
|
+
* @returns {Promise<Manifest>}
|
|
267
|
+
*/
|
|
268
|
+
async store({
|
|
269
|
+
source,
|
|
270
|
+
slug,
|
|
271
|
+
filename,
|
|
272
|
+
encryptionKey,
|
|
273
|
+
passphrase,
|
|
274
|
+
encryption,
|
|
275
|
+
kdfOptions,
|
|
276
|
+
compression,
|
|
277
|
+
recipients,
|
|
278
|
+
merkleThreshold,
|
|
279
|
+
}) {
|
|
280
|
+
if (!source || typeof source[Symbol.asyncIterator] !== 'function') {
|
|
281
|
+
throw createCasError('source must be an async iterable', ErrorCodes.INVALID_OPTIONS, { sourceType: typeof source });
|
|
282
|
+
}
|
|
275
283
|
if (recipients && (encryptionKey || passphrase)) {
|
|
276
|
-
throw
|
|
284
|
+
throw createCasError('Provide recipients or encryptionKey/passphrase, not both', ErrorCodes.INVALID_OPTIONS);
|
|
277
285
|
}
|
|
278
286
|
KeyResolver.validateKeySourceExclusive(encryptionKey, passphrase);
|
|
279
287
|
this._validateCompression(compression);
|
|
288
|
+
CasService.#validateMerkleThreshold(merkleThreshold);
|
|
280
289
|
|
|
281
290
|
const keyInfo = recipients
|
|
282
291
|
? await this.#keyResolver.resolveRecipients(recipients)
|
|
283
292
|
: await this.#keyResolver.resolveForStore(encryptionKey, passphrase, kdfOptions);
|
|
284
|
-
|
|
293
|
+
const encryptionConfig = this._resolveStoreEncryptionConfig(encryption, !!keyInfo.key);
|
|
285
294
|
const manifestData = this._buildManifestData(slug, filename, compression);
|
|
286
|
-
const processedSource = compression ? this.
|
|
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
|
-
}
|
|
295
|
-
if (keyInfo.key) {
|
|
296
|
-
const { encrypt, finalize } = this.crypto.createEncryptionStream(keyInfo.key);
|
|
297
|
-
await this._chunkAndStore(encrypt(processedSource), manifestData);
|
|
298
|
-
manifestData.encryption = { ...finalize(), ...keyInfo.encExtra };
|
|
299
|
-
} else {
|
|
300
|
-
await this._chunkAndStore(processedSource, manifestData);
|
|
301
|
-
}
|
|
295
|
+
const processedSource = compression ? this.#compression.compress(source) : source;
|
|
302
296
|
|
|
297
|
+
await this._dispatchStore({ processedSource, manifestData, keyInfo, encryptionConfig });
|
|
303
298
|
const manifest = new Manifest(manifestData);
|
|
299
|
+
this.#rememberMerkleThreshold(manifest, merkleThreshold);
|
|
304
300
|
this.observability.metric('file', {
|
|
305
|
-
action: 'stored',
|
|
301
|
+
action: 'stored',
|
|
302
|
+
slug,
|
|
303
|
+
size: manifest.size,
|
|
304
|
+
chunkCount: manifest.chunks.length,
|
|
305
|
+
encrypted: !!keyInfo.key,
|
|
306
306
|
});
|
|
307
|
-
return manifest;
|
|
307
|
+
return new StoreSuccess({ manifest }).manifest;
|
|
308
308
|
}
|
|
309
309
|
|
|
310
310
|
/**
|
|
311
|
-
*
|
|
312
|
-
* @
|
|
311
|
+
* @param {Manifest} manifest
|
|
312
|
+
* @param {number|undefined} merkleThreshold
|
|
313
313
|
*/
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
data.chunking = { strategy: this.chunker.strategy, params: this.chunker.params };
|
|
314
|
+
#rememberMerkleThreshold(manifest, merkleThreshold) {
|
|
315
|
+
if (merkleThreshold !== undefined) {
|
|
316
|
+
this.#merkleThresholdByManifest.set(manifest, merkleThreshold);
|
|
318
317
|
}
|
|
319
|
-
if (compression) { data.compression = { algorithm: 'gzip' }; }
|
|
320
|
-
return data;
|
|
321
318
|
}
|
|
322
319
|
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
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;
|
|
320
|
+
async _dispatchStore({ processedSource, manifestData, keyInfo, encryptionConfig }) {
|
|
321
|
+
const strategy = StoreStrategy.for({
|
|
322
|
+
keyInfo,
|
|
323
|
+
encryptionConfig,
|
|
324
|
+
chunker: this.chunker,
|
|
325
|
+
observability: this.observability,
|
|
326
|
+
strategies: this.#storeStrategies,
|
|
327
|
+
});
|
|
328
|
+
await strategy.execute({ processedSource, manifestData, keyInfo, encryptionConfig });
|
|
347
329
|
}
|
|
348
330
|
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
* unique chunk digest, preserving first-seen order.
|
|
354
|
-
*
|
|
355
|
-
* @param {Object} options
|
|
356
|
-
* @param {import('../value-objects/Manifest.js').default} options.manifest - The file manifest.
|
|
357
|
-
* @returns {Promise<string>} Git OID of the created tree.
|
|
358
|
-
*/
|
|
359
|
-
async createTree({ manifest }) {
|
|
360
|
-
const chunks = manifest.chunks;
|
|
361
|
-
|
|
362
|
-
if (chunks.length > this.merkleThreshold) {
|
|
363
|
-
return await this._createMerkleTree({ manifest });
|
|
331
|
+
_buildManifestData(slug, filename, compression) {
|
|
332
|
+
const data = { slug, filename, size: 0, chunks: [] };
|
|
333
|
+
if (this.formatVersion) {
|
|
334
|
+
data.formatVersion = this.formatVersion;
|
|
364
335
|
}
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
const manifestOid = await this.persistence.writeBlob(serializedManifest);
|
|
368
|
-
|
|
369
|
-
const treeEntries = [
|
|
370
|
-
`100644 blob ${manifestOid}\tmanifest.${this.codec.extension}`,
|
|
371
|
-
...this._createChunkTreeEntries(chunks),
|
|
372
|
-
];
|
|
373
|
-
|
|
374
|
-
return await this.persistence.writeTree(treeEntries);
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
/**
|
|
378
|
-
* Creates a Merkle tree by splitting chunks into sub-manifests.
|
|
379
|
-
* @private
|
|
380
|
-
* @param {Object} options
|
|
381
|
-
* @param {import('../value-objects/Manifest.js').default} options.manifest
|
|
382
|
-
* @returns {Promise<string>} Git tree OID.
|
|
383
|
-
*/
|
|
384
|
-
async _createMerkleTree({ manifest }) {
|
|
385
|
-
const chunks = [...manifest.chunks];
|
|
386
|
-
const subManifestRefs = [];
|
|
387
|
-
|
|
388
|
-
for (let i = 0; i < chunks.length; i += this.merkleThreshold) {
|
|
389
|
-
const group = chunks.slice(i, i + this.merkleThreshold);
|
|
390
|
-
const subManifestData = { chunks: group.map((c) => ({ index: c.index, size: c.size, digest: c.digest, blob: c.blob })) };
|
|
391
|
-
const serialized = this.codec.encode(subManifestData);
|
|
392
|
-
const oid = await this.persistence.writeBlob(serialized);
|
|
393
|
-
|
|
394
|
-
subManifestRefs.push({
|
|
395
|
-
oid,
|
|
396
|
-
chunkCount: group.length,
|
|
397
|
-
startIndex: i,
|
|
398
|
-
});
|
|
336
|
+
if (this.chunker.strategy !== 'fixed') {
|
|
337
|
+
data.chunking = { strategy: this.chunker.strategy, params: this.chunker.params };
|
|
399
338
|
}
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
chunks: [],
|
|
405
|
-
subManifests: subManifestRefs,
|
|
406
|
-
};
|
|
407
|
-
|
|
408
|
-
const serializedRoot = this.codec.encode(rootManifestData);
|
|
409
|
-
const rootOid = await this.persistence.writeBlob(serializedRoot);
|
|
410
|
-
|
|
411
|
-
const subManifestEntries = subManifestRefs.map(
|
|
412
|
-
(ref, idx) => `100644 blob ${ref.oid}\tsub-manifest-${idx}.${this.codec.extension}`,
|
|
413
|
-
);
|
|
414
|
-
|
|
415
|
-
const treeEntries = [
|
|
416
|
-
`100644 blob ${rootOid}\tmanifest.${this.codec.extension}`,
|
|
417
|
-
...subManifestEntries,
|
|
418
|
-
...this._createChunkTreeEntries(chunks),
|
|
419
|
-
];
|
|
420
|
-
|
|
421
|
-
return await this.persistence.writeTree(treeEntries);
|
|
339
|
+
if (compression) {
|
|
340
|
+
data.compression = { algorithm: 'gzip' };
|
|
341
|
+
}
|
|
342
|
+
return data;
|
|
422
343
|
}
|
|
423
344
|
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
* @private
|
|
427
|
-
* @param {{ index: number, size: number, digest: string, blob: string }} chunk - Chunk metadata.
|
|
428
|
-
* @returns {Promise<Buffer>} Verified chunk buffer.
|
|
429
|
-
* @throws {CasError} INTEGRITY_ERROR if the chunk digest does not match.
|
|
430
|
-
*/
|
|
431
|
-
async _readAndVerifyChunk(chunk) {
|
|
432
|
-
const blob = await this.persistence.readBlob(chunk.blob);
|
|
433
|
-
const digest = await this._sha256(blob);
|
|
434
|
-
if (digest !== chunk.digest) {
|
|
435
|
-
const err = new CasError(
|
|
436
|
-
`Chunk ${chunk.index} integrity check failed`,
|
|
437
|
-
'INTEGRITY_ERROR',
|
|
438
|
-
{ chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
|
|
439
|
-
);
|
|
440
|
-
this.observability.metric('error', { code: err.code, message: err.message });
|
|
441
|
-
throw err;
|
|
442
|
-
}
|
|
443
|
-
return blob;
|
|
345
|
+
_isLegacyNoAad(manifest) {
|
|
346
|
+
return this.#manifestRepository.isLegacyNoAad(manifest);
|
|
444
347
|
}
|
|
445
348
|
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
*/
|
|
453
|
-
async _readAndVerifyChunks(chunks) {
|
|
454
|
-
const buffers = [];
|
|
455
|
-
for (const chunk of chunks) {
|
|
456
|
-
const blob = await this._readAndVerifyChunk(chunk);
|
|
457
|
-
buffers.push(blob);
|
|
458
|
-
this.observability.metric('chunk', { action: 'restored', index: chunk.index, size: blob.length, digest: chunk.digest });
|
|
459
|
-
}
|
|
460
|
-
return buffers;
|
|
349
|
+
async createTree({ manifest, merkleThreshold }) {
|
|
350
|
+
CasService.#validateMerkleThreshold(merkleThreshold);
|
|
351
|
+
return await this.#manifestRepository.createTree({
|
|
352
|
+
manifest,
|
|
353
|
+
merkleThreshold: merkleThreshold ?? this.#merkleThresholdByManifest.get(manifest),
|
|
354
|
+
});
|
|
461
355
|
}
|
|
462
356
|
|
|
463
|
-
/**
|
|
464
|
-
* Restores a file from its manifest by reading and reassembling chunks.
|
|
465
|
-
*
|
|
466
|
-
* If the manifest has encryption metadata, decrypts the reassembled
|
|
467
|
-
* ciphertext using the provided key.
|
|
468
|
-
*
|
|
469
|
-
* @param {Object} options
|
|
470
|
-
* @param {import('../value-objects/Manifest.js').default} options.manifest - The file manifest.
|
|
471
|
-
* @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
|
|
472
|
-
* @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
|
|
473
|
-
* @returns {Promise<{ buffer: Buffer, bytesWritten: number }>}
|
|
474
|
-
* @throws {CasError} MISSING_KEY if manifest is encrypted but no key is provided.
|
|
475
|
-
* @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
|
|
476
|
-
*/
|
|
477
357
|
async restore({ manifest, encryptionKey, passphrase }) {
|
|
478
358
|
const chunks = [];
|
|
479
359
|
for await (const chunk of this.restoreStream({ manifest, encryptionKey, passphrase })) {
|
|
480
360
|
chunks.push(chunk);
|
|
481
361
|
}
|
|
482
|
-
|
|
483
|
-
return { buffer, bytesWritten: buffer.length };
|
|
362
|
+
return RestoreSuccess.fromChunks(chunks);
|
|
484
363
|
}
|
|
485
364
|
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
* @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
|
|
496
|
-
* @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
|
|
497
|
-
* Note: For unencrypted files, each yielded buffer corresponds to an original
|
|
498
|
-
* stored chunk. For encrypted/compressed files, yielded buffers are
|
|
499
|
-
* chunkSize-sliced pieces of the decrypted/decompressed result and may not
|
|
500
|
-
* correspond 1:1 to the original chunks.
|
|
501
|
-
*
|
|
502
|
-
* @yields {Buffer}
|
|
503
|
-
* @throws {CasError} MISSING_KEY if manifest is encrypted but no key is provided.
|
|
504
|
-
* @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
|
|
505
|
-
*/
|
|
506
|
-
async *restoreStream({ manifest, encryptionKey, passphrase }) {
|
|
507
|
-
const key = await this.#keyResolver.resolveForDecryption(manifest, encryptionKey, passphrase);
|
|
508
|
-
|
|
509
|
-
if (manifest.chunks.length === 0) {
|
|
510
|
-
this.observability.metric('file', {
|
|
511
|
-
action: 'restored', slug: manifest.slug, size: 0, chunkCount: 0,
|
|
512
|
-
});
|
|
513
|
-
return;
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
if (manifest.encryption?.encrypted || manifest.compression) {
|
|
517
|
-
yield* this._restoreBuffered(manifest, key);
|
|
518
|
-
} else {
|
|
519
|
-
yield* this._restoreStreaming(manifest);
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
/**
|
|
524
|
-
* Buffered restore path for encrypted/compressed manifests.
|
|
525
|
-
* @private
|
|
526
|
-
*/
|
|
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
|
-
}
|
|
538
|
-
let buffer = Buffer.concat(await this._readAndVerifyChunks(manifest.chunks));
|
|
539
|
-
|
|
540
|
-
if (manifest.encryption?.encrypted) {
|
|
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
|
-
}
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
if (manifest.compression) {
|
|
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
|
-
}
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
this.observability.metric('file', {
|
|
563
|
-
action: 'restored', slug: manifest.slug, size: buffer.length, chunkCount: manifest.chunks.length,
|
|
564
|
-
});
|
|
565
|
-
|
|
566
|
-
for (let offset = 0; offset < buffer.length; offset += this.chunkSize) {
|
|
567
|
-
yield buffer.subarray(offset, offset + this.chunkSize);
|
|
365
|
+
async createFileRestorePlan({ manifest, encryptionKey, passphrase }) {
|
|
366
|
+
const encryptionMeta = this._validatedEncryptionMeta(manifest);
|
|
367
|
+
if (encryptionMeta?.scheme === 'whole') {
|
|
368
|
+
const key = await this.#keyResolver.resolveForDecryption(manifest, encryptionKey, passphrase);
|
|
369
|
+
return {
|
|
370
|
+
mode: 'bounded-file',
|
|
371
|
+
source: await this.#restoreStrategies.whole.createBoundedSource({ manifest, key, encryptionMeta }),
|
|
372
|
+
encryptionMeta,
|
|
373
|
+
};
|
|
568
374
|
}
|
|
375
|
+
return {
|
|
376
|
+
mode: 'stream',
|
|
377
|
+
source: this.restoreStream({ manifest, encryptionKey, passphrase }),
|
|
378
|
+
encryptionMeta,
|
|
379
|
+
};
|
|
569
380
|
}
|
|
570
381
|
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
*/
|
|
575
|
-
async *_restoreStreaming(manifest) {
|
|
576
|
-
const chunks = manifest.chunks;
|
|
577
|
-
const readAhead = this.concurrency;
|
|
578
|
-
let totalSize = 0;
|
|
579
|
-
|
|
580
|
-
const readAndVerify = (chunk) => this._readAndVerifyChunk(chunk);
|
|
581
|
-
|
|
582
|
-
const ahead = [];
|
|
583
|
-
for (let i = 0; i < Math.min(readAhead, chunks.length); i++) {
|
|
584
|
-
ahead.push(readAndVerify(chunks[i]));
|
|
585
|
-
}
|
|
382
|
+
async *restoreStream({ manifest, encryptionKey, passphrase }) {
|
|
383
|
+
const encryptionMeta = this._validatedEncryptionMeta(manifest);
|
|
384
|
+
const key = await this.#keyResolver.resolveForDecryption(manifest, encryptionKey, passphrase);
|
|
586
385
|
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
this.observability.metric('chunk', { action: 'restored', index: chunks[i].index, size: blob.length, digest: chunks[i].digest });
|
|
591
|
-
totalSize += blob.length;
|
|
592
|
-
const nextIdx = i + readAhead;
|
|
593
|
-
if (nextIdx < chunks.length) {
|
|
594
|
-
ahead[i % readAhead] = readAndVerify(chunks[nextIdx]);
|
|
595
|
-
}
|
|
596
|
-
yield blob;
|
|
597
|
-
}
|
|
598
|
-
} finally {
|
|
599
|
-
await Promise.allSettled(ahead);
|
|
386
|
+
if (manifest.chunks.length === 0 && !encryptionMeta && !manifest.compression) {
|
|
387
|
+
this.observability.metric('file', { action: 'restored', slug: manifest.slug, size: 0, chunkCount: 0 });
|
|
388
|
+
return;
|
|
600
389
|
}
|
|
601
390
|
|
|
602
|
-
this.
|
|
603
|
-
action: 'restored', slug: manifest.slug, size: totalSize, chunkCount: chunks.length,
|
|
604
|
-
});
|
|
391
|
+
yield* this._dispatchRestore(manifest, key, encryptionMeta);
|
|
605
392
|
}
|
|
606
393
|
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
*/
|
|
611
|
-
async _decompress(buffer) {
|
|
612
|
-
try {
|
|
613
|
-
return await gunzipAsync(buffer);
|
|
614
|
-
} catch (err) {
|
|
615
|
-
if (err instanceof CasError) { throw err; }
|
|
616
|
-
throw new CasError(`Decompression failed: ${err.message}`, 'INTEGRITY_ERROR', { originalError: err });
|
|
617
|
-
}
|
|
394
|
+
async *_dispatchRestore(manifest, key, encryptionMeta) {
|
|
395
|
+
const strategy = RestoreStrategy.for({ manifest, encryptionMeta, strategies: this.#restoreStrategies });
|
|
396
|
+
yield* strategy.execute({ manifest, key, encryptionMeta });
|
|
618
397
|
}
|
|
619
398
|
|
|
620
|
-
/**
|
|
621
|
-
* Reads a manifest from a Git tree OID.
|
|
622
|
-
*
|
|
623
|
-
* @param {Object} options
|
|
624
|
-
* @param {string} options.treeOid - Git tree OID to read the manifest from
|
|
625
|
-
* @returns {Promise<import('../value-objects/Manifest.js').default>}
|
|
626
|
-
* @throws {CasError} MANIFEST_NOT_FOUND if no manifest entry exists in the tree
|
|
627
|
-
* @throws {CasError} GIT_ERROR if the underlying Git command fails
|
|
628
|
-
*/
|
|
629
399
|
async readManifest({ treeOid }) {
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
entries = await this.persistence.readTree(treeOid);
|
|
633
|
-
} catch (err) {
|
|
634
|
-
if (err instanceof CasError) { throw err; }
|
|
635
|
-
throw new CasError(
|
|
636
|
-
`Failed to read tree ${treeOid}: ${err.message}`,
|
|
637
|
-
'GIT_ERROR',
|
|
638
|
-
{ treeOid, originalError: err },
|
|
639
|
-
);
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
const manifestName = `manifest.${this.codec.extension}`;
|
|
643
|
-
const manifestEntry = entries.find((e) => e.name === manifestName);
|
|
644
|
-
|
|
645
|
-
if (!manifestEntry) {
|
|
646
|
-
throw new CasError(
|
|
647
|
-
`No manifest entry (${manifestName}) found in tree ${treeOid}`,
|
|
648
|
-
'MANIFEST_NOT_FOUND',
|
|
649
|
-
{ treeOid, expectedName: manifestName },
|
|
650
|
-
);
|
|
651
|
-
}
|
|
652
|
-
|
|
653
|
-
let blob;
|
|
654
|
-
try {
|
|
655
|
-
blob = await this.persistence.readBlob(manifestEntry.oid);
|
|
656
|
-
} catch (err) {
|
|
657
|
-
if (err instanceof CasError) { throw err; }
|
|
658
|
-
throw new CasError(
|
|
659
|
-
`Failed to read manifest blob ${manifestEntry.oid}: ${err.message}`,
|
|
660
|
-
'GIT_ERROR',
|
|
661
|
-
{ treeOid, manifestOid: manifestEntry.oid, originalError: err },
|
|
662
|
-
);
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
const decoded = this.codec.decode(blob);
|
|
666
|
-
|
|
667
|
-
if (decoded.version === 2 && decoded.subManifests?.length > 0) {
|
|
668
|
-
decoded.chunks = await this._resolveSubManifests(decoded.subManifests, treeOid);
|
|
669
|
-
}
|
|
400
|
+
return await this.#manifestRepository.readManifest({ treeOid });
|
|
401
|
+
}
|
|
670
402
|
|
|
671
|
-
|
|
403
|
+
async readManifestRaw({ treeOid }) {
|
|
404
|
+
return await this.#manifestRepository.readManifestRaw({ treeOid });
|
|
672
405
|
}
|
|
673
406
|
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
* @private
|
|
677
|
-
* @param {Array<{ oid: string }>} subManifests - Sub-manifest references.
|
|
678
|
-
* @param {string} treeOid - Parent tree OID (for error context).
|
|
679
|
-
* @returns {Promise<Array>} Flattened chunk entries.
|
|
680
|
-
*/
|
|
681
|
-
async _resolveSubManifests(subManifests, treeOid) {
|
|
682
|
-
const allChunks = [];
|
|
683
|
-
for (const ref of subManifests) {
|
|
684
|
-
const subBlob = await this._readSubManifestBlob(ref.oid, treeOid);
|
|
685
|
-
const subDecoded = this.codec.decode(subBlob);
|
|
686
|
-
allChunks.push(...subDecoded.chunks);
|
|
687
|
-
}
|
|
688
|
-
return allChunks;
|
|
407
|
+
async _verifyManifestHash(decoded, treeOid) {
|
|
408
|
+
await this.#manifestRepository.verifyManifestHash(decoded, treeOid);
|
|
689
409
|
}
|
|
690
410
|
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
* @private
|
|
694
|
-
*/
|
|
695
|
-
async _readSubManifestBlob(oid, treeOid) {
|
|
696
|
-
try {
|
|
697
|
-
return await this.persistence.readBlob(oid);
|
|
698
|
-
} catch (err) {
|
|
699
|
-
if (err instanceof CasError) { throw err; }
|
|
700
|
-
throw new CasError(
|
|
701
|
-
`Failed to read sub-manifest blob ${oid}: ${err.message}`,
|
|
702
|
-
'GIT_ERROR',
|
|
703
|
-
{ treeOid, subManifestOid: oid, originalError: err },
|
|
704
|
-
);
|
|
705
|
-
}
|
|
411
|
+
static diffManifests(oldManifest, newManifest) {
|
|
412
|
+
return diffManifests(oldManifest, newManifest);
|
|
706
413
|
}
|
|
707
414
|
|
|
708
|
-
/**
|
|
709
|
-
* Reads a manifest from a Git tree and returns inspection metadata.
|
|
710
|
-
* Does not perform any destructive Git operations.
|
|
711
|
-
*
|
|
712
|
-
* @param {Object} options
|
|
713
|
-
* @param {string} options.treeOid - Git tree OID of the asset
|
|
714
|
-
* @returns {Promise<{ chunksOrphaned: number, slug: string }>}
|
|
715
|
-
* @throws {CasError} MANIFEST_NOT_FOUND if the tree has no manifest
|
|
716
|
-
*/
|
|
717
415
|
async inspectAsset({ treeOid }) {
|
|
718
416
|
const manifest = await this.readManifest({ treeOid });
|
|
719
|
-
return {
|
|
720
|
-
slug: manifest.slug,
|
|
721
|
-
chunksOrphaned: manifest.chunks.length,
|
|
722
|
-
};
|
|
417
|
+
return { slug: manifest.slug, chunksOrphaned: manifest.chunks.length };
|
|
723
418
|
}
|
|
724
419
|
|
|
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
420
|
async deleteAsset(options) {
|
|
732
421
|
this.observability.log('warn', 'deleteAsset() is deprecated — use inspectAsset()');
|
|
733
422
|
return await this.inspectAsset(options);
|
|
734
423
|
}
|
|
735
424
|
|
|
736
|
-
/**
|
|
737
|
-
* Aggregates referenced chunk blob OIDs across multiple stored assets.
|
|
738
|
-
* Analysis only — does not delete or modify anything.
|
|
739
|
-
*
|
|
740
|
-
* @param {Object} options
|
|
741
|
-
* @param {string[]} options.treeOids - Git tree OIDs to analyze
|
|
742
|
-
* @returns {Promise<{ referenced: Set<string>, total: number }>}
|
|
743
|
-
* @throws {CasError} MANIFEST_NOT_FOUND if any treeOid lacks a manifest
|
|
744
|
-
*/
|
|
745
425
|
async collectReferencedChunks({ treeOids }) {
|
|
746
426
|
const referenced = new Set();
|
|
747
427
|
let total = 0;
|
|
748
|
-
|
|
749
428
|
for (const treeOid of treeOids) {
|
|
750
429
|
const manifest = await this.readManifest({ treeOid });
|
|
751
430
|
for (const chunk of manifest.chunks) {
|
|
@@ -753,261 +432,46 @@ export default class CasService {
|
|
|
753
432
|
total += 1;
|
|
754
433
|
}
|
|
755
434
|
}
|
|
756
|
-
|
|
757
435
|
return { referenced, total };
|
|
758
436
|
}
|
|
759
437
|
|
|
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
438
|
async findOrphanedChunks(options) {
|
|
767
439
|
this.observability.log('warn', 'findOrphanedChunks() is deprecated — use collectReferencedChunks()');
|
|
768
440
|
return await this.collectReferencedChunks(options);
|
|
769
441
|
}
|
|
770
442
|
|
|
771
|
-
/**
|
|
772
|
-
* Derives an encryption key from a passphrase using PBKDF2 or scrypt.
|
|
773
|
-
* @param {Object} options
|
|
774
|
-
* @param {string} options.passphrase - The passphrase to derive a key from.
|
|
775
|
-
* @param {Buffer} [options.salt] - Salt (random if omitted).
|
|
776
|
-
* @param {'pbkdf2'|'scrypt'} [options.algorithm='pbkdf2'] - KDF algorithm.
|
|
777
|
-
* @param {number} [options.iterations] - PBKDF2 iterations.
|
|
778
|
-
* @param {number} [options.cost] - scrypt cost (N).
|
|
779
|
-
* @param {number} [options.blockSize] - scrypt block size (r).
|
|
780
|
-
* @param {number} [options.parallelization] - scrypt parallelization (p).
|
|
781
|
-
* @param {number} [options.keyLength=32] - Derived key length.
|
|
782
|
-
* @returns {Promise<{ key: Buffer, salt: Buffer, params: Object }>}
|
|
783
|
-
*/
|
|
784
443
|
async deriveKey(options) {
|
|
785
444
|
return await this.crypto.deriveKey(options);
|
|
786
445
|
}
|
|
787
446
|
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
*
|
|
791
|
-
* Unwraps the DEK using `existingKey`, wraps it with `newRecipientKey`,
|
|
792
|
-
* and returns a new Manifest with the appended recipient entry.
|
|
793
|
-
*
|
|
794
|
-
* @param {Object} options
|
|
795
|
-
* @param {import('../value-objects/Manifest.js').default} options.manifest
|
|
796
|
-
* @param {Buffer} options.existingKey - KEK of an existing recipient.
|
|
797
|
-
* @param {Buffer} options.newRecipientKey - KEK for the new recipient.
|
|
798
|
-
* @param {string} options.label - Label for the new recipient.
|
|
799
|
-
* @returns {Promise<import('../value-objects/Manifest.js').default>}
|
|
800
|
-
* @throws {CasError} INVALID_OPTIONS if manifest has no recipients.
|
|
801
|
-
* @throws {CasError} RECIPIENT_ALREADY_EXISTS if label is a duplicate.
|
|
802
|
-
* @throws {CasError} DEK_UNWRAP_FAILED if existingKey doesn't match any recipient.
|
|
803
|
-
*/
|
|
804
|
-
async addRecipient({ manifest, existingKey, newRecipientKey, label }) {
|
|
805
|
-
const recipients = manifest.encryption?.recipients;
|
|
806
|
-
if (!recipients || recipients.length === 0) {
|
|
807
|
-
throw new CasError(
|
|
808
|
-
'Manifest does not use envelope encryption (no recipients)',
|
|
809
|
-
'INVALID_OPTIONS',
|
|
810
|
-
);
|
|
811
|
-
}
|
|
812
|
-
|
|
813
|
-
if (recipients.some((r) => r.label === label)) {
|
|
814
|
-
throw new CasError(
|
|
815
|
-
`Recipient "${label}" already exists`,
|
|
816
|
-
'RECIPIENT_ALREADY_EXISTS',
|
|
817
|
-
{ label },
|
|
818
|
-
);
|
|
819
|
-
}
|
|
820
|
-
|
|
821
|
-
this.crypto._validateKey(existingKey);
|
|
822
|
-
this.crypto._validateKey(newRecipientKey);
|
|
823
|
-
|
|
824
|
-
// Unwrap DEK using the existing key
|
|
825
|
-
let dek;
|
|
826
|
-
try {
|
|
827
|
-
dek = await this.#keyResolver.resolveKeyForRecipients(manifest, existingKey);
|
|
828
|
-
} catch (err) {
|
|
829
|
-
if (err instanceof CasError && err.code === 'NO_MATCHING_RECIPIENT') {
|
|
830
|
-
throw new CasError('Failed to unwrap DEK: authentication failed', 'DEK_UNWRAP_FAILED', { originalError: err });
|
|
831
|
-
}
|
|
832
|
-
throw err;
|
|
833
|
-
}
|
|
834
|
-
|
|
835
|
-
// Wrap DEK for the new recipient
|
|
836
|
-
const newEntry = { label, ...(await this.#keyResolver.wrapDek(dek, newRecipientKey)) };
|
|
837
|
-
|
|
838
|
-
const json = manifest.toJSON();
|
|
839
|
-
const updatedEncryption = {
|
|
840
|
-
...json.encryption,
|
|
841
|
-
recipients: [...recipients.map((r) => ({ ...r })), newEntry],
|
|
842
|
-
};
|
|
843
|
-
|
|
844
|
-
return new Manifest({ ...json, encryption: updatedEncryption });
|
|
447
|
+
async addRecipient(options) {
|
|
448
|
+
return await this.#recipientService.addRecipient(options);
|
|
845
449
|
}
|
|
846
450
|
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
*
|
|
850
|
-
* Returns a new Manifest with the recipient entry removed. Does not
|
|
851
|
-
* require a key — this is a manifest-only mutation.
|
|
852
|
-
*
|
|
853
|
-
* @param {Object} options
|
|
854
|
-
* @param {import('../value-objects/Manifest.js').default} options.manifest
|
|
855
|
-
* @param {string} options.label - Label of the recipient to remove.
|
|
856
|
-
* @returns {Promise<import('../value-objects/Manifest.js').default>}
|
|
857
|
-
* @throws {CasError} RECIPIENT_NOT_FOUND if label doesn't exist.
|
|
858
|
-
* @throws {CasError} CANNOT_REMOVE_LAST_RECIPIENT if only one recipient remains.
|
|
859
|
-
*/
|
|
860
|
-
async removeRecipient({ manifest, label }) {
|
|
861
|
-
const recipients = manifest.encryption?.recipients;
|
|
862
|
-
if (!recipients || recipients.length === 0) {
|
|
863
|
-
throw new CasError(
|
|
864
|
-
'Manifest does not use envelope encryption (no recipients)',
|
|
865
|
-
'INVALID_OPTIONS',
|
|
866
|
-
);
|
|
867
|
-
}
|
|
868
|
-
if (!recipients.some((r) => r.label === label)) {
|
|
869
|
-
throw new CasError(
|
|
870
|
-
`Recipient "${label}" not found`,
|
|
871
|
-
'RECIPIENT_NOT_FOUND',
|
|
872
|
-
{ label },
|
|
873
|
-
);
|
|
874
|
-
}
|
|
875
|
-
|
|
876
|
-
if (recipients.length === 1) {
|
|
877
|
-
throw new CasError(
|
|
878
|
-
'Cannot remove the last recipient',
|
|
879
|
-
'CANNOT_REMOVE_LAST_RECIPIENT',
|
|
880
|
-
);
|
|
881
|
-
}
|
|
882
|
-
|
|
883
|
-
const filtered = recipients.filter((r) => r.label !== label).map((r) => ({ ...r }));
|
|
884
|
-
if (filtered.length === 0) {
|
|
885
|
-
throw new CasError(
|
|
886
|
-
'Cannot remove the last recipient',
|
|
887
|
-
'CANNOT_REMOVE_LAST_RECIPIENT',
|
|
888
|
-
);
|
|
889
|
-
}
|
|
890
|
-
const json = manifest.toJSON();
|
|
891
|
-
const updatedEncryption = { ...json.encryption, recipients: filtered };
|
|
892
|
-
|
|
893
|
-
return new Manifest({ ...json, encryption: updatedEncryption });
|
|
451
|
+
async removeRecipient(options) {
|
|
452
|
+
return await this.#recipientService.removeRecipient(options);
|
|
894
453
|
}
|
|
895
454
|
|
|
896
|
-
/**
|
|
897
|
-
* Lists recipient labels from an envelope-encrypted manifest.
|
|
898
|
-
*
|
|
899
|
-
* @param {import('../value-objects/Manifest.js').default} manifest
|
|
900
|
-
* @returns {string[]} Recipient labels, or empty array if not envelope-encrypted.
|
|
901
|
-
*/
|
|
902
455
|
listRecipients(manifest) {
|
|
903
|
-
return (manifest
|
|
904
|
-
}
|
|
905
|
-
|
|
906
|
-
/**
|
|
907
|
-
* Rotates a recipient's key without re-encrypting data blobs.
|
|
908
|
-
*
|
|
909
|
-
* Re-wraps the DEK with `newKey` for the matched recipient entry.
|
|
910
|
-
* Increments `keyVersion` at both manifest-level and recipient-level.
|
|
911
|
-
*
|
|
912
|
-
* @param {Object} options
|
|
913
|
-
* @param {import('../value-objects/Manifest.js').default} options.manifest
|
|
914
|
-
* @param {Buffer} options.oldKey - Current KEK of the recipient to rotate.
|
|
915
|
-
* @param {Buffer} options.newKey - New KEK to wrap the DEK with.
|
|
916
|
-
* @param {string} [options.label] - If provided, only rotate the named recipient.
|
|
917
|
-
* @returns {Promise<import('../value-objects/Manifest.js').default>}
|
|
918
|
-
* @throws {CasError} ROTATION_NOT_SUPPORTED if manifest has no recipients.
|
|
919
|
-
* @throws {CasError} RECIPIENT_NOT_FOUND if label doesn't exist.
|
|
920
|
-
* @throws {CasError} DEK_UNWRAP_FAILED if oldKey doesn't match the recipient.
|
|
921
|
-
* @throws {CasError} NO_MATCHING_RECIPIENT if no label and oldKey matches no entry.
|
|
922
|
-
*/
|
|
923
|
-
async rotateKey({ manifest, oldKey, newKey, label }) {
|
|
924
|
-
const recipients = manifest.encryption?.recipients;
|
|
925
|
-
if (!recipients || recipients.length === 0) {
|
|
926
|
-
throw new CasError(
|
|
927
|
-
'Key rotation requires envelope encryption (recipients)',
|
|
928
|
-
'ROTATION_NOT_SUPPORTED',
|
|
929
|
-
);
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
this.crypto._validateKey(oldKey);
|
|
933
|
-
this.crypto._validateKey(newKey);
|
|
934
|
-
|
|
935
|
-
const { matchIndex, dek } = label
|
|
936
|
-
? await this.#findRecipientByLabel(recipients, label, oldKey)
|
|
937
|
-
: await this.#findRecipientByKey(recipients, oldKey);
|
|
938
|
-
|
|
939
|
-
return this.#buildRotatedManifest({ manifest, recipients, matchIndex, dek, newKey });
|
|
456
|
+
return this.#recipientService.listRecipients(manifest);
|
|
940
457
|
}
|
|
941
458
|
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
*/
|
|
945
|
-
async #findRecipientByLabel(recipients, label, oldKey) {
|
|
946
|
-
const matchIndex = recipients.findIndex((r) => r.label === label);
|
|
947
|
-
if (matchIndex === -1) {
|
|
948
|
-
throw new CasError(`Recipient "${label}" not found`, 'RECIPIENT_NOT_FOUND', { label });
|
|
949
|
-
}
|
|
950
|
-
const dek = await this.#keyResolver.unwrapDek(recipients[matchIndex], oldKey);
|
|
951
|
-
return { matchIndex, dek };
|
|
459
|
+
async rotateKey(options) {
|
|
460
|
+
return await this.#recipientService.rotateKey(options);
|
|
952
461
|
}
|
|
953
462
|
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
*/
|
|
957
|
-
async #findRecipientByKey(recipients, oldKey) {
|
|
958
|
-
for (let i = 0; i < recipients.length; i++) {
|
|
959
|
-
try {
|
|
960
|
-
const dek = await this.#keyResolver.unwrapDek(recipients[i], oldKey);
|
|
961
|
-
return { matchIndex: i, dek };
|
|
962
|
-
} catch (err) {
|
|
963
|
-
if (!(err instanceof CasError && err.code === 'DEK_UNWRAP_FAILED')) { throw err; }
|
|
964
|
-
}
|
|
965
|
-
}
|
|
966
|
-
throw new CasError(
|
|
967
|
-
'No recipient entry could be unwrapped with the provided key',
|
|
968
|
-
'NO_MATCHING_RECIPIENT',
|
|
969
|
-
);
|
|
463
|
+
async verifyIntegrity(manifest, options = {}) {
|
|
464
|
+
return await this.#integrityVerifier.verify(manifest, options);
|
|
970
465
|
}
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
const json = manifest.toJSON();
|
|
981
|
-
const updatedRecipients = recipients.map((r, i) => {
|
|
982
|
-
if (i === matchIndex) {
|
|
983
|
-
return { ...r, ...newWrapped, keyVersion: recipientKeyVersion };
|
|
984
|
-
}
|
|
985
|
-
return { ...r };
|
|
986
|
-
});
|
|
987
|
-
|
|
988
|
-
return new Manifest({
|
|
989
|
-
...json,
|
|
990
|
-
encryption: { ...json.encryption, recipients: updatedRecipients, keyVersion: manifestKeyVersion },
|
|
466
|
+
#initIntegrity({ safeObservability }) {
|
|
467
|
+
this.#integrityVerifier = new IntegrityVerifier({
|
|
468
|
+
chunks: this.#chunkRepository,
|
|
469
|
+
crypto: this.crypto,
|
|
470
|
+
framed: this.#framed,
|
|
471
|
+
isLegacyNoAad: (manifest) => this._isLegacyNoAad(manifest),
|
|
472
|
+
keyResolver: this.#keyResolver,
|
|
473
|
+
observability: safeObservability,
|
|
474
|
+
validateEncryptionMeta: (manifest) => this._validatedEncryptionMeta(manifest),
|
|
991
475
|
});
|
|
992
476
|
}
|
|
993
|
-
|
|
994
|
-
/**
|
|
995
|
-
* Verifies the integrity of a stored file by re-hashing its chunks.
|
|
996
|
-
* @param {import('../value-objects/Manifest.js').default} manifest
|
|
997
|
-
* @returns {Promise<boolean>}
|
|
998
|
-
*/
|
|
999
|
-
async verifyIntegrity(manifest) {
|
|
1000
|
-
for (const chunk of manifest.chunks) {
|
|
1001
|
-
const blob = await this.persistence.readBlob(chunk.blob);
|
|
1002
|
-
const digest = await this._sha256(blob);
|
|
1003
|
-
if (digest !== chunk.digest) {
|
|
1004
|
-
this.observability.metric('integrity', {
|
|
1005
|
-
action: 'fail', slug: manifest.slug, chunkIndex: chunk.index, expected: chunk.digest, actual: digest,
|
|
1006
|
-
});
|
|
1007
|
-
return false;
|
|
1008
|
-
}
|
|
1009
|
-
}
|
|
1010
|
-
this.observability.metric('integrity', { action: 'pass', slug: manifest.slug });
|
|
1011
|
-
return true;
|
|
1012
|
-
}
|
|
1013
477
|
}
|