# Run sandboxes on another machine (https://kumoba.dev/guide/remote-daemon)

kumobad needs hardware virtualization: `/dev/kvm` on Linux, or an Apple silicon Mac. When the application that drives sandboxes runs somewhere without it, such as a cloud VM or a VMware guest without nested virtualization, run kumobad on a second machine that has it and reach it over TLS. It also keeps untrusted code on a host apart from your application and its data.

Below, machine A runs your application and machine B runs kumobad at `sandboxes.example.com`.

## Make a certificate for machine B [#make-a-certificate-for-machine-b]

Any certificate whose names cover how A reaches B works: one from your company's CA, from a public CA, or from a CA you make for this. To make one with `openssl`:

```sh
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 \
  -subj "/CN=kumoba CA" -keyout ca.key -out ca.pem \
  -addext basicConstraints=critical,CA:TRUE -addext keyUsage=critical,keyCertSign,cRLSign
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
  -subj "/CN=sandboxes.example.com" -keyout server.key -out server.csr
printf 'subjectAltName=DNS:sandboxes.example.com,IP:192.0.2.10\nextendedKeyUsage=serverAuth\n' > server.ext
openssl x509 -req -in server.csr -CA ca.pem -CAkey ca.key -CAcreateserial -days 825 \
  -extfile server.ext -out server.pem
```

Put the names and addresses A uses in `subjectAltName`. Keep `ca.key` off both machines once you have signed what you need.

## Start kumobad on machine B [#start-kumobad-on-machine-b]

```sh
KUMOBAD_TLS_CERT=/etc/kumoba/server.pem \
KUMOBAD_TLS_KEY=/etc/kumoba/server.key \
KUMOBAD_LISTEN=0.0.0.0:7788 \
KUMOBAD_PREVIEW_LISTEN=0.0.0.0:7789 \
KUMOBAD_PREVIEW_URL=https://sandboxes.example.com:7789 \
kumobad
```

Both TCP listeners now speak TLS with that certificate. The ready line says `"tls":"server"`. The bearer token is still required on every API call: copy `~/.kumoba/token` from B to A, or set `KUMOBAD_TOKEN_FILE`. After you replace the certificate, send kumobad `SIGHUP` instead of restarting it; [Rotate certificates and tokens](#rotate-certificates-and-tokens) has the steps. [Run kumobad as a service](/service) shows the same settings in a systemd unit.

## Connect from machine A [#connect-from-machine-a]

```sh
export KUMOBA_URL=https://sandboxes.example.com:7788
export KUMOBA_TOKEN_FILE=$HOME/.kumoba/b-token
export KUMOBA_CA_FILE=$HOME/.kumoba/ca.pem
kumoba run -- uname -a
```

`KUMOBA_CA_FILE` is needed only for a private CA. When it is set, the client trusts that CA instead of the public ones. It and the client certificate variables below apply only to an `https://` URL, and the clients refuse `http://` to any host but `127.0.0.1` or `localhost`, so the token never crosses the network unencrypted. The TypeScript SDK reads the same variables, or takes the values as options:

```ts
import { readFileSync } from "node:fs";
import { Kumoba } from "kumoba";

const kumoba = new Kumoba({
  url: "https://sandboxes.example.com:7788",
  token: readFileSync("/etc/app/kumoba-token", "utf8").trim(),
  ca: readFileSync("/etc/app/kumoba-ca.pem"),
});
await kumoba.run("echo hello from B");
```

## Require client certificates [#require-client-certificates]

With `KUMOBAD_TLS_CLIENT_CA`, the API listener accepts only clients that present a certificate signed by one of the CAs in that file. Sign a client certificate the same way as the server's, with `extendedKeyUsage=clientAuth`, then:

```sh
# machine B
KUMOBAD_TLS_CLIENT_CA=/etc/kumoba/clients-ca.pem kumobad   # plus the settings above

# machine A
export KUMOBA_CERT_FILE=$HOME/.kumoba/client.pem
export KUMOBA_KEY_FILE=$HOME/.kumoba/client.key
kumoba list
```

The SDK takes `cert` and `key` the same way it takes `ca`. A client without a certificate, or with one another CA signed, is refused during the TLS handshake, before kumobad reads the request, and kumobad logs `tls_refused` (at most once every 10 seconds, with a count of the refusals it left out). The token is still required.

kumobad does not check certificate revocation lists. To revoke a client certificate, issue the clients you keep certificates from a new CA, write that CA into the `KUMOBAD_TLS_CLIENT_CA` file and send kumobad `SIGHUP`. The revoked client's new handshakes fail from then on, but connections it already has open stay open until they close, so restart kumobad to cut those as well. A revoked client still needs the token too; if the token may have leaked along with the certificate, rotate the token as below. Every request checks the token again, but a shell or live view opened with the old token keeps running until it closes or kumobad restarts, and preview and desktop links issued before the rotation keep working until they expire, at most an hour later.

## Rotate certificates and tokens [#rotate-certificates-and-tokens]

kumobad re-reads its certificate, key, client CA and token files when it gets `SIGHUP` (`kill -HUP <pid>`, or `systemctl reload kumobad` with `ExecReload` as in [Run kumobad as a service](/service)). New TLS handshakes and new requests use the new files; open connections, shells and live views carry on, and so do the sandboxes. A file that fails to load, such as a key that does not match the certificate or a token shorter than 32 bytes, changes nothing: kumobad keeps the old certificates or the old tokens and logs why. Each reload logs a `token_reloaded` line, and with TLS a `tls_reloaded` line, with `"ok": true` or `"ok": false` and an `error`, never the values. kumobad reads the files at the paths it started with, so changing a variable still needs a restart.

To replace the certificate, write the new certificate and key over the old files, then send `SIGHUP`. Clients that trust the CA that signed it connect as before.

To replace the token without a moment when clients are refused, start kumobad with `KUMOBAD_TOKEN_FILE_NEXT` pointing at a second file, which may not exist yet. Write each token file whole before kumobad can read it: write to a temporary file in the same directory, `chmod 600` it, then `mv` it into place, so a reload never reads half a token. kumobad logs `token_file_readable` with the path and mode, at startup and after each reload, when a token file is readable by its group or others.

1. Write the new token to that file and send `SIGHUP`. kumobad now accepts the old and the new token.
2. Move every client to the new token.
3. Write the new token to the token file, delete the next-token file and send `SIGHUP`. The old token is refused from then on.

## Set up a host for a fleet [#set-up-a-host-for-a-fleet]

`kumobad host init` prepares machine B for a fleet of kumobad hosts without making certificates by hand. Run it as the user kumobad runs as, with the same `KUMOBA_HOME`, `KUMOBAD_STATE_DIR` and listen variables as the service, or the files and codes land where the daemon never looks:

```sh
kumobad host init --address sandboxes.example.com
```

It writes these files to `$KUMOBA_HOME/tls/`, each mode 0600 in a 0700 directory:

- `server.pem` and `server.key`: a self-signed certificate for the `--address` names (repeat the flag for more), the machine's host name, its IPv4 addresses, `localhost`, `127.0.0.1` and `::1`. The first `--address` is the name the pairing code gives.
- `client-ca.pem` and `client-ca.key`: a CA that signs only the client certificates paired fleets get.
- `host.json`: that address and the names the certificate covers.

Then it prints a pairing code on stdout. Running it again keeps the keys and prints a new code. An `--address` the certificate does not cover is an error until you add `--force`, which replaces both keys and certificates and withdraws every unused pairing code, so every fleet must pair again.

When `KUMOBAD_TLS_CERT`, `KUMOBAD_TLS_KEY` and `KUMOBAD_TLS_CLIENT_CA` are all unset and `$KUMOBA_HOME/tls/host.json` exists, kumobad serves those files. The API listens on `0.0.0.0:7788` and previews on `0.0.0.0:7789` unless `KUMOBAD_LISTEN` or `KUMOBAD_PREVIEW_LISTEN` say otherwise. Preview links use `https://<address>:7789` unless `KUMOBAD_PREVIEW_URL` is set, and the Unix socket stays on as well. A port that is taken stops kumobad. The ready line says `"tls":"mutual"` and `"pairing":true`. Restart kumobad after the first `host init`; after `--force`, `SIGHUP` is enough.

### Pairing codes [#pairing-codes]

`kumobad host pair-code` prints a fresh code. A code is `kfp1.` followed by base64url JSON:

```json
{"url": "https://sandboxes.example.com:7788", "previewUrl": "https://sandboxes.example.com:7789", "fingerprint": "<SHA-256 of server.pem's certificate, hex>", "pairingToken": "..."}
```

The token works once and expires after an hour. kumobad keeps only its SHA-256, in `$KUMOBAD_STATE_DIR/pairing-tokens.json`. Treat a code like a password until it has been used.

### Pair with a code [#pair-with-a-code]

A client without a certificate can finish the TLS handshake with the API listener, but on that connection kumobad answers only `POST /v1/pair`. Every other request, `/healthz` and preview links included, gets 403 and the connection is closed. A client certificate that another CA signed still fails the handshake, and the Unix socket is unaffected. To pair by hand, with the token from the code in `$TOKEN`:

```sh
openssl s_client -connect sandboxes.example.com:7788 </dev/null 2>/dev/null | openssl x509 > host.pem
openssl x509 -in host.pem -outform der | shasum -a 256    # must equal the code's fingerprint
openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
  -subj /CN=fleet -keyout fleet.key -out fleet.csr
jq -n --arg token "$TOKEN" --rawfile csr fleet.csr \
  '{pairingToken: $token, csr: $csr, name: "fleet-a"}' |
  curl --cacert host.pem -H 'content-type: application/json' -d @- \
    https://sandboxes.example.com:7788/v1/pair
```

The reply holds `certificate`, `caCertificate`, the bearer `token`, `hostId`, `name` and `notAfterMs`. kumobad signs the certificate with its client CA for one year, for client authentication only, with `name` as its common name; from the CSR it takes only the public key. Use the certificate, `fleet.key` and the token as in [Require client certificates](#require-client-certificates). kumobad logs `paired` with the name. A wrong, used or expired token answers 403 and logs `pair_refused`. After 5 of those within a minute from one address (one /64 for IPv6), further wrong tokens from it answer 429 `rate_limited` with `Retry-After` until the minute has passed; a valid token always pairs. To withdraw a paired fleet's certificate, run `kumobad host init --force` and send `SIGHUP`; the fleets you keep then pair again. Until kumobad has loaded the new files, pairing answers 503 `unavailable` and leaves the code unused, so it never hands out a certificate the listener would refuse. `--force` writes the new files to `tls.new` beside `tls` and swaps the directories, so an interrupted run leaves the old files in place, and the next `host init` tidies up.

## Open previews and the live view [#open-previews-and-the-live-view]

`expose` and `desktop` links point at `KUMOBAD_PREVIEW_URL`, here `https://sandboxes.example.com:7789`. A browser that opens them has to trust the certificate: with a private CA, add `ca.pem` to the browser's or the system's trusted certificates. The preview listener never asks for a client certificate, since browsers usually have none. Its links are signed, bound to one sandbox and port, and expire, so share them like passwords.

Anyone who can reach the preview port can try links, and only a valid, unexpired link opens anything. Still, let only the machines that need them reach port 7788 and port 7789, with a firewall or security group. See the [Security model](/security).

## Follow the sandboxes on machine B [#follow-the-sandboxes-on-machine-b]

A client that tracks several machines, for example to bill sandbox time, can read each machine's event feed instead of listing every sandbox again and again:

```sh
kumoba events --limit 100
```

It lists every sandbox being created, started, stopped (with the reason) and deleted, with exact times. kumobad keeps 72 hours of them, those of deleted sandboxes included. Next time pass the `nextCursor` it returned as `--cursor` to get only what is new; the cursor stays valid when kumobad restarts. Each machine's feed is in the order that machine recorded it, not `atMs` order, and a cursor only reads on in the feed it came from: given another machine's cursor, kumobad starts from its oldest event and says `"reset": true`. See [Events](/http-api#events).

To free a slot on a full machine, ask it which started sandboxes nobody is using:

```sh
kumoba list --idle --idle-for-ms 600000
```

It applies the test auto-stop uses: no open command, shell, transfer, preview or live view, and no activity for 10 minutes. A sandbox with a live view open counts as in use however quiet it is; its `activeOperations` and `openPreviews` say so.

Someone can start using a sandbox between the listing and your stop. Stop it only if it is still idle, and a stop that comes too late fails with `not_idle` instead of cutting off their work:

```sh
kumoba stop "$id" --if-idle-for-ms 600000
```

## What kumobad refuses [#what-kumobad-refuses]

- A `KUMOBAD_LISTEN` or `KUMOBAD_PREVIEW_LISTEN` that is not a loopback address while TLS is off. kumobad stops at startup and names `KUMOBAD_TLS_CERT` and `KUMOBAD_TLS_KEY`.
- One of `KUMOBAD_TLS_CERT` and `KUMOBAD_TLS_KEY` without the other, a key that does not match the certificate, or `KUMOBAD_TLS_CLIENT_CA` without them.
- A preview listener on `0.0.0.0` or `[::]` without `KUMOBAD_PREVIEW_URL`, since links need an address browsers can open.

Without the TLS settings nothing changes: the Unix socket, `127.0.0.1:7788` and `127.0.0.1:7789` speak plain HTTP to this machine only. With them, the Unix socket still speaks plain HTTP, and only to users who can open it.