<p align="center"><img src="https://docs.sculk.network/nightly/assets/crates/sculkworm/assets/banner.png" alt="Sculkworm by sculk.network: route Minecraft connections by hostname" width="100%"></p>

# Sculkworm

Sculkworm is a standalone Rust TCP relay that routes Minecraft Java Edition connections by the hostname inside the initial Handshake packet. It lets multiple Minecraft servers share a single public IP address and port `25565` without decrypting traffic or terminating the Minecraft protocol. After matching the hostname against a JSON route file, Sculkworm replays the buffered bytes to the backend and splices the TCP stream in both directions.

One relay can serve many services at once. Each service is a tenant with its own bearer key and its own domains, and registers open or closed routes for its Minecraft servers through the [HTTP admin API](https://docs.sculk.network/nightly/sculkworm/api.md) while the relay keeps running. A routes file still works for static open routes you manage by hand.

Closed routes let a Minecraft server listen on `127.0.0.1` with no open inbound port: `sculkworm-agent` (or `sculkworm agent`) dials out to the relay over TLS (`ALPN sculkworm`), and each player joins through `sculkworm-connect` (or `sculkworm connect`) after authenticating via browser redirect or device flow with an OIDC provider (including [sculk.network server membership](https://docs.sculk.network/nightly/sculkworm/sculk-authorizer.md)), Discord (with optional guild membership check), or another OAuth2 provider.

## How it works

1. A Minecraft Java Edition client connects to Sculkworm and sends the unencrypted Handshake packet (`0x00`) containing the server hostname.
2. Sculkworm parses the Handshake frame, strips any Forge `\0` suffix, normalizes the hostname (preferring the `_o` origin parameter if present), and looks it up in the in-memory route table loaded from `SCULKWORM_ROUTES_FILE`.
3. If a route matches, Sculkworm opens a TCP connection to the backend `host:port`, replays every buffered byte received so far verbatim, and splices the two TCP streams with `tokio::io::copy_bidirectional`. Unknown hostnames close with zero bytes written.

```mermaid
sequenceDiagram
    participant Client
    participant Sculkworm
    participant Routes as routes.json
    participant Backend

    Client->>Sculkworm: TCP connect + Handshake 0x00 (host="survival.play.example")
    Sculkworm->>Routes: Lookup normalized route key
    alt Route found
        Routes-->>Sculkworm: Target (host:port)
        Sculkworm->>Backend: TCP connect + replay buffered bytes
        Client<<->>Backend: Bidirectional TCP splice (opaque)
    else Unknown host
        Routes-->>Sculkworm: None
        Sculkworm--xClient: Close socket (0 bytes written)
    end
```

## Quick start

Pull a published container image from `ghcr.io/yellowumbrelladev/sculkworm` (for example `:latest`, `:nightly`, or an exact `<version>` tag from [Releases](https://github.com/YellowUmbrellaDev/sculk.network/releases)), or build it locally from source:

```sh
docker pull ghcr.io/yellowumbrelladev/sculkworm:nightly
```

To build the image locally from `crates/sculkworm` instead:

```sh
docker build -t sculkworm crates/sculkworm
```

```text
 => => naming to docker.io/library/sculkworm:latest
```

Create a `config/` directory with a `routes.json` file mapping each hostname to a backend `host:port` target (replace `host.docker.internal:25581` and `host.docker.internal:25582` with your own Minecraft server addresses):

```sh
mkdir -p config
cat > config/routes.json <<'EOF'
{
  "routes": {
    "survival.play.example": "host.docker.internal:25581",
    "creative.play.example": "host.docker.internal:25582"
  }
}
EOF
```

Start Sculkworm mounting the `config/` directory at `/etc/sculkworm` (mounting the directory rather than the single file lets `SIGHUP` reloads see atomic file replacements). The command below binds loopback port `25595` so it does not collide with a local Minecraft server on `25565`; in production publish `-p 25565:25565` and drop `--add-host`:

```sh
docker run -d --name sculkworm \
  --add-host=host.docker.internal:host-gateway \
  -p 127.0.0.1:25595:25565 \
  -v "$PWD/config:/etc/sculkworm:ro" \
  sculkworm
```

```text
<container id>
```

Check the startup log:

```sh
docker logs sculkworm
```

```text
level=info event=listening addr=0.0.0.0:25565 routes=2
```

With a Minecraft backend listening on port `25581`, send a Minecraft Status ping (`protocol=769`, Minecraft 1.21.4) for `survival.play.example` using Node.js with no extra packages:

```sh
node --input-type=module -e '
import net from "node:net";
const enc = (n) => { const b = []; let u = n >>> 0; do { let c = u & 0x7f; u >>>= 7; if (u) c |= 0x80; b.push(c); } while (u); return Buffer.from(b); };
const frame = (id, p) => { const body = Buffer.concat([enc(id), p]); return Buffer.concat([enc(body.length), body]); };
const host = Buffer.from("survival.play.example");
const port = Buffer.alloc(2); port.writeUInt16BE(25595);
const hs = frame(0x00, Buffer.concat([enc(769), enc(host.length), host, port, enc(1)]));
const req = frame(0x00, Buffer.alloc(0));
const sock = net.connect(25595, "127.0.0.1", () => sock.write(Buffer.concat([hs, req])));
const chunks = [];
const varint = (b, o) => { let v = 0, shift = 0; while (o < b.length) { const x = b[o++]; v |= (x & 0x7f) << shift; if (!(x & 0x80)) return [v, o]; shift += 7; } };
sock.on("data", (c) => {
  chunks.push(c);
  const b = Buffer.concat(chunks);
  const len = varint(b, 0);
  if (!len || b.length < len[1] + len[0]) return;
  const id = varint(b, len[1]);
  const str = id && varint(b, id[1]);
  if (!str || b.length < str[1] + str[0]) return;
  console.log(b.subarray(str[1], str[1] + str[0]).toString("utf8"));
  sock.end();
});
'
```

```json
{"version":{"name":"1.21.4","protocol":769},"players":{"max":20,"online":0},"description":{"text":"Survival backend"}}
```

Inspect the relay logs to see the routed connection:

```sh
docker logs sculkworm
```

```text
level=info event=listening addr=0.0.0.0:25565 routes=2
level=info event=route host=survival.play.example target=host.docker.internal:25581 intent=status protocol=769 peer=172.17.0.1:52190
level=info event=closed host=survival.play.example target=host.docker.internal:25581 bytes_up=31 bytes_down=121 peer=172.17.0.1:52190
```

For the full walkthrough with two live `minecraft-protocol` backends, unknown-host checks, and live `SIGHUP` reloads, read [Getting started](https://docs.sculk.network/nightly/sculkworm/getting-started.md).

## Quick start: closed route (no open server port)

Download the prebuilt archive for your platform (or the cross-platform Java 8+ `sculkworm-connect.jar` player client) from the [Releases](https://github.com/YellowUmbrellaDev/sculk.network/releases) page (tags starting with `sculkworm-v`) and verify its checksum against `SHA256SUMS`. Linux (`x86_64-unknown-linux-musl`, `aarch64-unknown-linux-musl`) and macOS (`x86_64-apple-darwin`, `aarch64-apple-darwin`) archives include `sculkworm`, `sculkworm-agent`, and `sculkworm-connect`; Windows (`x86_64-pc-windows-gnu`, `.zip`) ships `sculkworm-connect.exe` for players; `sculkworm-connect.jar` runs on any platform with Java 8u251+ or Java 9+.

```sh
TAG=sculkworm-v0.1.0-nightly.20261127.5
VERSION=${TAG#sculkworm-v}
ARCHIVE="sculkworm-${VERSION}-x86_64-unknown-linux-musl.tar.gz"
curl -sSfLO "https://github.com/YellowUmbrellaDev/sculk.network/releases/download/${TAG}/${ARCHIVE}"
curl -sSfLO "https://github.com/YellowUmbrellaDev/sculk.network/releases/download/${TAG}/SHA256SUMS"
sha256sum -c SHA256SUMS --ignore-missing
tar -xzf "$ARCHIVE"
./sculkworm-connect --help
```

```text
sculkworm-0.1.0-nightly.20261127.5-x86_64-unknown-linux-musl.tar.gz: OK
Usage: sculkworm-connect <command> [OPTIONS]
   or: sculkworm connect <command> [OPTIONS]

Commands:
  play <host[:port]>     Log in if needed and open a local Minecraft listener for <host>
  login <host[:port]>    Log in to a closed route via browser redirect or device flow
  logout <route|--all>   Revoke and remove a stored login (or all logins)
```

Or build all three binaries from source inside `crates/sculkworm`:

```sh
cargo build --release --locked --bins
```

```text
    Finished `release` profile [optimized] target(s) in 51.49s
```

1. **Create `tenants.json` and `secrets.json` (`0600`)** on the relay host (see [Deploying closed mode](https://docs.sculk.network/nightly/sculkworm/deploy.md#1-prepare-certificates-tenantsjson-and-secretsjson-0600) for full examples defining tenant `sculk` and client `example-oidc`). Generate a 32-byte login key with `head -c 32 /dev/urandom | basenc --base64url | tr -d '='`, point your IdP's redirect URI at `${SCULKWORM_PUBLIC_URL}/login/callback`, export any `client_secret_env` variables referenced in `secrets.json`, and start the relay with `SCULKWORM_TUNNEL_LISTEN` (published on port `443` in production):

   ```sh
   SCULKWORM_LISTEN=0.0.0.0:25565 \
   SCULKWORM_API_ADDR=127.0.0.1:8080 \
   SCULKWORM_TENANTS_FILE=/etc/sculkworm/tenants.json \
   SCULKWORM_STATE_FILE=/var/lib/sculkworm/state.json \
   SCULKWORM_TUNNEL_LISTEN=0.0.0.0:8443 \
   SCULKWORM_TLS_CERT_FILE=/etc/sculkworm/tls/fullchain.pem \
   SCULKWORM_TLS_KEY_FILE=/etc/sculkworm/tls/privkey.pem \
   SCULKWORM_PUBLIC_URL=https://relay.example \
   SCULKWORM_SECRETS_FILE=/etc/sculkworm/secrets.json \
   SCULKWORM_DISCORD_SECRET="$DISCORD_SECRET" \
   SCULKWORM_OIDC_SECRET="$OIDC_SECRET" \
     ./target/release/sculkworm
   ```

   ```text
   level=info event=state_loaded routes=0
   level=info event=listening addr=0.0.0.0:25565 routes=0
   level=info event=api_listening addr=127.0.0.1:8080
   level=info event=tunnel_listening addr=0.0.0.0:8443
   ```

2. **Create the closed route and mint an agent token** via the admin API:

   ```sh
   curl -sS -X PUT \
     -H "Authorization: Bearer $KEY" \
     -H "Content-Type: application/json" \
     -d '{"mode":"closed","authorizer":{"type":"oidc","client":"example-oidc","scopes":["openid","profile"],"allow":{"claim":"groups","any_of":["minecraft"]}}}' \
     http://127.0.0.1:8080/v1/routes/friends.play.example
   ```

   ```json
   {"active":true,"agent_connected":false,"agent_token":null,"authorizer":{"allow":{"any_of":["minecraft"],"claim":"groups"},"client":"example-oidc","scopes":["openid","profile"],"type":"oidc"},"authorizer_id":"a36e0b5c286c1fd2","host":"friends.play.example","mode":"closed","tenant":"sculk"}
   ```

   ```sh
   curl -sS -X POST \
     -H "Authorization: Bearer $KEY" \
     http://127.0.0.1:8080/v1/routes/friends.play.example/agent-token
   ```

   ```json
   {"token":"swa_0d35c60dc471b165_<base64url-32-random-bytes>","id":"0d35c60dc471b165","created_at":"2026-11-27T09:06:26Z"}
   ```

3. **Run `sculkworm-agent` next to the Minecraft server** (listening on `127.0.0.1:25565`):

   ```sh
   ./target/release/sculkworm-agent \
     --relay https://relay.example \
     --route friends.play.example \
     --token-file /etc/sculkworm/agent.token \
     --target 127.0.0.1:25565
   ```

   Verify the session on the relay:

   ```sh
   curl -sS -H "Authorization: Bearer $KEY" http://127.0.0.1:8080/v1/agents
   ```

   ```json
   {"agents":[{"connected_at":"2026-11-27T09:06:26Z","host":"friends.play.example","peer":"127.0.0.1:41278","session":"e8ddcfbf3c6af4e2","software":"sculkworm-agent/0.1","streams":0,"token_id":"0d35c60dc471b165"}]}
   ```

4. **Log in and play with `sculkworm-connect`** (loopback browser login by default, or `--device` on headless hosts). `--add-server` accepts three path forms: bare `--add-server` (uses the existing OS default `.minecraft` directory), `--add-server=<dir>` (writes `<dir>/servers.dat` inside an existing directory), and `--add-server=<dir>/servers.dat` (writes that file in an existing parent directory). Leading `~` and `~/` (or `~\` on Windows) in `--add-server=<path>` expand against `HOME` (`USERPROFILE` on Windows). It never creates missing directories, follows a symlinked `servers.dat` in place (preserving its target and permissions), caps existing files at 4 MiB, and updates every entry whose `name` matches the route. Minecraft keeps the server list in memory and overwrites `servers.dat` when edited in game, so run `--add-server` while Minecraft is closed:

   ```sh
   ./target/release/sculkworm-connect play friends.play.example --add-server
   ```

   ```text
   Logged in to friends.play.example as alex (subject user-alex-42, expires 2026-12-27T09:06:35Z)
   level=info event=servers_dat_updated path="/home/alex/.minecraft/servers.dat" name=friends.play.example ip=127.0.0.1:25565
   level=info event=connect_listening route=friends.play.example listen=127.0.0.1:25565
   ```

   Passing a path that does not exist (and is not a `servers.dat` inside an existing directory) is refused with exit code `2` and creates nothing:

   ```sh
   ./target/release/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"
   ```

   Then join `127.0.0.1:25565` (or pick `friends.play.example` from Multiplayer) in Minecraft. See [Deploying closed mode](https://docs.sculk.network/nightly/sculkworm/deploy.md#deploying-closed-mode) for TLS certificate options, systemd units, Discord preset setup, and the state v2 downgrade note.

## DNS setup

Point every routed hostname at the host running Sculkworm on port `25565`:

- **Wildcard record**: add `*.play.example` as an `A` (or `AAAA`) record pointing to the relay IP, and list each subdomain in `routes.json`.
- **Custom domains**: add a `CNAME` record pointing to the relay hostname (or an `A` record pointing to the relay IP) and add that custom domain to `routes.json`.

Avoid DNS `SRV` records for custom domains until `SRV` handshake host behavior is verified against real clients (see below).

## Documentation

- [Documentation index and glossary](https://docs.sculk.network/nightly/sculkworm/index.md)
- [Getting started](https://docs.sculk.network/nightly/sculkworm/getting-started.md) — build, start local backends, ping hostnames, reload with `SIGHUP`, and shut down end to end
- [Configuration](https://docs.sculk.network/nightly/sculkworm/configuration.md) — every `SCULKWORM_*` environment variable, the routes file schema, and validation errors
- [HTTP admin API](https://docs.sculk.network/nightly/sculkworm/api.md) — tenants, bearer keys, route endpoints, limits, and error codes, plus the [OpenAPI schema](https://docs.sculk.network/nightly/sculkworm/openapi.md)
- [TypeScript SDK](https://docs.sculk.network/nightly/sculkworm/sdk/js.md) — zero-dependency `sculkworm` client for Node.js 18+, Deno, Bun, and Cloudflare Workers
- [Deploying](https://docs.sculk.network/nightly/sculkworm/deploy.md) — Docker, Docker Compose, `SIGHUP` route reloads, graceful shutdown, TCP proxies, and log events
- [Security model](https://docs.sculk.network/nightly/sculkworm/security.md) — threat model, unauthenticated hostnames, open-relay boundary, log sanitization, resource caps, and player IP visibility
- [Minecraft protocol](https://docs.sculk.network/nightly/sculkworm/protocol.md) — Handshake packet layout, Minecraft 26.4 query grammar, normalization rules, and rejection reasons
- [Contributing](https://docs.sculk.network/nightly/sculkworm/contributing.md) — building from source, Rust tests, live client check, code layout, and conventions
- [Releases](https://github.com/YellowUmbrellaDev/sculk.network/releases) — release notes, under the `sculkworm-v` tags

## Supported versions and limits

Because Sculkworm reads only the initial Handshake packet (`0x00`) and splices raw TCP bytes afterward, it does not depend on Play-state or Configuration-state packet layouts.

- **Verified with `minecraft-protocol` (`1.68.0`) on Minecraft 1.21.4 (protocol `769`)**: status pings, offline-mode full Play-state login (chat and 3 keepalive roundtrips), and online-mode encrypted login (RSA-1024 + `dev/mock-mojang` `join`/`hasJoined` + AES-128-CFB8 encrypted Play traffic) routed end to end through the compiled binary (`node tests/clients/run-all.mjs` from `crates/sculkworm`), plus Rust unit and TCP integration tests covering fragmented reads, Forge `\0FML\0` suffixes, 1024-character hosts, and live route swaps.
- **Implemented from specification and covered by wire/Rust tests, not yet verified with a real vanilla / Prism Launcher client** (see the [verification runbook](https://docs.sculk.network/nightly/sculkworm/verification.md)):
  - Online-mode encrypted login with a real Mojang/Microsoft account and vanilla launcher (automated coverage uses `minecraft-protocol` and `dev/mock-mojang`, not real Mojang session servers or Mojang-signed keys).
  - Minecraft 26.4 `_o` (origin) and `_id` Handshake host query parameters (covered by `tests/clients/handshake-26.4-srv.mjs` and Rust tests against the 26.4 specification).
  - What vanilla Minecraft Java clients older than 26.4 put in the Handshake host field after following a live DNS `SRV` record.
- **Current limits**: Handshake packet body capped at `4096` bytes; no HAProxy PROXY protocol (v1 or v2); no per-IP connection or rate limiting (only the global `SCULKWORM_MAX_CONNECTIONS` cap); backends see the relay's IP address rather than each player's IP. See [Security model](https://docs.sculk.network/nightly/sculkworm/security.md) and [Minecraft protocol](https://docs.sculk.network/nightly/sculkworm/protocol.md#verification-status).

## Roadmap

Shipped: the shared multi-tenant HTTP admin API with persisted routes, the [TypeScript SDK](https://docs.sculk.network/nightly/sculkworm/sdk/js.md), and closed routes (`sculkworm-agent` / `sculkworm agent`, `sculkworm-connect` / `sculkworm connect` with browser redirect, RFC 8628 device flow, and `--add-server`, `oidc`, `oauth2` with Discord preset, `fixed-list`, and `sculk` authorizers, and state v2; see [Deploying closed mode](https://docs.sculk.network/nightly/sculkworm/deploy.md#deploying-closed-mode), [Closed routes](https://docs.sculk.network/nightly/sculkworm/tunnel.md), and [sculk.network as an authorizer](https://docs.sculk.network/nightly/sculkworm/sculk-authorizer.md)).

- **Backlog**: UDP support and multi-region routing.

## License

Sculkworm is licensed under the [MIT License](https://github.com/YellowUmbrellaDev/sculk.network/blob/96e9a1b/crates/sculkworm/LICENSE).

Sculkworm is not affiliated with or endorsed by Mojang Studios or Microsoft. Minecraft is a trademark of Mojang Studios.
