Skip to content

node:vm: DONT_CONTEXTIFY returns the context's real global object - #45284

Closed
dylan-conway wants to merge 2 commits into
mainfrom
claude/vm-dont-contextify-globals
Closed

dylan-conway wants to merge 2 commits into
mainfrom
claude/vm-dont-contextify-globals

Conversation

@dylan-conway

@dylan-conway dylan-conway commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

In a context made with vm.createContext(vm.constants.DONT_CONTEXTIFY), top-level var and function declarations read back undefined, and a store to any name the global already held was dropped.

const ctx = vm.createContext(vm.constants.DONT_CONTEXTIFY);
vm.runInContext("var w = 1 + 1; function f() {} [w, typeof f].join()", ctx);
// 1.4.3: ",undefined"    Node and this PR: "2,function"

The context object was a stand-in (NodeVMSpecialSandbox) with storage of its own. Reads asked the global first and the stand-in second, while writes always went to the stand-in, so the two disagreed about every name the global held. The stand-in's answers were also cacheable although they depended on the global.

The context object is now the global's own globalThis, as in Node, and such a global has no sandbox attached, so every hook on NodeVMGlobalObject falls through to the base class. NodeVMSpecialSandbox is deleted. Object.freeze(globalThis) works on the ordinary global proxy.

in a DONT_CONTEXTIFY context 1.4.3 Node, this PR
var w = 2; w undefined 2
Array = 1; typeof Array "function" "number"
ctx.Array = 1, then typeof Array "function" "number"
'use strict'; NaN = 1 no error TypeError
delete globalThis.Array; typeof Array "function" "undefined"
Object.hasOwn(ctx, "b") asked before and after var b false, false false, true
frozen, then var z = 1 no error TypeError
var w = 2; Object.freeze(globalThis); w = 3; w undefined 2

A global proxy now counts as a context only when its global has no sandbox. runInContext no longer re-attaches the object it was given as the sandbox on each run. Before, passing vm.runInContext("this", ctx) of an ordinary context back to vm.runInContext made the global forward to itself and crashed the process. It now throws ERR_INVALID_ARG_TYPE and vm.isContext returns false for it, as in Node.

runInNewContext() now does what Node's does: make the context, or take the one it was given, and run in it. Before, vm.runInNewContext() made a context in JS and Script#runInNewContext() then made a second one around the same object and ran there. With the real global as the context object that second one would have wrapped a global proxy. It also means:

1.4.3 Node, this PR
vm.runInNewContext("x = []", ctx), then x instanceof Array in ctx false true
let l = 1 in one runInNewContext(..., ctx), typeof l in the next "undefined" "number"
vm.runInNewContext("eval('1')", DONT_CONTEXTIFY, { contextCodeGeneration: { strings: false } }) 1 EvalError
vm.runInNewContext("1", {}, { codeGeneration: { get strings() { throw ... } } }) throws does not read it

How did you verify your code works?

Eleven new tests in test/js/node/vm/vm.test.ts. All fail with USE_SYSTEM_BUN=1 bun test (1.4.3) and pass with bun bd test. One existing test listed the option getters vm.runInNewContext() reads, and now lists the ones Node reads. On the debug build the rest of vm.test.ts passes and so do the 98 test-vm-*.js files of Node's own suite in test/js/node/test. Expected values come from running the same scripts in Node v26.7.0.

@robobun

robobun commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator
Updated 4:58 PM PT - Oct 14th, 2026

@dylan-conway, your commit 2824bd1 is building: #125627

@coderabbitai

coderabbitai Bot commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: oven-sh/bun/.coderabbit.yaml
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 13f7c272-c00e-4f6c-830c-46f0d222e98f
📥 Commits

Reviewing files that changed from the base of the PR and between 9510e74 and a29500f.

📒 Files selected for processing: 6
  • src/jsc/bindings/NodeVM.cpp
  • src/jsc/bindings/NodeVM.h
  • src/jsc/bindings/NodeVMScript.cpp
  • src/jsc/bindings/webcore/DOMClientIsoSubspaces.h
  • src/jsc/bindings/webcore/DOMIsoSubspaces.h
  • test/js/node/vm/vm.test.ts
💤 Files with no reviewable changes: 2
  • src/jsc/bindings/webcore/DOMIsoSubspaces.h
  • src/jsc/bindings/webcore/DOMClientIsoSubspaces.h

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

Walkthrough

Not-contextified VM contexts now use the target global object instead of a special sandbox wrapper. Context creation, script evaluation, property handling, and context recognition use the updated global-object model. Tests cover global property behavior and context identity.

Changes

Node VM not-contextified contexts

Layer / File(s) Summary
Global object property routing
src/jsc/bindings/NodeVM.h, src/jsc/bindings/NodeVM.cpp, src/jsc/bindings/webcore/DOM*IsoSubspaces.h
Removes NodeVMSpecialSandbox and its subspace members. Routes sandbox property operations through NodeVMGlobalObject.
Context creation and script execution
src/jsc/bindings/NodeVM.cpp, src/jsc/bindings/NodeVMScript.cpp
Returns the target context’s globalThis for not-contextified contexts. Script evaluation uses the target VM global without installing a special sandbox.
Context lookup and behavior tests
src/jsc/bindings/NodeVM.cpp, test/js/node/vm/vm.test.ts
Narrows context lookup and isContext recognition to the specified not-contextified global proxy targets. Adds tests for global property behavior and context identity.

Possibly related PRs

  • oven-sh/bun#39588: Introduced the Node VM sandbox and global-proxy model that this PR continues.

Suggested reviewers: robobun

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to a2950

The investigated compatibility gaps predate this change; no change-specific issue remains to resolve before merging.

Pre-merge checks: Passed 4
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely identifies the main change: making DONT_CONTEXTIFY return the context's real global object.
Description check Passed The description follows the required template. It explains the behavior change and verification steps, and includes relevant examples and test results.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches: 💡 1
🛠️ Fix failing CI checks: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Beyond the inline findings, I also checked that the NodeVMSpecialSandbox removal is complete (no remaining references anywhere in the tree, both iso-subspace slots and the visitChildrenImpl append removed with the field), and that tightening isContext/getGlobalObjectFromContext to reject a contextified global's own proxy matches Node's ERR_INVALID_ARG_TYPE behavior rather than silently breaking a supported input.

Extended reasoning...

The change deletes a JSC cell class and reroutes DONT_CONTEXTIFY contexts in src/jsc/bindings/NodeVM.cpp and NodeVMScript.cpp to use the real JSGlobalProxy; the dead-code removal and GC visitor wiring were verified complete, and the isContext polarity change was ruled out as a regression.

Findings marked 🟡 are optional suggestions and need no follow-up push.

Additional findings (outside the current diff — GitHub can't attach inline comments there):

  • 🟣 src/jsc/bindings/NodeVM.cpp — pre-existing: Callers of vm.compileFunction with parsingContext set to a DONT_CONTEXTIFY context still get ERR_INVALID_ARG_INSTANCE, while Node accepts it. The validator at NodeVM.cpp:1872-1881 only consults vmModuleContextMap, which this PR now never populates for DONT_CONTEXTIFY globals, so the global proxy returned by createContext is rejected even though isContext says true for it. Fix: resolve parsingContext through the shared getGlobalObjectFromContext helper (NodeVM.cpp:780) so every context accepted by isContext, including the DONT_CONTEXTIFY global proxy, is accepted here too.

    Why this was flagged

    User calls vm.compileFunction("return 1", [], { parsingContext: vm.createContext(vm.constants.DONT_CONTEXTIFY) }). vm.createContext returns targetContext->globalThis() at NodeVM.cpp:1498 and returns before the vmModuleContextMap()->set at NodeVM.cpp:1505, so the proxy is never in the map. The parsingContext branch at NodeVM.cpp:1874-1877 does vmModuleContextMap()->get(context) and throws ERR::INVALID_ARG_INSTANCE "options.parsingContext" when it is undefined; it does not fall back to the JSGlobalProxy check that getGlobalObjectFromContext does at NodeVM.cpp:802-805 and isContext does at NodeVM.cpp:847-849. On the base branch the same call also threw (the special sandbox was not in the map either), so this is pre-existing; Node compiles the function in that context. A fix within this PR's stated purpose (global proxy counts as a context) is to route this validator through getGlobalObjectFromContext.

    Verification: pre-existing. Trigger: compileFunction with parsingContext: vm.createContext(vm.constants.DONT_CONTEXTIFY). createContext at src/jsc/bindings/NodeVM.cpp:1497-1499 returns the proxy before the map set, so it is never a map key. The validator at 1872-1877 consults only the map and returns ERR::INVALID_ARG_INSTANCE. The base validator was byte-identical, so merging makes nothing worse.

  • 🟣 src/jsc/bindings/NodeVM.cpp — Host code reading a lazily-initialised accessor through a contextified context's global proxy gets the getter invoked with the host realm as receiver, so the value can come from the wrong realm or the getter can reject the receiver. src/jsc/bindings/NodeVM.cpp:1258 sets the slot's this value to the lexical globalObject argument rather than cell before Base::getOwnPropertySlot at NodeVM.cpp:1262. When the lookup arrives via JSGlobalProxy from the host realm, globalObject is the host global, not the vm global. Fix: set the receiver to cell (the NodeVMGlobalObject) or to its globalThis() so accessors on the vm global see their own realm.

    Why this was flagged

    NodeVMGlobalObject::getOwnPropertySlot at src/jsc/bindings/NodeVM.cpp:1256-1262 reaches try_from_global after the sandbox lookup misses, then calls slot.setThisValue(globalObject) where globalObject is the lexical global passed by the caller, not the cell being inspected. A host-realm access such as vm.runInContext("this", ctx).someLazyGlobal flows through JSGlobalProxy::getOwnPropertySlot with the host global as the lexical global, so any CustomGetterSetter or accessor found on the vm global by Base::getOwnPropertySlot at NodeVM.cpp:1262 runs with the host global as receiver. The dismissal notes the line is unchanged, but this PR makes the global proxy the first-class context object (NodeVM.cpp:1498) and removes the specialSandbox interception that previously answered globalThis before this block, so more host-side reads now flow through this path. Remedy: use cell or cell's globalThis() as the receiver.

    Verification: Pre-existing (line 1258 blames to 9ed8d11, before this PR). Triggering condition: host-realm code reads, through a contextified context's JSGlobalProxy, a name the sandbox chain lacks but that resolves to an accessor in the vm realm. src/jsc/bindings/NodeVM.cpp:1258 sets the host global as the slot's receiver, so the vm realm's __proto__ getter returns the host global's [[Prototype]].

Comment thread src/jsc/bindings/NodeVMScript.cpp Resolved
Comment thread src/jsc/bindings/NodeVM.cpp Resolved
Comment thread src/jsc/bindings/NodeVMScript.cpp Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

The second commit addresses what I raised last round: Script#runInNewContext now resolves an existing context through getGlobalObjectFromContext instead of wrapping it in a second global, and getContextArg no longer allocates the unused placeholder object for DONT_CONTEXTIFY. The remaining inline comments are pre-existing gaps, not regressions from this change.

Beyond those, I also checked that every NodeVMGlobalObject hook (put, getOwnPropertySlot, defineOwnProperty, deleteProperty, getOwnPropertyNames) falls through to the base class when m_sandbox is null, so a DONT_CONTEXTIFY global behaves as an ordinary JSGlobalObject, and that nothing under src/ still references NodeVMSpecialSandbox or its subspace slots after the deletion.

Extended reasoning...

The change deletes the NodeVMSpecialSandbox JSC cell class and its iso-subspace slots, reroutes DONT_CONTEXTIFY contexts to the real JSGlobalProxy, narrows isContext/getGlobalObjectFromContext so a contextified context's global proxy is no longer a context, and makes both runInNewContext entry points reuse a context they are given. It touches no auth, crypto or injection surface, but it rewires property-access hooks on a JSC global object and context identity rules in node:vm, which is behaviour-sensitive engine binding code best confirmed by a human maintainer of the vm bindings. The three inline findings are pre-existing Node-compat gaps rather than regressions introduced here.

Comment on lines +567 to 569
if (!notContextified) {
targetContext->setContextifiedObject(asObject(contextObjectValue));
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 pre-existing, not blocking: pre-existing: Callers of Script#runInNewContext(obj) with a plain object still get an object that is not a context afterwards, unlike Node. NodeVMScript.cpp:567-569 attaches obj as the sandbox of the fresh global but never stores it in vmModuleContextMap, so vm.isContext(obj) stays false, vm.runInContext(code, obj) throws ERR_INVALID_ARG_TYPE, and a second script.runInNewContext(obj) builds another realm. Fix: register obj the way vmModule_createContext does at NodeVM.cpp:1505 (or route Script#runInNewContext through the same createContext path), so the new reuse check at NodeVMScript.cpp:556 finds it on the next call and every entry point contextifies the same way.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

A user runs new vm.Script("var x = []; let l = 1").runInNewContext(obj) with a plain object obj, then vm.isContext(obj), vm.runInContext("x instanceof Array", obj), or script.runInNewContext(obj) again. getGlobalObjectFromContext at NodeVMScript.cpp:556 returns nullptr because obj is not in the map, a fresh NodeVMGlobalObject is created at :562 and :568 calls setContextifiedObject, which only sets m_sandbox (NodeVM.cpp:1082); nothing calls vmModuleContextMap()->set as vmModule_createContext does at NodeVM.cpp:1505. isContext at NodeVM.cpp:843 therefore returns false for obj, getGlobalObjectFromContext throws ERR_INVALID_ARG_TYPE from NodeVM.cpp:809, and a second runInNewContext(obj) takes the create path again. Node's Script#runInNewContext calls createContext(obj) first, so vm.isContext(obj) is true and later runs share the realm. The base branch behaves the same way, so this is pre-existing; the PR's new test at test/js/node/vm/vm.test.ts:1898-1900 only passes an object already made by createContext, so this path is untested.

Verification: pre-existing. Triggered whenever new vm.Script(code).runInNewContext(obj) is called with a plain object. getGlobalObjectFromContext at src/jsc/bindings/NodeVMScript.cpp:556 returns nullptr and :568 only does m_sandbox.set(...); nothing inserts obj into vmModuleContextMap, unlike vmModule_createContext at NodeVM.cpp:1505. The base branch had the same omission.

Comment on lines +541 to 544
if (!notContextified && !contextObjectValue.isObject()) [[unlikely]] {
throwTypeError(globalObject, scope, "Context must be an object"_s);
return {};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 pre-existing, not blocking: pre-existing: callers of Script#runInNewContext with a non-object context (null, a string, a number) get a bare TypeError with no code, where Node throws ERR_INVALID_ARG_TYPE. NodeVMScript.cpp:542 uses throwTypeError with "Context must be an object", so error.code is undefined. Fix: reject every non-object, non-DONT_CONTEXTIFY context at both native entry points with ERR_INVALID_ARG_TYPE named "object" as Node's isContext does, while still accepting undefined (empty object) and the DONT_CONTEXTIFY symbol. Same pattern at 2 sites (NodeVMScript.cpp:542, NodeVM.cpp:1465, which has the code but names the argument "context").
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

new vm.Script("1").runInNewContext(null) reaches scriptRunInNewContext at src/jsc/bindings/NodeVMScript.cpp:539. getContextArg returns false for null, so the check at NodeVMScript.cpp:541 fails and NodeVMScript.cpp:542 calls throwTypeError(globalObject, scope, "Context must be an object"_s), a plain TypeError without a code property. Node's Script#runInNewContext calls createContext, whose isContext runs validateObject and throws ERR_INVALID_ARG_TYPE with message 'The "object" argument must be of type object. Received null', so code written as catch (e) { if (e.code === "ERR_INVALID_ARG_TYPE") ... } behaves differently under Bun. The sibling at src/jsc/bindings/NodeVM.cpp:1465 (reached by vm.createContext(123)) does throw ERR_INVALID_ARG_TYPE but names the argument "context" instead of Node's "object". vm.runInNewContext is unaffected because src/js/node/vm.ts:116-118 validates non-objects first through vm.isContext. The base branch behaves the same at both sites; the diff rewrites both conditions without changing the error.

Verification: pre-existing. Triggered by new vm.Script(code).runInNewContext(x) with a non-object, non-DONT_CONTEXTIFY x. Only vm.runInNewContext has validateContext (vm.ts:116-118). NodeVMScript.cpp:542 runs throwTypeError(globalObject, scope, "Context must be an object"_s), a plain TypeError with no code. Base NodeVMScript.cpp:545-546 is identical, so merging makes nothing worse.

Comment on lines +1477 to +1478
bool optionsOfRunInNewContext = callFrame->argument(2).isTrue();
getNodeVMContextOptions(globalObject, vm, scope, optionsArg, contextOptions, optionsOfRunInNewContext ? optionNames(vm).contextCodeGeneration(vm) : optionNames(vm).codeGeneration(vm), &importer);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 pre-existing, not blocking: pre-existing: callers of vm.runInNewContext() or Script#runInNewContext() with a non-string name or origin option get ERR_INVALID_ARG_TYPE, where Node ignores those keys. NodeVM.cpp:1477-1478 now picks contextCodeGeneration for the runInNewContext path, but getNodeVMContextOptions at NodeVM.cpp:693-710 still validates name/origin for every caller, while Node's runInNewContext only maps contextName/contextOrigin into the context options. Fix: when optionsOfRunInNewContext is set (and in scriptRunInNewContext), skip the name/origin reads, and drop "name"/"origin" from the runInNewContext rows of the test matrix at vm.test.ts:1684-1695, which currently asserts the divergent behaviour.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

vm.runInNewContext("1", {}, { name: 123 }) reaches src/js/node/vm.ts:124 createTrackedContext(..., true) and then vmModule_createContext, which calls getNodeVMContextOptions at NodeVM.cpp:1478. That function reads options.name at NodeVM.cpp:693 and throws ERR_INVALID_ARG_TYPE "options.name" at NodeVM.cpp:697; the same happens via scriptRunInNewContext at NodeVMScript.cpp:550. In Node, runInNewContext's getContextOptions only reads contextName/contextOrigin and never looks at name/origin, so the call succeeds and returns 1. The base branch behaves the same as this PR here, so this is pre-existing, but the diff adds the per-entry-point option-key switch at NodeVM.cpp:1477 and the test at test/js/node/vm/vm.test.ts:1684-1695 codifies that runInNewContext reads name and origin, which Node does not.

Verification: pre-existing. Trigger: vm.runInNewContext(code, ctx, { name: }) or { origin: }. getNodeVMContextOptions at src/jsc/bindings/NodeVM.cpp:693-710 reads options.name/options.origin and throws ERR_INVALID_ARG_TYPE when non-string; Node ignores { name: 123 } there. The test at test/js/node/vm/vm.test.ts:1684-1694 pins that behaviour. Base branch takes the identical route.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants