<!-- SPDX-FileCopyrightText: 2026 The Hermitbox Authors -->
<!-- SPDX-License-Identifier: AGPL-3.0-only -->

# Operating Hermitbox

The operator API owns node identity, lifecycle,
placement and history; the public API owns sandbox lifecycles. Nodes never choose assignments.

For an ordinary account, follow [installation](https://docs.hermitbox.dev/v0.2.0/install.md). Local upgrades and purge keep
their files below home. Use the same guide to install on a Linux systemd server.
`hermitbox up --check --domain sandboxes.example.com` shows the server install plan when
run as root. Debian and Ubuntu install missing Docker from Docker's own repository
and nftables from apt. Other systemd Linux hosts need Docker and nftables installed first.
The release installer checks the first download against the SHA-256 digest built into the script for that asset and architecture.
It keeps Postgres and the S3 store in persistent Docker volumes, runs control and edge as systemd
units, enrolls the local daemon and explicitly allows alpine images unless --allow-image is given.
A repeated run retains credentials, data, binaries and files already matching the desired state.
The domain is immutable until existing public address assignments are migrated deliberately.

Control, operator, node endpoint, Postgres and S3 bind to loopback in the one-box setup. Public
HTTP/TLS/raw fronts belong to edge. On a server installed with a domain, edge forwards TLS for
that exact hostname to the local `hermitbox-api-tls` unit. The unit obtains and renews the API
certificate via ACME on TCP 443 and keeps its account and certificate keys in private service
state. Point the API hostname's DNS A record at the server and keep TCP 443 reachable for
renewals. The API certificate covers that hostname. Check `journalctl -u hermitbox-api-tls` if certificate validation fails.
Upgrades preserve existing named installations' transport, including operator-configured TLS proxies.
New named server installations use managed TLS.
Each sandbox owns its own TLS certificate and uses separately configured DNS.
The API key printed once by up configures public clients.

```sh
export HERMITBOX_API_URL=https://sandboxes.example.com
export HERMITBOX_API_KEY=...                 # the initial key, printed once
hermitbox run --image alpine:3.22 -- echo hello
```

Control/edge/operator/store/Postgres credentials generated by up are in root-owned 0600 unit
environment files under /etc/hermitbox. Storage containers source a read-only mount of that file;
Docker's saved container configuration contains no generated password. The daemon's existing
identity format requires private certificate keys under its root-only /var/lib/hermitboxd/identity
and a one-time enrollment token file, removed after enrollment; both are mode 0600.
Do not copy an enrolled state directory into an image. If up stops between marking the initial
key printed and displaying it, create another with the operator API; it will not print it again.

## Adding nodes and daily operation

Join control, edge and nodes through a private network (for example WireGuard). Configure the
node endpoint's names/addresses and firewall before joining remote hosts. Only control reaches
hermitboxd's mutual-TLS management API; only edge reaches edge-audience ports. Images are explicitly
allowed by host policy, never by a public request. Use `hermitbox node token <region>` with
HERMITBOX_OPERATOR_API and HERMITBOX_OPERATOR_TOKEN on a trusted operator host. Install the current hermitbox
CLI independently from the project's release distribution on the joining node, then run the
returned command (`export HERMITBOX_JOIN_TOKEN='<token>' && sudo --preserve-env=HERMITBOX_JOIN_TOKEN hermitbox node join`)
as a user who may use sudo, and append `--allow-image <prefix>` for each
permitted image. Never pass the token as `sudo HERMITBOX_JOIN_TOKEN=<token> hermitbox …`: that puts it in
sudo's own arguments, which every account on the host can read while the join runs. The local CLI verifies the bootstrap's ML-DSA-65 signature with compiled release keys; the fleet CA
authenticates transport only. The authenticated script pins both executable digests before any
installation or execution. `--verify-only` checks the artifacts without installing them. Unsigned
preview builds cannot bootstrap remote hosts. Provider cloud-init installs the verifier from
the independent project distribution before joining; no verifier key comes from the fleet.
One-box installs publish the daemon and its detached signatures under `/opt/hermitbox/fleet`,
readable by control. The daemon's identity and active binary stay under root-only
`/var/lib/hermitboxd`; exposing public release artifacts does not grant control access to that tree.
Use --address when the host has multiple possible private addresses. Then `hermitbox node ls` shows
active/healthy and placement begins. XFS reflink makes snapshots cheap until data changes;
ext4 works with full copies and needs extra disk space.

```sh
export HERMITBOX_OPERATOR_API=http://127.0.0.1:8081
export HERMITBOX_OPERATOR_TOKEN=...          # from the protected control environment
export HERMITBOX_OPERATOR=operator
hermitbox node ls
hermitbox node get <node-id>
hermitbox node events
hermitbox node summary
hermitbox node drain <node-id>
hermitbox node undrain <node-id>
```

Prometheus can scrape `/metrics` on the operator listener with its existing bearer token. Configure
the scraper's authorization credentials file on the trusted operator host. Control reports HTTP
request counts by registered route, method and status, response latency histograms, and open, idle
and waiting counts for the query and lock pools. A long-lived stream reports the time to its
response headers. The public sandbox API continues to expose each sandbox's own measurements.

Run `hermitbox sandbox top ID` to follow CPU, memory, disk and network observations without waking
the sandbox. A missing counter is `null`. To print retained minute samples and exit, use
`hermitbox sandbox top ID --since 2026-11-01T00:00:00Z --once`. The TypeScript method
`sandbox.top({ since, follow: false })` and Python method `sandbox.top(since=since, follow=False)`
iterate the same samples in time order. A live sandbox keeps its history across stops and wakes.

Run `hermitbox sandbox logs ID --follow` to follow application output. Each line identifies the
process and its stdout or stderr stream. The sandbox journal retains bounded output from the
entrypoint, commands, shells and terminals across agent restarts. Process arguments, input,
environment and internal tool transfers stay outside the journal.

Run `hermitbox sandbox why ID` or call `sandbox.why()` in either SDK to read the last 100 recorded
lifecycle decisions, newest first. Each decision includes its timestamp, cause and explanation.
The history distinguishes idle sleep, requested sleep, edge wake, recovery and scheduler refusals.

The same response includes recent destinations seen by the sandbox's hostname gateway. HTTP and
TLS entries marked `reached` identify a verified upstream TCP connection. A `denied` entry
records a DNS, HTTP or TLS policy refusal. Each entry gives the host, service and last observed
time. The gateway summarizes its latest 64 distinct destinations per sample, and control retains
the latest 128 host, service and outcome combinations across placements. `truncated` records
evictions or a shortened sample. Nodes send up to 256 KiB of observations per heartbeat after
reserving space for required state. Successive heartbeats take turns across sandboxes.
Direct traffic outside the gateway has no hostname observation. `coverage: unavailable`
means the sandbox has never reported a gateway sample.

Use `hermitbox doctor --fleet` on a trusted operator host to check the control measurements.
It reads `HERMITBOX_OPERATOR_API` with `HERMITBOX_OPERATOR_TOKEN`. Use `hermitbox doctor --metrics URL` for
a node or edge metrics listener. Both commands accept `--json` and exit with status 1 when
a reported signal needs attention. They read the service directly.

For Grafana, import the [host dashboard](https://github.com/hermitbox/hermitbox/blob/f9b5d4aa3cc4636cd916d6b84e56d6ba38b271a7/deploy/observability/host.json) or the
[fleet dashboard](https://github.com/hermitbox/hermitbox/blob/f9b5d4aa3cc4636cd916d6b84e56d6ba38b271a7/deploy/observability/fleet.json). Select a Prometheus data source and a
scrape target. The host dashboard reads the node ops listener. The fleet dashboard reads one
control instance at a time so shared archive and lease records are counted once.

Add [alerts.yml](https://github.com/hermitbox/hermitbox/blob/f9b5d4aa3cc4636cd916d6b84e56d6ba38b271a7/deploy/observability/alerts.yml) to the Prometheus `rule_files` list and
reload Prometheus. The rules report sustained node reconciliation issues, unavailable control
metrics, failed uploads and a stale edge route feed. The edge rule uses the edge metrics listener.
Run `promtool test rules deploy/observability/alerts.test.yml` to check incident and recovery cases.

Drain stops new placement and upkeep moves assigned sandboxes when another node has room.
It can interrupt applications; schedule maintenance appropriately. With nowhere to move, data
stays on the old node. A full node refuses new work; a sleeping sandbox can move before wake
when memory elsewhere is needed. Snapshot upload must complete before the last local copy is
released. Inspect sandbox events and node issues before retrying failures.

## A host stops answering

Defaults become suspect after 15 seconds and unavailable after 45 seconds; health is measured
using database time. Inspect `hermitbox node get`, the provider console/network, `journalctl -u hermitboxd`
and `hermitboxd doctor`. A daemon restart leaves containers running; a host reboot resumes only after
control authorizes it. A network partition never authorizes another live copy by itself.

When the host is permanently lost, first fence it so it cannot run: power it off through a
provider that guarantees it stays off, boot rescue, or remove it from the private network and
edge's reach. Then use an operator confirmation, for example:

```sh
hermitbox node lost <node-id> --fenced-by power-off --reason 'disk failure'
```

The operator API accepts power-off, provider, network or none as the proof category; record the
actual action in the reason. A beating host is refused unless explicitly forced. Upkeep rebuilds
under a new epoch from the newest uploaded snapshot when capacity exists. Work after that
snapshot exists only on the lost host. With no uploaded snapshot, do not invent an empty rebuild.

If a lost host returns, old copies are fenced and retained; the edge closes stale connections.
Inspect fork.detected, recover requested data out of the fenced directory before deleting it,
and reinstate only after resolving which copy is authoritative. If no rebuild happened yet,
`hermitbox node reinstate <node-id>` restores its assignments. Retire only once placements have moved:
`hermitbox node retire <node-id>`. Retirement revokes credentials; wipe the host before reuse.

## Certificates and upgrades

Nodes renew automatically before expiry. An expired/lost identity requires an operator token
naming its existing node id, via POST /fleet/v1/tokens with region and node, then the usual join
line. That re-enrolls the same node without discarding its placements. A failed re-enrollment
restores the prior identity where possible; inspect its journal. Replacing a compromised fleet
CA cuts nodes off until each re-enrolls under the new CA; dual CA trust is not implemented.

Deploy the daemon, control, edge and clients from one release. Every signature a release
carries (`hermitboxd.sig`, the join bootstrap's, the host bundles' and the server asset
manifests') is ML-DSA-65 (FIPS 204). `release.yml` makes them with Bun
(`control/tools/release-sign.ts`), since the runners' OpenSSL has no ML-DSA, from the `release`
environment's `HERMITBOXD_RELEASE_KEY`: an ML-DSA-65 PKCS#8 private key, in the seed form or
the seed-and-expanded form `openssl genpkey` writes, whose public half is in
`deploy/release-keys.pem`, or the release stops. Control serves the signed daemon
release to enrolled nodes; one healthy node per region upgrades at a time. A node keeps hermitboxd.prev
and rolls back if its new daemon cannot reconcile and get an accepted heartbeat. Regions stop
on a failed rollout. HERMITBOX_UPGRADES=off stops offers. Verify release attestations and SHA256SUMS
as described in README. Never push tags by hand; the release workflow creates them after CI.

For a manual release, select the `main` branch after its push CI has passed on the commit
to publish. The release jobs build and tag that verified commit. Repository owners should
configure the GitHub `release` environment’s deployment rules to allow only the `main` branch,
with no tag rules, so GitHub also enforces the restriction on access to signing credentials.

## Disk, duplicates, observation and undo

Watch free disk near the configured floor, snapshot/upload failures, multipart uploads left in
the store, certificate expiry, unavailable nodes, duplicate identities, fork.detected and
placement errors. Delete incomplete multipart uploads with a bucket lifecycle rule. Do not drop
local copies whose only store copy is missing. Deleted data stays in daemon trash for its
configured retention; release and destroy are deliberate operations.

A duplicated enrolled disk image becomes quarantined. Find and stop the duplicate, remove its
identity, then `hermitbox node clear-quarantine <node-id>`. Templates must have an empty machine-id
before first boot. Keep metrics private: hermitboxd's ops listener, edge's metrics listener and the
operator summary. No event or metric is a reason to declare a host lost by a timer.

Up prints its undo commands. Stop and disable hermitbox-api-tls if installed, then hermitbox-edge,
hermitbox-control, hermitboxd, hermitbox-store and hermitbox-postgres. Remove their managed unit files and reload
systemd. Keep `/etc/hermitbox`, `/var/lib/private/hermitbox-api-tls` and Docker volumes until credentials,
backups and data are saved. Removing hermitbox-postgres and hermitbox-store volumes
and /var/lib/hermitboxd destroys data and is always a separate explicit operator action. Docker,
nftables and Docker's daemon.json remain installed; existing Docker settings are merged, and
running containers cause a reload rather than an automatic restart.

## CLI installation and client credentials

The release includes `install.sh` in SHA256SUMS and the release attestation. On Linux x86_64
and aarch64 the script verifies the server CLI before invoking it, or the bootstrap archive
before extracting it. An alternate release mirror must serve bytes matching the same digest.
For the server preset, the CLI then verifies the asset manifest's ML-DSA-65 signature with its
compiled release keys. The signed manifest identifies the CLI's release and architecture and pins the service
binaries, signature files, control archive, namespace helper archive, and VM descriptor when
included, and the release image's multi-architecture index digest. For a local install with
`--from-dir`, put `hermitbox-server-assets-linux-ARCH.sha256` and its `.sig` file
beside the release assets, using `x64` or `arm64` for `ARCH`.
After installation, up writes the public API URL and key for the invoking user to the file the
CLI reads (0600, private directory): `$XDG_CONFIG_HOME/hermitbox/client.json` when XDG_CONFIG_HOME is
absolute, else ~/.config/hermitbox/client.json. The local CLI reads that file without manual exports.
sudo usually drops XDG_CONFIG_HOME, so the CLI also reads ~/.config's file when the XDG one is
absent. All root operations finish before up drops groups/gid/uid to write that file. HERMITBOX_CONFIG
may select another owned/private client file, and is then the only file read; an environment API
URL never borrows a saved key for a different endpoint. HERMITBOX_API_KEY explicitly overrides saved
credentials.

CA, operator and store credentials remain root-only. Up prints the initial key once; repeated up
prints a hermitbox config key command reference instead. That explicit command reads the user's key
when shell setup is wanted. Up's final output is three export lines followed by the next command.
The bootstrap policy allows official Alpine and Node images; repeat --allow-image to replace it.

The operator scrape also reports placement evaluations and bounded refusal reasons. A refused
evaluation increments each distinct reason that excluded its candidates once. Archive upload
gauges count local, uploading and failed copies. Store lease gauges count current placement
records and distinguish those with a matching fence. These records describe control's view of
the lease. A timed-out or failed database read omits the queue and lease gauges and sets
`hermitbox_control_fleet_metrics_available` to zero. HTTP and connection-pool metrics remain available.

Control returns a W3C `traceparent` header on both listeners. The TypeScript SDK exposes its trace ID as `HermitboxError.traceId`. Python exposes `HermitboxError.trace_id` in both synchronous and asynchronous calls. The CLI prints the ID on an HTTP failure. Control passes the active context to its node requests. hermitboxd records the trace ID in its structured request logs and returns its child trace context with each API response. The edge HTTP relay sends a child context to control, the sandbox agent and exposed applications. Its refusal and error responses carry the same trace ID as its relay logs. An operator can export control, node and edge spans to an OTLP/HTTP receiver by setting `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` to its full trace URL, or `OTEL_EXPORTER_OTLP_ENDPOINT` to its base URL. Spans contain route patterns, methods and response status. With both variables unset, no spans are exported.

Authenticated project requests and operator API requests have a PostgreSQL audit history.
Read your project's records at `GET /v1/audit`. Operators can read `GET /operator/v1/audit`
on the private listener and filter by `project`. Both return the newest records first. Set
`limit` to 1–100 and pass the last record's ID as `before` for the next page. Each record
identifies the actor, project, key and sandbox when known, the HTTP method and route, the
admission time and the response status. A null status means completion could not be recorded. Control returns the original response
after an admitted operation and logs the audit ID if the completion write fails.
The source is the direct peer address, including the proxy address when one is in use.
Headers, request bodies and query strings are excluded. Control retains records for
`HERMITBOX_AUDIT_RETENTION_DAYS` days (90 by default) and removes older records during upkeep.
