sandbox
Declare a Linux sandbox in a luna, and run commands, processes and files in it with ctx.sandboxes.
sandbox declares a Linux machine of the luna’s own under the luna type’s sandboxes option. A handler drives it as ctx.sandboxes.<name>, and it starts on first use.
import { defineLuna, sandbox, t } from "luna";
export const User = defineLuna({
name: "User",
key: { id: t.string() },
sandboxes: {
dev: sandbox({ image: "ghcr.io/acme/tools@sha256:<DIGEST>", memory: "1GB" }),
},
handlers: (h) => ({
test: h({}, async (ctx) => {
const r = await ctx.sandboxes.dev.exec("npm test", { cwd: "/home/app" });
return { ok: r.exitCode === 0, out: r.stdout };
}),
}),
});
Reference
sandbox(options)
imagestring
An OCI image pinned by digest, such as `ghcr.io/acme/tools@sha256:…`, and when the digest names an index, the build for the machine's architecture is used.
stringcpu?number | { max: number; default?: number }
Virtual CPUs, and with `max`, each instance starts with `default` and can be resized from 1 to `max`.
number | { max: number; default?: number }1memory?string | { max: string; default?: string }
Memory as `"512MB"` or `"2GB"`, and with `max`, each instance starts with `default` and can be resized from `"256MB"` to `max`.
string | { max: string; default?: string }"512MB"disk?string
The size of `/home`, and of the writable layer over the image.
string"4GB"idle?string | number
Powers it off after this long with no request.
string | number"5m"persist?"none" | "filesystem" | "freeze"
What is kept when it stops: nothing, its disks, or its disks with its memory and processes where that can be done.
"none" | "filesystem" | "freeze""filesystem"network?"none" | "public" | { allow: string[] }
What it can reach: nothing, as it has no network device, the internet, or only the names listed, such as `"*.github.com"`.
"none" | "public" | { allow: string[] }"none"privateNetwork?boolean
Puts it on a network with this luna's other such sandboxes, as `<name>.sandbox.internal`.
booleanfalseports?number[]
The ports the luna reaches with `port(n)`.
number[]Sizes take MB, GB or TB, such as "1.5GB".
Sandbox
namestring
The instance's name.
stringfilesSandboxFiles
The files of its `/home` volume.
SandboxFilesexec(command, opts?)Promise<ExecResult>
Runs a command and waits for it, where a string goes to `/bin/sh -c` and an array runs as it is.
Promise<ExecResult>spawn(command?, opts?)Promise<SandboxProcess>
Starts a process that runs on after this call, and with no command, a login shell.
Promise<SandboxProcess>attach(name)SandboxProcess
A process started before, by its name.
SandboxProcessprocesses()Promise<ProcessInfo[]>
Its processes: those running, and those that ended whose output is kept.
Promise<ProcessInfo[]>port(n)SandboxPort
A declared port, to send HTTP requests to or hand to an app.
SandboxPortterminal(opts?)Promise<SandboxTicket>
A ticket for an app to connect to a process as a terminal, over a WebSocket.
Promise<SandboxTicket>ssh()Promise<SandboxSsh>
How to reach it over SSH, which the luna's `onSshConnect` hook allows.
Promise<SandboxSsh>status()Promise<SandboxStatus>
Its state, size and last use, without starting it.
Promise<SandboxStatus>list()Promise<SandboxStatus[]>
Every instance of this declaration the luna has.
Promise<SandboxStatus[]>instance(name, size?)Sandbox
Another instance of this declaration, which starts on first use with `size` if it is new.
Sandboxfork(name)Promise<Sandbox>
A new instance with a copy of this one's disks as they are now.
Promise<Sandbox>resize(size)Promise<{ cpu: number; memoryMib: number }>
Sets its size, at once if it runs or for its next start, for a resizable declaration.
Promise<{ cpu: number; memoryMib: number }>stop()Promise<void>
Powers it off now, keeping what `persist` says.
Promise<void>freeze()Promise<void>
Saves its memory and processes with its disks, so the next use carries on from there.
Promise<void>destroy()Promise<void>
Deletes it and everything kept of it.
Promise<void>SandboxPort
portnumber
The port.
numberfetch(path, init?)Promise<Response>
Sends an HTTP request with `method`, `headers`, `body` and `timeout`, wakes the sandbox for it, and returns up to 16 MiB.
Promise<Response>connect()Promise<SandboxTicket>
A ticket for an app to reach the port over a WebSocket whose binary messages are the bytes each way.
Promise<SandboxTicket>publicUrl()Promise<string>
A public HTTPS address for the port while the sandbox runs, the same every time, where your plan allows it.
Promise<string>revokePublicUrl()Promise<void>
Takes the public address down.
Promise<void>A port works whether or not the sandbox has a network.
SandboxFiles
Paths are relative to /home, or absolute within it.
read(path, opts?)Promise<Uint8Array>
A file's bytes, from `opts.offset` for `opts.length` bytes.
Promise<Uint8Array>text(path)Promise<string>
A file as UTF-8 text.
Promise<string>write(path, data, opts?)Promise<number>
Writes a file with any directories it needs, with `opts.mode`, and returns its size.
Promise<number>list(path?)Promise<FileInfo[]>
The entries of a directory, `"."` by default.
Promise<FileInfo[]>stat(path)Promise<FileInfo | null>
What is at `path`, or `null`.
Promise<FileInfo | null>remove(path, opts?)Promise<boolean>
Removes a file, or a directory with `opts.recursive`, and says whether there was one.
Promise<boolean>mkdir(path)Promise<void>
Makes a directory.
Promise<void>copyTo(bucket, from, to?, opts?)Promise<void>
Copies a file of up to 256 MiB to a bucket, with `opts.contentType`.
Promise<void>copyFrom(bucket, from, to?)Promise<void>
Copies an object from a bucket into the volume, waking the sandbox.
Promise<void>SandboxProcess
namestring
The process's name in its sandbox.
stringat{ stdout: number; stderr: number }
How far its output has been read, which you may set to read again from there.
{ stdout: number; stderr: number }read(opts?)Promise<ProcessOutput>
What it wrote since the last read, waiting up to `opts.wait` and at most a minute, `opts.max` bytes at most.
Promise<ProcessOutput>text(opts?)Promise<{ stdout: string; stderr: string; lost: number; exit: ProcessExit | null }>
`read`, as text.
Promise<{ stdout: string; stderr: string; lost: number; exit: ProcessExit | null }>write(data)Promise<void>
Writes to its input.
Promise<void>end()Promise<void>
Closes its input.
Promise<void>resize(cols, rows)Promise<void>
Sets its terminal's size.
Promise<void>kill(signal?)Promise<void>
Sends it and everything it started a signal, `"TERM"` by default.
Promise<void>wait(timeout?)Promise<ProcessExit | null>
How it ended, waiting up to `timeout`, `"1m"` by default and at most, and `null` if it still runs.
Promise<ProcessExit | null>remove()Promise<void>
Ends it if it runs, and forgets it and its output.
Promise<void>ExecOptions and ExecResult
cwd?string
The working directory.
string"/home"env?Record<string, string>
Environment variables.
Record<string, string>timeout?string | number
Stops the command and everything it started after this long.
string | number"5m"stdin?string | Uint8Array
Written to its standard input.
string | Uint8Arrayexec returns an ExecResult.
exitCodenumber | null
Its exit code, or `null` if a signal ended it.
number | nullstdoutstring
Its standard output.
stringstderrstring
Its standard error.
stringtimedOutboolean
Whether `timeout` stopped it.
booleantruncatedboolean
Whether output past 16 MiB on either stream was dropped.
booleanSpawnOptions
name?string
A name to `attach` by, unique in the sandbox, of letters, digits, `-`, `_` and `.`, and without one it gets a name of its own.
stringpty?boolean | { cols: number; rows: number }
Runs it on a terminal, 80 by 24 for `true`, with its output and errors together.
boolean | { cols: number; rows: number }cwd?string
The working directory.
string"/home"env?Record<string, string>
Environment variables.
Record<string, string>user?string
A user of the image to run as.
stringrootkeepAwake?boolean
Keeps the sandbox, and its luna, awake while it runs.
booleanfalsebuffer?string
How much of its output is kept to read back, at most `"64MB"`.
string"1MB"TerminalOptions
TerminalOptions takes cwd, env, user, keepAwake and buffer as in SpawnOptions, and these.
name?string
The process to join, started first if it does not run, and kept when the connection goes, while one with no name ends with its connection.
stringcommand?string | string[]
What to start, a login shell by default.
string | string[]pty?boolean | { cols: number; rows: number }
Its terminal's size to begin with, or `false` for none.
boolean | { cols: number; rows: number }80 by 24replay?number
How many bytes of what a named process wrote before are sent first, all that is kept by default.
numberSandboxTicket and SandboxSsh
pathstring
The path to open as a WebSocket on your app's URL, such as `/_luna/sandbox/connect?ticket=…`.
stringticketstring
The ticket.
stringexpiresMsnumber
When it stops working, a minute after it was made, in milliseconds since the epoch.
numberA ticket works once. ssh() returns a SandboxSsh.
hoststring
The host to connect to.
stringportnumber
The port to connect to.
numberuserstring
The SSH login name, which names this sandbox and is the same every time.
stringhostKeystring
The host key, as `ssh-ed25519 AAAA…`, for a `known_hosts` line of `[host]:port` and this.
stringcommandstring
The command to connect, `ssh -p <port> <user>@<host>`.
stringSandboxStatus and SandboxSize
namestring
The instance's name.
stringstate"running" | "asleep" | "frozen" | "none"
Running, stopped with its disks, stopped with its memory and processes too, or no such sandbox.
"running" | "asleep" | "frozen" | "none"cpunumber
The CPUs it has, or will start with.
numbermemoryMibnumber
The memory it has, or will start with, in MiB.
numbermax?{ cpu: number; memoryMib: number }
The most it can be resized to, for a resizable declaration.
{ cpu: number; memoryMib: number }createdMs?number
When it was made.
numberlastUsedMs?number
When it was last used.
numberdiskUsedBytes?number
What its disks hold.
numberstartedMs?number
When it started, while it runs.
numberconnections?number
The connections open to it, while it runs.
numberstoppedBy?"idle" | "code" | "luna" | "crash"
Why it last stopped: no use, its luna's code, its luna sleeping or moving, or it ended by itself.
"idle" | "code" | "luna" | "crash"stoppedMs?number
When it last stopped.
numberTimes are milliseconds since the epoch. A SandboxSize is { cpu?: number; memory?: string }, with memory as "2GB".
ProcessInfo, ProcessOutput and ProcessExit
namestring
Its name.
stringpidnumber
Its process id.
numberptyboolean
Whether it runs on a terminal.
booleancommandstring
What it runs.
stringstartedMsnumber
When it started, in milliseconds since the epoch.
numberkeepAwakeboolean
Whether it keeps the sandbox awake.
booleanrunningboolean
Whether it still runs.
booleanexitProcessExit | null
How it ended.
ProcessExit | nullstdoutnumber
How many bytes it wrote to standard output.
numberstderrnumber
How many bytes it wrote to standard error.
numberread returns a ProcessOutput.
stdoutUint8Array
Standard output since the last read.
Uint8ArraystderrUint8Array
Standard error since the last read.
Uint8Arraylostnumber
Bytes written before these that are no longer kept, because its buffer was full.
numberexitProcessExit | null
How it ended, once all it wrote has been read.
ProcessExit | nullA ProcessExit is { exitCode: number | null; signal: number | null }: its exit code, or the signal that ended it.
FileInfo
namestring
The entry's name.
stringtype"file" | "dir" | "symlink"
What it is.
"file" | "dir" | "symlink"sizenumber
Its size in bytes.
numbermodenumber
Its permission bits.
numbermtimeMsnumber
When it last changed, in milliseconds since the epoch.
numberGood to know
- An image with a tag and no digest is refused when the luna type is defined. An image unpacks to at most 32 GiB.
- A process does not keep an idle sandbox running unless it was spawned with
keepAwake. - A named process runs until it ends or is killed, and its output stays readable after.
- A command that must outlive the call runs with
spawn, and later calls read it withattach. - Reading its files works while the sandbox is asleep.
resizeis refused when the sandbox uses more memory than it would be left with. A sandbox is billed at the size it is set to.- Private addresses are never reachable from a sandbox.
internet: falseon the luna type also turns the internet off for its sandboxes. - A request for more CPU, memory or disk than Luna allows is refused. Your plan also caps how many sandboxes run at once. See Limits.
Examples
Run a dev server and read its output
serve: h({}, async (ctx) => {
const p = await ctx.sandboxes.dev.spawn("npm run dev", { name: "server", cwd: "/home/app", keepAwake: true });
return p.name;
}),
logs: h({}, async (ctx) => {
const out = await ctx.sandboxes.dev.attach("server").text({ wait: "5s" });
return { text: out.stdout, lost: out.lost, exit: out.exit };
}),
Write and read files
files: h({}, async (ctx) => {
const files = ctx.sandboxes.dev.files;
await files.write("app/notes.txt", "hello");
const list = await files.list("app");
return { text: await files.text("app/notes.txt"), names: list.map((f) => f.name) };
}),
Make a sandbox resizable
sandboxes: {
dev: sandbox({
image: "ghcr.io/acme/tools@sha256:<DIGEST>",
cpu: { max: 4 },
memory: { max: "8GB", default: "1GB" },
disk: "10GB",
network: "public",
ports: [3000],
}),
},
grow: h({}, async (ctx) => ctx.sandboxes.dev.resize({ cpu: 4, memory: "8GB" })),
Call a server in the sandbox
health: h({}, async (ctx) => (await ctx.sandboxes.dev.port(3000).fetch("/health")).status),
Hand an app a terminal
shell: h({}, async (ctx) => ctx.sandboxes.dev.terminal({ name: "shell", cwd: "/home/app" })),
The app opens the ticket’s path on your app’s URL as a WebSocket within a minute.
Try a change on a copy
branch: h({ args: { name: t.string() } }, async (ctx, { name }) => {
const copy = await ctx.sandboxes.dev.fork(name);
return (await copy.exec(["git", "status"])).stdout;
}),