[wasm] Catch error from loading "node:crypto" module (#78916)
authorMarek Fišera <mara@neptuo.com>
Tue, 29 Nov 2022 16:58:04 +0000 (17:58 +0100)
committerGitHub <noreply@github.com>
Tue, 29 Nov 2022 16:58:04 +0000 (17:58 +0100)
* 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

index b93eb1c..58f1bdd 100644 (file)
@@ -201,8 +201,18 @@ export async function init_polyfills_async(): Promise<void> {
             globalThis.crypto = <any>{};
         }
         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) => {