# Sculkworm relay integration

When the `sculkworm` feature flag is enabled and `SCULKWORM_URL`, `SCULKWORM_API_KEY`, and `SCULKWORM_BASE_DOMAIN` are configured, sculk.network registers a `<server-slug>.<SCULKWORM_BASE_DOMAIN>` route in a shared Sculkworm relay (`crates/sculkworm`) for managed servers, keeps it in sync, and deletes it when the server is disconnected.

Routes run in one of two modes:

- **Open mode** (`mode: "open"`, default): hostname-based TCP routing to the server's backend `target` (`host:port`) without authentication gating.
- **Closed mode** (`mode: "closed"`): no backend target is configured on the relay; players authenticate via OIDC (using this sculk.network instance as the identity provider with `{"sculk_server": "<server-id>"}`) and reach the game server only through a tunnel opened by a `sculkworm-agent` authenticated with a per-route agent token. A server owner who runs their own relay can also set a per-server `relayUrl` override so sculk.network directs players there without touching the shared relay's admin API.

See [crates/sculkworm/docs/sculk-authorizer.md](https://docs.sculk.network/nightly/sculkworm/sculk-authorizer.md) for configuring a relay's OIDC client against this sculk.network instance.

## Enabling the feature

`sculkworm` is at the `nightly` [feature stage](https://docs.sculk.network/nightly/sculk/releases.md#feature-stages):

- Enabled by default on `dev` (`0.0.0-dev`) and `nightly` builds.
- Disabled by default on `stable` builds.
- Force on or off with `SCULK_FEATURES=sculkworm` or `SCULK_FEATURES=-sculkworm`.

To use the shared relay in open mode, set the first three environment variables; leaving any of them unset disables shared-relay integration. To also enable closed routes on the shared relay, set `SCULKWORM_PUBLIC_URL` and `SCULKWORM_OIDC_CLIENT`:

| Variable | Secret | Example | Purpose |
| --- | --- | --- | --- |
| `SCULKWORM_URL` | no | `http://sculkworm:8080` | Base URL of the Sculkworm HTTP admin API. |
| `SCULKWORM_API_KEY` | yes | `<tenant bearer token>` | Bearer key from `SCULKWORM_TENANTS_FILE` (at least 32 characters). Never logged. |
| `SCULKWORM_BASE_DOMAIN` | no | `play.example.org` | Domain scope owned by this tenant; routes are registered as `<slug>.<SCULKWORM_BASE_DOMAIN>`. |
| `SCULKWORM_PUBLIC_URL` | no | `https://relay.example.org` | Public `https://` URL players' tools use to reach the shared relay (optional; required for shared closed routes). |
| `SCULKWORM_OIDC_CLIENT` | no | `sculk-main` | Name of the OIDC client in the relay's `SCULKWORM_SECRETS_FILE` pointing at this sculk.network instance (optional; required for shared closed routes). |

When the `sculkworm` flag is off:

- `GET /api/servers/:id/route`, `PUT /api/servers/:id/route`, `POST /api/servers/:id/route/agent-token`, `DELETE /api/servers/:id/route/agent-token`, and `GET /api/servers/:id/tunnel` all return `404 {"error":"not_found"}` with `Cache-Control: no-store`.
- `GET /api/servers/:id` omits `sculkwormAddress`.
- The server header in the web app does not show a relay address chip.
- Setting `gameAddress`, creating a server with `sculkworm: "closed"`, disconnecting a server, and booting the server make zero requests to Sculkworm.

## Address derivation and stability

- A server's slug is derived from its name when a route is first assigned: NFKD diacritic stripping, lowercasing, collapsing non-alphanumeric runs to `-`, trimming leading/trailing `-`, capped to a 63-character DNS label (`[a-z0-9-]`).
- Slugs are unique per sculk.network instance and stable once assigned (stored in `sculkworm_routes`).
- Collisions are rejected (`409 {"error":"slug_collision"}` on `PUT /api/servers/:id/route`, logged and skipped on background hooks).
- When a server is disconnected while Sculkworm is unreachable, its `sculkworm_routes` row stays tombstoned (`deleted_at` set) until Sculkworm confirms deletion, preventing a new server from reusing the slug before the old route is gone.

## Closed routes and agent tokens

When a route is put in closed mode (`PUT /api/servers/:id/route` with `{"mode": "closed"}`):

- `target` must be `null` or omitted (a closed route has no backend target).
- sculk.network registers the route on the shared relay with `{"mode": "closed", "authorizer": {"type": "oidc", "client": "<SCULKWORM_OIDC_CLIENT>", "allow": {"sculk_server": "<server-id>"}}}`.
- If either `SCULKWORM_PUBLIC_URL` or `SCULKWORM_OIDC_CLIENT` is unset, the request returns `409 {"error":"sculkworm_closed_not_configured"}`.
- Switching between `open` and `closed` converges on the relay (and reconciles automatically after any transient relay outage).
- A member with `server.settings` can mint an agent token via `POST /api/servers/:id/route/agent-token`. The raw token is returned once in the `201` response (`Cache-Control: no-store`); sculk.network persists only the token ID (`agent_token_id`) and never logs or stores the raw token. `DELETE /api/servers/:id/route/agent-token` revokes the token on the relay. Both actions are recorded in the audit log (`settings.sculkworm.agent_token.mint` and `settings.sculkworm.agent_token.revoke`).
- A new server can request closed mode at creation time by setting `"sculkworm": "closed"` in `POST /api/create` (defaults to `"off"`; ignored silently when the `sculkworm` flag is off or closed mode is not configured; relay outages never fail or roll back server creation and are retried by reconcile).

## Self-hosted relay override (`relayUrl` and `routeHost`)

A server owner running their own Sculkworm relay can point a server's closed route at it by sending both `"relayUrl": "https://relay.example.org"` and `"routeHost": "friends.play.example.org"` on `PUT /api/servers/:id/route` with `mode: "closed"`:

- `relayUrl` must be an `https://` URL with no credentials, query string, or fragment (max 200 characters; trailing slashes are trimmed).
- `routeHost` is required whenever `relayUrl` is set (`400 {"error":"route_host_required"}` if missing) and is only valid together with a non-null `relayUrl` (`400` otherwise). It is validated as a lowercase Sculkworm hostname with no scheme or port, and stored as the route's unique `host` (`409 {"error":"slug_collision"}` if another server already claims that hostname).
- Sending `"relayUrl": null` clears the override, recomputes `host` from `<slug>.<SCULKWORM_BASE_DOMAIN>`, and converges the route back to the shared relay.
- While a `relayUrl` override is set, sculk.network does not call the shared relay's admin API for that server (neither on `PUT`, disconnect, nor reconcile), and the server does not require `SCULKWORM_URL`, `SCULKWORM_API_KEY`, `SCULKWORM_BASE_DOMAIN`, `SCULKWORM_PUBLIC_URL`, or `SCULKWORM_OIDC_CLIENT` — only the `sculkworm` feature flag.
- The server owner registers the closed route (`routeHost`) on their own relay using this instance as the OIDC provider with `allow: {"sculk_server": "<server-id>"}` (see [crates/sculkworm/docs/sculk-authorizer.md](https://docs.sculk.network/nightly/sculkworm/sculk-authorizer.md)) and mints agent tokens directly on their relay (`POST`/`DELETE /api/servers/:id/route/agent-token` returns `409 {"error":"relay_is_custom"}`).
- `GET /api/servers/:id/tunnel` returns the given `routeHost` and `relayUrl` with `"custom": true`.

## Route lifecycle and reconciliation

- **On backend address set/change (`PUT /api/servers/:id/status/game-address`):** for servers without a closed route, assigns an open route if needed and pushes `PUT /v1/routes/{host}` via the `sculkworm` JS SDK (`crates/sculkworm/sdk/js`). Closed routes are left untouched by `game-address` updates.
- **On explicit route update (`PUT /api/servers/:id/route`):** assigns or updates the server's mode (`open` or `closed`), `target`, or custom `relayUrl`, and pushes the matching route shape (`putRoute` or `putClosedRoute`) on the shared relay when no custom `relayUrl` is set.
- **On server creation (`POST /api/create`):** when `sculkworm: "closed"` is requested and closed mode is enabled and configured, assigns the closed route idempotently after the server row is created and schedules reconcile on any transient outage.
- **On server disconnect (`POST /api/servers/:id/disconnect`):** tombstones the row inside the disconnect transaction, then sends `DELETE /v1/routes/{host}` via the SDK and deletes the local row once confirmed (`204` or `404 not_found`). Custom-relay rows are removed locally without calling the shared relay.
- **Reconcile job (`sculkworm.reconcile`):** runs on boot and every 5 minutes. Lists routes owned by this tenant via `GET /v1/routes`, creates missing routes, fixes drifted open targets or closed authorizers, deletes routes for deleted servers (plus orphaned routes under `SCULKWORM_BASE_DOMAIN`), and skips custom-relay rows.
- **Outage handling:** a relay outage never fails a sculk.network request. Errors from the SDK are handled by `err.code`, logged without ever printing `SCULKWORM_API_KEY` or agent tokens, and retried by the reconcile job with exponential backoff (10 s up to 5 min).

## API endpoints

| Endpoint | Access | Behavior |
| --- | --- | --- |
| `GET /api/servers/:id` | `server.view` | Includes `sculkwormAddress` when `sculkworm` is enabled and an active synced route (or custom closed route) exists. |
| `GET /api/servers/:id/route` | `server.settings` | Returns `{"route":{"host","slug","mode","target","synced","relayUrl"?}}` or `{"route":null}`. Returns `404` when the flag is off or the caller lacks `server.settings`. |
| `PUT /api/servers/:id/route` | `server.settings` | Body `{"mode"?: "open" \| "closed", "target"?: "host:port" \| null, "slug"?: "...", "relayUrl"?: "https://..." \| null, "routeHost"?: "friends.play.example.org" \| null}`. Registers, updates, or clears the server's route. Returns `409 slug_collision`, `409 slug_immutable`, `409 sculkworm_not_configured`, `409 sculkworm_closed_not_configured`, `400 route_host_required` / `400` on invalid input, `404` when flag is off or caller lacks `server.settings`. |
| `POST /api/servers/:id/route/agent-token` | `server.settings` | Mints a new agent token on the shared relay for a closed route and returns `201 {"id","created_at","token"}` once with `Cache-Control: no-store`. Stores only `agent_token_id`. Returns `409 route_not_closed`, `409 relay_is_custom`, `409 sculkworm_not_configured`, `404` when flag is off, route is missing, or caller lacks `server.settings`. |
| `DELETE /api/servers/:id/route/agent-token` | `server.settings` | Revokes the current agent token on the shared relay and clears `agent_token_id`, returning `204` (`Cache-Control: no-store`). Same `404`/`409` error codes as `POST`. |
| `GET /api/servers/:id/tunnel` | `server.play` | Public-safe read returning `200 {"mode":"closed","route","relayUrl","custom"}` with `Cache-Control: no-store` when the server has an active, synced closed route (or custom closed route). Returns `404` when flag is off, caller lacks `server.play`, or the route is absent, open, or unsynced. Never exposes `target` or agent tokens. |
| `GET /api/servers/:id/export/prism` | `server.view` | When the server has an active closed route, the `sculkworm` flag is on, and the caller holds `server.play`, bundles `sculkworm-connect.jar`, adds the `connect` block to `sculk.json`, sets `OverrideJavaArgs=true` and `JvmArgs=-javaagent:../sculkworm-connect.jar=..` in `instance.cfg`, and writes `minecraft/servers.dat` pointing to `127.0.0.1:25565`. Otherwise returns the plain Prism export unchanged. |

## Worked flow (against a dev lane and real Sculkworm binary)

1. Build and start Sculkworm with a tenants file scoped to `play.sculk.test`:

```sh
cargo build --manifest-path crates/sculkworm/Cargo.toml
SCULKWORM_LISTEN=127.0.0.1:18946 \
SCULKWORM_API_ADDR=0.0.0.0:18945 \
SCULKWORM_TENANTS_FILE=/tmp/tenants.json \
SCULKWORM_STATE_FILE=/tmp/state.json \
  ./crates/sculkworm/target/debug/sculkworm &
curl -sS http://127.0.0.1:18945/healthz
```

```json
{"status":"ok"}
```

2. Bring up a dev lane pointed at the relay with `SCULK_FEATURES=sculkworm`:

```sh
pnpm lane up \
  --env SCULK_FEATURES=sculkworm \
  --env SCULKWORM_URL=http://172.30.0.1:18945 \
  --env SCULKWORM_API_KEY="$KEY" \
  --env SCULKWORM_BASE_DOMAIN=play.sculk.test
```

3. Sign in, create a server, and set its game address:

```sh
APP=http://127.0.0.1:40010
COOKIE=$(pnpm lane login 1 owner)
curl -sS -X POST "$APP/api/servers" \
  -H "Cookie: sculk_session=$COOKIE" \
  -H "Content-Type: application/json" \
  -d '{"name":"Survival SMP"}'
```

```json
{"id":"e4lytgrcw6v4fo3v","name":"Survival SMP","createdAt":"2026-11-26T23:57:40.963Z"}
```

```sh
curl -sS -X PUT "$APP/api/servers/e4lytgrcw6v4fo3v/status/game-address" \
  -H "Cookie: sculk_session=$COOKIE" \
  -H "Content-Type: application/json" \
  -d '{"gameAddress":"127.0.0.1:25565"}'

curl -sS -H "Authorization: Bearer $KEY" http://127.0.0.1:18945/v1/routes
```

```json
{"routes":[{"host":"survival-smp.play.sculk.test","target":"127.0.0.1:25565","tenant":"sculk"}]}
```

4. Update the backend target and confirm Sculkworm reflects the change:

```sh
curl -sS -X PUT "$APP/api/servers/e4lytgrcw6v4fo3v/status/game-address" \
  -H "Cookie: sculk_session=$COOKIE" \
  -H "Content-Type: application/json" \
  -d '{"gameAddress":"127.0.0.1:25566"}'

curl -sS -H "Authorization: Bearer $KEY" http://127.0.0.1:18945/v1/routes/survival-smp.play.sculk.test
```

```json
{"host":"survival-smp.play.sculk.test","target":"127.0.0.1:25566","tenant":"sculk"}
```

5. Disconnect the server and confirm the route is deleted:

```sh
curl -sS -X POST "$APP/api/servers/e4lytgrcw6v4fo3v/disconnect" \
  -H "Cookie: sculk_session=$COOKIE" \
  -H "Content-Type: application/json" \
  -d '{"confirmName":"Survival SMP"}'

curl -sS -H "Authorization: Bearer $KEY" http://127.0.0.1:18945/v1/routes
```

```json
{"ok":true}
{"routes":[]}
```

6. Restart with `SCULK_FEATURES=-sculkworm` to confirm flag-off returns `404` with `Cache-Control: no-store` and leaves Sculkworm untouched:

```sh
pnpm lane svc 1 restart app --env SCULK_FEATURES=-sculkworm
curl -sS -i "$APP/api/servers/jfiehjtlr3jvf2af/route" -H "Cookie: sculk_session=$COOKIE" | head -n 4
```

```text
HTTP/1.1 404 Not Found
cache-control: no-store
content-type: application/json
```
