@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
@@ -0,0 +1,204 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import createCasError from '../errors/createCasError.js';
3
+ import { concatBytes, normalizeByteChunk, readUint32BE, writeUint32BE } from '../bytes/ByteLayout.js';
4
+ import { decodeBase64, encodeBase64 } from '../encoding/base64.js';
5
+ import { buildFramedAad } from './Aad.js';
6
+ import { ErrorCodes } from '../errors/index.js';
7
+
8
+ /** @typedef {import('../value-objects/Manifest.js').default} Manifest */
9
+
10
+ const FRAMED_LENGTH_BYTES = 4;
11
+ const GCM_NONCE_BYTES = 12;
12
+ const GCM_TAG_BYTES = 16;
13
+ const FRAMED_RECORD_HEADER_BYTES = FRAMED_LENGTH_BYTES + GCM_NONCE_BYTES + GCM_TAG_BYTES;
14
+
15
+ /**
16
+ * Owns framed encryption record byte layout and parsing.
17
+ */
18
+ export default class FramedRecordCodec {
19
+ #crypto;
20
+ #observability;
21
+
22
+ /**
23
+ * @param {Object} options
24
+ * @param {import('../../ports/CryptoPort.js').default} options.crypto
25
+ * @param {import('../../ports/ObservabilityPort.js').default} options.observability
26
+ */
27
+ constructor({ crypto, observability }) {
28
+ this.#crypto = crypto;
29
+ this.#observability = observability;
30
+ }
31
+
32
+ /**
33
+ * @param {AsyncIterable<Uint8Array>} source
34
+ * @param {Uint8Array} key
35
+ * @param {{ frameBytes: number, slug: string }} options
36
+ * @returns {AsyncIterable<Uint8Array>}
37
+ */
38
+ async *encryptFrames(source, key, { frameBytes, slug }) {
39
+ let pending = new Uint8Array(0);
40
+ let sawPlaintext = false;
41
+ let frameIndex = 0;
42
+
43
+ for await (const chunk of source) {
44
+ const buf = normalizeByteChunk(chunk);
45
+ if (buf.length === 0) {
46
+ continue;
47
+ }
48
+
49
+ sawPlaintext = true;
50
+ pending = pending.length === 0 ? buf : concatBytes([pending, buf]);
51
+
52
+ while (pending.length >= frameBytes) {
53
+ const frame = pending.subarray(0, frameBytes);
54
+ pending = pending.subarray(frameBytes);
55
+ yield await this.serialize(frame, key, buildFramedAad(slug, frameIndex));
56
+ frameIndex++;
57
+ }
58
+ }
59
+
60
+ if (pending.length > 0) {
61
+ yield await this.serialize(pending, key, buildFramedAad(slug, frameIndex));
62
+ return;
63
+ }
64
+
65
+ if (!sawPlaintext) {
66
+ yield await this.serialize(new Uint8Array(0), key, buildFramedAad(slug, frameIndex));
67
+ }
68
+ }
69
+
70
+ /**
71
+ * @param {Uint8Array} frame
72
+ * @param {Uint8Array} key
73
+ * @param {Uint8Array} [aad]
74
+ * @returns {Promise<Uint8Array>}
75
+ */
76
+ async serialize(frame, key, aad) {
77
+ const { buf, meta } = await this.#crypto.encryptBuffer(frame, key, aad);
78
+ const nonce = decodeBase64(meta.nonce);
79
+ const tag = decodeBase64(meta.tag);
80
+ const header = new Uint8Array(FRAMED_RECORD_HEADER_BYTES);
81
+ writeUint32BE(header, 0, buf.length);
82
+ header.set(nonce, FRAMED_LENGTH_BYTES);
83
+ header.set(tag, FRAMED_LENGTH_BYTES + GCM_NONCE_BYTES);
84
+ return concatBytes([header, buf]);
85
+ }
86
+
87
+ /**
88
+ * @param {AsyncIterable<Uint8Array>} source
89
+ * @param {number} frameBytes
90
+ * @returns {AsyncIterable<{ ciphertext: Uint8Array, meta: { encrypted: true, algorithm: 'aes-256-gcm', nonce: string, tag: string } }>}
91
+ */
92
+ async *parse(source, frameBytes) {
93
+ let pending = new Uint8Array(0);
94
+
95
+ for await (const chunk of source) {
96
+ const buf = normalizeByteChunk(chunk);
97
+ pending = pending.length === 0 ? buf : concatBytes([pending, buf]);
98
+
99
+ while (pending.length >= FRAMED_RECORD_HEADER_BYTES) {
100
+ const consumed = this.consume(pending, frameBytes);
101
+ if (!consumed) {
102
+ break;
103
+ }
104
+ pending = consumed.remaining;
105
+ yield consumed.record;
106
+ }
107
+ }
108
+
109
+ if (pending.length > 0) {
110
+ throw createCasError(
111
+ 'Framed ciphertext is truncated or malformed',
112
+ ErrorCodes.INTEGRITY_ERROR,
113
+ { reason: 'framed-record-parse', remainingBytes: pending.length },
114
+ );
115
+ }
116
+ }
117
+
118
+ /**
119
+ * @param {Uint8Array} pending
120
+ * @param {number} frameBytes
121
+ * @returns {null|{ remaining: Uint8Array, record: { ciphertext: Uint8Array, meta: { encrypted: true, algorithm: 'aes-256-gcm', nonce: string, tag: string } } }}
122
+ */
123
+ consume(pending, frameBytes) {
124
+ const ciphertextLength = readUint32BE(pending, 0);
125
+ if (ciphertextLength > frameBytes) {
126
+ throw createCasError(
127
+ `Framed ciphertext length ${ciphertextLength} exceeds frameBytes ${frameBytes}`,
128
+ ErrorCodes.INTEGRITY_ERROR,
129
+ { reason: 'framed-record-parse', ciphertextLength, frameBytes },
130
+ );
131
+ }
132
+
133
+ const recordLength = FRAMED_RECORD_HEADER_BYTES + ciphertextLength;
134
+ if (pending.length < recordLength) {
135
+ return null;
136
+ }
137
+
138
+ return {
139
+ remaining: pending.subarray(recordLength),
140
+ record: {
141
+ ciphertext: pending.subarray(FRAMED_RECORD_HEADER_BYTES, recordLength),
142
+ meta: this.buildMeta(pending),
143
+ },
144
+ };
145
+ }
146
+
147
+ /**
148
+ * @param {Uint8Array} pending
149
+ * @returns {{ encrypted: true, algorithm: 'aes-256-gcm', nonce: string, tag: string }}
150
+ */
151
+ buildMeta(pending) {
152
+ return {
153
+ encrypted: true,
154
+ algorithm: 'aes-256-gcm',
155
+ nonce: encodeBase64(pending.subarray(FRAMED_LENGTH_BYTES, FRAMED_LENGTH_BYTES + GCM_NONCE_BYTES)),
156
+ tag: encodeBase64(pending.subarray(FRAMED_LENGTH_BYTES + GCM_NONCE_BYTES, FRAMED_RECORD_HEADER_BYTES)),
157
+ };
158
+ }
159
+
160
+ /**
161
+ * @param {{ record: { ciphertext: Uint8Array, meta: object }, key: Uint8Array, aad?: Uint8Array }} options
162
+ * @returns {Promise<Uint8Array>}
163
+ */
164
+ async decryptRecord({ record, key, aad }) {
165
+ try {
166
+ return await this.#crypto.decryptBuffer(record.ciphertext, key, record.meta, aad);
167
+ } catch (err) {
168
+ if (err instanceof CasError) {
169
+ throw err;
170
+ }
171
+ throw createCasError('Decryption failed: Integrity check error', ErrorCodes.INTEGRITY_ERROR, { originalError: err });
172
+ }
173
+ }
174
+
175
+ /**
176
+ * @param {Object} options
177
+ * @param {Manifest} options.manifest
178
+ * @param {AsyncIterable<Uint8Array>} options.source
179
+ * @param {Uint8Array} options.key
180
+ * @param {{ frameBytes: number }} options.encryptionMeta
181
+ * @param {boolean} options.legacyNoAad
182
+ * @returns {AsyncIterable<Uint8Array>}
183
+ */
184
+ async *decryptSource({ manifest, source, key, encryptionMeta, legacyNoAad }) {
185
+ let frameIndex = 0;
186
+ for await (const record of this.parse(source, encryptionMeta.frameBytes)) {
187
+ let plaintext;
188
+ try {
189
+ const aad = legacyNoAad ? undefined : buildFramedAad(manifest.slug, frameIndex);
190
+ plaintext = await this.decryptRecord({ record, key, aad });
191
+ } catch (err) {
192
+ if (err instanceof CasError && err.code === ErrorCodes.INTEGRITY_ERROR) {
193
+ this.#observability.metric('error', { action: 'decryption_failed', slug: manifest.slug });
194
+ }
195
+ throw err;
196
+ }
197
+
198
+ frameIndex++;
199
+ if (plaintext.length > 0) {
200
+ yield plaintext;
201
+ }
202
+ }
203
+ }
204
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Restores plaintext gzip-compressed content as a stream.
3
+ *
4
+ * @typedef {import('../value-objects/Manifest.js').default} Manifest
5
+ */
6
+ export default class RestoreCompressed {
7
+ #chunks;
8
+ #compression;
9
+ #observability;
10
+
11
+ /**
12
+ * @param {Object} options
13
+ * @param {import('../services/ChunkRepository.js').default} options.chunks
14
+ * @param {import('../services/CompressionStreams.js').default} options.compression
15
+ * @param {import('../../ports/ObservabilityPort.js').default} options.observability
16
+ */
17
+ constructor({ chunks, compression, observability }) {
18
+ this.#chunks = chunks;
19
+ this.#compression = compression;
20
+ this.#observability = observability;
21
+ }
22
+
23
+ /**
24
+ * @param {{ manifest: Manifest }} options
25
+ * @returns {AsyncIterable<Uint8Array>}
26
+ */
27
+ async *execute({ manifest }) {
28
+ let totalSize = 0;
29
+ for await (const chunk of this.#compression.decompress(this.#chunks.iterVerifiedChunkBlobs(manifest))) {
30
+ totalSize += chunk.length;
31
+ yield chunk;
32
+ }
33
+ this.#observability.metric('file', {
34
+ action: 'restored',
35
+ slug: manifest.slug,
36
+ size: totalSize,
37
+ chunkCount: manifest.chunks.length,
38
+ });
39
+ }
40
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Restores convergent encrypted chunks, optionally decompressing after decryption.
3
+ *
4
+ * @typedef {import('../value-objects/Manifest.js').default} Manifest
5
+ */
6
+ export default class RestoreConvergent {
7
+ #chunks;
8
+ #compression;
9
+ #observability;
10
+
11
+ /**
12
+ * @param {Object} options
13
+ * @param {import('../services/ChunkRepository.js').default} options.chunks
14
+ * @param {import('../services/CompressionStreams.js').default} options.compression
15
+ * @param {import('../../ports/ObservabilityPort.js').default} options.observability
16
+ */
17
+ constructor({ chunks, compression, observability }) {
18
+ this.#chunks = chunks;
19
+ this.#compression = compression;
20
+ this.#observability = observability;
21
+ }
22
+
23
+ /**
24
+ * @param {{ manifest: Manifest, key: Uint8Array }} options
25
+ * @returns {AsyncIterable<Uint8Array>}
26
+ */
27
+ async *execute({ manifest, key }) {
28
+ const source = manifest.compression
29
+ ? this.#compression.decompress(this.#chunks.iterConvergentChunks(manifest, key))
30
+ : this.#chunks.iterConvergentChunks(manifest, key);
31
+
32
+ let totalSize = 0;
33
+ for await (const chunk of source) {
34
+ totalSize += chunk.length;
35
+ yield chunk;
36
+ }
37
+ this.#observability.metric('file', {
38
+ action: 'restored',
39
+ slug: manifest.slug,
40
+ size: totalSize,
41
+ chunkCount: manifest.chunks.length,
42
+ });
43
+ }
44
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Restores framed encrypted records, optionally decompressing after decryption.
3
+ *
4
+ * @typedef {import('../value-objects/Manifest.js').default} Manifest
5
+ */
6
+ export default class RestoreFramed {
7
+ #chunks;
8
+ #compression;
9
+ #framed;
10
+ #isLegacyNoAad;
11
+ #observability;
12
+
13
+ /**
14
+ * @param {Object} options
15
+ * @param {import('../services/ChunkRepository.js').default} options.chunks
16
+ * @param {import('../services/CompressionStreams.js').default} options.compression
17
+ * @param {import('./FramedRecordCodec.js').default} options.framed
18
+ * @param {(manifest: Manifest) => boolean} options.isLegacyNoAad
19
+ * @param {import('../../ports/ObservabilityPort.js').default} options.observability
20
+ */
21
+ constructor({ chunks, compression, framed, isLegacyNoAad, observability }) {
22
+ this.#chunks = chunks;
23
+ this.#compression = compression;
24
+ this.#framed = framed;
25
+ this.#isLegacyNoAad = isLegacyNoAad;
26
+ this.#observability = observability;
27
+ }
28
+
29
+ /**
30
+ * @param {{ manifest: Manifest, key: Uint8Array, encryptionMeta: { frameBytes: number } }} options
31
+ * @returns {AsyncIterable<Uint8Array>}
32
+ */
33
+ async *execute({ manifest, key, encryptionMeta }) {
34
+ const decrypted = this.#framed.decryptSource({
35
+ manifest,
36
+ source: this.#chunks.iterVerifiedChunkBlobs(manifest),
37
+ key,
38
+ encryptionMeta,
39
+ legacyNoAad: this.#isLegacyNoAad(manifest),
40
+ });
41
+ const source = manifest.compression ? this.#compression.decompress(decrypted) : decrypted;
42
+
43
+ let totalSize = 0;
44
+ for await (const chunk of source) {
45
+ totalSize += chunk.length;
46
+ yield chunk;
47
+ }
48
+ this.#observability.metric('file', {
49
+ action: 'restored',
50
+ slug: manifest.slug,
51
+ size: totalSize,
52
+ chunkCount: manifest.chunks.length,
53
+ });
54
+ }
55
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Restores unencrypted, uncompressed chunks with read-ahead.
3
+ *
4
+ * @typedef {import('../value-objects/Manifest.js').default} Manifest
5
+ */
6
+ export default class RestorePlain {
7
+ #chunks;
8
+ #observability;
9
+
10
+ /**
11
+ * @param {Object} options
12
+ * @param {import('../services/ChunkRepository.js').default} options.chunks
13
+ * @param {import('../../ports/ObservabilityPort.js').default} options.observability
14
+ */
15
+ constructor({ chunks, observability }) {
16
+ this.#chunks = chunks;
17
+ this.#observability = observability;
18
+ }
19
+
20
+ /**
21
+ * @param {{ manifest: Manifest }} options
22
+ * @returns {AsyncIterable<Uint8Array>}
23
+ */
24
+ async *execute({ manifest }) {
25
+ let totalSize = 0;
26
+ for await (const blob of this.#chunks.iterVerifiedChunkBlobs(manifest)) {
27
+ totalSize += blob.length;
28
+ yield blob;
29
+ }
30
+ this.#observability.metric('file', {
31
+ action: 'restored',
32
+ slug: manifest.slug,
33
+ size: totalSize,
34
+ chunkCount: manifest.chunks.length,
35
+ });
36
+ }
37
+ }
@@ -0,0 +1,35 @@
1
+ import {
2
+ SCHEME_CONVERGENT,
3
+ SCHEME_FRAMED,
4
+ SCHEME_WHOLE,
5
+ } from '../encryption/schemes.js';
6
+
7
+ /** @typedef {import('../value-objects/Manifest.js').default} Manifest */
8
+
9
+ /**
10
+ * Selects the restore strategy entity for a manifest.
11
+ */
12
+ export default class RestoreStrategy {
13
+ /**
14
+ * @param {Object} options
15
+ * @param {Manifest} options.manifest
16
+ * @param {{ scheme?: string }} [options.encryptionMeta]
17
+ * @param {{ plain: object, compressed: object, convergent: object, framed: object, whole: object }} options.strategies
18
+ * @returns {object}
19
+ */
20
+ static for({ manifest, encryptionMeta, strategies }) {
21
+ if (encryptionMeta?.scheme === SCHEME_CONVERGENT) {
22
+ return strategies.convergent;
23
+ }
24
+ if (encryptionMeta?.scheme === SCHEME_FRAMED) {
25
+ return strategies.framed;
26
+ }
27
+ if (encryptionMeta?.scheme === SCHEME_WHOLE) {
28
+ return strategies.whole;
29
+ }
30
+ if (manifest.compression) {
31
+ return strategies.compressed;
32
+ }
33
+ return strategies.plain;
34
+ }
35
+ }
@@ -0,0 +1,135 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import createCasError from '../errors/createCasError.js';
3
+ import { concatBytes } from '../bytes/ByteLayout.js';
4
+ import { buildWholeAad } from './Aad.js';
5
+ import { ErrorCodes } from '../errors/index.js';
6
+
7
+ /**
8
+ * Restores whole-object encrypted content while preserving the auth boundary.
9
+ *
10
+ * @typedef {import('../value-objects/Manifest.js').default} Manifest
11
+ */
12
+ export default class RestoreWhole {
13
+ #chunkSize;
14
+ #chunks;
15
+ #compression;
16
+ #crypto;
17
+ #isLegacyNoAad;
18
+ #maxRestoreBufferSize;
19
+ #observability;
20
+
21
+ /**
22
+ * @param {Object} options
23
+ * @param {number} options.chunkSize
24
+ * @param {import('../services/ChunkRepository.js').default} options.chunks
25
+ * @param {import('../services/CompressionStreams.js').default} options.compression
26
+ * @param {import('../../ports/CryptoPort.js').default} options.crypto
27
+ * @param {(manifest: Manifest) => boolean} options.isLegacyNoAad
28
+ * @param {number} options.maxRestoreBufferSize
29
+ * @param {import('../../ports/ObservabilityPort.js').default} options.observability
30
+ */
31
+ constructor({ chunkSize, chunks, compression, crypto, isLegacyNoAad, maxRestoreBufferSize, observability }) {
32
+ this.#chunkSize = chunkSize;
33
+ this.#chunks = chunks;
34
+ this.#compression = compression;
35
+ this.#crypto = crypto;
36
+ this.#isLegacyNoAad = isLegacyNoAad;
37
+ this.#maxRestoreBufferSize = maxRestoreBufferSize;
38
+ this.#observability = observability;
39
+ }
40
+
41
+ /**
42
+ * @param {{ manifest: Manifest, key?: Uint8Array, encryptionMeta?: object }} options
43
+ * @returns {AsyncIterable<Uint8Array>}
44
+ */
45
+ async *execute({ manifest, key, encryptionMeta }) {
46
+ const buffer = await this.#bufferRestore({ manifest, key, encryptionMeta });
47
+ this.#observability.metric('file', {
48
+ action: 'restored',
49
+ slug: manifest.slug,
50
+ size: buffer.length,
51
+ chunkCount: manifest.chunks.length,
52
+ });
53
+ for (let offset = 0; offset < buffer.length; offset += this.#chunkSize) {
54
+ yield buffer.subarray(offset, offset + this.#chunkSize);
55
+ }
56
+ }
57
+
58
+ /**
59
+ * @param {{ manifest: Manifest, key?: Uint8Array, encryptionMeta?: object }} options
60
+ * @returns {Promise<AsyncIterable<Uint8Array>>}
61
+ */
62
+ async createBoundedSource({ manifest, key, encryptionMeta }) {
63
+ let source = this.#chunks.iterVerifiedChunkBlobs(manifest);
64
+ if (encryptionMeta) {
65
+ if (manifest.compression) {
66
+ const plaintext = await this.#decryptWhole({
67
+ manifest,
68
+ ciphertext: concatBytes(await this.#collect(source)),
69
+ key,
70
+ encryptionMeta,
71
+ });
72
+ source = (async function* plaintextSource() { yield plaintext; })();
73
+ } else {
74
+ source = this.#decryptWholeStream({ manifest, source, key, encryptionMeta });
75
+ }
76
+ }
77
+ if (manifest.compression) {
78
+ source = this.#compression.decompress(source);
79
+ }
80
+ return source;
81
+ }
82
+
83
+ async #bufferRestore({ manifest, key, encryptionMeta }) {
84
+ const totalSize = manifest.chunks.reduce((acc, c) => acc + c.size, 0);
85
+ if (totalSize > this.#maxRestoreBufferSize) {
86
+ throw createCasError(
87
+ `Encrypted/compressed restore would buffer ${totalSize} bytes ` +
88
+ `(limit: ${this.#maxRestoreBufferSize}). Increase maxRestoreBufferSize ` +
89
+ 'or store without encryption.',
90
+ ErrorCodes.RESTORE_TOO_LARGE,
91
+ { size: totalSize, limit: this.#maxRestoreBufferSize },
92
+ );
93
+ }
94
+
95
+ let buffer = concatBytes(await this.#chunks.readAndVerifyChunks(manifest.chunks, {
96
+ totalLimit: this.#maxRestoreBufferSize,
97
+ }));
98
+
99
+ if (encryptionMeta) {
100
+ buffer = await this.#decryptWhole({ manifest, ciphertext: buffer, key, encryptionMeta });
101
+ }
102
+ if (manifest.compression) {
103
+ buffer = await this.#compression.decompressBufferedWithLimit(buffer, this.#maxRestoreBufferSize);
104
+ }
105
+ return buffer;
106
+ }
107
+
108
+ async #decryptWhole({ manifest, ciphertext, key, encryptionMeta }) {
109
+ try {
110
+ const aad = this.#isLegacyNoAad(manifest) ? undefined : buildWholeAad(manifest.slug);
111
+ return await this.#crypto.decryptBuffer(ciphertext, key, encryptionMeta, aad);
112
+ } catch (err) {
113
+ if (err instanceof CasError && err.code === ErrorCodes.INTEGRITY_ERROR) {
114
+ this.#observability.metric('error', { action: 'decryption_failed', slug: manifest.slug });
115
+ }
116
+ if (err instanceof CasError) {
117
+ throw err;
118
+ }
119
+ throw createCasError('Decryption failed: Integrity check error', ErrorCodes.INTEGRITY_ERROR, { originalError: err });
120
+ }
121
+ }
122
+
123
+ #decryptWholeStream({ manifest, source, key, encryptionMeta }) {
124
+ const aad = this.#isLegacyNoAad(manifest) ? undefined : buildWholeAad(manifest.slug);
125
+ return this.#crypto.createDecryptionStream(key, encryptionMeta, aad).decrypt(source);
126
+ }
127
+
128
+ async #collect(source) {
129
+ const chunks = [];
130
+ for await (const chunk of source) {
131
+ chunks.push(chunk);
132
+ }
133
+ return chunks;
134
+ }
135
+ }
@@ -0,0 +1,28 @@
1
+ import { SCHEME_CONVERGENT } from '../encryption/schemes.js';
2
+
3
+ /**
4
+ * Stores content using convergent per-chunk encryption.
5
+ */
6
+ export default class StoreConvergent {
7
+ #chunks;
8
+
9
+ /**
10
+ * @param {import('../services/ChunkRepository.js').default} chunks
11
+ */
12
+ constructor(chunks) {
13
+ this.#chunks = chunks;
14
+ }
15
+
16
+ /**
17
+ * @param {{ processedSource: AsyncIterable<Uint8Array>, manifestData: { chunks: Array, size: number, encryption?: object }, keyInfo: { key: Uint8Array, encExtra: object } }} options
18
+ */
19
+ async execute({ processedSource, manifestData, keyInfo }) {
20
+ await this.#chunks.chunkAndStore(processedSource, manifestData, { convergentKey: keyInfo.key });
21
+ manifestData.encryption = {
22
+ scheme: SCHEME_CONVERGENT,
23
+ algorithm: 'aes-256-gcm',
24
+ encrypted: true,
25
+ ...keyInfo.encExtra,
26
+ };
27
+ }
28
+ }
@@ -0,0 +1,39 @@
1
+ import { SCHEME_FRAMED } from '../encryption/schemes.js';
2
+
3
+ /**
4
+ * Stores content as independently encrypted framed records.
5
+ */
6
+ export default class StoreFramed {
7
+ #chunks;
8
+ #framed;
9
+
10
+ /**
11
+ * @param {Object} options
12
+ * @param {import('../services/ChunkRepository.js').default} options.chunks
13
+ * @param {import('./FramedRecordCodec.js').default} options.framed
14
+ */
15
+ constructor({ chunks, framed }) {
16
+ this.#chunks = chunks;
17
+ this.#framed = framed;
18
+ }
19
+
20
+ /**
21
+ * @param {{ processedSource: AsyncIterable<Uint8Array>, manifestData: { slug: string, chunks: Array, size: number, encryption?: object }, keyInfo: { key: Uint8Array, encExtra: object }, encryptionConfig: { frameBytes: number } }} options
22
+ */
23
+ async execute({ processedSource, manifestData, keyInfo, encryptionConfig }) {
24
+ await this.#chunks.chunkAndStore(
25
+ this.#framed.encryptFrames(processedSource, keyInfo.key, {
26
+ frameBytes: encryptionConfig.frameBytes,
27
+ slug: manifestData.slug,
28
+ }),
29
+ manifestData,
30
+ );
31
+ manifestData.encryption = {
32
+ scheme: SCHEME_FRAMED,
33
+ algorithm: 'aes-256-gcm',
34
+ encrypted: true,
35
+ frameBytes: encryptionConfig.frameBytes,
36
+ ...keyInfo.encExtra,
37
+ };
38
+ }
39
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Stores plaintext chunks without encryption.
3
+ */
4
+ export default class StorePlain {
5
+ #chunks;
6
+
7
+ /**
8
+ * @param {import('../services/ChunkRepository.js').default} chunks
9
+ */
10
+ constructor(chunks) {
11
+ this.#chunks = chunks;
12
+ }
13
+
14
+ /**
15
+ * @param {{ processedSource: AsyncIterable<Uint8Array>, manifestData: { chunks: Array, size: number } }} options
16
+ */
17
+ async execute({ processedSource, manifestData }) {
18
+ await this.#chunks.chunkAndStore(processedSource, manifestData);
19
+ }
20
+ }