diff --git a/src/runtime/node/crypto/node.ts b/src/runtime/node/crypto/node.ts index f9fa7e71..20625e41 100644 --- a/src/runtime/node/crypto/node.ts +++ b/src/runtime/node/crypto/node.ts @@ -7,6 +7,19 @@ import { getRandomValues } from "./web"; // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues const MAX_RANDOM_VALUE_BYTES: number = 65_536; +// Node.js webcrypto implementation +export const webcrypto = new Proxy( + globalThis.crypto as Crypto & typeof nodeCrypto.webcrypto, + { + get(_, key: keyof typeof globalThis.crypto | "CryptoKey") { + if (key === "CryptoKey") { + return globalThis.CryptoKey; + } + return globalThis.crypto[key]; + }, + }, +); + // ---- implemented Utils ---- export const randomBytes: typeof nodeCrypto.randomBytes = ( diff --git a/src/runtime/node/crypto/web.ts b/src/runtime/node/crypto/web.ts index 527f00dc..b8900435 100644 --- a/src/runtime/node/crypto/web.ts +++ b/src/runtime/node/crypto/web.ts @@ -1,27 +1,12 @@ // https://nodejs.org/api/crypto.html // https://github.com/unjs/uncrypto -import type nodeCrypto from "node:crypto"; -export const CryptoKey = - globalThis.CryptoKey as unknown as typeof nodeCrypto.webcrypto.CryptoKey; - -function ensureBound(thisArg: any, name: string | symbol) { - const fn = thisArg[name]; - return typeof fn === "function" ? fn.bind(thisArg) : fn; -} - -export const webcrypto: Crypto & typeof nodeCrypto.webcrypto = new Proxy({} as any, { - get(target, name) { - return CryptoKey && (CryptoKey as any)[name] ? ensureBound(CryptoKey, name) : ensureBound(globalThis.crypto, name); - }, -}); - -export const subtle: SubtleCrypto = webcrypto.subtle; +export const subtle: SubtleCrypto = globalThis.crypto?.subtle; export const randomUUID: Crypto["randomUUID"] = () => { - return webcrypto.randomUUID(); + return globalThis.crypto?.randomUUID(); }; export const getRandomValues: Crypto["getRandomValues"] = (array: any) => { - return webcrypto.getRandomValues(array); + return globalThis.crypto?.getRandomValues(array); };