Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
[wasm] Use "node:crypto" to polyfill crypto.getRandomValues on older …
…node versions.
  • Loading branch information
maraf committed Nov 22, 2022
commit d780f591def7f9b74ea4951448fe90d768131e26
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
12 changes: 0 additions & 12 deletions src/mono/wasm/test-main.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,6 @@ 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') {
// **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 ()
globalThis.crypto = {
getRandomValues: function (buffer) {
for (let i = 0; i < buffer.length; i++)
buffer[i] = (Math.random() * 256) | 0;
}
}
}

let v8args;
if (typeof arguments !== "undefined") {
// this must be captured in top level scope in V8
Expand Down