Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
35 changes: 34 additions & 1 deletion lib/inspector.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
'use strict';

const {
Array,
ArrayIsArray,
JSONParse,
JSONStringify,
ObjectEntries,
ObjectSetPrototypeOf,
SafeMap,
SafeWeakMap,
SymbolDispose,
} = primordials;

Expand Down Expand Up @@ -51,6 +56,34 @@ const {
emitProtocolEvent,
} = internalBinding('inspector');

function toNullProtoTree(value, seen = new SafeWeakMap()) {
if (value === null || typeof value !== 'object') return value;

if (seen.has(value)) {
// Escape infinite recursion.
return seen.get(value);
}

if (ArrayIsArray(value)) {
const { length } = value;
const arr = ObjectSetPrototypeOf(new Array(length), null);
seen.set(value, arr);
for (let i = 0; i < length; i++) {
arr[i] = toNullProtoTree(value[i], seen);
}
return arr;
}

const clean = { __proto__: null };
seen.set(value, clean);
const entries = ObjectEntries(value);
for (let i = 0; i < entries.length; i++) {
const { 0: key, 1: value } = entries[i];
clean[key] = toNullProtoTree(value, seen);
}
return clean;
}

class Session extends EventEmitter {
#connection = null;
#nextId = 1;
Expand Down Expand Up @@ -136,7 +169,7 @@ class Session extends EventEmitter {
if (callback) {
this.#messageCallbacks.set(id, callback);
}
this.#connection.dispatch(JSONStringify(message));
this.#connection.dispatch(JSONStringify(toNullProtoTree(message)));
}

/**
Expand Down
7 changes: 3 additions & 4 deletions lib/internal/repl/eval.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const {
kDynamicImportName,
transformModuleSyntax,
} = require('internal/repl/transform');
const { getReplInspector, prepareContext } = require('internal/repl/inspector');
const { getReplInspector } = require('internal/repl/inspector');

let debug = require('internal/util/debuglog').debuglog('repl', (fn) => {
debug = fn;
Expand Down Expand Up @@ -117,7 +117,8 @@ function createReplEval(repl) {

async function inspectorEval(rawCode, context, file, cb) {
installDynamicImport(context);
prepareContext(context);
const contextId = repl.useGlobal ? undefined : repl[kContextId];
await inspector.prepareContext(context, contextId);

// Wrap bare object literals so `{ a: 1 }` is evaluated as an expression
// rather than a block statement.
Expand All @@ -142,8 +143,6 @@ function createReplEval(repl) {
return cb(await null);
}

const contextId = repl.useGlobal ? undefined : repl[kContextId];

const evaluateParams = {
expression: `${code}\n//# sourceURL=${file}`,
objectGroup: inspector.objectGroup,
Expand Down
64 changes: 45 additions & 19 deletions lib/internal/repl/inspector.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

const {
BigInt,
JSONStringify,
ObjectDefineProperty,
Promise,
PromisePrototypeThen,
ReflectHas,
SafeWeakMap,
StringPrototypeSlice,
Symbol,
} = primordials;
Expand All @@ -28,26 +28,14 @@ let Session;
let nextObjectGroupId = 0;

// Property used to ferry a live value from the inspector world back to ours.
// The stash is passed by object id rather than looked up through a global, so
// user code deleting or shadowing `globalThis` (or anything else) can't break it.
const kStashKey = '__nodeREPLStash';
const kStashFn = `function() {
globalThis[${JSONStringify(kStashKey)}].value = this;
}`;
const kStashFn = 'function(stash) { stash.value = this; }';

// Cached channel, attached to the REPL server instance.
const kChannel = Symbol('kReplInspectorChannel');

function prepareContext(context) {
if (!ReflectHas(context, kStashKey)) {
ObjectDefineProperty(context, kStashKey, {
__proto__: null,
value: { __proto__: null },
enumerable: false,
writable: false,
configurable: true,
});
}
}

// Converts the `unserializableValue` field of a remote object back into the
// real primitive it represents.
function fromUnserializable(value) {
Expand Down Expand Up @@ -79,6 +67,10 @@ class ReplInspectorChannel {
this.session = null;
// Exposed so callers can scope their own remote handles to the shared group.
this.objectGroup = `node-repl-${nextObjectGroupId++}`;
// Remote handles to each context's stash, kept outside `objectGroup` so
// `releaseObjects()` does not drop them.
this.stashObjectGroup = `${this.objectGroup}-stash`;
this.stashes = new SafeWeakMap();
}

// Lazily connects the shared session and arranges for it to be torn down on
Expand Down Expand Up @@ -193,16 +185,22 @@ class ReplInspectorChannel {
// it points at.
async toLiveValue(remote, context) {
if (remote.objectId !== undefined) {
const entry = this.stashes.get(context);
if (entry === undefined) {
throw new ERR_INSPECTOR_NOT_AVAILABLE();
}
const response = await this.post('Runtime.callFunctionOn', {
functionDeclaration: kStashFn,
objectId: remote.objectId,
arguments: [{ objectId: entry.objectId }],
Comment thread
aduh95 marked this conversation as resolved.
Resolved
objectGroup: this.objectGroup,
});
if (response.exceptionDetails) {
throw new ERR_INSPECTOR_NOT_AVAILABLE();
}
const value = context[kStashKey].value;
context[kStashKey].value = undefined;
const { stash } = entry;
const value = stash.value;
stash.value = undefined;
return { __proto__: null, value };
}
if (remote.type === 'undefined') {
Expand All @@ -217,6 +215,35 @@ class ReplInspectorChannel {
return { __proto__: null, value: undefined };
}

// Installs the stash on `context` if needed and retains a remote handle to it.
// Runs before any user code is evaluated in a fresh context.
async prepareContext(context, contextId) {
if (this.stashes.has(context) && ReflectHas(context, kStashKey)) {
return;
}
if (!ReflectHas(context, kStashKey)) {
ObjectDefineProperty(context, kStashKey, {
__proto__: null,
value: { __proto__: null },
enumerable: false,
writable: false,
configurable: true,
});
}
const stash = context[kStashKey];
const { result, exceptionDetails } = await this.post('Runtime.evaluate', {
expression: kStashKey,
Comment thread
aduh95 marked this conversation as resolved.
Resolved
objectGroup: this.stashObjectGroup,
silent: true,
...(contextId !== undefined ? { contextId } : null),
Comment thread
aduh95 marked this conversation as resolved.
Resolved
});
if (exceptionDetails || result.objectId === undefined) {
this.stashes.delete(context);
return;
}
this.stashes.set(context, { __proto__: null, stash, objectId: result.objectId });
}

// Releases every remote handle created in the shared object group.
releaseObjects() {
if (this.session !== null) {
Expand Down Expand Up @@ -268,5 +295,4 @@ function getReplInspector(repl) {

module.exports = {
getReplInspector,
prepareContext,
};
8 changes: 8 additions & 0 deletions test/parallel/test-repl-inspector.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,11 @@ await run([

assert(output.accumulator.includes(
"null { result: { type: 'number', value: 2, description: '2' } }"));

// Ensures that we do not rely on user-mutable global identifiers:
await run([
'Object.prototype.toJSON = function() { throw new Error() }',
'delete global, delete globalThis, delete Function, delete eval, delete Object, delete Reflect; Math',
]);

assert.match(output.accumulator, /^Object \[Math\] \{\}$/m);
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ start({

input.end('setImmediate(() => { throw new Error("test"); });\n');

setImmediate(common.mustCall(() => {
process.on('beforeExit', common.mustCall(() => {
assert.match(output.read(), /Uncaught Error: test/);
}));
Loading