JavaScript Sandbox Escape: How a Shared Script Could Run Code in the Host, and How to Run Untrusted JavaScript Safely
A JavaScript sandbox escape happens when code that was supposed to stay inside a small, safe set of functions reaches the host instead: its globals, its network, its files, its secrets. In a browser that means the user's session and storage. On a server it means environment variables, API keys and the filesystem.
More products run code their own team did not write than ever before. Trading charts load indicators other users shared. No-code tools run formulas and plugins. AI agents write scripts and run them. Each of these needs a sandbox, and in JavaScript a sandbox is easy to build wrong. This post explains how JavaScript sandbox escapes happen, why the common shortcuts fail, and what a sandbox that holds looks like. It then walks through a real Critical vulnerability from our code review of an open-source Pine Script engine.
What is a JavaScript sandbox escape?
A sandbox is a promise: whatever this code does, it can only touch what we gave it. A sandbox escape breaks that promise. The code finds a route to something it was never meant to reach.
Untrusted code is any code that someone outside your team can write or change:
- Scripts, indicators, formulas or templates that users write or share with each other.
- Plugins and extensions from third parties.
- Code generated by an LLM, especially when the prompt contains content from users or the web.
- Scripts in a small language of your own that you compile to JavaScript before running.
The last one is easy to miss. A custom language feels safe because it is not JavaScript. But if your compiler turns it into JavaScript and runs the result in your page or your server process, the language is only as safe as the compiler's checks. Anything the compiler lets through becomes host code.
As with the AI sandbox escape we covered before, the escape is rarely clever. It is usually a route the limits never covered.
JavaScript sandbox escape techniques
Most JavaScript sandbox bypass techniques fall into a few groups:
- Direct access to globals. Code run with
evalornew Functionsees the global scope:globalThis,fetch,processin Node.js,documentand storage in a browser. - The prototype chain. Every ordinary value, a number, a string or an array, has a prototype chain that leads to the
Functionconstructor. TheFunctionconstructor turns any string into code. - Computed property names. If code can build a property name from strings at runtime, no list of forbidden words can stop it.
- Runtime internals. Objects your engine passes into the script often hold references back to the engine itself, its config or its data provider.
- Fallback paths. An input format that skips the checks, such as "if this is not our language, run it as plain JavaScript".
Why blocklists fail
The first defense most teams try is a blocklist: refuse any code that contains eval, Function, process or constructor. Here is why that does not work:
// A naive blocklist
function looksSafe(code) {
const banned = ['eval', 'Function', 'process', 'globalThis', 'window', 'constructor'];
return !banned.some((word) => code.includes(word));
}
// Passes the check: none of the banned words appears in the text
const userCode = 'const k = "constr" + "uctor"; return (0)[k][k]("return 2 + 2")();';
if (looksSafe(userCode)) {
console.log(new Function(userCode)()); // 4
}The code builds the word constructor from two halves, walks from the number 0 to Number and then to the Function constructor, and runs a new string as code. Here the string only adds two numbers. It could just as well read process.env or call fetch, and the blocklist would never see a forbidden word.
Key point: a sandbox has to allow a closed set of operations and reject everything else. A list of forbidden words is always one string concatenation away from failing.
Node.js sandbox escape: the vm module is not a boundary
Node.js has a vm module, and it looks like a sandbox. Its documentation says plainly that it is not a security mechanism and should not be used to run untrusted code. Code inside a vm context can reach the host through the same prototype-chain techniques shown above.
Even dedicated sandbox libraries struggle. vm2 was discontinued in 2023 after a run of sandbox escapes, revived in 2025, and got another critical escape in January 2026. A Node.js sandbox escape is a recurring class of bug, not a one-off.
Two layers: language-level containment and runtime isolation
A sandbox that holds has two layers:
- Layer 1, language-level containment. Before the code runs, parse it and check the syntax tree. Allow a closed set of identifiers and operations. Reject everything else: unknown names, reserved properties such as
constructorand__proto__, and dynamic property access. - Layer 2, runtime isolation. Run the code somewhere that holds nothing worth stealing: a separate process with no secrets in its environment, a restricted worker, or a sandboxed iframe on a different origin.
The layers do different jobs, so one cannot replace the other. Layer 1 decides what code is allowed to run. Layer 2 decides what a gap in Layer 1 can reach. With only Layer 1, one missed construct reaches your secrets. With only Layer 2, the script still does anything it likes with the data and access you handed it.

Warning:
eval,new Functionand the Node.jsvmmodule are neither layer. They run code; they do not limit it.
A real JavaScript sandbox escape vulnerability
PineTS is an open-source TypeScript engine from LuxAlgo, published on npm as pinets. It runs Pine Script, the language of TradingView indicators, outside TradingView, in Node.js or in the browser. Its stated goal is to reproduce TradingView's behavior exactly. Its README shows two hosts that take scripts as input: a charting library where you add an indicator by passing Pine source, and a CLI that an agent can call as a tool.
Pine indicators are shared between people all the time, and that is the world PineTS was built for. So the question we asked in our review was simple: what can a script from someone else do?
The finding (Critical, CVSS 9.8)
The advisory is GHSA-r762-fqrw-jv2c. We reviewed commit c5e6b0e. The path:
- A host passes a Pine script, marked with
//@version=6, toPineTS.run(). - The Pine front end translates the script to JavaScript. Any name the script does not declare is kept unchanged. In
ExpressionTransformer.tsthe code returns unknown names with the comment "Global/unknown var, return as is". - The generated code is compiled with
new Functioninsrc/transpiler/index.tsand called once per bar. Inside it, the unknown names resolve against the host's global scope. - So a script can name a host global directly, or reach the
Functionconstructor through the prototype chain of an ordinary value, and run any JavaScript with the host's privileges.

A simplified model of the mechanism (not the real PineTS code):
// Simplified model of the transpiler before 0.11.1
function emitIdentifier(name, declaredNames) {
if (declaredNames.has(name)) {
return `scope.${name}`; // a variable the script declared
}
return name; // "Global/unknown var, return as is"
}
// The generated string is compiled and called for every bar.
// Any name the script never declared now resolves against the host.
const runBar = new Function('scope', generatedCode);And a harmless script that shows the effect. It never declares globalThis, so on affected versions the name went straight into the generated code and called the host's real eval:
//@version=6
indicator("demo")
x = globalThis.eval("1 + 1")
plot(x)The same path is reached through stream() and update(), and through every request.security call, which runs the same source again. The advisory also notes that a script could read PineTS's own runtime internals.
The stricter check already existed
PineTS already knows the "Undeclared identifier" error. TradingView rejects undeclared names, and PineTS raises the same error in analyzeInputs.ts. But that check covered only the arguments of input() calls, and even there it skipped names it did not know. Everywhere else, an unknown name went straight into the generated code.
A second route: raw JavaScript input
Source without a //@version marker runs as plain JavaScript. That is intended and documented, because PineTS also has its own JavaScript-based syntax. But it meant a host that passed user text to the engine was also running user JavaScript whenever the marker was missing.
Impact
The advisory describes it as arbitrary code execution. In a browser, the script gets the page's origin, session and storage. In Node.js, it gets the process's environment variables, credentials, filesystem and network. For a charting product that lets users load each other's indicators, one shared indicator can steal the viewer's session or the server's API keys.
Hosts that only run their own scripts are not affected. The advisory names the hosts that are: those that run shared indicators, user uploads or machine-generated scripts.
The fix
PineTS fixed it in version 0.11.1 and published the advisory on November 4, 2026, with credit for the report. Versions below 0.11.1 are affected. The fix has three parts:
- A closed-world verifier checks the generated code right before
new Functioncompiles it, and rejects undeclared identifiers, reserved properties such asconstructor, dynamic member access and several other constructs. It runs by default on the Pine path. - A new
pineOnlytranspile option rejects source without a version marker instead of running it as JavaScript. - Context method dispatch no longer falls through to native JavaScript members.
We ran the harmless demo script above on 0.11.1. It is rejected at transpile time, before any of it runs:
ClosedWorldViolation: Undeclared identifier "globalThis"
What pineOnly changes, simplified from the transpiler source in 0.11.1:
// Simplified from the PineTS transpiler, version 0.11.1
if (pineVersion === null) { // no //@version marker
if (options.pineOnly) {
throw new Error('Pine Script version marker required ...');
}
return source; // treated as JavaScript and run as is
}
// Marker present: Pine is transpiled, and the generated code
// goes through the closed-world verifier before new FunctionThe advisory is also clear about what the fix is not. It is language-level containment, not an OS or VM sandbox. For untrusted scripts it recommends running execution in an isolated realm, such as a locked-down worker or a separate process. That is the two-layer model from above, written by the maintainers themselves. Thank you to the PineTS team for the fix and the clear advisory.
Takeaway: the fix closes Layer 1 for Pine scripts. If your product runs scripts from other people, Layer 2 is still your job.
What we did not prove
- During the review we ran nothing. It was a static review, and the proof of concept in the advisory describes how to check the issue rather than a result we observed on an affected version. After the fix, we ran the harmless demo above on 0.11.1 only to confirm the rejection.
- We did not check whether the charting library or the CLI from the README accept scripts from untrusted people. They live outside the repository.
- The Critical rating assumes a host that runs third-party scripts. For a host that runs only its own scripts, this is not a vulnerability.
- The README also offers a worker variant of the browser engine. A worker narrows what a script can reach but does not remove it. We did not test what remains reachable there.
The pattern
The right check existed, and it guarded only one small part of the input. We saw the same shape in our AI sandbox escape case, where a strict path check guarded writes and not reads, and in our AI agent access control review. When a codebase already has the right check somewhere, the most useful question is where it is missing.
Running user scripts or AI-generated code in your product? We can review how that code is checked and isolated, and look for escape paths like this one before someone else does. Discuss your project
How to run untrusted JavaScript safely
Each practice below closes a different route. Skipping one usually leaves exactly the gap an attacker needs.
1. Decide what counts as untrusted
What to do: list every place your product runs code, and mark which code someone outside your team can write or influence. That includes code your own AI agent generated from user input.
Why: you cannot protect a boundary you have not drawn. Escapes often sit in a path the team never thought of as "running user code", like a fallback format or an import feature.
2. Allow a closed set, do not block a list
What to do: parse the code into a syntax tree and allow only the identifiers and operations your language needs. Reject unknown names, reserved properties (constructor, prototype, __proto__) and computed property access such as obj[name].
Why: the blocklist example above shows how easily forbidden words are rebuilt at runtime. An allowlist fails closed: anything you did not think of is rejected.
Watch out: check the code that will actually run. If you compile your own language to JavaScript, verify the generated JavaScript, not only the source. That is what the PineTS verifier does: it checks the exact string new Function compiles.
3. Remove fallback paths for untrusted input
What to do: give hosts a strict mode that accepts only your language and never raw JavaScript, and use it for every script you did not write. If your engine has no such mode, enforce it before calling the engine:
// Accept only real Pine for scripts you did not write.
// Same marker check PineTS uses to tell Pine from JavaScript.
const PINE_VERSION = /^\s*\/\/\s*@version\s*=\s*(\d+)\s*$/im;
if (!PINE_VERSION.test(userScript)) {
throw new Error('Only Pine Script with a //@version marker is accepted');
}Why: a perfect verifier does nothing if the input can skip it. "Run as JavaScript if it does not look like our language" is a fallback path an attacker controls.
4. Never run untrusted text with eval or new Function in your main realm
What to do: keep eval, new Function, vm.runInContext and similar calls away from untrusted text in the page or process that holds your session, cookies, keys or database access.
Why: these calls give the code everything the realm can reach. There is no option you can pass to them that makes the result a sandbox.
5. Isolate the runtime
What to do: run untrusted code where a successful escape finds nothing. In Node.js, that is a separate process with an empty environment, a time limit and a memory cap, ideally as an unprivileged user in a container with no network:
import { spawn } from 'node:child_process';
const child = spawn(process.execPath, ['--max-old-space-size=128', 'run-script.js'], {
env: {}, // no API keys or tokens from the parent environment
timeout: 5000, // kill scripts that run too long
});
child.stdin.end(JSON.stringify({ script, candles }));In the browser, run it in a sandboxed iframe served from a separate origin, and pass data in and results out with postMessage:
<!-- allow-scripts without allow-same-origin gives the frame an opaque origin:
no access to your page's cookies, storage or DOM -->
<iframe sandbox="allow-scripts" src="https://sandbox.example-usercontent.com/runner.html"></iframe>Why: Layer 1 will have gaps eventually, through a new language feature, a dependency or a mistake. Isolation decides whether a gap becomes a stolen session or nothing at all.
Watch out: a Web Worker on your own origin is not isolation. It can still call fetch with your origin's cookies and open your origin's IndexedDB. A worker helps only inside a frame or process that is already isolated.
6. Limit time, memory and calls
What to do: set a time budget per run, a memory cap and limits on loops, array sizes and any calls that reach the network or a paid API on the host's behalf.
Why: a script that cannot escape can still freeze a user's tab, take down a server worker, or spend the host's API quota. These are reliability problems for every user of a multi-user product.
7. Keep secrets out of reach
What to do: pass the sandbox only the data the script needs. No API keys, no session tokens, no database handles, no references back to your engine's internals.
Why: isolation only helps if the isolated place is empty. A sandbox that holds your production API key is a sandbox worth escaping.
Key point: checks decide what runs, isolation decides what a mistake costs. Products that run other people's code need both.
Running AI-generated code safely
This matters more now that AI agents write code and call tools that run it. A CLI that an agent can call as a tool, fed a script the agent generated from a prompt, is running untrusted code by definition: whoever influences the prompt influences the script. That is prompt injection, and it has no reliable fix at the model level. The fix has to sit where the code runs. Treat agent-written code exactly like a script from a stranger: closed-world checks before it runs, an isolated runtime while it runs, and no secrets within reach.
How we work
We read the project's docs and stated goals first, so we know what it is built for and what it promises. We review the code statically and tie each finding to files and lines, the same way as in our code audits for clients. We report through the project's private vulnerability reporting channel and write about a finding once the advisory is public.
FAQ
What is a JavaScript sandbox escape?
A JavaScript (JS) sandbox escape is any way for code that should be limited to a small set of functions to reach the host's globals, network, files or secrets. In the case above, a Pine script reached host JavaScript globals because the compiler kept undeclared names unchanged in the code it generated.
What are common JavaScript sandbox escape techniques?
Reaching globals through eval or new Function, walking the prototype chain from an ordinary value to the Function constructor, building forbidden property names from strings at runtime, reading references to the engine's internals, and using a fallback input path that skips the checks.
Is the Node.js vm module a sandbox?
No. The Node.js documentation says the vm module is not a security mechanism and should not be used to run untrusted code. A Node.js sandbox escape from vm usually takes one line. Use a separate process with no secrets in its environment instead.
How do you run untrusted JavaScript safely?
Use two layers. First, parse the code and allow only a closed set of names and operations. Second, run it in an isolated runtime that holds nothing worth stealing, such as a separate process or a sandboxed iframe on another origin. Never run it with eval or new Function in your main page or server process.
Is new Function safer than eval?
Only slightly. new Function cannot see local variables, but it still runs in the global scope, with access to globals, the network and, in Node.js, the process. It is not a JavaScript sandbox.
Can a shared Pine Script indicator run code on my machine?
It depends on the engine that runs it. In PineTS before version 0.11.1, yes: a Pine script could run arbitrary JavaScript in the host page or process. Upgrade to 0.11.1 or later, accept only scripts with a Pine version marker (that is what the transpiler's pineOnly option enforces), and run them in an isolated worker or process.
How do you run AI-generated code safely?
Treat it as untrusted code, because anyone who can influence the prompt can influence the code. Check it against a closed set of allowed operations before it runs, run it in an isolated process or frame with no secrets, and limit its time and memory.
We review products that run user scripts, plugins and AI-generated code by hand, with every finding tied to specific files. Tell us about your product.
About the author
Aleksandr Tynianov is CTO at Krasty Soft. He found and reported this vulnerability to the PineTS team and is credited on the advisory. He leads Krasty Soft's code audits of AI agents, developer tools and open-source libraries, and his reports have led to credited GitHub security advisories across several projects.