From 0ec98b020aff5d323f83201f506a78b230dde8f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Fi=C5=A1era?= Date: Wed, 7 Dec 2022 17:31:10 +0100 Subject: [PATCH] [wasm] Catch error from loading "node:crypto" module (#78916) * Catch error from loading node:crypto module. * Throw error with explanation when crypto module is not available. * Fix providing error throwing polyfill. --- 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 b93eb1c3f211d0..58f1bdd13eec06 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) => {