From a31811bc6ae92a02fe7c29440ce8ba45d60984c0 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 4 Jan 2023 12:16:15 -0800 Subject: [PATCH] [release/7.0] [wasm] Use "node:crypto" to polyfill getRandomValues on older node (#78766) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [wasm] Use "node:crypto" to polyfill crypto.getRandomValues on older node versions. * Revert getRandomValues using Math for tests on V8. Co-authored-by: Marek FiĊĦera --- src/mono/wasm/runtime/polyfills.ts | 17 +++++++++++++++++ src/mono/wasm/test-main.js | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/mono/wasm/runtime/polyfills.ts b/src/mono/wasm/runtime/polyfills.ts index b330f45b8f18e..b93eb1c3f211d 100644 --- a/src/mono/wasm/runtime/polyfills.ts +++ b/src/mono/wasm/runtime/polyfills.ts @@ -7,6 +7,7 @@ import { ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, ENVIRONMENT_IS_WEB, ENVIRONM import { afterUpdateGlobalBufferAndViews } from "./memory"; import { replaceEmscriptenPThreadLibrary } from "./pthreads/shared/emscripten-replacements"; import { DotnetModuleConfigImports, EarlyReplacements } from "./types"; +import { TypedArray } from "./types/emscripten"; let node_fs: any | undefined = undefined; let node_url: any | undefined = undefined; @@ -195,6 +196,22 @@ export async function init_polyfills_async(): Promise { const { performance } = INTERNAL.require("perf_hooks"); globalThis.performance = performance; } + + if (!globalThis.crypto) { + globalThis.crypto = {}; + } + if (!globalThis.crypto.getRandomValues) { + const nodeCrypto = INTERNAL.require("node:crypto"); + if (nodeCrypto.webcrypto) { + globalThis.crypto = nodeCrypto.webcrypto; + } else if (nodeCrypto.randomBytes) { + globalThis.crypto.getRandomValues = (buffer: TypedArray) => { + if (buffer) { + buffer.set(nodeCrypto.randomBytes(buffer.length)); + } + }; + } + } } } diff --git a/src/mono/wasm/test-main.js b/src/mono/wasm/test-main.js index bac3f856160c5..24f5817ef19ba 100644 --- a/src/mono/wasm/test-main.js +++ b/src/mono/wasm/test-main.js @@ -23,7 +23,7 @@ if (is_node && process.versions.node.split(".")[0] < 14) { throw new Error(`NodeJS at '${process.execPath}' has too low version '${process.versions.node}'`); } -if (typeof globalThis.crypto === 'undefined') { +if (!is_node && !is_browser && typeof globalThis.crypto === 'undefined') { // **NOTE** this is a simple insecure polyfill for testing purposes only // /dev/random doesn't work on js shells, so define our own // See library_fs.js:createDefaultDevices ()