---
title: Connect to a sandbox
description: Open a terminal in a sandbox from an app, reach a port of it, and let people in over SSH, with the luna deciding who may.
related:
  - /files-and-code/run-processes-in-a-sandbox
  - /sdk/sandbox
  - /http/check-who-is-calling
---

An app may need a sandbox itself: a terminal in the browser, a dev server's port, an editor over SSH. Luna gives no one a way in by default. The luna hands out each way in, so it decides who connects.

## Open a terminal from an app

`terminal` returns a ticket for one connection. The app opens it as a WebSocket within a minute, and the sandbox starts when it connects.

```ts luna/lunas/user.ts
import { defineLuna, sandbox, t } from "luna";

export const User = defineLuna({
  name: "User",
  visibility: "public",
  key: { id: t.string() },
  sandboxes: {
    box: sandbox({ image: "<IMAGE>" }),
  },
  handlers: (h) => ({
    terminal: h({}, (ctx) => ctx.sandboxes.box.terminal({ name: "main", cwd: "/home/app" })),
  }),
});
```

The ticket's `path` goes after the app's `LUNA_URL`, with `ws` in place of `http`. A ticket works once, and the request carries no key.

```ts app/terminal.ts
import { createClient } from "luna/client";
import type { User } from "../luna/lunas/user.ts";

const LUNA_URL = process.env.LUNA_URL!;
const client = createClient({ url: LUNA_URL, key: process.env.LUNA_KEY });

export async function openTerminal(userId: string, show: (text: string) => void) {
  const ticket = await client.luna<typeof User>("User", userId).mutate("terminal", {});
  const socket = new WebSocket(LUNA_URL.replace(/^http/, "ws") + ticket.path);
  socket.binaryType = "arraybuffer";
  const decoder = new TextDecoder();
  socket.onmessage = (e) => {
    if (typeof e.data === "string") console.log(JSON.parse(e.data));
    else show(decoder.decode(e.data as ArrayBuffer, { stream: true }));
  };
  return {
    type: (keys: string) => socket.send(new TextEncoder().encode(keys)),
    resize: (cols: number, rows: number) => socket.send(JSON.stringify({ type: "resize", cols, rows })),
  };
}
```

Binary messages carry the bytes typed and the bytes written, each way. Text messages are JSON about the connection.

| Sent by | `type` | Means |
| --- | --- | --- |
| Luna | `ready` | The connection is open. Comes first |
| Luna | `stderr` | Error output in base64 `data`, for a process without a terminal |
| Luna | `lost` | Output was dropped before it was sent |
| Luna | `exit` | The process ended, with `exitCode` and `signal`. The socket closes next |
| Luna | `error` | The connection failed, with a `message`. The socket closes next |
| The app | `resize` | Sets the terminal to `cols` and `rows` |
| The app | `signal` | Sends the process a signal, such as `"INT"` |
| The app | `eof` | Closes the process's input |

The socket closes with code 1000 when the process ends, 1001 when the sandbox stops, and 4000 when the connection fails.

## Choose what the terminal runs

| Option | Does |
| --- | --- |
| `name` | Joins the process of this name, starting it first if it does not run. A named process stays when the connection goes. Without a name, it ends with the connection |
| `command` | What to start. A login shell by default |
| `pty` | The terminal's size to begin with, 80 by 24 by default. `false` for none |
| `replay` | How many bytes of a named process's earlier output to send first. All that is kept by default |
| `cwd`, `env`, `user`, `keepAwake`, `buffer` | As for `spawn` in [Run processes in a sandbox](/files-and-code/run-processes-in-a-sandbox) |

A luna may have at most 64 tickets waiting to be used.

## Reach a port from the luna

Declare the ports the luna may reach with `ports`. `port(n).fetch` sends an HTTP request to one and returns a `Response`. The sandbox starts for it if it is stopped.

```ts luna/lunas/user.ts
box: sandbox({ image: "<IMAGE>", ports: [3000] }),
```

```ts luna/lunas/user.ts
preview: h({ args: { path: t.string() } }, async (ctx, { path }) => {
  const r = await ctx.sandboxes.box.port(3000).fetch(path, { timeout: "10s" });
  return { status: r.status, body: await r.text() };
}),
```

Up to 16 MiB of the answer comes back. A port that the declaration does not list is refused. Reaching a port needs no network in the sandbox.

## Connect an app to a port

`port(n).connect()` returns a ticket like a terminal's. Over its WebSocket, binary messages are the port's bytes each way, so an app can speak any protocol to it.

```ts luna/lunas/user.ts
portTicket: h({}, (ctx) => ctx.sandboxes.box.port(3000).connect()),
```

A port's socket takes binary messages only. It closes with code 1000 when the program closes the connection.

## Let people in over SSH

`ssh()` returns how to reach the sandbox with `ssh`, `scp`, `sftp` and editors that use them. The `onSshConnect` hook decides who may. This one lets in the keys whose fingerprints the luna keeps in an `sshKeys` table.

```ts luna/lunas/user.ts
hooks: {
  onSshConnect: (ctx, { fingerprint }) => ctx.db.sshKeys.first({ where: { fingerprint } }) !== undefined,
},
```

Luna asks the hook once a connection has proved it holds a key. Return `true` to let it in, or `{ user }` to also name the Linux account its programs run as, `root` otherwise. Anything else, or a throw, refuses it, and so does a luna type without the hook.

| Field | Holds |
| --- | --- |
| `sandbox` | The sandbox, as the luna type declares it |
| `instance` | The instance's name, or `null` for the first |
| `publicKey` | The key, as `ssh-ed25519 AAAA…` |
| `fingerprint` | Its fingerprint, as `ssh-keygen -l` prints it |
| `address` | Where the connection comes from |

The hook runs once per connection, and again when the luna has slept since and the connection opens something new.

```ts luna/lunas/user.ts
sshAddress: h({}, (ctx) => ctx.sandboxes.box.ssh()),
```

`ssh()` returns `host`, `port`, a `user` that names this sandbox and stays the same, the `hostKey`, and the whole `command` to run. A `known_hosts` line is `[host]:port` followed by `hostKey`.

## Next steps

- [Run processes in a sandbox](/files-and-code/run-processes-in-a-sandbox) reads a named process's output from a handler.
- [Check who is calling](/http/check-who-is-calling) decides which app users get a ticket.
- [sandbox](/sdk/sandbox) lists `SandboxTicket`, `TerminalOptions` and `SandboxSsh`.
