Run untrusted code
Run JavaScript that a customer wrote or a model generated in an isolate, with its own memory, CPU and time limits, and only the tools you give it.
A customer’s formula or a model’s generated script must never run inside your handler. There it could read the luna’s tables and secrets, reach the internet, and loop until Luna stops the handler.
An isolate runs that code apart. Each run gets a fresh JavaScript engine of its own, sees only the input and tools you pass, and stops at the limits you set.
Run a snippet
Declare an isolate under isolates with isolate, then call run on ctx.isolates.<name>.
import { defineLuna, isolate, t } from "luna";
export const User = defineLuna({
name: "User",
key: { id: t.string() },
isolates: {
formula: isolate({ cpu: "100ms" }),
},
handlers: (h) => ({
evaluate: h({ args: { code: t.string(), points: t.int() } }, async (ctx, { code, points }) => {
const { result } = await ctx.isolates.formula.run(code, { input: { points } });
return result;
}),
}),
});
An expression, such as input.points * 2, is its own result. Anything else runs as the body of an async function, and return gives the result.
The code reads input as a JavaScript value, and its result comes back the same way. Both pass as JSON, so they hold only what JSON can. Nothing is kept from one run to the next.
Set its limits
cpu is required. The other limits have defaults.
| Option | Does |
|---|---|
cpu |
The most CPU time one run may use, such as "2s" |
memory |
The most memory one run may use, as "64MB" or "1GB". "64MB" by default |
timeout |
The longest one run may take, waiting on tools included. "10s" by default |
network |
What its fetch can reach. Nothing by default, and then it has no fetch |
agent: isolate({ memory: "128MB", cpu: "2s", timeout: "30s", network: { allow: ["api.example.com"] } }),
Handle a failed run
A run that throws, or that a limit stops, rejects with an IsolateError. Its name says what happened, its message says why, and its logs hold what the code logged before it failed.
try {
const run = await ctx.isolates.formula.run<number>(code, { input: { points: 10 } });
return { ok: true, value: run.result };
} catch (e) {
if (e instanceof IsolateError) return { ok: false, error: e.name, message: e.message };
throw e;
}
name |
The run |
|---|---|
The error’s own name, such as TypeError |
Threw an error |
CpuLimitExceeded |
Used its cpu |
MemoryLimitExceeded |
Used its memory |
TimeoutExceeded |
Ran past its timeout |
ResultTooLarge |
Returned a result over 32 MiB |
When a limit stops a run, Luna also writes a warning to the luna’s logs, even if your code catches the error. It writes at most one a second for each isolate and limit. Read them with Read logs.
Read what it logged
A run that ends well returns an IsolateResult. The code’s console.log, info, warn, error and debug lines are in it, not in your luna’s logs.
| Field | Holds |
|---|---|
result |
What the code returned |
logs |
Each line as { level, message } |
logsTruncated |
true when lines past 1 MiB were dropped |
cpuMs |
The CPU time the run used |
Give it tools
A tool is a function of yours that the code calls as tools.<name>(...). Tools run in your luna, so they can read its tables while the snippet sees only what they return.
withTools: h({ args: { code: t.string() } }, async (ctx, { code }) => {
const tools = {
total: () => ctx.db.scores.find().reduce((sum, s) => sum + s.points, 0),
};
return (await ctx.isolates.formula.run(code, { tools })).result;
}),
In the snippet, every tool returns a promise, so the code writes await tools.total(). Arguments and results pass as JSON. A tool that throws rejects the snippet’s call with the error’s message. Tool names may not start with __.
Let it reach the internet
With network, the code gets a fetch of its own. "public" reaches any public address. { allow: [...] } reaches only those host names, and "*.example.com" covers every name under example.com.
Each redirect is checked against the rule before it is followed. Only http and https URLs work, and a response body is read up to the run’s memory or 16 MiB, whichever is smaller.
The snippet’s fetch answers with status, ok, headers.get(name), text() and json(). Reach the internet covers the addresses Luna always refuses.
What a snippet cannot use
A snippet has the JavaScript language and console, and nothing of Node. It has no ctx, no file system, no timers and no modules. WebAssembly, SharedArrayBuffer and Atomics are removed.
Stateless luna types can declare isolates too. For a program that needs a whole Linux machine, use Run a sandbox.
Next steps
- isolate lists every option and type.
- Run a sandbox compares isolates with sandboxes.
- Track usage shows the CPU your isolates use.