Skip to content

Commit

Permalink
[release/7.0] [wasm] Use "node:crypto" to polyfill getRandomValues on…
Browse files Browse the repository at this point in the history
… older node (#78766)

* [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 <mara@neptuo.com>
  • Loading branch information
github-actions[bot] and maraf committed Jan 4, 2023
1 parent 814af26 commit a31811b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/mono/wasm/runtime/polyfills.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -195,6 +196,22 @@ export async function init_polyfills_async(): Promise<void> {
const { performance } = INTERNAL.require("perf_hooks");
globalThis.performance = performance;
}

if (!globalThis.crypto) {
globalThis.crypto = <any>{};
}
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));
}
};
}
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/mono/wasm/test-main.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 ()
Expand Down

0 comments on commit a31811b

Please sign in to comment.