From 7a886425d532ed4a49be40b5bc0527dcc8fad7c7 Mon Sep 17 00:00:00 2001 From: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> Date: Thu, 5 Jan 2023 14:51:37 -0800 Subject: [PATCH] [wasm] Catch error from loading "node:crypto" module (dotnet#78916) (#80249) * Catch error from loading node:crypto module. * Throw error with explanation when crypto module is not available. * Fix providing error throwing polyfill. Co-authored-by: carlossanlop --- src/mono/wasm/runtime/polyfills.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/mono/wasm/runtime/polyfills.ts b/src/mono/wasm/runtime/polyfills.ts index b93eb1c3f211d..c28d343b1b7b4 100644 --- a/src/mono/wasm/runtime/polyfills.ts +++ b/src/mono/wasm/runtime/polyfills.ts @@ -201,8 +201,18 @@ export async function init_polyfills_async(): Promise { globalThis.crypto = {}; } if (!globalThis.crypto.getRandomValues) { - const nodeCrypto = INTERNAL.require("node:crypto"); - if (nodeCrypto.webcrypto) { + let nodeCrypto: any = undefined; + try { + nodeCrypto = INTERNAL.require("node:crypto"); + } catch (err: any) { + // Noop, error throwing polyfill provided bellow + } + + if (!nodeCrypto) { + globalThis.crypto.getRandomValues = () => { + throw new Error("Using node without crypto support. To enable current operation, either provide polyfill for 'globalThis.crypto.getRandomValues' or enable 'node:crypto' module."); + }; + } else if (nodeCrypto.webcrypto) { globalThis.crypto = nodeCrypto.webcrypto; } else if (nodeCrypto.randomBytes) { globalThis.crypto.getRandomValues = (buffer: TypedArray) => {