Running untrusted JavaScript in a workflow: how the Run code step stays sandboxed
How the Emberblocks Run code step runs builder JavaScript in QuickJS compiled to WebAssembly: why not node:vm, a fresh runtime per run, and hard limits.
Published 11 min read
On this page
Emberblocks workflows have a Run code step: a box where a builder writes plain JavaScript that loops over found records, reshapes data or does math a formula cannot. That code runs on our server, in the same process that holds the credentials for every workspace's data. So it runs inside QuickJS compiled to WebAssembly, in a fresh runtime that is thrown away after each run, with a 5 second clock, a 64 MB memory ceiling and nothing from the host in reach. There is no process, no require and no fetch, because they never existed in that world.
This post explains why we picked that design over the obvious alternatives, how a run is set up and torn down, the exact limits, and what a builder can do with the step. At the end there is a short note on the other place builder code runs: code blocks, which live in a sandboxed frame in the browser.
The problem: user code next to service-role credentials
A workflow step runs on the server, not in the viewer's browser. The process that executes it has to read and write app data for every workspace, so it holds service-role credentials. Builder code must never share a world with that process.
The person writing the code is a builder, and a builder can already do a lot on purpose: point a Call webhook step at any URL, email anyone, update rows with the workflow's authority. The Run code step must not add anything to that list. It should add compute, not authority: the code gets the data its own workflow already reads, and nothing else. And the design has to hold up against the worst possible author, not the typical one.
Two more constraints come from where we deploy. Emberblocks runs on Vercel serverless functions, so there is no Docker daemon to start a container from and no sidecar process to hand code to. And a warm function instance serves request after request, so a step from one workspace can run in the same process that just ran a step for another.
Why not node:vm, isolated-vm or a container?
node:vm: not a security boundary
Node ships a vm module that runs code in a separate context, and it is tempting because it costs nothing to set up. Node's own documentation opens the page with a warning in bold: the module is not a security mechanism, and you should not use it to run untrusted code. A vm context is a separate set of globals inside the same process, not a wall around it. Our sandbox file says it plainly in its header: node:vm is never an acceptable fallback here, because the process holds service-role credentials.
Libraries that harden vm, such as vm2, still run guest code in the host process. vm2's own README says new bypasses will likely be discovered, that it should not be your only line of defense, and that code from completely untrusted sources calls for something with stronger isolation. That is our exact case.
isolated-vm: real isolates, wrong host
isolated-vm gives each guest its own V8 isolate, which is a genuine boundary. But it is a native addon: installing it needs a compiler, and the compiled binary has to match the Node version that runs it. On a serverless platform where we do not control the build image or the runtime, that is fragile. Its README also lists the project as being in maintenance mode, and it suggests keeping isolates in a different process from critical infrastructure, which a single serverless function cannot do.
A container or a separate service per run
Process isolation is the strongest option in general, and it is the honest fallback if the WebAssembly route ever fails us: a separate, locked-down endpoint that does nothing but evaluate code. For a step that mostly sums a column, though, a cold container per run adds seconds of latency, a second deployment to secure and a network hop that carries row data out of the function. We wanted the boundary inside the function instead.
QuickJS in WebAssembly as the boundary
QuickJS is a small, embeddable JavaScript engine created by Fabrice Bellard. The quickjs-emscripten project compiles it to WebAssembly and describes the result as able to evaluate untrusted JavaScript, supporting most of ES2023. We use quickjs-emscripten-core with the single-file release build, which embeds the WebAssembly binary in the JavaScript module as base64. That makes it ordinary JavaScript to the bundler: no native build, and no .wasm file that has to survive deployment.
The boundary is the WebAssembly memory model. Guest code lives in its own linear memory and can only touch objects inside the engine. The project's README says that by default no host functionality is exposed to code running inside QuickJS. That is the property we care about: process, require, fetch, the file system and the network are not removed or blocked. They were never part of the guest's world, so there is nothing to find.
We wrote our own thin wrapper rather than a higher-level package, so every capability inside the sandbox is one we added by hand. There is exactly one: a console that turns its arguments into text and hands two strings (a level and a line) to a host function that appends them to a log buffer. Everything else the code can use is the JavaScript standard library: Math, JSON, Date, String, Array, RegExp and the rest.
Data crosses the boundary only as JSON text. The host serializes input to a string, and the guest program parses it with JSON.parse. The builder's code runs as the body of one strict-mode function. Its return value is serialized with JSON.stringify inside the guest, and the host reads back exactly one string and parses it. No live object ever passes between the two sides, so there is no shared reference to walk across.
A fresh runtime for every run
Compiling the WebAssembly module takes tens of milliseconds, so it happens once per warm function instance and is reused. The module itself holds no state from any run. Everything stateful is created for one execution and destroyed after it:
const runtime = QuickJS.newRuntime();
try {
runtime.setMemoryLimit(MEMORY_LIMIT_BYTES); // 64 MB
runtime.setMaxStackSize(STACK_SIZE_BYTES); // 1 MB
runtime.setInterruptHandler(() => Date.now() > deadline); // 5 s
const context = runtime.newContext();
try {
// input goes in as JSON text; one JSON string comes back out
const result = context.evalCode(guestProgram(code, inputJson), "step.js", { type: "global" });
// ...read the string, enforce the 64 KB output cap, JSON.parse on the host
} finally {
context.dispose();
}
} finally {
runtime.dispose();
}- Never reused. A runtime is never shared between steps, between runs, or between workspaces that happen to land on the same warm instance. Nothing a step leaves behind, such as a global it set or a prototype it changed, survives to the next one.
- Disposed in
finally. Success, a thrown error, a timeout or a memory error all end the same way: the context and runtime are freed before the function returns. - Never throws to the engine. Every failure becomes a result with a builder-facing message, so a misbehaving step fails its own run and leaves the process healthy for the next request.
- Stopped from the outside. QuickJS calls the interrupt handler periodically while code runs. Ours compares the clock with the deadline, so a
while (true) {}stops at 5 seconds instead of holding the function.
The limits on every Run code step
The limits live as constants at the top of the sandbox file, in one place. When code hits one, the step fails, the run fails with it, and the message in run history says what happened.
| Limit | Value | Enforced by | When code goes over |
|---|---|---|---|
| Wall clock per execution | 5 seconds (5,000 ms) | Interrupt handler checking a deadline | Stopped, with "the code ran past the 5 second limit and was stopped" |
| Guest memory | 64 MB | Runtime memory limit | Stopped, with "the code used more than its 64 MB memory limit and was stopped" |
| Guest stack | 1 MB | Runtime maximum stack size | Deep recursion throws inside the guest and the step fails with that error |
| Returned value | 64 KB as JSON | Host, after reading the string back | The step fails and asks you to return less data |
| Console output | 50 entries or 8 KB of text | The console shim | Later lines are dropped and one "… logs truncated" line is added |
Runaway code ends inside the guest: an endless loop at the deadline, a memory bomb as an out-of-memory error rather than a crashed host. The host and whatever else it is serving carry on, which is exactly what node:vm cannot promise.
What builders can do with a Run code step
The expression language covers one value from one formula, and that handles most workflows. Run code is for the cases with a loop or intermediate state in them: group found rows by a field, dedupe by email, compute a weighted average or a running balance, build the exact JSON array a webhook expects, or pull fields out of the text an Ask Ember step returned.
The code is the body of one function. input holds everything it may read:
input.trigger: the trigger type, table name, row ID, the row itself keyed by field label, and the email of the person who triggered it (null for schedules).input.steps: earlier steps of this run that produced output, keyed by step name. A Find records step arrives as{ kind, count, truncated, rows }, Ask Ember as{ kind, text }, a Call API step as{ kind, status, json, text }and an earlier Run code step as{ kind, value }with its value still structured.input.now: the run's start time as ISO text, the same momentNOW()returns in formulas. Use it instead ofnew Date()so a run computes one consistent time.input.app.nameandinput.mode("published" or "draft").
Everything is JSON: dates are ISO strings, and a reference field arrives as the linked row's ID. Here is a weekly workflow: a schedule trigger, a Find records step named "Overdue invoices", this Run code step named "Overdue summary", then a Send email step whose body is STEP("Overdue summary", "value").
// Total overdue balance per client, one line each.
const found = input.steps["Overdue invoices"];
if (found.truncated) {
console.warn("More matches than the Find records limit: totals are partial");
}
const totals = {};
for (const row of found.rows) {
const client = row["Client"] || "No client";
totals[client] = (totals[client] || 0) + Number(row["Amount"] || 0);
}
const lines = Object.entries(totals)
.sort((a, b) => b[1] - a[1])
.map(([client, amount]) => client + ": " + amount.toFixed(2));
console.log(found.count + " overdue invoices across " + lines.length + " clients");
return lines.join("\n");A few details from the step's contract:
- Return a JSON value. Text, a number, a boolean, an object, an array or null. Returning nothing gives
null. A value JSON cannot carry, such as a cycle or aBigInt, fails the step by name instead of turning silently into null. - Formulas see text or primitives.
STEP("Overdue summary", "value")returns text, numbers and booleans as themselves, and an object or array as its JSON text. A later Run code step reads the same output fully structured frominput.steps. - Errors stop the run. A thrown error fails the step, and later steps do not run. Run history shows the message, the console lines, how long the code took and a preview of what it returned, never the code itself, which stays in the app definition.
- Try it before publishing. "Run with sample data" runs the code against the trigger table's first row. Earlier Find records steps run for real, since they only read, while Ask Ember and Call API steps get placeholder output, so a test never spends AI credits or calls an outside system. Nothing is written and no run is recorded.
- Publish checks the syntax. Drafts save whatever you type, because code is half-written most of the time. Publishing compiles the code to check its syntax, without running it, and blocks on a syntax error.
- No network. There is no
fetch. Put a Call API step before the code and read its response frominput.steps, or put a Call webhook step after it to send what the code returned.
The step itself cannot write or call anything, so running it again can only recompute. Every write happens in the steps around it. The workflows guide covers triggers, the other steps and how chaining works.
The other sandbox: code blocks in the browser
Builders can also write HTML, CSS and JavaScript for a block inside an app. That code runs in the viewer's browser, so it gets a different boundary built from browser primitives. The code becomes the document of an iframe with sandbox="allow-scripts" and nothing else, loaded inline through srcdoc, which gives it an opaque origin: as far as the browser is concerned it belongs to no site.
- No cookies and no storage, so the viewer's session never enters the frame.
- No reach into the page around it, and no top-level navigation, popups or form submission.
- No network by default. A template lists the
httpshosts it needs, and only those open up. - Writes go through a small bridge that only does what the template declares, then land on the same server routes forms and buttons use, where the viewer's role, row filters and field permissions apply.
The two sandboxes share one idea: the code gets an explicit, short list of things it may do, and everything else does not exist for it. The code blocks guide covers that side in full, and the post on connecting AI assistants through MCP applies the same idea to tools an AI model calls.
Questions people ask
- Can a Run code step call an external API?
- Not from inside the code: there is no fetch in the sandbox. Put a Call API step before the code and read its response from input.steps, or put a Call webhook step after it to send the value the code returns.
- Can I use npm packages in a Run code step?
- No. There is no require and no module loader. The code has the JavaScript standard library (Math, JSON, Date, String, Array, RegExp and so on). Small helper functions can go at the top of the step.
- Can the code see my database credentials or another workspace's data?
- No. Only the input object crosses into the sandbox, built from this run's trigger row and earlier step outputs. Each execution gets a fresh QuickJS runtime that is disposed when it ends, so nothing carries over between runs or workspaces.
- What happens when the code throws or runs too long?
- The step fails and the run stops, so later steps do not execute. Run history shows the error message and any console lines. Code that runs past 5 seconds or uses more than 64 MB of memory is stopped with a message naming the limit.
- Why not just use Node's vm module?
- Node's documentation says the vm module is not a security mechanism and should not be used to run untrusted code. A vm context shares the host process, and our process holds service-role credentials, so it is never an option here.
Sources
Written by Apostolos Papadopoulos
Apostolos builds Emberblocks, a visual app builder for internal tools on your own data, from Thessaloniki, Greece. Spotted something wrong or out of date? Write to hello@emberblocks.com.