Skip to content

Commit

Permalink
refactor: simplify and decouple node proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 8, 2023
1 parent e168422 commit 820bf67
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 18 deletions.
13 changes: 13 additions & 0 deletions src/runtime/node/crypto/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
Expand Down
21 changes: 3 additions & 18 deletions src/runtime/node/crypto/web.ts
Original file line number Diff line number Diff line change
@@ -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<Crypto & typeof nodeCrypto.webcrypto>({} 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);
};

0 comments on commit 820bf67

Please sign in to comment.