@git-stunts/git-cas 5.3.2 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/ADVANCED_GUIDE.md +1006 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +393 -5
  4. package/CODE_OF_CONDUCT.md +33 -0
  5. package/GUIDE.md +872 -0
  6. package/README.md +219 -325
  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 +998 -214
  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 +296 -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 +2224 -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 +208 -65
  60. package/index.js +163 -54
  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 +123 -38
  103. package/src/domain/services/CasService.js +298 -834
  104. package/src/domain/services/ChunkRepository.js +230 -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 +178 -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 +3 -1
  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,55 @@
1
+ import CasError from '../domain/errors/CasError.js';
2
+ import { decodeBase64, encodeBase64, isCanonicalBase64 } from '../domain/encoding/base64.js';
3
+ import { ErrorCodes } from '../domain/errors/index.js';
4
+
5
+ export const AES_GCM_ALGORITHM = 'aes-256-gcm';
6
+ export const AES_GCM_NONCE_BYTES = 12;
7
+ export const AES_GCM_TAG_BYTES = 16;
8
+
9
+ function invalidMeta(message, meta) {
10
+ return new CasError(`Invalid AES-GCM metadata: ${message}`, ErrorCodes.INTEGRITY_ERROR, {
11
+ reason: 'invalid-encryption-meta',
12
+ ...meta,
13
+ });
14
+ }
15
+
16
+ function decodeField(field, value, byteLength) {
17
+ if (typeof value !== 'string' || value.length === 0) {
18
+ throw invalidMeta(`${field} must be a non-empty base64 string`, { field });
19
+ }
20
+ if (!isCanonicalBase64(value)) {
21
+ throw invalidMeta(`${field} must be canonical base64`, { field });
22
+ }
23
+ const decoded = decodeBase64(value);
24
+ if (encodeBase64(decoded) !== value) {
25
+ throw invalidMeta(`${field} must be canonical base64`, { field });
26
+ }
27
+ if (decoded.length !== byteLength) {
28
+ throw invalidMeta(`${field} must decode to ${byteLength} bytes`, {
29
+ field,
30
+ expected: byteLength,
31
+ actual: decoded.length,
32
+ });
33
+ }
34
+ return decoded;
35
+ }
36
+
37
+ export default function validateAesGcmMeta(meta) {
38
+ if (!meta || typeof meta !== 'object') {
39
+ throw invalidMeta('metadata object is required');
40
+ }
41
+ if (meta.encrypted !== true) {
42
+ throw invalidMeta('encrypted must be true', { field: 'encrypted' });
43
+ }
44
+ if (meta.algorithm !== AES_GCM_ALGORITHM) {
45
+ throw invalidMeta(`algorithm must be ${AES_GCM_ALGORITHM}`, {
46
+ field: 'algorithm',
47
+ algorithm: meta.algorithm,
48
+ });
49
+ }
50
+
51
+ return {
52
+ nonce: decodeField('nonce', meta.nonce, AES_GCM_NONCE_BYTES),
53
+ tag: decodeField('tag', meta.tag, AES_GCM_TAG_BYTES),
54
+ };
55
+ }
@@ -0,0 +1 @@
1
+ export { isCanonicalBase64 } from '../domain/encoding/base64.js';
@@ -0,0 +1,194 @@
1
+ import CasError from '../domain/errors/CasError.js';
2
+ import { isCanonicalBase64 } from './canonicalBase64.js';
3
+ import { base64DecodedLength } from '../domain/encoding/base64.js';
4
+ import { ErrorCodes } from '../domain/errors/index.js';
5
+
6
+ export const DEFAULT_PBKDF2_ITERATIONS = 600_000;
7
+ export const DEFAULT_SCRYPT_COST = 131_072;
8
+ export const DEFAULT_SCRYPT_BLOCK_SIZE = 8;
9
+ export const DEFAULT_SCRYPT_PARALLELIZATION = 1;
10
+ export const DEFAULT_KDF_KEY_LENGTH = 32;
11
+ export const LEGACY_SCRYPT_COST = 16_384;
12
+
13
+ const MIN_PBKDF2_ITERATIONS = 100_000;
14
+ const MAX_PBKDF2_ITERATIONS = 2_000_000;
15
+ const MIN_SCRYPT_COST = 16_384;
16
+ const MAX_SCRYPT_COST = 1_048_576;
17
+ const MIN_SCRYPT_BLOCK_SIZE = 8;
18
+ const MAX_SCRYPT_BLOCK_SIZE = 32;
19
+ const MIN_SCRYPT_PARALLELIZATION = 1;
20
+ const MAX_SCRYPT_PARALLELIZATION = 16;
21
+
22
+ /** Maximum combined scrypt memory budget: 1 GiB (128 * cost * blockSize). */
23
+ const MAX_SCRYPT_MEMORY = 1024 * 1024 * 1024;
24
+
25
+ function buildPolicyError(message, meta) {
26
+ throw new CasError(message, ErrorCodes.KDF_POLICY_VIOLATION, meta);
27
+ }
28
+
29
+ function assertSupportedAlgorithm(algorithm, source) {
30
+ if (algorithm !== 'pbkdf2' && algorithm !== 'scrypt') {
31
+ buildPolicyError(
32
+ `${source} KDF algorithm is unsupported: ${algorithm}`,
33
+ { source, field: 'algorithm', value: algorithm },
34
+ );
35
+ }
36
+ }
37
+
38
+ function normalizeCost(algorithm, cost) {
39
+ if (cost !== undefined) {
40
+ return cost;
41
+ }
42
+ return algorithm === 'scrypt' ? DEFAULT_SCRYPT_COST : LEGACY_SCRYPT_COST;
43
+ }
44
+
45
+ function assertFiniteInteger(value, field, source) {
46
+ if (!Number.isInteger(value) || value <= 0) {
47
+ buildPolicyError(
48
+ `${source} KDF field "${field}" must be a positive integer`,
49
+ { source, field, value },
50
+ );
51
+ }
52
+ }
53
+
54
+ function assertCanonicalBase64(value, field, source) {
55
+ if (typeof value !== 'string' || value.length === 0 || !isCanonicalBase64(value)) {
56
+ buildPolicyError(
57
+ `${source} KDF field "${field}" must be canonical base64`,
58
+ { source, field, value },
59
+ );
60
+ }
61
+ }
62
+
63
+ function assertRange({ value, field, min, max, source }) {
64
+ assertFiniteInteger(value, field, source);
65
+ if (value < min || value > max) {
66
+ buildPolicyError(
67
+ `${source} KDF field "${field}" must be between ${min} and ${max}`,
68
+ { source, field, value, min, max },
69
+ );
70
+ }
71
+ }
72
+
73
+ function assertKeyLength(keyLength, source) {
74
+ assertFiniteInteger(keyLength, 'keyLength', source);
75
+ if (keyLength !== DEFAULT_KDF_KEY_LENGTH) {
76
+ buildPolicyError(
77
+ `${source} KDF keyLength must be ${DEFAULT_KDF_KEY_LENGTH}`,
78
+ { source, field: 'keyLength', value: keyLength, expected: DEFAULT_KDF_KEY_LENGTH },
79
+ );
80
+ }
81
+ }
82
+
83
+ function assertScryptCost(cost, source) {
84
+ assertRange({
85
+ value: cost,
86
+ field: 'cost',
87
+ min: MIN_SCRYPT_COST,
88
+ max: MAX_SCRYPT_COST,
89
+ source,
90
+ });
91
+ if ((cost & (cost - 1)) !== 0) {
92
+ buildPolicyError(
93
+ `${source} scrypt cost must be a power of two`,
94
+ { source, field: 'cost', value: cost },
95
+ );
96
+ }
97
+ }
98
+
99
+ export function normalizeKdfOptions(options = {}, { source = 'kdf-options' } = {}) {
100
+ const algorithm = options.algorithm ?? 'pbkdf2';
101
+ assertSupportedAlgorithm(algorithm, source);
102
+ return {
103
+ algorithm,
104
+ iterations: options.iterations ?? DEFAULT_PBKDF2_ITERATIONS,
105
+ cost: normalizeCost(algorithm, options.cost),
106
+ blockSize: options.blockSize ?? DEFAULT_SCRYPT_BLOCK_SIZE,
107
+ parallelization: options.parallelization ?? DEFAULT_SCRYPT_PARALLELIZATION,
108
+ keyLength: options.keyLength ?? DEFAULT_KDF_KEY_LENGTH,
109
+ };
110
+ }
111
+
112
+ function requireField(value, field, source) {
113
+ if (value === undefined) {
114
+ buildPolicyError(
115
+ `${source} KDF field "${field}" is required`,
116
+ { source, field, value },
117
+ );
118
+ }
119
+ return value;
120
+ }
121
+
122
+ export function assertKdfPolicy(params, { source }) {
123
+ if (params.algorithm === 'pbkdf2') {
124
+ assertRange({
125
+ value: requireField(params.iterations, 'iterations', source),
126
+ field: 'iterations',
127
+ min: MIN_PBKDF2_ITERATIONS,
128
+ max: MAX_PBKDF2_ITERATIONS,
129
+ source,
130
+ });
131
+ assertKeyLength(params.keyLength, source);
132
+ return;
133
+ }
134
+
135
+ if (params.algorithm === 'scrypt') {
136
+ assertScryptCost(requireField(params.cost, 'cost', source), source);
137
+ assertRange({
138
+ value: requireField(params.blockSize, 'blockSize', source),
139
+ field: 'blockSize',
140
+ min: MIN_SCRYPT_BLOCK_SIZE,
141
+ max: MAX_SCRYPT_BLOCK_SIZE,
142
+ source,
143
+ });
144
+ assertRange(
145
+ {
146
+ value: requireField(params.parallelization, 'parallelization', source),
147
+ field: 'parallelization',
148
+ min: MIN_SCRYPT_PARALLELIZATION,
149
+ max: MAX_SCRYPT_PARALLELIZATION,
150
+ source,
151
+ },
152
+ );
153
+ assertKeyLength(params.keyLength, source);
154
+
155
+ const memoryBytes = 128 * params.cost * params.blockSize;
156
+ if (memoryBytes > MAX_SCRYPT_MEMORY) {
157
+ buildPolicyError(
158
+ `${source} scrypt memory budget exceeds ${MAX_SCRYPT_MEMORY} bytes (128 × ${params.cost} × ${params.blockSize} = ${memoryBytes})`,
159
+ { source, field: 'memory', cost: params.cost, blockSize: params.blockSize, memoryBytes },
160
+ );
161
+ }
162
+ return;
163
+ }
164
+ assertSupportedAlgorithm(params.algorithm, source);
165
+ }
166
+
167
+ export function prepareKdfOptions(kdfOptions, { source }) {
168
+ const normalized = normalizeKdfOptions(kdfOptions, { source });
169
+ assertKdfPolicy(normalized, { source });
170
+ return normalized;
171
+ }
172
+
173
+ const MIN_SALT_BYTES = 16;
174
+
175
+ export function prepareStoredKdfOptions(kdf, { source }) {
176
+ assertCanonicalBase64(kdf.salt, 'salt', source);
177
+ const saltBytes = base64DecodedLength(kdf.salt);
178
+ if (saltBytes < MIN_SALT_BYTES) {
179
+ buildPolicyError(
180
+ `${source} KDF salt must be at least ${MIN_SALT_BYTES} bytes, got ${saltBytes}`,
181
+ { source, field: 'salt', saltBytes, minSaltBytes: MIN_SALT_BYTES },
182
+ );
183
+ }
184
+ const params = {
185
+ algorithm: kdf.algorithm,
186
+ iterations: kdf.iterations,
187
+ cost: kdf.cost,
188
+ blockSize: kdf.blockSize,
189
+ parallelization: kdf.parallelization,
190
+ keyLength: kdf.keyLength,
191
+ };
192
+ assertKdfPolicy(params, { source });
193
+ return params;
194
+ }
@@ -1,12 +1,24 @@
1
+ import { ErrorCodes } from '../../domain/errors/index.js';
1
2
  // @ts-ignore -- 'bun' module only available in Bun runtime
2
3
  import { CryptoHasher } from 'bun';
3
4
  import CryptoPort from '../../ports/CryptoPort.js';
4
5
  import CasError from '../../domain/errors/CasError.js';
6
+ import scryptMaxmem from '../../domain/helpers/scryptMaxmem.js';
7
+ import validateAesGcmMeta, { AES_GCM_ALGORITHM, AES_GCM_TAG_BYTES } from '../../helpers/aesGcmMeta.js';
5
8
  // We still use node:crypto for AES-GCM because Bun's native implementation
6
9
  // is heavily optimized for these specific Node APIs.
7
- import { createCipheriv, createDecipheriv, pbkdf2, scrypt } from 'node:crypto';
10
+ import { createHmac, createCipheriv, createDecipheriv, pbkdf2, scrypt } from 'node:crypto';
8
11
  import { promisify } from 'node:util';
9
12
 
13
+ function wrapDecryptError(err) {
14
+ if (err instanceof CasError) {
15
+ return err;
16
+ }
17
+ return new CasError('Decryption failed: Integrity check error', ErrorCodes.INTEGRITY_ERROR, {
18
+ originalError: err,
19
+ });
20
+ }
21
+
10
22
  /**
11
23
  * Bun-native {@link CryptoPort} implementation.
12
24
  *
@@ -38,12 +50,16 @@ export default class BunCryptoAdapter extends CryptoPort {
38
50
  * @override
39
51
  * @param {Buffer|Uint8Array} buffer - Plaintext to encrypt.
40
52
  * @param {Buffer|Uint8Array} key - 32-byte encryption key.
53
+ * @param {Buffer|Uint8Array} [aad] - Optional additional authenticated data (AAD).
41
54
  * @returns {Promise<{ buf: Buffer, meta: import('../../ports/CryptoPort.js').EncryptionMeta }>}
42
55
  */
43
- async encryptBuffer(buffer, key) {
56
+ async encryptBuffer(buffer, key, aad) {
44
57
  this._validateKey(key);
45
58
  const nonce = this.randomBytes(12);
46
59
  const cipher = createCipheriv('aes-256-gcm', key, nonce);
60
+ if (aad) {
61
+ cipher.setAAD(aad);
62
+ }
47
63
  const enc = Buffer.concat([cipher.update(buffer), cipher.final()]);
48
64
  const tag = cipher.getAuthTag();
49
65
  return {
@@ -57,26 +73,35 @@ export default class BunCryptoAdapter extends CryptoPort {
57
73
  * @param {Buffer|Uint8Array} buffer - Ciphertext to decrypt.
58
74
  * @param {Buffer|Uint8Array} key - 32-byte encryption key.
59
75
  * @param {import('../../ports/CryptoPort.js').EncryptionMeta} meta - Encryption metadata.
76
+ * @param {Buffer|Uint8Array} [aad] - Optional additional authenticated data (AAD).
60
77
  * @returns {Promise<Buffer>}
61
78
  */
62
- async decryptBuffer(buffer, key, meta) {
79
+ async decryptBuffer(buffer, key, meta, aad) { // eslint-disable-line max-params
63
80
  this._validateKey(key);
64
- const nonce = Buffer.from(meta.nonce, 'base64');
65
- const tag = Buffer.from(meta.tag, 'base64');
66
- const decipher = createDecipheriv('aes-256-gcm', key, nonce);
81
+ const { nonce, tag } = validateAesGcmMeta(meta);
82
+ const decipher = createDecipheriv(AES_GCM_ALGORITHM, key, nonce, {
83
+ authTagLength: AES_GCM_TAG_BYTES,
84
+ });
67
85
  decipher.setAuthTag(tag);
86
+ if (aad) {
87
+ decipher.setAAD(aad);
88
+ }
68
89
  return Buffer.concat([decipher.update(buffer), decipher.final()]);
69
90
  }
70
91
 
71
92
  /**
72
93
  * @override
73
94
  * @param {Buffer|Uint8Array} key - 32-byte encryption key.
95
+ * @param {Buffer|Uint8Array} [aad] - Optional additional authenticated data (AAD).
74
96
  * @returns {{ encrypt: (source: AsyncIterable<Buffer>) => AsyncIterable<Buffer>, finalize: () => import('../../ports/CryptoPort.js').EncryptionMeta }}
75
97
  */
76
- createEncryptionStream(key) {
98
+ createEncryptionStream(key, aad) {
77
99
  this._validateKey(key);
78
100
  const nonce = this.randomBytes(12);
79
101
  const cipher = createCipheriv('aes-256-gcm', key, nonce);
102
+ if (aad) {
103
+ cipher.setAAD(aad);
104
+ }
80
105
  let streamFinalized = false;
81
106
 
82
107
  /** @param {AsyncIterable<Buffer>} source */
@@ -98,7 +123,7 @@ export default class BunCryptoAdapter extends CryptoPort {
98
123
  if (!streamFinalized) {
99
124
  throw new CasError(
100
125
  'Cannot finalize before the encrypt stream is fully consumed',
101
- 'STREAM_NOT_CONSUMED',
126
+ ErrorCodes.STREAM_NOT_CONSUMED,
102
127
  );
103
128
  }
104
129
  const tag = cipher.getAuthTag();
@@ -108,6 +133,46 @@ export default class BunCryptoAdapter extends CryptoPort {
108
133
  return { encrypt, finalize };
109
134
  }
110
135
 
136
+ /**
137
+ * @override
138
+ * @param {Buffer|Uint8Array} key - 32-byte encryption key.
139
+ * @param {import('../../ports/CryptoPort.js').EncryptionMeta} meta - Encryption metadata.
140
+ * @param {Buffer|Uint8Array} [aad] - Optional additional authenticated data (AAD).
141
+ * @returns {{ decrypt: (source: AsyncIterable<Buffer>) => AsyncIterable<Buffer> }}
142
+ */
143
+ createDecryptionStream(key, meta, aad) {
144
+ this._validateKey(key);
145
+ const { nonce, tag } = validateAesGcmMeta(meta);
146
+
147
+ return {
148
+ decrypt: async function* (source) {
149
+ try {
150
+ const decipher = createDecipheriv(AES_GCM_ALGORITHM, key, nonce, {
151
+ authTagLength: AES_GCM_TAG_BYTES,
152
+ });
153
+ decipher.setAuthTag(tag);
154
+ if (aad) {
155
+ decipher.setAAD(aad);
156
+ }
157
+
158
+ for await (const chunk of source) {
159
+ const decrypted = decipher.update(chunk);
160
+ if (decrypted.length > 0) {
161
+ yield decrypted;
162
+ }
163
+ }
164
+
165
+ const final = decipher.final();
166
+ if (final.length > 0) {
167
+ yield final;
168
+ }
169
+ } catch (err) {
170
+ throw wrapDecryptError(err);
171
+ }
172
+ },
173
+ };
174
+ }
175
+
111
176
  /**
112
177
  * @override
113
178
  * @param {string} passphrase - The passphrase.
@@ -124,6 +189,57 @@ export default class BunCryptoAdapter extends CryptoPort {
124
189
  N: cost,
125
190
  r: blockSize,
126
191
  p: parallelization,
192
+ maxmem: scryptMaxmem({ cost, blockSize, parallelization, keyLength }),
127
193
  });
128
194
  }
195
+
196
+ /**
197
+ * @override
198
+ * @param {Buffer|Uint8Array} buffer - Plaintext to encrypt.
199
+ * @param {Buffer|Uint8Array} key - 32-byte encryption key.
200
+ * @param {Buffer|Uint8Array} nonce - 12-byte nonce (IV).
201
+ * @returns {{ buf: Buffer, tag: Buffer }}
202
+ */
203
+ encryptBufferWithNonce(buffer, key, nonce) {
204
+ this._validateKey(key);
205
+ if (nonce.length !== 12) {
206
+ throw new CasError('Nonce must be 12 bytes', ErrorCodes.INVALID_NONCE_LENGTH, { actual: nonce.length });
207
+ }
208
+ const cipher = createCipheriv('aes-256-gcm', key, nonce);
209
+ const encrypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
210
+ const tag = cipher.getAuthTag();
211
+ return { buf: encrypted, tag };
212
+ }
213
+
214
+ /**
215
+ * @override
216
+ * @param {Buffer|Uint8Array} buffer - Ciphertext to decrypt.
217
+ * @param {Buffer|Uint8Array} key - 32-byte encryption key.
218
+ * @param {Buffer|Uint8Array} nonce - 12-byte nonce (IV).
219
+ * @param {Buffer|Uint8Array} tag - 16-byte GCM authentication tag.
220
+ * @returns {Buffer}
221
+ */
222
+ decryptBufferWithNonceTag(buffer, key, nonce, tag) { // eslint-disable-line max-params
223
+ this._validateKey(key);
224
+ if (nonce.length !== 12) {
225
+ throw new CasError('Nonce must be 12 bytes', ErrorCodes.INVALID_NONCE_LENGTH, { actual: nonce.length });
226
+ }
227
+ if (tag.length !== 16) {
228
+ throw new CasError('Tag must be 16 bytes', ErrorCodes.INVALID_TAG_LENGTH, { actual: tag.length });
229
+ }
230
+ try {
231
+ const decipher = createDecipheriv(AES_GCM_ALGORITHM, key, nonce, {
232
+ authTagLength: AES_GCM_TAG_BYTES,
233
+ });
234
+ decipher.setAuthTag(tag);
235
+ return Buffer.concat([decipher.update(buffer), decipher.final()]);
236
+ } catch (err) {
237
+ throw wrapDecryptError(err);
238
+ }
239
+ }
240
+
241
+ /** @override */
242
+ hmacSha256(key, data) {
243
+ return createHmac('sha256', key).update(data).digest();
244
+ }
129
245
  }
@@ -1,28 +1,50 @@
1
1
  /**
2
2
  * @fileoverview File I/O helpers for storing and restoring files via CasService.
3
+ *
4
+ * @typedef {import('../../domain/services/CasService.js').default} CasService
5
+ * @typedef {import('../../domain/value-objects/Manifest.js').default} Manifest
6
+ * @typedef {import('../../domain/value-objects/Manifest.js').EncryptionMeta} EncryptionMeta
3
7
  */
4
8
  import { createReadStream, createWriteStream } from 'node:fs';
9
+ import { mkdtemp, realpath, rename, rm } from 'node:fs/promises';
5
10
  import path from 'node:path';
6
11
  import { Readable, Transform } from 'node:stream';
7
12
  import { pipeline } from 'node:stream/promises';
13
+ import CasError from '../../domain/errors/CasError.js';
14
+ import { ErrorCodes } from '../../domain/errors/index.js';
15
+
16
+ const FILE_NOT_FOUND_CODE = 'ENOENT';
8
17
 
9
18
  /**
10
19
  * Reads a file from disk and stores it in Git as chunked blobs via
11
- * the given {@link import('../../domain/services/CasService.js').default CasService}.
20
+ * the given {@link CasService}.
12
21
  *
13
- * @param {import('../../domain/services/CasService.js').default} service - Initialized CasService.
22
+ * @param {CasService} service - Initialized CasService.
14
23
  * @param {Object} options
15
24
  * @param {string} options.filePath - Absolute or relative path to the file.
16
25
  * @param {string} options.slug - Logical identifier for the stored asset.
17
26
  * @param {string} [options.filename] - Override filename (defaults to basename of filePath).
18
- * @param {Buffer} [options.encryptionKey] - 32-byte key for AES-256-GCM encryption.
27
+ * @param {Uint8Array} [options.encryptionKey] - 32-byte key for AES-256-GCM encryption.
19
28
  * @param {string} [options.passphrase] - Derive encryption key from passphrase.
29
+ * @param {{ scheme?: 'whole'|'framed'|'convergent', frameBytes?: number, convergent?: boolean }} [options.encryption] - Explicit encryption scheme selection.
20
30
  * @param {Object} [options.kdfOptions] - KDF options when using passphrase.
21
31
  * @param {{ algorithm: 'gzip' }} [options.compression] - Enable compression.
22
- * @param {Array<{label: string, key: Buffer}>} [options.recipients] - Envelope recipients.
23
- * @returns {Promise<import('../../domain/value-objects/Manifest.js').default>} The resulting manifest.
32
+ * @param {Array<{label: string, key: Uint8Array}>} [options.recipients] - Envelope recipients.
33
+ * @param {number} [options.merkleThreshold] - Per-operation chunk count threshold for Merkle manifests.
34
+ * @returns {Promise<Manifest>} The resulting manifest.
24
35
  */
25
- export async function storeFile(service, { filePath, slug, filename, encryptionKey, passphrase, kdfOptions, compression, recipients }) {
36
+ export async function storeFile(service, {
37
+ filePath,
38
+ slug,
39
+ filename,
40
+ encryptionKey,
41
+ passphrase,
42
+ encryption,
43
+ kdfOptions,
44
+ compression,
45
+ recipients,
46
+ merkleThreshold,
47
+ }) {
26
48
  const source = createReadStream(filePath);
27
49
  return await service.store({
28
50
  source,
@@ -30,28 +52,48 @@ export async function storeFile(service, { filePath, slug, filename, encryptionK
30
52
  filename: filename || path.basename(filePath),
31
53
  encryptionKey,
32
54
  passphrase,
55
+ encryption,
33
56
  kdfOptions,
34
57
  compression,
35
58
  recipients,
59
+ merkleThreshold,
36
60
  });
37
61
  }
38
62
 
39
63
  /**
40
64
  * Restores a file from its manifest and writes it to disk via the given
41
- * {@link import('../../domain/services/CasService.js').default CasService}.
65
+ * {@link CasService}.
42
66
  *
43
- * @param {import('../../domain/services/CasService.js').default} service - Initialized CasService.
67
+ * @param {CasService} service - Initialized CasService.
44
68
  * @param {Object} options
45
- * @param {import('../../domain/value-objects/Manifest.js').default} options.manifest - The file manifest.
46
- * @param {Buffer} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
69
+ * @param {Manifest} options.manifest - The file manifest.
70
+ * @param {Uint8Array} [options.encryptionKey] - 32-byte key, required if manifest is encrypted.
47
71
  * @param {string} [options.passphrase] - Passphrase for KDF-based decryption.
48
72
  * @param {string} options.outputPath - Destination file path.
73
+ * @param {string} options.baseDirectory - The permitted base directory for restoration (e.g. repo root).
49
74
  * @returns {Promise<{ bytesWritten: number }>}
50
75
  */
51
- export async function restoreFile(service, { manifest, encryptionKey, passphrase, outputPath }) {
52
- const iterable = service.restoreStream({ manifest, encryptionKey, passphrase });
76
+ export async function restoreFile(service, { manifest, encryptionKey, passphrase, outputPath, baseDirectory }) {
77
+ if (!baseDirectory) {
78
+ throw new CasError('baseDirectory is required for safe restoration', ErrorCodes.INVALID_OPTIONS);
79
+ }
80
+
81
+ const safeOutputPath = await resolveSafeRestorePath({ baseDirectory, outputPath });
82
+
83
+ const plan = await service.createFileRestorePlan({ manifest, encryptionKey, passphrase });
84
+
85
+ if (plan.mode === 'bounded-file') {
86
+ return await restoreBufferedFile(service, {
87
+ manifest,
88
+ outputPath: safeOutputPath,
89
+ source: plan.source,
90
+ encryptionMeta: plan.encryptionMeta,
91
+ });
92
+ }
93
+
94
+ const iterable = plan.source;
53
95
  const readable = Readable.from(iterable);
54
- const writable = createWriteStream(outputPath);
96
+ const writable = createWriteStream(safeOutputPath);
55
97
  let bytesWritten = 0;
56
98
  const counter = new Transform({
57
99
  transform(chunk, _encoding, cb) {
@@ -62,3 +104,126 @@ export async function restoreFile(service, { manifest, encryptionKey, passphrase
62
104
  await pipeline(readable, counter, writable);
63
105
  return { bytesWritten };
64
106
  }
107
+
108
+ /**
109
+ * @param {{ baseDirectory: string, outputPath: string }} options
110
+ * @returns {Promise<string>}
111
+ */
112
+ async function resolveSafeRestorePath({ baseDirectory, outputPath }) {
113
+ const resolvedBase = path.resolve(baseDirectory);
114
+ const resolvedPath = path.resolve(resolvedBase, outputPath);
115
+ const canonicalBase = await realpath(resolvedBase);
116
+ const canonicalPath = await canonicalizeTargetPath(resolvedPath);
117
+
118
+ if (!isInsideBaseDirectory(canonicalPath, canonicalBase)) {
119
+ throw new CasError(
120
+ `Restoration path "${outputPath}" escapes base directory "${baseDirectory}"`,
121
+ ErrorCodes.SECURITY_BOUNDARY_VIOLATION,
122
+ { outputPath, baseDirectory },
123
+ );
124
+ }
125
+ return canonicalPath;
126
+ }
127
+
128
+ /**
129
+ * Resolves symlinks in the existing path prefix while allowing the leaf path
130
+ * not to exist yet.
131
+ *
132
+ * @param {string} targetPath
133
+ * @returns {Promise<string>}
134
+ */
135
+ async function canonicalizeTargetPath(targetPath) {
136
+ const missingParts = [];
137
+ let current = targetPath;
138
+ while (true) {
139
+ try {
140
+ return path.join(await realpath(current), ...missingParts.reverse());
141
+ } catch (err) {
142
+ if (!isNotFoundError(err)) {
143
+ throw err;
144
+ }
145
+ const parent = path.dirname(current);
146
+ if (parent === current) {
147
+ throw err;
148
+ }
149
+ missingParts.push(path.basename(current));
150
+ current = parent;
151
+ }
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Restores buffered modes through a temp-file path so whole-object auth can
157
+ * stay intact without publishing partial output.
158
+ *
159
+ * @param {CasService} service
160
+ * @param {{ manifest: Manifest, outputPath: string, source: AsyncIterable<Uint8Array>, encryptionMeta?: EncryptionMeta }} options
161
+ * @returns {Promise<{ bytesWritten: number }>}
162
+ */
163
+ async function restoreBufferedFile(service, {
164
+ manifest,
165
+ outputPath,
166
+ source,
167
+ encryptionMeta,
168
+ }) {
169
+ let bytesWritten = 0;
170
+ const outputDir = path.dirname(outputPath);
171
+ const tempDir = await mkdtemp(path.join(outputDir, '.git-cas-restore-'));
172
+ const tempPath = path.join(tempDir, path.basename(outputPath));
173
+
174
+ try {
175
+ const counter = createByteCounter((n) => { bytesWritten += n; });
176
+
177
+ await pipeline(
178
+ Readable.from(source),
179
+ counter,
180
+ createWriteStream(tempPath),
181
+ );
182
+
183
+ await rename(tempPath, outputPath);
184
+ service.observability.metric('file', {
185
+ action: 'restored',
186
+ slug: manifest.slug,
187
+ size: bytesWritten,
188
+ chunkCount: manifest.chunks.length,
189
+ });
190
+ return { bytesWritten };
191
+ } catch (err) {
192
+ if (encryptionMeta && err instanceof CasError && err.code === ErrorCodes.INTEGRITY_ERROR) {
193
+ service.observability.metric('error', { action: 'decryption_failed', slug: manifest.slug });
194
+ }
195
+ throw err;
196
+ } finally {
197
+ await rm(tempDir, { recursive: true, force: true });
198
+ }
199
+ }
200
+
201
+ /**
202
+ * @param {string} resolvedPath
203
+ * @param {string} resolvedBase
204
+ * @returns {boolean}
205
+ */
206
+ function isInsideBaseDirectory(resolvedPath, resolvedBase) {
207
+ const relativePath = path.relative(resolvedBase, resolvedPath);
208
+ return (
209
+ relativePath === '' ||
210
+ (!relativePath.startsWith('..') && !path.isAbsolute(relativePath))
211
+ );
212
+ }
213
+
214
+ /**
215
+ * @param {unknown} err
216
+ * @returns {boolean}
217
+ */
218
+ function isNotFoundError(err) {
219
+ return Boolean(err && typeof err === 'object' && err.code === FILE_NOT_FOUND_CODE);
220
+ }
221
+
222
+ function createByteCounter(onChunk) {
223
+ return new Transform({
224
+ transform(chunk, _encoding, cb) {
225
+ onChunk(chunk.length);
226
+ cb(null, chunk);
227
+ },
228
+ });
229
+ }