Skip to content

Commit

Permalink
fix(node:crypto): properly call web crypto methods (#122)
Browse files Browse the repository at this point in the history
* Add deno compatibility to the webCrypto node implementation

* refactor: simplify and decouple node proxy

* simplify type

* reorder export

---------

Co-authored-by: Pooya Parsa <pooya@pi0.io>
  • Loading branch information
AaronDewes and pi0 authored Aug 8, 2023
1 parent 10781a4 commit 2fcf9b8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
12 changes: 12 additions & 0 deletions src/runtime/node/crypto/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@ const MAX_RANDOM_VALUE_BYTES: number = 65_536;

// ---- implemented Utils ----

export const webcrypto = new Proxy(
globalThis.crypto as typeof nodeCrypto.webcrypto,
{
get(_, key: keyof typeof globalThis.crypto | "CryptoKey") {
if (key === "CryptoKey") {
return globalThis.CryptoKey;
}
return globalThis.crypto[key];
},
},
);

export const randomBytes: typeof nodeCrypto.randomBytes = (
size: number,
cb?: (err: Error | null, buf: Buffer) => void,
Expand Down
15 changes: 3 additions & 12 deletions src/runtime/node/crypto/web.ts
Original file line number Diff line number Diff line change
@@ -1,21 +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;

export const webcrypto: Crypto & typeof nodeCrypto.webcrypto = {
CryptoKey,
...globalThis.crypto,
};

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 2fcf9b8

Please sign in to comment.