diff --git a/lib/internal/repl/inspector.js b/lib/internal/repl/inspector.js index 371255eac28d..76c083b0e883 100644 --- a/lib/internal/repl/inspector.js +++ b/lib/internal/repl/inspector.js @@ -2,7 +2,6 @@ const { BigInt, - JSONStringify, ObjectDefineProperty, Promise, PromisePrototypeThen, @@ -29,8 +28,10 @@ let nextObjectGroupId = 0; // Property used to ferry a live value from the inspector world back to ours. const kStashKey = '__nodeREPLStash'; +// Resolve the stash directly so deleting or shadowing globalThis in the REPL +// does not prevent transferring results and exceptions back to the host. const kStashFn = `function() { - globalThis[${JSONStringify(kStashKey)}].value = this; + ${kStashKey}.value = this; }`; // Cached channel, attached to the REPL server instance. diff --git a/test/parallel/test-repl-delete-global-this.mjs b/test/parallel/test-repl-delete-global-this.mjs new file mode 100644 index 000000000000..d5f80b9cc860 --- /dev/null +++ b/test/parallel/test-repl-delete-global-this.mjs @@ -0,0 +1,40 @@ +import '../common/index.mjs'; +import assert from 'node:assert/strict'; +import { startNewREPLServer } from '../common/repl.js'; + +const globalObject = globalThis; +const globalThisDescriptor = Object.getOwnPropertyDescriptor(globalObject, 'globalThis'); + +for (const useGlobal of [false, true]) { + const { replServer, output, run } = startNewREPLServer({ + terminal: false, + useColors: false, + useGlobal, + }); + + async function check(input, expected) { + output.accumulator = ''; + await run([input]); + assert.match(output.accumulator, expected); + } + + try { + await check('delete globalThis', /^true\n$/); + await check('typeof globalThis', /^'undefined'\n$/); + await check('Math', /\[Math\]/); + await check('JSON', /\[JSON\]/); + await check('Object', /\[Function: Object\]/); + await check('JSON.stringify({ pi: Math.PI })', /3\.141592653589793/); + + await check('a', /^Uncaught ReferenceError: a is not defined\n/); + await check('21 * 2', /^42\n$/); + await check('!@#$%^&[]', /^Uncaught SyntaxError:/); + await check('21 * 2', /^42\n$/); + + await check('({', /^\| $/); + await check('answer: 42 })', /^\{ answer: 42 \}\n$/); + } finally { + Object.defineProperty(globalObject, 'globalThis', globalThisDescriptor); + replServer.close(); + } +}