@git-stunts/git-cas 5.3.2 → 6.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ADVANCED_GUIDE.md +1027 -0
- package/ARCHITECTURE.md +514 -0
- package/CHANGELOG.md +449 -5
- package/CODE_OF_CONDUCT.md +33 -0
- package/GUIDE.md +926 -0
- package/README.md +106 -366
- 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 +1255 -212
- 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 +367 -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 +2254 -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 +273 -80
- package/index.js +220 -59
- 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 +153 -53
- package/src/domain/services/CasService.js +322 -837
- package/src/domain/services/ChunkRepository.js +268 -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 +180 -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 +10 -6
- 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
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import Manifest from '../value-objects/Manifest.js';
|
|
2
|
+
import Oid from '../value-objects/Oid.js';
|
|
3
|
+
import { ChunkSchema } from '../schemas/ManifestSchema.js';
|
|
4
|
+
import CasError from '../errors/CasError.js';
|
|
5
|
+
import createCasError from '../errors/createCasError.js';
|
|
6
|
+
import { normalizeCodecBytes, encodeForHash } from '../helpers/codecBytes.js';
|
|
7
|
+
import {
|
|
8
|
+
buildFlatManifestTreeEntries,
|
|
9
|
+
buildMerkleTreeEntries,
|
|
10
|
+
} from './GitTreeBuilder.js';
|
|
11
|
+
import {
|
|
12
|
+
assertCurrentScheme,
|
|
13
|
+
isLegacyNoAad,
|
|
14
|
+
mapToCurrentScheme,
|
|
15
|
+
SCHEME_WHOLE,
|
|
16
|
+
} from '../encryption/schemes.js';
|
|
17
|
+
import { ErrorCodes } from '../errors/index.js';
|
|
18
|
+
|
|
19
|
+
const originalSchemeMap = new WeakMap();
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Manifest serialization, tree publication, and readback boundary.
|
|
23
|
+
*/
|
|
24
|
+
export default class ManifestRepository {
|
|
25
|
+
#codec;
|
|
26
|
+
#crypto;
|
|
27
|
+
#legacyMode;
|
|
28
|
+
#merkleThreshold;
|
|
29
|
+
#persistence;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param {Object} options
|
|
33
|
+
* @param {import('../../ports/CodecPort.js').default} options.codec
|
|
34
|
+
* @param {import('../../ports/CryptoPort.js').default} options.crypto
|
|
35
|
+
* @param {boolean} options.legacyMode
|
|
36
|
+
* @param {number} options.merkleThreshold
|
|
37
|
+
* @param {import('../../ports/GitPersistencePort.js').default} options.persistence
|
|
38
|
+
*/
|
|
39
|
+
constructor({ codec, crypto, legacyMode, merkleThreshold, persistence }) {
|
|
40
|
+
this.#codec = codec;
|
|
41
|
+
this.#crypto = crypto;
|
|
42
|
+
this.#legacyMode = legacyMode;
|
|
43
|
+
this.#merkleThreshold = merkleThreshold;
|
|
44
|
+
this.#persistence = persistence;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {{ manifest: Manifest, merkleThreshold?: number }} options
|
|
49
|
+
* @returns {Promise<string>}
|
|
50
|
+
*/
|
|
51
|
+
async createTree({ manifest, merkleThreshold }) {
|
|
52
|
+
const chunks = manifest.chunks;
|
|
53
|
+
const effectiveThreshold = merkleThreshold ?? this.#merkleThreshold;
|
|
54
|
+
if (chunks.length > effectiveThreshold) {
|
|
55
|
+
return await this.#createMerkleTree({ manifest, merkleThreshold: effectiveThreshold });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const manifestData = manifest.toJSON();
|
|
59
|
+
const hashableBytes = encodeForHash(manifestData, this.#codec);
|
|
60
|
+
manifestData.manifestHash = await this.#crypto.sha256(hashableBytes);
|
|
61
|
+
const serializedManifest = normalizeCodecBytes(this.#codec.encode(manifestData));
|
|
62
|
+
const manifestOid = await this.#persistence.writeBlob(serializedManifest);
|
|
63
|
+
|
|
64
|
+
const treeEntries = buildFlatManifestTreeEntries({
|
|
65
|
+
manifestOid,
|
|
66
|
+
chunks,
|
|
67
|
+
extension: this.#codec.extension,
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
return await this.#persistence.writeTree(treeEntries);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* @param {{ treeOid: string }} options
|
|
75
|
+
* @returns {Promise<Manifest>}
|
|
76
|
+
*/
|
|
77
|
+
async readManifest({ treeOid }) {
|
|
78
|
+
const blob = await this.#readManifestBlob(treeOid);
|
|
79
|
+
const decoded = this.#codec.decode(blob);
|
|
80
|
+
|
|
81
|
+
await this.#verifyManifestHash(decoded, treeOid);
|
|
82
|
+
const originalScheme = this.#resolveEncryptionScheme(decoded);
|
|
83
|
+
|
|
84
|
+
if (decoded.version === 2 && decoded.subManifests?.length > 0) {
|
|
85
|
+
decoded.chunks = await this.#resolveSubManifests(decoded.subManifests, treeOid);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const manifest = new Manifest(decoded);
|
|
89
|
+
if (this.#legacyMode && decoded.encryption) {
|
|
90
|
+
originalSchemeMap.set(manifest, originalScheme);
|
|
91
|
+
}
|
|
92
|
+
return manifest;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* @param {{ treeOid: string }} options
|
|
97
|
+
* @returns {Promise<object>}
|
|
98
|
+
*/
|
|
99
|
+
async readManifestRaw({ treeOid }) {
|
|
100
|
+
const blob = await this.#readManifestBlob(treeOid);
|
|
101
|
+
return this.#codec.decode(blob);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* @param {object} decoded
|
|
106
|
+
* @param {string} treeOid
|
|
107
|
+
*/
|
|
108
|
+
async verifyManifestHash(decoded, treeOid) {
|
|
109
|
+
await this.#verifyManifestHash(decoded, treeOid);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* @param {Manifest} manifest
|
|
114
|
+
* @returns {boolean}
|
|
115
|
+
*/
|
|
116
|
+
isLegacyNoAad(manifest) {
|
|
117
|
+
if (!this.#legacyMode || !originalSchemeMap.has(manifest)) {
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
const original = originalSchemeMap.get(manifest);
|
|
121
|
+
return original === undefined || isLegacyNoAad(original);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async #createMerkleTree({ manifest, merkleThreshold }) {
|
|
125
|
+
const chunks = [...manifest.chunks];
|
|
126
|
+
const subManifestRefs = [];
|
|
127
|
+
|
|
128
|
+
for (let i = 0; i < chunks.length; i += merkleThreshold) {
|
|
129
|
+
const group = chunks.slice(i, i + merkleThreshold);
|
|
130
|
+
const subManifestData = { chunks: group.map((c) => ({ index: c.index, size: c.size, digest: c.digest, blob: c.blob })) };
|
|
131
|
+
const serialized = normalizeCodecBytes(this.#codec.encode(subManifestData));
|
|
132
|
+
const oid = await this.#persistence.writeBlob(serialized);
|
|
133
|
+
|
|
134
|
+
subManifestRefs.push({
|
|
135
|
+
oid,
|
|
136
|
+
chunkCount: group.length,
|
|
137
|
+
startIndex: i,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const rootManifestData = {
|
|
142
|
+
...manifest.toJSON(),
|
|
143
|
+
version: 2,
|
|
144
|
+
chunks: [],
|
|
145
|
+
subManifests: subManifestRefs,
|
|
146
|
+
};
|
|
147
|
+
const rootHashableBytes = encodeForHash(rootManifestData, this.#codec);
|
|
148
|
+
rootManifestData.manifestHash = await this.#crypto.sha256(rootHashableBytes);
|
|
149
|
+
|
|
150
|
+
const serializedRoot = normalizeCodecBytes(this.#codec.encode(rootManifestData));
|
|
151
|
+
const rootManifestOid = await this.#persistence.writeBlob(serializedRoot);
|
|
152
|
+
|
|
153
|
+
const treeEntries = buildMerkleTreeEntries({
|
|
154
|
+
rootManifestOid,
|
|
155
|
+
subManifests: subManifestRefs,
|
|
156
|
+
chunks,
|
|
157
|
+
extension: this.#codec.extension,
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
return await this.#persistence.writeTree(treeEntries);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async #readManifestBlob(treeOid) {
|
|
164
|
+
const normalizedTreeOid = Oid.from(treeOid).toString();
|
|
165
|
+
let entries;
|
|
166
|
+
try {
|
|
167
|
+
entries = await this.#persistence.readTree(normalizedTreeOid);
|
|
168
|
+
} catch (err) {
|
|
169
|
+
if (err instanceof CasError) {
|
|
170
|
+
throw err;
|
|
171
|
+
}
|
|
172
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
173
|
+
throw createCasError(
|
|
174
|
+
`Failed to read tree ${normalizedTreeOid}: ${message}`,
|
|
175
|
+
ErrorCodes.GIT_ERROR,
|
|
176
|
+
{ treeOid: normalizedTreeOid, originalError: err },
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const manifestName = `manifest.${this.#codec.extension}`;
|
|
181
|
+
const manifestEntry = entries.find((entry) => entry.name === manifestName);
|
|
182
|
+
if (!manifestEntry) {
|
|
183
|
+
throw createCasError(
|
|
184
|
+
`No manifest entry (${manifestName}) found in tree ${normalizedTreeOid}`,
|
|
185
|
+
ErrorCodes.MANIFEST_NOT_FOUND,
|
|
186
|
+
{ treeOid: normalizedTreeOid, expectedName: manifestName },
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
const manifestOid = Oid.from(manifestEntry.oid).toString();
|
|
190
|
+
|
|
191
|
+
try {
|
|
192
|
+
return await this.#persistence.readBlob(manifestOid);
|
|
193
|
+
} catch (err) {
|
|
194
|
+
if (err instanceof CasError) {
|
|
195
|
+
throw err;
|
|
196
|
+
}
|
|
197
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
198
|
+
throw createCasError(
|
|
199
|
+
`Failed to read manifest blob ${manifestOid}: ${message}`,
|
|
200
|
+
ErrorCodes.GIT_ERROR,
|
|
201
|
+
{ treeOid: normalizedTreeOid, manifestOid, originalError: err },
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async #verifyManifestHash(decoded, treeOid) {
|
|
207
|
+
const normalizedTreeOid = Oid.from(treeOid).toString();
|
|
208
|
+
if (!decoded.manifestHash) {
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const hashableBytes = encodeForHash(decoded, this.#codec);
|
|
212
|
+
const computed = await this.#crypto.sha256(hashableBytes);
|
|
213
|
+
if (computed !== decoded.manifestHash) {
|
|
214
|
+
throw createCasError(
|
|
215
|
+
'Manifest integrity check failed: hash mismatch',
|
|
216
|
+
ErrorCodes.MANIFEST_INTEGRITY_ERROR,
|
|
217
|
+
{ treeOid: normalizedTreeOid, slug: decoded.slug, expected: decoded.manifestHash, actual: computed },
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
#resolveEncryptionScheme(decoded) {
|
|
223
|
+
if (this.#legacyMode && decoded.encryption && !decoded.encryption.scheme) {
|
|
224
|
+
decoded.encryption.scheme = SCHEME_WHOLE;
|
|
225
|
+
return undefined;
|
|
226
|
+
}
|
|
227
|
+
if (!decoded.encryption?.scheme) {
|
|
228
|
+
return undefined;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const originalScheme = decoded.encryption.scheme;
|
|
232
|
+
if (this.#legacyMode) {
|
|
233
|
+
const mapped = mapToCurrentScheme(originalScheme);
|
|
234
|
+
if (mapped) {
|
|
235
|
+
decoded.encryption.scheme = mapped;
|
|
236
|
+
}
|
|
237
|
+
} else {
|
|
238
|
+
assertCurrentScheme(decoded.encryption.scheme);
|
|
239
|
+
}
|
|
240
|
+
return originalScheme;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async #resolveSubManifests(subManifests, treeOid) {
|
|
244
|
+
const allChunks = [];
|
|
245
|
+
for (const ref of subManifests) {
|
|
246
|
+
const subBlob = await this.#readSubManifestBlob(ref.oid, treeOid);
|
|
247
|
+
const subDecoded = this.#codec.decode(subBlob);
|
|
248
|
+
if (subDecoded.chunks.length !== ref.chunkCount) {
|
|
249
|
+
throw createCasError(
|
|
250
|
+
`Sub-manifest ${ref.oid} declares chunkCount ${ref.chunkCount} but contains ${subDecoded.chunks.length} chunks`,
|
|
251
|
+
ErrorCodes.MANIFEST_INTEGRITY_ERROR,
|
|
252
|
+
{ subManifestOid: ref.oid, declaredCount: ref.chunkCount, actualCount: subDecoded.chunks.length, treeOid },
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
try {
|
|
256
|
+
allChunks.push(...subDecoded.chunks.map((chunk) => ChunkSchema.parse(chunk)));
|
|
257
|
+
} catch (err) {
|
|
258
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
259
|
+
throw createCasError(
|
|
260
|
+
`Sub-manifest ${ref.oid} contains invalid chunk data: ${message}`,
|
|
261
|
+
ErrorCodes.MANIFEST_INTEGRITY_ERROR,
|
|
262
|
+
{ subManifestOid: ref.oid, treeOid, originalError: err },
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return allChunks;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async #readSubManifestBlob(oid, treeOid) {
|
|
270
|
+
const subManifestOid = Oid.from(oid).toString();
|
|
271
|
+
const normalizedTreeOid = Oid.from(treeOid).toString();
|
|
272
|
+
try {
|
|
273
|
+
return await this.#persistence.readBlob(subManifestOid);
|
|
274
|
+
} catch (err) {
|
|
275
|
+
if (err instanceof CasError) {
|
|
276
|
+
throw err;
|
|
277
|
+
}
|
|
278
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
279
|
+
throw createCasError(
|
|
280
|
+
`Failed to read sub-manifest blob ${subManifestOid}: ${message}`,
|
|
281
|
+
ErrorCodes.GIT_ERROR,
|
|
282
|
+
{ treeOid: normalizedTreeOid, subManifestOid, originalError: err },
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Sliding prefetch window for ordered parallel chunk reads.
|
|
3
|
+
*
|
|
4
|
+
* Reads up to `concurrency` chunks ahead of the yield cursor, maintaining
|
|
5
|
+
* strict output ordering while maximizing I/O throughput.
|
|
6
|
+
*
|
|
7
|
+
* No classes, no state, no dependencies — just an async generator.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Fetches chunks in parallel with a sliding window, yielding in order.
|
|
12
|
+
*
|
|
13
|
+
* @param {Array<{ index: number }>} chunks - Chunk metadata array (ordered).
|
|
14
|
+
* @param {(chunk: { index: number }) => Promise<Uint8Array>} fetchFn - Async function to fetch a single chunk.
|
|
15
|
+
* @param {number} concurrency - Maximum number of concurrent in-flight fetches.
|
|
16
|
+
* @yields {Uint8Array} Chunk data in manifest order.
|
|
17
|
+
*/
|
|
18
|
+
export default async function* prefetchChunks(chunks, fetchFn, concurrency) {
|
|
19
|
+
if (chunks.length === 0) { return; }
|
|
20
|
+
|
|
21
|
+
const window = new Array(concurrency);
|
|
22
|
+
let yieldCursor = 0;
|
|
23
|
+
let fetchCursor = 0;
|
|
24
|
+
|
|
25
|
+
// Fill the initial window
|
|
26
|
+
while (fetchCursor < chunks.length && fetchCursor < concurrency) {
|
|
27
|
+
window[fetchCursor % concurrency] = fetchFn(chunks[fetchCursor]);
|
|
28
|
+
fetchCursor++;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Yield in order, sliding the window forward
|
|
32
|
+
try {
|
|
33
|
+
while (yieldCursor < chunks.length) {
|
|
34
|
+
const slot = yieldCursor % concurrency;
|
|
35
|
+
yield await window[slot];
|
|
36
|
+
|
|
37
|
+
yieldCursor++;
|
|
38
|
+
|
|
39
|
+
// Start the next fetch if there are more chunks
|
|
40
|
+
if (fetchCursor < chunks.length) {
|
|
41
|
+
window[slot] = fetchFn(chunks[fetchCursor]);
|
|
42
|
+
fetchCursor++;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
} finally {
|
|
46
|
+
await Promise.allSettled(window.filter(Boolean));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import Manifest from '../value-objects/Manifest.js';
|
|
2
|
+
import CasError from '../errors/CasError.js';
|
|
3
|
+
import createCasError from '../errors/createCasError.js';
|
|
4
|
+
import { ErrorCodes } from '../errors/index.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Envelope recipient mutation boundary.
|
|
8
|
+
*/
|
|
9
|
+
export default class RecipientService {
|
|
10
|
+
#crypto;
|
|
11
|
+
#keyResolver;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {Object} options
|
|
15
|
+
* @param {import('../../ports/CryptoPort.js').default} options.crypto
|
|
16
|
+
* @param {import('./KeyResolver.js').default} options.keyResolver
|
|
17
|
+
*/
|
|
18
|
+
constructor({ crypto, keyResolver }) {
|
|
19
|
+
this.#crypto = crypto;
|
|
20
|
+
this.#keyResolver = keyResolver;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param {{ manifest: Manifest, existingKey: Uint8Array, newRecipientKey: Uint8Array, label: string }} options
|
|
25
|
+
* @returns {Promise<Manifest>}
|
|
26
|
+
*/
|
|
27
|
+
async addRecipient({ manifest, existingKey, newRecipientKey, label }) {
|
|
28
|
+
const recipients = this.#requireRecipients(manifest);
|
|
29
|
+
if (recipients.some((recipient) => recipient.label === label)) {
|
|
30
|
+
throw createCasError(`Recipient "${label}" already exists`, ErrorCodes.RECIPIENT_ALREADY_EXISTS, { label });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
this.#crypto._validateKey(existingKey);
|
|
34
|
+
this.#crypto._validateKey(newRecipientKey);
|
|
35
|
+
|
|
36
|
+
let dek;
|
|
37
|
+
try {
|
|
38
|
+
dek = await this.#keyResolver.resolveKeyForRecipients(manifest, existingKey);
|
|
39
|
+
} catch (err) {
|
|
40
|
+
if (err instanceof CasError && err.code === ErrorCodes.NO_MATCHING_RECIPIENT) {
|
|
41
|
+
throw createCasError('Failed to unwrap DEK: authentication failed', ErrorCodes.DEK_UNWRAP_FAILED, { originalError: err });
|
|
42
|
+
}
|
|
43
|
+
throw err;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const newEntry = { label, ...(await this.#keyResolver.wrapDek(dek, newRecipientKey)) };
|
|
47
|
+
const json = manifest.toJSON();
|
|
48
|
+
const updatedEncryption = {
|
|
49
|
+
...json.encryption,
|
|
50
|
+
recipients: [...recipients.map((recipient) => ({ ...recipient })), newEntry],
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
return new Manifest({ ...json, encryption: updatedEncryption });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @param {{ manifest: Manifest, label: string }} options
|
|
58
|
+
* @returns {Promise<Manifest>}
|
|
59
|
+
*/
|
|
60
|
+
async removeRecipient({ manifest, label }) {
|
|
61
|
+
const recipients = this.#requireRecipients(manifest);
|
|
62
|
+
if (!recipients.some((recipient) => recipient.label === label)) {
|
|
63
|
+
throw createCasError(`Recipient "${label}" not found`, ErrorCodes.RECIPIENT_NOT_FOUND, { label });
|
|
64
|
+
}
|
|
65
|
+
if (recipients.length === 1) {
|
|
66
|
+
throw createCasError('Cannot remove the last recipient', ErrorCodes.CANNOT_REMOVE_LAST_RECIPIENT);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const filtered = recipients.filter((recipient) => recipient.label !== label).map((recipient) => ({ ...recipient }));
|
|
70
|
+
if (filtered.length === 0) {
|
|
71
|
+
throw createCasError('Cannot remove the last recipient', ErrorCodes.CANNOT_REMOVE_LAST_RECIPIENT);
|
|
72
|
+
}
|
|
73
|
+
const json = manifest.toJSON();
|
|
74
|
+
return new Manifest({ ...json, encryption: { ...json.encryption, recipients: filtered } });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* @param {Manifest} manifest
|
|
79
|
+
* @returns {string[]}
|
|
80
|
+
*/
|
|
81
|
+
listRecipients(manifest) {
|
|
82
|
+
return (manifest.encryption?.recipients || []).map((recipient) => recipient.label);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @param {{ manifest: Manifest, oldKey: Uint8Array, newKey: Uint8Array, label?: string }} options
|
|
87
|
+
* @returns {Promise<Manifest>}
|
|
88
|
+
*/
|
|
89
|
+
async rotateKey({ manifest, oldKey, newKey, label }) {
|
|
90
|
+
const recipients = manifest.encryption?.recipients;
|
|
91
|
+
if (!recipients || recipients.length === 0) {
|
|
92
|
+
throw createCasError('Key rotation requires envelope encryption (recipients)', ErrorCodes.ROTATION_NOT_SUPPORTED);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
this.#crypto._validateKey(oldKey);
|
|
96
|
+
this.#crypto._validateKey(newKey);
|
|
97
|
+
|
|
98
|
+
const { matchIndex, dek } = label
|
|
99
|
+
? await this.#findRecipientByLabel(recipients, label, oldKey)
|
|
100
|
+
: await this.#findRecipientByKey(recipients, oldKey);
|
|
101
|
+
|
|
102
|
+
return this.#buildRotatedManifest({ manifest, recipients, matchIndex, dek, newKey });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
#requireRecipients(manifest) {
|
|
106
|
+
const recipients = manifest.encryption?.recipients;
|
|
107
|
+
if (!recipients || recipients.length === 0) {
|
|
108
|
+
throw createCasError('Manifest does not use envelope encryption (no recipients)', ErrorCodes.INVALID_OPTIONS);
|
|
109
|
+
}
|
|
110
|
+
return recipients;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async #findRecipientByLabel(recipients, label, oldKey) {
|
|
114
|
+
const matchIndex = recipients.findIndex((recipient) => recipient.label === label);
|
|
115
|
+
if (matchIndex === -1) {
|
|
116
|
+
throw createCasError(`Recipient "${label}" not found`, ErrorCodes.RECIPIENT_NOT_FOUND, { label });
|
|
117
|
+
}
|
|
118
|
+
const dek = await this.#keyResolver.unwrapDek(recipients[matchIndex], oldKey);
|
|
119
|
+
return { matchIndex, dek };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async #findRecipientByKey(recipients, oldKey) {
|
|
123
|
+
let match = null;
|
|
124
|
+
for (let index = 0; index < recipients.length; index++) {
|
|
125
|
+
try {
|
|
126
|
+
const dek = await this.#keyResolver.unwrapDek(recipients[index], oldKey);
|
|
127
|
+
match ??= { matchIndex: index, dek };
|
|
128
|
+
} catch (err) {
|
|
129
|
+
if (!(err instanceof CasError && err.code === ErrorCodes.DEK_UNWRAP_FAILED)) {
|
|
130
|
+
throw err;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (match) {
|
|
135
|
+
return match;
|
|
136
|
+
}
|
|
137
|
+
throw createCasError('No recipient entry could be unwrapped with the provided key', ErrorCodes.NO_MATCHING_RECIPIENT);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async #buildRotatedManifest({ manifest, recipients, matchIndex, dek, newKey }) {
|
|
141
|
+
const newWrapped = await this.#keyResolver.wrapDek(dek, newKey);
|
|
142
|
+
const manifestKeyVersion = (manifest.encryption.keyVersion || 0) + 1;
|
|
143
|
+
const recipientKeyVersion = (recipients[matchIndex].keyVersion || 0) + 1;
|
|
144
|
+
const json = manifest.toJSON();
|
|
145
|
+
const updatedRecipients = recipients.map((recipient, index) => {
|
|
146
|
+
if (index === matchIndex) {
|
|
147
|
+
return { ...recipient, ...newWrapped, keyVersion: recipientKeyVersion };
|
|
148
|
+
}
|
|
149
|
+
return { ...recipient };
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
return new Manifest({
|
|
153
|
+
...json,
|
|
154
|
+
encryption: { ...json.encryption, recipients: updatedRecipients, keyVersion: manifestKeyVersion },
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
const REDACTED = '[REDACTED]';
|
|
2
|
+
const SENSITIVE_FIELD_NAMES = new Set([
|
|
3
|
+
'ciphertext',
|
|
4
|
+
'dek',
|
|
5
|
+
'encryptionkey',
|
|
6
|
+
'key',
|
|
7
|
+
'kek',
|
|
8
|
+
'newpassphrase',
|
|
9
|
+
'nonce',
|
|
10
|
+
'oldpassphrase',
|
|
11
|
+
'passphrase',
|
|
12
|
+
'password',
|
|
13
|
+
'privatekey',
|
|
14
|
+
'salt',
|
|
15
|
+
'secret',
|
|
16
|
+
'tag',
|
|
17
|
+
'token',
|
|
18
|
+
'vaultencryptionkey',
|
|
19
|
+
'wrappeddek',
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Observability decorator that strips sensitive metadata before it leaves the
|
|
24
|
+
* domain service boundary.
|
|
25
|
+
*/
|
|
26
|
+
export default class RedactingObservability {
|
|
27
|
+
#inner;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @param {import('../../ports/ObservabilityPort.js').default} inner
|
|
31
|
+
*/
|
|
32
|
+
constructor(inner) {
|
|
33
|
+
this.#inner = inner;
|
|
34
|
+
Object.freeze(this);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param {import('../../ports/ObservabilityPort.js').default} inner
|
|
39
|
+
* @returns {RedactingObservability}
|
|
40
|
+
*/
|
|
41
|
+
static wrap(inner) {
|
|
42
|
+
return inner instanceof RedactingObservability ? inner : new RedactingObservability(inner);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @param {string} channel
|
|
47
|
+
* @param {Record<string, unknown>} data
|
|
48
|
+
*/
|
|
49
|
+
metric(channel, data) {
|
|
50
|
+
this.#inner.metric(channel, RedactingObservability.redact(data));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @param {'debug'|'info'|'warn'|'error'} level
|
|
55
|
+
* @param {string} msg
|
|
56
|
+
* @param {Record<string, unknown>} [meta]
|
|
57
|
+
*/
|
|
58
|
+
log(level, msg, meta) {
|
|
59
|
+
if (meta === undefined) {
|
|
60
|
+
this.#inner.log(level, msg);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
this.#inner.log(level, msg, RedactingObservability.redact(meta));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* @param {string} name
|
|
68
|
+
* @returns {{ end(meta?: Record<string, unknown>): void }}
|
|
69
|
+
*/
|
|
70
|
+
span(name) {
|
|
71
|
+
const span = this.#inner.span(name);
|
|
72
|
+
return {
|
|
73
|
+
end(meta) {
|
|
74
|
+
span.end(RedactingObservability.redact(meta));
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* @template T
|
|
81
|
+
* @param {T} value
|
|
82
|
+
* @returns {T}
|
|
83
|
+
*/
|
|
84
|
+
static redact(value) {
|
|
85
|
+
return /** @type {T} */ (RedactingObservability.#redactValue(value, new WeakSet()));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* @param {unknown} value
|
|
90
|
+
* @param {WeakSet<object>} seen
|
|
91
|
+
* @returns {unknown}
|
|
92
|
+
*/
|
|
93
|
+
static #redactValue(value, seen) {
|
|
94
|
+
if (value instanceof Uint8Array) {
|
|
95
|
+
return REDACTED;
|
|
96
|
+
}
|
|
97
|
+
if (!value || typeof value !== 'object') {
|
|
98
|
+
return value;
|
|
99
|
+
}
|
|
100
|
+
if (seen.has(value)) {
|
|
101
|
+
return '[Circular]';
|
|
102
|
+
}
|
|
103
|
+
seen.add(value);
|
|
104
|
+
|
|
105
|
+
if (value instanceof Error) {
|
|
106
|
+
return RedactingObservability.#redactError(value, seen);
|
|
107
|
+
}
|
|
108
|
+
if (Array.isArray(value)) {
|
|
109
|
+
return value.map((entry) => RedactingObservability.#redactValue(entry, seen));
|
|
110
|
+
}
|
|
111
|
+
return RedactingObservability.#redactObject(value, seen);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* @param {Error & Record<string, unknown>} error
|
|
116
|
+
* @param {WeakSet<object>} seen
|
|
117
|
+
* @returns {Record<string, unknown>}
|
|
118
|
+
*/
|
|
119
|
+
static #redactError(error, seen) {
|
|
120
|
+
const sanitized = {
|
|
121
|
+
name: error.name,
|
|
122
|
+
message: error.message,
|
|
123
|
+
};
|
|
124
|
+
if ('code' in error) {
|
|
125
|
+
sanitized.code = error.code;
|
|
126
|
+
}
|
|
127
|
+
for (const key of Object.keys(error)) {
|
|
128
|
+
if (key === 'name' || key === 'message' || key === 'code') {
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
sanitized[key] = RedactingObservability.#redactField(key, error[key], seen);
|
|
132
|
+
}
|
|
133
|
+
return sanitized;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* @param {object} object
|
|
138
|
+
* @param {WeakSet<object>} seen
|
|
139
|
+
* @returns {Record<string, unknown>}
|
|
140
|
+
*/
|
|
141
|
+
static #redactObject(object, seen) {
|
|
142
|
+
const sanitized = {};
|
|
143
|
+
for (const [key, fieldValue] of Object.entries(object)) {
|
|
144
|
+
sanitized[key] = RedactingObservability.#redactField(key, fieldValue, seen);
|
|
145
|
+
}
|
|
146
|
+
return sanitized;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* @param {string} key
|
|
151
|
+
* @param {unknown} value
|
|
152
|
+
* @param {WeakSet<object>} seen
|
|
153
|
+
* @returns {unknown}
|
|
154
|
+
*/
|
|
155
|
+
static #redactField(key, value, seen) {
|
|
156
|
+
if (RedactingObservability.#isSensitiveField(key)) {
|
|
157
|
+
return REDACTED;
|
|
158
|
+
}
|
|
159
|
+
return RedactingObservability.#redactValue(value, seen);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* @param {string} key
|
|
164
|
+
* @returns {boolean}
|
|
165
|
+
*/
|
|
166
|
+
static #isSensitiveField(key) {
|
|
167
|
+
return SENSITIVE_FIELD_NAMES.has(key.toLowerCase().replaceAll(/[-_]/g, ''));
|
|
168
|
+
}
|
|
169
|
+
}
|