# Configuration

Sculkworm reads process settings from `SCULKWORM_*` environment variables at startup. It loads static routes from `SCULKWORM_ROUTES_FILE` (when set), tenant definitions from `SCULKWORM_TENANTS_FILE` (when set), persisted dynamic routes from `SCULKWORM_STATE_FILE` (when `SCULKWORM_TENANTS_FILE` is set), and closed-mode secrets from `SCULKWORM_SECRETS_FILE` (when `SCULKWORM_TUNNEL_LISTEN` is set).

If an environment variable is missing or out of bounds, Sculkworm prints one `config_error` line to stderr and exits with code `2`.

```text
level=error event=config_error error="at least one of SCULKWORM_ROUTES_FILE or SCULKWORM_TENANTS_FILE must be set"
```

If the routes file, tenants file, state file, or secrets file cannot be read or fails validation at startup, Sculkworm prints one `routes_error`, `tenants_error`, `state_error`, or `secrets_error` line to stderr and exits with code `2`.

## Environment variables

Leading and trailing whitespace is trimmed from every variable. An empty or whitespace-only value is treated as unset, so optional variables fall back to their default.

At least one of `SCULKWORM_ROUTES_FILE` or `SCULKWORM_TENANTS_FILE` must be set. When `SCULKWORM_TENANTS_FILE` is unset, the HTTP admin API is disabled and Sculkworm runs in static-only mode. When `SCULKWORM_TENANTS_FILE` is set, `SCULKWORM_STATE_FILE` is required. When `SCULKWORM_TUNNEL_LISTEN` is set, `SCULKWORM_TENANTS_FILE`, `SCULKWORM_TLS_CERT_FILE`, `SCULKWORM_TLS_KEY_FILE`, `SCULKWORM_PUBLIC_URL`, and `SCULKWORM_SECRETS_FILE` are all required.

| Variable | Default | Bounds | Meaning |
| --- | --- | --- | --- |
| `SCULKWORM_LISTEN` | `0.0.0.0:25565` | Valid `SocketAddr` (`ip:port` or `[ipv6]:port`) | TCP socket address that the Minecraft relay binds to. |
| `SCULKWORM_ROUTES_FILE` | *(unset)* (`"/etc/sculkworm/routes.json"` in Docker) | Non-empty file path | Path to the JSON file containing static routes. Optional when `SCULKWORM_TENANTS_FILE` is set. |
| `SCULKWORM_TENANTS_FILE` | *(unset)* | Non-empty file path | Path to the JSON file defining admin API tenants. Unset disables the HTTP admin API. |
| `SCULKWORM_STATE_FILE` | *(unset)* (`"/var/lib/sculkworm/state.json"` in Docker) | Non-empty file path | Path to the JSON file where dynamic routes are persisted. Required when `SCULKWORM_TENANTS_FILE` is set. |
| `SCULKWORM_API_ADDR` | `127.0.0.1:8080` (`0.0.0.0:8080` in Docker) | Valid `SocketAddr` (`ip:port` or `[ipv6]:port`) | TCP socket address that the HTTP admin API binds to when `SCULKWORM_TENANTS_FILE` is set. |
| `SCULKWORM_MAX_API_CONNECTIONS` | `64` | `1..=10000` | Maximum concurrent HTTP admin API connections. Excess connections close immediately. |
| `SCULKWORM_HANDSHAKE_TIMEOUT_SECONDS` | `10` | `1..=120` | Maximum seconds allowed to read a complete Handshake packet before closing the connection with `reason=timeout`. |
| `SCULKWORM_MAX_CONNECTIONS` | `1024` | `1..=100000` | Maximum number of concurrent relay connections (including connections still reading a Handshake). Excess connections close immediately with `reason=max_connections`. |
| `SCULKWORM_CONNECT_TIMEOUT_SECONDS` | `5` | `1..=60` | Maximum seconds allowed for DNS resolution and TCP connect to the selected backend target. |
| `SCULKWORM_TUNNEL_LISTEN` | *(unset: closed mode disabled)* | Valid `SocketAddr` (`ip:port` or `[ipv6]:port`) | TLS socket address for the tunnel listener (ALPN `sculkworm` for agent/connect sessions, `http/1.1` or no ALPN for public HTTPS endpoints). Unset disables closed routes (`503 closed_mode_disabled`). |
| `SCULKWORM_TLS_CERT_FILE` | *(unset)* | Non-empty file path | Path to the PEM certificate chain for the tunnel listener. Required when `SCULKWORM_TUNNEL_LISTEN` is set. Reloaded on `SIGHUP`. |
| `SCULKWORM_TLS_KEY_FILE` | *(unset)* | Non-empty file path | Path to the PEM private key (PKCS#8, PKCS#1, or SEC1) for the tunnel listener. Required when `SCULKWORM_TUNNEL_LISTEN` is set. Reloaded on `SIGHUP`. |
| `SCULKWORM_PUBLIC_URL` | *(unset)* | `https://` URL without path, query, or fragment | External base URL of the tunnel listener (for example `https://relay.example`). Required when `SCULKWORM_TUNNEL_LISTEN` is set. Advertised in `sculkworm.relay` on closed-route Minecraft status pings. |
| `SCULKWORM_SECRETS_FILE` | *(unset)* | Non-empty file path (`0600` or `0400` on Unix) | Path to the JSON file holding login encryption keys and IdP OAuth2/OIDC clients. Required when `SCULKWORM_TUNNEL_LISTEN` is set. Reloaded on `SIGHUP`. |
| `SCULKWORM_IDP_ALLOW_PRIVATE` | `0` | `0` or `1` | When `1`, allows outbound IdP HTTP requests (such as OIDC discovery) to reach loopback, RFC 1918, link-local, CGNAT, and unique-local addresses. |

## Routes file format

The routes file is a JSON object with a single required field named `routes`. Unknown top-level fields are rejected. Each entry in `routes` maps a domain name string to a backend target string in `host:port` format.

```json
{
	"routes": {
		"survival.play.example": "10.0.0.10:25565",
		"creative.play.example": "backend.internal:25565",
		"ipv6.play.example": "[::1]:25582"
	}
}
```

- **Keys.** Every route key is parsed with `Domain::parse`, which lowercases the string and strips at most one trailing dot (`.`). Two keys that normalize to the same domain (such as `alpha.example` and `ALPHA.example.`) are rejected as duplicates. An empty `"routes": {}` map is valid and rejects every incoming connection with `event=unknown_host`.
- **Targets.** Every target must have a non-empty host and a `u16` port between `1` and `65535`. Bracketed IPv6 literals such as `[::1]:25582` are validated as IPv6 addresses. Unbracketed hosts may be hostnames or IPv4 addresses and cannot contain `:`, `[`, `]`, whitespace, or control characters. Backend hostnames are resolved via DNS when a client connects, not when the file is loaded.

## Routes file validation errors

Every error below is returned verbatim by `load_routes_file` and `parse_routes_json` in `src/routes.rs`. On startup, Sculkworm logs `level=error event=routes_error error="<message>"` and exits with code `2`. On a `SIGHUP` reload, Sculkworm logs `level=error event=reload_failed path="<path>" error="<message>"` and keeps the previous route table active.

| Error message | Condition |
| --- | --- |
| `failed to read routes file <path>: <io error>` | The file does not exist, cannot be opened, or is not valid UTF-8. |
| `invalid routes file: <serde_json error>` | The file is empty, not valid JSON, missing the `routes` field, contains an unknown top-level field, or fails one of the map validation checks below. |
| `invalid route domain "<raw_domain>": domain must not be empty` | A route key is empty (`""`) or consists of a single dot (`"."`). |
| `duplicate route domain after normalization: <domain>` | Two entries in `routes` normalize to the same domain after lowercasing and stripping a single trailing dot. |
| `target "<raw>" must be in host:port format` | A target string does not contain a `:` separator. |
| `target "<raw>" has invalid port "<raw_port>"` | The port substring after the last `:` is not a valid `u16` integer (`0..=65535`). |
| `target "<raw>" port must be non-zero` | The parsed port is `0`. |
| `target "<raw>" has invalid bracketed IPv6 host` | The host part is enclosed in `[...]` but the inner string is not a valid IPv6 address. |
| `target "<raw>" has invalid host "<raw_host>"` | An unbracketed host is empty or contains `:`, `[`, `]`, whitespace, or control characters. |

When `serde_json` wraps a custom error from the `routes` map visitor, the logged string is `invalid routes file: <visitor error> at line <n> column <m>`.

## Tenants file format

When `SCULKWORM_TENANTS_FILE` is set, Sculkworm loads tenant credentials and scopes from a JSON object with a single required field named `tenants`. Unknown fields at the top level or inside any tenant entry are rejected.

```json
{
	"tenants": [
		{
			"name": "sculk",
			"key": "replace-with-a-random-key-of-at-least-32-chars",
			"domains": ["play.sculk.network"],
			"max_routes": 1000,
			"allowed_targets": ["10.0.0.5", "*.mc.internal"]
		},
		{
			"name": "partner",
			"key": "another-random-key-of-at-least-32-characters-long",
			"domains": ["games.example"]
		}
	]
}
```

- **`name`.** Required. Unique across tenants, 1–32 ASCII characters matching `[a-z0-9-]`.
- **`key`.** Required. Unique across tenants, at least 32 bytes long. Used as the `Authorization: Bearer <key>` token on the HTTP admin API. Never logged.
- **`domains`.** Required, non-empty array of domain strings normalized with `Domain::parse`. A tenant may manage hostname `H` if and only if `H` equals one of its domains or ends with `.` plus one of its domains. No two tenants may have overlapping domain scopes (equal domains or one being a subdomain of the other).
- **`max_routes`.** Optional integer, default `100`, range `1..=100000`. Maximum number of dynamic routes (open and closed combined) the tenant may hold at once.
- **`allowed_targets`.** Optional array of target host patterns (applies to open routes only). Each pattern is either an exact IP literal (`10.0.0.5`, `::1`, `[::1]`), an exact hostname (`mc.internal`), or a `*.suffix` wildcard hostname (`*.mc.internal`, matching strict subdomains only, not `mc.internal` itself). CIDR ranges are not supported. Because hostnames are resolved via DNS at connect time, IP literals provide the strongest allowlist guarantee. Omitting `allowed_targets` marks a trusted tenant that may point routes at any valid `host:port` target.

## Tenants file validation errors

Every error below is returned verbatim by `TenantRegistry::from_file`, `TenantRegistry::from_json`, and `TargetPattern::parse` in `src/tenants.rs`. On startup, Sculkworm logs `level=error event=tenants_error error="<message>"` and exits with code `2`.

| Error message | Condition |
| --- | --- |
| `failed to read tenants file <path>: <io error>` | The file does not exist, cannot be opened, or is not valid UTF-8. |
| `invalid tenants file: <serde_json error>` | The file is empty, not valid JSON, missing a required field, or contains an unknown field. |
| `tenant "<name>" has invalid domain "<raw_domain>": domain must not be empty` | A domain entry in `domains` is empty (`""`) or a single dot (`"."`). |
| `tenant "<name>": allowed_targets pattern must not be empty` | An entry in `allowed_targets` is `""`. |
| `tenant "<name>": invalid allowed_targets pattern "<raw>"` | An `allowed_targets` entry contains whitespace, control characters, empty labels, `/`, `:`, `[`, `]`, or fails parsing. |
| `tenant "<name>": invalid allowed_targets wildcard pattern "<raw>"` | A `*.` wildcard entry in `allowed_targets` has an empty or malformed suffix. |
| `tenant "<name>": invalid allowed_targets pattern "<raw>": wildcards must be '*.suffix'` | An `allowed_targets` entry contains `*` outside a leading `*.` prefix. |
| `invalid tenant name "<name>": must match [a-z0-9-]{1,32}` | A tenant `name` is empty, longer than 32 bytes, or contains characters outside `a-z`, `0-9`, and `-`. |
| `duplicate tenant name "<name>"` | Two tenants have the same `name`. |
| `tenant "<name>" key must be at least 32 characters long` | A tenant `key` is shorter than 32 bytes. |
| `duplicate tenant key for tenant "<name>"` | Two tenants share the same `key`. |
| `tenant "<name>" must have at least one domain` | A tenant's `domains` array is empty. |
| `tenant "<name>" max_routes must be between 1 and 100000` | A tenant's `max_routes` is `0` or greater than `100000`. |
| `overlapping domain scope between tenants "<left>" (<d1>) and "<right>" (<d2>)` | Two tenants claim the same domain or one claims a subdomain of the other. |

## Secrets file format

When `SCULKWORM_TUNNEL_LISTEN` is set, Sculkworm reads `SCULKWORM_SECRETS_FILE` at startup and on `SIGHUP`, and never writes it. On Unix, the file mode must be `0600` or `0400`; any broader permissions cause startup to exit with code `2` and `level=error event=secrets_error error="secrets file <path> must not be readable by group or others"`.

```json
{
	"login_keys": {
		"1": "QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl8"
	},
	"clients": {
		"discord-main": {
			"tenant": "sculk",
			"kind": "oauth2",
			"preset": "discord",
			"client_id": "1234567890",
			"client_secret": "replace-me"
		},
		"sculk-main": {
			"tenant": "sculk",
			"kind": "oidc",
			"issuer": "https://sculk.example",
			"scopes": ["openid", "profile", "offline_access", "sculk:servers"],
			"client_id": "vb3efdhxc2sbpqkmvbbd",
			"client_secret_env": "SCULKWORM_SCULK_OIDC_SECRET"
		}
	}
}
```

For a sculk.network instance acting as an OIDC provider (`sculk-main` above), obtain `client_id` and `client_secret` from `POST /api/oidc/clients` on that instance with `redirectUris: ["https://<relay>/login/callback"]` (plus loopback `http://127.0.0.1/callback` with `native: true` only if a native client talks to sculk.network directly; the relay itself uses `https://<relay>/login/callback`). Include `offline_access` in `scopes` if you want 30-day logins to refresh silently past the 1-hour access token TTL. Even if `sculk:servers` is omitted from `scopes`, any route with `allow: {"sculk_server": "<server id>"}` adds `sculk:servers` automatically. See [sculk.network as an authorizer](https://docs.sculk.network/nightly/sculkworm/sculk-authorizer.md) for a step-by-step setup guide.

- **`login_keys`.** Required object with `1..=255` entries mapping decimal key id (`"1"`..`"255"`) to unpadded base64url of exactly 32 random bytes.
- **`clients`.** Optional map of client name (`[a-z0-9-]{1,64}`) to an `oidc` or `oauth2` client definition scoped to a configured `tenant` or `"*"`. Each client sets `client_id` and exactly one of `client_secret` or `client_secret_env`. See [Closed routes: secrets file](https://docs.sculk.network/nightly/sculkworm/tunnel.md#65-secrets-file) for the full field table and error messages.
- **`SIGHUP` reload.** A reload that fails validation, removes a client referenced by a closed route, or changes a used client's `tenant` away from that route's owner (and not `"*"`) logs `level=error event=reload_failed` and keeps the previous secrets active.

## State file format

When the admin API is enabled, dynamic routes are persisted to `SCULKWORM_STATE_FILE` as versioned JSON written via temp file, `fsync`, and atomic rename in the same directory. Sculkworm reads state versions `1` and `2` and always writes version `2`. A version `1` file is loaded as open routes and migrated to version `2` on the next write (it is never rewritten at startup just to upgrade the version).

```json
{
  "version": 2,
  "routes": [
    {
      "host": "survival.play.sculk.network",
      "mode": "open",
      "target": "10.0.0.10:25565",
      "tenant": "sculk"
    },
    {
      "host": "friends.play.sculk.network",
      "mode": "closed",
      "tenant": "sculk",
      "authorizer": {
        "type": "oauth2",
        "client": "discord-main"
      },
      "authorizer_id": "fedcba9876543210",
      "agent_token": {
        "id": "0123456789abcdef",
        "sha256": "3710e97d7ffe5e799ff2aad6d389f4c602facf7900bfd2c7cde880b1cd9f7a95",
        "created_at": "2026-11-27T10:00:00Z"
      }
    }
  ]
}
```

If `SCULKWORM_STATE_FILE` does not exist at startup, Sculkworm starts with an empty dynamic route set and creates the file on the first write. If the file exists but cannot be read, fails JSON validation, has an unsupported `version`, contains an invalid host/target/authorizer, or lists a duplicate host, Sculkworm logs `level=error event=state_error error="<message>"` and exits with code `2` rather than discarding state.

- Entries referencing a removed tenant (`reason=unknown_tenant`), a host outside the tenant's current domain scope (`reason=host_out_of_scope`), or an open-route target the tenant's `allowed_targets` no longer allows (`reason=target_not_allowed`) are dropped and logged as `level=warn event=state_route_dropped host=<host> reason=<reason>`.
- Closed routes whose configured client is missing from the secrets file (`reason=unknown_client`), assigned to another tenant (`reason=client_tenant_mismatch`), or loaded while `SCULKWORM_TUNNEL_LISTEN` is unset (`reason=closed_mode_disabled`) are **kept in state** and marked inactive (`level=warn event=closed_route_inactive host=<host> reason=<reason>`). The state file is left untouched so fixing the secrets file restores them.
- Expired entries in `revoked_logins` are dropped at load and at write.

## Agent CLI flags and environment variables

`sculkworm-agent` (also available as `sculkworm agent`) dials out to the relay's TLS tunnel listener and forwards player streams to the local Minecraft server. Every flag accepts an environment fallback:

| Flag | Environment variable | Default | Meaning |
| --- | --- | --- | --- |
| `--relay <url\|host:port>` | `SCULKWORM_AGENT_RELAY` | *(required)* | Relay tunnel `https://host[:port]` URL or `host:port` authority. |
| `--route <host>` | `SCULKWORM_AGENT_ROUTE` | *(required)* | Closed route hostname (normalized with `Domain::parse`). |
| `--token <swa_...>` | `SCULKWORM_AGENT_TOKEN` | *(required unless `--token-file`)* | Agent token minted by `POST /v1/routes/{host}/agent-token`. |
| `--token-file <path>` | `SCULKWORM_AGENT_TOKEN_FILE` | *(unset)* | Path to a file containing the agent token (mutually exclusive with `--token`). |
| `--target <host:port>` | `SCULKWORM_AGENT_TARGET` | `127.0.0.1:25565` | Local Minecraft server socket address. |
| `--ca-file <pem>` | `SCULKWORM_AGENT_CA_FILE` | *(OS root store)* | PEM CA/certificate file used exclusively as the TLS root store instead of OS roots. |
| `--pin <sha256/base64>` | `SCULKWORM_AGENT_PIN` | *(unset)* | Repeatable SPKI SHA-256 pin checked in addition to root and hostname verification (comma-separated in the env var). Mismatch fails with `event=tls_pin_mismatch`. |
| `--software <string>` | *(none)* | `sculkworm-agent/0.1` | Software identifier sent in `HELLO` (0..=64 bytes). |

Exit codes: `0` on `SIGINT`/`SIGTERM`, `2` on invalid configuration, `SERVER_HELLO` `unsupported_version` (`1`), or `unknown_route` (`4`), and `3` when replaced by a newer agent (`GOAWAY replaced`) after all open streams finish. Service managers should not restart on exit code `3` (systemd: `RestartPreventExitStatus=3`).

## Connect CLI flags, environment variables, and `logins.json`

`sculkworm-connect` (also available as `sculkworm connect`) runs on the player's machine. Subcommands:

- `sculkworm-connect play <host[:port]>` — logs in if needed (loopback redirect + PKCE S256, falling back automatically to the RFC 8628 device flow if no browser can be opened, or forcing device flow with `--device`), opens a local Minecraft TCP listener (default `127.0.0.1:25565`), mints short-lived tickets on demand, and tunnels streams to the relay.
- `sculkworm-connect login <host[:port]>` — runs the browser login flow (or device flow with `--device` or automatic fallback) and saves the sealed login (`swl_...`) to `logins.json`.
- `sculkworm-connect logout <route|--all>` — calls `POST /logout` on the relay and removes the local entry (or all entries).

| Flag | Environment variable | Default | Meaning |
| --- | --- | --- | --- |
| `--relay <https://...>` | *(none)* | *(stored entry or Minecraft status ping)* | Relay HTTPS URL; skips Minecraft status-ping discovery. |
| `--device` | *(none)* | `false` | Forces the RFC 8628 device flow instead of opening a local browser (also engaged automatically when no browser can be opened). |
| `--listen <ip:port>` | *(none)* | `127.0.0.1:25565` | Local Minecraft TCP listener address for `play`. Non-loopback addresses require `--listen-any`. |
| `--listen-any` | *(none)* | `false` | Permits binding `--listen` to a non-loopback IP address. |
| `--add-server[=<path>]` | *(none)* | *(disabled; bare `--add-server` uses OS default `.minecraft`)* | Adds or updates every `servers.dat` entry whose `name` matches the route (`ip` = listen address, rewriting unspecified `0.0.0.0`/`[::]` binds to `127.0.0.1`/`[::1]`) atomically as uncompressed NBT while keeping every other entry and field byte for byte. Accepts `--add-server`, `--add-server=<dir>`, or `--add-server=<dir>/servers.dat` (bare `--add-server` never consumes the next argument; leading `~` and `~/` or `~\` on Windows expand against `HOME` / `USERPROFILE`). Never creates directories, follows a symlinked `servers.dat` in place (preserving target permissions), rejects files over 4 MiB or non-regular files, and requires a filesystem with file locking. Valid with `play` only. Run while Minecraft is closed, because Minecraft holds the server list in memory and overwrites `servers.dat` when edited in game. |
| `--ca-file <pem>` | `SCULKWORM_CONNECT_CA_FILE` | *(OS root store)* | PEM CA/certificate file replacing the OS root store for both HTTPS and tunnel TLS. |
| `--pin <sha256/base64>` | `SCULKWORM_CONNECT_PIN` | *(unset)* | Repeatable SPKI SHA-256 pin checked in addition to root and hostname verification (comma-separated in the env var). |
| `--logins-file <path>` | `SCULKWORM_CONNECT_LOGINS_FILE` | OS config dir (`~/.config/sculkworm/logins.json` on Linux) | Path to the player's `logins.json` store. On Unix, the default `sculkworm` config directory is created/tightened to mode `0700` (symlinks refused); for custom `--logins-file` paths, missing parent directories are created `0700` and pre-existing parent directories are left untouched. The file itself is always created `0600` and broader file permissions are refused. |
| `--yes`, `-y` | *(none)* | `false` | Skips the interactive confirmation prompt when the relay URL was discovered via an unauthenticated Minecraft status ping. |
| `--software <string>` | *(none)* | `sculkworm-connect/0.1` | Software identifier sent in `HELLO` (0..=64 bytes). |

When `--add-server` receives a missing directory or a non-`servers.dat` file, `sculkworm-connect` refuses it without creating or modifying anything and exits with code `2`:

```sh
sculkworm-connect play friends.play.example --add-server=/tmp/no-such-minecraft-dir
```

```text
level=error event=servers_dat_error error="/tmp/no-such-minecraft-dir is not an existing directory or a servers.dat file"
```
