@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.
Files changed (173) hide show
  1. package/ADVANCED_GUIDE.md +1027 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +449 -5
  4. package/CODE_OF_CONDUCT.md +33 -0
  5. package/GUIDE.md +926 -0
  6. package/README.md +106 -366
  7. package/SECURITY.md +993 -0
  8. package/SUPPORT.md +54 -0
  9. package/UPGRADING.md +299 -0
  10. package/bin/actions.js +70 -21
  11. package/bin/agent/cli.js +51 -0
  12. package/bin/agent/commands/doctor.js +99 -0
  13. package/bin/agent/commands/index.js +1489 -0
  14. package/bin/agent/input.js +619 -0
  15. package/bin/agent/passphrase-source.js +123 -0
  16. package/bin/agent/protocol.js +193 -0
  17. package/bin/build-version.js +64 -0
  18. package/bin/credentials.js +425 -0
  19. package/bin/git-cas.js +595 -449
  20. package/bin/passphrase-source.js +266 -0
  21. package/bin/restore-output-target.js +28 -0
  22. package/bin/ui/blocks/asset-card.js +109 -0
  23. package/bin/ui/blocks/health-dashboard.js +149 -0
  24. package/bin/ui/blocks/heatmap-block.js +67 -0
  25. package/bin/ui/blocks/merkle-explorer.js +163 -0
  26. package/bin/ui/blocks/operation-feed.js +176 -0
  27. package/bin/ui/blocks/wizard-block.js +168 -0
  28. package/bin/ui/components/short-sha.js +36 -0
  29. package/bin/ui/context.js +56 -1
  30. package/bin/ui/dashboard-cmds.js +1578 -13
  31. package/bin/ui/dashboard-view.js +612 -145
  32. package/bin/ui/dashboard.js +1255 -212
  33. package/bin/ui/encryption-card.js +69 -26
  34. package/bin/ui/heatmap.js +26 -54
  35. package/bin/ui/history-timeline.js +51 -19
  36. package/bin/ui/manifest-view.js +115 -60
  37. package/bin/ui/merkle-dag.js +83 -0
  38. package/bin/ui/progress.js +15 -9
  39. package/bin/ui/repo-treemap.js +328 -0
  40. package/bin/ui/shaders/bak-sneppen.js +180 -0
  41. package/bin/ui/shaders/fractal-zoom.js +99 -0
  42. package/bin/ui/shaders/merkle-tree.js +142 -0
  43. package/bin/ui/shaders/organic-flow.js +96 -0
  44. package/bin/ui/shaders/phase-portrait.js +93 -0
  45. package/bin/ui/store-wizard.js +367 -0
  46. package/bin/ui/theme.js +155 -0
  47. package/bin/ui/vault-report.js +495 -0
  48. package/build-info.json +4 -0
  49. package/docs/API.md +2254 -0
  50. package/docs/ENCRYPTION_MODES.md +33 -0
  51. package/docs/EXTENDING.md +174 -0
  52. package/docs/STORE_RESTORE_PIPELINE.md +199 -0
  53. package/docs/THREAT_MODEL.md +269 -0
  54. package/docs/VAULT_INTERNALS.md +251 -0
  55. package/docs/WALKTHROUGH.md +1868 -0
  56. package/docs/demo.gif +0 -0
  57. package/docs/releases/v6.0.0.md +104 -0
  58. package/examples/README.md +260 -0
  59. package/index.d.ts +273 -80
  60. package/index.js +220 -59
  61. package/package.json +35 -6
  62. package/scripts/migrate-encryption.js +680 -0
  63. package/src/domain/bytes/ByteLayout.js +96 -0
  64. package/src/domain/encoding/base64.js +91 -0
  65. package/src/domain/encoding/hex.js +14 -0
  66. package/src/domain/encoding/utf8.js +123 -0
  67. package/src/domain/encryption/schemes.js +132 -0
  68. package/src/domain/errors/CannotRemoveLastRecipientError.js +10 -0
  69. package/src/domain/errors/CasError.d.ts +28 -0
  70. package/src/domain/errors/CasError.js +43 -6
  71. package/src/domain/errors/Codes.js +54 -0
  72. package/src/domain/errors/DekUnwrapFailedError.js +10 -0
  73. package/src/domain/errors/GitError.js +10 -0
  74. package/src/domain/errors/GitPlumbingInitializationError.js +10 -0
  75. package/src/domain/errors/IntegrityError.js +10 -0
  76. package/src/domain/errors/InvalidChunkingStrategyError.js +10 -0
  77. package/src/domain/errors/InvalidOidError.js +10 -0
  78. package/src/domain/errors/InvalidOptionsError.js +10 -0
  79. package/src/domain/errors/ManifestIntegrityError.js +10 -0
  80. package/src/domain/errors/ManifestNotFoundError.js +10 -0
  81. package/src/domain/errors/NoMatchingRecipientError.js +10 -0
  82. package/src/domain/errors/PersistenceCapabilityRequiredError.js +10 -0
  83. package/src/domain/errors/PortNotImplementedError.js +10 -0
  84. package/src/domain/errors/RecipientAlreadyExistsError.js +10 -0
  85. package/src/domain/errors/RecipientNotFoundError.js +10 -0
  86. package/src/domain/errors/RestoreTooLargeError.js +10 -0
  87. package/src/domain/errors/RotationNotSupportedError.js +10 -0
  88. package/src/domain/errors/createCasError.js +68 -0
  89. package/src/domain/errors/index.js +20 -0
  90. package/src/domain/helpers/buildKdfMetadata.js +4 -2
  91. package/src/domain/helpers/codecBytes.js +34 -0
  92. package/src/domain/helpers/gitRefErrors.js +84 -0
  93. package/src/domain/helpers/scryptMaxmem.js +22 -0
  94. package/src/domain/outcomes/RestoreFailure.js +15 -0
  95. package/src/domain/outcomes/RestoreOutcome.js +11 -0
  96. package/src/domain/outcomes/RestoreSuccess.js +34 -0
  97. package/src/domain/outcomes/StoreFailure.js +15 -0
  98. package/src/domain/outcomes/StoreOutcome.js +11 -0
  99. package/src/domain/outcomes/StoreSuccess.js +17 -0
  100. package/src/domain/schemas/ManifestSchema.d.ts +40 -9
  101. package/src/domain/schemas/ManifestSchema.js +67 -13
  102. package/src/domain/services/CasService.d.ts +153 -53
  103. package/src/domain/services/CasService.js +322 -837
  104. package/src/domain/services/ChunkRepository.js +268 -0
  105. package/src/domain/services/CompressionStreams.js +72 -0
  106. package/src/domain/services/ConvergentEncryption.js +128 -0
  107. package/src/domain/services/GitTreeBuilder.js +86 -0
  108. package/src/domain/services/IntegrityVerifier.js +199 -0
  109. package/src/domain/services/KeyResolver.js +49 -42
  110. package/src/domain/services/ManifestDiff.js +56 -0
  111. package/src/domain/services/ManifestRepository.js +286 -0
  112. package/src/domain/services/PrefetchWindow.js +48 -0
  113. package/src/domain/services/RecipientService.js +157 -0
  114. package/src/domain/services/RedactingObservability.js +169 -0
  115. package/src/domain/services/RestorePipeline.js +68 -0
  116. package/src/domain/services/StorePipeline.js +201 -0
  117. package/src/domain/services/VaultKeyVerifier.js +101 -0
  118. package/src/domain/services/VaultMetadataCodec.js +206 -0
  119. package/src/domain/services/VaultMutationRetryPolicy.js +105 -0
  120. package/src/domain/services/VaultPersistence.js +410 -0
  121. package/src/domain/services/VaultPrivacyIndex.js +191 -0
  122. package/src/domain/services/VaultService.js +749 -251
  123. package/src/domain/services/VaultStateCache.js +225 -0
  124. package/src/domain/services/VaultTreeCodec.js +121 -0
  125. package/src/domain/services/rotateVaultPassphrase.js +37 -20
  126. package/src/domain/strategies/Aad.js +39 -0
  127. package/src/domain/strategies/FramedRecordCodec.js +204 -0
  128. package/src/domain/strategies/RestoreCompressed.js +40 -0
  129. package/src/domain/strategies/RestoreConvergent.js +44 -0
  130. package/src/domain/strategies/RestoreFramed.js +55 -0
  131. package/src/domain/strategies/RestorePlain.js +37 -0
  132. package/src/domain/strategies/RestoreStrategy.js +35 -0
  133. package/src/domain/strategies/RestoreWhole.js +135 -0
  134. package/src/domain/strategies/StoreConvergent.js +28 -0
  135. package/src/domain/strategies/StoreFramed.js +39 -0
  136. package/src/domain/strategies/StorePlain.js +20 -0
  137. package/src/domain/strategies/StoreStrategy.js +61 -0
  138. package/src/domain/strategies/StoreWhole.js +34 -0
  139. package/src/domain/value-objects/Chunk.js +1 -2
  140. package/src/domain/value-objects/EncryptionMetadata.js +87 -0
  141. package/src/domain/value-objects/Manifest.d.ts +40 -4
  142. package/src/domain/value-objects/Manifest.js +61 -20
  143. package/src/domain/value-objects/Oid.js +45 -0
  144. package/src/domain/value-objects/Slug.js +124 -0
  145. package/src/domain/value-objects/StoreEncryptionConfig.js +114 -0
  146. package/src/helpers/aesGcmMeta.js +55 -0
  147. package/src/helpers/canonicalBase64.js +1 -0
  148. package/src/helpers/kdfPolicy.js +194 -0
  149. package/src/infrastructure/adapters/BunCryptoAdapter.js +124 -8
  150. package/src/infrastructure/adapters/FileIOHelper.js +180 -13
  151. package/src/infrastructure/adapters/GitPersistenceAdapter.js +235 -42
  152. package/src/infrastructure/adapters/GitPlumbingFactoryAdapter.js +62 -0
  153. package/src/infrastructure/adapters/GitRefAdapter.js +19 -6
  154. package/src/infrastructure/adapters/NodeCompressionAdapter.js +64 -0
  155. package/src/infrastructure/adapters/NodeCryptoAdapter.js +130 -10
  156. package/src/infrastructure/adapters/WebCryptoAdapter.js +187 -77
  157. package/src/infrastructure/chunkers/CdcChunker.js +53 -19
  158. package/src/infrastructure/chunkers/FixedChunker.js +15 -7
  159. package/src/infrastructure/chunkers/resolveChunker.js +10 -6
  160. package/src/infrastructure/codecs/CborCodec.js +3 -3
  161. package/src/infrastructure/codecs/JsonCodec.js +5 -5
  162. package/src/infrastructure/createGitPlumbing.js +22 -0
  163. package/src/package-version.js +1 -0
  164. package/src/ports/ChunkingPort.js +3 -3
  165. package/src/ports/CodecPort.js +4 -4
  166. package/src/ports/CompressionPort.js +57 -0
  167. package/src/ports/CryptoPort.js +138 -50
  168. package/src/ports/GitPersistencePort.js +32 -2
  169. package/src/ports/GitPlumbingFactoryPort.js +16 -0
  170. package/src/ports/GitRefPort.js +1 -1
  171. package/src/types/ambient.d.ts +10 -5
  172. package/test/CONVENTIONS.md +94 -0
  173. package/test/cycles/README.md +13 -0
@@ -1,28 +1,52 @@
1
1
  /* @ts-self-types="./CasService.d.ts" */
2
2
  /**
3
- * @fileoverview Domain service for Content Addressable Storage operations.
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 Semaphore from './Semaphore.js';
12
- import FixedChunker from '../../infrastructure/chunkers/FixedChunker.js';
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
- const gunzipAsync = promisify(gunzip);
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
- /** @type {KeyResolver} */
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,398 @@ 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] - 256 KiB
34
- * @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
35
- * @param {number} [options.concurrency=1] - Maximum parallel chunk I/O operations.
36
- * @param {import('../../ports/ChunkingPort.js').default} [options.chunker] - Chunking strategy (default FixedChunker).
37
- * @param {number} [options.maxRestoreBufferSize=536870912] - Max bytes for buffered restore (default 512 MiB).
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 = observability;
79
+ this.observability = safeObservability;
46
80
  this.chunkSize = chunkSize;
47
- if (chunkSize > 10 * 1024 * 1024) {
48
- observability.log('warn', `Chunk size ${chunkSize} exceeds 10 MiB — consider a smaller value`, { chunkSize });
49
- }
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
- * Validates constructor numeric arguments.
60
- * @private
61
- */
62
- static #validateConstructorArgs({ chunkSize, merkleThreshold, concurrency, maxRestoreBufferSize }) {
63
- if (!Number.isInteger(chunkSize) || chunkSize < 1024) {
64
- throw new Error('Chunk size must be an integer >= 1024 bytes');
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 });
65
118
  }
66
- const MAX_CHUNK_SIZE = 100 * 1024 * 1024;
67
- if (chunkSize > MAX_CHUNK_SIZE) {
68
- throw new Error(`Chunk size must not exceed ${MAX_CHUNK_SIZE} bytes (100 MiB)`);
69
- }
70
- if (!Number.isInteger(merkleThreshold) || merkleThreshold < 1) {
71
- throw new Error('Merkle threshold must be a positive integer');
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 (!Number.isInteger(concurrency) || concurrency < 1) {
74
- throw new Error('Concurrency must be a positive integer');
130
+ if (!compressionAdapter) {
131
+ throw createCasError('compressionAdapter is required — inject a CompressionPort instance', ErrorCodes.INVALID_OPTIONS);
75
132
  }
76
- if (!Number.isInteger(maxRestoreBufferSize) || maxRestoreBufferSize < 1024) {
77
- throw new Error('maxRestoreBufferSize must be a positive integer >= 1024');
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
- !observability ||
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
- * Generates a SHA-256 hex digest for a buffer.
99
- * @private
100
- * @param {Buffer} buf - Data to hash.
101
- * @returns {Promise<string>} 64-character hex digest.
102
- */
152
+ #buildStoreStrategies({ crypto, chunks = this.#chunkRepository }) {
153
+ return Object.freeze({
154
+ plain: new StorePlain(chunks),
155
+ convergent: new StoreConvergent(chunks),
156
+ framed: new StoreFramed({ chunks, framed: this.#framed }),
157
+ whole: new StoreWhole({ chunks, 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
- * Stores a single buffer chunk in Git, returning its metadata.
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
- * Reads an async iterable source, splits it into chunks via the configured
123
- * chunker, and stores each chunk in Git.
124
- * @private
125
- * @param {AsyncIterable<Buffer>} source - The data source to chunk.
126
- * @param {Object} manifestData - Mutable manifest accumulator.
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
- for await (const chunk of this.chunker.chunk(source)) {
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
- const casErr = new CasError(
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
- const results = await Promise.all(pending);
171
- results.sort((a, b) => a.index - b.index);
172
- for (const entry of results) {
173
- manifestData.chunks.push(entry);
174
- manifestData.size += entry.size;
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
- * Encrypts a buffer using AES-256-GCM.
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
- * Decrypts a buffer. Returns the buffer unchanged if `meta.encrypted` is falsy.
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
- * Wraps an async iterable through gzip compression.
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 new CasError(
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) { return; }
247
- const validStrategies = ['fixed', 'cdc'];
248
- if (!validStrategies.includes(chunking.strategy)) {
249
- throw new CasError(
250
- `Unsupported chunking strategy: ${chunking.strategy}`,
251
- 'INVALID_CHUNKING_STRATEGY',
252
- { strategy: chunking.strategy },
253
- );
242
+ if (!chunking) {
243
+ return;
244
+ }
245
+ if (!['fixed', 'cdc'].includes(chunking.strategy)) {
246
+ throw createCasError(`Unsupported chunking strategy: ${chunking.strategy}`, ErrorCodes.INVALID_CHUNKING_STRATEGY, { strategy: chunking.strategy });
247
+ }
248
+ }
249
+
250
+ #validateOperationChunker(chunker) {
251
+ if (!chunker) {
252
+ return this.chunker;
254
253
  }
254
+ if (typeof chunker.chunk !== 'function' || typeof chunker.strategy !== 'string') {
255
+ throw createCasError('chunker must implement ChunkingPort', ErrorCodes.INVALID_OPTIONS, { strategy: chunker.strategy });
256
+ }
257
+ return chunker;
258
+ }
259
+
260
+ #storeStrategiesFor(chunker) {
261
+ if (chunker === this.chunker) {
262
+ return this.#storeStrategies;
263
+ }
264
+ return this.#buildStoreStrategies({ crypto: this.crypto, chunks: this.#chunkRepository.withChunker(chunker) });
255
265
  }
256
266
 
257
267
  /**
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
268
  * @param {Object} options
264
- * @param {AsyncIterable<Buffer>} options.source
269
+ * @param {AsyncIterable<Uint8Array>} options.source
265
270
  * @param {string} options.slug
266
271
  * @param {string} options.filename
267
- * @param {Buffer} [options.encryptionKey]
268
- * @param {string} [options.passphrase] - Derive encryption key from passphrase instead.
269
- * @param {Object} [options.kdfOptions] - KDF options when using passphrase.
270
- * @param {{ algorithm: 'gzip' }} [options.compression] - Enable compression.
271
- * @param {Array<{label: string, key: Buffer}>} [options.recipients] - Envelope recipients (mutually exclusive with encryptionKey/passphrase).
272
- * @returns {Promise<import('../value-objects/Manifest.js').default>}
273
- */
274
- async store({ source, slug, filename, encryptionKey, passphrase, kdfOptions, compression, recipients }) {
272
+ * @param {Uint8Array} [options.encryptionKey]
273
+ * @param {string} [options.passphrase]
274
+ * @param {{ scheme?: 'whole'|'framed'|'convergent', frameBytes?: number, convergent?: boolean }} [options.encryption]
275
+ * @param {Object} [options.kdfOptions]
276
+ * @param {{ algorithm: 'gzip' }} [options.compression]
277
+ * @param {Array<{label: string, key: Uint8Array}>} [options.recipients]
278
+ * @param {number} [options.merkleThreshold]
279
+ * @param {import('../../ports/ChunkingPort.js').default} [options.chunker]
280
+ * @returns {Promise<Manifest>}
281
+ */
282
+ async store(options) {
283
+ const { source, slug, filename, compression, merkleThreshold } = options;
284
+ this.#validateStoreOptions(options);
285
+ const plan = await this.#buildStorePlan(options);
286
+ const manifestData = this._buildManifestData({ slug, filename, compression, chunker: plan.chunker });
287
+ const processedSource = compression ? this.#compression.compress(source) : source;
288
+
289
+ await this._dispatchStore({ processedSource, manifestData, keyInfo: plan.keyInfo, encryptionConfig: plan.encryptionConfig, chunker: plan.chunker });
290
+ return this.#finalizeStore({ manifestData, merkleThreshold, keyInfo: plan.keyInfo, slug });
291
+ }
292
+
293
+ #validateStoreOptions({ source, recipients, encryptionKey, passphrase, compression, merkleThreshold }) {
294
+ if (!source || typeof source[Symbol.asyncIterator] !== 'function') {
295
+ throw createCasError('source must be an async iterable', ErrorCodes.INVALID_OPTIONS, { sourceType: typeof source });
296
+ }
275
297
  if (recipients && (encryptionKey || passphrase)) {
276
- throw new CasError('Provide recipients or encryptionKey/passphrase, not both', 'INVALID_OPTIONS');
298
+ throw createCasError('Provide recipients or encryptionKey/passphrase, not both', ErrorCodes.INVALID_OPTIONS);
277
299
  }
278
300
  KeyResolver.validateKeySourceExclusive(encryptionKey, passphrase);
279
301
  this._validateCompression(compression);
302
+ CasService.#validateMerkleThreshold(merkleThreshold);
303
+ }
280
304
 
305
+ async #buildStorePlan({ encryptionKey, passphrase, encryption, kdfOptions, recipients, chunker }) {
306
+ const operationChunker = this.#validateOperationChunker(chunker);
281
307
  const keyInfo = recipients
282
308
  ? await this.#keyResolver.resolveRecipients(recipients)
283
309
  : await this.#keyResolver.resolveForStore(encryptionKey, passphrase, kdfOptions);
310
+ const encryptionConfig = this._resolveStoreEncryptionConfigForChunker({ encryption, hasEncryptionKey: !!keyInfo.key, chunker: operationChunker });
311
+ return { chunker: operationChunker, keyInfo, encryptionConfig };
312
+ }
284
313
 
285
- const manifestData = this._buildManifestData(slug, filename, compression);
286
- const processedSource = compression ? this._compressStream(source) : source;
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
- }
302
-
314
+ #finalizeStore({ manifestData, merkleThreshold, keyInfo, slug }) {
303
315
  const manifest = new Manifest(manifestData);
316
+ this.#rememberMerkleThreshold(manifest, merkleThreshold);
304
317
  this.observability.metric('file', {
305
- action: 'stored', slug, size: manifest.size, chunkCount: manifest.chunks.length, encrypted: !!keyInfo.key,
318
+ action: 'stored',
319
+ slug,
320
+ size: manifest.size,
321
+ chunkCount: manifest.chunks.length,
322
+ encrypted: !!keyInfo.key,
306
323
  });
307
- return manifest;
324
+ return new StoreSuccess({ manifest }).manifest;
308
325
  }
309
326
 
310
- /**
311
- * Builds initial manifest data with optional chunking and compression metadata.
312
- * @private
313
- */
314
- _buildManifestData(slug, filename, compression) {
315
- const data = { slug, filename, size: 0, chunks: [] };
316
- if (this.chunker.strategy !== 'fixed') {
317
- data.chunking = { strategy: this.chunker.strategy, params: this.chunker.params };
318
- }
319
- if (compression) { data.compression = { algorithm: 'gzip' }; }
320
- return data;
327
+ _resolveStoreEncryptionConfigForChunker({ encryption, hasEncryptionKey, chunker }) {
328
+ return StoreEncryptionConfig.resolve({ encryption, hasEncryptionKey, chunker, observability: this.observability });
321
329
  }
322
330
 
323
331
  /**
324
- * Builds unique chunk blob tree entries in first-seen order.
325
- *
326
- * Tree entries keep chunk blobs reachable in Git. The manifest remains the
327
- * authoritative ordered list of chunk occurrences, so repeated digests only
328
- * need one tree entry.
329
- *
330
- * @private
331
- * @param {import('../value-objects/Chunk.js').default[]} chunks
332
- * @returns {string[]}
332
+ * @param {Manifest} manifest
333
+ * @param {number|undefined} merkleThreshold
333
334
  */
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}`);
335
+ #rememberMerkleThreshold(manifest, merkleThreshold) {
336
+ if (merkleThreshold !== undefined) {
337
+ this.#merkleThresholdByManifest.set(manifest, merkleThreshold);
344
338
  }
345
-
346
- return treeEntries;
347
339
  }
348
340
 
349
- /**
350
- * Creates a Git tree object from a manifest.
351
- *
352
- * The tree contains the serialized manifest file and one blob entry per
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 });
364
- }
365
-
366
- const serializedManifest = this.codec.encode(manifest.toJSON());
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);
341
+ async _dispatchStore({ processedSource, manifestData, keyInfo, encryptionConfig, chunker = this.chunker }) {
342
+ const strategy = StoreStrategy.for({
343
+ keyInfo,
344
+ encryptionConfig,
345
+ chunker,
346
+ observability: this.observability,
347
+ strategies: this.#storeStrategiesFor(chunker),
348
+ });
349
+ await strategy.execute({ processedSource, manifestData, keyInfo, encryptionConfig });
375
350
  }
376
351
 
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
- });
352
+ _buildManifestData({ slug, filename, compression, chunker = this.chunker }) {
353
+ const data = { slug, filename, size: 0, chunks: [] };
354
+ if (this.formatVersion) {
355
+ data.formatVersion = this.formatVersion;
399
356
  }
400
-
401
- const rootManifestData = {
402
- ...manifest.toJSON(),
403
- version: 2,
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);
357
+ if (chunker.strategy !== 'fixed') {
358
+ data.chunking = { strategy: chunker.strategy, params: chunker.params };
359
+ }
360
+ if (compression) {
361
+ data.compression = { algorithm: 'gzip' };
362
+ }
363
+ return data;
422
364
  }
423
365
 
424
- /**
425
- * Reads a single chunk blob from Git and verifies its SHA-256 digest.
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;
366
+ _isLegacyNoAad(manifest) {
367
+ return this.#manifestRepository.isLegacyNoAad(manifest);
444
368
  }
445
369
 
446
- /**
447
- * Reads chunk blobs from Git and verifies their SHA-256 digests.
448
- * @private
449
- * @param {import('../value-objects/Chunk.js').default[]} chunks - Chunk metadata from the manifest.
450
- * @returns {Promise<Buffer[]>} Verified chunk buffers in order.
451
- * @throws {CasError} INTEGRITY_ERROR if any chunk digest does not match.
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;
370
+ async createTree({ manifest, merkleThreshold }) {
371
+ CasService.#validateMerkleThreshold(merkleThreshold);
372
+ return await this.#manifestRepository.createTree({
373
+ manifest,
374
+ merkleThreshold: merkleThreshold ?? this.#merkleThresholdByManifest.get(manifest),
375
+ });
461
376
  }
462
377
 
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
378
  async restore({ manifest, encryptionKey, passphrase }) {
478
379
  const chunks = [];
479
380
  for await (const chunk of this.restoreStream({ manifest, encryptionKey, passphrase })) {
480
381
  chunks.push(chunk);
481
382
  }
482
- const buffer = Buffer.concat(chunks);
483
- return { buffer, bytesWritten: buffer.length };
484
- }
485
-
486
- /**
487
- * Restores a file from its manifest as an async iterable of Buffer chunks.
488
- *
489
- * For unencrypted, uncompressed files this is true per-chunk streaming
490
- * with O(chunkSize) memory. For encrypted or compressed files, all chunks
491
- * are buffered internally for decryption/decompression, then yielded.
492
- *
493
- * @param {Object} options
494
- * @param {import('../value-objects/Manifest.js').default} options.manifest - The file manifest.
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
- }
383
+ return RestoreSuccess.fromChunks(chunks);
521
384
  }
522
385
 
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);
386
+ async createFileRestorePlan({ manifest, encryptionKey, passphrase }) {
387
+ const encryptionMeta = this._validatedEncryptionMeta(manifest);
388
+ if (encryptionMeta?.scheme === 'whole') {
389
+ const key = await this.#keyResolver.resolveForDecryption(manifest, encryptionKey, passphrase);
390
+ return {
391
+ mode: 'bounded-file',
392
+ source: await this.#restoreStrategies.whole.createBoundedSource({ manifest, key, encryptionMeta }),
393
+ encryptionMeta,
394
+ };
568
395
  }
396
+ return {
397
+ mode: 'stream',
398
+ source: this.restoreStream({ manifest, encryptionKey, passphrase }),
399
+ encryptionMeta,
400
+ };
569
401
  }
570
402
 
571
- /**
572
- * Per-chunk streaming restore with read-ahead.
573
- * @private
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
- }
403
+ async *restoreStream({ manifest, encryptionKey, passphrase }) {
404
+ const encryptionMeta = this._validatedEncryptionMeta(manifest);
405
+ const key = await this.#keyResolver.resolveForDecryption(manifest, encryptionKey, passphrase);
586
406
 
587
- try {
588
- for (let i = 0; i < chunks.length; i++) {
589
- const blob = await ahead[i % readAhead];
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);
407
+ if (manifest.chunks.length === 0 && !encryptionMeta && !manifest.compression) {
408
+ this.observability.metric('file', { action: 'restored', slug: manifest.slug, size: 0, chunkCount: 0 });
409
+ return;
600
410
  }
601
411
 
602
- this.observability.metric('file', {
603
- action: 'restored', slug: manifest.slug, size: totalSize, chunkCount: chunks.length,
604
- });
412
+ yield* this._dispatchRestore(manifest, key, encryptionMeta);
605
413
  }
606
414
 
607
- /**
608
- * Decompresses a gzip buffer.
609
- * @private
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
- }
415
+ async *_dispatchRestore(manifest, key, encryptionMeta) {
416
+ const strategy = RestoreStrategy.for({ manifest, encryptionMeta, strategies: this.#restoreStrategies });
417
+ yield* strategy.execute({ manifest, key, encryptionMeta });
618
418
  }
619
419
 
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
420
  async readManifest({ treeOid }) {
630
- let entries;
631
- try {
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
- }
421
+ return await this.#manifestRepository.readManifest({ treeOid });
422
+ }
670
423
 
671
- return new Manifest(decoded);
424
+ async readManifestRaw({ treeOid }) {
425
+ return await this.#manifestRepository.readManifestRaw({ treeOid });
672
426
  }
673
427
 
674
- /**
675
- * Reads and flattens sub-manifest blobs into a single chunk array.
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;
428
+ async _verifyManifestHash(decoded, treeOid) {
429
+ await this.#manifestRepository.verifyManifestHash(decoded, treeOid);
689
430
  }
690
431
 
691
- /**
692
- * Reads a sub-manifest blob, wrapping errors as GIT_ERROR.
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
- }
432
+ static diffManifests(oldManifest, newManifest) {
433
+ return diffManifests(oldManifest, newManifest);
706
434
  }
707
435
 
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
436
  async inspectAsset({ treeOid }) {
718
437
  const manifest = await this.readManifest({ treeOid });
719
- return {
720
- slug: manifest.slug,
721
- chunksOrphaned: manifest.chunks.length,
722
- };
438
+ return { slug: manifest.slug, chunksOrphaned: manifest.chunks.length };
723
439
  }
724
440
 
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
441
  async deleteAsset(options) {
732
442
  this.observability.log('warn', 'deleteAsset() is deprecated — use inspectAsset()');
733
443
  return await this.inspectAsset(options);
734
444
  }
735
445
 
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
446
  async collectReferencedChunks({ treeOids }) {
746
447
  const referenced = new Set();
747
448
  let total = 0;
748
-
749
449
  for (const treeOid of treeOids) {
750
450
  const manifest = await this.readManifest({ treeOid });
751
451
  for (const chunk of manifest.chunks) {
@@ -753,261 +453,46 @@ export default class CasService {
753
453
  total += 1;
754
454
  }
755
455
  }
756
-
757
456
  return { referenced, total };
758
457
  }
759
458
 
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
459
  async findOrphanedChunks(options) {
767
460
  this.observability.log('warn', 'findOrphanedChunks() is deprecated — use collectReferencedChunks()');
768
461
  return await this.collectReferencedChunks(options);
769
462
  }
770
463
 
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
464
  async deriveKey(options) {
785
465
  return await this.crypto.deriveKey(options);
786
466
  }
787
467
 
788
- /**
789
- * Adds a new recipient to an envelope-encrypted manifest.
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 });
468
+ async addRecipient(options) {
469
+ return await this.#recipientService.addRecipient(options);
845
470
  }
846
471
 
847
- /**
848
- * Removes a recipient from an envelope-encrypted manifest.
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 });
472
+ async removeRecipient(options) {
473
+ return await this.#recipientService.removeRecipient(options);
894
474
  }
895
475
 
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
476
  listRecipients(manifest) {
903
- return (manifest.encryption?.recipients || []).map((r) => r.label);
477
+ return this.#recipientService.listRecipients(manifest);
904
478
  }
905
479
 
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 });
940
- }
941
-
942
- /**
943
- * Finds a recipient by label and unwraps the DEK.
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 };
480
+ async rotateKey(options) {
481
+ return await this.#recipientService.rotateKey(options);
952
482
  }
953
483
 
954
- /**
955
- * Finds the first recipient whose DEK can be unwrapped with the given key.
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
- );
484
+ async verifyIntegrity(manifest, options = {}) {
485
+ return await this.#integrityVerifier.verify(manifest, options);
970
486
  }
971
-
972
- /**
973
- * Builds a new Manifest with the rotated recipient entry and updated keyVersions.
974
- */
975
- async #buildRotatedManifest({ manifest, recipients, matchIndex, dek, newKey }) {
976
- const newWrapped = await this.#keyResolver.wrapDek(dek, newKey);
977
- const manifestKeyVersion = (manifest.encryption.keyVersion || 0) + 1;
978
- const recipientKeyVersion = (recipients[matchIndex].keyVersion || 0) + 1;
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 };
487
+ #initIntegrity({ safeObservability }) {
488
+ this.#integrityVerifier = new IntegrityVerifier({
489
+ chunks: this.#chunkRepository,
490
+ crypto: this.crypto,
491
+ framed: this.#framed,
492
+ isLegacyNoAad: (manifest) => this._isLegacyNoAad(manifest),
493
+ keyResolver: this.#keyResolver,
494
+ observability: safeObservability,
495
+ validateEncryptionMeta: (manifest) => this._validatedEncryptionMeta(manifest),
986
496
  });
987
-
988
- return new Manifest({
989
- ...json,
990
- encryption: { ...json.encryption, recipients: updatedRecipients, keyVersion: manifestKeyVersion },
991
- });
992
- }
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
497
  }
1013
498
  }