@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,7 +1,19 @@
1
- import { createHash, createCipheriv, createDecipheriv, randomBytes, pbkdf2, scrypt } from 'node:crypto';
1
+ import { createHash, createHmac, createCipheriv, createDecipheriv, randomBytes, pbkdf2, scrypt } from 'node:crypto';
2
2
  import { promisify } from 'node:util';
3
3
  import CryptoPort from '../../ports/CryptoPort.js';
4
4
  import CasError from '../../domain/errors/CasError.js';
5
+ import scryptMaxmem from '../../domain/helpers/scryptMaxmem.js';
6
+ import validateAesGcmMeta, { AES_GCM_ALGORITHM, AES_GCM_TAG_BYTES } from '../../helpers/aesGcmMeta.js';
7
+ import { ErrorCodes } from '../../domain/errors/index.js';
8
+
9
+ function wrapDecryptError(err) {
10
+ if (err instanceof CasError) {
11
+ return err;
12
+ }
13
+ return new CasError('Decryption failed: Integrity check error', ErrorCodes.INTEGRITY_ERROR, {
14
+ originalError: err,
15
+ });
16
+ }
5
17
 
6
18
  /**
7
19
  * Node.js implementation of CryptoPort using node:crypto.
@@ -29,12 +41,16 @@ export default class NodeCryptoAdapter extends CryptoPort {
29
41
  * @override
30
42
  * @param {Buffer|Uint8Array} buffer - Plaintext to encrypt.
31
43
  * @param {Buffer|Uint8Array} key - 32-byte encryption key.
44
+ * @param {Buffer|Uint8Array} [aad] - Optional additional authenticated data (AAD).
32
45
  * @returns {Promise<{ buf: Buffer, meta: import('../../ports/CryptoPort.js').EncryptionMeta }>}
33
46
  */
34
- async encryptBuffer(buffer, key) {
47
+ async encryptBuffer(buffer, key, aad) {
35
48
  this._validateKey(key);
36
49
  const nonce = randomBytes(12);
37
50
  const cipher = createCipheriv('aes-256-gcm', key, nonce);
51
+ if (aad) {
52
+ cipher.setAAD(aad);
53
+ }
38
54
  const enc = Buffer.concat([cipher.update(buffer), cipher.final()]);
39
55
  const tag = cipher.getAuthTag();
40
56
  return {
@@ -48,26 +64,39 @@ export default class NodeCryptoAdapter extends CryptoPort {
48
64
  * @param {Buffer|Uint8Array} buffer - Ciphertext to decrypt.
49
65
  * @param {Buffer|Uint8Array} key - 32-byte encryption key.
50
66
  * @param {import('../../ports/CryptoPort.js').EncryptionMeta} meta - Encryption metadata.
67
+ * @param {Buffer|Uint8Array} [aad] - Optional additional authenticated data (AAD).
51
68
  * @returns {Buffer}
52
69
  */
53
- decryptBuffer(buffer, key, meta) {
70
+ decryptBuffer(buffer, key, meta, aad) { // eslint-disable-line max-params
54
71
  this._validateKey(key);
55
- const nonce = Buffer.from(meta.nonce, 'base64');
56
- const tag = Buffer.from(meta.tag, 'base64');
57
- const decipher = createDecipheriv('aes-256-gcm', key, nonce);
58
- decipher.setAuthTag(tag);
59
- return Buffer.concat([decipher.update(buffer), decipher.final()]);
72
+ const { nonce, tag } = validateAesGcmMeta(meta);
73
+ try {
74
+ const decipher = createDecipheriv(AES_GCM_ALGORITHM, key, nonce, {
75
+ authTagLength: AES_GCM_TAG_BYTES,
76
+ });
77
+ decipher.setAuthTag(tag);
78
+ if (aad) {
79
+ decipher.setAAD(aad);
80
+ }
81
+ return Buffer.concat([decipher.update(buffer), decipher.final()]);
82
+ } catch (err) {
83
+ throw wrapDecryptError(err);
84
+ }
60
85
  }
61
86
 
62
87
  /**
63
88
  * @override
64
89
  * @param {Buffer|Uint8Array} key - 32-byte encryption key.
90
+ * @param {Buffer|Uint8Array} [aad] - Optional additional authenticated data (AAD).
65
91
  * @returns {{ encrypt: (source: AsyncIterable<Buffer>) => AsyncIterable<Buffer>, finalize: () => import('../../ports/CryptoPort.js').EncryptionMeta }}
66
92
  */
67
- createEncryptionStream(key) {
93
+ createEncryptionStream(key, aad) {
68
94
  this._validateKey(key);
69
95
  const nonce = randomBytes(12);
70
96
  const cipher = createCipheriv('aes-256-gcm', key, nonce);
97
+ if (aad) {
98
+ cipher.setAAD(aad);
99
+ }
71
100
  let streamFinalized = false;
72
101
 
73
102
  /** @param {AsyncIterable<Buffer>} source */
@@ -89,7 +118,7 @@ export default class NodeCryptoAdapter extends CryptoPort {
89
118
  if (!streamFinalized) {
90
119
  throw new CasError(
91
120
  'Cannot finalize before the encrypt stream is fully consumed',
92
- 'STREAM_NOT_CONSUMED',
121
+ ErrorCodes.STREAM_NOT_CONSUMED,
93
122
  );
94
123
  }
95
124
  const tag = cipher.getAuthTag();
@@ -99,6 +128,46 @@ export default class NodeCryptoAdapter extends CryptoPort {
99
128
  return { encrypt, finalize };
100
129
  }
101
130
 
131
+ /**
132
+ * @override
133
+ * @param {Buffer|Uint8Array} key - 32-byte encryption key.
134
+ * @param {import('../../ports/CryptoPort.js').EncryptionMeta} meta - Encryption metadata.
135
+ * @param {Buffer|Uint8Array} [aad] - Optional additional authenticated data (AAD).
136
+ * @returns {{ decrypt: (source: AsyncIterable<Buffer>) => AsyncIterable<Buffer> }}
137
+ */
138
+ createDecryptionStream(key, meta, aad) {
139
+ this._validateKey(key);
140
+ const { nonce, tag } = validateAesGcmMeta(meta);
141
+
142
+ return {
143
+ decrypt: async function* (source) {
144
+ try {
145
+ const decipher = createDecipheriv(AES_GCM_ALGORITHM, key, nonce, {
146
+ authTagLength: AES_GCM_TAG_BYTES,
147
+ });
148
+ decipher.setAuthTag(tag);
149
+ if (aad) {
150
+ decipher.setAAD(aad);
151
+ }
152
+
153
+ for await (const chunk of source) {
154
+ const decrypted = decipher.update(chunk);
155
+ if (decrypted.length > 0) {
156
+ yield decrypted;
157
+ }
158
+ }
159
+
160
+ const final = decipher.final();
161
+ if (final.length > 0) {
162
+ yield final;
163
+ }
164
+ } catch (err) {
165
+ throw wrapDecryptError(err);
166
+ }
167
+ },
168
+ };
169
+ }
170
+
102
171
  /**
103
172
  * @override
104
173
  * @param {string} passphrase - The passphrase.
@@ -115,6 +184,57 @@ export default class NodeCryptoAdapter extends CryptoPort {
115
184
  N: cost,
116
185
  r: blockSize,
117
186
  p: parallelization,
187
+ maxmem: scryptMaxmem({ cost, blockSize, parallelization, keyLength }),
118
188
  });
119
189
  }
190
+
191
+ /**
192
+ * @override
193
+ * @param {Buffer|Uint8Array} buffer - Plaintext to encrypt.
194
+ * @param {Buffer|Uint8Array} key - 32-byte encryption key.
195
+ * @param {Buffer|Uint8Array} nonce - 12-byte nonce (IV).
196
+ * @returns {{ buf: Buffer, tag: Buffer }}
197
+ */
198
+ encryptBufferWithNonce(buffer, key, nonce) {
199
+ this._validateKey(key);
200
+ if (nonce.length !== 12) {
201
+ throw new CasError('Nonce must be 12 bytes', ErrorCodes.INVALID_NONCE_LENGTH, { actual: nonce.length });
202
+ }
203
+ const cipher = createCipheriv('aes-256-gcm', key, nonce);
204
+ const encrypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
205
+ const tag = cipher.getAuthTag();
206
+ return { buf: encrypted, tag };
207
+ }
208
+
209
+ /**
210
+ * @override
211
+ * @param {Buffer|Uint8Array} buffer - Ciphertext to decrypt.
212
+ * @param {Buffer|Uint8Array} key - 32-byte encryption key.
213
+ * @param {Buffer|Uint8Array} nonce - 12-byte nonce (IV).
214
+ * @param {Buffer|Uint8Array} tag - 16-byte GCM authentication tag.
215
+ * @returns {Buffer}
216
+ */
217
+ decryptBufferWithNonceTag(buffer, key, nonce, tag) { // eslint-disable-line max-params
218
+ this._validateKey(key);
219
+ if (nonce.length !== 12) {
220
+ throw new CasError('Nonce must be 12 bytes', ErrorCodes.INVALID_NONCE_LENGTH, { actual: nonce.length });
221
+ }
222
+ if (tag.length !== 16) {
223
+ throw new CasError('Tag must be 16 bytes', ErrorCodes.INVALID_TAG_LENGTH, { actual: tag.length });
224
+ }
225
+ try {
226
+ const decipher = createDecipheriv(AES_GCM_ALGORITHM, key, nonce, {
227
+ authTagLength: AES_GCM_TAG_BYTES,
228
+ });
229
+ decipher.setAuthTag(tag);
230
+ return Buffer.concat([decipher.update(buffer), decipher.final()]);
231
+ } catch (err) {
232
+ throw wrapDecryptError(err);
233
+ }
234
+ }
235
+
236
+ /** @override */
237
+ hmacSha256(key, data) {
238
+ return createHmac('sha256', key).update(data).digest();
239
+ }
120
240
  }
@@ -1,5 +1,9 @@
1
1
  import CryptoPort from '../../ports/CryptoPort.js';
2
2
  import CasError from '../../domain/errors/CasError.js';
3
+ import validateAesGcmMeta from '../../helpers/aesGcmMeta.js';
4
+ import { concatBytes } from '../../domain/bytes/ByteLayout.js';
5
+ import { encodeBase64 } from '../../domain/encoding/base64.js';
6
+ import { ErrorCodes } from '../../domain/errors/index.js';
3
7
 
4
8
  /**
5
9
  * {@link CryptoPort} implementation using the Web Crypto API.
@@ -9,28 +13,44 @@ import CasError from '../../domain/errors/CasError.js';
9
13
  * AES-GCM is a one-shot API (the GCM tag is computed over the entire plaintext).
10
14
  */
11
15
  export default class WebCryptoAdapter extends CryptoPort {
16
+ /** @override */
17
+ supports(capability) {
18
+ if (capability === 'scrypt') { return false; }
19
+ return super.supports(capability);
20
+ }
21
+
12
22
  /** @type {number} */
13
23
  #maxEncryptionBufferSize;
24
+ /** @type {number} */
25
+ #maxDecryptionBufferSize;
14
26
 
15
27
  /**
16
28
  * @param {Object} [options]
17
29
  * @param {number} [options.maxEncryptionBufferSize=536870912] - Max bytes to buffer during streaming encryption (default 512 MiB).
30
+ * @param {number} [options.maxDecryptionBufferSize=536870912] - Max bytes to buffer during streaming decryption (default 512 MiB).
18
31
  */
19
- constructor({ maxEncryptionBufferSize = 512 * 1024 * 1024 } = {}) {
32
+ constructor({
33
+ maxEncryptionBufferSize = 512 * 1024 * 1024,
34
+ maxDecryptionBufferSize = 512 * 1024 * 1024,
35
+ } = {}) {
20
36
  super();
21
37
  if (!Number.isFinite(maxEncryptionBufferSize) || maxEncryptionBufferSize <= 0) {
22
38
  throw new RangeError('maxEncryptionBufferSize must be a finite positive number');
23
39
  }
40
+ if (!Number.isFinite(maxDecryptionBufferSize) || maxDecryptionBufferSize <= 0) {
41
+ throw new RangeError('maxDecryptionBufferSize must be a finite positive number');
42
+ }
24
43
  this.#maxEncryptionBufferSize = maxEncryptionBufferSize;
44
+ this.#maxDecryptionBufferSize = maxDecryptionBufferSize;
25
45
  }
26
46
 
27
47
  /**
28
48
  * @override
29
- * @param {Buffer|Uint8Array} buf - Data to hash.
49
+ * @param {Uint8Array} buf - Data to hash.
30
50
  * @returns {Promise<string>} 64-char hex digest.
31
51
  */
32
52
  async sha256(buf) {
33
- // @ts-ignore -- Buffer satisfies BufferSource at runtime; TS strictness mismatch
53
+ // @ts-ignore -- Uint8Array satisfies BufferSource at runtime; TS strictness mismatch
34
54
  const hashBuffer = await globalThis.crypto.subtle.digest('SHA-256', buf);
35
55
  return Array.from(new Uint8Array(hashBuffer))
36
56
  .map(b => b.toString(16).padStart(2, '0'))
@@ -40,31 +60,34 @@ export default class WebCryptoAdapter extends CryptoPort {
40
60
  /**
41
61
  * @override
42
62
  * @param {number} n - Number of random bytes.
43
- * @returns {Buffer|Uint8Array}
63
+ * @returns {Uint8Array}
44
64
  */
45
65
  randomBytes(n) {
46
- const uint8 = globalThis.crypto.getRandomValues(new Uint8Array(n));
47
- if (globalThis.Buffer) {
48
- return Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength);
49
- }
50
- return uint8;
66
+ return globalThis.crypto.getRandomValues(new Uint8Array(n));
51
67
  }
52
68
 
53
69
  /**
54
70
  * @override
55
- * @param {Buffer|Uint8Array} buffer - Plaintext to encrypt.
56
- * @param {Buffer|Uint8Array} key - 32-byte encryption key.
57
- * @returns {Promise<{ buf: Buffer, meta: import('../../ports/CryptoPort.js').EncryptionMeta }>}
71
+ * @param {Uint8Array} buffer - Plaintext to encrypt.
72
+ * @param {Uint8Array} key - 32-byte encryption key.
73
+ * @param {Uint8Array} [aad] - Optional additional authenticated data (AAD).
74
+ * @returns {Promise<{ buf: Uint8Array, meta: import('../../ports/CryptoPort.js').EncryptionMeta }>}
58
75
  */
59
- async encryptBuffer(buffer, key) {
76
+ async encryptBuffer(buffer, key, aad) {
60
77
  this._validateKey(key);
61
78
  const nonce = this.randomBytes(12);
62
79
  const cryptoKey = await this.#importKey(key);
63
80
 
81
+ /** @type {AesGcmParams} */
82
+ const algoParams = { name: 'AES-GCM', iv: /** @type {Uint8Array} */ (nonce) };
83
+ if (aad) {
84
+ algoParams.additionalData = aad;
85
+ }
86
+
64
87
  // AES-GCM in Web Crypto includes the tag at the end of the ciphertext
65
88
  const encrypted = await globalThis.crypto.subtle.encrypt(
66
89
  // @ts-ignore -- Uint8Array satisfies BufferSource at runtime
67
- { name: 'AES-GCM', iv: /** @type {Uint8Array} */ (nonce) },
90
+ algoParams,
68
91
  cryptoKey,
69
92
  buffer
70
93
  );
@@ -75,22 +98,22 @@ export default class WebCryptoAdapter extends CryptoPort {
75
98
  const tag = fullBuffer.slice(-tagLength);
76
99
 
77
100
  return {
78
- buf: Buffer.from(ciphertext),
79
- meta: this._buildMeta(this.#toBase64(nonce), this.#toBase64(tag)),
101
+ buf: ciphertext,
102
+ meta: this._buildMeta(encodeBase64(nonce), encodeBase64(tag)),
80
103
  };
81
104
  }
82
105
 
83
106
  /**
84
107
  * @override
85
- * @param {Buffer|Uint8Array} buffer - Ciphertext to decrypt.
86
- * @param {Buffer|Uint8Array} key - 32-byte encryption key.
108
+ * @param {Uint8Array} buffer - Ciphertext to decrypt.
109
+ * @param {Uint8Array} key - 32-byte encryption key.
87
110
  * @param {import('../../ports/CryptoPort.js').EncryptionMeta} meta - Encryption metadata.
88
- * @returns {Promise<Buffer>}
111
+ * @param {Uint8Array} [aad] - Optional additional authenticated data (AAD).
112
+ * @returns {Promise<Uint8Array>}
89
113
  */
90
- async decryptBuffer(buffer, key, meta) {
114
+ async decryptBuffer(buffer, key, meta, aad) { // eslint-disable-line max-params
91
115
  this._validateKey(key);
92
- const nonce = this.#fromBase64(meta.nonce);
93
- const tag = this.#fromBase64(meta.tag);
116
+ const { nonce, tag } = validateAesGcmMeta(meta);
94
117
  const cryptoKey = await this.#importKey(key);
95
118
 
96
119
  // Reconstruct Web Crypto format (ciphertext + tag)
@@ -98,43 +121,84 @@ export default class WebCryptoAdapter extends CryptoPort {
98
121
  combined.set(new Uint8Array(buffer));
99
122
  combined.set(tag, buffer.length);
100
123
 
124
+ /** @type {AesGcmParams} */
125
+ const algoParams = { name: 'AES-GCM', iv: /** @type {Uint8Array} */ (nonce) };
126
+ if (aad) {
127
+ algoParams.additionalData = aad;
128
+ }
129
+
101
130
  try {
102
131
  const decrypted = await globalThis.crypto.subtle.decrypt(
103
132
  // @ts-ignore -- Uint8Array satisfies BufferSource at runtime
104
- { name: 'AES-GCM', iv: /** @type {Uint8Array} */ (nonce) },
133
+ algoParams,
105
134
  cryptoKey,
106
135
  combined
107
136
  );
108
- return Buffer.from(decrypted);
137
+ return new Uint8Array(decrypted);
109
138
  } catch (err) {
110
- throw new CasError('Decryption failed', 'INTEGRITY_ERROR', { originalError: err });
139
+ throw new CasError('Decryption failed', ErrorCodes.INTEGRITY_ERROR, { originalError: err });
111
140
  }
112
141
  }
113
142
 
114
143
  /**
115
144
  * @override
116
- * @param {Buffer|Uint8Array} key - 32-byte encryption key.
117
- * @returns {{ encrypt: (source: AsyncIterable<Buffer>) => AsyncIterable<Buffer>, finalize: () => import('../../ports/CryptoPort.js').EncryptionMeta }}
145
+ * @param {Uint8Array} key - 32-byte encryption key.
146
+ * @param {Uint8Array} [aad] - Optional additional authenticated data (AAD).
147
+ * @returns {{ encrypt: (source: AsyncIterable<Uint8Array>) => AsyncIterable<Uint8Array>, finalize: () => import('../../ports/CryptoPort.js').EncryptionMeta }}
118
148
  */
119
- createEncryptionStream(key) {
149
+ createEncryptionStream(key, aad) {
120
150
  this._validateKey(key);
121
151
  const nonce = this.randomBytes(12);
122
152
  const cryptoKeyPromise = this.#importKey(key);
123
153
  const maxBuf = this.#maxEncryptionBufferSize;
124
154
  const state = { /** @type {Uint8Array|null} */ tag: null, consumed: false };
125
155
 
126
- const encrypt = WebCryptoAdapter.#makeEncryptGenerator({ cryptoKeyPromise, nonce, maxBuf, state });
156
+ const encrypt = WebCryptoAdapter.#makeEncryptGenerator({ cryptoKeyPromise, nonce, maxBuf, state, aad });
127
157
 
128
158
  const finalize = () => {
129
159
  if (!state.consumed) {
130
- throw new CasError('Cannot finalize before the encrypt stream is fully consumed', 'STREAM_NOT_CONSUMED');
160
+ throw new CasError('Cannot finalize before the encrypt stream is fully consumed', ErrorCodes.STREAM_NOT_CONSUMED);
131
161
  }
132
- return this._buildMeta(this.#toBase64(nonce), this.#toBase64(/** @type {Uint8Array} */ (state.tag)));
162
+ return this._buildMeta(encodeBase64(nonce), encodeBase64(/** @type {Uint8Array} */ (state.tag)));
133
163
  };
134
164
 
135
165
  return { encrypt, finalize };
136
166
  }
137
167
 
168
+ /**
169
+ * @override
170
+ * @param {Uint8Array} key - 32-byte encryption key.
171
+ * @param {import('../../ports/CryptoPort.js').EncryptionMeta} meta - Encryption metadata.
172
+ * @param {Uint8Array} [aad] - Optional additional authenticated data (AAD).
173
+ * @returns {{ decrypt: (source: AsyncIterable<Uint8Array>) => AsyncIterable<Uint8Array> }}
174
+ */
175
+ createDecryptionStream(key, meta, aad) {
176
+ this._validateKey(key);
177
+ validateAesGcmMeta(meta);
178
+ const maxBuf = this.#maxDecryptionBufferSize;
179
+
180
+ return {
181
+ decrypt: async function* (source) {
182
+ /** @type {Uint8Array[]} */
183
+ const chunks = [];
184
+ let accumulatedBytes = 0;
185
+ for await (const chunk of source) {
186
+ accumulatedBytes += chunk.length;
187
+ if (accumulatedBytes > maxBuf) {
188
+ throw new CasError(
189
+ `Streaming decryption buffered ${accumulatedBytes} bytes (limit: ${maxBuf}). ` +
190
+ 'Web Crypto AES-GCM decrypt is one-shot. Use Node.js/Bun or framed encryption for large encrypted restores.',
191
+ ErrorCodes.DECRYPTION_BUFFER_EXCEEDED,
192
+ { accumulated: accumulatedBytes, limit: maxBuf },
193
+ );
194
+ }
195
+ chunks.push(chunk);
196
+ }
197
+ yield await this.decryptBuffer(concatBytes(chunks, accumulatedBytes), key, meta, aad);
198
+ }.bind(this),
199
+ };
200
+ }
201
+
138
202
  /**
139
203
  * Builds the encrypt async generator for createEncryptionStream.
140
204
  *
@@ -142,12 +206,12 @@ export default class WebCryptoAdapter extends CryptoPort {
142
206
  * cannot be an arrow function — `this` binding would be lost. The `state`
143
207
  * object bridges mutable data between the generator and `finalize()`.
144
208
  *
145
- * @param {{ cryptoKeyPromise: Promise<CryptoKey>, nonce: Buffer|Uint8Array, maxBuf: number, state: { tag: Uint8Array|null, consumed: boolean } }} ctx
146
- * @returns {(source: AsyncIterable<Buffer>) => AsyncGenerator<Buffer>}
209
+ * @param {{ cryptoKeyPromise: Promise<CryptoKey>, nonce: Uint8Array, maxBuf: number, state: { tag: Uint8Array|null, consumed: boolean }, aad?: Uint8Array }} ctx
210
+ * @returns {(source: AsyncIterable<Uint8Array>) => AsyncGenerator<Uint8Array>}
147
211
  */
148
- static #makeEncryptGenerator({ cryptoKeyPromise, nonce, maxBuf, state }) {
212
+ static #makeEncryptGenerator({ cryptoKeyPromise, nonce, maxBuf, state, aad }) {
149
213
  return async function* (source) {
150
- /** @type {Buffer[]} */
214
+ /** @type {Uint8Array[]} */
151
215
  const chunks = [];
152
216
  let accumulatedBytes = 0;
153
217
  for await (const chunk of source) {
@@ -156,33 +220,38 @@ export default class WebCryptoAdapter extends CryptoPort {
156
220
  throw new CasError(
157
221
  `Streaming encryption buffered ${accumulatedBytes} bytes (limit: ${maxBuf}). ` +
158
222
  'Web Crypto AES-GCM buffers all data. Use Node.js/Bun or store without encryption for large files.',
159
- 'ENCRYPTION_BUFFER_EXCEEDED',
223
+ ErrorCodes.ENCRYPTION_BUFFER_EXCEEDED,
160
224
  { accumulated: accumulatedBytes, limit: maxBuf },
161
225
  );
162
226
  }
163
227
  chunks.push(chunk);
164
228
  }
165
- const buffer = Buffer.concat(chunks);
229
+ const buffer = concatBytes(chunks, accumulatedBytes);
166
230
  const cryptoKey = await cryptoKeyPromise;
231
+ /** @type {AesGcmParams} */
232
+ const algoParams = { name: 'AES-GCM', iv: /** @type {Uint8Array} */ (nonce) };
233
+ if (aad) {
234
+ algoParams.additionalData = aad;
235
+ }
167
236
  const encrypted = await globalThis.crypto.subtle.encrypt(
168
237
  // @ts-ignore -- Uint8Array satisfies BufferSource at runtime
169
- { name: 'AES-GCM', iv: /** @type {Uint8Array} */ (nonce) },
238
+ algoParams,
170
239
  cryptoKey, buffer,
171
240
  );
172
241
  const fullBuffer = new Uint8Array(encrypted);
173
242
  const tagLength = 16;
174
243
  state.tag = fullBuffer.slice(-tagLength);
175
244
  state.consumed = true;
176
- yield Buffer.from(fullBuffer.slice(0, -tagLength));
245
+ yield fullBuffer.slice(0, -tagLength);
177
246
  };
178
247
  }
179
248
 
180
249
  /**
181
250
  * @override
182
251
  * @param {string} passphrase - The passphrase.
183
- * @param {Buffer|Uint8Array} saltBuf - Salt bytes.
252
+ * @param {Uint8Array} saltBuf - Salt bytes.
184
253
  * @param {import('../../ports/CryptoPort.js').DeriveKeyParams} params - KDF parameters.
185
- * @returns {Promise<Buffer>}
254
+ * @returns {Promise<Uint8Array>}
186
255
  */
187
256
  async _doDeriveKey(passphrase, saltBuf, { algorithm, iterations, cost, blockSize, parallelization, keyLength }) {
188
257
  if (algorithm === 'pbkdf2') {
@@ -194,9 +263,9 @@ export default class WebCryptoAdapter extends CryptoPort {
194
263
  /**
195
264
  * Derives a key using PBKDF2 via Web Crypto.
196
265
  * @param {string} passphrase - The passphrase.
197
- * @param {Buffer|Uint8Array} saltBuf - Salt bytes.
266
+ * @param {Uint8Array} saltBuf - Salt bytes.
198
267
  * @param {{ iterations: number, keyLength: number }} params - PBKDF2 parameters.
199
- * @returns {Promise<Buffer>}
268
+ * @returns {Promise<Uint8Array>}
200
269
  */
201
270
  async #derivePbkdf2(passphrase, saltBuf, params) {
202
271
  const enc = new globalThis.TextEncoder();
@@ -208,40 +277,32 @@ export default class WebCryptoAdapter extends CryptoPort {
208
277
  { name: 'PBKDF2', salt: /** @type {Uint8Array} */ (saltBuf), iterations: params.iterations, hash: 'SHA-512' },
209
278
  baseKey, params.keyLength * 8,
210
279
  );
211
- return Buffer.from(bits);
280
+ return new Uint8Array(bits);
212
281
  }
213
282
 
214
283
  /**
215
- * Derives a key using scrypt via Node's crypto module (fallback).
216
- * @param {string} passphrase - The passphrase.
217
- * @param {Buffer|Uint8Array} saltBuf - Salt bytes.
284
+ * Derives a key using scrypt.
285
+ * @param {string} _passphrase - The passphrase.
286
+ * @param {Uint8Array} _saltBuf - Salt bytes.
218
287
  * @param {{ cost: number, blockSize: number, parallelization: number, keyLength: number }} params - scrypt parameters.
219
- * @returns {Promise<Buffer>}
288
+ * @returns {Promise<Uint8Array>}
220
289
  */
221
- async #deriveScrypt(passphrase, saltBuf, params) {
222
- let scryptCb;
223
- let promisifyFn;
224
- try {
225
- ({ scrypt: scryptCb } = await import('node:crypto'));
226
- ({ promisify: promisifyFn } = await import('node:util'));
227
- } catch {
228
- throw new Error('scrypt KDF requires a Node.js-compatible runtime (node:crypto unavailable)');
229
- }
230
- // @ts-ignore -- promisify(scrypt) accepts options as 4th arg at runtime
231
- return promisifyFn(scryptCb)(passphrase, saltBuf, params.keyLength, {
232
- N: params.cost, r: params.blockSize, p: params.parallelization,
233
- });
290
+ async #deriveScrypt(_passphrase, _saltBuf, params) {
291
+ throw new Error(
292
+ `scrypt KDF is unavailable in WebCryptoAdapter ` +
293
+ `(cost=${params.cost}, blockSize=${params.blockSize}, parallelization=${params.parallelization}, keyLength=${params.keyLength})`,
294
+ );
234
295
  }
235
296
 
236
297
  /**
237
298
  * Imports a raw key for use with Web Crypto AES-GCM operations.
238
- * @param {Buffer|Uint8Array} rawKey - 32-byte raw key material.
299
+ * @param {Uint8Array} rawKey - 32-byte raw key material.
239
300
  * @returns {Promise<CryptoKey>}
240
301
  */
241
302
  async #importKey(rawKey) {
242
303
  return globalThis.crypto.subtle.importKey(
243
304
  'raw',
244
- // @ts-ignore -- Buffer/Uint8Array satisfies BufferSource at runtime
305
+ // @ts-ignore -- Uint8Array satisfies BufferSource at runtime
245
306
  /** @type {Uint8Array} */ (rawKey),
246
307
  { name: 'AES-GCM' },
247
308
  false,
@@ -250,26 +311,75 @@ export default class WebCryptoAdapter extends CryptoPort {
250
311
  }
251
312
 
252
313
  /**
253
- * Encodes binary data to base64, using Buffer when available.
254
- * @param {Buffer|Uint8Array} buf - Binary data to encode.
255
- * @returns {string}
314
+ * @override
315
+ * @param {Uint8Array} buffer - Plaintext to encrypt.
316
+ * @param {Uint8Array} key - 32-byte encryption key.
317
+ * @param {Uint8Array} nonce - 12-byte nonce (IV).
318
+ * @returns {Promise<{ buf: Uint8Array, tag: Uint8Array }>}
256
319
  */
257
- #toBase64(buf) {
258
- if (globalThis.Buffer) {
259
- return Buffer.from(buf).toString('base64');
320
+ async encryptBufferWithNonce(buffer, key, nonce) {
321
+ this._validateKey(key);
322
+ if (nonce.length !== 12) {
323
+ throw new CasError('Nonce must be 12 bytes', ErrorCodes.INVALID_NONCE_LENGTH, { actual: nonce.length });
260
324
  }
261
- return globalThis.btoa(String.fromCharCode(...new Uint8Array(buf)));
325
+ const cryptoKey = await this.#importKey(key);
326
+ const encrypted = await globalThis.crypto.subtle.encrypt(
327
+ // @ts-ignore -- Uint8Array satisfies BufferSource at runtime
328
+ { name: 'AES-GCM', iv: /** @type {Uint8Array} */ (nonce) },
329
+ cryptoKey,
330
+ buffer,
331
+ );
332
+ const fullBuffer = new Uint8Array(encrypted);
333
+ const tagLength = 16;
334
+ return {
335
+ buf: fullBuffer.slice(0, -tagLength),
336
+ tag: fullBuffer.slice(-tagLength),
337
+ };
262
338
  }
263
339
 
264
340
  /**
265
- * Decodes a base64 string to binary, using Buffer when available.
266
- * @param {string} str - Base64-encoded string.
267
- * @returns {Buffer|Uint8Array}
341
+ * @override
342
+ * @param {Uint8Array} buffer - Ciphertext to decrypt.
343
+ * @param {Uint8Array} key - 32-byte encryption key.
344
+ * @param {Uint8Array} nonce - 12-byte nonce (IV).
345
+ * @param {Uint8Array} tag - 16-byte GCM authentication tag.
346
+ * @returns {Promise<Uint8Array>}
268
347
  */
269
- #fromBase64(str) {
270
- if (globalThis.Buffer) {
271
- return Buffer.from(str, 'base64');
348
+ async decryptBufferWithNonceTag(buffer, key, nonce, tag) { // eslint-disable-line max-params
349
+ this._validateKey(key);
350
+ if (nonce.length !== 12) {
351
+ throw new CasError('Nonce must be 12 bytes', ErrorCodes.INVALID_NONCE_LENGTH, { actual: nonce.length });
352
+ }
353
+ if (tag.length !== 16) {
354
+ throw new CasError('Tag must be 16 bytes', ErrorCodes.INVALID_TAG_LENGTH, { actual: tag.length });
355
+ }
356
+ const cryptoKey = await this.#importKey(key);
357
+ const combined = new Uint8Array(buffer.length + tag.length);
358
+ combined.set(new Uint8Array(buffer));
359
+ combined.set(new Uint8Array(tag), buffer.length);
360
+ try {
361
+ const decrypted = await globalThis.crypto.subtle.decrypt(
362
+ // @ts-ignore -- Uint8Array satisfies BufferSource at runtime
363
+ { name: 'AES-GCM', iv: /** @type {Uint8Array} */ (nonce) },
364
+ cryptoKey,
365
+ combined,
366
+ );
367
+ return new Uint8Array(decrypted);
368
+ } catch (err) {
369
+ throw new CasError('Decryption failed', ErrorCodes.INTEGRITY_ERROR, { originalError: err });
272
370
  }
273
- return Uint8Array.from(globalThis.atob(str), c => c.charCodeAt(0));
371
+ }
372
+
373
+ /** @override */
374
+ async hmacSha256(key, data) {
375
+ const cryptoKey = await globalThis.crypto.subtle.importKey(
376
+ 'raw',
377
+ key,
378
+ { name: 'HMAC', hash: 'SHA-256' },
379
+ false,
380
+ ['sign'],
381
+ );
382
+ const signature = await globalThis.crypto.subtle.sign('HMAC', cryptoKey, data);
383
+ return new Uint8Array(signature);
274
384
  }
275
385
  }