Skip to content

Commit

Permalink
fixup! lib: enable global WebCrypto by default
Browse files Browse the repository at this point in the history
  • Loading branch information
aduh95 committed Jun 4, 2022
1 parent abc6081 commit 8aea94d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
2 changes: 0 additions & 2 deletions lib/internal/main/eval_string.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ const { addBuiltinLibsToObject } = require('internal/modules/cjs/helpers');
const { getOptionValue } = require('internal/options');

prepareMainThreadExecution();
// Delete Webcrypto from the global scope for backward compatibility.
delete globalThis.crypto;
addBuiltinLibsToObject(globalThis, '<eval>');
markBootstrapComplete();

Expand Down
4 changes: 3 additions & 1 deletion lib/internal/process/execution.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const {
StringPrototypeIncludes,
globalThis,
} = primordials;

Expand Down Expand Up @@ -63,6 +64,7 @@ function evalScript(name, body, breakFirstLine, print) {
const asyncESM = require('internal/process/esm_loader');
const baseUrl = pathToFileURL(module.filename).href;

const shouldDefineCrypto = internalBinding('config').hasOpenSSL && StringPrototypeIncludes(body, 'crypto');
// Create wrapper for cache entry
const script = `
globalThis.module = module;
Expand All @@ -73,7 +75,7 @@ function evalScript(name, body, breakFirstLine, print) {
`;
globalThis.__filename = name;
const result = module._compile(script, `${name}-wrapper`)(() =>
require('vm').runInThisContext(body, {
require('vm').runInThisContext(shouldDefineCrypto ? `let crypto=require("crypto");{${body}}` : body, {
filename: name,
displayErrors: true,
[kVmBreakFirstLineSymbol]: !!breakFirstLine,
Expand Down
26 changes: 26 additions & 0 deletions test/parallel/test-cli-eval.js
Original file line number Diff line number Diff line change
Expand Up @@ -297,4 +297,30 @@ if (common.hasCrypto) {
common.mustSucceed((stdout) => {
assert.match(stdout, /[0-9a-f]{32}/i);
}));
child.exec(
`${nodejs} ` +
'-p "crypto.randomBytes(16).toString(\'hex\')"',
common.mustSucceed((stdout) => {
assert.match(stdout, /[0-9a-f]{32}/i);
}));
}
// Assert that overriding crypto works.
child.exec(
`${nodejs} ` +
'-p "crypto=Symbol(\'test\')"',
common.mustSucceed((stdout) => {
assert.match(stdout, /Symbol\(test\)/i);
}));
child.exec(
`${nodejs} ` +
'-e "crypto = {};console.log(\'randomBytes\', typeof crypto.randomBytes)"',
common.mustSucceed((stdout) => {
assert.match(stdout, /randomBytes\sundefined/);
}));
// Assert that overriding crypto with a local variable works.
child.exec(
`${nodejs} ` +
'-e "const crypto = {};console.log(\'randomBytes\', typeof crypto.randomBytes)"',
common.mustSucceed((stdout) => {
assert.match(stdout, /randomBytes\sundefined/);
}));

0 comments on commit 8aea94d

Please sign in to comment.