@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 354 lines 12.7 KB
Raw
1 /**
2 * Node.js layers for the `effect/crypto` modules, also used by Bun.
3 *
4 * {@link layerDigest} runs MD5 and SHA on `node:crypto`, {@link layerMac} runs
5 * HMAC on `node:crypto`, {@link layerKdf} adds Argon2id, {@link layerAead}
6 * runs ChaCha20-Poly1305 on `node:crypto`, and {@link layerSecureRandom},
7 * {@link layerCipher}, {@link layerSignature}, {@link layerKeyAgreement}, and
8 * {@link layerKeyWrap} run the core WebCrypto layers. Each Node.js layer
9 * handles only the algorithms and keys it exists for and hands the rest to
10 * the core WebCrypto implementation. Layers that need `SecureRandom` get it
11 * from {@link layerSecureRandom}, so no layer here has requirements.
12 * {@link layer} provides every family at once; provide a family's own layer to
13 * pick services selectively.
14 *
15 * `CryptoKey`-backed keys go through Node.js's `crypto.subtle`, because
16 * `KeyObject.from(cryptoKey)` is deprecated (DEP0204). A `CryptoKey` must
17 * come from the `WebCrypto` reference: Node.js rejects one from another
18 * reference with a `TypeError`, which is a defect.
19 *
20 * @stability unstable
21 * @since 1.0.0
22 */
23 import * as Aead from "effect/crypto/Aead"
24 import * as Cipher from "effect/crypto/Cipher"
25 import * as CryptoError from "effect/crypto/CryptoError"
26 import * as Digest from "effect/crypto/Digest"
27 import * as Kdf from "effect/crypto/Kdf"
28 import * as KeyAgreement from "effect/crypto/KeyAgreement"
29 import * as KeyWrap from "effect/crypto/KeyWrap"
30 import * as Mac from "effect/crypto/Mac"
31 import * as SecureRandom from "effect/crypto/SecureRandom"
32 import * as Signature from "effect/crypto/Signature"
33 import * as Effect from "effect/Effect"
34 import * as Layer from "effect/Layer"
35 import * as NodeCrypto from "node:crypto"
36
37 /**
38 * Layer that provides `SecureRandom` from `getRandomValues` on the `WebCrypto`
39 * reference.
40 *
41 * **Details**
42 *
43 * This is `SecureRandom.layerWebCrypto`, re-exported so that Node.js programs
44 * take every crypto layer from `NodeCrypto`. `node:crypto` adds nothing here.
45 *
46 * @stability unstable
47 * @category layers
48 * @since 4.0.0
49 */
50 export const layerSecureRandom: Layer.Layer<SecureRandom.SecureRandom> = SecureRandom.layerWebCrypto
51
52 const nodeHashNames: Record<Digest.Algorithm["name"], string> = {
53 "MD5": "md5",
54 "SHA-1": "sha1",
55 "SHA-256": "sha256",
56 "SHA-384": "sha384",
57 "SHA-512": "sha512"
58 }
59
60 // Copies the Buffer, which may be a view into Node's shared pool.
61 const nodeDigest = (algorithm: Digest.Algorithm, data: Uint8Array): Uint8Array =>
62 new Uint8Array(NodeCrypto.createHash(nodeHashNames[algorithm.name]).update(data).digest())
63
64 /**
65 * Layer that provides `Digest` using `createHash` from `node:crypto`.
66 *
67 * **Details**
68 *
69 * MD5 and the SHA algorithms run synchronously on `node:crypto`. On Node.js,
70 * `crypto.subtle.digest` sends each call to the threadpool, which is
71 * noticeably slower for small inputs. Output is identical to
72 * `Digest.layerWebCrypto`.
73 *
74 * @stability unstable
75 * @category layers
76 * @since 4.0.0
77 */
78 export const layerDigest: Layer.Layer<Digest.Digest> = Layer.succeed(Digest.Digest, {
79 digest: (algorithm, data) => Effect.sync(() => nodeDigest(algorithm, data)),
80 digestHex: (algorithm, data) =>
81 Effect.sync(() => NodeCrypto.createHash(nodeHashNames[algorithm.name]).update(data).digest("hex"))
82 })
83
84 // Copies the Buffer, which may be a view into Node's shared pool.
85 const nodeHmac = (hash: Digest.Algorithm["name"], key: Uint8Array, data: Uint8Array): Uint8Array =>
86 new Uint8Array(NodeCrypto.createHmac(nodeHashNames[hash], key).update(data).digest())
87
88 /**
89 * Layer that provides `Mac` using `createHmac` from `node:crypto`.
90 *
91 * **Details**
92 *
93 * Byte-backed keys sign and verify synchronously on `node:crypto`, since
94 * webhook verification is a server hot path. `CryptoKey`-backed keys go
95 * through Node.js's `crypto.subtle`, and generated keys come from
96 * {@link layerSecureRandom}. This is `Mac.layerWebCryptoWith` with a
97 * `node:crypto` primitive, so output and errors are identical to
98 * `Mac.layerWebCrypto`.
99 *
100 * @stability unstable
101 * @category layers
102 * @since 4.0.0
103 */
104 export const layerMac: Layer.Layer<Mac.Mac> = Mac.layerWebCryptoWith({
105 hmac: nodeHmac
106 }).pipe(Layer.provide(layerSecureRandom))
107
108 const kdfFailure = (reason: CryptoError.CryptoErrorReason): Effect.Effect<never, CryptoError.CryptoError> =>
109 Effect.fail(new CryptoError.CryptoError({ module: "Kdf", method: "derive", reason }))
110
111 const argon2Unsupported = (cause?: unknown) =>
112 kdfFailure(
113 new CryptoError.Unsupported({
114 description: "NodeCrypto.layerKdf does not provide argon2id on this runtime",
115 ...(cause === undefined ? {} : { cause })
116 })
117 )
118
119 // Only a missing Argon2id engine is a typed failure; anything else is a defect.
120 const argon2Failure = (cause: unknown): Effect.Effect<never, CryptoError.CryptoError> =>
121 typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ERR_CRYPTO_ARGON2_NOT_SUPPORTED"
122 ? argon2Unsupported(cause)
123 : Effect.die(cause)
124
125 const isIntegerIn = (n: number, min: number, max: number): boolean => Number.isSafeInteger(n) && n >= min && n <= max
126
127 type DeriveOptions = Parameters<Kdf.Kdf["Service"]["derive"]>[2]
128
129 // The RFC 9106 bounds, checked before `node:crypto`, which throws on them.
130 const argon2Problem = (algorithm: Kdf.Argon2id, options: DeriveOptions): string | undefined => {
131 if (options.info !== undefined) return "info only applies to HKDF"
132 const uint32 = (n: number) => isIntegerIn(n, 1, 0xffff_ffff)
133 if (!uint32(algorithm.passes) || !isIntegerIn(algorithm.parallelism, 1, 0xff_ffff)) {
134 return "passes must be between 1 and 2^32 - 1 and parallelism between 1 and 2^24 - 1"
135 }
136 if (!uint32(algorithm.memory) || algorithm.memory < 8 * algorithm.parallelism) {
137 return "memory must be at least 8 KiB per lane and below 2^32 KiB"
138 }
139 if (options.salt.length < 8) return "salt must be at least 8 bytes"
140 return isIntegerIn(options.length, 4, 0xffff_ffff) ? undefined : "length must be between 4 and 2^32 - 1 bytes"
141 }
142
143 const argon2id = (algorithm: Kdf.Argon2id, secret: Uint8Array, options: DeriveOptions) =>
144 Effect.callback<Uint8Array, CryptoError.CryptoError>((resume) => {
145 const problem = argon2Problem(algorithm, options)
146 if (problem !== undefined) return resume(kdfFailure(new CryptoError.InvalidArgument({ description: problem })))
147 // Checked at call time, since Node.js added `argon2` in 24.7.
148 if (typeof NodeCrypto.argon2 !== "function") return resume(argon2Unsupported())
149 try {
150 NodeCrypto.argon2("argon2id", {
151 message: secret,
152 nonce: options.salt,
153 memory: algorithm.memory,
154 passes: algorithm.passes,
155 parallelism: algorithm.parallelism,
156 tagLength: options.length
157 }, (cause, key) => {
158 if (cause) resume(argon2Failure(cause))
159 else resume(Effect.succeed(new Uint8Array(key.buffer, key.byteOffset, key.length)))
160 })
161 } catch (cause) {
162 resume(argon2Failure(cause))
163 }
164 }).pipe(Effect.uninterruptible)
165
166 /**
167 * Layer that provides `Kdf`, adding Argon2id from `node:crypto`.
168 *
169 * **Details**
170 *
171 * Argon2id runs on `argon2` from `node:crypto`, which needs Node.js 24.7 or
172 * later linked against OpenSSL 3.2, or Bun 1.4. Support is checked at call
173 * time: on other runtimes, deriving with Argon2id fails with an `Unsupported`
174 * reason. HKDF and PBKDF2 go through `Kdf.layerWebCrypto`, which keeps them
175 * off the event loop.
176 *
177 * @stability unstable
178 * @category layers
179 * @since 4.0.0
180 */
181 export const layerKdf: Layer.Layer<Kdf.Kdf> = Layer.effect(
182 Kdf.Kdf,
183 Effect.gen(function*() {
184 const core = yield* Kdf.Kdf
185 return Kdf.Kdf.of({
186 derive: (algorithm, secret, options) =>
187 algorithm._tag === "Argon2id" ? argon2id(algorithm, secret, options) : core.derive(algorithm, secret, options)
188 })
189 })
190 ).pipe(Layer.provide(Kdf.layerWebCrypto))
191
192 // Copies into a fresh array, wiping the parts, so no plaintext stays in
193 // Node.js's shared Buffer pool.
194 const concat = (parts: ReadonlyArray<Uint8Array>): Uint8Array => {
195 const output = new Uint8Array(parts.reduce((length, part) => length + part.length, 0))
196 let offset = 0
197 for (const part of parts) {
198 output.set(part, offset)
199 offset += part.length
200 part.fill(0)
201 }
202 return output
203 }
204
205 const nodeChacha: Aead.Implementation = {
206 encrypt: (key, nonce, plaintext, aad) => {
207 const cipher = NodeCrypto.createCipheriv("chacha20-poly1305", key, nonce, { authTagLength: 16 })
208 cipher.setAAD(aad)
209 return concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()])
210 },
211 decrypt: (key, nonce, ciphertext, aad) => {
212 const decipher = NodeCrypto.createDecipheriv("chacha20-poly1305", key, nonce, { authTagLength: 16 })
213 decipher.setAAD(aad)
214 decipher.setAuthTag(ciphertext.subarray(ciphertext.length - 16))
215 const plaintext = decipher.update(ciphertext.subarray(0, ciphertext.length - 16))
216 try {
217 // `final` throws only when the tag does not match.
218 return concat([plaintext, decipher.final()])
219 } catch {
220 plaintext.fill(0)
221 return undefined
222 }
223 }
224 }
225
226 /**
227 * Layer that provides `Aead`, running ChaCha20-Poly1305 on `node:crypto`.
228 *
229 * **Details**
230 *
231 * Byte-backed ChaCha20-Poly1305 keys encrypt and decrypt synchronously on
232 * `node:crypto`. AES-GCM runs on `crypto.subtle` and XChaCha20-Poly1305 on its
233 * pure TypeScript implementation. This is `Aead.layerWebCryptoWith` with a
234 * `node:crypto` implementation, so arguments are checked and errors reported
235 * as in `Aead.layerWebCrypto`. Bun's `node:crypto` lacks ChaCha20-Poly1305, so
236 * on Bun this layer runs the core implementation. Output is identical to
237 * `Aead.layerWebCrypto`. Generated keys come from {@link layerSecureRandom}.
238 *
239 * @stability unstable
240 * @category layers
241 * @since 4.0.0
242 */
243 export const layerAead: Layer.Layer<Aead.Aead> = Aead.layerWebCryptoWith(
244 NodeCrypto.getCiphers().includes("chacha20-poly1305") ? { implementations: { chacha20Poly1305: nodeChacha } } : {}
245 ).pipe(Layer.provide(layerSecureRandom))
246
247 /**
248 * Layer that provides `Cipher` from `crypto.subtle` on the `WebCrypto`
249 * reference.
250 *
251 * **Details**
252 *
253 * This is `Cipher.layerWebCrypto` with {@link layerSecureRandom}, so that
254 * Node.js programs take every crypto layer from `NodeCrypto`. Node.js's
255 * `crypto.subtle` already runs AES-CTR and AES-CBC on OpenSSL.
256 *
257 * @stability unstable
258 * @category layers
259 * @since 4.0.0
260 */
261 export const layerCipher: Layer.Layer<Cipher.Cipher> = Cipher.layerWebCrypto.pipe(
262 Layer.provide(layerSecureRandom)
263 )
264
265 /**
266 * Layer that provides `Signature` on Node.js's `crypto.subtle`.
267 *
268 * **Details**
269 *
270 * This is `Signature.layerWebCrypto` with {@link layerSecureRandom}, so that
271 * Node.js programs take every crypto layer from `NodeCrypto`.
272 * `CryptoKey`-backed keys go through Node.js's `crypto.subtle`, because
273 * `KeyObject.from(cryptoKey)` is deprecated (DEP0204).
274 *
275 * @stability unstable
276 * @category layers
277 * @since 4.0.0
278 */
279 export const layerSignature: Layer.Layer<Signature.Signature> = Signature.layerWebCrypto.pipe(
280 Layer.provide(layerSecureRandom)
281 )
282
283 /**
284 * Layer that provides `KeyAgreement` on Node.js's `crypto.subtle`.
285 *
286 * **Details**
287 *
288 * This is `KeyAgreement.layerWebCrypto` with {@link layerSecureRandom}, so
289 * that Node.js programs take every crypto layer from `NodeCrypto`.
290 * `CryptoKey`-backed keys go through Node.js's `crypto.subtle`, because
291 * `KeyObject.from(cryptoKey)` is deprecated (DEP0204).
292 *
293 * @stability unstable
294 * @category layers
295 * @since 4.0.0
296 */
297 export const layerKeyAgreement: Layer.Layer<KeyAgreement.KeyAgreement> = KeyAgreement.layerWebCrypto.pipe(
298 Layer.provide(layerSecureRandom)
299 )
300
301 /**
302 * Layer that provides `KeyWrap` on Node.js's `crypto.subtle`.
303 *
304 * **Details**
305 *
306 * This is `KeyWrap.layerWebCrypto` with {@link layerSecureRandom}, so that
307 * Node.js programs take every crypto layer from `NodeCrypto`. Node.js's
308 * `crypto.subtle` runs AES-KW and RSA-OAEP on OpenSSL. `CryptoKey`-backed
309 * keys go through it, because `KeyObject.from(cryptoKey)` is deprecated
310 * (DEP0204).
311 *
312 * @stability unstable
313 * @category layers
314 * @since 4.0.0
315 */
316 export const layerKeyWrap: Layer.Layer<KeyWrap.KeyWrap> = KeyWrap.layerWebCrypto.pipe(
317 Layer.provide(layerSecureRandom)
318 )
319
320 /**
321 * Layer that provides every `effect/crypto` service with the Node.js
322 * implementations.
323 *
324 * **Details**
325 *
326 * This merges the family layers of this module, so it requires nothing. It
327 * keeps the `node:crypto` implementations of {@link layerDigest},
328 * {@link layerMac}, {@link layerKdf}, and {@link layerAead}.
329 *
330 * @stability unstable
331 * @category layers
332 * @since 4.0.0
333 */
334 export const layer: Layer.Layer<
335 | SecureRandom.SecureRandom
336 | Digest.Digest
337 | Mac.Mac
338 | Kdf.Kdf
339 | Aead.Aead
340 | Cipher.Cipher
341 | Signature.Signature
342 | KeyAgreement.KeyAgreement
343 | KeyWrap.KeyWrap
344 > = Layer.mergeAll(
345 layerSecureRandom,
346 layerDigest,
347 layerMac,
348 layerKdf,
349 layerAead,
350 layerCipher,
351 layerSignature,
352 layerKeyAgreement,
353 layerKeyWrap
354 )