Skip to content

Commit 4e8e5e5

Browse files
authored
[wasm] Use "node:crypto" to polyfill getRandomValues on older node (#78696)
1 parent e56518f commit 4e8e5e5

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/mono/wasm/runtime/polyfills.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, ENVIRONMENT_IS_WEB, ENVIRONM
77
import { afterUpdateGlobalBufferAndViews } from "./memory";
88
import { replaceEmscriptenPThreadLibrary } from "./pthreads/shared/emscripten-replacements";
99
import { DotnetModuleConfigImports, EarlyReplacements } from "./types";
10+
import { TypedArray } from "./types/emscripten";
1011

1112
let node_fs: any | undefined = undefined;
1213
let node_url: any | undefined = undefined;
@@ -195,6 +196,22 @@ export async function init_polyfills_async(): Promise<void> {
195196
const { performance } = INTERNAL.require("perf_hooks");
196197
globalThis.performance = performance;
197198
}
199+
200+
if (!globalThis.crypto) {
201+
globalThis.crypto = <any>{};
202+
}
203+
if (!globalThis.crypto.getRandomValues) {
204+
const nodeCrypto = INTERNAL.require("node:crypto");
205+
if (nodeCrypto.webcrypto) {
206+
globalThis.crypto = nodeCrypto.webcrypto;
207+
} else if (nodeCrypto.randomBytes) {
208+
globalThis.crypto.getRandomValues = (buffer: TypedArray) => {
209+
if (buffer) {
210+
buffer.set(nodeCrypto.randomBytes(buffer.length));
211+
}
212+
};
213+
}
214+
}
198215
}
199216
}
200217

src/mono/wasm/test-main.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ if (is_node && process.versions.node.split(".")[0] < 14) {
2323
throw new Error(`NodeJS at '${process.execPath}' has too low version '${process.versions.node}'`);
2424
}
2525

26-
if (typeof globalThis.crypto === 'undefined') {
26+
if (!is_node && !is_browser && typeof globalThis.crypto === 'undefined') {
2727
// **NOTE** this is a simple insecure polyfill for testing purposes only
2828
// /dev/random doesn't work on js shells, so define our own
2929
// See library_fs.js:createDefaultDevices ()

0 commit comments

Comments
 (0)