Source: https://docs.sculk.network/nightly/sculk.md

sculk.network

One modpack for your Minecraft server and for every player who joins it.
Keep the modpack in GitHub, apply a change once, and the server and every player's launcher follow.

Documentation · Self-host · Develop · Releases · Write a plugin · Contributing

The sculk.network landing page: Manage your modpack, Play with the right mods

sculk.network manages a Minecraft modpack for a server and for every player who joins it. A server owner connects a PufferPanel or Pterodactyl server, keeps the modpack in a GitHub repository, and marks each mod and config as server-side, client-side or both. When the owner applies a change, the server gets it first. Players get it at their next Prism Launcher start, and never before the server runs it. ## What you get | | | | --- | --- | | **Modpack in GitHub** | The pack is a repository with a `sculk.json` manifest. Every change is a commit, every apply is a published version, and History can undo it. | | **Sides per file** | Mark each mod and config as server, client or both, so players never download what only the server needs. | | **Server first** | Applying a change restarts the server on the new version. Players sync at their next launch and never get a version the server does not run. | | **Panels you already use** | PufferPanel and Pterodactyl through declarative [backend plugins](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md). Console, files, power and live stats are in the same app. | | **Players and roles** | Owner, admin, moderator, user and custom roles with explicit permissions. Players link their Minecraft account by joining a server, with no Microsoft app approval. | | **One image** | The API and the web app are one Docker image on port 8080 with a SQLite file under `/data`. |

A server dashboard with live CPU, memory and player charts above the server console

Server settings, Roles: the built-in Owner, Admin and User roles and a custom Moderator role

The documentation of sculk.network, OAuthMC and Sculkworm is also published at [docs.sculk.network](https://docs.sculk.network), with both release channels (`/stable/` for the latest stable releases and `/nightly/` for `main`) and Markdown twins for AI agents. ## Run it [Host sculk.network yourself](https://docs.sculk.network/nightly/sculk/self-hosting.md) walks through the image, the settings in `.env`, sign-in, backups and upgrades. The short version: ```sh cp .env.example .env # then fill in SCULK_BASE_URL, SCULK_MASTER_KEY and one OAuth app docker compose up -d ``` The app answers on http://localhost:8080. Set `SCULK_PORT` in `.env` to use another host address and port, such as `127.0.0.1:8080` behind an https proxy, and `SCULK_IMAGE` to run a tagged image instead of building one. The named volume `sculk-data` holds the database, so `docker compose down` keeps it and `docker compose down -v` deletes it. ## The pieces | Path | What it is | | --- | --- | | [`apps/server`](https://github.com/YellowUmbrellaDev/sculk.network/blob/26cfdac/apps/server) | Hono API, jobs and SQLite migrations | | [`apps/web`](https://github.com/YellowUmbrellaDev/sculk.network/blob/26cfdac/apps/web) | React web app and landing page, in English and Spanish | | [`apps/docs`](https://docs.sculk.network/nightly/sculk/development.md#documentation-site) | The documentation site for all three products, built into one Cloudflare Worker (`docs.sculk.network`, serving `/stable/` and `/nightly/`) | | [`clients/sync`](https://docs.sculk.network/nightly/sculk/clients/sync.md) | Java sync jar that Prism Launcher runs before every launch | | [`packages/manifest`](https://github.com/YellowUmbrellaDev/sculk.network/blob/26cfdac/packages/manifest) | The `sculk.json` manifest schema and its logic | | [`packages/plugins`](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md) and [`plugins/*`](https://github.com/YellowUmbrellaDev/sculk.network/blob/26cfdac/plugins) | The backend plugin format and the PufferPanel and Pterodactyl plugins | | [`crates/oauthmc`](https://docs.sculk.network/nightly/oauthmc.md) | OAuthMC: verifies a Minecraft account when the player joins a server. Standalone, MIT | | [`crates/sculkworm`](https://docs.sculk.network/nightly/sculkworm.md) | Sculkworm: routes Minecraft connections by hostname and gates them behind a login. Standalone, MIT | OAuthMC and Sculkworm run without sculk.network. sculk.network uses OAuthMC to link Minecraft accounts and registers its servers' routes in Sculkworm, see [Sculkworm integration](https://docs.sculk.network/nightly/sculk/sculkworm-integration.md) and [OIDC provider](https://docs.sculk.network/nightly/sculk/oidc-provider.md). ## Develop You need Node.js 22 and pnpm 11. ```sh pnpm install pnpm lint pnpm typecheck pnpm test pnpm build ``` Pull requests target `main`. Every night `main` is published as a nightly, and the maintainers promote a nightly that held up to a stable release; until 1.0.0, stable is the beta. [AGENTS.md](https://github.com/YellowUmbrellaDev/sculk.network/blob/26cfdac/AGENTS.md) lists the conventions, [the development guide](https://docs.sculk.network/nightly/sculk/development.md) explains branches, CI and the dev server, and [the release guide](https://docs.sculk.network/nightly/sculk/releases.md) explains channels, versions and feature stages. `pnpm build` writes the server bundle to `apps/server/dist` and the web app to `apps/server/public`. Run it with `node apps/server/dist/index.js`. Set `SCULK_DATA_DIR` to a writable folder when you run outside the image, because the default is `/data`. `pnpm lane up` starts a private copy of the app in Docker, with mock sign-in and an optional PufferPanel and Minecraft server, to try a change by hand. The [`verify-sculk` skill](https://github.com/YellowUmbrellaDev/sculk.network/blob/26cfdac/.agents/skills/verify-sculk/SKILL.md) explains how. ## License sculk.network is free software. You can redistribute it and modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License or, at your option, any later version. `LICENSE` holds the text of version 2. `crates/oauthmc` and `crates/sculkworm` are licensed separately under the MIT License (see `LICENSE` in each crate). --- Source: https://docs.sculk.network/nightly/sculk/self-hosting.md # Host sculk.network yourself This guide runs your own copy of sculk.network with Docker Compose. Follow the sections in order. At the end of "Sign in and connect your first server" you are signed in as the owner of a connected server. You can add GitHub and CurseForge later. Every command runs in a terminal on the host. Each command block shows what it prints. Lines in angle brackets, like ``, are values that differ on your machine. ## Before you start You need: - A Linux host with Docker Engine and the Compose plugin version 2 or later. - A name or address that you and your players can reach, for example `https://sculk.example.org`. Players' launchers download mods from it. - Git and OpenSSL. Run one sculk.network container per database. Two containers on the same data volume corrupt each other's state. Check Docker and Compose: ```sh docker compose version ``` ```text Docker Compose version v2.. ``` Any version that starts with `v2` or later works. ## Get the code and build the image ```sh git clone https://github.com/YellowUmbrellaDev/sculk.network.git cd sculk.network ``` ```text Cloning into 'sculk.network'... ``` To run a specific release, check out its tag now with `git checkout `. Build the image. The build argument puts the commit into `/healthz`, so you can always see which code runs. ```sh docker build --build-arg SCULK_COMMIT="$(git rev-parse HEAD)" -t sculk . ``` `/healthz` reports the version `0.0.0-dev` for an image you build yourself. If you checked out a release tag such as `v0.2.0`, add `--build-arg SCULK_VERSION=0.2.0` and it reports that version instead. The build takes a few minutes. It ends with: ```text => => naming to docker.io/library/sculk:latest ``` ## Create the master key sculk.network encrypts panel credentials, API keys and other secrets in its database with one master key. Create it: ```sh openssl rand -base64 32 ``` ```text <44 characters ending in => ``` Store a copy of this key somewhere other than this host and other than your backups, for example in your password manager. Without it, nobody can read the secrets in the database or in a backup of it. If you lose it, [Lost the master key](#lost-the-master-key) explains how to start again without those secrets. ## Copy `.env.example` to `.env` All settings live in one file, `.env`, next to `compose.yml`. Start from the example: ```sh cp .env.example .env ``` This prints nothing. Open `.env` in an editor, fill in the two required lines, and add `SCULK_PORT` at the end: ```sh SCULK_BASE_URL=https://sculk.example.org SCULK_MASTER_KEY= SCULK_PORT=127.0.0.1:8080 ``` `SCULK_PORT` is the host address and port Compose publishes the container on. `127.0.0.1:8080` keeps it on this host only, so the only way in is your https reverse proxy. Without it, Compose publishes plain http on port 8080 on every network interface, and anyone who reaches the host skips your proxy. Keep it in `.env` rather than typing it in the shell, so every later `docker compose up -d` uses it. Use another port, such as `127.0.0.1:9000`, if 8080 is taken. Keep `.env` private. It holds your master key and, later, your OAuth and GitHub secrets. Never commit it. This table lists every setting. Optional settings are commented out in `.env.example` with their default value. | Name | Required | Default | Secret | What it does | Explained in | | --- | --- | --- | --- | --- | --- | | `SCULK_COMMIT` | no | | no | Commit that /healthz prints. The image build sets it. | [Get the code and build the image](#get-the-code-and-build-the-image) | | `SCULK_VERSION` | no | | no | Version that /healthz and the User-Agent print. The release build sets it; 0.0.0-dev otherwise. | [Get the code and build the image](#get-the-code-and-build-the-image) | | `SCULK_MASTER_KEY` | yes | | yes | 32 random bytes in base64 that seal stored secrets. | [Create the master key](#create-the-master-key) | | `SCULK_BASE_URL` | yes | | no | Public https origin players and owners reach. | [Copy .env.example to .env](#copy-envexample-to-env) | | `SCULK_OIDC_ADMINS` | no | | no | Comma-separated user IDs allowed to manage OIDC clients, grants, and signing keys. | [Serve as an OpenID Connect provider](#serve-as-an-openid-connect-provider) | | `SCULK_TRUSTED_PROXIES` | no | | no | Comma-separated trusted reverse-proxy IPs or CIDRs whose X-Forwarded-For header is read for rate limiting. | [Start sculk.network](#start-sculknetwork) | | `SCULK_PUBLIC` | no | | no | Set to 1 on an instance open to the internet. | [Copy .env.example to .env](#copy-envexample-to-env) | | `SCULK_DEV_IDP_URL` | no | | no | Development only. Sends sign-in to a mock provider. | [Copy .env.example to .env](#copy-envexample-to-env) | | `SCULK_LOG_LEVEL` | no | | no | Set to debug to log each file the client channel reads. | [Copy .env.example to .env](#copy-envexample-to-env) | | `SCULK_FEATURES` | no | | no | Comma-separated feature names to force on, or off with a leading -. See docs/releases.md#feature-stages. | [Copy .env.example to .env](#copy-envexample-to-env) | | `SCULK_CONTACT` | no | `https://github.com/YellowUmbrellaDev/sculk.network` | no | Contact URL sent to Modrinth and Mojang. | [Copy .env.example to .env](#copy-envexample-to-env) | | `SCULK_IMPORT_MAX_MB` | no | `512` | no | Largest modpack upload, in MB. | [Copy .env.example to .env](#copy-envexample-to-env) | | `SCULK_MODRINTH_BASE` | no | `https://api.modrinth.com/v2` | no | Modrinth API base URL. | [Copy .env.example to .env](#copy-envexample-to-env) | | `SCULK_MODRINTH_RPM` | no | `250` | no | Modrinth requests per minute. | [Copy .env.example to .env](#copy-envexample-to-env) | | `SCULK_MOJANG_BASE_URL` | no | `https://api.minecraftservices.com` | no | Mojang API base URL. | [Copy .env.example to .env](#copy-envexample-to-env) | | `GOOGLE_CLIENT_ID` | no | | no | Google OAuth client ID. | [Create one OAuth app](#create-one-oauth-app) | | `GOOGLE_CLIENT_SECRET` | no | | yes | Google OAuth client secret. | [Create one OAuth app](#create-one-oauth-app) | | `DISCORD_CLIENT_ID` | no | | no | Discord OAuth client ID. | [Create one OAuth app](#create-one-oauth-app) | | `DISCORD_CLIENT_SECRET` | no | | yes | Discord OAuth client secret. | [Create one OAuth app](#create-one-oauth-app) | | `MICROSOFT_CLIENT_ID` | no | | no | Microsoft OAuth client ID. | [Create one OAuth app](#create-one-oauth-app) | | `MICROSOFT_CLIENT_SECRET` | no | | yes | Microsoft OAuth client secret. | [Create one OAuth app](#create-one-oauth-app) | | `SCULK_MS_VERIFY` | no | | no | Set to 1 to let players prove Minecraft ownership. | [Create one OAuth app](#create-one-oauth-app) | | `SCULK_NAME_CLAIM` | no | | no | Set to 1 to let players link a Minecraft name they type, with no proof. | [Create one OAuth app](#create-one-oauth-app) | | `SCULK_OAUTHMC_URL` | no | | no | Base URL of the OAuthMC HTTP API, for example http://oauthmc:8080. | [Verify Minecraft accounts by joining a server](#verify-minecraft-accounts-by-joining-a-server) | | `SCULK_OAUTHMC_KEY` | no | | yes | Bearer API key for OAuthMC (must match OAUTHMC_API_KEYS). | [Verify Minecraft accounts by joining a server](#verify-minecraft-accounts-by-joining-a-server) | | `SCULK_OAUTHMC_ADDRESS` | no | | no | Minecraft server address players join to get their code, for example verify.sculk.network. | [Verify Minecraft accounts by joining a server](#verify-minecraft-accounts-by-joining-a-server) | | `SCULKWORM_URL` | no | | no | Base URL of the Sculkworm HTTP admin API, for example http://sculkworm:8080. | [Route servers through Sculkworm](#route-servers-through-sculkworm) | | `SCULKWORM_API_KEY` | no | | yes | Tenant bearer API key for Sculkworm (must match SCULKWORM_TENANTS_FILE). | [Route servers through Sculkworm](#route-servers-through-sculkworm) | | `SCULKWORM_BASE_DOMAIN` | no | | no | Base domain under which sculk.network registers server routes, for example play.sculk.network. | [Route servers through Sculkworm](#route-servers-through-sculkworm) | | `SCULKWORM_PUBLIC_URL` | no | | no | Public https URL players use to reach the shared Sculkworm relay, for example https://relay.sculk.network. | [Route servers through Sculkworm](#route-servers-through-sculkworm) | | `SCULKWORM_OIDC_CLIENT` | no | | no | OIDC client name in the relay secrets file that points at this sculk.network instance, for example sculk-main. | [Route servers through Sculkworm](#route-servers-through-sculkworm) | | `PORT` | no | `8080` | no | Port inside the container. | [Start sculk.network](#start-sculknetwork) | | `GITHUB_APP_ID` | no | | no | GitHub App ID. | [Add the GitHub App](#add-the-github-app) | | `GITHUB_APP_SLUG` | no | | no | GitHub App slug, from its public URL. | [Add the GitHub App](#add-the-github-app) | | `GITHUB_APP_CLIENT_ID` | no | | no | GitHub App client ID. | [Add the GitHub App](#add-the-github-app) | | `GITHUB_APP_CLIENT_SECRET` | no | | yes | GitHub App client secret. | [Add the GitHub App](#add-the-github-app) | | `GITHUB_APP_PRIVATE_KEY_FILE` | no | | no | Path in the container to the App private key. | [Add the GitHub App](#add-the-github-app) | | `GITHUB_APP_PRIVATE_KEY` | no | | yes | The App private key inline, instead of a file. | [Add the GitHub App](#add-the-github-app) | | `SCULK_GITHUB_BRANCH_ALLOW` | no | | no | Regular expression of branch names sculk may write. | [Add the GitHub App](#add-the-github-app) | | `CURSEFORGE_API_KEY` | no | | yes | CurseForge API key for the whole instance. | [Add the CurseForge key](#add-the-curseforge-key) | | `SCULK_CURSEFORGE_BASE` | no | `https://api.curseforge.com` | no | CurseForge API base URL. | [Add the CurseForge key](#add-the-curseforge-key) | | `SCULK_CURSEFORGE_RPM` | no | `120` | no | CurseForge requests per minute per key. | [Add the CurseForge key](#add-the-curseforge-key) | | `SCULK_PLUGIN_DIR` | no | | no | Folder whose *.plugin.json files every user may connect with. | [Add plugins for the whole instance](#add-plugins-for-the-whole-instance) | | `SCULK_MASTER_KEY_OLD` | no | | yes | Earlier master keys, comma-separated, while you rotate. | [Back up and restore](#back-up-and-restore) | | `SCULK_ALLOW_UNREADABLE_SECRETS` | no | | no | Set to 1 to start when the master key opens none of the stored secrets. | [Back up and restore](#back-up-and-restore) | | `SCULK_DATA_DIR` | no | `/data` | no | Folder that holds sculk.db. | [Back up and restore](#back-up-and-restore) | | `SCULK_DEV_PLUGIN_HOSTS` | no | | no | Development only. Exact host:port entries a user plugin may reach on a private address. Never set it in production. | [Development](#development) | ### Settings that change how the instance behaves `SCULK_BASE_URL` is the public origin of your instance, with no trailing slash. It must be the https address players reach. sculk.network uses it for: - When it starts with `https://`, the `sculk_session`, `sculk_oauth` and `sculk_oidc_consent` cookies get the `Secure` flag, so browsers only send them over https. - A sign-out request whose `Origin` header differs from it is refused. - It builds the OAuth redirect URIs, `/auth//callback`. - It builds the URLs in the client channel, installer and packwiz exports, which players' launchers download from. - It is the `issuer` and endpoint base URL when the [OpenID Connect provider](#serve-as-an-openid-connect-provider) is enabled. `SCULK_PUBLIC=1` turns on the protections an instance open to strangers needs. Panel addresses that are, or resolve to, private, loopback or link-local IP addresses are refused, both when an owner connects a panel and when sculk.network pings a server. Downloads of modpacks, CurseForge files, deployment files and plugin requests go through `outboundFetch` with the same address guard, a fixed host list and a size limit. It cannot be set together with `SCULK_DEV_IDP_URL` or `SCULK_DEV_PLUGIN_HOSTS`, and the server refuses to start if either is set alongside it. The public instance at sculk.network runs with `SCULK_PUBLIC=1`. A self-hosted instance on a private network leaves `SCULK_PUBLIC` unset, so it can reach a panel on a LAN address such as `http://192.168.1.20:8080`. That holds for the bundled plugins and the plugins in `SCULK_PLUGIN_DIR`, not for a plugin a user installed: see [Plugins your users install can't reach your network](#plugins-your-users-install-cant-reach-your-network). `SCULK_FEATURES` overrides [feature stages](https://docs.sculk.network/nightly/sculk/releases.md#feature-stages): a comma-separated list of feature names to force on, or off with a leading `-` (for example `SCULK_FEATURES=oidcProvider,sculkworm` or `SCULK_FEATURES=-sculkworm`). Boot fails if a name is not in `apps/server/src/config/features.ts`. `GET /api/build` reports the version, the channel (`dev`, `nightly` or `stable`) and the enabled flags. `CURSEFORGE_API_KEY` turns on CurseForge for every server on the instance: search, import of CurseForge modpacks and creating a server from one. Without it, CurseForge stays off: the owners see a notice that asks them to ask you for the key. `SCULK_LOG_LEVEL=debug` adds one `channel: read files/` line to the log for each file a player's launcher downloads. Leave it unset in normal use. ## Create one OAuth app People sign in with Google, Discord or Microsoft. You need at least one OAuth app with one of them. Each provider asks for a redirect URI. Use exactly: ```text /auth//callback ``` where `` is `google`, `discord` or `microsoft`. For example, `https://sculk.example.org/auth/discord/callback`. - Google: in the Google Cloud console, open "APIs & Services", then "Credentials", and create an "OAuth client ID" of type "Web application". Add the redirect URI. - Discord: in the Discord Developer Portal, create an application and open "OAuth2". Add the redirect URI. - Microsoft: in the Microsoft Entra admin center, register an application for "Accounts in any organizational directory and personal Microsoft accounts". Add the redirect URI under the "Web" platform, then create a client secret. Copy the secret's **Value**, which Entra shows only once, not its **Secret ID**. sculk.network refuses to start when `MICROSOFT_CLIENT_SECRET` is a Secret ID. Copy the client ID and the client secret into `.env`. For Discord: ```sh DISCORD_CLIENT_ID= DISCORD_CLIENT_SECRET= ``` Use `GOOGLE_` or `MICROSOFT_` in the names for the other providers. You can set more than one provider. The sign-in page shows a button for each. `SCULK_MS_VERIFY=1` lets players prove they own their Minecraft account with the same Microsoft app. It needs a second redirect URI, `/auth/minecraft/callback`, and Mojang's approval of the app's client ID ([form](https://aka.ms/AppRegistrationForm)). Until Mojang approves it, **Verify with Microsoft** answers "Microsoft did not allow this check. Your claim stays unverified." Microsoft is the only way to link a Minecraft account unless you turn on [Verify Minecraft accounts by joining a server](#verify-minecraft-accounts-by-joining-a-server) or opt in to `SCULK_NAME_CLAIM=1`. That setting lets a player link any name they type, with no proof, so anyone can take someone else's name until its owner verifies it with Microsoft or by joining. A claimed name never seats a member or reaches a whitelist on its own: an owner has to confirm it. Without the setting, `PUT /api/account/minecraft` answers `403 {"error":"name_claim_disabled"}` and `/account` shows no name box. Names claimed earlier stay linked, and their owners can unlink them or verify them. ## Verify Minecraft accounts by joining a server If you do not want to wait for Mojang to approve a Microsoft Entra app, players can verify their Minecraft Java Edition account by joining an OAuthMC server. Players on Minecraft 1.21.6 or later get an in-game dialog with a clickable verification link (`SCULK_BASE_URL` must start with `https://` for link mode; otherwise sculk.network falls back to code mode automatically). Older clients and fallback cases disconnect with a one-time 8-character code that the player types on `/account`. `compose.yml` ships OAuthMC under the optional `oauthmc` profile, built from `./crates/oauthmc` in this checkout, so it stays off until you enable it. 1. Generate a random API key (at least 32 characters): ```sh openssl rand -hex 24 ``` ```text <48 hex characters> ``` 2. Add the three settings to `.env`: ```sh SCULK_OAUTHMC_URL=http://oauthmc:8080 SCULK_OAUTHMC_KEY= SCULK_OAUTHMC_ADDRESS=verify.example.org ``` All three must be set for **Verify by joining a server** to appear on `/account`. The HTTP API stays on Compose's internal network; only the Minecraft port (`OAUTHMC_PORT`, default `25565`) is published. 3. Build OAuthMC and start both services with the `oauthmc` profile. Build only `oauthmc`: `--build` on `up` would also rebuild `sculk` without its commit, and `/healthz` would print `"commit":"unknown"`. ```sh docker compose --profile oauthmc build oauthmc docker compose --profile oauthmc up -d ``` ```text Image oauthmc Built Container sculknetwork-oauthmc-1 Started Container sculknetwork-sculk-1 Started ``` 4. Point DNS at the host so players can connect to `SCULK_OAUTHMC_ADDRESS`: - If port `25565` is free on your host, add an `A` (or `AAAA`) record pointing `verify.example.org` at your host's IP address. - If another Minecraft server already uses `25565`, set `OAUTHMC_PORT=25566` in `.env` and add a DNS `SRV` record so players still type `verify.example.org` without a port: ```text _minecraft._tcp.verify.example.org. 300 IN SRV 0 5 25566 verify-host.example.org. ``` 5. Open Minecraft Java Edition, add `verify.example.org` to your Multiplayer server list, and check that the entry shows online with the MOTD `OAuthMC account verification` / `Join to get your code`. ## Serve as an OpenID Connect provider sculk.network can act as an OpenID Connect 1.0 provider (issuer `SCULK_BASE_URL`, discovery at `/.well-known/openid-configuration`) so relying parties such as Sculkworm can authenticate players and read which servers they may play on (`sculk:servers`). See [sculk.network as an OpenID Connect provider](https://docs.sculk.network/nightly/sculk/oidc-provider.md) for the discovery document, protocol rules, and worked flow. This integration is currently behind the `oidcProvider` [feature stage](https://docs.sculk.network/nightly/sculk/releases.md#feature-stages) (`nightly`: enabled by default on `dev` and `nightly` builds, off on `stable` unless forced with `SCULK_FEATURES=oidcProvider`). To manage OIDC clients, grants, blocked subjects, and signing keys through `/api/oidc/*`, list the allowed user IDs in `.env`. When `SCULK_OIDC_ADMINS` is unset or empty, `/api/oidc/*` returns `403`: ```sh SCULK_OIDC_ADMINS=, ``` ## Route servers through Sculkworm When you run a shared Sculkworm Minecraft TCP relay (`crates/sculkworm`), sculk.network can automatically register `.` addresses for the servers it manages, update them when a server's backend address changes, and remove them when a server is disconnected. See [Sculkworm integration](https://docs.sculk.network/nightly/sculk/sculkworm-integration.md) for the full setup, API reference, and worked flow. This integration is currently behind the `sculkworm` [feature stage](https://docs.sculk.network/nightly/sculk/releases.md#feature-stages) (`nightly`: enabled by default on `dev` and `nightly` builds, off on `stable` unless forced with `SCULK_FEATURES=sculkworm`). Set all three variables in `.env` to turn it on; leaving any of them unset disables it: ```sh SCULKWORM_URL=http://sculkworm:8080 SCULKWORM_API_KEY= SCULKWORM_BASE_DOMAIN=play.example.org ``` ## Start sculk.network ```sh docker compose up -d ``` ```text Network sculknetwork_default Created Volume sculknetwork_sculk-data Created Container sculknetwork-sculk-1 Started ``` Check that it answers. Use the port from `SCULK_PORT` if you changed it. ```sh curl -s http://localhost:8080/healthz ``` ```json {"ok":true,"version":"0.0.0-dev","commit":""} ``` The `commit` is the output of `git rev-parse HEAD` from the build step. If `curl` prints nothing, read the log: ```sh docker compose logs sculk ``` The last line of a healthy start is `listening on :8080`. Any line before it that starts with an error names the setting to fix in `.env`. After you change `.env`, run `docker compose up -d` again. The container answers on the address in `SCULK_PORT`, `127.0.0.1:8080` above. Point your https reverse proxy at it, so that `SCULK_BASE_URL` reaches this port. Never publish that port to the internet without the proxy in front. When running behind a reverse proxy, set `SCULK_TRUSTED_PROXIES` to the proxy's IP address or CIDR (for example `127.0.0.1,::1` for a proxy on the same host, or `172.17.0.0/16` for a Docker bridge) and configure the proxy to append the client IP to `X-Forwarded-For`. Otherwise rate limiting sees every request coming from the proxy's address and shares one per-IP bucket across all users. Only list addresses controlled by your proxy: sculk.network reads the rightmost `X-Forwarded-For` hop that is not in `SCULK_TRUSTED_PROXIES`, ignores `X-Forwarded-For` when the direct socket peer is untrusted, and groups IPv6 clients by `/64`. ## Sign in and connect your first server 1. Open `SCULK_BASE_URL` in your browser and press **Sign in**. 2. Choose your provider and sign in. You land on your account page. 3. Open `/servers` and press **Connect a server**. 4. The form **Add a connection** is open. Choose your panel's plugin, PufferPanel or Pterodactyl, and fill in the panel URL and its credentials: - PufferPanel: create an OAuth2 client in your PufferPanel account settings, and copy its client ID and client secret. - Pterodactyl: create an application API key in the admin area and a client API key in your account, and copy both. 5. Press **Test**. It shows `Connected, 1 server`, or `Connected, servers` when the panel holds more. Press **Save**. 6. Choose the server from the list, give it a name, and press **Connect server**. The server's connection settings open. Press **Server page** (or open `/servers`), and your server shows with you as **Owner**. If **Test** shows "This panel address isn't allowed", the instance runs with `SCULK_PUBLIC=1` and the panel URL points to a private address. See [Settings that change how the instance behaves](#settings-that-change-how-the-instance-behaves). ## Set the server icon and message Minecraft shows two things about a server in the multiplayer list: `server-icon.png` and the `motd` line of `server.properties`. Both live in **Settings**, then **Server details**, the first section. Each saves to the draft; Minecraft reads them at startup, so open **Config**, press **Apply** and restart for them to go live. ### Icon The icon has to be a 64 x 64 PNG in the server root, so sculk.network converts what you pick. 1. Press **Choose an image** and pick a PNG, JPEG or WebP of up to 2 MiB. The image is cropped to its centre square and resized to 64 x 64. 2. **Draft** shows the result. **Live** changes only once the server restarts. The icon is the modpack file `server-icon.png`, so **History** lists it and you can undo it. A GIF answers `415` and a file over 2 MiB answers `413`; both leave the draft as it was. The icon appears beside the server name in `/servers` and in the server header, and the Prism and installer downloads carry it. The exports differ in what they can carry: | Export | Icon | | --- | --- | | Minecraft server | `server-icon.png` in the root, shown by Server List Ping | | Prism instance (`.zip`) | `iconKey=sculk-` in `instance.cfg` and `sculk-.png` at the instance root, which Prism installs as the instance icon | | Installer (`.jar`) | `iconKey` in `sculk-installer.json` and `server-icon.png` inside the jar, shown in the installer window and installed as the launcher icon | | `.mrpack` | None. `modrinth.index.json` has no icon field | | packwiz | None. `pack.toml` has no icon field | ### Message of the day **Message of the day** edits the `motd` line of the draft's `server.properties`. When the draft has no such file yet, the section says so: press **Import server.properties from the server** to bring in the server's own file, with its port and other settings, before you edit. 1. Click the preview and type, or paste text with `&` or `§` codes; pick a colour or a style from the toolbar (or press `Ctrl+B`, `Ctrl+I`, `Ctrl+U`) to style selected text or what you type next. 2. The preview draws the entry as the pack's Minecraft version draws it: the 2-line limit, the width each line wraps at (271 pixels up to 1.21.8, 267 from 1.21.9) and the text shadow (from 1.21.4). Under it, each line shows its width in pixels. **Centre** pads each line with spaces to the middle. 3. Press **Save to the draft**. Only the `motd` line changes; every other line of `server.properties` stays as it was. The saved line is what a vanilla server reads, for example: ```properties motd=\u00A76\u00A7lSculk \u00A77network\n\u00A7bplay ``` A vanilla, Fabric, Quilt, Forge or NeoForge server shows only the 16 legacy colours in this line: no hex colours, gradients or MiniMessage. **Source code** (shown outside Simplified view) reads and writes `&` codes, `§` codes, MiniMessage, JSON text components and the `server.properties` line, so you can bring a message from another tool or take this one to a Velocity or BungeeCord proxy. Hex colours and gradients on import become the nearest of the 16 colours, and the section says so. ## Add the GitHub App sculk.network keeps each modpack in a GitHub repository. It writes there through a GitHub App that you own. 1. On GitHub, open "Settings", then "Developer settings", then "GitHub Apps", and press "New GitHub App". To own it with an organization, open the organization's settings instead. 2. Fill in: - "Homepage URL": your `SCULK_BASE_URL`. - "Callback URL": `/auth/github/callback`. - Check "Request user authorization (OAuth) during installation". - Under "Webhook", clear "Active". - Under "Repository permissions", set "Contents" to "Read and write" and "Administration" to "Read and write". "Metadata" becomes "Read-only". "Administration" is what lets sculk.network create a new repository for a server. Without it, servers can still use a repository that already exists. 3. Create the App. On its page, note the "App ID" and the "Client ID". The slug is the last part of its public link, `https://github.com/apps/`. 4. Press "Generate a new client secret" and copy it. 5. Press "Generate a private key". GitHub downloads a `.pem` file. Add the values to `.env`: ```sh GITHUB_APP_ID= GITHUB_APP_SLUG= GITHUB_APP_CLIENT_ID= GITHUB_APP_CLIENT_SECRET= ``` Add the private key on one line. Replace the file name with yours: ```sh printf 'GITHUB_APP_PRIVATE_KEY=%s\n' "$(awk '{printf "%s\\n", $0}' .private-key.pem)" >> .env docker compose up -d ``` ```text Container sculknetwork-sculk-1 Started ``` On your server page, open **Settings**, then **GitHub**, and press **Install the GitHub App**. GitHub asks you to authorize the App and then where to install it. Pick the repositories sculk.network may use. If the App is already installed on your account or organization, GitHub does not ask again: sculk.network finds the installations you can see and registers them, so you never need to uninstall first. When you create or link a server, the repository step has two views: - **New repository** (the default) creates an empty repository, adds `sculk.json` and a `README.md` on the production branch, and creates the staging branch from it. The branch names start as `main` and `staging` and you can change them. A new repository needs two things from GitHub. The installation must be on an **organization**, because GitHub does not let a GitHub App create repositories on a personal account. And the App needs the "Administration" permission, which for an App you already created means opening its settings, adding "Administration: Read and write", and accepting the change on the installation (GitHub emails the owner and shows a banner on the installation page). Until both are true, the view explains what is missing and the **Existing repository** view stays available. - **Existing repository** assumes the repository already holds a sculk.network server. You pick it, then pick the production and staging branches from the ones it has. Both need a valid `sculk.json`. sculk.network reads the Minecraft version and the loader from the production branch and writes nothing to the repository. ## Add the CurseForge key CurseForge needs an API key. Ask for one in the CurseForge console at `https://console.curseforge.com`. The key belongs to the instance, so there is no setting per server: put it in `.env` and run `docker compose up -d`: ```sh CURSEFORGE_API_KEY= ``` Until you do, searching CurseForge, importing a CurseForge modpack and creating a server from one show "This sculk.network has no CurseForge key. Ask the operator to set CURSEFORGE_API_KEY.". Earlier versions let each owner save a key of their own in the server settings. That setting is gone and the keys saved there are deleted on upgrade, so set `CURSEFORGE_API_KEY` before you upgrade if any of your servers used one. ## Add plugins for the whole instance Each user can install their own panel plugin on their **Plugins** page. To offer a plugin to every user of the instance instead, put it on the `/data` volume: 1. Create a folder such as `/data/plugins` on the volume and copy your `*.plugin.json` files into it. Files in subfolders count too, and other files are ignored. 2. Set the folder in `.env`: ```sh SCULK_PLUGIN_DIR=/data/plugins ``` 3. Run `docker compose up -d` to restart. The plugins show under "This instance" when someone presses "Add a connection". sculk.network checks every file at start. An invalid file, or a file whose id a bundled plugin such as `pufferpanel` already has, stops the start, and `docker compose logs sculk` shows the reason: ```text SCULK_PLUGIN_DIR: /data/plugins/a/bad.plugin.json: /actions/listServers/steps/0/request/path uses url variable "url" SCULK_PLUGIN_DIR: /data/plugins/p.plugin.json uses id "pufferpanel", which a bundled plugin has ``` Fix or remove the file and start again. A user who installs a plugin by URL needs an `https` URL whose certificate the instance trusts. Plain `http` URLs are refused. ### Plugins your users install can't reach your network Anyone who can sign in can install a plugin, and a plugin decides which requests sculk.network sends. So a plugin a user installed is never trusted to reach private addresses, whether or not `SCULK_PUBLIC` is set: - Installing it is refused when one of its hosts is, or resolves to, a private, loopback or link-local address. - Every request it sends, the panel address and the sign-in request to the panel included, is refused when it goes to such an address. **Test** then shows "This panel address isn't allowed". The plugins you ship are different: bundled plugins and the ones in `SCULK_PLUGIN_DIR` are your code, and on an instance without `SCULK_PUBLIC` they reach a panel on your LAN as before. If a user needs a plugin for a panel on your network, review it and put it in `SCULK_PLUGIN_DIR`. ## Back up and restore A backup is the data volume, which holds `sculk.db`, plus your master key. One is useless without the other. Stop the container, so the database is complete on disk, copy the volume, and start again: ```sh docker compose stop docker compose cp sculk:/data ./sculk-backup docker compose start ``` ```text Container sculknetwork-sculk-1 Stopped sculknetwork-sculk-1 Copied sculknetwork-sculk-1:/data to ./sculk-backup Container sculknetwork-sculk-1 Started ``` Keep `./sculk-backup` off the host, and keep it apart from your master key. Store the key somewhere else, such as your password manager, and never next to the backup or in `.env` beside it. Anyone who holds both can read every panel credential, channel token and API key in the backup. You need both to restore: without the key, the secrets in the backup can't be read. To restore, start from a working `compose.yml` and a `.env` that holds the master key the backup was sealed with. Remove the container and its volume if they exist, copy the backup into a new volume, and start: ```sh docker compose down -v docker compose run --rm --no-deps -v "$PWD/sculk-backup:/backup:ro" sculk cp -r /backup/. /data/ docker compose up -d ``` `docker compose down -v` deletes the data volume. Run it only when you hold a backup. The copy runs inside the image, so the restored files belong to the user the server runs as. ### Start with the wrong key If `SCULK_MASTER_KEY` opens none of the stored secrets, the server refuses to start and names the problem. `docker compose logs sculk` shows, once per attempt: ```text sealed: values have no key, kid=<8 hex characters> sealed: SCULK_MASTER_KEY opens none of the stored secrets (kid=<8 hex characters>). Start with the key that sealed them, or set SCULK_ALLOW_UNREADABLE_SECRETS=1 to start without them. ``` The container keeps restarting and `/healthz` does not answer. Put the right key in `.env` and run `docker compose up -d`. If the key opens some secrets but not others, the server starts. Each `sealed: values have no key` line in the log counts secrets that an earlier key sealed. Those secrets stay unreadable. For panel credentials, the server's connection settings show "The saved credentials can't be read. Replace them to reconnect the panel." ### Lost the master key If the key is gone for good, you can still start the instance. Users, servers, members and modpack history are not encrypted and stay as they are. Every secret is lost: panel credentials, channel tokens, server secrets. 1. Create a new key with `openssl rand -base64 32` and put it in `SCULK_MASTER_KEY` in `.env`. Store a copy as in [Create the master key](#create-the-master-key). 2. Add `SCULK_ALLOW_UNREADABLE_SECRETS=1` to `.env` and run `docker compose up -d`. The server starts and logs how many secrets it can't read. 3. Each owner opens **Settings**, then **Connection**, on their server and presses **Replace credentials** to enter the panel credentials again. Re-enter any other secret the same way. 4. Remove `SCULK_ALLOW_UNREADABLE_SECRETS` from `.env` and run `docker compose up -d`. From now on the server starts as long as the new key opens at least one stored secret. ### Change the master key Move the current key to `SCULK_MASTER_KEY_OLD`, put a new key in `SCULK_MASTER_KEY`, and run `docker compose up -d`. The server re-encrypts every secret with the new key at start. Remove `SCULK_MASTER_KEY_OLD` after that start. ## Upgrade Back up first. Then fetch the new code, rebuild the image and restart. If you run a published image instead, set `SCULK_IMAGE` to the channel you want and run `docker compose pull && docker compose up -d`; [Switch channels on an instance](https://docs.sculk.network/nightly/sculk/releases.md#switch-channels-on-an-instance) lists the tags and why a nightly database cannot go back to stable. If your instance predates `.env`, create it before you restart: follow [Copy `.env.example` to `.env`](#copy-envexample-to-env) and [Create one OAuth app](#create-one-oauth-app). Compose refuses to start without it. Your data stays in the volume `sculknetwork_sculk-data`, because `compose.yml` fixes the project name to `sculknetwork`. Check that the volume exists before you start: ```sh docker volume ls --filter name=sculknetwork_sculk-data ``` ```text DRIVER VOLUME NAME local sculknetwork_sculk-data ``` If the list is empty and you ran sculk.network before, your data is in a volume with another prefix: Compose named it after the folder you ran it from. Find it with `docker volume ls --filter name=sculk-data`, then copy it into the new name before you start: ```sh docker volume create sculknetwork_sculk-data docker run --rm --user root -v :/from:ro -v sculknetwork_sculk-data:/to sculk sh -c 'cp -a /from/. /to/' ``` The copy runs as root so it can write into the new volume, and `cp -a` keeps the files owned by the user the server runs as. Then upgrade: ```sh git pull docker build --build-arg SCULK_COMMIT="$(git rev-parse HEAD)" -t sculk . docker compose up -d curl -s http://localhost:8080/healthz ``` ```json {"ok":true,"version":"","commit":""} ``` If you enabled the `oauthmc` profile, rebuild OAuthMC and restart it too. Build only `oauthmc`: `--build` on `up` would also rebuild `sculk` without its commit, and `/healthz` would print `"commit":"unknown"`. ```sh docker compose --profile oauthmc build oauthmc docker compose --profile oauthmc up -d ``` ```text Image oauthmc Built Container sculknetwork-oauthmc-1 Started Container sculknetwork-sculk-1 Running ``` The server applies database migrations when it starts. You don't run anything else. ## Development These settings exist for working on sculk.network itself. Don't set them on an instance people use. `SCULK_DEV_PLUGIN_HOSTS` lists exact `host:port` entries, such as `fake-panel:8080`, that a user plugin may reach even though they are private addresses. The development lanes set it for their fake panel. It never lets a request through to a link-local or cloud metadata address, the server refuses to start when it is set together with `SCULK_PUBLIC=1`, and it prints a warning that names the entries at every start. --- Source: https://docs.sculk.network/nightly/sculk/sculkworm-integration.md # 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 `.` 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": ""}`) 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 | `` | 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 `.`. | | `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": "", "allow": {"sculk_server": ""}}}`. - 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 `.`, 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": ""}` (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. | ## 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 ``` --- Source: https://docs.sculk.network/nightly/sculk/oidc-provider.md # sculk.network as an OpenID Connect provider When the `oidcProvider` feature flag is enabled, sculk.network acts as an OpenID Connect 1.0 provider so relying parties such as Sculkworm can authenticate players and inspect which servers on the instance they may play on. ## Enabling the feature `oidcProvider` is currently 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=oidcProvider` or `SCULK_FEATURES=-oidcProvider`. When the flag is off, every OIDC endpoint (`/.well-known/openid-configuration`, `/oauth/*`, `/api/oidc/*`) responds `404 {"error":"not_found"}` with `Cache-Control: no-store`. ## Discovery document `GET /.well-known/openid-configuration` (also served at `GET /oauth/.well-known/openid-configuration`) returns the provider metadata with `Cache-Control: no-store`. Replace `https://sculk.example` with your `SCULK_BASE_URL`: ```json { "issuer": "https://sculk.example", "authorization_endpoint": "https://sculk.example/oauth/authorize", "token_endpoint": "https://sculk.example/oauth/token", "userinfo_endpoint": "https://sculk.example/oauth/userinfo", "jwks_uri": "https://sculk.example/oauth/jwks.json", "response_types_supported": ["code"], "grant_types_supported": ["authorization_code", "refresh_token"], "subject_types_supported": ["public"], "id_token_signing_alg_values_supported": ["RS256"], "scopes_supported": ["openid", "profile", "offline_access", "sculk:servers"], "token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post", "none"], "code_challenge_methods_supported": ["S256"], "claims_supported": [ "iss", "sub", "aud", "exp", "iat", "auth_time", "nonce", "preferred_username", "picture", "sculk_servers" ] } ``` ## Protocol rules and claims - **Grant types:** `authorization_code` (with mandatory PKCE `S256`; `plain` is rejected) and `refresh_token` (only when `offline_access` was granted). Implicit, hybrid, and password grants are not supported. - **Redirect URIs:** exact string match against the client's registered list. Clients flagged `native: true` may register `http://127.0.0.1/…` or `http://[::1]/…` loopback URIs and match any loopback port (RFC 8252 §7.3). All other redirect URIs must use `https://`. Unregistered redirect URIs render an HTML error page and never redirect. - **Consent:** first-party clients (`firstParty: true`) auto-approve; third-party clients show a consent prompt the first time per subject and scope set. - **ID tokens:** signed with RS256 using an RSA-2048 key generated asynchronously on first use and stored sealed under `SCULK_MASTER_KEY`. Lifetime is 10 minutes (`exp - iat = 600`). - Standard claims: `iss`, `sub` (opaque sculk user id, never the email), `aud`, `exp`, `iat`, `auth_time`, and `nonce` when requested. - `profile`: adds `preferred_username` and `picture` (when set). - `sculk:servers`: adds `sculk_servers`, an array of `{ "id", "name", "role", "is_player": true }` for every server on the instance where the subject holds `server.play`. - **Access tokens:** opaque 256-bit tokens stored SHA-256 hashed, 1 hour TTL. `/oauth/userinfo` resolves live memberships on every call and rejects requests sending a bearer token in both the `Authorization` header and the form body (RFC 6750 §2). - **Refresh tokens:** opaque 256-bit tokens stored SHA-256 hashed, 30-day sliding TTL, rotated on every refresh. Narrowing `scope` on a refresh request limits the minted tokens without shrinking the underlying grant's original scope set (RFC 6749 §6); if `offline_access` is omitted from the narrowed scope, no new `refresh_token` is returned. Reusing an already-rotated refresh token revokes the entire grant (all access and refresh tokens). Every refresh re-checks that the subject still exists and is not blocked, and re-resolves live `sculk_servers`. - **Authorization codes:** 60-second TTL, single use, bound to client, redirect URI, subject, scopes, and PKCE challenge. Reusing a code revokes the tokens it already produced (RFC 6749 §4.1.2). - **Rate limiting and caching:** every OIDC response (including redirects and errors) carries `Cache-Control: no-store`. Rate limits key on the direct socket peer address unless the peer matches `SCULK_TRUSTED_PROXIES`, in which case sculk.network uses the rightmost untrusted hop in `X-Forwarded-For` (IPv6 clients are grouped by `/64`; `X-Real-IP` is ignored). `/oauth/token` enforces a per-IP limit, per-IP and per-`(normalized client_id, IP)` failed-authentication buckets reserved before `scrypt` (refunded on auth success) plus a global `scrypt` concurrency limit, and a per-client limit applied after authentication (keyed by `(client_id, IP)` for public clients). Expired authorization requests, codes, access tokens, and refresh tokens are pruned opportunistically and by a periodic `oidc.cleanup-tokens` job (every 15 minutes). ## Client and key management API Management endpoints require a signed-in session whose user ID is listed in `SCULK_OIDC_ADMINS` (comma-separated). When `SCULK_OIDC_ADMINS` is unset or empty, all `/api/oidc/*` endpoints return `403`. Authorization is enforced both at the route guard and inside each admin service function. All JSON responses carry `Cache-Control: no-store`. | Endpoint | Purpose | | --- | --- | | `POST /api/oidc/clients` | Register a client (`name`, `redirectUris`, optional `native`, `firstParty`, `public`). Returns `clientSecret` once for confidential clients. | | `GET /api/oidc/clients` | List registered clients (secret hashes are never returned). | | `PATCH /api/oidc/clients/:clientId` | Disable or re-enable a client (`{"disabled": true\|false}`). Disabling revokes active grants and tokens. | | `POST /api/oidc/clients/:clientId/rotate-secret` | Rotate a confidential client's secret (shown once). | | `POST /api/oidc/keys/rotate` | Rotate the RS256 signing key. The new key becomes `current`; the old `current` stays published in `/oauth/jwks.json` as `previous` until the next rotation. Rejects with `409 rotation_cooldown` (`Retry-After`) while the `previous` key is younger than the 10-minute ID token TTL (`600 s`). | | `DELETE /api/oidc/grants/:grantId` | Revoke a grant and its tokens immediately. | | `GET /api/oidc/subjects/:userId/grants` | List a user's OIDC grants (`id`, `clientId`, `clientName`, `scopes`, `authTime`, `createdAt`, `revokedAt`). | | `POST /api/oidc/subjects/:userId/block` | Block a user from OIDC (optional JSON `{"reason": "..."}`), immediately revoking all of their active grants and tokens and recording `oidc.subject.blocked`. | | `DELETE /api/oidc/subjects/:userId/block` | Unblock a previously blocked OIDC subject and record `oidc.subject.unblocked`. | | `GET /api/oidc/audit` | Read recent OIDC audit events (`oidc.client.*`, `oidc.grant.*`, `oidc.key.rotated`, `oidc.subject.*`). | ## Worked flow (against a dev lane) Start a lane with `oidcProvider` enabled and the owner user ID in `SCULK_OIDC_ADMINS` (sign in once to read `users.id` or pass it via `pnpm lane svc 1 restart app --env SCULK_FEATURES=oidcProvider --env SCULK_OIDC_ADMINS=`), then create a server so the owner holds an `owner` seat: ```sh APP=http://127.0.0.1:40010 OWNER_COOKIE=$(pnpm lane login 1 owner) curl -sS -X POST "$APP/api/servers" \ -H "Cookie: sculk_session=$OWNER_COOKIE" \ -H "Content-Type: application/json" \ -d '{"name":"Sculk Demo"}' ``` ```json {"id":"6uabltcpud3qpiy5","name":"Sculk Demo","createdAt":"2026-11-26T21:14:07.445Z"} ``` Read the discovery document: ```sh curl -sS "$APP/.well-known/openid-configuration" ``` ```json {"issuer":"http://127.0.0.1:40010","authorization_endpoint":"http://127.0.0.1:40010/oauth/authorize","token_endpoint":"http://127.0.0.1:40010/oauth/token","userinfo_endpoint":"http://127.0.0.1:40010/oauth/userinfo","jwks_uri":"http://127.0.0.1:40010/oauth/jwks.json","response_types_supported":["code"],"grant_types_supported":["authorization_code","refresh_token"],"subject_types_supported":["public"],"id_token_signing_alg_values_supported":["RS256"],"scopes_supported":["openid","profile","offline_access","sculk:servers"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post","none"],"code_challenge_methods_supported":["S256"],"claims_supported":["iss","sub","aud","exp","iat","auth_time","nonce","preferred_username","picture","sculk_servers"]} ``` Register a client: ```sh curl -sS -X POST "$APP/api/oidc/clients" \ -H "Cookie: sculk_session=$OWNER_COOKIE" \ -H "Content-Type: application/json" \ -d '{"name":"Sculkworm Live","redirectUris":["https://rp.example/cb"],"firstParty":true}' ``` ```json {"client":{"clientId":"vb3efdhxc2sbpqkmvbbd","name":"Sculkworm Live","redirectUris":["https://rp.example/cb"],"native":false,"firstParty":true,"public":false,"createdBy":"69bd3f16abf187baa9f3fdbc2116e120","createdAt":"2026-11-26T21:14:31.293Z","disabledAt":null},"clientSecret":""} ``` Authorize with PKCE `S256`, exchange the code at `/oauth/token`, verify the `id_token` signature against `/oauth/jwks.json`, call `/oauth/userinfo`, and test refresh rotation and reuse detection: ```text authorize status: 302 cache-control: no-store redirect state: demo-state code len: 43 token status: 200 cache-control: no-store keys: [ 'access_token', 'expires_in', 'id_token', 'refresh_token', 'scope', 'token_type' ] jwks status: 200 kids: [ '5zmsp-s7_yt1_P4h' ] id_token RS256 sig valid: true header: { alg: 'RS256', typ: 'JWT', kid: '5zmsp-s7_yt1_P4h' } userinfo status: 200 body: { sub: '69bd3f16abf187baa9f3fdbc2116e120', preferred_username: 'Owner', picture: 'https://avatars.sculk.test/owner.png', sculk_servers: [ { id: '6uabltcpud3qpiy5', name: 'Sculk Demo', role: 'owner', is_player: true } ] } refresh status: 200 rotated: true refresh reuse status: 400 body: { error: 'invalid_grant', error_description: 'Refresh token reuse detected.' } userinfo after reuse status: 401 ``` Disabling the feature flag returns `404` with `Cache-Control: no-store` on every OIDC route: ```sh pnpm lane svc 1 restart app --env SCULK_FEATURES=-oidcProvider curl -sS -i "$APP/.well-known/openid-configuration" | head -n 5 ``` ```text HTTP/1.1 404 Not Found cache-control: no-store content-type: application/json ``` --- Source: https://docs.sculk.network/nightly/sculk/clients/sync.md # Player sync and the installer The sync jar (`clients/sync`) brings a player's game folder up to date with the server's published client files before Minecraft starts, and can also run an opt-in Sculkworm tunnel agent. The installer jar adds the server to the player's launcher and picks the right launch mode for that launcher. ## Build ```sh node clients/sync/build.mjs ``` The build runs in `eclipse-temurin:17-jdk`, targets Java 8, compiles every class into package `network.sculk.sync` (keeping the jars out of the unnamed default package so signed vanilla Minecraft jars load cleanly when attached via `-javaagent`), and writes four files: | File | What it is | | --- | --- | | `clients/sync/out/sculk-sync.jar` | The sync jar (unchanged: sync and opt-in tunnel agent only). Its manifest has both `Main-Class` and `Premain-Class` (`network.sculk.sync.SculkSync`). | | `clients/sync/out/sculkworm-connect.jar` | Standalone Java 8 player-side `sculkworm-connect` client. `Main-Class` runs the `play` / `login` / `logout` CLI; `Premain-Class` runs connect only (`network.sculk.sync.SculkwormConnect`). | | `clients/sync/out/sculk-sync-sculkworm.jar` | Combined sync + connect jar. `Main-Class` stays `network.sculk.sync.SculkSync`; `Premain-Class` (`network.sculk.sync.SculkSyncSculkwormAgent`) runs sync first (blocking until sync finishes, plus any configured `tunnel` agent) and then starts connect in daemon threads. | | `clients/sync/out/sculk-installer.jar` | The installer (`Main-Class`: `network.sculk.sync.Installer`). It holds `sculk-sync.jar` and `sculk-installer.json` at its root. The server adds `server-icon.png` next to them when it serves the download. | `clients/sync/build.sh` does the work, and the `Dockerfile` runs the same script. The image ships `sculk-sync.jar` and `sculk-installer.jar` in `/app/clients/sync/`. ## Two ways to run the sync jar Both read `sculk.json` in the instance folder and share the same rules: a 30 second budget (`timeoutSeconds`), the same log lines, channel tokens and `swa_` agent tokens masked in the output, three-way merging of merge-flagged configs (keeping a base copy in `sculk-base/`), a confirmation prompt for mods uploaded by hand (`sculk-accepted-mods.txt`), and a failure never stops the launch (only cancelling the hand-added mods prompt exits with code `1`). | Mode | Command | Game folder | Who uses it | | --- | --- | --- | --- | | Pre-launch | `java -jar sculk-sync.jar [instance dir] [game dir]` (or `INST_DIR`, `INST_MC_DIR`) | `INST_MC_DIR`, else 2nd arg, else `gameDir` in `sculk.json`, else `/minecraft` | Prism, PolyMC, MultiMC (`PreLaunchCommand`) | | Agent | `java -javaagent:sculk-sync.jar= ...` | `INST_MC_DIR`, else `gameDir` in `sculk.json` (absolute, or relative to the instance dir), else `/minecraft` | Every other launcher, through the Java arguments | | Tunnel agent | `java -jar sculk-sync.jar --tunnel-agent [instance dir]` (or `INST_DIR`) | Not used (reads `tunnel` in `sculk.json`) | Opt-in closed-route tunnel agent (see [Tunnel agent mode](#tunnel-agent-mode-opt-in)) | In agent mode the JVM runs `premain` before the game's `main`, in the same process, so the mods folder is up to date before Fabric or Forge scans it. The agent returns when the sync ends or the budget runs out (and, if `sculk.json` has an enabled `tunnel` block, starts the tunnel agent on a daemon thread). It only halts the JVM (exit code `1`) if the player cancels the hand-added mods prompt; otherwise the game starts with its own exit code. After a timeout the worker stops before it writes again. ATLauncher and the Modrinth App start Java in the game folder, so their agent argument is relative and a space in the user's folder name cannot split it: ``` -javaagent:sculk/sculk-sync.jar=sculk ``` The Minecraft Launcher gets an absolute agent argument, because nobody has checked which folder it starts Java in. It splits the Java arguments on spaces and a missing agent jar stops the JVM before the game starts, so the installer never writes a profile whose sync folder has a space in its path. It refuses and writes nothing. The player then runs it again with `--sync-dir` and a folder whose path has no spaces (`C:\sculk`, `/Users/Shared/sculk`, `/opt/sculk`). The jar and `sculk.json` go to `/`, and `gameDir` in that `sculk.json` is the profile's absolute game folder: ``` $ java -jar sculk-installer.jar --cli --launcher mojang Installing Aileen SMP for Minecraft Launcher in C:\Users\Jane Doe\AppData\Roaming\.minecraft The Minecraft Launcher splits Java arguments on spaces, and the sync folder C:\Users\Jane Doe\AppData\Roaming\.minecraft\sculk\aileen-smp\sculk has one. Run this installer again with a folder whose path has no spaces: java -jar sculk-installer.jar --cli --launcher mojang --sync-dir C:\sculk Or choose "Another launcher (manual)" and set up the profile by hand. $ java -jar sculk-installer.jar --cli --launcher mojang --sync-dir C:\sculk Installing Aileen SMP for Minecraft Launcher in C:\Users\Jane Doe\AppData\Roaming\.minecraft Downloading Fabric 0.16.9 for Minecraft 1.21.1 from https://meta.fabricmc.net/v2/versions/loader/1.21.1/0.16.9/profile/json Wrote C:\Users\Jane Doe\AppData\Roaming\.minecraft\versions\fabric-loader-0.16.9-1.21.1\fabric-loader-0.16.9-1.21.1.json Wrote C:\sculk\aileen-smp\sculk.json Wrote C:\sculk\aileen-smp\sculk-sync.jar Wrote C:\Users\Jane Doe\AppData\Roaming\.minecraft\launcher_profiles.json.sculk-backup Wrote C:\Users\Jane Doe\AppData\Roaming\.minecraft\launcher_profiles.json Close the Minecraft Launcher if it is open, open it, choose the installation "Aileen SMP" and play. ``` The installer window has no field for this folder. A player whose path has a space sees the same message there and runs the command line. ## sculk-installer.json The installer reads this entry from its own jar. The server overwrites it per server when it serves the download, so its name and shape are a contract: ```json { "serverName": "Aileen SMP", "manifestUrl": "https://sculk.network/c//manifest.json", "minecraft": "1.21.1", "loader": { "kind": "fabric", "version": "0.16.9" }, "iconKey": "aileen" } ``` `loader.kind` is one of `fabric`, `quilt`, `forge`, `neoforge` or `vanilla`. `version` is required except for `vanilla`. `minecraft` and `version` are plain version names (letters, digits, `.`, `_`, `+`, `-`), because they become folder names and URL paths. `iconKey` is optional. The installer rejects any other kind, any missing field and any other version before it writes a file. The build puts a placeholder in the jar (`clients/sync/installer.placeholder.json`). When the live modpack has a `server-icon.png`, the server writes the same 64x64 PNG as the Prism export into the jar as the root entry `server-icon.png` and sets `iconKey` to `sculk-`. Without an icon there is neither. The jar's other entries keep their bytes and order, so every download of the same commit has the same bytes. ## Installer ```sh java -jar sculk-installer.jar # a window, or the CLI when there is no display java -jar sculk-installer.jar --cli --list # the launchers it found java -jar sculk-installer.jar --cli --launcher prism java -jar sculk-installer.jar --cli --launcher manual --dir "/path/to/game folder" java -jar sculk-installer.jar --cli --launcher mojang --sync-dir /opt/sculk ``` The window shows the server's icon and name, the launchers it found and a log. Download progress lines are grey, the result is green and a failure is red. When an install ends it opens a dialog with the result: a green **Done** with what to do next, or a red **Not installed** with the reason. The command line prints the same lines and exits 0 when the install is done, 1 when it failed and 2 for a usage error. It colours the result green or red only on a terminal and never when `NO_COLOR` is set, so a pipe or a log file gets plain text. On Windows it colours only in Windows Terminal or a terminal that sets `TERM`, because the classic console prints the codes as text. `--list` prints one launcher per line, with the folder it found or `--dir ` when the player picks one: ``` Aileen SMP: Minecraft 1.21.1, Fabric 0.16.9 prism Prism Launcher /home/ana/.local/share/PrismLauncher mojang Minecraft Launcher /home/ana/.minecraft modrinth Modrinth App --dir manual Another launcher (manual) --dir ``` `Launchers.ALL` in `clients/sync/src/Launchers.java` is the only place that knows launchers. Each entry has an id, a name, the data folders to look in on each system (`%APPDATA%`, `~/Library/Application Support`, `$XDG_DATA_HOME` or `~/.local/share`, and Flatpak folders), the file that proves the folder is that launcher's, and its install step. Detection only reads. Every install can run again: it rewrites the jar and the config in place, writes only the files that changed and never adds a second profile. | Id | What the install does | | --- | --- | | `prism`, `polymc`, `multimc` | Writes `instances//` with the same `instance.cfg`, `mmc-pack.json` and `sculk.json` as the server's Prism export, and keeps the pre-launch hook. With an icon it writes `.png` into the launcher's icons folder (`IconsDir` in its config, `icons` by default) and `iconKey` into `instance.cfg`: the launcher reads a `.png` beside an instance only when it imports a zip. A rerun keeps the keys the launcher added to `instance.cfg`. The launcher downloads the loader itself. | | `atlauncher` | Needs an instance with the server's name, Minecraft version and loader, which the player creates in ATLauncher. Writes `sculk/` in it and adds the agent to `launcher.javaArguments` in `instance.json`, after a copy in `instance.json.sculk-backup`. | | `mojang` | Installs the loader into `versions/` when it is not there yet (see [Loaders in the Minecraft Launcher](#loaders-in-the-minecraft-launcher)). Adds the profile `sculk-` to `launcher_profiles.json`, named after the server, with its own game folder under `.minecraft/sculk/`, the server's icon as a `data:image/png;base64,` URL (`Grass` without one) and the launcher's default Java arguments plus the absolute agent, after a copy in `launcher_profiles.json.sculk-backup`. The sync folder is `sculk/` inside that game folder, or `/` with `--sync-dir`. When its path has a space it refuses and writes nothing. | | `modrinth` | Manual. Never writes the app's database. Writes `sculk/` in the profile folder the player picks and prints the argument to paste in the profile's Java arguments. | | `manual` | Writes `sculk/` in the folder the player picks and prints the absolute agent argument, quoted when the path has a space. | GDLauncher is not supported yet. ### Loaders in the Minecraft Launcher The Minecraft Launcher starts a profile from `versions//.json`. A loader's JSON names the vanilla version it builds on in `inheritsFrom`, and the launcher downloads that version and every library on the first Play. `InstallerConfig.LoaderKind` holds what differs per loader: the version id, where to download it and how. | Loader | Version id | What the installer does | | --- | --- | --- | | Fabric | `fabric-loader--` | Downloads `https://meta.fabricmc.net/v2/versions/loader///profile/json`, checks that its `id` is the version id and writes it. That is all Fabric's own installer writes. | | Quilt | `quilt-loader--` | The same with `https://meta.quiltmc.org/v3/versions/loader///profile/json`. | | NeoForge | `neoforge-` | Downloads `https://maven.neoforged.net/releases/net/neoforged/neoforge//neoforge--installer.jar`, checks it against the `.sha1` the Maven publishes (`.sha256` or `.md5` when there is no `.sha1`) and runs `/bin/java -jar --installClient <.minecraft>` in a temporary folder. | | Forge | `-forge-` | The same with `https://maven.minecraftforge.net/net/minecraftforge/forge/-/forge---installer.jar`. | | Vanilla | `` | Nothing: the launcher has every vanilla version. | When the version JSON is already there it prints ` for Minecraft is already installed.` and downloads nothing. Downloads follow redirects, never from https to http, time out after 10 seconds to connect and 30 to read, and go to a temporary file first, so a failure leaves no partial file. The Forge and NeoForge installers download the vanilla version (`versions//.json` and its jar) and the libraries they patch themselves; their output goes to the log without the thousands of lines that list patched classes. They also add a profile named after themselves (`NeoForge`, `forge`), so the installer removes every profile that was not in `launcher_profiles.json` before the run, except `sculk-`, also when they fail. Their installers need `launcher_profiles.json`, which the launcher writes on its first start. A failure says why and what to do next: ``` $ java -jar sculk-installer.jar --cli --launcher mojang Installing Sculk Testing for Minecraft Launcher in C:\Users\Ana\AppData\Roaming\.minecraft Could not download https://maven.neoforged.net/releases/net/neoforged/neoforge/21.1.266/neoforge-21.1.266-installer.jar (java.net.UnknownHostException: maven.neoforged.net). Check your internet connection and run the installer again. ``` Tests point every loader download at a stand-in server with the `SCULK_LOADER_BASE` environment variable or the `sculk.loaderBase` system property: the loader's path is appended to it instead of its own server. ## Tunnel agent mode (opt-in) `sculk-sync.jar` can also act as a **Sculkworm tunnel agent** for a closed route (see `crates/sculkworm/docs/tunnel.md`): it dials out to the relay's TLS tunnel listener (`ALPN sculkworm`), authenticates with a per-route `swa_` agent token, serves incoming player streams to a local TCP target (`host:port`), sends `PING`/`PONG` keepalives, reconnects with full-jitter exponential backoff, and honors `GOAWAY` (including `GOAWAY replaced`, where it drains open streams and exits with code `3` without reconnecting). The agent is **opt-in**: if `sculk.json` has no `tunnel` block (or `"enabled": false`), `sculk-sync.jar` makes zero tunnel network connections and behaves identically to standard sync mode. ### Configuration in `sculk.json` Add an optional `tunnel` object to `sculk.json`: ```json { "manifestUrl": "https://sculk.network/c//manifest.json", "tunnel": { "relay": "https://relay.example:8443", "route": "friends.play.example", "token": "swa__", "target": "127.0.0.1:25565", "caFile": "relay-ca.pem", "pin": "sha256/" } } ``` | Field | Required | Default | Meaning | | --- | --- | --- | --- | | `enabled` | No | `true` | Set to `false` to disable the tunnel agent without removing the block. | | `relay` | Yes | — | Relay tunnel URL (`https://host[:port]`) or `host[:port]` (default port `443`). | | `route` | Yes | — | Closed route hostname registered on the relay. | | `token` | Yes* | — | Per-route agent token (`swa__`). Masked in log output. | | `tokenFile` | Yes* | — | Path to a file containing the agent token (relative to the instance folder, or absolute). Used when `token` is omitted. | | `target` | No | `127.0.0.1:25565` | Local Minecraft server `host:port` to bridge incoming `OPEN` streams to (5 s connect timeout). | | `caFile` | No | OS/JDK roots | PEM certificate/CA file replacing the default trust store (useful for self-signed or private relay CAs). Relative to the instance folder, or absolute. | | `pin` / `pins` | No | — | Optional SPKI SHA-256 certificate pin (`sha256/`) or array of pins checked in addition to normal certificate chain and hostname verification. | | `software` | No | `sculk-sync/1` | Software string sent in `HELLO` (at most 64 UTF-8 bytes). | \*Either `token` or `tokenFile` must be set. ### Running the tunnel agent - **Standalone foreground mode**: run `java -jar sculk-sync.jar --tunnel-agent [instance-dir]` (or set `INST_DIR`). The process runs the reconnect loop in the foreground, shuts down cleanly with `GOAWAY normal` on `SIGTERM`/`SIGINT`, and returns the spec exit codes (`0` on clean shutdown, `2` on config error / `unsupported_version` / `unknown_route`, `3` on `GOAWAY replaced`). - **In-JVM `-javaagent` mode**: when launched with `-javaagent:sculk-sync.jar=` and `sculk.json` contains an enabled `tunnel` block, `premain` starts the tunnel agent on a daemon thread right after sync completes so it runs alongside the JVM process and sends `GOAWAY normal` via a shutdown hook when the JVM exits. Java 8u251+ or Java 9+ is required for TLS ALPN (`sculkworm`). ## Sculkworm connect client (player side) `sculkworm-connect.jar` and `sculk-sync-sculkworm.jar` carry a pure Java 8 port of the player-side `sculkworm-connect` client (see `crates/sculkworm/docs/tunnel.md` sections 4 and 5). It authenticates players via the relay's loopback redirect + PKCE S256 flow (falling back to the RFC 8628 device flow with `--device` or whenever a browser cannot be opened), stores opaque `swl_` sealed logins in `logins.json` (`0600` on POSIX, atomic temp + `fsync` + rename), mints short-lived `swt_` tickets via `POST /tickets`, opens a lazy TLS ALPN `sculkworm` connect session on the first local Minecraft connection (reused across connections and closed after 60 s idle), and answers the local Minecraft client with the exact section 4.6 packets when the route is offline, login is still in progress, or an error occurs. ### Configuration in `sculk.json` (`connect` block) Add an optional `connect` object to `sculk.json` when using `-javaagent:sculkworm-connect.jar=` or `-javaagent:sculk-sync-sculkworm.jar=`: ```json { "manifestUrl": "https://sculk.network/c//manifest.json", "connect": { "enabled": true, "relay": "https://relay.example", "route": "friends.play.example", "listen": "127.0.0.1:25565", "caFile": "relay-ca.pem", "pin": "sha256/" } } ``` | Field | Required | Default | Meaning | | --- | --- | --- | --- | | `enabled` | No | `true` | Set to `false` to disable connect (zero network activity and zero threads). | | `relay` | Yes | — | Relay public `https://` URL (`SCULKWORM_PUBLIC_URL`, `https://` only). | | `route` | Yes | — | Closed route hostname registered on the relay. | | `listen` | No | `127.0.0.1:25565` | Local Minecraft listener `ip:port`. Non-loopback addresses require `"listenAny": true`. | | `listenAny` | No | `false` | Allow binding `listen` to a non-loopback address. | | `caFile` | No | OS/JDK roots | PEM CA/certificate file replacing the default trust store (relative to the instance folder, or absolute). | | `pin` / `pins` | No | — | Optional SPKI SHA-256 certificate pin (`sha256/`) or array of pins checked on both HTTPS API and tunnel connections. | | `loginsFile` | No | `/sculkworm/logins.json` | Path to `logins.json` (kept inside the instance folder by default in `-javaagent` mode). | | `device` | No | `false` | Force the RFC 8628 device login flow instead of opening a local browser. | | `software` | No | `sculkworm-connect/0.1` | Software string sent in `HELLO` (at most 64 UTF-8 bytes). | In `-javaagent` mode, `premain` never blocks the game JVM: if `connect` is absent or `"enabled": false` it starts no threads and opens no sockets; otherwise it binds the local listener and, if no stored login exists for `(route, relay)`, starts the login flow on a daemon thread while answering local joins with a Login Disconnect telling the player to finish logging in in the browser and retry. All threads are daemon threads and exit cleanly with the game. ### Standalone CLI (`sculkworm-connect.jar`) Every Sculkworm release (`sculkworm-v` on the [Releases](https://github.com/YellowUmbrellaDev/sculk.network/releases) page) attaches `sculkworm-connect.jar` alongside `SHA256SUMS` so players can download and verify it without building from source: ```sh TAG=sculkworm-v0.1.0-nightly.20261127.5 curl -sSfLO "https://github.com/YellowUmbrellaDev/sculk.network/releases/download/${TAG}/sculkworm-connect.jar" curl -sSfLO "https://github.com/YellowUmbrellaDev/sculk.network/releases/download/${TAG}/SHA256SUMS" sha256sum -c SHA256SUMS --ignore-missing java -jar sculkworm-connect.jar --help ``` Or run the locally built jar at `clients/sync/out/sculkworm-connect.jar`: ```sh java -jar clients/sync/out/sculkworm-connect.jar --help ``` ```text Usage: sculkworm-connect [OPTIONS] Commands: play Log in if needed and open a local Minecraft listener for login Log in to a closed route via browser redirect or device flow logout Revoke and remove a stored login (or all logins) Options: --relay Relay URL (skips Minecraft status-ping discovery) --device Use device flow instead of opening a local browser --listen Local listener address for play (default: 127.0.0.1:25565) --listen-any Allow binding --listen to a non-loopback address --ca-file PEM CA/cert file replacing OS roots (env: SCULKWORM_CONNECT_CA_FILE) --pin Expected leaf SPKI SHA-256 pin; repeatable (env: SCULKWORM_CONNECT_PIN) --logins Override logins.json path (alias: --logins-file; env: SCULKWORM_CONNECT_LOGINS_FILE) --yes Skip confirmation prompt for relay URL discovered via status ping --software Software string sent in HELLO (default: sculkworm-connect/0.1) -h, --help Show this help text ``` In standalone CLI mode, `logins.json` defaults to the OS config path from `crates/sculkworm/docs/tunnel.md` section 5.8 (`$XDG_CONFIG_HOME/sculkworm/logins.json` or `~/.config/sculkworm/logins.json` on Linux/Unix, `~/Library/Application Support/sculkworm/logins.json` on macOS, `%APPDATA%\sculkworm\logins.json` on Windows), so logins interoperate directly with the Rust `sculkworm-connect` binary. Relay discovery follows section 4.2 (`--relay`, then stored login's `relay`, then Minecraft status ping reading `sculkworm.relay` with a `[y/N]` prompt unless `--yes` is passed). Usage, configuration, and port-in-use errors exit with code `2`. ## Tests `pnpm --filter @sculk/sync test` runs every case on Java 8 and Java 21 in Docker. `test/sync.test.ts` covers both modes of the sync jar. `test/tunnel.test.ts` runs `test/java/TunnelProtocolTest.java` and `test/java/TunnelAgentTest.java` on Java 8 and Java 21 to verify every hex vector in `crates/sculkworm/docs/tunnel.md`, the session multiplexer over in-memory pipes, the reconnect backoff policy, TLS/ALPN/SPKI pinning, stream bridging, and `GOAWAY` handling; when `SCULKWORM_BIN` points to a built `sculkworm` binary, it also runs an end-to-end interoperability test against the real relay (registering a closed route and agent token via the admin API, connecting `sculk-sync.jar --tunnel-agent`, pushing a real Minecraft status ping over TCP, and verifying `GOAWAY replaced` exit code `3`). `test/connect.test.ts` runs `test/java/SculkwormConnectTest.java` on Java 8 and Java 21 to verify the RFC 7636 PKCE vector, token masking, section 4.6 Minecraft failure packet hex vectors, `logins.json` round-trip and POSIX `0600`/`0700` permissions, `sculk.json` `connect` config and CLI parsing, loopback PKCE and device fallback login flows, ticket rotation and `401` re-login, lazy session reuse and idle timeout, premain pending-login replies, jar manifests, and (when `SCULKWORM_BIN` is set) a full end-to-end test against the real Sculkworm relay with a mock OAuth2 IdP, Java agent, and Java `sculkworm-connect.jar` bridging a Minecraft status ping to a stand-in server. `test/installer.test.ts` writes a `sculk-installer.json` and an icon into the built installer, runs it against a temporary home for each launcher, reruns it and compares the files, then starts a stand-in game with the Java arguments the installer wrote and checks that the mods folder was synced first. A local HTTP server stands in for the loaders' meta servers and Mavens, and `test/fixtures/FakeInstaller.java` for the Forge and NeoForge installers: it adds its own profile like they do. --- Source: https://docs.sculk.network/nightly/sculk/plugins/writing-a-plugin.md # Write a panel plugin sculk.network talks to a game panel only through a plugin: one JSON file that declares every request the panel may receive. In this tutorial we write a small plugin for a fake panel that runs on your machine, run it from the command line, and watch it refuse bad input before any request leaves. You need Git, Node.js 22.18 or later and pnpm 11. [Format v1](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md) explains every field we use. ## Get the code We clone the repository and install its dependencies. ```sh git clone https://github.com/YellowUmbrellaDev/sculk.network.git cd sculk.network pnpm install ``` The install ends with: ```text Done in s using pnpm v11.. ``` ## Start the fake panel `dev/fake-panel/` is a small server that answers like PufferPanel. It accepts the client ID `fake-id` with the secret `fake-secret`, it already holds a server called `s1`, and it writes every request it gets to a log file. Open a second terminal in the `sculk.network` folder and start it on port 47123: ```sh node dev/fake-panel/server.mjs --port 47123 --log /tmp/toy-panel.log ``` ```text FAKE-PANEL url=http://127.0.0.1:47123 log=/tmp/toy-panel.log ``` Leave it running. Go back to the first terminal for the rest of the tutorial. ## Make a folder for the plugin We keep our plugin outside the repository, in a folder next to it. A link named `toy` inside the repository points to it, so every command below runs from the `sculk.network` folder: ```sh mkdir ../toy ln -s ../toy toy ``` This prints nothing. `git status` lists the link as a new file. Don't commit it. ## Write the connection file A connection holds the panel address and its credentials. sculk.network stores it encrypted. For the command line we write it to a file, `toy/conn.json`: ```json { "baseUrl": "http://127.0.0.1:47123", "clientId": "fake-id", "clientSecret": "fake-secret" } ``` ## Write the plugin Create `toy/plugin.json`: ```json { "format": 1, "id": "toy", "kind": "backend", "name": "Toy Panel", "connection": { "baseUrl": { "type": "url" }, "clientId": { "type": "text" }, "clientSecret": { "type": "secret" } }, "vars": { "serverId": { "type": "pattern", "pattern": "^[a-z0-9]{1,32}$" } }, "auth": { "panel": { "kind": "token", "request": { "method": "POST", "path": "/oauth2/token", "body": { "form": { "grant_type": "client_credentials", "client_id": "{{clientId}}", "client_secret": "{{clientSecret}}" } }, "accept": [200] }, "extract": { "token": "access_token", "ttl": "expires_in" }, "apply": { "headers": { "Authorization": "Bearer {{token}}" } } } }, "fetch": { "allowHosts": [] }, "capabilities": ["status"], "actions": { "listServers": { "steps": [ { "request": { "method": "GET", "path": "/api/servers", "accept": [200], "extract": { "servers": "servers" } } } ] }, "status": { "steps": [ { "request": { "method": "GET", "path": "/api/servers/{{serverId}}/status", "accept": [200], "extract": { "running": { "path": "running", "equals": true } } } } ] } } } ``` Here is what each part does: - [`connection`](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md#connection) lists the fields of `conn.json`. A `secret` field can only appear in the `request` and `apply` blocks of its own credential in `auth`, so a plugin cannot leak it into a step URL or a log. - [`vars`](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md#vars) declares `serverId` as a `pattern` variable. A value that does not match `^[a-z0-9]{1,32}$` stops the run before any request. - [`auth`](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md#auth) trades the client ID and secret for a token at `/oauth2/token` and adds it to every later request. - [`capabilities`](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md#capabilities) says what the plugin can do. `status` needs the `status` capability. - [`actions`](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md#actions) holds one entry per thing sculk.network asks a panel. Every plugin has `listServers`. `status` reads `running` from the panel's answer and reports whether it equals `true`. Check that the file is valid: ```sh node dev/scripts/plugin.mjs validate toy/plugin.json ``` ```text valid (format 1, stable) ``` ## Run the status action ```sh node dev/scripts/plugin.mjs run toy/plugin.json status --conn toy/conn.json --var serverId=s1 ``` ```json {"ok":true,"outputs":{"running":false}} ``` The fake panel's `s1` server is stopped, so `running` is `false`. Look at what the panel received: ```sh grep -o '"method":"[A-Z]*","rawUrl":"[^"]*"' /tmp/toy-panel.log ``` ```text "method":"POST","rawUrl":"/oauth2/token" "method":"GET","rawUrl":"/api/servers/s1/status" ``` Exactly the two requests the plugin declares: one for the token, one for the status. ## Send a console command A console command is one line of text. If the line could hold a newline, a caller could slip a second command after the first. We declare a `command` variable that refuses carriage returns and line feeds. In `toy/plugin.json`, add `command` to `vars`: ```json "vars": { "serverId": { "type": "pattern", "pattern": "^[a-z0-9]{1,32}$" }, "command": { "type": "pattern", "pattern": "^[^\\r\\n]{1,256}$" } }, ``` add `console` to `capabilities`: ```json "capabilities": ["status", "console"], ``` and add a `sendCommand` action next to `status` in `actions`: ```json "sendCommand": { "steps": [ { "request": { "method": "POST", "path": "/api/servers/{{serverId}}/console", "body": { "text": "{{command}}" }, "accept": [204] } } ] }, ``` ```sh node dev/scripts/plugin.mjs validate toy/plugin.json ``` ```text valid (format 1, stable) ``` Send a command. Like PufferPanel, the fake panel refuses console commands while the server is stopped, so `s1` answers `500 ErrServerOffline` until it is started: ```sh node dev/scripts/plugin.mjs run toy/plugin.json sendCommand --conn toy/conn.json --var serverId=s1 --var "command=say hi" ``` ```json {"ok":false,"error":{"code":"status_unexpected","step":"/actions/sendCommand/steps/0/request","status":500,"body":"{\"error\":\"ErrServerOffline\"}"}} ``` If you also add a `start` action (with capability `power`, `POST /api/servers/{{serverId}}/start?wait=true`, `accept: [204]`) and start `s1` first, `sendCommand` returns `{"ok":true,"outputs":{}}`. Now try a command with a newline in it: ```sh node dev/scripts/plugin.mjs run toy/plugin.json sendCommand --conn toy/conn.json --var serverId=s1 --var "command=$(printf 'say hi\nop Mallory')" echo "exit $?" ``` ```text {"ok":false,"error":{"code":"var_invalid","var":"command","rule":"pattern: CR, LF or NUL"}} exit 1 ``` The run stops at the variable and names it. Nothing reaches the panel: ```sh grep -c 'op Mallory' /tmp/toy-panel.log ``` ```text 0 ``` ## Read the console The `logs` capability reads what the server prints, so the creation page can show the install and the first start. It is optional: declare it only when the panel gives you the console over HTTP. Add an integer `since` to `vars`, the capability `logs`, and a `readLog` action. PufferPanel answers `GET /api/servers/{id}/console?time=` with `{ "epoch": , "logs": "" }`, where `epoch` is the time of the read: ```json "readLog": { "steps": [ { "request": { "method": "GET", "path": "/api/servers/{{serverId}}/console", "query": { "time": "{{since}}" }, "accept": [200], "extract": { "cursor": "epoch", "text": { "path": "logs", "as": "base64" } } } } ] }, ``` `cursor` is what the caller passes as `since` on its next read, so it receives only the new lines. A first read passes `0`. ## Read the resource use The `stats` capability reads the CPU and memory the server uses, so the server page can draw their history. It is optional. Add the capability `stats` and a `stats` action. PufferPanel answers `GET /api/servers/{id}/stats` with `{ "cpu": , "memory": , ... }`: ```json "stats": { "steps": [ { "request": { "method": "GET", "path": "/api/servers/{{serverId}}/stats", "accept": [200], "extract": { "cpuPercent": "cpu", "memoryBytes": "memory" } } } ] }, ``` `cpuPercent` is `100` for one full core, so a server that uses three cores reads `300`. Pterodactyl reports the same unit as `cpu_absolute` under `attributes.resources` of `GET /api/client/servers/{id}/resources`. ## Read a file A file path must stay inside the server's folder. The `relpath` shape refuses absolute paths and any `..` segment. Add `path` to `vars`: ```json "path": { "type": "relpath" } ``` add `files` to `capabilities`: ```json "capabilities": ["status", "console", "files"], ``` and add a `readFile` action: ```json "readFile": { "steps": [ { "request": { "method": "GET", "path": "/api/servers/{{serverId}}/file/{{path}}", "accept": [200], "response": "bytes", "extract": { "content": "$" } } } ] } ``` ```sh node dev/scripts/plugin.mjs validate toy/plugin.json ``` ```text valid (format 1, stable) ``` Ask for a file outside the server's folder: ```sh node dev/scripts/plugin.mjs run toy/plugin.json readFile --conn toy/conn.json --var serverId=s1 --var path=../x echo "exit $?" ``` ```text {"ok":false,"error":{"code":"var_invalid","var":"path","rule":"relpath: segment \"..\""}} exit 1 ``` Again the run stops before any request: ```sh grep -c '/file/' /tmp/toy-panel.log ``` ```text 0 ``` ## Clean up Stop the fake panel with Ctrl+C in its terminal. Remove the log and the link. Keep `../toy` if you want your plugin: ```sh rm /tmp/toy-panel.log toy ``` ## Next steps - [Format v1](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md) lists every field, every variable shape and every error code. - [`plugins/pufferpanel/plugin.json`](https://github.com/YellowUmbrellaDev/sculk.network/blob/main/plugins/pufferpanel/plugin.json) is a full plugin for a real panel. Compare it with yours. - [Run Error Codes](https://docs.sculk.network/nightly/sculk/plugins/format-v1.md#run-error-codes) explains each `code` a failed run prints. ## Install your plugin and connect a server So far we ran the plugin from the command line. Now we install it in sculk.network and connect a server through it. We use a development instance with the fake panel next to it, so this part needs Docker. We start with the finished plugin of this tutorial, which also sends console commands: ```sh mkdir -p toy cp dev/fake-panel/toy.plugin.json toy/plugin.json ``` We start a lane with the fake panel: ```sh pnpm lane up --with fakepanel ``` The last line names the lane number `` and the address of the app: ```text LANE k= app=http://127.0.0.1: ``` A plugin a user installs is never trusted to reach a private address, on any instance: its hosts, the panel address and every request it sends are checked, and a private, loopback or link-local address gets "This panel address isn't allowed". The fake panel runs on the lane's private network, so the `fakepanel` profile sets `SCULK_DEV_PLUGIN_HOSTS=fake-panel:8080` on the app, which lets user plugins reach exactly that `host:port` and nothing else. Never set it on an instance people use. A plugin for a panel on your own network goes in `SCULK_PLUGIN_DIR` instead, where the operator reviews it; see the self-hosting guide. We open that address and press **Sign in**. The Sign in page lists the providers. We press **Continue with Google**, which opens the development sign-in page, and press `owner`. The account page opens. We press **Plugins** on the account page. The Plugins page opens and says "You have not installed a plugin yet." We press **Upload file** and choose `toy/plugin.json`. The review shows: - the name "Toy panel" and the id `toy`, - under "Capabilities", `console` and `status`, - under "Connection fields", `baseUrl`, `clientId` and `clientSecret`, - under "Hosts this plugin may call", one line, "The panel URL you enter". Our plugin lists no other host. We press **Install**. The list shows "Toy panel" with the id `toy`, "Uploaded file", the first 12 characters of its SHA-256, and "0 connections". We ask the lane for the fake panel's values: ```sh pnpm lane creds fakepanel ``` ```text {"baseUrl":"http://fake-panel:8080","clientId":"lane","clientSecret":"lanesecret"} ``` We open `/new` and press "Add a connection" if the form is not open yet. The plugins are grouped by where they come from: "Included" for the ones sculk.network ships, "This instance" when the operator added some, and "Yours" for the ones we installed. We pick "Toy panel" under "Yours", which shows "Installed by you" and the same 12 characters. We enter the three values in **Panel URL**, **Client ID** and **Client secret** and press **Test**. It shows "Connected, 1 server". We press **Save**. The list "Choose a panel server" shows `sculkmc`. We pick it, keep or change the name in **Server name**, and press **Connect server**. The server's connection settings open and name "Toy panel" as the plugin. The connection is pinned to the exact file we installed. An update of the plugin moves the pin only after we review it and press **Update**, and an update that removes actions a connection needs to deploy is refused. When we are done, we stop the lane: ```sh pnpm lane down ``` --- Source: https://docs.sculk.network/nightly/sculk/plugins/format-v1.md # Sculk Backend Plugin Format v1 Format v1 is **stable** (`"x-stability": "stable"` in `packages/plugins/schema/plugin-v1.schema.json`, locked by `packages/plugins/schema/v1.sha256`). A later change to format 1 may only add optional fields; anything else is format 2. --- ## Top-Level Fields A plugin document is a strict JSON object (`PluginV1`) with ten top-level fields: ### `format` Literal integer `1`. Identifies the plugin schema revision. ### `id` Plugin identifier matching `^[a-z0-9][a-z0-9-]{0,63}$` (for example, `"pufferpanel"` or `"pterodactyl"`). ### `kind` Literal string `"backend"`. ### `name` Human-readable plugin display name (`1..100` characters). ### `connection` Map of connection fields (`Record`) supplied by the caller when connecting to a panel instance. Must include `"baseUrl": { "type": "url" }`. Fields marked `"secret"` may only be referenced inside the `request` and `apply` blocks of their own credential in `auth`. ### `vars` Map of input variable definitions (`Record`). Defaults to `{}`. Every variable referenced in an action's steps must be declared in `vars`. ### `auth` Optional map of named credentials (`Record`). Each entry defines either a `"token"` credential or a `"static"` credential. ### `fetch` Optional outbound allowlist `{ "allowHosts": ["..."] }` (defaults to `{ "allowHosts": [] }`). ### `capabilities` Array of capability identifiers declared by the plugin: - `"power"` — requires actions `start`, `stop`, `kill` - `"status"` — requires action `status` - `"players"` — requires action `players` - `"files"` — requires actions `listDir`, `mkdir`, `readFile`, `writeFile`, `uploadFile`, `deleteFile` (and optional `moveFile`, `backupFile` and `restoreFile`, which take root names `^\.sculk-…` for `from`, `backup` and `scratch`; a contract variable with a fixed pattern must declare exactly that pattern, and optional `sftpDetails`, which reads the host and port the panel's SFTP service listens on and extracts `sftp` as `{ "host": ..., "port": ... }`; the Files tab shows SFTP details only for a plugin that has it) - `"console"` — requires action `sendCommand` - `"logs"` — requires action `readLog`, which reads the server's console output without sending anything. It takes `serverId` and an integer `since` (`0` for the whole log, or the `cursor` of the last read) and extracts `cursor`, the value to pass as `since` next time, and `text`, the output since `since`. A plugin whose panel cannot read the console over HTTP leaves `logs` out: Pterodactyl does, because its console is a websocket. This capability is optional, and sculk.network shows no console for a plugin without it. - `"stats"` — requires action `stats`, which reads the resources the server uses right now. It takes `serverId` and extracts `cpuPercent`, a number where `100` is one full core, and `memoryBytes`, the memory in use in bytes. sculk.network samples every bound server every 30 seconds, and every 5 seconds while someone watches it, and draws the history, so the action must be one cheap `GET`. A panel that reports zeros for a stopped server is fine: sculk.network does not call `stats` for a server it knows is stopped. This capability is optional, and sculk.network shows no resource graphs for a plugin without it. - `"create"` — requires actions `createServer`, `deleteServer` (and optional `listNodes`, `listEggs`, `listAllocations`) - `"downloadUrl"` — requires action `downloadFromUrl` Every contract action present in `actions` requires its declared capability to be listed in `capabilities` (except `listServers`, which is always required and has no capability) and must match the exact variable types and extracted outputs required by `ACTIONS`. ### `actions` Map of action definitions (`Record`). Each action declares: - `auth` (optional when `auth` has one entry; required on the action or per step when `auth` has multiple entries): default credential name for `path` steps in this action. - `steps`: non-empty array of step objects (`request`, `poll`, or `merge`). --- ## Variable Shapes (`vars`) Every variable declared in `vars` uses one of the eight shapes in `VarShape`. Variable values are validated by `parseVar` before any network request is made and are **never re-templated**. | Shape | Schema Fields | Validation Rules | Allowed Template Slots | | :--- | :--- | :--- | :--- | | `pattern` | `{ type?: "pattern", pattern: string }` | String matching `^(?:)$`, no `\r`, `\n`, or `\0`. | URL path segment, query value, header value, JSON whole value or substring, multipart `filename`. | | `enum` | `{ type: "enum", values: [string, ...] }` | String equal to one of `values`, no `\r`, `\n`, or `\0`. | URL path segment, query value, header value, JSON whole value or substring. | | `integer` | `{ type: "integer", min?: number, max?: number }` | Safe integer `n` (`min <= n <= max`), no `\r`, `\n`, or `\0`. | URL path segment, query value, header value, JSON whole value (substituted as a JSON number) or substring. | | `relpath` | `{ type: "relpath" }` | Relative POSIX path, no leading `/`, no `\`, no drive letter, no `\r`, `\n`, `\0`, no empty or `.` / `..` segment (including after percent-decoding). Supports `{{dirname x}}` and `{{basename x}}`. | URL path segment, query value, header value, JSON whole value or substring, multipart `filename` (via `{{basename x}}`). `{{dirname x}}` and `{{basename x}}` are allowed in `path`, `url`, `query`, and `body`. | | `url` | `{ type: "url", allowHosts: [string, ...] }` | Valid `https://` URL with no credentials (`username`/`password`), no explicit port, no `\r`, `\n`, `\0`, and host matching `allowHosts`. Supports `{{basename x}}` in `body`. | Query value, header value, `body` (JSON whole value or substring, `body.text`, `body.form`), `auth`. | | `text` | `{ type: "text", maxLength?: number }` | UTF-8 string with length (`string.length`) `<= maxLength`, no `\0`. CR and LF pass through unchanged. | `body` (`body.text`, `body.json`, `body.form`). | | `bytes` | `{ type: "bytes", maxBytes?: number }` | `Uint8Array` (or UTF-8 string) with `byteLength <= maxBytes`. | `body.bytes` (`"bytes": "{{var}}"`) or `body.multipart.bytes` (`"bytes": "{{var}}"`). | | `map` | `{ type: "map", keyPattern: string, valuePattern: string, maxEntries: number }` | Plain JSON object with `<= maxEntries` entries, string keys matching `keyPattern`, string values matching `valuePattern`, and no `\r`, `\n`, or `\0` anywhere. | Whole JSON value in `body.json` only (`"environment": "{{environment}}"`). Values are never templated again. | ### Patterns that load Patterns use **RE2 syntax** and run on RE2 (the `re2js` port), whose matching time is linear in the value. Each `pattern`, `keyPattern` and `valuePattern` is compiled as `^(?:)$` when the plugin loads, in every plugin. A pattern that fails fails with `plugin_invalid` at `/vars/`: - Longer than 200 characters: `has a pattern longer than 200 characters`. - Not valid RE2: `has a pattern RE2 cannot compile ()`. RE2 has **no backreferences** (`\1`, `\k`) and **no lookarounds** (`(?=`, `(?!`, `(?<=`, `(? at character is not allowed in a user pattern`. An inline flag or a named group fails with `has a pattern with a `(?` group other than `(?:`; a user plugin may not set inline flags such as (?i), (?s), (?m) or (?U), or use named groups`, and `\p` or `\P` with `has a pattern with a Unicode property class; a user plugin may not use \p or \P`. - Each pattern may compile to at most 1024 RE2 instructions. RE2 stays linear above that, but its work per character grows with the program. While parsing, sculk.network estimates the size, counting each atom times every repeat around it and never less than RE2 builds; an estimate over 4096 fails at once with `has a pattern that would compile to more than 1024 RE2 instructions`, so a pattern such as `(?:()()…){1000}` costs nothing to refuse. A pattern under that estimate is compiled, and one that still compiles to more than 1024 fails with `has a pattern that compiles to RE2 instructions, more than 1024`. The estimate overcounts, so a pattern that repeats a large group many times may be refused even though it would fit; split it or use a smaller repeat. The bundled plugins' patterns other than Pterodactyl's `startup` compile to between 14 and 518 instructions. - All its patterns together (`pattern`, `keyPattern` and `valuePattern`) may compile to at most 4096 instructions. They compile in the order the variables are declared, and the first variable that takes the total past 4096 fails with `brings the plugin's patterns to RE2 instructions, more than 4096`. A user's own copy of PufferPanel fits, and so does one of Pterodactyl once its `startup` pattern is `^[^\r\n]{1,256}$`, the most a user value can hold anyway. - At most 64 variables may carry a pattern. The 65th fails with `is pattern variable 65, more than 64`. - Each string value of a `pattern` or `map` variable may be at most 256 characters. A longer value fails with `var_invalid` and rule `pattern: longer than 256 characters` before the pattern runs. Bundled plugins and the plugins in `SCULK_PLUGIN_DIR` keep the bounds their own patterns set, and are not held to the user grammar. #### The user grammar A pattern in a plugin a user installed is made only of these: - **Literals:** any character other than the metacharacters `\ . ^ $ | ( ) [ ] { } * + ?`. Other characters, such as `-`, `/`, `:` and non-ASCII letters, are literals as they are. - **Escapes, from a fixed set:** `\d \D \w \W \s \S`; `\n \r \t`; and an escaped metacharacter, `\-` or `\/`, such as `\.` or `\(`. Every other escape is refused, including `\Q`, `\E`, `\x`, `\p`, `\P`, `\b`, `\B`, `\A`, `\z`, octal and `\C`. - **`.`, `^` and `$`.** - **Classes `[…]` and `[^…]`** with at least one member. A member is a single character, an escape from the set above, or a range `a-z` between two single characters with the start not after the end. `-` is a member only first, last or escaped; `]` and `[` only escaped, so POSIX classes such as `[[:alpha:]]` are refused. - **Groups** `(…)` and `(?:…)`. Every other `(?`, including named groups, is refused. - **Alternation** `|`. - **Repeats** after an atom: `*`, `+`, `?`, `{n}`, `{n,}` and `{n,m}`, optionally followed by `?` for a non-greedy repeat. Counts are plain decimal numbers with no leading zero and no spaces, at most 1000, with `n` not above `m`. A repeat may not directly follow another repeat (`a**`, `a{2}{3}`), and nested counts may not multiply past 1000, as in RE2. Every bundled pattern follows this grammar, so a user's own copy of a bundled plugin loads. --- ## Credential Kinds (`auth`) `auth` maps credential names (`^[A-Za-z][A-Za-z0-9_]*$`) to one of two credential kinds: 1. **`token`** (`kind: "token"`): - `request`: `BareRequest` (`method`, `path`, optional `query`, `headers`, `body` (`text` or `form`), `accept`, `timeoutMs`, `response`; `url`, `body.json`, and `body.multipart` are not allowed in `auth`) - `extract`: `{ token: string, ttl: string }` (JSONPath expressions against the token response) - `apply`: `{ headers: Record }` referencing `{{token}}` - Cached per `(plugin, credentialName, connection)` (keyed via HMAC-SHA256) and refreshed 60 seconds before expiry. A `401` on a step drops and refreshes only that step's credential token, then retries once. 2. **`static`** (`kind: "static"`): - `apply`: `{ headers: Record }` referencing connection secrets owned by that credential (for example, `"Authorization": "Bearer {{applicationKey}}"`). - Each credential owns the `secret` connection fields referenced in its own `request` and `apply` blocks (collected on a first pass over `auth`, with no field-name heuristics). A secret field may be owned by at most one credential and may only appear inside that credential's `request` and `apply` blocks; referencing it in another credential or in an action step (or referencing an unowned secret in a step) fails at load with `plugin_invalid`. --- ## Step Kinds (`steps`) Every step in an action's `steps` array has optional `auth?: string` and exactly one of `request`, `poll`, or `merge`: ### 1. `request` Executes a single HTTP request (`{ auth?: string, request: Request }`): - `method`: `"GET" | "POST" | "PUT" | "PATCH" | "DELETE"`. - `path` or `url` (mutually exclusive): - `path`: relative path starting with `/` resolved against `connection.baseUrl`. Sends the step's resolved credential headers. - `url`: template starting with `"{{urlVar}}"` where `urlVar` was extracted earlier in the action with `as: "url"`. Sends **no** panel `auth` headers. - `query` (optional): `Record`. - `headers` (optional): `Record`. - `body` (optional): strict object with exactly one of: - `json`: arbitrary JSON value. - `text`: `"{{textVar}}"` from a `text` variable. - `bytes`: `"{{bytesVar}}"` from a `bytes` variable. - `form`: `Record` (`application/x-www-form-urlencoded`). - `multipart`: `{ field: string, filename: string, bytes: "{{bytesVar}}" }` (`multipart/form-data` upload where `filename` takes a `pattern` variable or `{{basename x}}` of a `relpath` variable, and `bytes` takes a `bytes` variable). - `accept`: non-empty array of HTTP status codes (`100..599`). - `timeoutMs` (optional): request timeout in milliseconds (`1..3600000`). - `response` (optional): `"json" | "text" | "bytes"`. - `extract` (optional): `Record` storing values into the action scope and outputs. - `optional` (optional): boolean; when `true` and the response status is `204`, extraction is skipped instead of failing on an empty body. ### 2. `poll` Repeatedly runs a request until `until` matches or `failWhen` / `timeoutMs` triggers (`{ auth?: string, poll: Poll }`): - `request`: `Request` executed on each poll attempt. - `until`: `{ status: number[] }`, `{ json: string, equals: Json }`, or `{ json: string, contains: string }`. `contains` is a template; the condition holds when the value at `json` equals it or, for an array (such as `$[*].name` of a folder listing), includes it. - `failWhen` (optional): `{ status: number[], request?: BareRequest }` or `{ json: string, equals: Json, request?: BareRequest }`. When matched (or when its optional `request` matches), aborts polling with `poll_failed`. - `intervalMs`: delay between attempts in milliseconds (`1..3600000`). - `timeoutMs`: maximum total poll time in milliseconds (`1..3600000`). ### 3. `merge` Fetches a JSON document and merges keys into it before storing the result in a step variable (`{ auth?: string, merge: Merge }`): - `request`: `BareRequest` that fetches the source JSON object. - `set`: `Record` mapping dot-separated paths (`a.b.c`, rejecting empty segments and `__proto__`, `constructor`, and `prototype`) to templated JSON values. - `into`: step variable name (`Name`) that receives the merged JSON object for use in a subsequent `request` step's `body.json`. --- ## Extract Paths and `as` Tags Each entry in `extract` is one of: - A JSONPath string (`"attributes.id"`, `"data[*].attributes"`, `"$"`). - Dot-separated segments (`a.b.c`), integer indices (`items[0].id`), and the `[*]` wildcard (`data[*].attributes.fqdn`) are supported. - When `[*]` appears in a path, extraction maps across the array and produces an array of extracted values. - `"$"` extracts the entire response payload (including raw `Uint8Array` when `response: "bytes"`). - `{ path: string, equals: Json }` — extracts a boolean (`true` when the value at `path` equals `equals`, `false` otherwise). - `{ path: string, as: "url" | "nodeHost" | "base64" }`: - `as: "url"`: marks the variable as a signed URL for a later `url` step (validated as a URL when that step builds its request) and redacts its query string in `trace` as `?`. - `as: "nodeHost"`: extracts a host string or (with `[*]`) an array of host strings and adds every host in it to the run's allowed node hosts. - `as: "base64"`: decodes the extracted base64 string to UTF-8 text. A value that is not a base64 string fails the run with `response_invalid`. PufferPanel returns its console this way, so `readLog` reads `{ "path": "logs", "as": "base64" }`. - `{ path: string, fields: Record }` — renames values to the names an action contract expects. Each `fields` entry maps an output field to a JSONPath read relative to the value at `path`. When that value is an array (such as `data[*].attributes`), each item becomes an object holding only the named fields; otherwise the value itself does. A missing field fails the run with `response_invalid`. Pterodactyl's `listServers` uses `{ "path": "data[*].attributes", "fields": { "id": "identifier", "name": "name" } }`, because the client API names the server id `identifier`. --- ## Template Rules 1. **Typed whole-value substitution**: In `body.json` and `merge.set`, a string consisting of a single `"{{var}}"` placeholder evaluates to the variable's typed value (`integer` becomes a JSON number, `map` becomes a JSON object, `into` / extracted values keep their structure). 2. **Per-segment path encoding**: In `path`, each `{{var}}` is URL-encoded per path segment (`encodeURIComponent` for scalar variables; per-segment encoding joined by `/` for `relpath`, with `{{dirname x}}` and `{{basename x}}` helpers). 3. **No re-templating of values**: Variable values are substituted once and never templated again. A Pterodactyl startup line such as `java -Xmx{{SERVER_MEMORY}}M` passes through as literal text. --- ## Fetch Boundary Rules All HTTP requests go through `packages/plugins/src/boundary.ts`: - A `path` request may only contact `connection.baseUrl`. A `url` request may only contact `connection.baseUrl`, `fetch.allowHosts`, or a host extracted during the same run with `as: "nodeHost"`. Any other host fails with `host_blocked` before sending a request. - Resolved IP addresses are checked against the address guard (`unspecified`, `private`, `cgnat`, `loopback`, `link-local`, `site-local`, `benchmarking`, `multicast`, `broadcast`, `nat64-local`), failing with `address_blocked` when disallowed. - Redirects are followed up to 3 hops only when the target host is allowed and the scheme does not downgrade from `https:` to `http:`; otherwise the request fails with `redirect_blocked` (`host not allowed`, `scheme downgrade`, or `too many redirects`). Cross-origin redirects strip `Authorization` and credential headers. - Signed URLs (`as: "url"`) never carry panel `auth` headers, and their query strings are replaced with `?` in `trace`. --- ## Run Error Codes Every load or run failure returns `{ ok: false, error: RunError }` with one of these 12 `code` values: - `plugin_invalid` — schema validation, capability contract, credential isolation, or template slot check failed (`{ code: "plugin_invalid", pointer, message }`). - `var_invalid` — input variable failed `parseVar` (`{ code: "var_invalid", var, rule }`). - `host_blocked` — target host is outside the allowlist and run node hosts (`{ code: "host_blocked", host }`). - `address_blocked` — resolved IP address is blocked by the address guard (`{ code: "address_blocked", host, address, reason }`). - `redirect_blocked` — redirect was rejected (`{ code: "redirect_blocked", host, reason }`). - `auth_failed` — token request returned a non-accepted status, returned a token with control characters, or a step still returned `401` after refreshing the token (`{ code: "auth_failed", status?, reason? }`). - `status_unexpected` — step returned an HTTP status outside `accept` (`{ code: "status_unexpected", step, status?, body }`). - `timeout` — single HTTP request timed out (`{ code: "timeout", step }`). - `poll_timeout` — `poll` step exceeded `timeoutMs` (`{ code: "poll_timeout", step, attempts }`). - `poll_failed` — `poll` step matched `failWhen` (`{ code: "poll_failed", step, failWhen }`). - `response_invalid` — response body was invalid JSON or missed a required `extract` path (`{ code: "response_invalid", step, reason }`). - `aborted` — the caller's `beforeRequest` hook refused the next request, so the action stopped before sending it (`{ code: "aborted", reason }`). --- ## Complete Example ```json plugin { "format": 1, "id": "example-panel", "kind": "backend", "name": "Example Panel", "connection": { "baseUrl": { "type": "url" }, "apiKey": { "type": "secret" } }, "vars": { "serverId": { "type": "pattern", "pattern": "^[0-9a-f]{8}$" }, "command": { "type": "pattern", "pattern": "^[^\\r\\n]{1,256}$" } }, "auth": { "panel": { "kind": "static", "apply": { "headers": { "Authorization": "Bearer {{apiKey}}" } } } }, "capabilities": ["status", "console"], "actions": { "listServers": { "auth": "panel", "steps": [ { "request": { "method": "GET", "path": "/api/client", "accept": [200], "extract": { "servers": "data[*].attributes" } } } ] }, "status": { "auth": "panel", "steps": [ { "request": { "method": "GET", "path": "/api/client/servers/{{serverId}}/resources", "accept": [200], "extract": { "running": { "path": "attributes.current_state", "equals": "running" } } } } ] }, "sendCommand": { "auth": "panel", "steps": [ { "request": { "method": "POST", "path": "/api/client/servers/{{serverId}}/command", "body": { "json": { "command": "{{command}}" } }, "accept": [204] } } ] } } } ``` --- Source: https://docs.sculk.network/nightly/sculk/development.md # Development guide How code gets from a branch to the dev server. [AGENTS.md](https://github.com/YellowUmbrellaDev/sculk.network/blob/26cfdac/AGENTS.md) holds the short rules; this guide holds the steps. Nightlies, stable releases, fixes and feature stages are in [the release guide](https://docs.sculk.network/nightly/sculk/releases.md). ## Branches | Branch | Purpose | Receives | | --- | --- | --- | | `main` | The only long-lived branch and the default branch. See [Branches](https://docs.sculk.network/nightly/sculk/releases.md#branches) | Every PR, by squash merge | | `release--X.Y` | Fixes for an older stable line | Cherry-picked fix PRs. See [Fix a stable release](https://docs.sculk.network/nightly/sculk/releases.md#fix-a-stable-release) | Work on a short-lived branch cut from `main`, open a PR into `main`, and delete the branch after it merges. ```sh git fetch --prune git switch -c fix-restart-timeout origin/main ``` ```text branch 'fix-restart-timeout' set up to track 'origin/main'. Switched to a new branch 'fix-restart-timeout' ``` A PR into a `release-*` branch fails the `branch-flow` job of `ci` unless every commit in it, other than a merge commit, is a cherry-pick (`git cherry-pick -x`) of a commit already in `main`. ## Commit messages Every commit subject is a [Conventional Commit](https://www.conventionalcommits.org): `(): `. A `commit-msg` hook in `.githooks` checks it. `pnpm install` turns it on through the `prepare` script, which runs `git config core.hooksPath .githooks`. ```sh git commit -m "Add the nightly channel" ``` ```text commit-msg: "Add the nightly channel" is not a Conventional Commit: expected (): , with type one of feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert ``` The hook lets merge, revert, `fixup!`, `squash!` and `amend!` messages through, since git writes them. Because a squash merge turns the PR title into the commit subject on `main`, give the PR the same format. ## Checks The `ci` workflow runs on every commit pushed to a PR into `main` or a `release-*` branch, and on every push to those branches. A new commit never cancels the run of the previous one. A `changes` job filters pull requests so build jobs only run for areas the PR touches; pushes to `main` and `release-*` run everything. | Job | What it proves | Run it locally | | --- | --- | --- | | `lint` | Biome, `.env.example` and the env table match `env-keys.ts`, every relative doc link resolves, and every Mermaid diagram parses | `pnpm lint` | | `typecheck` | `tsc` passes in every package | `pnpm typecheck` | | `test` | Every test passes, and the run leaves the tree clean | `pnpm test` | | `image` | The image builds, starts and `/healthz` reports the commit. Skipped on pushes to `main`, where `deploy-dev` builds it | `docker build -t sculk . && docker run --rm -p 8080:8080 sculk` | | `oauthmc` | Rust fmt, clippy, unit tests, musl release build, Minecraft client matrix, lane `mc-join` e2e test, and Docker healthcheck smoke run | `cargo test --manifest-path crates/oauthmc/Cargo.toml` | | `sculkworm` | Rust fmt, clippy, unit tests, musl release build, Minecraft client verification, and Docker smoke run | `cargo test --manifest-path crates/sculkworm/Cargo.toml` | | `branch-flow` | A PR into a `release-*` branch carries only cherry-picks of commits in `main` (pull requests only) | | | `ci-ok` | All of the above succeeded | | `ci-ok` exists so that one name can be marked as required. GitHub offers branch protection and rulesets on private repositories only on a paid plan, and the `YellowUmbrellaDev` organisation is on Free, so nothing blocks a merge with a red check today. The rule is: merge a PR only when every check is green. When the plan changes, or the repository goes public, require `ci-ok` and a PR on `main` and `release-*`. ## Dev server Every merge to `main` runs `deploy-dev`: 1. `publish` builds the image and pushes `ghcr.io/yellowumbrelladev/sculk.network:sha-<7 chars>` and `:dev`. 2. `deploy` joins the tailnet as `tag:ci` with Tailscale in userspace networking (the runner has no root), connects to the dev host over SSH on port 2222 and passes the new tag. Port 22 on the tailnet address is Tailscale SSH, which ignores the forced command of the key, so the host runs a second `sshd` listener for it. 3. The host pulls that tag and restarts the container. `deploy` then polls `https://dev.sculk.network/healthz` until `commit` equals the pushed commit, and fails after five minutes. Deploys queue in order and never cancel each other, so the server ends on the last merge. Run the workflow again from the Actions tab (`workflow_dispatch`) to redeploy the dev server. The dev server is `https://dev.sculk.network` on the host `0-0-0`. Its stack lives in the `homelab` repository (`hosts/0-0-0/services/sculk-qa`, which is being renamed `sculk-dev`), with its secrets in 1Password. It runs the same image as production with `SCULK_PUBLIC=1`. Treat its data as disposable. ### One-time setup These steps need an owner of the GitHub organisation and of the tailnet. Do them once. 1. Tailnet policy: add `tag:ci` to `tagOwners`. No access rule is needed while the default grant allows every connection; once it is restricted, allow `tag:ci` to reach `0-0-0:2222`. 2. Tailscale admin, Settings, OAuth clients: create a client with the `auth_keys` scope and the tag `tag:ci`. 3. On `0-0-0`, create the deploy key and authorise it with a forced command, so the key can do nothing but deploy a tag. 4. In the repository settings, create the environment `dev`, then add: | Kind | Name | Value | | --- | --- | --- | | Secret | `TS_OAUTH_SECRET` | Secret of the OAuth client | | Secret | `DEV_SSH_KEY` | Private half of the deploy key | | Variable | `DEV_SSH_HOST` | Tailnet name of the dev host, `0-0-0` | | Variable | `DEV_SSH_USER` | User the forced command runs as | | Variable | `DEV_SSH_KNOWN_HOSTS` | Output of `ssh-keyscan 0-0-0` taken from a trusted machine | | Variable | `DEV_URL` | `https://dev.sculk.network` | 5. Sign-in redirect URIs of the Google, Discord and GitHub App registrations: add `https://dev.sculk.network/auth//callback`. The GitHub App's first callback URL is the `github` one. ### Roll back dev Run the workflow `deploy-dev` from the Actions tab, choosing the older commit's ref, or on the host run the deploy command with the old tag. Both pull that exact image. If a migration merged after that commit, the older image refuses the database, which it does not know (see [Switch channels on an instance](https://docs.sculk.network/nightly/sculk/releases.md#switch-channels-on-an-instance)). The dev data is disposable: delete the data volume on the host and let the older image start from an empty database, or roll forward with a fix instead. ## Teaser While the product is in development, `https://sculk.network` serves a one-page teaser from `apps/teaser`: a Cloudflare Worker named `sculk-teaser` with static assets only, attached to the apex domain as a custom domain. The `deploy-teaser` workflow builds and deploys it on every push to `main` that changes `apps/teaser`, `packages/brand`, the font license or the lockfile, then checks that the live page matches the build. Run it from the Actions tab to redeploy. Try a change locally with `node apps/teaser/build.mjs`, then open `apps/teaser/dist/index.html` through any static server (the page loads its fonts and icons from `/`). Deploy by hand with: ```sh CLOUDFLARE_API_TOKEN= pnpm --filter @sculk/teaser run deploy ``` ``` Uploaded sculk-teaser Deployed sculk-teaser triggers sculk.network (custom domain) ``` The token lives in the GitHub environment `teaser` as `CLOUDFLARE_TEASER_TOKEN`. It is an account-owned token named `sculk-teaser-deploy (GitHub Actions)` with Workers Scripts Write and Read on the account and Workers Routes Write and Zone Read on the `sculk.network` zone, nothing else. The logo, the favicon and the ink colour come from `packages/brand`, which the web app also draws from: change the mark there and both the app and the teaser follow. ## Documentation site The documentation for sculk.network, OAuthMC and Sculkworm is built by `apps/docs/build.mjs` into one Cloudflare Worker (`sculk-docs`, `apps/docs/wrangler.jsonc`) at `https://docs.sculk.network` that serves both release channels under a path prefix: | Channel | Prefix | Source | | --- | --- | --- | | Stable | `/stable/` | Each product's latest stable tag (`vX.Y.Z`, `oauthmc-vX.Y.Z`, `sculkworm-vX.Y.Z`) | | Nightly | `/nightly/` | `main` working tree | `/` redirects (`302`) to `/stable/` once at least one product has a stable tag, and to `/nightly/` until then. On `/stable/`, any product without a stable tag renders a "not released yet" page linking to its nightly documentation. Every page also has a Markdown twin for AI agents at the path `apps/docs/src/urls.mjs` defines (such as `/nightly/sculk/self-hosting.md`), with relative links rewritten to absolute URLs (internal docs to their `.md` twin, assets to their absolute URL, other repo files to GitHub). Requesting a page route with `Accept: text/markdown` serves that twin directly. Each channel publishes `//llms.txt` and `//llms-full.txt`, and `/llms.txt` at the root mirrors the default channel. Sidebar navigation is declared per product as titled `sections` in `apps/docs/src/config.mjs`. Any discovered non-excluded Markdown file that is not listed in a section fails the build; internal files go in `EXCLUDED_DOCS` (`docs/decisiones.md`, `docs/design-t*.md`, `docs/especificacion-aileen.md` and `docs/presentacion-aileen.html`). A section entry may set `title` to override only the sidebar label and `agent` (`{ label, task }`) to render a copy-a-prompt card that points an AI agent at that page's absolute Markdown URL (used on `docs/self-hosting.md`). Preview a change locally by building the site and running Wrangler from `apps/docs`: ```sh pnpm --filter @sculk/docs run build pnpm --filter @sculk/docs exec wrangler dev ``` `deploy-docs` runs on every push to `main` touching documented files and when dispatched by `release` after a stable release. Deploy by hand with: ```sh CLOUDFLARE_API_TOKEN= pnpm --filter @sculk/docs run deploy ``` The token lives in the GitHub environment `docs` as `CLOUDFLARE_DOCS_TOKEN`. Create an account-owned Cloudflare API token named `sculk-docs-deploy (GitHub Actions)` with Workers Scripts Write and Read on the account and Workers Routes Write and Zone Read on the `sculk.network` zone, matching the teaser token's least-privilege permissions. ## Everyday routines | Routine | Command | | --- | --- | | Find branches that did not land | `git fetch --prune && git branch -r --no-merged origin/main` | | Check a branch is already in `main` after a squash merge | `git cherry origin/main ` (`-` means it is) | | Add an env variable | Edit `apps/server/src/config/env-keys.ts`, then `node scripts/gen-env-docs.mjs` | | Add a migration | New `apps/server/migrations/S-.sql`; never edit a merged one | | Prove a UI or API change | `pnpm lane up`, then the `verify-sculk` skill | | Run one package's tests | `pnpm --filter @sculk/server test` | | Build or change the sync jar and the installer | [clients/sync.md](https://docs.sculk.network/nightly/sculk/clients/sync.md) | --- Source: https://docs.sculk.network/nightly/sculk/releases.md # Releases How sculk.network, OAuthMC and Sculkworm get from `main` to the people who run them. [AGENTS.md](https://github.com/YellowUmbrellaDev/sculk.network/blob/26cfdac/AGENTS.md) holds the short rules; this guide holds the model and the steps. The `release` workflow does the work, and `scripts/release.mjs` decides what it publishes. ## Channels | Channel | Comes from | When | Version | Image tags | GitHub Release | | --- | --- | --- | --- | --- | --- | | dev.sculk.network | `main` | Every merge | `0.0.0-dev` | `:dev`, `:sha-<7>` | None | | Nightly | `main` | Every night at 03:17 UTC, if something changed and `ci-ok` passed | `0.3.0-nightly.20261126.57` | `:nightly`, the version | Pre-release | | Stable | A nightly, unchanged | When a maintainer decides | `0.3.0` | `:latest`, `:0.3`, from 1.0.0 also `:1`, the version | Latest (sculk.network only) | A nightly carries the number of the next stable release (one minor above the last one), then the date and the run number. By SemVer, `0.3.0-nightly.…` sorts after `0.2.0` and before `0.3.0`. A stable release is a nightly that people already ran: the workflow publishes the exact commit of the latest nightly, it does not take what `main` holds that day. Until 1.0.0, stable is the public beta: a minor release (`0.3.0` after `0.2.0`) may change the API, the plugin format, `sculk.json` or the settings, and its notes say how. Migrations always upgrade the data. From 1.0.0, stable follows SemVer: removing or breaking anything a user relies on takes a new major version. ## Products sculk.network, OAuthMC and Sculkworm each have their own version, tags and images. A product gets a nightly only when something in its image changed since its last one, and its release notes list only the commits that touched it. | Product | Tag | Image | Release assets | Built from | | --- | --- | --- | --- | --- | | sculk.network | `v0.3.0` | `ghcr.io/yellowumbrelladev/sculk.network` | Container image only | The root `Dockerfile`: `apps/server`, `apps/web`, `packages`, `plugins`, `clients/sync`, the OAuthMC and Sculkworm JS SDKs | | OAuthMC | `oauthmc-v0.3.0` | `ghcr.io/yellowumbrelladev/oauthmc` | Container image only | `crates/oauthmc` | | Sculkworm | `sculkworm-v0.3.0` | `ghcr.io/yellowumbrelladev/sculkworm` | Container image, per-target binary archives, `sculkworm-connect.jar`, and `SHA256SUMS` | `crates/sculkworm`, `clients/sync/src`, `clients/sync/build.sh` | No file in the repository holds a version. The workflow stamps it into the image: sculk.network reads `SCULK_VERSION` and reports it in `/healthz`, `GET /api/build` and the User-Agent; the crate images carry it in the `org.opencontainers.image.version` label. `Cargo.toml` stays at `0.1.0`, and the crates are not published to crates.io. The Releases page is the changelog. Only a stable sculk.network release becomes the Latest release on GitHub. A crate's stable release does not. ### Sculkworm release assets Every Sculkworm release (nightly, stable promotion, and fix release) publishes the relay container image `ghcr.io/yellowumbrelladev/sculkworm:`, standalone binary archives, and the Java 8+ `sculkworm-connect.jar` attached to the `sculkworm-v` GitHub Release. Each archive contains the binaries listed below, `LICENSE`, and a short `README.txt` pointing to the documentation, packed reproducibly from the release commit timestamp. | Archive | Target | Binaries included | Notes | | --- | --- | --- | --- | | `sculkworm--x86_64-unknown-linux-musl.tar.gz` | Linux x86_64 (static musl) | `sculkworm`, `sculkworm-agent`, `sculkworm-connect` | Self-contained static binaries for servers and desktops | | `sculkworm--aarch64-unknown-linux-musl.tar.gz` | Linux ARM64 (static musl) | `sculkworm`, `sculkworm-agent`, `sculkworm-connect` | Self-contained static binaries for ARM64 servers and SBCs | | `sculkworm--x86_64-apple-darwin.tar.gz` | macOS Intel (11.0+) | `sculkworm`, `sculkworm-agent`, `sculkworm-connect` | Unsigned cross-compiled Mach-O binaries | | `sculkworm--aarch64-apple-darwin.tar.gz` | macOS Apple Silicon (11.0+) | `sculkworm`, `sculkworm-agent`, `sculkworm-connect` | Unsigned cross-compiled Mach-O binaries | | `sculkworm--x86_64-pc-windows-gnu.zip` | Windows x86_64 (UCRT) | `sculkworm-connect.exe` | Player client only (relay/agent `SIGHUP` reload and `0600` secret checks are Unix-only); cross-compiled with Zig against Windows UCRT instead of `x86_64-pc-windows-msvc` | | `sculkworm-connect.jar` | Java 8+ (cross-platform) | `network.sculk.sync.SculkwormConnect` (`Main-Class`, `Premain-Class`) | Standalone Java 8 player client and `-javaagent` built from `clients/sync/src` inside `eclipse-temurin:17-jdk` | | `SHA256SUMS` | All targets | — | Sorted SHA-256 checksums for every archive and `sculkworm-connect.jar` in the release | The `binaries` job cross-compiles every Rust target from the Linux Blacksmith runner with pinned Zig and `cargo-zigbuild` (plus the pinned `MacOSX11.3.sdk` for Darwin targets), the `connect-jar` job builds `sculkworm-connect.jar` inside `eclipse-temurin:17-jdk` via `clients/sync/build.sh` and uploads only `sculkworm-connect.jar`, and the `publish` job attaches every asset and `SHA256SUMS` to the GitHub Release with `gh release upload --clobber` before moving the floating container tags (`:nightly`, `:latest`, `:X.Y`). Re-running failed jobs overwrites or skips existing assets idempotently. Verify a downloaded archive against `SHA256SUMS` before unpacking it: ```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 [OPTIONS] or: sculkworm connect [OPTIONS] Commands: play Log in if needed and open a local Minecraft listener for login Log in to a closed route via browser redirect or device flow logout Revoke and remove a stored login (or all logins) ``` ## Branches | Branch | Holds | Who writes to it | | --- | --- | --- | | `main` | The next release. Every PR targets it, and it is the default branch | PRs, by squash merge | | `release--X.Y` | Fixes for an older stable line, such as `release-sculk-0.3` | Fix PRs, only when needed | No branch tracks what is released: the tags do (`v0.3.0`, `oauthmc-v0.3.0`), and the Releases page marks the newest sculk.network release as Latest. Nobody pushes to `main` or tags by hand. The one push a person makes by hand is the first one to a release branch, which creates it from a stable tag; see [Fix a stable release](#fix-a-stable-release). ## Publish a nightly Nothing to do: the workflow runs every night. To publish one now, for example to test a fix on a nightly instance, run **release** from the Actions tab on `main` with `channel` `nightly`, or: ```sh gh workflow run release --ref main -f channel=nightly -f product=all ``` The run plans first and prints what it will publish and what it skips: ```text v0.3.0-nightly.20261126.57 from 1a2b3c4d… ghcr.io/yellowumbrelladev/sculk.network:0.3.0-nightly.20261126.57 ghcr.io/yellowumbrelladev/sculk.network:nightly Notice: OAuthMC: nothing in its image changed since oauthmc-v0.1.0-nightly.20261125.50. ``` When `ci-ok` has not passed on the head of `main`, it publishes nothing. To pull a bad nightly, delete its GitHub Release and tag (which removes any attached binary archives and `SHA256SUMS` as well), and point `:nightly` back at the previous one: ```sh gh release delete v0.3.0-nightly.20261126.57 --cleanup-tag --yes docker buildx imagetools create -t ghcr.io/yellowumbrelladev/sculk.network:nightly \ ghcr.io/yellowumbrelladev/sculk.network:0.3.0-nightly.20261125.50 ``` ## Publish a stable release 1. Pick the nightly. The default rule: it has run for seven days, on dev.sculk.network and on at least one nightly instance, with no open issue that blocks it. Look at its notes on the Releases page and at what is still behind a [feature stage](#feature-stages). 2. Run **release** from the Actions tab on `main` with `channel` `stable` and the product. Leave `version` empty to publish the version the nightly previews (`0.3.0` for `0.3.0-nightly.…`), or type a higher one, such as `1.0.0` for the first stable release: ```sh gh workflow run release --ref main -f channel=stable -f product=sculk ``` Only someone with the admin or maintain role on the repository can run it. GitHub has no approval step for environments of a private repository on the Free plan, so the plan checks the role of whoever started the run and stops otherwise: ```text Error: A stable release takes the admin or maintain role on the repository, and someone has write. ``` 3. Check the result: the GitHub Release exists, and the image answers with the version. ```sh docker run --rm -d --name check -p 8081:8080 ghcr.io/yellowumbrelladev/sculk.network:0.3.0 curl -s http://localhost:8081/healthz docker rm -f check ``` ```json {"ok":true,"version":"0.3.0","commit":"1a2b3c4d…"} ``` The planner promotes the latest nightly of that product, so publish it before a newer nightly replaces it, or wait for the next one. It refuses a nightly that a stable release already shipped (wait for the next nightly) and a version lower than the one the nightly previews. When a run fails halfway, for example after the image is pushed or binary archives are built but before the GitHub Release or its assets are uploaded, open it and choose **Re-run failed jobs**. Every step skips or overwrites (`--clobber`) what the first attempt finished, and the floating tags (`:latest`, `:0.3`, `:nightly`) move only at the end, so people who follow them never get an image without its release and assets. ### Documentation site After a stable release finishes, the `release` workflow dispatches `deploy-docs`, which rebuilds `https://docs.sculk.network` (updating `/stable/` from each product's latest stable tag `vX.Y.Z`, `oauthmc-vX.Y.Z`, `sculkworm-vX.Y.Z`, alongside `/nightly/` from `main`). The deploy runs in its own concurrency group so a docs failure never stalls or marks a release as failed. The Cloudflare API token lives in the `docs` environment as `CLOUDFLARE_DOCS_TOKEN` (see [Documentation site](https://docs.sculk.network/nightly/sculk/development.md#documentation-site)). ## Fix a stable release A fix for the newest stable line usually waits for the next stable release: merge it into `main`, then promote the next nightly. When it cannot wait, or when it fixes an older line people still run: 1. Merge the fix into `main` first, as usual. 2. Create the release branch from the stable tag, if it does not exist yet, and cherry-pick the fix onto a branch cut from it. `-x` records where the commit came from, which `ci` checks: ```sh git fetch --tags origin git push origin v0.3.0^{commit}:refs/heads/release-sculk-0.3 git switch -c fix-restart-timeout-0.3 origin/release-sculk-0.3 git cherry-pick -x ``` 3. Open a PR into `release-sculk-0.3`. The `branch-flow` job of `ci` fails if a commit in it, other than a merge commit, is not a cherry-pick of a commit in `main`. It reads the `-x` trailer, so it catches a fix that never went into `main`; the maintainer who publishes still reviews what the PR changes. Merge it once every check passes. 4. Run **release** on `release-sculk-0.3` with `channel` `stable` and `product` `sculk`. It publishes `v0.3.1` from the head of the branch. It moves `:0.3`, `:0` from 1.0.0 on if that major has nothing newer, and `:latest` only if 0.3 is still the newest line. Delete a release branch once nobody runs that line. ## Feature stages A stable release is a copy of a nightly, so everything merged into `main` reaches stable. A feature flag is how unfinished work rides along without showing up there. Use one for a user-visible feature that will not be finished before the next stable release. Never gate a bug fix or a small change. Flags live in one map in `apps/server/src/config/features.ts`. Each entry names its stage (`nightly` or `labs`), where its Labs toggle will live (`user` or `server`), and a short description: ```ts export const FEATURES = { myFeature: { stage: 'nightly', scope: 'server', about: 'Short description of what the feature adds.', }, } as const satisfies Record; ``` Every feature follows the same path, one small PR per step: 1. `nightly` while it is unfinished: on in dev and nightly builds, off in stable. 2. `labs` when it is finished: still on in nightly builds, off by default in stable, where the Labs page will let people switch it on. 3. Removed from `FEATURES` once it is trusted, together with every check for it. The next stable release ships it to everyone. Check the flag in the route or service as well as in the UI, so a hidden feature cannot be called directly: ```ts import { isEnabled } from '../config/features'; if (!isEnabled('myFeature')) return c.json({ error: 'not_found' }, 404, { 'Cache-Control': 'no-store' }); ``` ```tsx import { useFeature } from '../shell/useBuild'; const enabled = useFeature('myFeature'); ``` While a feature is behind a flag, it must not change what already works when the flag is off. Its migrations still run on stable, so they may only add tables or columns, never change or drop existing ones. `GET /api/build` reports the version, the channel (`dev`, `nightly` or `stable`, derived from the version) and the enabled flags, and the footer shows the channel (`Dev`, `Nightly`, or `Beta` for `0.x` stable builds; hidden from `1.0.0` on). An operator forces a flag with `SCULK_FEATURES`, a comma-separated list (`name` on, `-name` off). Boot refuses a name that is not in `FEATURES`. Currently `FEATURES` holds `oidcProvider` (`nightly`, [OIDC provider](https://docs.sculk.network/nightly/sculk/oidc-provider.md)) and `sculkworm` (`nightly`, [Sculkworm integration](https://docs.sculk.network/nightly/sculk/sculkworm-integration.md)). ### Labs The Labs pages do not exist yet. They come with the first `labs` feature, as two pages: one in the account settings for `user` features, and one in each server's settings for `server` features, which the server owner sets for every player. An instance operator's `SCULK_FEATURES` wins over both, and the page shows the switch locked. ## Switch channels on an instance Set `SCULK_IMAGE` in `.env` to the channel or version, then pull and restart: | You want | `SCULK_IMAGE` | | --- | --- | | Every stable release | `ghcr.io/yellowumbrelladev/sculk.network:latest` | | Fixes for one line only | `ghcr.io/yellowumbrelladev/sculk.network:0.3` | | One exact version | `ghcr.io/yellowumbrelladev/sculk.network:0.3.1` | | Every nightly | `ghcr.io/yellowumbrelladev/sculk.network:nightly` | Moving from stable to nightly works at any time. Moving back does not: a nightly may have applied migrations that the stable release does not know, and the server refuses to start on a database newer than itself: ```text Error: migrations: the database has S40-labs.sql, which this version does not know. A newer version migrated it. Run that version or a later one, or restore a backup taken before the upgrade. ``` Wait for the stable release that contains that nightly, or restore the backup you took before the switch. ## One-time setup These need a repository admin. Do them once. 1. Before the first release, Settings → Environments: create `nightly` and `release`. They need no protection rules: the workflow checks the role of whoever starts a stable release. 2. Once the repository is public, or on a paid plan: protect `main` and `release-*` (require a PR and `ci-ok`), and on the `release` environment add the maintainers as **Required reviewers** and limit **Deployment branches** to `main` and `release-*`. Also restrict **Deployment branches** on the `docs` environment to `main` once the plan allows. Until then the role check stops mistakes, not someone with write access: they can push a branch whose workflow skips the check, as they can with any workflow in the repository. 3. After the first run, open each package on GitHub (Packages → `sculk.network`, `oauthmc`, `sculkworm`) and set its visibility, and under **Manage Actions access** give this repository the **Write** role. --- Source: https://docs.sculk.network/nightly/oauthmc.md

OAuthMC by sculk.network: verify Minecraft Java accounts by joining a server

# OAuthMC OAuthMC is a standalone Rust service that verifies a player owns a Minecraft Java Edition account by having them join a Minecraft server. It runs an online-mode Minecraft listener alongside a private HTTP API, requires no database, and lets platforms verify accounts without Microsoft Entra app approval. ## How it works 1. Your platform creates a short-lived ticket for a Minecraft username over the HTTP API (`POST /v1/tickets`). 2. The player joins your OAuthMC server in Minecraft Java Edition. OAuthMC authenticates them against Mojang's session server and delivers a single-use 8-character code (`XXXX-XXXX`): - **Code mode** (all supported versions): disconnects the player with the code, which they enter on your platform. - **Link mode** (Minecraft 1.21.6+, automatic code-mode fallback on older versions): holds the player in Configuration with an in-game dialog (**Open link** and **Copy code**) and disconnects them with a confirmation message once redeemed. 3. Your platform redeems the code (`POST /v1/tickets/{id}/redeem`) to receive the player's Mojang UUID and canonical username. ```mermaid sequenceDiagram participant Platform participant OAuthMC participant Player Platform->>OAuthMC: POST /v1/tickets {name} OAuthMC-->>Platform: 201 {id, address, expires_at} Platform-->>Player: Show server address Player->>OAuthMC: Join in Minecraft (online mode) OAuthMC-->>Player: Code disconnect or 1.21.6+ dialog Player->>Platform: Enter code or confirm link in signed-in session Platform->>OAuthMC: POST /v1/tickets/{id}/redeem {code} OAuthMC-->>Platform: 200 {uuid, name} ``` ## Quick start `ghcr.io/yellowumbrelladev/oauthmc` is not published yet; it ships with the first release. Build the container locally from `crates/oauthmc` (or `.` if you are already inside that directory): ```sh docker build -t oauthmc crates/oauthmc ``` ```text => => naming to docker.io/library/oauthmc:latest ``` Generate a 32+ character API key and start OAuthMC (binding port `8080` to loopback so the HTTP API stays private): ```sh API_KEY=$(openssl rand -hex 24) docker run -d --name oauthmc \ -p 25565:25565 \ -p 127.0.0.1:8080:8080 \ -e OAUTHMC_API_KEYS="$API_KEY" \ -e OAUTHMC_PUBLIC_ADDRESS="verify.example.com" \ oauthmc ``` ```text ``` Create a ticket: ```sh curl -sS -X POST http://127.0.0.1:8080/v1/tickets \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{"name":"HatsuneMiku"}' ``` ```json {"address":"verify.example.com","exclusive":false,"expires_at":"2026-11-26T10:32:09Z","id":"tkt_823fc8dac7451029a38794aef229ea24","max_attempts":5,"metadata":null,"mode":"code","name":"HatsuneMiku","status":"pending"} ``` Join `127.0.0.1:25565` in Minecraft Java Edition with that account to get your one-time code, then redeem it: ```sh curl -sS -X POST http://127.0.0.1:8080/v1/tickets/tkt_823fc8dac7451029a38794aef229ea24/redeem \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{"code":"N6AN-46TW"}' ``` ```json {"name":"HatsuneMiku","uuid":"a0c4b8c5-a04f-4a6f-9d02-1dea6154a9f6"} ``` For the full walkthrough with every step and status check, read [Getting started](https://docs.sculk.network/nightly/oauthmc/getting-started.md). ## Documentation - [Documentation index and glossary](https://docs.sculk.network/nightly/oauthmc/index.md) - [Getting started](https://docs.sculk.network/nightly/oauthmc/getting-started.md) — build, run, join, and redeem end to end - [Integrating OAuthMC](https://docs.sculk.network/nightly/oauthmc/integrating.md) — code mode, link mode confirmation pages, polling, errors, SDK, and raw HTTP - [Configuration](https://docs.sculk.network/nightly/oauthmc/configuration.md) — every `OAUTHMC_*` environment variable and message template - [HTTP API](https://docs.sculk.network/nightly/oauthmc/api.md) — endpoints, schemas, and error codes ([OpenAPI spec](https://docs.sculk.network/nightly/oauthmc/openapi.md)) - [Deploying](https://docs.sculk.network/nightly/oauthmc/deploy.md) — Docker Compose, DNS SRV, TCP proxies, health checks, upgrades, and shutdown - [Security model](https://docs.sculk.network/nightly/oauthmc/security.md) — threat model, session binding, tenant isolation, rate limits, and cryptography - [Minecraft protocol](https://docs.sculk.network/nightly/oauthmc/protocol.md) — version matrix, packet quirks, and Configuration dialogs - [TypeScript SDK](https://docs.sculk.network/nightly/oauthmc/sdk/js.md) — zero-dependency `oauthmc` client for Node.js 18+, Deno, Bun, and Cloudflare Workers - [Contributing](https://docs.sculk.network/nightly/oauthmc/contributing.md) — building from source, Rust tests, client matrix, and releases ## Supported versions Verified against real `node-minecraft-protocol` clients in online mode: - **Code mode**: 1.8.9, 1.12.2, 1.16.5, 1.19, 1.19.2, 1.20.1, 1.21.1, and 26.1. - **Link mode**: 1.21.6, 1.21.8, 1.21.11, and 26.1 (older clients fall back to code mode). Protocol `776` (26.2) and `777` (26.3) are implemented from the protocol spec and verified by in-repo integration tests. See [Minecraft protocol](https://docs.sculk.network/nightly/oauthmc/protocol.md) for details. ## License OAuthMC is licensed under the [MIT License](https://github.com/YellowUmbrellaDev/sculk.network/blob/26cfdac/crates/oauthmc/LICENSE). OAuthMC is not affiliated with or endorsed by Mojang Studios or Microsoft. Minecraft is a trademark of Mojang Studios. --- Source: https://docs.sculk.network/nightly/oauthmc/getting-started.md # Getting started This guide builds the OAuthMC container locally, starts it, creates a verification ticket, joins with Minecraft, and redeems the code. Every command runs in a terminal on the host. Each command block is followed by the output you see. Values in angle brackets, like ``, change on every run. ## Prerequisites - Docker Engine - `curl` and `openssl` - Minecraft Java Edition (or the test client in `tests/clients/` for local testing without a real Minecraft account) ## 1. Build the container image The prebuilt image at `ghcr.io/yellowumbrelladev/oauthmc` is not published yet; it ships with the first stable release. Until then, build the image from the `crates/oauthmc` directory (or pass `crates/oauthmc` from the monorepo root): ```sh docker build -t oauthmc crates/oauthmc ``` The build compiles a static Linux musl binary and packages it into a non-root distroless image. It finishes with: ```text => => naming to docker.io/library/oauthmc:latest ``` ## 2. Generate an API key and start OAuthMC Every key in `OAUTHMC_API_KEYS` must be at least 32 characters long. Generate a random 48-character hex key: ```sh API_KEY=$(openssl rand -hex 24) echo "$API_KEY" ``` ```text <48 hex characters> ``` Start the container. Expose port `25565` for Minecraft clients and bind port `8080` to `127.0.0.1` so the HTTP API stays private: ```sh docker run -d --name oauthmc \ -p 25565:25565 \ -p 127.0.0.1:8080:8080 \ -e OAUTHMC_API_KEYS="$API_KEY" \ -e OAUTHMC_PUBLIC_ADDRESS="verify.example.com" \ oauthmc ``` ```text ``` Check the startup log and the health probe: ```sh docker logs oauthmc ``` ```text level=info event=listening mc_addr=0.0.0.0:25565 api_addr=0.0.0.0:8080 ``` ```sh curl -sS http://127.0.0.1:8080/healthz ``` ```json {"ok":true} ``` ## 3. Create a ticket Replace `HatsuneMiku` with the Minecraft Java username you want to verify: ```sh curl -sS -X POST http://127.0.0.1:8080/v1/tickets \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{"name":"HatsuneMiku"}' ``` ```json {"address":"verify.example.com","exclusive":false,"expires_at":"2026-11-26T10:32:09Z","id":"tkt_823fc8dac7451029a38794aef229ea24","max_attempts":5,"metadata":null,"mode":"code","name":"HatsuneMiku","status":"pending"} ``` Save the returned `id` as `TICKET_ID`: ```sh TICKET_ID="tkt_823fc8dac7451029a38794aef229ea24" ``` ## 4. Join the Minecraft server Open Minecraft Java Edition, go to **Multiplayer**, add `127.0.0.1:25565` (or your `OAUTHMC_PUBLIC_ADDRESS`), and join. OAuthMC completes the online-mode login handshake against Mojang's session server and disconnects you with a one-time 8-character code: ```text Your verification code: N6AN-46TW Enter it on the website (expires in 15 min). Never share this code with anyone. ``` You can confirm the ticket moved from `pending` to `joined`: ```sh curl -sS "http://127.0.0.1:8080/v1/tickets/$TICKET_ID" \ -H "Authorization: Bearer $API_KEY" ``` ```json {"attempts_left":5,"expires_at":"2026-11-26T10:32:09Z","id":"tkt_823fc8dac7451029a38794aef229ea24","metadata":null,"mode":"code","name":"HatsuneMiku","status":"joined"} ``` `GET /v1/tickets/{id}` never returns the player's Mojang UUID. ## 5. Redeem the code Send the code from the disconnect screen to `POST /v1/tickets/{id}/redeem`. Matching ignores case and dashes: ```sh curl -sS -X POST "http://127.0.0.1:8080/v1/tickets/$TICKET_ID/redeem" \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{"code":"N6AN-46TW"}' ``` ```json {"name":"HatsuneMiku","uuid":"a0c4b8c5-a04f-4a6f-9d02-1dea6154a9f6"} ``` Redeeming consumes the ticket. A second redeem returns `409 Conflict`: ```json {"error":"not_redeemable","message":"ticket cannot be redeemed in its current status","status":"redeemed"} ``` If you send a wrong code before redeeming, OAuthMC returns `422 Unprocessable Entity` and decrements `attempts_left`: ```json {"attempts_left":4,"error":"wrong_code","message":"verification code does not match"} ``` ## 6. Clean up Remove the test container when you finish: ```sh docker rm -f oauthmc ``` ```text oauthmc ``` ## Next steps - Read [Integrating OAuthMC](https://docs.sculk.network/nightly/oauthmc/integrating.md) to wire code mode or link mode into your backend and UI. - Read [Configuration](https://docs.sculk.network/nightly/oauthmc/configuration.md) to tune TTLs, rate limits, MOTD, favicon, and message templates. - Read [Deploying](https://docs.sculk.network/nightly/oauthmc/deploy.md) to run OAuthMC with Docker Compose, DNS SRV records, or a TCP proxy. --- Source: https://docs.sculk.network/nightly/oauthmc/integrating.md # Integrating OAuthMC This guide shows how a platform connects to OAuthMC, chooses between code mode and link mode, builds a safe confirmation page, polls ticket status, and handles errors. OAuthMC's HTTP API is server-to-server only. Never send an API key from `OAUTHMC_API_KEYS` to browser code or a mobile client. ## Verification flow ```mermaid sequenceDiagram participant Platform participant OAuthMC participant Player Platform->>OAuthMC: POST /v1/tickets {name, mode, link_url?} OAuthMC-->>Platform: 201 {id, address, mode, status: "pending", expires_at} Platform-->>Player: Show server address (and code input in code mode) Player->>OAuthMC: Minecraft Login Start (username) Note over OAuthMC: Check open ticket + per-IP rate limit
RSA + AES-128-CFB8 + Mojang hasJoined alt Code mode (or Minecraft < 1.21.6) OAuthMC-->>Player: Login Disconnect with code (XXXX-XXXX) Player->>Platform: Enter code in signed-in session else Link mode (Minecraft >= 1.21.6) OAuthMC-->>Player: Configuration Show Dialog (Open link + Copy code) Player->>Platform: Click Open link -> confirm POST in signed-in session end Platform->>OAuthMC: POST /v1/tickets/{id}/redeem {code} OAuthMC-->>Platform: 200 {uuid, name} opt Link mode OAuthMC-->>Player: Configuration Disconnect ("verified" message) end ``` ## Code mode vs link mode - **Code mode** (`mode: "code"`, the default) works on every supported Minecraft version (tested across 1.8.9–26.1). OAuthMC disconnects the player during Login with an 8-character code (`XXXX-XXXX`). The player types or pastes that code into your platform's form. - **Link mode** (`mode: "link"` with `link_url`) targets Minecraft 1.21.6 and later (protocol `>= 771`). OAuthMC transitions the client to Configuration and displays a native dialog with **Open link** and **Copy code** buttons while holding the connection open. As soon as your platform redeems the ticket, OAuthMC disconnects the player with the `verified` message. Players on versions older than 1.21.6—or joining when `OAUTHMC_MAX_HELD`, `OAUTHMC_MAX_HELD_PER_IP`, or mixed-tenant isolation triggers—receive a code-mode disconnect even for a link-mode ticket. Keep a manual code input on your platform alongside link mode so every player can finish verification. ## Building the link-mode confirmation page Link mode shifts the code from manual typing to a browser navigation. That navigation is only safe when your platform enforces three rules: 1. **Put `{ticket}` and `{code}` in the URL fragment, not the query string.** Use a `link_url` such as: ```text https://example.com/account/minecraft/verify#ticket={ticket}&code={code} ``` Browsers do not send URL fragments in HTTP requests, so the ticket ID and code never appear in reverse proxy logs, application logs, or `Referer` headers. Read `window.location.hash` on the client, keep `{ticket, code}` in `sessionStorage` if you need to redirect through sign-in, and clear the fragment immediately with `window.history.replaceState(null, '', '/account/minecraft/verify')`. Also send `Referrer-Policy: no-referrer` on the verification page. 2. **Bind every redeem to the authenticated session that created the ticket.** Store the active ticket ID against the signed-in user in your platform's database (for example, `minecraft_join_tickets(user_id, ticket_id, name)`). When the player opens the confirmation page, require an authenticated session and check that the ticket ID from the link matches the ticket owned by that session's user. Reject mismatches with `404` or `403` and never call `/redeem` on a ticket belonging to another user. See [Security model](https://docs.sculk.network/nightly/oauthmc/security.md#link-mode-requires-session-binding-on-the-platform) for the attack this prevents. 3. **Never redeem on `GET`.** Render a confirmation view showing the Minecraft username and the signed-in platform account, and perform the redeem on an explicit `POST` action protected by your platform's session and CSRF checks. Link previews, browser prefetchers, and accidental clicks must never complete account linking. If your development environment runs on plain `http://` (so OAuthMC rejects `link_url` with `422 invalid_link_url`), catch `invalid_link_url` or `unsupported_mode` and fall back to creating a `mode: "code"` ticket instead of enabling `OAUTHMC_ALLOW_HTTP_LINKS` in production. ## TypeScript SDK example The zero-dependency [`oauthmc`](https://docs.sculk.network/nightly/oauthmc/sdk/js.md) package works in Node.js 18+, Deno, Bun, and Cloudflare Workers. ```ts import { OAuthMC, OAuthMCError, isValidMinecraftName } from 'oauthmc'; const oauthmc = new OAuthMC({ baseUrl: process.env.OAUTHMC_URL ?? 'http://oauthmc:8080', apiKey: process.env.OAUTHMC_API_KEY!, timeoutMs: 5_000, }); // 1. Start verification for a signed-in user. export async function startVerification(userId: string, playerName: string) { if (!isValidMinecraftName(playerName)) { throw new Error('Invalid Minecraft username'); } let ticket; try { ticket = await oauthmc.createTicket({ name: playerName, mode: 'link', linkUrl: 'https://example.com/account/minecraft/verify#ticket={ticket}&code={code}', ttlSeconds: 900, maxAttempts: 5, metadata: { userId }, }); } catch (err) { if (err instanceof OAuthMCError && err.status === 422 && err.code === 'invalid_link_url') { ticket = await oauthmc.createTicket({ name: playerName, mode: 'code', ttlSeconds: 900, maxAttempts: 5, metadata: { userId }, }); } else { throw err; } } // Persist { userId, ticketId: ticket.id, name: ticket.name } in your database. return ticket; } // 2. Redeem from a POST handler after verifying the signed-in user owns ticketId. export async function completeVerification( userId: string, ownedTicketId: string, expectedName: string, submittedCode: string, ) { const result = await oauthmc.redeem(ownedTicketId, submittedCode); if (result.ok) { // Defense in depth: confirm canonical username matches the ticket. if (result.name.toLowerCase() !== expectedName.toLowerCase()) { throw new Error('Username mismatch'); } // Always store result.uuid and result.name returned by OAuthMC. return { ok: true as const, uuid: result.uuid, name: result.name }; } return result; // wrong_code | not_redeemable | not_found } ``` ## Raw HTTP example Any language with an HTTP client can integrate directly against the [HTTP API](https://docs.sculk.network/nightly/oauthmc/api.md) or generate a client from [openapi.yaml](https://docs.sculk.network/nightly/oauthmc/openapi.md). Create a link-mode ticket: ```sh curl -sS -X POST http://127.0.0.1:8080/v1/tickets \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "HatsuneMiku", "mode": "link", "link_url": "https://example.com/account/minecraft/verify#ticket={ticket}&code={code}" }' ``` ```json {"address":"verify.example.com","exclusive":false,"expires_at":"2026-11-26T10:32:10Z","id":"tkt_cf7711bb913524ba2b17e16370a52105","max_attempts":5,"metadata":null,"mode":"link","name":"HatsuneMiku","status":"pending"} ``` Poll ticket status: ```sh curl -sS http://127.0.0.1:8080/v1/tickets/tkt_cf7711bb913524ba2b17e16370a52105 \ -H "Authorization: Bearer $API_KEY" ``` ```json {"attempts_left":5,"expires_at":"2026-11-26T10:32:10Z","id":"tkt_cf7711bb913524ba2b17e16370a52105","metadata":null,"mode":"link","name":"HatsuneMiku","status":"joined"} ``` Redeem the code once the player confirms on your page: ```sh curl -sS -X POST http://127.0.0.1:8080/v1/tickets/tkt_cf7711bb913524ba2b17e16370a52105/redeem \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{"code":"7DQ8-AM76"}' ``` ```json {"name":"HatsuneMiku","uuid":"a0c4b8c5-a04f-4a6f-9d02-1dea6154a9f6"} ``` Cancel a pending ticket when a user abandons or restarts verification: ```sh curl -sS -i -X DELETE http://127.0.0.1:8080/v1/tickets/tkt_cf7711bb913524ba2b17e16370a52105 \ -H "Authorization: Bearer $API_KEY" ``` ```text HTTP/1.1 204 No Content date: Thu, 26 Nov 2026 10:17:12 GMT ``` ## Polling ticket status Poll `GET /v1/tickets/{id}` from your backend (for example, every 2–3 seconds while the verification modal is open) to update the UI when the player joins or when the ticket transitions to a terminal state: | `status` | Meaning | UI action | | --- | --- | --- | | `pending` | Waiting for the player to join in Minecraft. | Keep showing the server address. | | `joined` | Player authenticated with Mojang and received a code/dialog. | Focus the code input or prompt the player to click **Open link**. | | `redeemed` | Ticket was redeemed (for example, in another tab via link mode). | Refresh the account state and stop polling. | | `expired` | Ticket TTL elapsed. | Show an expired notice with a button to start a new ticket; stop polling. | | `locked` | Wrong codes exhausted `max_attempts`. | Show a locked notice with a button to start a new ticket; stop polling. | If `GET /v1/tickets/{id}` returns `404 not_found`, the ticket was deleted, swept after `OAUTHMC_EXPIRED_GRACE_SECONDS`, or lost on an OAuthMC restart. Clear the local ticket record and let the user start a new verification. ## Error handling Handle expected redeem outcomes explicitly instead of treating them as server crashes: - `422 wrong_code`: display the remaining `attempts_left`. If `attempts_left` is `0`, the ticket is now `locked`. - `409 not_redeemable`: inspect `status`: - `pending`: the player submitted a code before joining in Minecraft. - `redeemed`: already completed (for example, double submit or redeemed in another tab). - `expired` or `locked`: prompt the player to start a new ticket. - `404 not_found`: ticket no longer exists; clear your stored ticket row. - `503 ticket_limit`: OAuthMC reached `OAUTHMC_MAX_TICKETS` or `OAUTHMC_MAX_TICKETS_PER_KEY`. Rate-limit ticket creation per user on your platform and delete displaced tickets when a user starts a new one. - Network errors, timeouts, or `5xx`: return a temporary-unavailable error to the user without deleting their local ticket so they can retry. ## Multi-tenant API keys Pass multiple comma-separated keys in `OAUTHMC_API_KEYS` to share one OAuthMC instance across several platforms or environments (for example, staging and production): - Each key is an isolated tenant on `/v1/*`. Tickets created by key A return `404 not_found` to key B. - If two tenants hold open tickets for the same Minecraft username at the same time, OAuthMC ignores per-ticket `messages` overrides and falls back to code mode using server templates. Both tenants' tickets still receive the code hash so either can redeem the code. ## Message overrides You can override in-game text at two levels: - **Instance-wide** via `OAUTHMC_MESSAGES` (JSON file path). Overrides any of the 14 templates, including pre-ticket messages (`no_ticket`, `rate_limited`, `shutdown`). - **Per-ticket** via the `messages` field on `POST /v1/tickets` (for localization or per-platform branding). Overrides any of the 11 ticket-scoped templates (`code`, `unverified`, `dialog_title`, `dialog_code`, `link`, `open_link`, `copy_code`, `verified`, `expired`, `locked`, `replaced`), up to 512 bytes each. Per-ticket overrides apply only when every open ticket for that username belongs to the same tenant. See [Configuration](https://docs.sculk.network/nightly/oauthmc/configuration.md#message-templates) for every key, default string, and placeholder. --- Source: https://docs.sculk.network/nightly/oauthmc/index.md # OAuthMC documentation OAuthMC verifies that a player owns a Minecraft Java Edition account by having them join a Minecraft server. These pages cover running, integrating, configuring, operating, and contributing to OAuthMC. ## Pages - [Getting started](https://docs.sculk.network/nightly/oauthmc/getting-started.md): build the container, create a ticket, join with Minecraft, and redeem a code end to end. - [Integrating OAuthMC](https://docs.sculk.network/nightly/oauthmc/integrating.md): connect a platform with code mode or link mode, build the confirmation page, poll status, and handle errors. - [Configuration](https://docs.sculk.network/nightly/oauthmc/configuration.md): every `OAUTHMC_*` environment variable, its default, its bounds, and the message templates. - [HTTP API](https://docs.sculk.network/nightly/oauthmc/api.md): endpoint reference, schemas, status codes, and error codes, alongside [openapi.yaml](https://docs.sculk.network/nightly/oauthmc/openapi.md). - [Deploying](https://docs.sculk.network/nightly/oauthmc/deploy.md): Docker Compose, DNS SRV records, TCP proxies, health checks, upgrades, and graceful shutdown. - [Security model](https://docs.sculk.network/nightly/oauthmc/security.md): threat model, session binding, tenant isolation, rate limiting, and cryptography. - [Minecraft protocol](https://docs.sculk.network/nightly/oauthmc/protocol.md): supported versions, wire-level quirks, and how link mode works in the Configuration state. - [TypeScript SDK](https://docs.sculk.network/nightly/oauthmc/sdk/js.md): zero-dependency client library (`oauthmc`) for Node.js, Deno, Bun, and Cloudflare Workers. - [Contributing](https://docs.sculk.network/nightly/oauthmc/contributing.md): building from source, running the Rust tests and client matrix, and cutting a release. ## Glossary - **Platform**: the web application or backend service that calls the OAuthMC HTTP API to verify players. - **Player**: the person proving ownership of a Minecraft Java Edition account. - **Ticket**: a short-lived, in-memory verification request created by a platform for one Minecraft username. - **Code**: a single-use 8-character secret (`XXXX-XXXX`) generated when a player completes online-mode login. - **Code mode**: the default verification flow. OAuthMC disconnects the player during Login with their code, and the player enters that code on the platform. - **Link mode**: the verification flow for Minecraft 1.21.6 and later. OAuthMC holds the player in the Configuration state and shows an in-game dialog with **Open link** and **Copy code** buttons. Older clients fall back to code mode. - **Tenant**: the isolated scope bound to one bearer API key in `OAUTHMC_API_KEYS`. One tenant cannot read, redeem, or delete another tenant's tickets. --- Source: https://docs.sculk.network/nightly/oauthmc/configuration.md # Configuration OAuthMC reads all configuration from `OAUTHMC_*` environment variables at startup. If any value is invalid or out of range, OAuthMC prints one diagnostic line to stderr and exits with status `2`: ```text configuration error: OAUTHMC_API_KEYS must be set with at least one key of at least 32 characters ``` Boolean variables accept `true`, `false`, `1`, `0`, `yes`, or `no` (case-insensitive). Empty or whitespace-only values are treated as unset, except for `OAUTHMC_MOTD`, where only an empty string falls back to the default. ## Listeners and identity | Variable | Default | Format / range | Purpose | | --- | --- | --- | --- | | `OAUTHMC_API_KEYS` | *(required)* | Comma-separated strings, each >= 32 characters | Bearer tokens for `/v1/*`. Each distinct key defines an isolated tenant. Whitespace around commas is trimmed and duplicates are removed. | | `OAUTHMC_MC_ADDR` | `0.0.0.0:25565` | `ip:port` | TCP socket address for the Minecraft listener (IPv4 or `[IPv6]:port`). | | `OAUTHMC_API_ADDR` | `127.0.0.1:8080` (`0.0.0.0:8080` in Docker) | `ip:port` | TCP socket address for the HTTP API listener. Bind to loopback or a private container network. | | `OAUTHMC_PUBLIC_ADDRESS` | *(unset)* | Non-empty string | Public Minecraft hostname echoed in `address` by `POST /v1/tickets`. Returns `null` when unset. | | `OAUTHMC_SESSION_URL` | `https://sessionserver.mojang.com` | `https://...` or `http://...` | Mojang session server base URL. Trailing slashes are stripped. Use `http://` only for local mocks and tests. | ## Tickets | Variable | Default | Format / range | Purpose | | --- | --- | --- | --- | | `OAUTHMC_TICKET_TTL` | `900` | `1..=OAUTHMC_MAX_TTL` | Default ticket lifetime in seconds. Must not exceed `OAUTHMC_MAX_TTL`. | | `OAUTHMC_MAX_TTL` | `3600` | `1..=86400` | Maximum `ttl_seconds` a platform may request per ticket. | | `OAUTHMC_MAX_ATTEMPTS` | `5` | `1..=OAUTHMC_MAX_ATTEMPTS_CAP` | Default redeem attempts before a ticket locks. Must not exceed `OAUTHMC_MAX_ATTEMPTS_CAP`. | | `OAUTHMC_MAX_ATTEMPTS_CAP` | `10` | `1..=100` | Maximum `max_attempts` a platform may request per ticket. | | `OAUTHMC_EXCLUSIVE` | `false` | Boolean | Default `exclusive` flag for new tickets. When `true`, `POST /v1/tickets` returns `409 name_busy` if any open ticket exists for that username across any tenant. | | `OAUTHMC_MAX_TICKETS` | `10000` | `1..=1000000` | Global cap on stored tickets, including expired tickets inside their grace period. Returns `503 ticket_limit` when full. | | `OAUTHMC_MAX_TICKETS_PER_KEY` | `min(1000, OAUTHMC_MAX_TICKETS)` | `1..=OAUTHMC_MAX_TICKETS` | Per-tenant cap on stored tickets, including expired tickets in grace. Must not exceed `OAUTHMC_MAX_TICKETS`. Returns `503 ticket_limit` when full. | | `OAUTHMC_EXPIRED_GRACE_SECONDS` | `300` | `0..=86400` | Seconds an expired ticket stays queryable as `expired` before the background sweep removes it. | ## Link mode Link mode holds clients on Minecraft 1.21.6 and later in the Configuration state while showing an in-game dialog. If a held-connection limit is reached, OAuthMC falls back to a code-mode disconnect for that join. | Variable | Default | Format / range | Purpose | | --- | --- | --- | --- | | `OAUTHMC_ALLOW_HTTP_LINKS` | `false` | Boolean | Allow `http://` in `link_url` templates. Leave `false` in production so only `https://` URLs are accepted. | | `OAUTHMC_LINK_HOLD_SECONDS` | `600` | `1..=86400` | Maximum seconds a link-mode connection stays held in Configuration. Capped by the ticket's remaining TTL. | | `OAUTHMC_MAX_HELD` | `OAUTHMC_MAX_CONNECTIONS / 2` (`128`) | `0..OAUTHMC_MAX_CONNECTIONS` | Maximum concurrent held link-mode connections globally. Must be strictly less than `OAUTHMC_MAX_CONNECTIONS` so held sessions cannot starve code-mode logins or status pings. | | `OAUTHMC_MAX_HELD_PER_IP` | `2` | `0..=10000` | Maximum concurrent held link-mode connections per IP bucket (IPv4 `/32`, IPv6 `/64`). | ## Limits and timeouts Per-IP limits group IPv4 peers by `/32` and IPv6 peers by `/64`. IPv4-mapped IPv6 addresses (`::ffff:a.b.c.d`) fold back into their IPv4 `/32` bucket. | Variable | Default | Format / range | Purpose | | --- | --- | --- | --- | | `OAUTHMC_MAX_PACKET_LEN` | `4096` | `256..=65536` | Maximum Minecraft packet payload length in bytes during Handshake and Login. | | `OAUTHMC_MAX_HANDSHAKE_ADDR_LEN` | `255` | `16..=4096` | Maximum Handshake server address length in bytes. | | `OAUTHMC_LOGIN_TIMEOUT_SECONDS` | `10` | `1..=120` | Overall deadline in seconds for Handshake and Login (including Login Acknowledged in link mode). | | `OAUTHMC_SESSION_TIMEOUT_SECONDS` | `5` | `1..=60` | HTTP timeout in seconds for Mojang `hasJoined` requests. | | `OAUTHMC_MAX_CONNECTIONS` | `256` | `1..=100000` | Global concurrent Minecraft TCP connection cap (includes held link-mode connections). | | `OAUTHMC_MAX_CONNECTIONS_PER_IP` | `16` | `1..=10000` | Per-IP concurrent Minecraft TCP connection cap (includes held connections). | | `OAUTHMC_AUTH_RATE_PER_MINUTE` | `6` | `1..=100000` | Per-IP auth token bucket refill rate per minute, checked after confirming an open ticket exists and before RSA or Mojang calls. | | `OAUTHMC_AUTH_BURST` | `3` | `1..=100000` | Per-IP auth token bucket burst size. | | `OAUTHMC_MAX_SESSION_CALLS` | `32` | `1..=10000` | Global cap on concurrent outgoing Mojang `hasJoined` requests. Excess logins are kicked with the `rate_limited` message. | | `OAUTHMC_MAX_API_CONNECTIONS` | `256` | `1..=100000` | Global concurrent HTTP API connection cap. | | `OAUTHMC_API_HEADER_TIMEOUT_SECONDS` | `10` | `1..=120` | HTTP API header read timeout in seconds. | | `OAUTHMC_API_BODY_TIMEOUT_SECONDS` | `10` | `1..=120` | HTTP API request body read timeout in seconds. Exceeding it returns `408 body_timeout`. | ## Appearance and messages | Variable | Default | Format / range | Purpose | | --- | --- | --- | --- | | `OAUTHMC_MOTD` | `OAuth§bMC§7 account verification\n§bJoin to get your code` | Non-empty string | Server list description, up to two lines. `§` formatting codes and `\n` line breaks pass through to the client. | | `OAUTHMC_FAVICON` | Built-in OAuthMC icon | Path to a 64x64 PNG (`<= 64 KiB`) | Server list icon, read and base64-encoded at startup. | | `OAUTHMC_MESSAGES` | *(unset)* | Path to a JSON file | Overrides any subset of the default kick, dialog, and disconnect message templates. | ### Message templates Pass a JSON object file via `OAUTHMC_MESSAGES` to override any subset of the 14 server templates. Unknown keys or empty strings cause startup to fail with exit status `2`. Default templates: ```json { "no_ticket": "No verification is waiting for {name}.\nStart one on the website first.", "code": "Your verification code: {code}\nEnter it on the website (expires in {minutes_left} min).\nNever share this code with anyone.", "unverified": "Could not verify your Minecraft account.\nMake sure your game is running in online mode and try again.", "rate_limited": "Too many verification attempts. Try again in a minute.", "dialog_title": "Verify your Minecraft account", "dialog_code": "Your code: {code}", "link": "Open the verification link in your browser or copy the code above (expires in {minutes_left} min).\nNever share this code or link with anyone.", "open_link": "Open link", "copy_code": "Copy code", "verified": "Your Minecraft account is now verified. You can close the game.", "expired": "Your verification ticket has expired. Start a new one on the website.", "locked": "Too many incorrect verification codes. Start a new verification on the website.", "replaced": "You joined again in another session. Use the newest verification code.", "shutdown": "The verification server is shutting down. Please reconnect." } ``` ### Template keys and placeholders Templates support four placeholders: `{name}`, `{code}`, `{link}`, and `{minutes_left}`. Placeholders that do not apply to a given event expand to an empty string. | Key | Per-ticket override | When shown | Available placeholders | | --- | --- | --- | --- | | `no_ticket` | No | Login Disconnect before encryption when no open ticket matches the username. | `{name}` (`{minutes_left}` is `0`) | | `rate_limited` | No | Login Disconnect when the per-IP auth bucket or `OAUTHMC_MAX_SESSION_CALLS` is exhausted. | `{name}`, `{minutes_left}` | | `unverified` | Yes | Login Disconnect when Mojang `hasJoined` fails, returns `204`, or returns a different username. | `{name}`, `{minutes_left}` | | `code` | Yes | Login Disconnect in code mode, code-kick fallback for link mode, or Configuration Disconnect when `OAUTHMC_LINK_HOLD_SECONDS` expires before ticket TTL. | `{name}`, `{code}`, `{minutes_left}`, `{link}` (on link-mode fallback only) | | `dialog_title` | Yes | Link-mode Configuration dialog title. | `{name}`, `{code}`, `{link}`, `{minutes_left}` | | `dialog_code` | Yes | First body line of the link-mode dialog. | `{name}`, `{code}`, `{link}`, `{minutes_left}` | | `link` | Yes | Second body line of the link-mode dialog. | `{name}`, `{code}`, `{link}`, `{minutes_left}` | | `open_link` | Yes | Label of the `open_url` button in the link-mode dialog. | `{name}`, `{code}`, `{link}`, `{minutes_left}` | | `copy_code` | Yes | Label of the `copy_to_clipboard` button in the link-mode dialog. | `{name}`, `{code}`, `{link}`, `{minutes_left}` | | `verified` | Yes | Configuration Disconnect after the platform redeems the ticket. | `{name}`, `{code}`, `{link}`, `{minutes_left}` | | `expired` | Yes | Configuration Disconnect when the ticket expires or is deleted while held. | `{name}`, `{code}`, `{link}` (`{minutes_left}` is `0`) | | `locked` | Yes | Configuration Disconnect when wrong codes exhaust `max_attempts`. `{code}` and `{link}` are omitted. | `{name}` (`{minutes_left}` is `0`) | | `replaced` | Yes | Configuration Disconnect on an older held session when the player joins again. `{code}` and `{link}` are omitted. | `{name}`, `{minutes_left}` | | `shutdown` | No | Configuration Disconnect sent to held clients when OAuthMC receives `SIGTERM` or `SIGINT`. | `{name}` (`{minutes_left}` is `0`) | Per-ticket overrides in `POST /v1/tickets` are limited to 1–512 bytes per string. When multiple open tickets exist for the same player and all belong to the same tenant, OAuthMC applies the newest ticket's overrides. When open tickets span multiple tenants, OAuthMC ignores per-ticket overrides and falls back to the server templates in code mode. See [Security model](https://docs.sculk.network/nightly/oauthmc/security.md#multi-tenant-mode-and-message-isolation). --- Source: https://docs.sculk.network/nightly/oauthmc/api.md # HTTP API The HTTP API manages short-lived verification tickets and redeems one-time codes issued over the Minecraft port. The machine-readable schema lives in [openapi.yaml](https://docs.sculk.network/nightly/oauthmc/openapi.md). For TypeScript and JavaScript backends, use the [official client SDK](https://docs.sculk.network/nightly/oauthmc/sdk/js.md). ## Authentication and tenancy Every `/v1/*` endpoint requires an `Authorization` header: ```text Authorization: Bearer ``` The `Bearer` scheme is matched case-insensitively per RFC 7235. Configure keys with `OAUTHMC_API_KEYS` (comma-separated, at least 32 characters each). Keys are compared in constant time, and each key defines an isolated tenant: tickets created with key A are visible, redeemable, and deletable only with key A. Any other key receives `404 not_found`. `GET /healthz` requires no authentication. ## Limits and error format - Request bodies are capped at 16 KiB (`413 body_too_large`). - Body reads time out after `OAUTHMC_API_BODY_TIMEOUT_SECONDS` (default `10` s, returning `408 body_timeout`). Unreadable bodies return `400 invalid_body`. - Header reads time out after `OAUTHMC_API_HEADER_TIMEOUT_SECONDS` (default `10` s). Concurrent API connections are capped at `OAUTHMC_MAX_API_CONNECTIONS` (default `256`). - All error responses return `Content-Type: application/json`: ```json { "error": "unauthorized", "message": "missing or invalid bearer token" } ``` Two errors carry an extra field: `attempts_left` on `422 wrong_code` and `status` on `409 not_redeemable`. ## Endpoints ### `POST /v1/tickets` Creates a verification ticket in `pending` state. Request body: ```json { "name": "HatsuneMiku", "mode": "link", "link_url": "https://example.com/account/minecraft/verify#ticket={ticket}&code={code}", "ttl_seconds": 900, "max_attempts": 5, "exclusive": false, "messages": { "code": "Your code: {code} (valid {minutes_left} min)", "unverified": "Could not verify {name}." }, "metadata": { "user_id": "42" } } ``` Only `name` is required. Unknown fields return `400 invalid_json`. | Field | Required | Rules | Default | Cap | | --- | --- | --- | --- | --- | | `name` | Yes | 1–16 ASCII characters matching `[A-Za-z0-9_]` | — | 16 chars | | `mode` | No | `"code"` or `"link"` (any other value, including `"auto"`, returns `422 unsupported_mode`) | `"code"` | — | | `link_url` | When `mode` is `"link"` | Template URL (1–512 bytes) containing both `{ticket}` and `{code}`. Must start with `https://` (`http://` is accepted only when `OAUTHMC_ALLOW_HTTP_LINKS=1`). After substituting both placeholders, the URL must have a valid host (no userinfo `@`) and contain only RFC 3986 URI characters (unreserved, reserved, or `%HH`; `[` and `]` are allowed in the query string only, and at most one `#`). Omitting `link_url` in link mode or sending it in code mode returns `422 invalid_link_url`. | — | 512 bytes | | `ttl_seconds` | No | Whole integer `>= 1` (rejects `0`, negatives, decimals, and scientific notation such as `1e3`) | `OAUTHMC_TICKET_TTL` (`900`) | `OAUTHMC_MAX_TTL` (`3600`) | | `max_attempts` | No | Whole integer `>= 1` | `OAUTHMC_MAX_ATTEMPTS` (`5`) | `OAUTHMC_MAX_ATTEMPTS_CAP` (`10`) | | `exclusive` | No | Boolean. When `true`, returns `409 name_busy` if any open ticket exists for `name` (case-insensitive) across any tenant. | `OAUTHMC_EXCLUSIVE` (`false`) | — | | `messages` | No | Overrides for `code`, `unverified`, `dialog_title`, `dialog_code`, `link`, `open_link`, `copy_code`, `verified`, `expired`, `locked`, `replaced` (1–512 bytes each). Applied only when all open tickets for `name` belong to the same tenant. | Server templates | 512 bytes per key | | `metadata` | No | JSON object or `null`, at most 1024 serialized bytes, echoed on `GET /v1/tickets/{id}`. | `null` | 1024 bytes | Response `201 Created`: ```json { "address": "verify.example.com", "exclusive": false, "expires_at": "2026-11-26T10:32:09Z", "id": "tkt_823fc8dac7451029a38794aef229ea24", "max_attempts": 5, "metadata": null, "mode": "code", "name": "HatsuneMiku", "status": "pending" } ``` `address` equals `OAUTHMC_PUBLIC_ADDRESS`, or `null` when unset. Ticket IDs are `tkt_` followed by 32 lowercase hex characters (128 bits of OS randomness). ### `GET /v1/tickets/{id}` Returns the current ticket status for the calling tenant. Never returns the player's UUID, code, or filled `link_url`. Response `200 OK`: ```json { "attempts_left": 5, "expires_at": "2026-11-26T10:32:09Z", "id": "tkt_823fc8dac7451029a38794aef229ea24", "metadata": null, "mode": "code", "name": "HatsuneMiku", "status": "joined" } ``` Ticket statuses: - `pending`: ticket created; player has not completed online-mode login yet. - `joined`: player completed online-mode login and received a code. - `redeemed`: code redeemed; ticket is consumed. - `expired`: TTL elapsed before redemption. Remains queryable for `OAUTHMC_EXPIRED_GRACE_SECONDS` before sweep. - `locked`: wrong codes exhausted `max_attempts`. Returns `404 not_found` for unknown IDs, malformed IDs, or tickets owned by another tenant. ### `POST /v1/tickets/{id}/redeem` Redeems a one-time code. OAuthMC trims whitespace, ignores `-` characters, and matches ASCII case-insensitively (`N6AN-46TW` and `n6an46tw` are equivalent). Request body: ```json { "code": "N6AN-46TW" } ``` Response `200 OK`: ```json { "name": "HatsuneMiku", "uuid": "a0c4b8c5-a04f-4a6f-9d02-1dea6154a9f6" } ``` `uuid` is lowercase with standard hyphens. `name` is Mojang's canonical username from `hasJoined`. The ticket transitions to `redeemed`, and any held link-mode client disconnects with the `verified` message. Response `422 Unprocessable Entity` (`wrong_code`): ```json { "attempts_left": 4, "error": "wrong_code", "message": "verification code does not match" } ``` Each wrong code decrements `attempts_left`. Reaching `0` transitions the ticket to `locked` and disconnects any held link-mode client with the `locked` message. Response `409 Conflict` (`not_redeemable`): ```json { "error": "not_redeemable", "message": "ticket cannot be redeemed in its current status", "status": "redeemed" } ``` Returned when the ticket is `pending`, `redeemed`, `expired`, or `locked`. ### `DELETE /v1/tickets/{id}` Cancels and removes a ticket owned by the calling tenant. If a link-mode client is held for the ticket, it disconnects with the `expired` message. - `204 No Content`: ticket deleted. - `404 not_found`: unknown ID or ticket owned by another tenant. ### `GET /healthz` Unauthenticated liveness probe. Response `200 OK`: ```json { "ok": true } ``` ## Error codes Every error code returned by `api.rs`: | HTTP status | `error` | Cause | | --- | --- | --- | | `400` | `invalid_body` | Failed to read the request body. | | `400` | `invalid_json` | Malformed JSON, wrong field type, or unknown field. | | `401` | `unauthorized` | Missing or invalid `Authorization: Bearer ` header. | | `404` | `not_found` | Unknown route, invalid ticket ID format, unknown ticket ID, or ticket owned by another tenant. | | `405` | `method_not_allowed` | Unsupported HTTP method on `/v1/tickets`, `/v1/tickets/{id}`, or `/v1/tickets/{id}/redeem`. | | `408` | `body_timeout` | Request body did not finish within `OAUTHMC_API_BODY_TIMEOUT_SECONDS`. | | `409` | `name_busy` | `exclusive: true` requested while an open ticket exists for the same username. | | `409` | `not_redeemable` | Ticket is not in `joined` state. Includes `status`. | | `413` | `body_too_large` | Request body exceeds 16 KiB. | | `422` | `invalid_name` | `name` is not 1–16 characters of `[A-Za-z0-9_]`. | | `422` | `unsupported_mode` | `mode` is not `"code"` or `"link"`. | | `422` | `invalid_link_url` | `link_url` missing in link mode, present in code mode, over 512 bytes, missing placeholders, non-`https://` (unless `OAUTHMC_ALLOW_HTTP_LINKS=1`), invalid host, or non-RFC 3986 characters. | | `422` | `invalid_ttl_seconds` | `ttl_seconds` is not an integer in `1..=OAUTHMC_MAX_TTL`. | | `422` | `invalid_max_attempts` | `max_attempts` is not an integer in `1..=OAUTHMC_MAX_ATTEMPTS_CAP`. | | `422` | `invalid_messages` | A per-ticket message override is empty or exceeds 512 bytes. | | `422` | `invalid_metadata` | `metadata` is not a JSON object (or `null`), or serializes to more than 1024 bytes. | | `422` | `wrong_code` | Submitted code does not match. Includes `attempts_left`. | | `503` | `ticket_limit` | Stored tickets (including expired tickets in grace) reached `OAUTHMC_MAX_TICKETS` or `OAUTHMC_MAX_TICKETS_PER_KEY`. | For configuration variables and message templates, see [Configuration](https://docs.sculk.network/nightly/oauthmc/configuration.md). --- Source: https://docs.sculk.network/nightly/oauthmc/openapi.md # OAuthMC OpenAPI specification ```yaml openapi: 3.1.0 info: title: OAuthMC API version: 0.1.0 description: Ticket lifecycle and code redemption API for OAuthMC (code mode and link mode). license: name: MIT url: https://opensource.org/licenses/MIT servers: - url: http://127.0.0.1:8080 security: - bearerAuth: [] paths: /healthz: get: summary: Liveness probe security: [] responses: "200": description: Service is running content: application/json: schema: type: object required: [ok] properties: ok: type: boolean const: true /v1/tickets: post: summary: Create a verification ticket requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateTicketRequest" responses: "201": description: Ticket created content: application/json: schema: $ref: "#/components/schemas/TicketCreatedResponse" "400": $ref: "#/components/responses/ErrorResponse" "401": $ref: "#/components/responses/ErrorResponse" "408": description: Timed out reading request body content: application/json: schema: $ref: "#/components/schemas/Error" "409": description: Exclusive ticket requested while another open ticket exists for the name content: application/json: schema: $ref: "#/components/schemas/Error" "413": $ref: "#/components/responses/ErrorResponse" "422": $ref: "#/components/responses/ErrorResponse" "503": description: Global or per-key stored ticket limit reached (error code ticket_limit) content: application/json: schema: $ref: "#/components/schemas/Error" /v1/tickets/{id}: parameters: - name: id in: path required: true schema: type: string get: summary: Get ticket status responses: "200": description: Current ticket status (UUID is never returned here) content: application/json: schema: $ref: "#/components/schemas/TicketStatusResponse" "401": $ref: "#/components/responses/ErrorResponse" "404": $ref: "#/components/responses/ErrorResponse" delete: summary: Delete a ticket responses: "204": description: Ticket deleted "401": $ref: "#/components/responses/ErrorResponse" "404": $ref: "#/components/responses/ErrorResponse" /v1/tickets/{id}/redeem: parameters: - name: id in: path required: true schema: type: string post: summary: Redeem a verification code requestBody: required: true content: application/json: schema: type: object required: [code] additionalProperties: false properties: code: type: string description: Case-insensitive 8-character code, with or without dash responses: "200": description: Verification succeeded content: application/json: schema: $ref: "#/components/schemas/RedeemResponse" "400": $ref: "#/components/responses/ErrorResponse" "401": $ref: "#/components/responses/ErrorResponse" "404": $ref: "#/components/responses/ErrorResponse" "408": description: Timed out reading request body content: application/json: schema: $ref: "#/components/schemas/Error" "409": description: Ticket is not in joined state content: application/json: schema: $ref: "#/components/schemas/NotRedeemableError" "413": $ref: "#/components/responses/ErrorResponse" "422": description: Incorrect verification code content: application/json: schema: $ref: "#/components/schemas/WrongCodeError" components: securitySchemes: bearerAuth: type: http scheme: bearer responses: ErrorResponse: description: Error response content: application/json: schema: $ref: "#/components/schemas/Error" schemas: TicketStatus: type: string enum: [pending, joined, redeemed, expired, locked] TicketMessages: type: object additionalProperties: false properties: code: type: string minLength: 1 maxLength: 512 unverified: type: string minLength: 1 maxLength: 512 dialog_title: type: string minLength: 1 maxLength: 512 dialog_code: type: string minLength: 1 maxLength: 512 link: type: string minLength: 1 maxLength: 512 open_link: type: string minLength: 1 maxLength: 512 copy_code: type: string minLength: 1 maxLength: 512 verified: type: string minLength: 1 maxLength: 512 expired: type: string minLength: 1 maxLength: 512 locked: type: string minLength: 1 maxLength: 512 replaced: type: string minLength: 1 maxLength: 512 CreateTicketRequest: type: object required: [name] additionalProperties: false properties: name: type: string pattern: "^[A-Za-z0-9_]{1,16}$" mode: type: string enum: [code, link] default: code link_url: type: string minLength: 1 maxLength: 512 description: Required when mode is "link" and forbidden otherwise. Template URL starting with https:// (or http:// when OAUTHMC_ALLOW_HTTP_LINKS=1) containing both {ticket} and {code}; after substituting both placeholders, the result must have a valid host and contain only RFC 3986 URI characters (unreserved, reserved, or %HH). ttl_seconds: type: integer minimum: 1 max_attempts: type: integer minimum: 1 exclusive: type: boolean messages: $ref: "#/components/schemas/TicketMessages" metadata: type: object additionalProperties: true description: Opaque JSON object, at most 1024 serialized bytes TicketCreatedResponse: type: object required: [id, name, address, mode, status, expires_at, max_attempts, exclusive, metadata] properties: id: type: string name: type: string address: type: [string, "null"] mode: type: string enum: [code, link] status: $ref: "#/components/schemas/TicketStatus" expires_at: type: string format: date-time max_attempts: type: integer exclusive: type: boolean metadata: type: [object, "null"] TicketStatusResponse: type: object required: [id, name, mode, status, expires_at, attempts_left, metadata] properties: id: type: string name: type: string mode: type: string enum: [code, link] status: $ref: "#/components/schemas/TicketStatus" expires_at: type: string format: date-time attempts_left: type: integer metadata: type: [object, "null"] RedeemResponse: type: object required: [uuid, name] properties: uuid: type: string format: uuid name: type: string Error: type: object required: [error, message] properties: error: type: string message: type: string WrongCodeError: allOf: - $ref: "#/components/schemas/Error" - type: object required: [attempts_left] properties: attempts_left: type: integer NotRedeemableError: allOf: - $ref: "#/components/schemas/Error" - type: object required: [status] properties: status: $ref: "#/components/schemas/TicketStatus" ``` --- Source: https://docs.sculk.network/nightly/oauthmc/sdk/js.md # oauthmc Zero-dependency TypeScript client for the [OAuthMC](https://github.com/YellowUmbrellaDev/sculk.network/blob/main/crates/oauthmc/README.md) HTTP API. > [!CAUTION] > **Server-side only.** Never bundle this package into browser code or expose your `OAUTHMC_API_KEYS` bearer token to a client. Anyone with the API key can create, inspect, redeem, and delete tickets for your tenant. Keep OAuthMC on a private network (loopback or internal container network) and call it exclusively from your backend. ## Install `oauthmc` is not published on npm yet. Once published, install it with: ```sh npm install oauthmc ``` Until the first release, build and pack a tarball from a checkout of this repository and install the generated `.tgz` file: ```sh # From the repository root (pnpm workspace) pnpm --filter oauthmc pack # Or directly inside crates/oauthmc/sdk/js npm pack ``` Then install the resulting tarball in your project: ```sh npm install /path/to/oauthmc-0.1.0.tgz ``` ## Quick start (code mode) ```ts import { OAuthMC, OAuthMCError, isValidMinecraftName } from 'oauthmc'; const client = new OAuthMC({ baseUrl: process.env.OAUTHMC_URL ?? 'http://oauthmc:8080', apiKey: process.env.OAUTHMC_API_KEY!, // Optional: custom fetch implementation (defaults to globalThis.fetch) // Optional: request timeout in milliseconds (default 10_000) timeoutMs: 10_000, }); // 1. Validate input (optional helper; the server always validates) and create a ticket. if (!isValidMinecraftName(playerName)) { throw new Error('Invalid Minecraft username'); } const ticket = await client.createTicket({ name: playerName, metadata: { userId: currentUser.id }, }); // Store ticket.id in the user's server-side session. // Show ticket.address and ticket.expiresAt to the user so they can join in Minecraft. console.log(`Join ${ticket.address} before ${ticket.expiresAt.toISOString()}`); // 2. (Optional) Poll ticket status while waiting for the player to join. // getTicket() returns null on 404 and never returns the player's UUID. const state = await client.getTicket(ticket.id); if (state?.status === 'joined') { console.log(`Player joined; ${state.attemptsLeft} attempts left`); } // 3. When the user submits the code shown on the Minecraft kick screen, redeem it on the server. const result = await client.redeem(ticket.id, submittedCode); if (result.ok) { // Always trust and persist result.uuid and result.name returned by redeem(). // Never accept a UUID supplied by the browser or client request. await linkMinecraftAccount(currentUser.id, result.uuid, result.name); } else if (result.reason === 'wrong_code') { // Normal outcome (HTTP 422 wrong_code): prompt the user to retry. console.log(`Wrong code, ${result.attemptsLeft} attempts left`); } else if (result.reason === 'not_redeemable') { // Normal outcome (HTTP 409 not_redeemable): status is pending, redeemed, expired, or locked. console.log(`Ticket cannot be redeemed (status: ${result.status})`); } else { // result.reason === 'not_found' (HTTP 404) console.log('Ticket not found'); } // 4. Cancel/clean up a ticket if needed. Returns true when deleted, false on 404 (idempotent). await client.deleteTicket(ticket.id); ``` ## API ### `new OAuthMC(options)` | Option | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `baseUrl` | `string` | yes | — | Base URL of the OAuthMC HTTP API (trailing slash optional) | | `apiKey` | `string` | yes | — | Tenant bearer token from `OAUTHMC_API_KEYS` | | `fetch` | `typeof fetch` | no | `globalThis.fetch` | Custom Fetch API implementation | | `timeoutMs` | `number` | no | `10_000` | Per-request timeout via `AbortSignal.timeout` | ### Methods - `createTicket(options): Promise` — Creates a verification ticket (`POST /v1/tickets`). Only `name` is required. Unset optional fields are omitted from the request body so server defaults apply. - `getTicket(id): Promise` — Fetches ticket status (`GET /v1/tickets/{id}`). Returns `null` on `404`. Never includes a UUID. - `redeem(id, code): Promise` — Redeems a one-time verification code (`POST /v1/tickets/{id}/redeem`). Returns a discriminated union for normal outcomes (`ok: true`, `wrong_code`, `not_redeemable`, `not_found`). - `deleteTicket(id): Promise` — Deletes a ticket (`DELETE /v1/tickets/{id}`). Returns `true` on `204` and `false` on `404` so retries converge. - `health(): Promise` — Probes `GET /healthz` without authentication. Returns `true` only on HTTP `200` with `{"ok": true}`, `false` otherwise. ### Per-ticket options `createTicket` accepts: - `name` (`string`, required): 1–16 characters matching `[A-Za-z0-9_]`. - `mode` (`'code' | 'link' | 'auto'`, optional): Verification mode (server defaults to `'code'` and decides which modes it accepts). - `linkUrl` (`string`, optional): Required when `mode` is `'link'`; template URL mapped to `link_url` containing `{ticket}` and `{code}`. - `ttlSeconds` (`number`, optional): Ticket lifetime in seconds. - `maxAttempts` (`number`, optional): Maximum redeem attempts before locking. - `exclusive` (`boolean`, optional): Reject with `409 name_busy` when another open ticket exists for the same username. - `messages` (`TicketMessages`, optional): Per-ticket kick/dialog/disconnect message template overrides (`code`, `unverified`, `dialogTitle`, `dialogCode`, `link`, `openLink`, `copyCode`, `verified`, `expired`, `locked`, `replaced`). - `metadata` (`Record`, optional): Opaque JSON object echoed on `getTicket`. See [docs/api.md](https://github.com/YellowUmbrellaDev/sculk.network/blob/main/crates/oauthmc/docs/api.md#post-v1tickets) for the server's defaults, caps, validation rules, and multi-tenant message isolation rules. ### Helper - `isValidMinecraftName(name: string): boolean` — Checks whether `name` matches `^[A-Za-z0-9_]{1,16}$`. Exported as a convenience helper; the SDK does not block requests client-side. ## Error handling Expected redemption outcomes (`wrong_code`, `not_redeemable`, `not_found`) are returned as a discriminated union from `redeem()` instead of throwing: ```ts type RedeemResult = | { ok: true; uuid: string; name: string } | { ok: false; reason: 'wrong_code'; attemptsLeft: number } | { ok: false; reason: 'not_redeemable'; status: TicketStatus } | { ok: false; reason: 'not_found' }; ``` Unexpected API errors (`401 unauthorized`, `409 name_busy`, `422` validation errors, `503 ticket_limit`, `5xx`), malformed or incomplete responses (`invalid_response`), timeouts (`timeout`), and network errors (`network`) throw `OAuthMCError`: ```ts try { await client.createTicket({ name: playerName, exclusive: true }); } catch (err) { if (err instanceof OAuthMCError) { // err.status: HTTP status code, or null for network/timeout errors // err.code: server error code (e.g. 'name_busy', 'ticket_limit') or 'network' | 'timeout' | 'invalid_response' // err.message: human-readable message (API key is never included in message or cause) if (err.code === 'name_busy') { // Another verification is already in progress for this player. } } throw err; } ``` ## Runtime support Built strictly on standard Web APIs (`fetch`, `AbortSignal.timeout`, `URL`, `JSON`) with zero runtime dependencies. - Node.js 18+ (Node.js 22.18+ can import `src/index.ts` directly via native type stripping) - Deno - Bun - Cloudflare Workers ## License [MIT](https://github.com/YellowUmbrellaDev/sculk.network/blob/main/crates/oauthmc/sdk/js/LICENSE) --- Source: https://docs.sculk.network/nightly/oauthmc/deploy.md # Deploying OAuthMC OAuthMC compiles to a static Linux musl binary inside a non-root `gcr.io/distroless/static-debian12:nonroot` container image. It needs no database or persistent volume: tickets live in memory and expire after a few minutes. ## Container image The GHCR image (`ghcr.io/yellowumbrelladev/oauthmc`) is not published yet; it ships with the first stable release. Until then, build the image locally from `crates/oauthmc`: ```sh docker build -t oauthmc crates/oauthmc ``` ```text => => naming to docker.io/library/oauthmc:latest ``` Once published, replace `build: ./crates/oauthmc` / `image: oauthmc` in the examples below with `ghcr.io/yellowumbrelladev/oauthmc:` (pin a version tag such as `0.1.0`, not `:latest`). ## Docker Compose Publish the Minecraft port (`25565`) publicly and keep the HTTP API (`8080`) on an internal network reachable only by your platform backend: ```yaml services: oauthmc: image: oauthmc build: ./crates/oauthmc restart: unless-stopped ports: - "25565:25565" environment: OAUTHMC_API_KEYS: "${OAUTHMC_API_KEY}" OAUTHMC_PUBLIC_ADDRESS: "verify.example.com" networks: - internal networks: internal: driver: bridge ``` Inside the Docker image, `OAUTHMC_API_ADDR` defaults to `0.0.0.0:8080` so sibling containers on `internal` can reach `http://oauthmc:8080`, while port `8080` is never published on the host. Start the service and inspect its log: ```sh docker compose up -d oauthmc docker compose logs oauthmc ``` ```text level=info event=listening mc_addr=0.0.0.0:25565 api_addr=0.0.0.0:8080 ``` ## Non-default port with a DNS SRV record If a Minecraft game server already uses port `25565` on the host, publish OAuthMC on another port (for example `25566`) and add a DNS `SRV` record so players still connect to `verify.example.com` without typing a port: ```text _minecraft._tcp.verify.example.com. 300 IN SRV 0 5 25566 verify-host.example.com. ``` Set `OAUTHMC_PUBLIC_ADDRESS=verify.example.com`. Minecraft Java Edition resolves `_minecraft._tcp.` automatically. ## Running behind a TCP proxy OAuthMC enforces per-IP concurrency (`OAUTHMC_MAX_CONNECTIONS_PER_IP`, default `16`), per-IP held link sessions (`OAUTHMC_MAX_HELD_PER_IP`, default `2`), and the per-IP auth rate limit (`OAUTHMC_AUTH_RATE_PER_MINUTE`, `OAUTHMC_AUTH_BURST`) using the TCP peer address returned by `accept()`. OAuthMC does not parse PROXY protocol headers. If you run it behind a SNATing L4 proxy or load balancer (such as HAProxy, Nginx stream, or a cloud TCP load balancer), every connection arrives from the proxy's IP address instead of the player's IP address. When running behind a SNATing proxy: - Raise `OAUTHMC_MAX_CONNECTIONS_PER_IP`, `OAUTHMC_MAX_HELD_PER_IP`, `OAUTHMC_AUTH_RATE_PER_MINUTE`, and `OAUTHMC_AUTH_BURST` so legitimate players do not trip the shared per-IP caps. - Enforce per-client connection and rate limits at the proxy layer. ## Health checks The container image defines a built-in `HEALTHCHECK` that runs every 30 seconds: ```sh /oauthmc healthcheck ``` The `healthcheck` subcommand reads `OAUTHMC_API_ADDR` (rewriting `0.0.0.0` to `127.0.0.1` and `::` to `::1`), sends `GET http:///healthz` with a 3-second timeout, and exits `0` on HTTP `200` or `1` otherwise. Verify it on a running container: ```sh docker exec oauthmc /oauthmc healthcheck && echo "healthy" ``` ```text healthy ``` External orchestrators on the internal network can also probe `GET /healthz` directly without an API key: ```sh curl -sS http://127.0.0.1:8080/healthz ``` ```json {"ok":true} ``` ## Upgrades OAuthMC keeps no state on disk. Upgrading replaces the container image and restarts the process: 1. Rebuild the image (or pull the new version tag once published on GHCR): ```sh docker compose build oauthmc ``` 2. Recreate the container: ```sh docker compose up -d oauthmc ``` 3. Verify the container is listening and healthy: ```sh docker compose exec oauthmc /oauthmc healthcheck && echo "healthy" ``` ```text healthy ``` Because tickets live in memory, any open ticket is dropped during the restart. Players whose ticket disappears receive `404 not_found` on the platform and start a fresh verification. ## Graceful shutdown OAuthMC listens for `SIGTERM` and `SIGINT`. On receiving either signal, it: 1. Logs `level=info event=shutdown`. 2. Stops accepting new Minecraft and HTTP API connections and stops the ticket-expiry sweep loop. 3. Sends Configuration Disconnect (`0x02`) with the `shutdown` template to held link-mode clients. 4. Exits with status `0`. --- Source: https://docs.sculk.network/nightly/oauthmc/security.md # Security model This document explains the threats OAuthMC defends against, the responsibilities of the calling platform, and the trade-offs baked into the protocol. ## Why join alone never verifies an account Joining a Minecraft server in online mode proves which Mojang account connected. It does not prove which account on the platform started the verification. Because anyone can open a ticket for any Minecraft username, OAuthMC never marks a player verified on join alone. A naive "auto-verify on join" design fails in three ways: 1. **Ticket hijacking**: an attacker opens a ticket for victim `V` and waits until `V` joins to verify their own account. Both open tickets observe `V`'s join. 2. **Phishing**: even with `exclusive: true` or per-ticket hostnames, an attacker can trick `V` into joining a server address ("join `verify.example.com` for an event"). Joining a server does not look like handing over a credential. 3. **Username squatting**: with `exclusive: true`, an attacker can keep opening tickets for `V` to block `V` from verifying their own account. In both code mode and link mode, OAuthMC generates an 8-character secret (`XXXX-XXXX`, drawn from an unambiguous 30-character alphabet, ~39.2 bits of entropy) using rejection sampling over OS randomness. OAuthMC sends the secret over the AES-128-CFB8 encrypted Minecraft connection after Mojang `hasJoined` succeeds. Only the player who owns the Minecraft account receives it, and verification completes only when the platform redeems that code through `POST /v1/tickets/{id}/redeem`. - `exclusive` defaults to `false` so attackers cannot block other players from starting verification. - On join, OAuthMC hashes the fresh code with SHA-256 and stores the hash on every open ticket for that username (only when Mojang's canonical username matches the login username ASCII case-insensitively). Rejoining replaces the hash without resetting `attempts`. - `GET /v1/tickets/{id}` never returns the Mojang UUID, the code, or a filled `link_url`. The UUID is returned once, on a successful redeem. - Redeeming consumes the ticket (`status: "redeemed"`). Wrong codes decrement `attempts_left` and lock the ticket at `0`. ## Link mode requires session binding on the platform In link mode, OAuthMC substitutes `{ticket}` and `{code}` into `link_url` and displays an **Open link** button in Minecraft's Configuration dialog. When the player clicks it, Minecraft shows its built-in confirmation prompt and opens the URL in the player's browser. **Link mode is safe only if the platform enforces all three rules on the verification page:** 1. **Check session ownership before redeeming.** Verify that the authenticated browser session belongs to the user who created `{ticket}`. If an attacker `A` creates a link-mode ticket for victim `V` and tricks `V` into joining and clicking **Open link**, `V`'s browser carries `V`'s session (or no session), not `A`'s. Reject the request and never call `/redeem` on `A`'s ticket. 2. **Never redeem on `GET`.** Render a confirmation page that shows which Minecraft username is being linked to which platform account, and redeem only on an explicit `POST` action protected by the platform's normal session and CSRF checks. 3. **Keep `{ticket}` and `{code}` out of server logs and `Referer` headers.** Put both placeholders in the URL fragment (`https://example.com/verify#ticket={ticket}&code={code}`), strip the fragment with `history.replaceState` after reading it in JavaScript, and send `Referrer-Policy: no-referrer` on the page. Always use `https://` in production (`OAUTHMC_ALLOW_HTTP_LINKS` defaults to `false`). See [Integrating OAuthMC](https://docs.sculk.network/nightly/oauthmc/integrating.md#building-the-link-mode-confirmation-page) for the full pattern. ## Multi-tenant mode and message isolation Each key in `OAUTHMC_API_KEYS` is an isolated tenant. API reads, redeems, and deletes are strictly scoped to the owning key. On the Minecraft port, a username may have open tickets from more than one tenant at the same time. OAuthMC applies link mode and per-ticket `messages` overrides only when **every** open ticket for the joining username belongs to the same tenant (and, for link mode, the newest open ticket uses link mode). If two tenants both have open tickets for the same username, OAuthMC ignores per-ticket overrides and forces **code mode with server templates**. One tenant cannot inject clickable URLs or phishing text into another tenant's verification flow, while every tenant's open ticket can still redeem the code. ## Pre-encryption rejection trade-off When a client sends Login Start for a username with no open ticket, OAuthMC sends Login Disconnect immediately before Encryption Request. - **Benefit**: port scanners and unsolicited connections cost zero RSA decryptions and zero Mojang `hasJoined` requests. - **Trade-off**: anyone can probe whether a specific Minecraft username has an open ticket right now. If your platform treats an in-flight verification attempt as sensitive, account for this disclosure in your own ticket-creation rate limits and UX. ## Rate limiting and why there is no per-name limit After confirming an open ticket exists and before sending Encryption Request, OAuthMC checks a per-IP token bucket (`OAUTHMC_AUTH_RATE_PER_MINUTE`, default `6`; `OAUTHMC_AUTH_BURST`, default `3`). IPv4 peers are bucketed by `/32` and IPv6 peers by `/64`, with IPv4-mapped IPv6 addresses (`::ffff:a.b.c.d`) folded back to IPv4 `/32`. Requests over the limit are kicked before encryption with the `rate_limited` message. Outgoing Mojang `hasJoined` calls are also capped globally (`OAUTHMC_MAX_SESSION_CALLS`, default `32`). Excess logins are kicked with `rate_limited`. OAuthMC does not enforce a per-username login rate limit. A per-name limit would let an unauthenticated attacker flood Login Start packets for a victim's username and block the victim from verifying. Bounding abuse per source IP bucket and capping global `hasJoined` concurrency protects CPU and Mojang quota without creating a per-player denial-of-service vector. ## Cryptography and protocol hardening - **RSA-1024 PKCS#1 v1.5**: generated fresh at startup from OS randomness (`getrandom`). OAuthMC pins `rsa = 0.10.0`, which uses constant-time implicit rejection for PKCS#1 v1.5 decryption (mitigating Marvin / RUSTSEC-2023-0071). Any decryption or framing error closes the connection identically with no error oracle and zero Mojang calls. - **Verify token**: 4 random bytes per Encryption Request, compared in constant time on Encryption Response. - **Minecraft 1.19 and 1.19.2 (`hasToken = false`)**: protocols `759` and `760` allow clients with a Mojang profile public key to send a salt and signature instead of the encrypted verify token. OAuthMC accepts `hasToken = false` without verifying the signature. This remains safe because: 1. The decrypted 16-byte shared secret is hashed with the server's RSA public key into Mojang's `hasJoined` `serverId`, so only a client holding the account's Mojang session token makes `hasJoined` return `200`. 2. The code is sent in the encrypted Login Disconnect packet under that shared secret, so replaying an encrypted secret only produces ciphertext an attacker cannot decrypt. - **Mojang `hasJoined` over TLS**: uses `rustls` with `ring` and embedded `webpki-roots` (no host CA bundle needed in `distroless/static`). Responses are capped at 64 KiB with a 5-second default timeout and zero redirects. Mojang's returned canonical username must match the login username (ASCII case-insensitively), or OAuthMC kicks with `unverified` and mutates no ticket. Plain `http://` is used only when `OAUTHMC_SESSION_URL` is explicitly overridden for local tests. - **No secrets in logs**: OAuthMC never logs verification codes, filled verification links, API keys, RSA private keys, or shared secrets. ## API and resource protection - Bearer keys must be at least 32 characters and are checked across every configured key in constant time. - HTTP request bodies are capped at 16 KiB (`413 body_too_large`), `metadata` at 1024 bytes, and `link_url` at 512 bytes. `link_url` is validated after substituting `{ticket}` and `{code}` to enforce `https://` (unless `OAUTHMC_ALLOW_HTTP_LINKS=1`), a valid host without userinfo, and RFC 3986 URI characters only. - HTTP connections enforce header timeout (`OAUTHMC_API_HEADER_TIMEOUT_SECONDS`, default `10` s), body timeout (`OAUTHMC_API_BODY_TIMEOUT_SECONDS`, default `10` s), and concurrency cap (`OAUTHMC_MAX_API_CONNECTIONS`, default `256`) to mitigate slowloris attacks. - Ticket storage is capped globally (`OAUTHMC_MAX_TICKETS`, default `10000`) and per key (`OAUTHMC_MAX_TICKETS_PER_KEY`, default `1000`), counting expired tickets still inside their grace period. At capacity, `POST /v1/tickets` returns `503 ticket_limit`. - Minecraft connections enforce `OAUTHMC_MAX_PACKET_LEN` (`4096` bytes during Handshake/Login; Configuration streams and discards non-Keep-Alive packets up to 1 MiB without buffering), `OAUTHMC_MAX_HANDSHAKE_ADDR_LEN` (`255` bytes), `OAUTHMC_LOGIN_TIMEOUT_SECONDS` (`10` s), `OAUTHMC_MAX_CONNECTIONS` (`256`), and `OAUTHMC_MAX_CONNECTIONS_PER_IP` (`16`). - **Held link-mode DoS controls**: held sessions stay open for up to `OAUTHMC_LINK_HOLD_SECONDS` (default `600` s, capped by ticket TTL). Four controls keep them from starving code-mode logins or status pings: 1. `OAUTHMC_MAX_HELD` defaults to half of `OAUTHMC_MAX_CONNECTIONS` (`128`), and startup rejects any value `>= OAUTHMC_MAX_CONNECTIONS`. Excess link-mode joins fall back to a code-mode disconnect. 2. `OAUTHMC_MAX_HELD_PER_IP` (default `2` per `/32` or `/64`) caps held connections per IP bucket and falls back to code mode above the cap. 3. At most one held connection is kept per ticket. Rejoining disconnects the older held connection immediately with `replaced` (omitting `{code}` and `{link}`). 4. Redeeming (`verified`), locking (`locked`, omitting `{code}` and `{link}`), expiring or deleting (`expired`), or missing a Configuration Keep Alive for 30 seconds disconnects immediately and releases all slots. Always bind `OAUTHMC_API_ADDR` to loopback or a private container network. Never expose the HTTP API to the public internet. --- Source: https://docs.sculk.network/nightly/oauthmc/protocol.md # Minecraft protocol OAuthMC implements the Handshake, Status, Login, and (for link mode on 1.21.6+) Configuration states of the Minecraft Java Edition TCP protocol. It never enters the Play state, so world, chunk, entity, and registry changes across Minecraft releases do not affect it. ## Tested client matrix `tests/clients/run-matrix.mjs` verifies every release against real `node-minecraft-protocol` clients in online mode: | Minecraft version | Protocol version | Code mode | Link mode (dialog) | Notes | | --- | --- | --- | --- | --- | | 1.8.9 | 47 | Tested | Fallback (code kick) | Classic login layout | | 1.12.2 | 340 | Tested | Fallback (code kick) | Classic login layout | | 1.16.5 | 754 | Tested | Fallback (code kick) | Classic login layout | | 1.19 | 759 | Tested | Fallback (code kick) | Encryption Response includes `hasToken` boolean | | 1.19.2 | 760 | Tested | Fallback (code kick) | Encryption Response includes `hasToken` boolean | | 1.20.1 | 763 | Tested | Fallback (code kick) | Login Start includes optional UUID | | 1.21.1 | 767 | Tested | Fallback (code kick) | Encryption Request includes `shouldAuthenticate` boolean | | 1.21.6 | 771 | Fallback/code | Tested | First version with Configuration `Show Dialog` (`0x12`) | | 1.21.8 | 772 | Fallback/code | Tested | Configuration `Show Dialog` (`0x12`) | | 1.21.11 | 774 | Fallback/code | Tested | Configuration `Show Dialog` (`0x12`) | | 26.1 | 775 | Tested | Tested | Latest version tested by `node-minecraft-protocol` (`Show Dialog` `0x12`) | Protocol `776` (26.2, trailing 16-byte Session ID in Login Success) and protocol `777` (26.3, `Show Dialog` shifted to `0x13`) are implemented from the protocol spec and verified in `tests/integration.rs`, not in `run-matrix.mjs`. ## Why link mode uses a Configuration dialog Minecraft's `DisconnectedScreen` renders kick reasons in a non-clickable `MultiLineTextWidget`. `open_url` click events inside a Login Disconnect or Configuration Disconnect text component cannot be clicked. Starting in Minecraft 1.21.6 (protocol `771`), the client supports the Dialog system and the clientbound **Show Dialog (configuration)** packet during the Configuration state, without entering a world. Dialog action buttons natively support `open_url` (with Minecraft's confirmation prompt before launching the browser) and `copy_to_clipboard`. - **Protocol >= 771 (1.21.6+)**: OAuthMC sends `Login Success` (`0x02`), waits for `Login Acknowledged` (`0x03`), and sends `Show Dialog (configuration)` with an inline `minecraft:multi_action` dialog containing **Open link** (`open_url`) and **Copy code** (`copy_to_clipboard`), `columns: 2`, `can_close_with_escape: false` (so Escape cannot dismiss the dialog with no way back), `pause: false` (required by the vanilla dialog codec when `after_action` is `"none"`), and `after_action: "none"`. - **Protocol < 771**: OAuthMC falls back to the encrypted Login Disconnect code kick. The ticket still works by code, and the `code` template may include `{link}` (though older clients cannot click it). - **Held-connection limits or mixed tenants**: if `OAUTHMC_MAX_HELD` or `OAUTHMC_MAX_HELD_PER_IP` is full, or if open tickets for that username span multiple tenants, OAuthMC falls back to the Login Disconnect code kick. - **Rejoining on a held ticket**: at most one held connection is kept per ticket. When a player rejoins, OAuthMC signals the older held connection to disconnect with `replaced` and waits up to 2 seconds for its held slot to release so rejoins succeed even when `OAUTHMC_MAX_HELD=1` or `OAUTHMC_MAX_HELD_PER_IP=1`. ## Handshake and Status - **Legacy `0xFE` Server List Ping**: connections starting with byte `0xFE` are closed immediately. - **Status (intent `1`)**: OAuthMC echoes the client's protocol number so the server list never shows a version mismatch badge, reports `0/0` players, returns `OAUTHMC_MOTD` and the 64x64 PNG icon (`OAUTHMC_FAVICON`, or the built-in OAuthMC icon), and echoes the 8-byte Ping Request payload (`0x01`). - **Login (intent `2`) and Transfer (intent `3`)**: both enter the Login state. ## Login state quirks across versions - **Login Start (`0x00`)**: trailing fields after the username changed across versions (optional profile public key in 1.19, optional UUID in 1.19.3, required UUID in 1.20.2). OAuthMC reads only the leading username string (capped at 64 bytes) and ignores trailing payload bytes. - **Encryption Request (`0x01`)**: - Server ID is always the empty string `""`. - Public key is DER-encoded X.509 `SubjectPublicKeyInfo` for the runtime RSA-1024 key. - Verify token is 4 fresh random bytes per connection. - Starting at protocol `766` (1.20.5+), a trailing `shouldAuthenticate` boolean (`0x01`) is appended. - **Encryption Response (`0x01`)**: - For protocols `759` (1.19) and `760` (1.19.1/1.19.2), a boolean `hasToken` precedes the verify token. When `hasToken` is `0`, the client sent a salt and signature instead of the encrypted token; OAuthMC accepts this (see [Security model](https://docs.sculk.network/nightly/oauthmc/security.md#cryptography-and-protocol-hardening)). - For all other versions, the encrypted verify token is decrypted and compared in constant time. - The decrypted shared secret must be 16 bytes and initializes AES-128-CFB8 in both directions (`IV = key`). - **Server hash**: Minecraft's signed hex SHA-1 digest of `"" || shared_secret || public_key_der` (two's complement with `-` prefix when MSB is set, leading zeroes stripped). - **Login Disconnect (`0x00`)**: always encoded as a JSON text component `{"text": "..."}`, which remains valid in the Login state across all supported versions (including 1.20.3+ and 26.x). - **Login Success (`0x02`)** (link mode, protocol `>= 771`): encrypted 16-byte UUID, username string, and VarInt-prefixed properties array forwarded from Mojang's `hasJoined` response. Starting at protocol `776` (26.2+), a trailing 16-byte random Session ID is appended. - **Login Acknowledged (`0x03`, serverbound)**: empty payload sent by the client to enter the Configuration state. ## Configuration state (link mode) Text components and inline dialogs in Configuration packets use the 1.20.2+ nameless (network) NBT format: no root name bytes after the root tag byte (`0x08` + big-endian `u16` length + modified UTF-8 for plain text components; `0x0A` + entries + `0x00` for compounds). Every NBT string uses Java modified UTF-8 (`DataInput.readUTF` / `DataOutput.writeUTF`: `U+0000` as `C0 80`, supplementary characters as a 6-byte UTF-16 surrogate pair) and truncates cleanly before `u16::MAX` bytes without splitting a surrogate pair. | Packet | Direction | Packet ID | Notes | | --- | --- | --- | --- | | Disconnect (configuration) | Clientbound | `0x02` | Nameless NBT `TAG_String` (`verified`, `expired`, `locked`, `replaced`, `shutdown`, or `code` when `OAUTHMC_LINK_HOLD_SECONDS` expires before ticket TTL). | | Keep Alive (configuration) | Clientbound / Serverbound | `0x04` / `0x04` | Big-endian `i64`; sent every 12 seconds, connection dropped if unanswered after 30 seconds. | | Show Dialog (configuration) | Clientbound | `0x12` (`771..=776`), `0x13` (`>= 777`) | Nameless NBT `TAG_Compound` inline `minecraft:multi_action` dialog. Shifted by `+1` in 26.3 (`777`) after `Post Effects` was inserted at `0x0A`. | While held in Configuration, a dedicated reader task accepts serverbound packets up to 1 MiB (keeping `OAUTHMC_MAX_PACKET_LEN` for Handshake and Login) so modded clients (Fabric, NeoForge) sending large channel-registration plugin messages are not dropped. Every serverbound packet except Keep Alive is streamed and discarded in 4 KiB chunks without buffering the full payload. When the ticket transitions (redeemed, locked, deleted, or superseded by a newer join) or the server shuts down, a `tokio::sync::watch` or `Notify` signal wakes the hold loop immediately and sends Configuration Disconnect (`0x02`). --- Source: https://docs.sculk.network/nightly/oauthmc/contributing.md # Contributing to OAuthMC OAuthMC is a standalone Rust crate with a zero-dependency TypeScript SDK (`sdk/js`) and a `node-minecraft-protocol` client test matrix (`tests/clients`). ## Toolchain and prerequisites - Rust toolchain pinned in [rust-toolchain.toml](https://github.com/YellowUmbrellaDev/sculk.network/blob/26cfdac/crates/oauthmc/rust-toolchain.toml) (`1.100.0`, with `rustfmt` and `clippy`) - Node.js 22.18 or later (for the client matrix and TypeScript SDK tests) - `musl-tools` and the `x86_64-unknown-linux-musl` Rust target (only for static release builds outside Docker) - Docker (only for testing the container build) ## Build from source Run all commands from `crates/oauthmc`: ```sh cargo build --locked ``` For an optimized release binary: ```sh cargo build --release --locked ``` For a static Linux musl binary (matching CI and the Dockerfile): ```sh rustup target add x86_64-unknown-linux-musl CC_x86_64_unknown_linux_musl=musl-gcc cargo build --release --locked --target x86_64-unknown-linux-musl ``` ## Checks and tests ### Format, lint, and Rust tests Run the same Rust checks CI executes: ```sh cargo fmt --check cargo clippy --all-targets -- -D warnings cargo test --locked ``` `cargo test --locked` runs the unit tests (`src/`) and integration tests (`tests/integration.rs`): ```text test result: ok. 19 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out ... test result: ok. 20 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out ``` ### Minecraft client matrix The client matrix in `tests/clients/run-matrix.mjs` starts a mock Mojang session server (`tests/clients/mock-session.mjs`) and an OAuthMC binary, then connects real `node-minecraft-protocol` clients in online mode across: - **Code mode**: `1.8.9`, `1.12.2`, `1.16.5`, `1.19`, `1.19.2`, `1.20.1`, `1.21.1`, `26.1` - **Link mode**: `1.21.6`, `1.21.8`, `1.21.11`, `26.1` Install the client dependencies once and run the matrix against your built binary: ```sh npm --prefix tests/clients ci --no-audit --no-fund OAUTHMC_BIN="$PWD/target/release/oauthmc" node tests/clients/run-matrix.mjs ``` Each version prints one `OK` line with the generated code, verified UUID, and username (using the mock session server's fixture player): ```text [] OK code= uuid= name= ... [ link] OK code= uuid= name= verified=true ``` ### TypeScript SDK tests From the repository root: ```sh pnpm --filter oauthmc typecheck pnpm --filter oauthmc test ``` ## Container smoke test Build the Docker image and run the built-in health check: ```sh docker build -t oauthmc . docker run -d --name oauthmc-smoke \ -e OAUTHMC_API_KEYS="smoke-test-key-0123456789abcdef0123" \ oauthmc docker exec oauthmc-smoke /oauthmc healthcheck docker rm -f oauthmc-smoke ``` ## Releases OAuthMC is released from this monorepo with its own version and tags (`oauthmc-v0.3.0`), by the same `release` workflow as sculk.network. [The release guide](https://docs.sculk.network/nightly/sculk/releases.md) has the model and the steps. In short: - Every night, if anything under `src/`, `Cargo.toml`, `Cargo.lock`, `rust-toolchain.toml` or `Dockerfile` changed and `ci-ok` passed on `main`, the workflow publishes `oauthmc-vX.Y.0-nightly..` and the image tags `:X.Y.0-nightly..` and `:nightly`. - A maintainer promotes the latest nightly to a stable release with `gh workflow run release --ref main -f channel=stable -f product=oauthmc`. It publishes `:X.Y.0`, `:X.Y` and `:latest`. - The version lives in the tag and the image's `org.opencontainers.image.version` label. Leave `Cargo.toml` at `0.1.0`, and do not keep a changelog: the GitHub Release notes list the commits that touched OAuthMC. ## Documentation Keep the Markdown under `docs/` and the root `README.md` in sync with the source code: - Environment variables and default message templates live in `src/config.rs` and are documented in [docs/configuration.md](https://docs.sculk.network/nightly/oauthmc/configuration.md). - HTTP endpoints, status codes, and error codes live in `src/api.rs` and are documented in [docs/api.md](https://docs.sculk.network/nightly/oauthmc/api.md) and [docs/openapi.yaml](https://docs.sculk.network/nightly/oauthmc/openapi.md). - Protocol version constants live in `src/mc.rs` and are documented in [docs/protocol.md](https://docs.sculk.network/nightly/oauthmc/protocol.md). - The default server list icon is `src/favicon.png` (64x64, embedded in the binary). The mark ([docs/assets/mark.svg](https://docs.sculk.network/nightly/assets/crates/oauthmc/docs/assets/mark.svg)), the README banner and the GitHub social preview (`docs/assets/social.png`, 1280x640) live in `docs/assets/`. - Use relative links only so every page renders on both GitHub and static-site generators. --- Source: https://docs.sculk.network/nightly/sculkworm.md

Sculkworm by sculk.network: route Minecraft connections by hostname

# 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 `` 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 ``` 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 [OPTIONS] or: sculkworm connect [OPTIONS] Commands: play Log in if needed and open a local Minecraft listener for login Log in to a closed route via browser redirect or device flow logout 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_","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=` (writes `/servers.dat` inside an existing directory), and `--add-server=/servers.dat` (writes that file in an existing parent directory). Leading `~` and `~/` (or `~\` on Windows) in `--add-server=` 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/26cfdac/crates/sculkworm/LICENSE). Sculkworm is not affiliated with or endorsed by Mojang Studios or Microsoft. Minecraft is a trademark of Mojang Studios. --- Source: https://docs.sculk.network/nightly/sculkworm/getting-started.md # Getting started This guide builds the Sculkworm container locally, starts two throwaway Minecraft Java Edition status backends using `minecraft-protocol`, writes a routes file, runs Sculkworm, pings both hostnames, reloads routes with `SIGHUP`, inspects the structured logs, and shuts everything down. Every command runs in a terminal on the host. Each command block is followed by the output you see. Values in angle brackets, like ``, or ephemeral client port numbers change on every run. The walkthrough publishes the relay on `127.0.0.1:25595` so it does not collide with any local Minecraft server on port `25565`. In production, publish `-p 25565:25565` and drop `--add-host`. ## Prerequisites - Docker Engine - Node.js 22.18 or later and `npm` (for the two throwaway backends and the status ping client) ## 1. Get the container image (or standalone binaries) Pull a published relay image from `ghcr.io/yellowumbrelladev/sculkworm` (for example `:nightly` or an exact `` tag from [Releases](https://github.com/YellowUmbrellaDev/sculk.network/releases)) and tag it locally as `sculkworm` for the rest of this guide: ```sh docker pull ghcr.io/yellowumbrelladev/sculkworm:nightly docker tag ghcr.io/yellowumbrelladev/sculkworm:nightly sculkworm ``` Or build the image locally from `crates/sculkworm` (or pass `crates/sculkworm` from the repository root): ```sh docker build -t sculkworm crates/sculkworm ``` The build compiles a static Linux musl binary and packages it into a non-root distroless image. It finishes with: ```text => => naming to docker.io/library/sculkworm:latest ``` To run `sculkworm`, `sculkworm-agent`, or `sculkworm-connect` directly without Docker, download a release archive and verify it against `SHA256SUMS` as shown in [Installing binaries from a release](https://docs.sculk.network/nightly/sculkworm/deploy.md#installing-binaries-from-a-release). ## 2. Start two local Minecraft status backends Create a working directory and install `minecraft-protocol` pinned to `1.68.0`: ```sh mkdir -p sculkworm-demo/config cd sculkworm-demo cat > package.json <<'EOF' { "name": "sculkworm-demo", "private": true, "type": "module", "dependencies": { "minecraft-protocol": "1.68.0" } } EOF npm install --no-audit --no-fund ``` Save `backends.mjs` to start two offline-mode Minecraft 1.21.4 status responders on ports `25581` and `25582` with distinct MOTDs: ```sh cat > backends.mjs <<'EOF' import mc from 'minecraft-protocol'; const servers = [ { port: 25581, motd: 'Survival backend' }, { port: 25582, motd: 'Creative backend' }, ]; for (const { port, motd } of servers) { const server = mc.createServer({ 'online-mode': false, host: '0.0.0.0', port, version: '1.21.4', motd, }); server.on('listening', () => { console.log(`listening on 0.0.0.0:${port} (${motd})`); }); } EOF ``` Start both backends in the background and confirm they are listening: ```sh node backends.mjs & BACKENDS_PID=$! ``` ```text listening on 0.0.0.0:25581 (Survival backend) listening on 0.0.0.0:25582 (Creative backend) ``` ## 3. Write the routes file and start Sculkworm Write `config/routes.json` mapping two hostnames to the two local backends via `host.docker.internal`: ```sh cat > config/routes.json <<'EOF' { "routes": { "survival.play.example": "host.docker.internal:25581", "creative.play.example": "host.docker.internal:25582" } } EOF ``` Start the Sculkworm container with `./config` mounted read-only at `/etc/sculkworm`. Mounting the directory (rather than the single file) lets atomic file replacements become visible inside the container on `SIGHUP`: ```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 ``` Check the startup log: ```sh docker logs sculkworm ``` ```text level=info event=listening addr=0.0.0.0:25565 routes=2 ``` ## 4. Ping both hostnames and an unknown hostname Save `ping.mjs`, which connects to `127.0.0.1:25595` while sending the requested hostname in the Minecraft 1.21.4 Handshake packet: ```sh cat > ping.mjs <<'EOF' import net from 'node:net'; import mc from 'minecraft-protocol'; const [, , serverHost, relayPort = '25595'] = process.argv; const status = await mc.ping({ host: serverHost, port: Number(relayPort), version: '1.21.4', connect: (client) => { const socket = net.connect(Number(relayPort), '127.0.0.1'); client.setSocket(socket); client.emit('connect'); }, }); console.log(JSON.stringify({ host: serverHost, version: status.version.name, motd: status.description.text })); EOF ``` Ping `survival.play.example`: ```sh node ping.mjs survival.play.example 25595 ``` ```json {"host":"survival.play.example","version":"1.21.4","motd":"Survival backend"} ``` Ping `creative.play.example`: ```sh node ping.mjs creative.play.example 25595 ``` ```json {"host":"creative.play.example","version":"1.21.4","motd":"Creative backend"} ``` Ping a hostname not listed in `routes.json`. Sculkworm closes the connection with zero bytes written: ```sh node ping.mjs unknown.play.example 25595 ``` ```text Error: Connection closed before the server sent a status response ``` ## 5. Hot-reload routes with SIGHUP Add a third hostname (`lobby.play.example`) by writing a temporary file and replacing `config/routes.json` atomically, then send `SIGHUP` to the container: ```sh cat > config/routes.json.tmp <<'EOF' { "routes": { "survival.play.example": "host.docker.internal:25581", "creative.play.example": "host.docker.internal:25582", "lobby.play.example": "host.docker.internal:25581" } } EOF mv config/routes.json.tmp config/routes.json docker kill --signal=HUP sculkworm ``` ```text sculkworm ``` Ping the newly added hostname without restarting the container: ```sh node ping.mjs lobby.play.example 25595 ``` ```json {"host":"lobby.play.example","version":"1.21.4","motd":"Survival backend"} ``` ## 6. Shut down and inspect the full logs Stop the container gracefully (`SIGTERM`), inspect every log line emitted during the walkthrough, and clean up: ```sh docker stop sculkworm 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:59278 level=info event=closed host=survival.play.example target=host.docker.internal:25581 bytes_up=45 bytes_down=145 peer=172.17.0.1:59278 level=info event=route host=creative.play.example target=host.docker.internal:25582 intent=status protocol=769 peer=172.17.0.1:59282 level=info event=closed host=creative.play.example target=host.docker.internal:25582 bytes_up=45 bytes_down=145 peer=172.17.0.1:59282 level=info event=unknown_host host=unknown.play.example peer=172.17.0.1:55140 level=info event=reloaded routes=3 level=info event=route host=lobby.play.example target=host.docker.internal:25581 intent=status protocol=769 peer=172.17.0.1:55154 level=info event=closed host=lobby.play.example target=host.docker.internal:25581 bytes_up=42 bytes_down=145 peer=172.17.0.1:55154 level=info event=shutdown ``` Remove the container and stop the local backends: ```sh docker rm sculkworm kill "$BACKENDS_PID" ``` ```text sculkworm ``` ## Next steps - Read [Configuration](https://docs.sculk.network/nightly/sculkworm/configuration.md) for every `SCULKWORM_*` environment variable and route validation error. - Read [Deploying](https://docs.sculk.network/nightly/sculkworm/deploy.md) for Docker Compose, `SIGHUP` reload error handling, and TCP proxy behavior. - Read [Security model](https://docs.sculk.network/nightly/sculkworm/security.md) before exposing Sculkworm to the public internet. --- Source: https://docs.sculk.network/nightly/sculkworm/configuration.md # 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=""` and exits with code `2`. On a `SIGHUP` reload, Sculkworm logs `level=error event=reload_failed path="" error=""` and keeps the previous route table active. | Error message | Condition | | --- | --- | | `failed to read routes file : ` | The file does not exist, cannot be opened, or is not valid UTF-8. | | `invalid routes file: ` | 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 "": domain must not be empty` | A route key is empty (`""`) or consists of a single dot (`"."`). | | `duplicate route domain after normalization: ` | Two entries in `routes` normalize to the same domain after lowercasing and stripping a single trailing dot. | | `target "" must be in host:port format` | A target string does not contain a `:` separator. | | `target "" has invalid port ""` | The port substring after the last `:` is not a valid `u16` integer (`0..=65535`). | | `target "" port must be non-zero` | The parsed port is `0`. | | `target "" has invalid bracketed IPv6 host` | The host part is enclosed in `[...]` but the inner string is not a valid IPv6 address. | | `target "" has invalid 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: at line column `. ## 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 ` 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=""` and exits with code `2`. | Error message | Condition | | --- | --- | | `failed to read tenants file : ` | The file does not exist, cannot be opened, or is not valid UTF-8. | | `invalid tenants file: ` | The file is empty, not valid JSON, missing a required field, or contains an unknown field. | | `tenant "" has invalid domain "": domain must not be empty` | A domain entry in `domains` is empty (`""`) or a single dot (`"."`). | | `tenant "": allowed_targets pattern must not be empty` | An entry in `allowed_targets` is `""`. | | `tenant "": invalid allowed_targets pattern ""` | An `allowed_targets` entry contains whitespace, control characters, empty labels, `/`, `:`, `[`, `]`, or fails parsing. | | `tenant "": invalid allowed_targets wildcard pattern ""` | A `*.` wildcard entry in `allowed_targets` has an empty or malformed suffix. | | `tenant "": invalid allowed_targets pattern "": wildcards must be '*.suffix'` | An `allowed_targets` entry contains `*` outside a leading `*.` prefix. | | `invalid tenant 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 ""` | Two tenants have the same `name`. | | `tenant "" key must be at least 32 characters long` | A tenant `key` is shorter than 32 bytes. | | `duplicate tenant key for tenant ""` | Two tenants share the same `key`. | | `tenant "" must have at least one domain` | A tenant's `domains` array is empty. | | `tenant "" max_routes must be between 1 and 100000` | A tenant's `max_routes` is `0` or greater than `100000`. | | `overlapping domain scope between tenants "" () and "" ()` | 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 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:///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:///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": ""}` 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=""` 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= 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= 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 ` | `SCULKWORM_AGENT_RELAY` | *(required)* | Relay tunnel `https://host[:port]` URL or `host:port` authority. | | `--route ` | `SCULKWORM_AGENT_ROUTE` | *(required)* | Closed route hostname (normalized with `Domain::parse`). | | `--token ` | `SCULKWORM_AGENT_TOKEN` | *(required unless `--token-file`)* | Agent token minted by `POST /v1/routes/{host}/agent-token`. | | `--token-file ` | `SCULKWORM_AGENT_TOKEN_FILE` | *(unset)* | Path to a file containing the agent token (mutually exclusive with `--token`). | | `--target ` | `SCULKWORM_AGENT_TARGET` | `127.0.0.1:25565` | Local Minecraft server socket address. | | `--ca-file ` | `SCULKWORM_AGENT_CA_FILE` | *(OS root store)* | PEM CA/certificate file used exclusively as the TLS root store instead of OS roots. | | `--pin ` | `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 ` | *(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 ` — 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 ` — 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 ` — calls `POST /logout` on the relay and removes the local entry (or all entries). | Flag | Environment variable | Default | Meaning | | --- | --- | --- | --- | | `--relay ` | *(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 ` | *(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[=]` | *(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=`, or `--add-server=/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 ` | `SCULKWORM_CONNECT_CA_FILE` | *(OS root store)* | PEM CA/certificate file replacing the OS root store for both HTTPS and tunnel TLS. | | `--pin ` | `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 ` | `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 ` | *(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" ``` --- Source: https://docs.sculk.network/nightly/sculkworm/index.md # Sculkworm documentation Sculkworm routes Minecraft Java Edition TCP connections by the hostname inside the initial Handshake packet. These pages cover running, configuring, operating, securing, and contributing to Sculkworm. ## Pages - [Getting started](https://docs.sculk.network/nightly/sculkworm/getting-started.md): build the container, configure routes, ping two 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.json` file format, and every validation error. - [HTTP admin API](https://docs.sculk.network/nightly/sculkworm/api.md): bearer-key tenancy, open and closed route endpoints, agent tokens, revocations, public HTTPS login/ticket endpoints, limits, and error codes. The machine-readable schema is [openapi.yaml](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, closed mode (TLS ALPN split, secrets file, `sculkworm-agent`, `sculkworm-connect`, systemd units, state v2 upgrade note), `SIGHUP` reloads, graceful shutdown, proxy limitations, and structured log events. - [Security model](https://docs.sculk.network/nightly/sculkworm/security.md): threat model, unauthenticated hostnames, open-relay and closed-mode trust boundaries, log sanitization, resource caps, and player IP visibility. - [Minecraft protocol](https://docs.sculk.network/nightly/sculkworm/protocol.md): Handshake wire format, closed-route answers on port 25565, the Minecraft 26.4 host query grammar, normalization rules, size limits, and rejection reasons. - [Closed routes (specification)](https://docs.sculk.network/nightly/sculkworm/tunnel.md): the agent and connect tunnel contract, its wire protocol with test vectors, browser and device login flows, authorizers, admin API additions, state version 2, and threat model. - [sculk.network as an authorizer](https://docs.sculk.network/nightly/sculkworm/sculk-authorizer.md): admitting players who hold `server.play` on a sculk.network server using sculk.network's OIDC provider. - [Real-client verification](https://docs.sculk.network/nightly/sculkworm/verification.md): automated `minecraft-protocol` offline/encrypted/26.4/`servers.dat`/closed-mode e2e checks and the manual checklist for real Discord, browser, Java sync-jar, and Prism Launcher runs. - [Contributing](https://docs.sculk.network/nightly/sculkworm/contributing.md): building from source, running Rust tests and live checks, code layout, conventions, and release status. - [Releases](https://github.com/YellowUmbrellaDev/sculk.network/releases): changes by release, under the `sculkworm-v` tags. ## Glossary - **Relay**: the Sculkworm TCP server that accepts incoming Minecraft connections on one port, reads the Handshake packet, and splices each connection to a backend. - **Route**: a single entry in `routes.json` mapping one normalized domain name to one backend target. - **Route table**: the in-memory `HashMap` (`RouteTable` in `src/routes.rs`) loaded from `SCULKWORM_ROUTES_FILE` and swapped atomically on `SIGHUP`. - **Target**: a validated destination backend address in `host:port` or `[ipv6]:port` format (`Target` in `src/routes.rs`) that receives the replayed Handshake bytes and the spliced TCP stream. - **Handshake**: the first serverbound packet (`0x00`) of every modern Minecraft Java Edition TCP connection, carrying protocol version, Server Address, port, and intent (`status`, `login`, or `transfer`). - **Host field**: the UTF-8 Server Address string inside the Handshake packet, parsed by `HostField::parse` (`src/domain.rs`) to strip Forge `\0` suffixes, decode 26.4 query parameters, and derive the lookup domain. - **Origin**: the original domain (and optional port) carried in the `_o` query parameter of the Handshake host field, defined for Minecraft 26.4 clients that connect through an `SRV` record. - **Static route**: a route declared in the JSON file at `SCULKWORM_ROUTES_FILE`. Read-only through the API, and it wins over a dynamic route for the same hostname. - **Dynamic route**: a route created through the admin API, persisted in `SCULKWORM_STATE_FILE` and kept across restarts and `SIGHUP` reloads. - **Tenant**: a service that uses the shared relay, defined in `SCULKWORM_TENANTS_FILE` with a bearer key, one or more domain scopes, a `max_routes` cap, and optional `allowed_targets`. A tenant can only see and change dynamic routes inside its own scopes. - **Domain scope**: a domain a tenant owns. It covers the domain itself and every subdomain of it, and no two tenants may overlap. - **Closed route**: a dynamic route (`mode: "closed"`) with no backend `target`. Only players admitted by its authorizer reach it, through `sculkworm-connect` and the route's `sculkworm-agent`. See [Closed routes](https://docs.sculk.network/nightly/sculkworm/tunnel.md). - **Agent**: `sculkworm-agent` (or `sculkworm agent`). Runs next to a Minecraft server that listens on `127.0.0.1` only, dials out to the relay over TLS with the route's agent token, and serves player streams to the local server. - **Connect**: `sculkworm-connect` (or `sculkworm connect`), the player CLI. Logs the player in through the browser (or RFC 8628 device flow), opens a local listener for Minecraft, optionally updates `servers.dat` (`--add-server`), and carries each connection to the relay with a ticket. - **Authorizer**: the per-route rule of a closed route that decides which identities may play: `fixed-list`, `oidc` (including `allow.sculk_server` for [sculk.network](https://docs.sculk.network/nightly/sculkworm/sculk-authorizer.md)), or `oauth2` (with a Discord preset). - **Ticket**: a 30-second, single-use `swt_` credential the relay mints after re-checking the player's permission with the identity provider. It opens one connect session on one route. --- Source: https://docs.sculk.network/nightly/sculkworm/api.md # HTTP Admin API When `SCULKWORM_TENANTS_FILE` is set, Sculkworm exposes a multi-tenant HTTP/1.1 admin API on `SCULKWORM_API_ADDR` (default `127.0.0.1:8080`, or `0.0.0.0:8080` in Docker). The machine-readable schema lives in [openapi.yaml](https://docs.sculk.network/nightly/sculkworm/openapi.md). For TypeScript and JavaScript backends, use the [official client SDK](https://docs.sculk.network/nightly/sculkworm/sdk/js.md). When `SCULKWORM_TENANTS_FILE` is unset, the HTTP admin API is disabled and no HTTP port is opened. ## Authentication and tenancy Every `/v1/*` endpoint requires an `Authorization` header: ```text Authorization: Bearer ``` The `Bearer` scheme is matched case-insensitively per RFC 7235. Keys are configured per tenant in `SCULKWORM_TENANTS_FILE` (at least 32 characters each, unique across tenants) and compared in constant time across all configured tenants without early exit. Missing or invalid credentials return `401 Unauthorized` with `WWW-Authenticate: Bearer`: ```sh curl -sS -i http://127.0.0.1:8080/v1/routes ``` ```text HTTP/1.1 401 Unauthorized content-type: application/json www-authenticate: Bearer cache-control: no-store content-length: 77 date: Thu, 26 Nov 2026 12:28:43 GMT {"error":{"code":"unauthorized","message":"missing or invalid bearer token"}} ``` Each tenant is restricted to its configured domain scopes: - A tenant may manage hostname `H` if and only if `H` equals one of its `domains` or ends with `.` plus one of its `domains`. - A tenant can only list, read, update, or delete its own dynamic routes, agent tokens, connected agents, and revocations. Static routes and other tenants' routes are hidden from `GET /v1/routes` and `GET /v1/agents`, and return `404 not_found` on `GET`, `DELETE`, `POST .../agent-token`, `DELETE .../agent-token`, and `POST .../revoke-logins`. - `GET /healthz` requires no authentication. ## Limits and error format - Request bodies are capped at 16 KiB (`413 body_too_large`). - Header reads and body reads each time out after 10 seconds (body timeout returns `408 body_timeout`). - Concurrent API connections are capped at `SCULKWORM_MAX_API_CONNECTIONS` (default `64`). Excess connections close immediately. - `PUT /v1/routes/{host}` and `POST /v1/routes/{host}/revoke-logins` require `Content-Type: application/json` (parameters such as `; charset=utf-8` are accepted). Any other or missing content type returns `415 unsupported_media_type`. - Every response carries `Cache-Control: no-store`, so proxies never cache tenant data. - All error responses return `Content-Type: application/json` with this envelope: ```json { "error": { "code": "host_out_of_scope", "message": "host is outside tenant domain scope" } } ``` ## Endpoints ### `GET /healthz` Unauthenticated liveness probe. ```sh curl -sS -i http://127.0.0.1:8080/healthz ``` ```text HTTP/1.1 200 OK content-type: application/json cache-control: no-store content-length: 15 date: Thu, 26 Nov 2026 12:28:43 GMT {"status":"ok"} ``` ### `GET /v1/routes` Lists all dynamic routes (both `open` and `closed`) owned by the calling tenant, sorted lexicographically by `host`. Static routes and other tenants' routes are never included. ```sh curl -sS -i \ -H "Authorization: Bearer $KEY" \ http://127.0.0.1:8080/v1/routes ``` ```text HTTP/1.1 200 OK content-type: application/json cache-control: no-store content-length: 120 date: Thu, 26 Nov 2026 12:28:43 GMT {"routes":[{"host":"survival.play.sculk.network","mode":"open","target":"host.docker.internal:25589","tenant":"sculk"}]} ``` ### `GET /v1/routes/{host}` Returns one dynamic route owned by the calling tenant. `{host}` is percent-decoded and normalized with `Domain::parse` (lowercased, at most one trailing dot stripped). Returns `404 not_found` if the route does not exist, belongs to another tenant, or is defined in `SCULKWORM_ROUTES_FILE`. Open route response: ```json {"host":"survival.play.sculk.network","mode":"open","target":"host.docker.internal:25589","tenant":"sculk"} ``` Closed route response: ```json {"host":"friends.play.sculk.network","mode":"closed","tenant":"sculk","authorizer":{"type":"oauth2","client":"discord-main","allow":{"discord_guild":"1234567890"}},"authorizer_id":"fedcba9876543210","agent_token":{"id":"0123456789abcdef","created_at":"2026-11-27T10:00:00Z"},"agent_connected":false,"active":true} ``` - `authorizer_id`: 16 lowercase hex characters; rotates whenever the normalized authorizer changes. - `agent_token`: `{"id","created_at"}` or `null` when no token has been minted. The raw token and its SHA-256 hash are never returned here. - `agent_connected`: live indicator of whether an agent session is attached. - `active`: `true` when the closed route is usable, or `false` accompanied by `inactive_reason` (`closed_mode_disabled`, `unknown_client`, or `client_tenant_mismatch`). ### `PUT /v1/routes/{host}` Creates or updates a dynamic route within the calling tenant's domain scope. Request body (`Content-Type: application/json`, unknown fields rejected with `400 invalid_json`): | Field | Required | Rules | | --- | --- | --- | | `mode` | No | `"open"` (default) or `"closed"`. Any other value returns `422 invalid_mode`. | | `target` | `open` only | Backend address in `host:port` or `[ipv6]:port` format with port `1..=65535`. Must match the tenant's `allowed_targets` if configured. On `mode: "closed"`, returns `422 invalid_target` (`a closed route has no target`). | | `authorizer` | `closed` only | Authorizer object (`type`: `"oidc"`, `"oauth2"`, or `"fixed-list"`, plus `client`, optional `scopes`, and `allow` — including `{"claim", "any_of"}`, `{"sculk_server"}` for `oidc`, or `{"field", "any_of"}` / `{"discord_guild"}` for `oauth2` — or `subjects`; see [Closed routes: authorizer configuration](https://docs.sculk.network/nightly/sculkworm/tunnel.md#6-authorizer-configuration)). On `mode: "open"`, returns `422 invalid_authorizer`. | `max_routes` counts open and closed routes together. `allowed_targets` applies only to open routes. Creating or updating a closed route requires `SCULKWORM_TUNNEL_LISTEN` (and its companion variables) to be configured; otherwise the endpoint returns `503 closed_mode_disabled`. On the public Minecraft port, closed routes answer status pings with the `sculkworm.relay` status JSON and reject login/transfer attempts with the `sculkworm-connect` Login Disconnect message (see [Closed-route answers](https://docs.sculk.network/nightly/sculkworm/protocol.md#closed-route-answers-on-the-minecraft-port)). Responses: - `201 Created`: route did not exist and was persisted and activated. - `200 OK`: route already existed for this tenant and was updated, or already had the exact same normalized configuration (idempotent; no state file rewrite occurs and `authorizer_id` is preserved when unchanged). Changes are persisted atomically to `SCULKWORM_STATE_FILE` before updating the in-memory route table. If writing the state file fails, Sculkworm returns `500 persist_failed` and leaves the in-memory table unchanged. Create open route example: ```sh curl -sS -i -X PUT \ -H "Authorization: Bearer $KEY" \ -H "Content-Type: application/json" \ -d '{"target":"host.docker.internal:25589"}' \ http://127.0.0.1:8080/v1/routes/survival.play.sculk.network ``` Create closed route example (OIDC claim rule): ```sh curl -sS -i -X PUT \ -H "Authorization: Bearer $KEY" \ -H "Content-Type: application/json" \ -d '{"mode":"closed","authorizer":{"type":"oidc","client":"mock-oidc","scopes":["openid","profile"],"allow":{"claim":"groups","any_of":["minecraft"]}}}' \ http://127.0.0.1:8080/v1/routes/friends.play.example ``` ```text HTTP/1.1 201 Created content-type: application/json cache-control: no-store {"active":true,"agent_connected":false,"agent_token":null,"authorizer":{"allow":{"any_of":["minecraft"],"claim":"groups"},"client":"mock-oidc","scopes":["openid","profile"],"type":"oidc"},"authorizer_id":"a36e0b5c286c1fd2","host":"friends.play.example","mode":"closed","tenant":"sculk"} ``` Create closed route example (Discord guild): ```sh curl -sS -i -X PUT \ -H "Authorization: Bearer $KEY" \ -H "Content-Type: application/json" \ -d '{"mode":"closed","authorizer":{"type":"oauth2","client":"discord-main","allow":{"discord_guild":"1234567890"}}}' \ http://127.0.0.1:8080/v1/routes/friends.play.sculk.network ``` Create closed route example (sculk.network server membership via OIDC): ```sh curl -sS -i -X PUT \ -H "Authorization: Bearer $KEY" \ -H "Content-Type: application/json" \ -d '{"mode":"closed","authorizer":{"type":"oidc","client":"sculk-main","allow":{"sculk_server":"6uabltcpud3qpiy5"}}}' \ http://127.0.0.1:8080/v1/routes/friends.play.sculk.network ``` With `allow.sculk_server`, the relay automatically adds the `sculk:servers` scope and admits players whose userinfo `sculk_servers` array includes an entry with `id == ""` and `is_player == true`. See [sculk.network as an authorizer](https://docs.sculk.network/nightly/sculkworm/sculk-authorizer.md) for the full operator guide. ### `DELETE /v1/routes/{host}` Deletes a dynamic route owned by the calling tenant. New Minecraft handshakes for `{host}` are rejected immediately with `event=unknown_host`, while existing spliced TCP connections remain connected until either side closes. - `204 No Content`: route deleted and persisted. - `404 not_found`: route does not exist, belongs to another tenant, or is a static route. ### `POST /v1/routes/{host}/agent-token` Mints a new agent token (`swa_<16-hex-id>_`) for a closed route owned by the caller, replacing any previous token. Any currently connected agent session on the route receives `GOAWAY revoked` and is disconnected immediately. The raw token is returned in this `201 Created` response only; the relay stores only the token `id`, `created_at`, and the lowercase hex SHA-256 of the full token string. ```sh curl -sS -i -X POST \ -H "Authorization: Bearer $KEY" \ http://127.0.0.1:8080/v1/routes/friends.play.example/agent-token ``` ```text HTTP/1.1 201 Created content-type: application/json cache-control: no-store {"token":"swa_0123456789abcdef_","id":"0123456789abcdef","created_at":"2026-11-27T10:00:00Z"} ``` Errors: `404 not_found`, `409 route_not_closed`, `500 persist_failed`, `503 closed_mode_disabled`. ### `DELETE /v1/routes/{host}/agent-token` Revokes the current agent token for a closed route owned by the caller and sends `GOAWAY revoked` to any live agent session for that route. - `204 No Content`: token removed and persisted. - `404 not_found`: route does not exist, belongs to another tenant, or has no token. - `409 route_not_closed`: route is in open mode. - `503 closed_mode_disabled`: closed mode is disabled. ### `GET /v1/agents` Lists connected agent sessions for the calling tenant's closed routes, sorted by `host` (and then `session`). When a replacement agent connects while the previous agent is still draining open player streams after `GOAWAY replaced`, both sessions appear until the draining session finishes. ```sh curl -sS -i \ -H "Authorization: Bearer $KEY" \ http://127.0.0.1:8080/v1/agents ``` ```text HTTP/1.1 200 OK content-type: application/json cache-control: no-store {"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"}]} ``` Returns `503 closed_mode_disabled` while `SCULKWORM_TUNNEL_LISTEN` is unset. ### `POST /v1/routes/{host}/revoke-logins` Records a login revocation on a closed route (`Content-Type: application/json`) and sends `GOAWAY revoked` (resetting open streams with code `6`) to matching live connect sessions: - `{}` sets `revoked_before` to the current UTC timestamp and returns `200 {"host":"...","revoked_before":"..."}`. - `{"subject":""}` records `revoked_subjects[subject]` to the current UTC timestamp and returns `200 {"host":"...","subject":"...","revoked_at":"..."}`. Errors: `400 invalid_json`, `404 not_found`, `409 route_not_closed`, `415 unsupported_media_type`, `422 invalid_subject` (empty or over 255 bytes), `422 too_many_revocations` (route already has 10000 revoked subjects), `500 persist_failed`, `503 closed_mode_disabled`. ## Error codes Every error code returned by `src/api.rs`: | HTTP status | `error.code` | Extra headers | Cause | | --- | --- | --- | --- | | `400` | `invalid_body` | — | Failed to read the request body stream. | | `400` | `invalid_json` | — | Malformed JSON, wrong field type, missing `target`, or unknown field. | | `401` | `unauthorized` | `WWW-Authenticate: Bearer` | Missing or invalid `Authorization: Bearer ` header. | | `403` | `host_out_of_scope` | — | Host is outside the authenticated tenant's configured `domains`. | | `404` | `not_found` | — | Unknown path, route not found, route owned by another tenant, missing agent token on `DELETE`, or static route on `GET`/`DELETE`. | | `405` | `method_not_allowed` | `Allow` | Unsupported HTTP method on an API path. | | `408` | `body_timeout` | — | Request body did not finish within 10 seconds. | | `409` | `route_is_static` | — | `PUT` targeted a hostname defined in `SCULKWORM_ROUTES_FILE`. | | `409` | `route_owned_by_other` | — | `PUT` targeted a dynamic hostname owned by another tenant. | | `409` | `route_not_closed` | — | Agent token or login revocation endpoint called on an open route. | | `413` | `body_too_large` | — | Request body exceeds 16 KiB. | | `415` | `unsupported_media_type` | — | Missing or non-`application/json` `Content-Type` header on `PUT` or `POST .../revoke-logins`. | | `422` | `invalid_host` | — | `{host}` path segment has invalid percent-encoding, non-UTF-8 bytes, invalid characters (including `*`: routes match one exact hostname and there are no wildcard routes), length > 255, or normalizes to empty. | | `422` | `invalid_mode` | — | `mode` is neither `"open"` nor `"closed"`. | | `422` | `invalid_target` | — | `target` is not a valid `host:port` or `[ipv6]:port` with port `1..=65535`, or `target` was provided with `mode: "closed"`. | | `422` | `invalid_authorizer` | — | Missing, disallowed, malformed, unknown-client, or failed-discovery authorizer (see [section 6.4](https://docs.sculk.network/nightly/sculkworm/tunnel.md#64-validation-errors)). | | `422` | `invalid_subject` | — | `subject` in `revoke-logins` is empty or exceeds 255 bytes. | | `422` | `target_not_allowed` | — | `target` does not match any entry in the tenant's `allowed_targets`. | | `422` | `too_many_routes` | — | Creating a new route would exceed the tenant's `max_routes` limit. | | `422` | `too_many_revocations` | — | Route already holds 10000 entries in `revoked_subjects`. | | `500` | `persist_failed` | — | Atomic write of `SCULKWORM_STATE_FILE` failed; in-memory route table is unchanged. | | `503` | `closed_mode_disabled` | — | `mode: "closed"` or a closed-route endpoint called while `SCULKWORM_TUNNEL_LISTEN` is unset. | ## Public HTTPS endpoints (tunnel listener) When `SCULKWORM_TUNNEL_LISTEN` is set, the TLS tunnel listener also serves the public HTTP/1.1 player login and ticket endpoints on ALPN `http/1.1` (or no ALPN). Every response carries `Cache-Control: no-store`; HTML pages carry `Content-Security-Policy`, `X-Content-Type-Options: nosniff`, and `Referrer-Policy: no-referrer`, and JSON errors use the same `{"error":{"code","message"}}` envelope. | Method and path | Auth / input | Success | Error codes | | --- | --- | --- | --- | | `GET /healthz` | None | `200 {"status":"ok"}` | `405 method_not_allowed` | | `GET /login/start` | Query: `route`, `redirect_uri` (loopback `/callback`), `state` (16–128 base64url chars), `code_challenge` (43 base64url chars), `code_challenge_method=S256` | `302` to IdP authorize URL | `400` HTML, `404` HTML, `429 rate_limited`, `503` HTML / `busy` | | `GET /login/callback` | Query from IdP: `code`, `state`, or `error` (plus `__Host-swdevcb` cookie for device flows) | `302` to loopback `redirect_uri` with one-time `swc_` code and `state`, or `200` HTML result page for device flows (clears `__Host-swdevcb`) | `400` HTML, `403` HTML (not admitted or missing/mismatched `__Host-swdevcb`), `404` HTML, `503` HTML / `busy` | | `POST /login/device` | JSON `{"route"}` | `200 {"device_code":"swd_...","user_code":"XXXX-XXXX","verification_uri","expires_in":600,"interval":5}` | `400 invalid_json`, `404 unknown_route`, `429 rate_limited`, `503 busy` | | `GET /login/device` | None (`user_code` query parameter ignored) | `200` HTML form; sets `__Host-swdev` cookie (`Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=600`) | `405 method_not_allowed` | | `POST /login/device/approve` | Form body (`application/x-www-form-urlencoded`) `user_code`, `csrf`, optional `confirm=1` or `cancel=1`, plus `__Host-swdev` cookie and `Sec-Fetch-Site: same-origin` | Without `confirm`: `200` confirmation HTML page with phishing warning. With `confirm=1`: `302` to IdP (with `prompt=consent` for OIDC and Discord preset) and sets `__Host-swdevcb` cookie (`SameSite=Lax`). With `cancel=1`: `200` HTML page | `403` HTML (cookie, `csrf`, or `Sec-Fetch-Site` check failed), `404` HTML (unknown/expired/already-claimed code), `429` HTML (per-IP, per-code, or global miss rate limit), `503` HTML | | `POST /login/token` | JSON `{"grant_type":"authorization_code","code","code_verifier","redirect_uri"}` or `{"grant_type":"device_code","device_code"}` | `200 {"login":"swl_...","route","subject","name","expires_at"}` | `400 invalid_grant`, `400 authorization_pending`, `400 slow_down`, `400 access_denied`, `400 expired_token`, `400 invalid_json`, `408 body_timeout`, `413 body_too_large`, `429 slow_down` | | `POST /tickets` | `Authorization: Bearer swl_...`; JSON `{"route"}` | `200 {"ticket":"swt_...","expires_in":30}` (plus `"login":"swl_..."` when rotated) | `400 invalid_json`, `401 login_invalid`, `401 login_expired`, `401 login_revoked`, `403 not_admitted`, `404 unknown_route`, `409 route_mismatch`, `429 rate_limited`, `503 idp_unavailable`, `503 busy` | | `POST /logout` | `Authorization: Bearer swl_...` | `204 No Content` (persists `lid` in `revoked_logins` and kicks live connect sessions for that `lid`) | `401 login_invalid`, `429 rate_limited`, `503 busy` | See [Closed routes: login flow and public HTTP endpoints](https://docs.sculk.network/nightly/sculkworm/tunnel.md#56-public-http-endpoints) for the full contract. For configuration variables and the tenants, secrets, and state file schemas, see [Configuration](https://docs.sculk.network/nightly/sculkworm/configuration.md). For deployment examples, see [Deploying sculkworm](https://docs.sculk.network/nightly/sculkworm/deploy.md). --- Source: https://docs.sculk.network/nightly/sculkworm/openapi.md # Sculkworm OpenAPI specification ```yaml openapi: 3.1.0 info: title: Sculkworm Admin API version: 0.1.0 description: Multi-tenant runtime route management API for Sculkworm. license: name: MIT url: https://opensource.org/licenses/MIT servers: - url: http://127.0.0.1:8080 security: - bearerAuth: [] paths: /healthz: get: summary: Liveness probe security: [] responses: "200": description: Service is running content: application/json: schema: type: object required: [status] additionalProperties: false properties: status: type: string const: ok "405": $ref: "#/components/responses/MethodNotAllowed" /v1/routes: get: summary: List routes owned by the authenticated tenant responses: "200": description: Caller's dynamic routes, sorted by host content: application/json: schema: $ref: "#/components/schemas/RouteListResponse" "401": $ref: "#/components/responses/Unauthorized" "405": $ref: "#/components/responses/MethodNotAllowed" /v1/agents: get: summary: List connected agent sessions for the authenticated tenant's closed routes responses: "200": description: Connected agent sessions sorted by host content: application/json: schema: $ref: "#/components/schemas/AgentListResponse" "401": $ref: "#/components/responses/Unauthorized" "405": $ref: "#/components/responses/MethodNotAllowed" "503": $ref: "#/components/responses/ErrorResponse" /v1/routes/{host}: parameters: - name: host in: path required: true description: Domain name (URL-decoded, lowercased, at most one trailing dot stripped) schema: type: string get: summary: Get one route owned by the authenticated tenant responses: "200": description: Route details content: application/json: schema: $ref: "#/components/schemas/Route" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/ErrorResponse" "405": $ref: "#/components/responses/MethodNotAllowed" put: summary: Create or update a route within the authenticated tenant's domain scope requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/PutRouteRequest" responses: "200": description: Existing route updated or unchanged content: application/json: schema: $ref: "#/components/schemas/Route" "201": description: Route created content: application/json: schema: $ref: "#/components/schemas/Route" "400": $ref: "#/components/responses/ErrorResponse" "401": $ref: "#/components/responses/Unauthorized" "403": description: Host is outside the authenticated tenant's domain scope content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "405": $ref: "#/components/responses/MethodNotAllowed" "408": $ref: "#/components/responses/ErrorResponse" "409": description: Host is defined as a static route or owned by another tenant content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "413": $ref: "#/components/responses/ErrorResponse" "415": $ref: "#/components/responses/ErrorResponse" "422": description: Invalid host, invalid mode, invalid target, invalid authorizer, target disallowed by allowed_targets, or max_routes reached content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "500": description: Persisting the state file failed; in-memory route table is unchanged content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "503": description: Closed mode is disabled (SCULKWORM_TUNNEL_LISTEN is unset) content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" delete: summary: Delete a route owned by the authenticated tenant responses: "204": description: Route deleted "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/ErrorResponse" "405": $ref: "#/components/responses/MethodNotAllowed" "500": description: Persisting the state file failed; in-memory route table is unchanged content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" /v1/routes/{host}/agent-token: parameters: - name: host in: path required: true description: Domain name of a closed route owned by the authenticated tenant schema: type: string post: summary: Mint a new agent token for a closed route, revoking any previous token responses: "201": description: Agent token minted (shown once) content: application/json: schema: $ref: "#/components/schemas/MintedAgentToken" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/ErrorResponse" "405": $ref: "#/components/responses/MethodNotAllowed" "409": description: Route is not a closed route content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "500": $ref: "#/components/responses/ErrorResponse" "503": $ref: "#/components/responses/ErrorResponse" delete: summary: Revoke the current agent token for a closed route responses: "204": description: Agent token revoked "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/ErrorResponse" "405": $ref: "#/components/responses/MethodNotAllowed" "409": $ref: "#/components/responses/ErrorResponse" "500": $ref: "#/components/responses/ErrorResponse" "503": $ref: "#/components/responses/ErrorResponse" /v1/routes/{host}/revoke-logins: parameters: - name: host in: path required: true description: Domain name of a closed route owned by the authenticated tenant schema: type: string post: summary: Revoke all logins or one subject's logins for a closed route requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/RevokeLoginsRequest" responses: "200": description: Revocation recorded content: application/json: schema: $ref: "#/components/schemas/RevokeLoginsResponse" "400": $ref: "#/components/responses/ErrorResponse" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/ErrorResponse" "405": $ref: "#/components/responses/MethodNotAllowed" "408": $ref: "#/components/responses/ErrorResponse" "409": $ref: "#/components/responses/ErrorResponse" "413": $ref: "#/components/responses/ErrorResponse" "415": $ref: "#/components/responses/ErrorResponse" "422": $ref: "#/components/responses/ErrorResponse" "500": $ref: "#/components/responses/ErrorResponse" "503": $ref: "#/components/responses/ErrorResponse" components: securitySchemes: bearerAuth: type: http scheme: bearer responses: ErrorResponse: description: Error response content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" Unauthorized: description: Missing or invalid bearer token headers: WWW-Authenticate: required: true schema: type: string const: Bearer content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" MethodNotAllowed: description: Method not allowed for this path headers: Allow: required: true schema: type: string content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" schemas: Authorizer: oneOf: - type: object required: [type, client] additionalProperties: false properties: type: type: string const: oidc client: type: string scopes: type: array items: type: string allow: oneOf: - type: object required: [claim, any_of] additionalProperties: false properties: claim: type: string any_of: type: array items: type: string - type: object required: [sculk_server] additionalProperties: false properties: sculk_server: type: string minLength: 1 maxLength: 64 - type: object required: [type, client] additionalProperties: false properties: type: type: string const: oauth2 client: type: string scopes: type: array items: type: string allow: oneOf: - type: object required: [field, any_of] additionalProperties: false properties: field: type: string any_of: type: array items: type: string - type: object required: [discord_guild] additionalProperties: false properties: discord_guild: type: string - type: object required: [type, client, subjects] additionalProperties: false properties: type: type: string const: fixed-list client: type: string scopes: type: array items: type: string subjects: type: array items: type: string PutRouteRequest: type: object additionalProperties: false properties: mode: type: string enum: [open, closed] default: open target: type: string description: Backend target in host:port or [ipv6]:port format (port 1..=65535); required for open routes, forbidden for closed routes authorizer: $ref: "#/components/schemas/Authorizer" AgentTokenSummary: type: object required: [id, created_at] additionalProperties: false properties: id: type: string created_at: type: string format: date-time MintedAgentToken: type: object required: [token, id, created_at] additionalProperties: false properties: token: type: string id: type: string created_at: type: string format: date-time AgentSession: type: object required: [host, session, token_id, peer, software, connected_at, streams] additionalProperties: false properties: host: type: string session: type: string token_id: type: string peer: type: string software: type: string connected_at: type: string format: date-time streams: type: integer minimum: 0 AgentListResponse: type: object required: [agents] additionalProperties: false properties: agents: type: array items: $ref: "#/components/schemas/AgentSession" RevokeLoginsRequest: type: object additionalProperties: false properties: subject: type: string minLength: 1 maxLength: 255 RevokeLoginsResponse: oneOf: - type: object required: [host, revoked_before] additionalProperties: false properties: host: type: string revoked_before: type: string format: date-time - type: object required: [host, subject, revoked_at] additionalProperties: false properties: host: type: string subject: type: string revoked_at: type: string format: date-time Route: type: object required: [host, mode, tenant] additionalProperties: false properties: host: type: string mode: type: string enum: [open, closed] target: type: string tenant: type: string authorizer: $ref: "#/components/schemas/Authorizer" authorizer_id: type: string agent_token: oneOf: - $ref: "#/components/schemas/AgentTokenSummary" - type: "null" agent_connected: type: boolean active: type: boolean inactive_reason: type: string RouteListResponse: type: object required: [routes] additionalProperties: false properties: routes: type: array items: $ref: "#/components/schemas/Route" ErrorEnvelope: type: object required: [error] additionalProperties: false properties: error: type: object required: [code, message] additionalProperties: false properties: code: type: string message: type: string ``` --- Source: https://docs.sculk.network/nightly/sculkworm/sdk/js.md # Sculkworm Zero-dependency TypeScript client for the [sculkworm](https://github.com/YellowUmbrellaDev/sculk.network/blob/main/crates/sculkworm/README.md) HTTP admin API. > [!CAUTION] > **Server-side only.** Never bundle this package into browser code or expose your tenant bearer key from `SCULKWORM_TENANTS_FILE` to a client. Anyone with the key can list, create, update, and delete dynamic routes within your tenant's domain scope. Keep Sculkworm's admin API on a private network (loopback or internal container network) and call it exclusively from your backend. ## Install `sculkworm` is not published on npm yet. Once published, install it with: ```sh npm install sculkworm ``` Inside this repository's pnpm workspace, reference it directly via `"sculkworm": "workspace:*"` in your package's `package.json`, or build it from source with `pnpm --filter sculkworm build` (outputs ESM and `.d.ts` files to `crates/sculkworm/sdk/js/dist/`). ## Quick start ```ts import { SculkwormClient, SculkwormError, isValidHost, isValidTarget } from 'sculkworm'; const client = new SculkwormClient({ baseUrl: process.env.SCULKWORM_URL ?? 'http://sculkworm:8080', apiKey: process.env.SCULKWORM_API_KEY!, // Optional: custom fetch implementation (defaults to globalThis.fetch) // Optional: request timeout in milliseconds (default 10_000) timeoutMs: 10_000, }); // 1. Optional liveness check (unauthenticated GET /healthz). if (!(await client.health())) { throw new Error('sculkworm is not reachable'); } // 2. Optional client-side validation helpers (the server always validates). const host = 'survival.play.sculk.network'; const target = '10.0.0.10:25565'; if (!isValidHost(host) || !isValidTarget(target)) { throw new Error('Invalid host or target'); } // 3. Create or update a dynamic route (PUT /v1/routes/{host}). // Returns { route, created } where created is true on 201 and false on 200. const { route, created } = await client.putRoute(host, target); console.log(created ? 'Created' : 'Updated', route); // 4. List all dynamic routes owned by this tenant (GET /v1/routes), sorted by host. const routes = await client.listRoutes(); // 5. Fetch one route (GET /v1/routes/{host}). Returns null on 404. const existing = await client.getRoute(host); // 6. Delete a route (DELETE /v1/routes/{host}). // Resolves on 204. A 404 throws SculkwormError with code 'not_found'. await client.deleteRoute(host); ``` ## API ### `new SculkwormClient(options)` | Option | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `baseUrl` | `string` | yes | — | Base URL of the Sculkworm HTTP admin API (trailing slash optional) | | `apiKey` | `string` | yes | — | Tenant bearer token from `SCULKWORM_TENANTS_FILE` | | `fetch` | `typeof fetch` | no | `globalThis.fetch` | Custom Fetch API implementation | | `timeoutMs` | `number` | no | `10_000` | Per-request timeout via `AbortSignal.timeout` | ### Methods - `health(): Promise` — Probes `GET /healthz` without authentication. Returns `true` only on HTTP `200` with `{"status": "ok"}`, `false` otherwise. - `listRoutes(): Promise` — Lists all dynamic routes owned by the calling tenant (`GET /v1/routes`), sorted lexicographically by `host`. Static routes and other tenants' routes are never included. - `getRoute(host): Promise` — Fetches one dynamic route (`GET /v1/routes/{host}`). Returns `null` on `404` (`not_found`). - `putRoute(host, target): Promise` — Creates or updates an open dynamic route (`PUT /v1/routes/{host}`). Returns `{ route, created }` where `created` is `true` on `201 Created` and `false` on `200 OK` (updated or unchanged). - `putClosedRoute(host, authorizer): Promise` — Creates or updates a closed dynamic route (`PUT /v1/routes/{host}` with `{"mode": "closed", "authorizer": ...}`). Returns `{ route, created }` where `created` is `true` on `201 Created` and `false` on `200 OK`. - `deleteRoute(host): Promise` — Deletes a dynamic route (`DELETE /v1/routes/{host}`). Resolves on `204 No Content`. A `404` is an error (`not_found`): the SDK has no silent-ignore flag, catch `err.code === 'not_found'` if your delete is meant to be idempotent. - `mintAgentToken(host): Promise` — Mints a new agent token (`POST /v1/routes/{host}/agent-token`) for a closed route, replacing any previous token. Returns `{ id, created_at, token }`; the raw `token` is only returned once. - `revokeAgentToken(host): Promise` — Revokes the current agent token (`DELETE /v1/routes/{host}/agent-token`) for a closed route. Resolves on `204 No Content`; throws `not_found` on `404` and `route_not_closed` on `409`. ### Helpers Convenience validators matching Sculkworm's server-side rules; `getRoute`, `putRoute`, `putClosedRoute`, `deleteRoute`, `mintAgentToken` and `revokeAgentToken` run them first and throw `SculkwormError` with `invalid_host`, `invalid_target` or `invalid_authorizer` (status `null`) without sending a request; the server stays the authority: - `isValidHost(host: string): boolean` — Checks that `host` is non-empty UTF-8 at most 255 bytes, has no whitespace, control characters, `/`, `?`, `#`, or `*`, and is non-empty after lowercasing and stripping at most one trailing dot. - `isValidTarget(target: string): boolean` — Checks that `target` is a valid `host:port` or `[ipv6]:port` backend address with a port in `1..=65535`. ## Error handling API errors (`401 unauthorized`, `403 host_out_of_scope`, `409 route_is_static`, `409 route_owned_by_other`, `422 invalid_host`, `422 invalid_target`, `422 target_not_allowed`, `422 too_many_routes`, `500 persist_failed`, etc.), malformed or unexpected responses (`invalid_response`), timeouts (`timeout`), and network errors (`network_error`) throw `SculkwormError`: ```ts try { await client.putRoute('survival.play.sculk.network', '10.0.0.10:25565'); } catch (err) { if (err instanceof SculkwormError) { // err.status: HTTP status code, or null for network/timeout errors // err.code: server error.code (e.g. 'host_out_of_scope', 'route_is_static') // or 'network_error' | 'timeout' | 'invalid_response' | 'invalid_host' | 'invalid_target' // err.message: human-readable message (apiKey is never included in message or cause) if (err.code === 'route_is_static') { // Host is pinned in SCULKWORM_ROUTES_FILE. } } throw err; } ``` See [docs/api.md](https://github.com/YellowUmbrellaDev/sculk.network/blob/main/crates/sculkworm/docs/api.md#error-codes) for every HTTP status and `error.code`. ## Runtime support Built strictly on standard Web APIs (`fetch`, `AbortSignal.timeout`, `URL`, `JSON`, `TextEncoder`) with zero runtime dependencies. - Node.js 18+ (Node.js 22.18+ can import `src/index.ts` directly via native type stripping) - Deno - Bun - Cloudflare Workers ## License [MIT](https://github.com/YellowUmbrellaDev/sculk.network/blob/main/crates/sculkworm/sdk/js/LICENSE) --- Source: https://docs.sculk.network/nightly/sculkworm/sculk-authorizer.md # Using sculk.network as an authorizer A closed route on Sculkworm can use a [sculk.network](https://docs.sculk.network/nightly/sculk/oidc-provider.md) instance as its OpenID Connect provider so that **only players who hold `server.play` on a specific server** on that instance are admitted. > **Provider requirement:** Only use `allow.sculk_server` with an `oidc` client whose `issuer` is a sculk.network instance (where the `sculk_servers` userinfo claim is authoritative and controlled solely by the provider, never editable by end users). Pointing `allow.sculk_server` at a different OIDC provider that lets users populate custom profile claims named `sculk_servers` would allow any user on that provider to admit themselves. Membership is re-checked live via `/oauth/userinfo` on every login, every ticket mint (`POST /tickets`), and every connect stream `OPEN` older than 60 seconds. Removing a player from the server, dropping their `server.play` permission, revoking their OIDC grant, or blocking their subject on sculk.network denies them on the next check. If the sculk.network instance is unreachable, the relay fails closed (`503 idp_unavailable` / `RESET` code `7`). ## 1. Enable the OIDC provider on sculk.network On the sculk.network instance, enable the `oidcProvider` feature flag (enabled by default on `dev` and `nightly` builds; forced on stable builds with `SCULK_FEATURES=oidcProvider`) and list at least one administrator user ID in `SCULK_OIDC_ADMINS` (comma-separated): ```sh SCULK_FEATURES=oidcProvider SCULK_OIDC_ADMINS= ``` Sign in on sculk.network and confirm `GET /api/me` returns your `id` and `GET /.well-known/openid-configuration` returns `200 OK`. ## 2. Register the relay as an OIDC client Call `POST /api/oidc/clients` with a session belonging to a user in `SCULK_OIDC_ADMINS`. Register `${SCULKWORM_PUBLIC_URL}/login/callback` as the redirect URI (use `firstParty: true` if you want players to skip the consent prompt). Only add loopback redirect URIs (such as `http://127.0.0.1/callback` with `native: true`) if a native client talks to sculk.network directly — `sculkworm-connect` talks to the relay, and the relay is the OIDC client. ```sh curl -sS -X POST https://sculk.example/api/oidc/clients \ -H "Cookie: sculk_session=$ADMIN_SESSION" \ -H "Content-Type: application/json" \ -d '{ "name": "sculkworm relay", "redirectUris": ["https://relay.example/login/callback"], "firstParty": true }' ``` Save `client.clientId` and `clientSecret` from the `201 Created` response (`clientSecret` is returned once and never shown again). ## 3. Add the client to the relay secrets file Add an `oidc` entry to `SCULKWORM_SECRETS_FILE` (mode `0600` or `0400`) pointing `issuer` at the sculk.network base URL (`SCULK_BASE_URL`): ```json { "login_keys": { "1": "QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl8" }, "clients": { "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" } } } ``` - Including `offline_access` lets the relay refresh expired 1-hour access tokens silently over the 30-day sealed login lifetime. - Even if you omit `sculk:servers` from the client's default `scopes` or the route's `scopes`, any route with `allow: {"sculk_server": ""}` adds `sculk:servers` automatically. - Reload the relay with `SIGHUP` (or restart it) after editing the secrets file. ## 4. Create the closed route with `allow.sculk_server` Create or update the route through the relay admin API using the server's sculk.network ID (from `GET /api/servers` or `POST /api/servers`): ```sh curl -sS -i -X PUT \ -H "Authorization: Bearer $SCULKWORM_TENANT_KEY" \ -H "Content-Type: application/json" \ -d '{ "mode": "closed", "authorizer": { "type": "oidc", "client": "sculk-main", "allow": { "sculk_server": "6uabltcpud3qpiy5" } } }' \ http://127.0.0.1:8080/v1/routes/friends.play.sculk.network ``` When saving the route, the relay fetches `https://sculk.example/.well-known/openid-configuration`, verifies that `issuer` matches verbatim and that `token_endpoint` and `userinfo_endpoint` share the issuer's origin, and stores the route. Then mint an agent token (`POST /v1/routes/friends.play.sculk.network/agent-token`) and run `sculkworm-agent` next to the Minecraft server as described in [Configuration](https://docs.sculk.network/nightly/sculkworm/configuration.md#agent-cli-flags-and-environment-variables). ## 5. What the player sees 1. **Vanilla Minecraft client without connect:** pinging `friends.play.sculk.network` shows `Closed server: join it with sculkworm-connect` and trying to join disconnects with instructions to run `sculkworm-connect play friends.play.sculk.network`. 2. **First login with `sculkworm-connect play friends.play.sculk.network`:** - Connect opens the player's browser (or falls back to the device code flow if no browser is available) and sends them to the relay, which redirects to `https://sculk.example/oauth/authorize` requesting `openid profile offline_access sculk:servers`. - The player signs in to sculk.network (and approves consent once if `firstParty` is `false`). - sculk.network redirects back to `https://relay.example/login/callback`. The relay exchanges the code, validates the ID token, calls `/oauth/userinfo`, and checks that `sculk_servers` contains an object with `id == "6uabltcpud3qpiy5"` and `is_player == true`. - **Admitted player:** the browser shows login complete, connect stores the sealed login (`swl_...`) in `logins.json` (`0600`), and the player joins `127.0.0.1:25565` in Minecraft. - **Non-member or member without `server.play`:** the relay answers `403 Forbidden` ("You are signed in as ``, but `friends.play.sculk.network` does not admit this account.") and issues no login. 3. **Revocation:** - **Player loses `server.play` on `6uabltcpud3qpiy5`** (removed from the server or moved to a role without `server.play`): `/oauth/userinfo` no longer includes that server with `is_player: true`, so the next `POST /tickets` fails with `403 not_admitted` (and a new connect stream `OPEN` past the 60-second check window fails with stream `RESET` code `6`). - **OIDC grant revoked (`DELETE /api/oidc/grants/:grantId`) or subject blocked (`POST /api/oidc/subjects/:userId/block`):** sculk.network rejects `/oauth/userinfo` with `401` and rejects the subsequent token refresh with `invalid_grant`, so the next `POST /tickets` fails with `401 login_expired` (and a new connect stream `OPEN` past the 60-second check window fails with stream `RESET` code `6`). --- Source: https://docs.sculk.network/nightly/sculkworm/deploy.md # Deploying Sculkworm Sculkworm compiles to a static Linux musl binary inside a non-root `gcr.io/distroless/static-debian12:nonroot` container image. It can run purely from a static `routes.json` file (stateless) or with the multi-tenant HTTP admin API enabled alongside a JSON state file. ## Sharing port 25565 across servers Minecraft Java Edition connects to TCP port `25565` by default. Because Sculkworm inspects the hostname in the initial Handshake packet before opening a backend socket, one Sculkworm instance on port `25565` can front as many Minecraft servers as you configure via `routes.json` or the admin API. Players connect using only the hostname (`survival.play.example`, `creative.play.example`) without entering a port number. ## Installing binaries from a release Every Sculkworm release (`sculkworm-v` on the [Releases](https://github.com/YellowUmbrellaDev/sculk.network/releases) page) attaches prebuilt archives and a `SHA256SUMS` manifest: | Platform | Archive | Contents | | --- | --- | --- | | Linux x86_64 (static musl) | `sculkworm--x86_64-unknown-linux-musl.tar.gz` | `sculkworm`, `sculkworm-agent`, `sculkworm-connect`, `LICENSE`, `README.txt` | | Linux ARM64 (static musl) | `sculkworm--aarch64-unknown-linux-musl.tar.gz` | `sculkworm`, `sculkworm-agent`, `sculkworm-connect`, `LICENSE`, `README.txt` | | macOS Intel (11.0+) | `sculkworm--x86_64-apple-darwin.tar.gz` | `sculkworm`, `sculkworm-agent`, `sculkworm-connect`, `LICENSE`, `README.txt` | | macOS Apple Silicon (11.0+) | `sculkworm--aarch64-apple-darwin.tar.gz` | `sculkworm`, `sculkworm-agent`, `sculkworm-connect`, `LICENSE`, `README.txt` | | Windows x86_64 (UCRT) | `sculkworm--x86_64-pc-windows-gnu.zip` | `sculkworm-connect.exe`, `LICENSE`, `README.txt` | | Java 8+ (cross-platform) | `sculkworm-connect.jar` | Standalone Java 8 player client (`Main-Class` and `-javaagent`) | Windows ships `sculkworm-connect.exe` only: the relay and agent rely on Unix `SIGHUP` reloads and `0600` file-mode checks and are meant for Linux or macOS hosts. The Windows archive is cross-compiled against Windows UCRT (`x86_64-pc-windows-gnu`, no `x86_64-pc-windows-msvc` artifact is published). Download the archive and `SHA256SUMS`, verify the checksum, and install the binaries (for example into `/usr/local/bin` on Linux): ```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 [OPTIONS] or: sculkworm connect [OPTIONS] Commands: play Log in if needed and open a local Minecraft listener for login Log in to a closed route via browser redirect or device flow logout Revoke and remove a stored login (or all logins) ``` On macOS, verify with `shasum -a 256 -c SHA256SUMS --ignore-missing`; on Windows PowerShell, compare `(Get-FileHash sculkworm--x86_64-pc-windows-gnu.zip -Algorithm SHA256).Hash` against the matching line in `SHA256SUMS`, then unpack with `Expand-Archive`. To build from source instead (requires Rust `1.100.0` per `crates/sculkworm/rust-toolchain.toml`): ```sh cargo build --release --locked --bins ``` ## Container image Pull a published relay image (`:latest`, `:nightly`, or an exact version): ```sh docker pull ghcr.io/yellowumbrelladev/sculkworm:nightly ``` Or build the image locally from `crates/sculkworm`. ```sh docker build -t sculkworm crates/sculkworm ``` ```text => => naming to docker.io/library/sculkworm:latest ``` The image sets: - `SCULKWORM_LISTEN=0.0.0.0:25565` - `SCULKWORM_ROUTES_FILE=/etc/sculkworm/routes.json` - `SCULKWORM_API_ADDR=0.0.0.0:8080` - `SCULKWORM_STATE_FILE=/var/lib/sculkworm/state.json` It creates `/var/lib/sculkworm` owned by `nonroot:nonroot`, runs as `nonroot:nonroot`, and exposes ports `25565` (Minecraft relay) and `8080` (admin API when `SCULKWORM_TENANTS_FILE` is set). When `SCULKWORM_TENANTS_FILE` is unset, port `8080` is not bound. ## Keeping the admin API private The HTTP admin API does not terminate TLS and grants full route control over each tenant's domain scope to anyone holding that tenant's bearer key. - **Never publish port `8080` on a public interface.** Bind `SCULKWORM_API_ADDR` to `127.0.0.1:8080` (the binary default) or publish it only to `127.0.0.1:8080:8080` or a private container/Tailscale/WireGuard network. - If callers reach the admin API across a network boundary, terminate TLS and enforce network-level access controls in front of it. - To run in API-only mode inside Docker without a `routes.json` file, clear `SCULKWORM_ROUTES_FILE` (`-e SCULKWORM_ROUTES_FILE=`). ## Example routes file Save a `routes.json` file on the host with one entry per public hostname. ```json { "routes": { "survival.play.example": "10.0.0.10:25565", "creative.play.example": "10.0.0.11:25565" } } ``` ## Docker run Mount `routes.json` read-only at `/etc/sculkworm/routes.json` and publish port `25565`. ```sh docker run -d --name sculkworm \ --restart unless-stopped \ -p 25565:25565 \ -v "$PWD/routes.json:/etc/sculkworm/routes.json:ro" \ sculkworm ``` ```text ``` Inspect stderr logs to confirm startup. ```sh docker logs sculkworm ``` ```text level=info event=listening addr=0.0.0.0:25565 routes=2 ``` ## Docker run with the admin API and state volume Create a `tenants.json` file and a named Docker volume (or a host directory writable by uid/gid `65532`, `nonroot:nonroot`) for `/var/lib/sculkworm`. Publish port `8080` on loopback (`127.0.0.1:8080:8080`) or attach callers to a private Docker network. ```sh docker volume create sculkworm-state docker run -d --name sculkworm \ --restart unless-stopped \ -p 25565:25565 \ -p 127.0.0.1:8080:8080 \ -e SCULKWORM_ROUTES_FILE= \ -e SCULKWORM_TENANTS_FILE=/etc/sculkworm/tenants.json \ -v "$PWD/tenants.json:/etc/sculkworm/tenants.json:ro" \ -v sculkworm-state:/var/lib/sculkworm \ 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=0.0.0.0:8080 ``` ## Docker Compose Mount the directory containing `routes.json` and `tenants.json` rather than a single file when you plan to edit files atomically (for example with `mv`). A single-file bind mount in Docker stays pinned to the old inode when the host replaces the file, so a `SIGHUP` reload inside the container would keep reading the old contents. ```yaml services: sculkworm: image: sculkworm build: ./crates/sculkworm restart: unless-stopped ports: - "25565:25565" - "127.0.0.1:8080:8080" environment: SCULKWORM_LISTEN: "0.0.0.0:25565" SCULKWORM_ROUTES_FILE: "/etc/sculkworm/routes.json" SCULKWORM_TENANTS_FILE: "/etc/sculkworm/tenants.json" SCULKWORM_STATE_FILE: "/var/lib/sculkworm/state.json" SCULKWORM_API_ADDR: "0.0.0.0:8080" SCULKWORM_MAX_CONNECTIONS: "1024" volumes: - ./config:/etc/sculkworm:ro - sculkworm-state:/var/lib/sculkworm volumes: sculkworm-state: ``` Start the service and check its startup log. ```sh docker compose up -d sculkworm docker compose logs sculkworm ``` ```text level=info event=state_loaded routes=0 level=info event=listening addr=0.0.0.0:25565 routes=2 level=info event=api_listening addr=0.0.0.0:8080 ``` ## Deploying closed mode Closed mode adds a single TLS listener (`SCULKWORM_TUNNEL_LISTEN`) that splits traffic on one port by TLS ALPN: - ALPN `sculkworm`: tunnel sessions from `sculkworm-agent` and `sculkworm-connect`. - ALPN `http/1.1` or no ALPN: public HTTPS login and ticket endpoints (`/login/*`, `/tickets`, `/logout`, `/healthz`). Because both protocols share one port and one TLS certificate, publish `SCULKWORM_TUNNEL_LISTEN` on **TCP port `443`** (for example bind `0.0.0.0:8443` inside the container and publish `-p 443:8443`, or bind `0.0.0.0:443` directly with `CAP_NET_BIND_SERVICE`) so players and agents behind restrictive firewalls can reach it. Do **not** terminate TLS in an HTTP reverse proxy in front of `SCULKWORM_TUNNEL_LISTEN`: an HTTP proxy cannot pass through ALPN `sculkworm` frames. Use either direct port 443 exposure or an L4 TLS passthrough (SNI/TCP) proxy. ### State version 2 and downgrade note > **Upgrade and downgrade note:** Sculkworm reads state versions `1` and `2` and always writes version `2`. A version `1` file is loaded as open routes and is only rewritten as version `2` on the next API write. **Older Sculkworm binaries refuse a version `2` state file (`unsupported state version 2`).** Back up `SCULKWORM_STATE_FILE` before upgrading if you may need to roll back to a pre-closed-mode release. ### 1. Prepare certificates, `tenants.json`, and `secrets.json` (`0600`) Choose the relay's public hostname (for example `relay.example`), point its `A`/`AAAA` record at the relay host, and obtain a TLS certificate and private key (ACME sidecar such as certbot/lego writing PEM files to a shared volume, or an operator-supplied cert/key). Sculkworm reloads both PEM files in place on `SIGHUP` without dropping existing sessions. Generate a 32-byte login encryption key: ```sh head -c 32 /dev/urandom | basenc --base64url | tr -d '=' ``` ```text brN9rJKkXotCk5p7QxRcalnFpPmOt_cIO8KDB2kic8M ``` Create `tenants.json` (with the tenant that owns your closed-route domain) and `secrets.json` with mode `0600` (or `0400`). On Unix, Sculkworm refuses to start if group or world permission bits are set on `secrets.json`. Register `${SCULKWORM_PUBLIC_URL}/login/callback` as the redirect URI in each IdP application (for example `https://relay.example/login/callback`). ```sh mkdir -p config cat > config/tenants.json <<'EOF' { "tenants": [ { "name": "sculk", "key": "replace-with-a-random-key-of-at-least-32-chars", "domains": ["play.example"] } ] } EOF ``` ```sh umask 077 cat > config/secrets.json <<'EOF' { "login_keys": { "1": "brN9rJKkXotCk5p7QxRcalnFpPmOt_cIO8KDB2kic8M" }, "clients": { "discord-main": { "tenant": "sculk", "kind": "oauth2", "preset": "discord", "client_id": "1234567890", "client_secret_env": "SCULKWORM_DISCORD_SECRET" }, "example-oidc": { "tenant": "sculk", "kind": "oidc", "issuer": "https://accounts.example.com", "client_id": "sculkworm", "client_secret_env": "SCULKWORM_OIDC_SECRET" } } } EOF chmod 0600 config/secrets.json ``` When running the distroless container (`USER nonroot:nonroot`, uid/gid `65532`), ensure the secrets file is owned by `65532:65532` with mode `0400` or `0600` so only the relay process can read it. ### 2. Run the relay with closed mode enabled Every `client_secret_env` referenced in `secrets.json` must be set and non-empty when the relay loads the file (`SCULKWORM_DISCORD_SECRET` and `SCULKWORM_OIDC_SECRET` for the example above): ```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" \ /usr/local/bin/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 ``` (In Step 1 the sample files are written to `./config/`; copy them to `/etc/sculkworm/` or adjust the `SCULKWORM_*_FILE` paths above to match.) Example systemd unit for the relay: ```ini [Unit] Description=sculkworm Minecraft relay (open + closed mode) After=network-online.target Wants=network-online.target [Service] User=sculkworm Group=sculkworm EnvironmentFile=/etc/sculkworm/relay.env ExecStart=/usr/local/bin/sculkworm ExecReload=/bin/kill -HUP $MAINPID AmbientCapabilities=CAP_NET_BIND_SERVICE CapabilityBoundingSet=CAP_NET_BIND_SERVICE NoNewPrivileges=true Restart=on-failure RestartSec=2s [Install] WantedBy=multi-user.target ``` After renewing TLS certificates (for example from a certbot/lego deploy hook) or editing `secrets.json`, reload without downtime: ```sh systemctl reload sculkworm ``` ### 3. Create a closed route and mint an agent token Closed routes support `oidc` (generic `allow.claim` or sculk.network `allow.sculk_server`), `oauth2` (generic `allow.field` or the Discord preset with `allow.discord_guild`), and `fixed-list` authorizers; see [Closed routes: authorizer configuration](https://docs.sculk.network/nightly/sculkworm/tunnel.md#6-authorizer-configuration) and [Using sculk.network as an authorizer](https://docs.sculk.network/nightly/sculkworm/sculk-authorizer.md). Set `KEY` to the `sculk` tenant key from `tenants.json`, then create the closed route referencing the `example-oidc` client from `secrets.json`: ```sh KEY="replace-with-a-random-key-of-at-least-32-chars" 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"} ``` Mint the route's agent token (returned once) and save it on the Minecraft server host with mode `0600`: ```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_","id":"0d35c60dc471b165","created_at":"2026-11-27T09:06:26Z"} ``` ### 4. Start `sculkworm-agent` next to the Minecraft server Configure the Minecraft server to listen only on `127.0.0.1:25565` (`server-ip=127.0.0.1`) with no public firewall port opened. Start the agent with the token file (optionally pinning the relay's leaf SPKI with `--pin`, computed directly in `sha256/` form via `printf 'sha256/%s\n' "$(openssl x509 -in fullchain.pem -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64)"`): ```sh sculkworm-agent \ --relay https://relay.example \ --route friends.play.example \ --token-file /etc/sculkworm/agent.token \ --target 127.0.0.1:25565 ``` Confirm the agent is connected from the relay's admin API: ```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"}]} ``` ### 5. Player commands (`sculkworm-connect`) On a desktop with a browser, a player runs `play` (optionally `--add-server` while Minecraft is closed to add/update `friends.play.example -> 127.0.0.1:25565` in the existing `.minecraft/servers.dat`, or `--add-server=` / `--add-server=/servers.dat` for another directory): ```sh sculkworm-connect play friends.play.example --add-server ``` On a headless machine or SSH session, use `--device` (connect also falls back to the device flow automatically if opening a browser fails): ```sh sculkworm-connect login friends.play.example --relay https://relay.example --device ``` ```text Open https://relay.example/login/device on any device, sign in and type the code KCXB-SMXC. Logged in to friends.play.example as alex (subject user-alex-42, expires 2026-12-27T09:06:30Z) ``` Then start the local listener and connect Minecraft to `127.0.0.1:25565`: ```sh sculkworm-connect play friends.play.example --add-server ``` ```text 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 ``` To sign out and revoke the stored login on the relay: ```sh sculkworm-connect logout friends.play.example ``` ## Reload routes, secrets, and TLS certificates with SIGHUP On Unix systems, send `SIGHUP` to reload `SCULKWORM_ROUTES_FILE`, `SCULKWORM_SECRETS_FILE`, and the tunnel TLS certificate/key pair (`SCULKWORM_TLS_CERT_FILE` / `SCULKWORM_TLS_KEY_FILE`) without dropping active connections. Existing connections stay spliced to their original backend, existing tunnel sessions stay open, dynamic routes registered via the admin API remain untouched, and new connections or TLS handshakes pick up the reloaded files immediately. With Docker: ```sh docker kill --signal=HUP sculkworm ``` ```text sculkworm ``` With a direct process: ```sh kill -HUP ``` When the updated file parses cleanly, Sculkworm replaces the table and prints: ```text level=info event=reloaded routes=3 ``` When the updated file cannot be read or fails validation, Sculkworm keeps the previous route table in memory and prints an error line: ```text level=error event=reload_failed path="/tmp/sculkworm-doc-routes.json" error="invalid routes file: key must be a string at line 1 column 3" ``` ## Graceful shutdown Sculkworm handles `SIGTERM` and `SIGINT` (Ctrl-C). When either signal arrives, the process: 1. Logs `level=info event=shutdown`. 2. Closes the listening TCP socket so no new connections are accepted. 3. Waits up to 5 seconds (`DRAIN_TIMEOUT`) for active connection tasks to finish and release their permits. 4. Exits with status `0` once all active tasks finish or the 5-second drain window expires. ```sh kill -TERM ``` ```text level=info event=shutdown ``` ## Running behind another TCP proxy Sculkworm does not support the HAProxy PROXY protocol (v1 or v2). If an upstream proxy prepends a PROXY protocol header before the Minecraft Handshake packet, Sculkworm rejects the connection during Handshake parsing. A PROXY v1 or v2 header followed by enough bytes is logged as `reason=unexpected_packet_id`. If fewer bytes arrive than the header's first byte claims as a packet length, Sculkworm waits for more and logs `reason=timeout` or `reason=eof`. If you run Sculkworm behind a plain L4 TCP forwarder that does not add PROXY headers, routing still works because the Minecraft Handshake bytes are unchanged. However, the `peer=` field in Sculkworm logs will record the proxy IP address instead of the player IP address. ## Log events Sculkworm writes structured `key=value` log lines to stderr. Hostnames written to `host=` are sanitized before logging. An empty value is logged as ``, and any character that is not printable ASCII graphic or is `"` or `\` is replaced with `?`. ### Lifecycle and reload events | Level | Event | Fields | When emitted | | --- | --- | --- | --- | | `error` | `config_error` | `error` | An environment variable is missing or invalid at startup. Process exits `2`. | | `error` | `routes_error` | `error` | The routes file cannot be read or fails validation at startup. Process exits `2`. | | `error` | `tenants_error` | `error` | The tenants file cannot be read or fails validation at startup. Process exits `2`. | | `error` | `state_error` | `error` | The state file cannot be read or fails validation at startup. Process exits `2`. | | `warn` | `state_route_dropped` | `host`, `reason` | A persisted route was dropped at startup (`unknown_tenant`, `host_out_of_scope` or `target_not_allowed`). | | `info` | `state_loaded` | `routes` | Persisted dynamic routes were loaded from `SCULKWORM_STATE_FILE`. | | `error` | `tls_error` | `error` | `SCULKWORM_TLS_CERT_FILE` or `SCULKWORM_TLS_KEY_FILE` cannot be read, fails PEM parsing, or does not match at startup. Process exits `2`. | | `error` | `runtime_error` | `error` | The Tokio runtime fails to initialize. Process exits `1`. | | `error` | `startup_error` | `error` | Binding `SCULKWORM_LISTEN`, `SCULKWORM_API_ADDR`, or `SCULKWORM_TUNNEL_LISTEN` fails. Process exits `1`. | | `info` | `listening` | `addr`, `routes` | The Minecraft TCP listener is bound and accepting connections. | | `info` | `api_listening` | `addr` | The HTTP admin API listener is bound and accepting connections. | | `info` | `tunnel_listening` | `addr` | The TLS tunnel listener is bound and accepting connections. | | `info` | `reloaded` | `routes` | A `SIGHUP` reload succeeded and replaced the static routes (dynamic routes stay intact). | | `info` | `secrets_reloaded` | *(none)* | A `SIGHUP` reload succeeded and replaced the secrets config. | | `info` | `tls_reloaded` | *(none)* | A `SIGHUP` reload succeeded and replaced the tunnel TLS certificate and key. | | `error` | `reload_failed` | `path`, `error` | A `SIGHUP` reload failed. The previous static route table, secrets, or TLS certificate remains active. | | `info` | `shutdown` | *(none)* | `SIGTERM` or `SIGINT` was received and drain has started on relay, API, and tunnel listeners. | ### Running `sculkworm-agent` under systemd Run `sculkworm-agent` (or `sculkworm agent`) next to a Minecraft server listening on `127.0.0.1:25565`. Configure `RestartPreventExitStatus=3` so systemd does not restart an agent that exited cleanly with code `3` after being replaced by a newer agent (`GOAWAY replaced`), and `RestartPreventExitStatus=2 3` if you also want configuration/protocol-version errors to stop immediately: ```ini [Unit] Description=sculkworm tunnel agent After=network-online.target Wants=network-online.target [Service] User=minecraft Group=minecraft ExecStart=/usr/local/bin/sculkworm-agent --relay https://relay.example --route friends.play.example --token-file /etc/sculkworm/agent.token --target 127.0.0.1:25565 NoNewPrivileges=true Restart=on-failure RestartSec=2s RestartPreventExitStatus=2 3 [Install] WantedBy=multi-user.target ``` ### Closed-mode tunnel and login events | Level | Event | Fields | When emitted | | --- | --- | --- | --- | | `error` | `secrets_error` | `error` | `SCULKWORM_SECRETS_FILE` is missing, malformed, or has permissions looser than `0600`/`0400` at startup. Process exits `2`. | | `warn` | `closed_route_inactive` | `host`, `reason` | A closed route loaded from state cannot serve (`closed_mode_disabled`, `unknown_client`, or `client_tenant_mismatch`). | | `info` | `agent_token_minted` | `tenant`, `host`, `token_id` | A tenant minted an agent token via `POST /v1/routes/{host}/agent-token`. | | `info` | `agent_token_revoked` | `tenant`, `host` | A tenant deleted an agent token via `DELETE /v1/routes/{host}/agent-token`. | | `info` | `logins_revoked` | `tenant`/`route`, `host`/`lid`, `subject`, `scope` | Logins were revoked by admin API (`scope=route` or `subject=...`) or player `POST /logout` (`scope=logout`). | | `warn` | `tunnel_connection_rejected` | `reason=ip_limit`, `peer` | Source IP exceeded the concurrent tunnel TCP limit (`16`). | | `info` | `tunnel_tls_failed` | `peer`, `error` | TLS handshake on the tunnel listener failed. | | `info` | `tunnel_handshake_timeout` | `peer` | Client did not complete TLS + `HELLO` within `SCULKWORM_HANDSHAKE_TIMEOUT_SECONDS`. | | `warn` | `agent_unauthorized` | `route`, `peer` | An agent presented an unknown, revoked, or wrong-route token in `HELLO`. | | `info` | `agent_connected` | `route`, `session`, `token_id`, `peer`, `software` | An agent session was established. | | `info` | `agent_replacing` | `route`, `old_session`, `new_session` | A newer agent replaced an existing agent session (`GOAWAY replaced` sent to old session). | | `info` | `agent_disconnected` | `route`, `session`, `token_id`, `peer`, `reason` | An agent session closed. | | `info` | `connect_session` | `route`, `session`, `lid`, `subject`, `name`, `peer`, `software` | A connect session was established with a valid ticket. | | `info` | `stream_open` | `route`, `session`, `stream_id`, `subject`, `name`, `peer` | A player stream was bridged to the route's agent. | | `info` | `stream_closed` | `route`, `session`, `stream_id`, `bytes_up`, `bytes_down`, `peer` | A bridged player stream finished. | | `info` | `login` | `route`, `lid`, `subject`, `name`, `peer` (plus `flow=device`) | A player completed login and was admitted by the route's authorizer. | | `info` | `login_denied` | `route`, `reason`, `peer` (plus `subject`, `name` when known) | A player login failed or was rejected by the authorizer. | | `info` | `ticket` | `route`, `lid`, `subject`, `name`, `rotated`, `peer` | A short-lived tunnel ticket was minted by `POST /tickets`. | | `info` | `ticket_denied` | `route`, `lid`, `subject`, `reason`, `peer` | `POST /tickets` denied a request. | | `warn` | `idp_unavailable` | `route`/`client`, `detail`/`status`, `peer` | An outbound IdP request failed, timed out, or returned `5xx`. | | `warn` | `session_timeout` | *(none)* | A tunnel session received no frame for 45 seconds and was closed. | | `error` | `tls_pin_mismatch` | `got` / `error` | Agent or connect observed a leaf certificate SPKI that did not match any `--pin`. | ### Admin API events | Level | Event | Fields | When emitted | | --- | --- | --- | --- | | `info` | `api_unauthorized` | `peer` | A request to `/v1/*` failed bearer authentication. | | `info` | `route_put` | `tenant`, `host`, `target`, `created` | A tenant created (`created=true`) or updated/confirmed (`created=false`) a dynamic route. | | `info` | `route_deleted` | `tenant`, `host` | A tenant deleted a dynamic route. | | `error` | `persist_failed` | `tenant`, `host`, `error` | Writing `SCULKWORM_STATE_FILE` failed; the in-memory table was not modified. | ### Per-connection events | Level | Event | Fields | When emitted | | --- | --- | --- | --- | | `warn` | `accept_error` | `error` | `accept()` returned an OS error. The loop backs off for 100 ms before retrying. | | `warn` | `connection_rejected` | `reason=max_connections`, `peer` | `SCULKWORM_MAX_CONNECTIONS` permits are all in use. The socket closes immediately. | | `info` | `handshake_rejected` | `reason`, `peer` | The client disconnected, timed out, or sent an invalid Handshake packet. See [Rejection reasons](https://docs.sculk.network/nightly/sculkworm/protocol.md#rejection-reasons). | | `info` | `unknown_host` | `host`, `peer` | The parsed route key has no matching open or closed route. The socket closes with zero bytes sent. | | `info` | `closed_route_answer` | `host`, `intent`, `protocol`, `peer` | The parsed route key matched a closed route on the public Minecraft port; Sculkworm answered directly with status/pong or Login Disconnect without forwarding. | | `warn` | `backend_unreachable` | `host`, `target`, `peer`, `error` | DNS lookup failed, TCP connect timed out or was refused, or replaying the buffered Handshake bytes to the backend failed. | | `warn` | `backend_loop` | `host`, `target`, `peer` | The backend connection reached the relay's own listening port, so a route points back at the relay. The connection closes with zero bytes sent. | | `info` | `route` | `host`, `target`, `intent`, `protocol`, `peer` | The backend accepted the replayed Handshake bytes and bidirectional splicing began. | | `info` | `closed` | `host`, `target`, `bytes_up`, `bytes_down`, `peer` | The spliced connection ended. `bytes_up` includes the initial buffered Handshake bytes. | --- Source: https://docs.sculk.network/nightly/sculkworm/security.md # Security model This document describes the threat model, trust boundaries, and operational limits of Sculkworm as currently implemented. For the full wire-level and login-flow threat table for closed routes (agent, connect, and IdP-gated access), see [Closed routes: security considerations](https://docs.sculk.network/nightly/sculkworm/tunnel.md#9-security-considerations). ## Handshake hostnames are unauthenticated routing hints Minecraft Java Edition sends the Handshake packet (`0x00`) in plain text before authentication or encryption begins. Because Sculkworm routes exclusively on the Server Address field parsed by `HostField::parse` in `src/domain.rs`, any client that can reach the relay port can send any hostname string—including arbitrary `_o` (origin) or `_id` query parameters. - **Never treat the hostname, `_o`, or `_id` as a credential or proof of identity.** A player can connect to the relay IP directly and supply any route key listed in `routes.json`, regardless of which DNS name they actually resolved. - **Do not rely on hidden hostnames for access control.** Because every entry in `routes.json` is reachable from the single listening port, guessing or learning a routed hostname is enough to reach that backend. ## Open relay behavior (not access control) Open routes are Layer 4 hostname routes: every client that can reach `SCULKWORM_LISTEN` can reach every open backend configured in `routes.json` or registered as an open dynamic route. - Access control, whitelists, online-mode authentication, ban lists, and gameplay permissions for open routes belong on the backend Minecraft servers (or on a network firewall in front of the relay). - When a client sends a hostname that matches a **closed** dynamic route on `SCULKWORM_LISTEN`, `Relay::handle_connection` never forwards traffic: it replies with the status JSON (including `sculkworm.relay` and `sculkworm.route`, or omitting `sculkworm` when `SCULKWORM_PUBLIC_URL` is unset) or the Login Disconnect message from `src/closed.rs` and closes the socket after at most 2 seconds. This intentionally tells vanilla clients that the hostname is a closed server and which relay URL handles it; unknown hostnames still close with zero bytes written (`event=unknown_host`), and no authorizer details, tenant names, client ids, or agent state are exposed on the Minecraft port. - When a client sends a hostname that has no matching route, `Relay::handle_connection` in `src/relay.rs` logs `event=unknown_host` and closes the socket with zero bytes written. - When an open route's backend is unreachable or refuses the connection, Sculkworm logs `event=backend_unreachable` and closes the client socket with zero bytes written. ## Transport encryption passes through untouched Sculkworm does not add TLS and does not terminate, inspect, or strip Minecraft's own encryption. 1. `read_handshake` in `src/relay.rs` buffers bytes only until `parse_handshake` in `src/handshake.rs` finishes reading the initial Handshake packet (`0x00`). 2. `Relay::handle_connection` replays the exact buffered client bytes (including any trailing bytes that arrived in the same TCP read, such as Status Request or Login Start) to the backend and then calls `tokio::io::copy_bidirectional`. 3. Every subsequent packet—including Minecraft's RSA key exchange, AES-128-CFB8 stream encryption, compression, Configuration, and Play traffic—passes through opaque. Traffic between the relay and backend servers travels over plain TCP unless the Minecraft protocol itself negotiates online-mode encryption (which starts after Login Start and runs end-to-end between the Minecraft client and the backend server). Status pings and the initial Handshake and Login Start packets are unencrypted in the Minecraft protocol; run the relay-to-backend hop over a private network or tunnel you control. ## Log injection protection Because the Handshake host field is attacker-controlled UTF-8, `Relay::handle_connection` passes the route key through `sanitize_log_value` in `src/relay.rs` before writing `host=` to stderr: - An empty string is logged as ``. - Any byte or character that is not printable ASCII graphic (`0x21..=0x7E`), or that is `"` or `\`, is replaced with `?`. This blocks newline injection (forging fake `level=... event=...` lines), whitespace field-splitting, terminal escape sequences, and quote breaks in log parsers. Error strings (`error=`) and reload paths (`path=`) are formatted with Rust's `{:?}` debug escaping in `src/main.rs` and `src/relay.rs`. ## Resource and denial-of-service limits Sculkworm bounds memory and socket usage per connection and globally: - **Global concurrency cap (`SCULKWORM_MAX_CONNECTIONS`, default `1024`, bounds `1..=100000`).** Enforced with a `tokio::sync::Semaphore` (`global_permits`) in `Relay::serve` (`src/relay.rs`). Every accepted socket—including connections still waiting for a Handshake—holds one permit until the task exits. Excess connections are closed immediately with `level=warn event=connection_rejected reason=max_connections`. - **Handshake packet ceiling (`MAX_HANDSHAKE_PACKET_LEN = 4096` bytes, `src/handshake.rs`).** Any packet declaring a length `<= 0` or `> 4096` bytes is rejected immediately with `reason=bad_length` before buffering the body. VarInts longer than 5 bytes are rejected with `reason=varint_too_long`. Each `read_handshake` iteration reads into a fixed 4096-byte stack buffer (`READ_CHUNK_SIZE`). - **Handshake read deadline (`SCULKWORM_HANDSHAKE_TIMEOUT_SECONDS`, default `10` s, bounds `1..=120`).** Slow or idle connections that do not send a complete Handshake within the deadline are closed with `reason=timeout`. - **Backend connect deadline (`SCULKWORM_CONNECT_TIMEOUT_SECONDS`, default `5` s, bounds `1..=60`).** Bounds DNS resolution (`tokio::net::lookup_host`) and TCP connect across resolved addresses in `connect_target` (`src/relay.rs`). - **Graceful shutdown drain (`DRAIN_TIMEOUT = 5` seconds, `src/relay.rs`).** On `SIGTERM` or `SIGINT`, Sculkworm closes the listener and waits up to 5 seconds for active tasks to release their semaphore permits before exiting. ### Limits Sculkworm does not enforce On the public Minecraft port (`SCULKWORM_LISTEN`), Sculkworm has **no per-IP connection limit** and **no per-IP rate limit**. A single source IP that opens `SCULKWORM_MAX_CONNECTIONS` idle sockets (or long-lived connections) can exhaust the global semaphore for other clients. Put OS-level (`nftables`/`iptables`) or L4 firewall connection limits per source IP in front of Sculkworm when exposing it on the public internet. On the closed-mode tunnel listener (`SCULKWORM_TUNNEL_LISTEN`), Sculkworm enforces per-IP concurrent TCP limits, `HELLO` failure blocks, per-IP and per-login/code HTTP rate limits, and per-subject/session stream caps (see [Closed routes: rate limits and caps](https://docs.sculk.network/nightly/sculkworm/tunnel.md#92-rate-limits-and-caps)), while still sharing the global `SCULKWORM_MAX_CONNECTIONS` semaphore. ## Backend targets and SSRF boundary `Target::parse` in `src/routes.rs` accepts any syntactically valid `host:port` or `[ipv6]:port` with a non-zero port, including loopback (`127.0.0.1`), RFC 1918 addresses, cloud metadata IPs (`169.254.169.254`), and internal hostnames. Static routes come from the operator-controlled JSON file at `SCULKWORM_ROUTES_FILE`; dynamic open routes are bounded by each tenant's optional `allowed_targets` policy in `SCULKWORM_TENANTS_FILE` (closed routes have no `target` and are served only by an authenticated agent). Keep `SCULKWORM_ROUTES_FILE` and `SCULKWORM_TENANTS_FILE` writable only by the operator, and restrict outbound egress from the Sculkworm container to the network containing your Minecraft backends so a misconfigured target cannot reach unrelated internal services. ## PROXY protocol and player IP visibility Sculkworm does not parse or emit HAProxy PROXY protocol headers (v1 or v2): - **Inbound:** placing Sculkworm behind an upstream proxy that prepends PROXY protocol headers breaks Handshake parsing (`reason=unexpected_packet_id`, `reason=timeout`, or `reason=eof`). - **Outbound:** Sculkworm opens a plain TCP connection to each backend server, so every backend sees the **Sculkworm host or container IP** as the player's source IP address rather than the player's real IP. Because backends see Sculkworm's IP instead of each player's IP: - Do not rely on IP bans (`ban-ip`) on backend Minecraft servers behind Sculkworm; banning a player's IP on the backend will block every player routed through the relay. - Use account-based bans (UUID) and whitelists on backends, and enforce IP-level blocks or rate limits at the firewall in front of Sculkworm. - Sculkworm logs the TCP peer IP it saw in `peer=` on every connection event (`route`, `closed`, `unknown_host`, `handshake_rejected`, `backend_unreachable`, `connection_rejected`). ## Secrets file, agent tokens, and IdP request boundaries When closed mode is configured (`SCULKWORM_TUNNEL_LISTEN` and `SCULKWORM_SECRETS_FILE`): - **Secrets file permissions and isolation.** `SecretsConfig::from_file` in `src/auth/secrets.rs` refuses to load a secrets file on Unix unless its mode is `0600` or `0400`. IdP URLs, client ids, client secrets, and login keys live only in the operator-controlled secrets file; tenants can only reference a client by name, and only when the client's `tenant` matches the caller or is explicitly `"*"`. Probing another tenant's client name returns the same `422 invalid_authorizer` message (`is not in the secrets file`) as an unknown client. Client secrets and login keys are never written to `SCULKWORM_STATE_FILE`, never returned by the admin API, and redacted from `Debug` output. - **Agent tokens.** `POST /v1/routes/{host}/agent-token` generates 32 random bytes from the OS CSPRNG (`ring::rand::SystemRandom`), returns the raw `swa_` token once, and persists only its 16-hex `id`, `created_at`, and the lowercase hex SHA-256 of the full token string. On `HELLO`, the tunnel listener (`src/tunnel/listener.rs`) checks the `id` and SHA-256 in constant time (`subtle::ConstantTimeEq`) against the route's stored token; a token for one route is rejected (`status 3 unauthorized`) for any other route. Rotating or deleting a token sends `GOAWAY revoked` to the live agent session. Before registering the new agent session under the registry write lock (and before demoting any existing agent), the listener re-checks that the route is still closed and active and that the token still matches, refusing stale sessions with `GOAWAY revoked` or `GOAWAY route_changed`. - **TLS tunnel transport, ALPN split, and SPKI pinning (`src/tunnel/tls.rs`).** The tunnel listener accepts TLS 1.3 and TLS 1.2 (no plaintext fallback), splits connections by ALPN (`sculkworm` for the tunnel protocol, `http/1.1` or no ALPN for public HTTPS endpoints), and enforces a per-source-IP concurrent TCP cap (default `16`, closed before TLS) and a `HELLO` failure block (`10` failures per minute blocks the source IP for `10` minutes with status `6` before step 5, never burning a connect ticket). `sculkworm-agent` verifies the server certificate against the OS root store (or `--ca-file` exclusively), verifies the SNI hostname, requires ALPN `sculkworm`, and when `--pin sha256/` is passed verifies the leaf certificate's DER `SubjectPublicKeyInfo` SHA-256 in constant time (`event=tls_pin_mismatch` on mismatch). - **Outbound IdP HTTP rules (`src/auth/idp_http.rs`).** Every outbound request to an IdP (including OIDC discovery during `PUT /v1/routes/{host}`) requires HTTPS with the OS root store, enforces a 5-second total timeout, caps response bodies at 1 MiB, does not follow redirects (`3xx` fails as `http_`), and resolves DNS first to refuse loopback, RFC 1918 private, link-local (`169.254.0.0/16`, `fe80::/10`), CGNAT (`100.64.0.0/10`), unique local (`fc00::/7`), unspecified, broadcast, and multicast addresses unless `SCULKWORM_IDP_ALLOW_PRIVATE=1`. The connection dials the checked address directly so DNS cannot change between validation and connect. OIDC discovery requires `issuer` to match verbatim and requires `token_endpoint` and `userinfo_endpoint` to share the issuer's origin unless the operator listed `endpoints` explicitly in the secrets file. - **Sealed logins, PKCE loopback flow, OIDC, Discord preset, device flow, tickets, and per-`OPEN` re-checks (`src/auth/sealed.rs`, `src/auth/oauth2.rs`, `src/auth/oidc.rs`, `src/auth/public_http.rs`, `src/tunnel/connect.rs`).** IdP access and refresh tokens are encrypted with ChaCha20-Poly1305 (`ring`) using the relay's `login_keys` (`swl_...`) and AAD `sculkworm-login || header`; `sculkworm-connect` stores only this opaque blob in `logins.json` (`0600` on Unix, refusing looser modes; the default `sculkworm` config directory is created/tightened to `0700` and symlinks are refused, while pre-existing parent directories of custom `--logins-file` paths are left untouched). The login flow uses independent PKCE S256 challenges on both the connect-to-relay and relay-to-IdP hops, validates loopback `redirect_uri` strictly (`http://127.0.0.1:/callback` or `http://[::1]:/callback`), compares `state`, relay codes, device codes, user codes, CSRF tokens, and PKCE verifiers in constant time, and escapes all HTML interpolations with `Content-Security-Policy: default-src 'none'; ...`, `X-Content-Type-Options: nosniff`, and `Referrer-Policy: no-referrer`. OIDC clients cache validated discovery documents in memory for 24 hours, validate `iss`, `aud`, `exp`, `nonce`, and `sub` on the ID token obtained over TLS from the token endpoint, require userinfo `sub` to match, and evaluate `allow.claim` rules against string and string-array claims as well as `allow.sculk_server` rules against the live userinfo `sculk_servers` array (adding `sculk:servers` automatically and admitting only when an object has `id == ` and `is_player == true`, failing closed on missing, malformed, or non-array claims, revoked grants/401 responses, blocked subjects, or provider outages). The Discord preset fetches `users/@me` (`id`/`username`) and, when `allow.discord_guild` is set, adds the `guilds` scope and checks live membership via `users/@me/guilds` on login and every re-check (failing closed on any IdP error). The RFC 8628 device flow uses unambiguous 8-character codes (`BCDFGHJKLMNPQRSTVWXZ`), omits `verification_uri_complete`, ignores `user_code` query parameters on `GET /login/device`, enforces `__Host-swdev` double-submit CSRF cookie + `Sec-Fetch-Site: same-origin` + per-IP (IPv6 `/64`), per-code, and global miss brute-force rate limits on `POST /login/device/approve`, caps pending device codes both globally and per route, shows a phishing warning confirmation page before redirecting with `prompt=consent` (OIDC and Discord), binds `confirm=1` to `/login/callback` via a random `__Host-swdevcb` (`SameSite=Lax`) cookie verified in constant time (marking the code denied on mismatch and clearing the cookie on callback), and ensures each device code can only be approved once and consumed once. Every `POST /tickets` and every connect stream `OPEN` older than 60 seconds re-checks revocations and the live IdP (`503 idp_unavailable` / `RESET` code `7` on outage, `401 login_revoked` / `RESET` code `6` on revocation); revoking a subject or changing a route's authorizer immediately sends `GOAWAY revoked` and `RESET` code `6` to affected connect sessions. Concurrent refreshes per `lid` are coalesced (single flight) with a 5-minute in-memory rotated-token cache (kept separate from verified admission results) so rotating IdP refresh tokens are never reused. - **Log redaction.** Client secrets, login keys, agent tokens, tickets, sealed logins, relay codes, device codes, IdP access/refresh/ID tokens, PKCE verifiers, `state` values, and `Authorization` headers are never logged; log lines record `token_id`, `lid`, sanitized `route`/`subject`/`name`, `session`, and `peer`. - **What closed mode does not protect against.** Closed mode proves an IdP identity, not a Minecraft account: keep `online-mode=true` (and a whitelist if usernames matter) on the Minecraft server behind `sculkworm-agent`. It does not stop an admitted player from sharing their computer or login, does not hide offline-mode Minecraft traffic from the relay operator, and does not protect against a compromised IdP account. ## Legacy ping rejection `parse_handshake` in `src/handshake.rs` rejects connections starting with the 3-byte Minecraft 1.6 legacy Server List Ping prefix `FE 01 FA` with `reason=legacy_ping` and closes the socket without forwarding to any backend. A single leading `0xFE` byte is not rejected immediately because a modern 254-byte Handshake packet begins with the VarInt `FE 01`; shorter legacy pings (1 or 2 bytes) time out after `SCULKWORM_HANDSHAKE_TIMEOUT_SECONDS` with `reason=timeout`. --- Source: https://docs.sculk.network/nightly/sculkworm/protocol.md # Minecraft protocol Sculkworm parses only the first packet of a Minecraft Java Edition TCP connection, the serverbound Handshake packet (`0x00`). Once the packet is complete and a route matches, Sculkworm writes the exact buffered client bytes (including any trailing bytes that arrived in the same TCP read) to the backend and splices the two sockets for the lifetime of the connection. Because Sculkworm never parses packets after the Handshake, it works across protocol versions and does not interfere with online-mode encryption, compression, Configuration, or Play packets. The closed-mode tunnel between the relay, the agent, and connect uses its own framing, specified in [Closed routes](https://docs.sculk.network/nightly/sculkworm/tunnel.md#3-wire-protocol-relay-and-agent). On the public Minecraft port, closed routes are answered directly by the relay (`src/closed.rs`) as described below and in [What a vanilla Minecraft client sees](https://docs.sculk.network/nightly/sculkworm/tunnel.md#46-what-a-vanilla-minecraft-client-sees). ## Closed-route answers on the Minecraft port When the parsed route key matches a dynamic closed route (and no static route with the same hostname takes precedence), `Relay::handle_connection` never opens a backend socket. Instead it logs `level=info event=closed_route_answer host= intent= protocol= peer=` and answers directly from `src/closed.rs`: - **Status (`1`).** The relay reads one Status Request (`0x00`, empty payload), replies with a Status Response (`0x00`) whose `version.name` is `"sculkworm"`, `version.protocol` echoes the client's Handshake protocol number, `players` is `{"max":0,"online":0}`, `description.text` tells the player to run `sculkworm-connect play `, and `sculkworm` carries `{"relay":"","route":""}` (the `sculkworm` object is omitted when `SCULKWORM_TUNNEL_LISTEN` / `SCULKWORM_PUBLIC_URL` is unset, such as for an inactive persisted closed route). If the client then sends one Ping Request (`0x01` + 8 opaque bytes), the relay echoes it in a Pong Response (`0x01`), shuts down its write half, and closes after at most 2 seconds. - **Login (`2`) and transfer (`3`).** Without waiting for Login Start, the relay sends a Login Disconnect (`0x00`) with the JSON text component instructing the player to run `sculkworm-connect play ` and join `127.0.0.1`, shuts down its write half, and closes after at most 2 seconds. - **Unknown hosts.** Hostnames that match neither an open route nor a closed route still close immediately with zero bytes written (`event=unknown_host`). ## Handshake packet layout Every modern Minecraft Java Edition connection begins with a VarInt-framed Handshake packet: | Field | Wire type | Notes | | --- | --- | --- | | Packet Length | VarInt | Byte length of the remaining packet fields. Must be `1..=4096`. | | Packet ID | VarInt | Must be `0x00`. | | Protocol Version | VarInt | Signed 32-bit protocol number, logged as `protocol=`. | | Server Address | String (VarInt byte length + UTF-8 bytes) | Parsed by `HostField::parse` to derive the route key. | | Server Port | Unsigned Short (`u16`, big-endian) | Parsed from the packet; not used for routing. | | Intent (Next State) | VarInt | `1` (`status`), `2` (`login`), or `3` (`transfer`). | VarInts are decoded using 7 data bits per byte with the high bit (`0x80`) as the continuation flag, up to 5 bytes (35 bits). Sculkworm buffers incoming bytes in 4096-byte reads (`READ_CHUNK_SIZE`) until the full Handshake packet arrives or `SCULKWORM_HANDSHAKE_TIMEOUT_SECONDS` expires. A Handshake split across multiple TCP segments (even 1 byte per segment) is reassembled before routing. ## Size limits - **Maximum Handshake packet length (`MAX_HANDSHAKE_PACKET_LEN`).** `4096` bytes for the packet body (excluding the outer Packet Length VarInt). Any Packet Length `<= 0` or `> 4096` is rejected before reading the rest of the frame. This ceiling accommodates Minecraft 26.4 host strings (up to 1024 characters plus query parameters and Forge markers). - **VarInt length.** At most 5 bytes per VarInt. A 5th byte with its continuation bit set is rejected with `varint_too_long`. ## Host field grammar Sculkworm parses the UTF-8 Server Address string in three steps (see `src/domain.rs`). Parsing never returns a Handshake parse error. An empty or malformed host field produces an unroutable sentinel domain and fails lookup with `event=unknown_host`. ```text server_address := host_and_query [ "\0" fml_suffix ] host_and_query := raw_domain [ "?" query_pairs ] query_pairs := pair *( "&" pair ) pair := key [ "=" value ] ``` ### Step 1. Strip the FML suffix If the string contains a NUL byte (`\0`), Sculkworm splits on the first `\0`, sets `fml = true`, and discards everything from the first `\0` onward for routing (for example `alpha.example\0FML\0` or `relay.example?_o=beta.example%3A25565\0FML\0`). The original unmodified bytes are still replayed to the backend, so Forge and NeoForge backends receive the full FML marker. ### Step 2. Split the Minecraft 26.4 query string If the remaining string contains `?`, Sculkworm splits on the first `?` into `raw_domain` and `raw_query`. Each non-empty `&`-separated pair in `raw_query` is split on the first `=`: - `key=value` stores both `key` and `value` after percent-decoding. - `key` without `=` stores `key` with an empty string value. - Duplicate keys overwrite earlier values in the `BTreeMap`. Percent-decoding replaces `%HH` sequences (ASCII hex digits) with their byte values. If any `%` escape is truncated (`%2`), contains non-hex characters (`%ZZ`), or decodes to invalid UTF-8 (`%FF`), percent-decoding falls back and returns the raw input string unchanged for that component. ### Step 3. Normalize domains and pick the route key `Domain::parse` applies two normalization rules: 1. Lowercase the string with Unicode `to_lowercase()`. 2. Strip at most one trailing dot (`.`). A string with two trailing dots (`alpha.example..`) keeps one trailing dot (`alpha.example.`). If the result is empty (`""` or `"."`), `Domain::parse` returns `DomainError::Empty`. Sculkworm reads two named query parameters: - **`_o` (origin).** If `_o` is present, Sculkworm splits it on the last `:` and checks whether the trailing part parses as a `u16` port. If it does, the prefix before `:` is parsed with `Domain::parse` as the origin domain and the trailing number is recorded as the origin port. Otherwise the entire `_o` value is parsed with `Domain::parse` with `port = None`. If `Domain::parse` returns `Empty` (for example `_o=`), `origin` is `None`. - **`_id`.** Recorded on `HostField.id` if present. Sculkworm does not route on `_id` and does not parse `@` prefixes (`abc123@alpha.example` is treated as a literal domain string). The route key is `origin.domain` when `origin` is `Some`, and the primary `domain` otherwise. If the primary domain was empty and no valid `_o` was supplied, the route key is the empty unroutable sentinel, which cannot match any entry in `routes.json` and logs `event=unknown_host host=`. ### Normalization examples | Raw Server Address | FML | Origin (`_o`) | Route key | | --- | --- | --- | --- | | `alpha.example` | `false` | *(none)* | `alpha.example` | | `ALPHA.Example.` | `false` | *(none)* | `alpha.example` | | `relay.example?_o=beta.example%3A25565` | `false` | `beta.example` (port `25565`) | `beta.example` | | `relay.example?_o=BETA.example.` | `false` | `beta.example` (no port) | `beta.example` | | `relay.example?_o=` | `false` | *(none)* | `relay.example` | | `alpha.example?_id=abc123` | `false` | *(none)* | `alpha.example` | | `relay.example?_o=beta.example%3A25565\0FML\0` | `true` | `beta.example` (port `25565`) | `beta.example` | | `abc123@alpha.example` | `false` | *(none)* | `abc123@alpha.example` | ## Rejection reasons When reading or parsing the Handshake fails, Sculkworm closes the client connection without writing any bytes and logs: ```text level=info event=handshake_rejected reason= peer= ``` ### `HandshakeError` reasons (`src/handshake.rs`) | Reason string | Cause | | --- | --- | | `legacy_ping` | The connection starts with the three bytes `FE 01 FA`, the Minecraft 1.6 legacy Server List Ping. A first byte of `FE` alone is not rejected, because a packet length of 254 is the VarInt `FE 01`. A shorter legacy ping waits for the handshake timeout. | | `bad_length` | Packet Length is `<= 0`, Packet Length exceeds `4096`, or the Server Address string length VarInt is negative. | | `varint_too_long` | A VarInt spans more than 5 bytes (5th byte has bit `0x80` set). | | `unexpected_packet_id` | The first packet ID is not `0x00`. | | `truncated` | The framed packet ends before all required fields (Packet ID, Protocol Version, Server Address bytes, 2-byte Port, or Intent) are read. | | `bad_utf8` | The Server Address byte slice is not valid UTF-8. | | `bad_intent` | The Intent (Next State) VarInt is not `1` (`status`), `2` (`login`), or `3` (`transfer`). | ### Transport reasons (`src/relay.rs`) | Reason string | Cause | | --- | --- | | `timeout` | A complete Handshake packet did not arrive within `SCULKWORM_HANDSHAKE_TIMEOUT_SECONDS`. | | `eof` | The client closed the TCP connection before sending a complete Handshake packet. | | `io_error` | Reading from the client TCP socket returned an OS I/O error. | ## Verification status Reproduce all automated client checks from `crates/sculkworm` with: ```sh cargo build --locked npm --prefix tests/clients ci --no-audit --no-fund node tests/clients/run-all.mjs ``` - **Verified with `minecraft-protocol` (`1.68.0`) on Minecraft 1.21.4 (protocol `769`)**: - Status pings routed by hostname to distinct backends and zero-byte close on unknown hostnames (`tests/clients/offline-play.mjs`, plus Docker image walkthrough). - Offline-mode full login through Configuration into Play state, receiving `system_chat`, completing 3 keepalive roundtrips, and disconnecting cleanly (`tests/clients/offline-play.mjs`). - Online-mode encrypted login through the relay using `dev/mock-mojang` (`tests/clients/online-encrypted.mjs`): RSA-1024 Encryption Request/Response, `POST /session/minecraft/join`, `GET /session/minecraft/hasJoined`, bidirectional AES-128-CFB8 encryption, and encrypted Configuration + Play traffic (`system_chat` + 3 keepalive roundtrips). This proves the relay splices encrypted login and Play streams untouched, but does not replace testing with real Mojang `sessionserver.mojang.com`, Microsoft OAuth tokens, or a real vanilla launcher. - **Verified at the wire level and in Rust tests (from specification, not a real vanilla client)**: - Handshake framing, 1-byte TCP fragmentation, `MAX_HANDSHAKE_PACKET_LEN` (`4096`), 254-byte packet length VarInt (`FE 01`) vs `FE 01 FA` legacy ping rejection, Forge `\0FML\0` suffix stripping and byte-for-byte replay (`src/domain.rs`, `src/handshake.rs`, `tests/relay.rs`). - Minecraft 26.4 `_o` (origin, percent-encoded and literal `:port`) and `_id` query parameters, Transfer intent (`3`), 1024-character hosts, verbatim Handshake replay, and pre-26.4 SRV target rejection (`tests/clients/handshake-26.4-srv.mjs`). - Source for 26.4 format (checked 2026-11-26): Minecraft Wiki [Java Edition 26.4 Snapshot 1](https://minecraft.wiki/w/Java_Edition_26.4_Snapshot_1) and [Java Edition 26.4](https://minecraft.wiki/w/Java_Edition_26.4) — serverbound `minecraft:intention` host field supports URI-like `?k=v&...` percent-encoded parameters up to 1024 characters; `@` is parsed as `?_id=`; SRV redirection sends `?_o=:` with the resolved port in the packet port field. - Source for pre-26.4 SRV behavior (checked 2026-11-26): Minecraft Wiki [Java Edition protocol/Packets](https://minecraft.wiki/w/Java_Edition_protocol/Packets) (`MC-278651`) — Server Address is the name obtained after SRV resolution on Login (except 1.17), whereas Server List Ping sends the user-entered hostname. - **Not yet verified with a real vanilla / Prism Launcher Minecraft client** (see the [Real-client verification runbook](https://docs.sculk.network/nightly/sculkworm/verification.md#4-manual-prism-launcher-runbook)): - Online-mode encrypted login with a real Mojang/Microsoft account and vanilla client. - Minecraft 26.4 `_o` (origin) and `_id` Handshake host query parameters from a real 26.4 client. - What vanilla Minecraft Java clients older than 26.4 send in the Handshake host field after following a live DNS `SRV` record. --- Source: https://docs.sculk.network/nightly/sculkworm/tunnel.md # Closed routes: agent, connect and login tunnel (specification) Status: **specification, not implemented**. This page is the contract for the closed-mode tunnel. The implementer follows it as written; any deviation goes into the [decision log](#11-decision-log) in the same PR that makes it. Keywords: **must**, **must not**, **should** and **may** are used as in RFC 2119. All integers on the wire are unsigned and big-endian unless a field says otherwise. All strings are UTF-8. Times in JSON are RFC 3339 UTC strings (`2026-11-27T10:00:00Z`) unless a field name ends in `_at` inside a sealed or wire structure, where it is Unix seconds. ## Contents 1. [Overview](#1-overview) 2. [Terminology and invariants](#2-terminology-and-invariants) 3. [Wire protocol: relay and agent](#3-wire-protocol-relay-and-agent) 4. [Wire protocol: connect and relay](#4-wire-protocol-connect-and-relay) 5. [Login flow for connect](#5-login-flow-for-connect) 6. [Authorizer configuration](#6-authorizer-configuration) 7. [Admin API additions](#7-admin-api-additions) 8. [State and persistence changes](#8-state-and-persistence-changes) 9. [Security considerations](#9-security-considerations) 10. [Implementation](#10-implementation) 11. [Decision log](#11-decision-log) 12. [Open items that need the operator](#12-open-items-that-need-the-operator) ## 1. Overview Today every route is **open**: anyone who reaches the relay's Minecraft port and sends a matching hostname is spliced to the route's backend `host:port` (see [Minecraft protocol](https://docs.sculk.network/nightly/sculkworm/protocol.md) and [Security model](https://docs.sculk.network/nightly/sculkworm/security.md)). Closed mode adds a second kind of route: - The Minecraft server listens on `127.0.0.1` only and opens no inbound port. - **sculkworm-agent** runs next to it, dials **out** to the relay over TLS, and serves the player streams the relay sends it to the local server. - **sculkworm-connect** runs on the player's computer. The player logs in once in the browser with the route's identity provider (IdP); the login lasts 30 days. On every play session connect asks the relay for a short-lived **tunnel ticket**, opens a TLS tunnel to the relay with it, and carries the Minecraft TCP stream through it. The relay re-checks the player's permission at the IdP every time it mints a ticket. - The relay is the only OAuth/OIDC client. It holds the client secrets; they never leave it. Open routes keep working unchanged on the same relay. A vanilla client that connects to a closed route's hostname on the public Minecraft port gets a readable status line and disconnect message that tell the player to use connect ([4.6](#46-what-a-vanilla-minecraft-client-sees)). The relay gains one new listener, the **tunnel listener** (`SCULKWORM_TUNNEL_LISTEN`, TLS). It serves two things on one port, split by TLS ALPN: the tunnel protocol (ALPN `sculkworm`) for agents and connect, and the public HTTPS endpoints (ALPN `http/1.1` or no ALPN) for the login flow and tickets. The admin API stays on `SCULKWORM_API_ADDR` and is unchanged except for the additions in [section 7](#7-admin-api-additions). ### Player login, then play ```mermaid sequenceDiagram autonumber participant MC as Minecraft client participant C as sculkworm-connect participant B as Browser participant R as Relay participant I as IdP participant A as sculkworm-agent participant S as Minecraft server Note over C,I: Login, once every 30 days C->>R: Minecraft status ping to friends.play.example R-->>C: Status JSON with sculkworm.relay URL C->>B: Open relay /login/start with PKCE challenge and loopback redirect_uri B->>R: GET /login/start R-->>B: 302 to IdP authorize URL, relay state and relay PKCE B->>I: Player signs in and consents I-->>B: 302 to relay /login/callback with code B->>R: GET /login/callback R->>I: Exchange code with client secret, read userinfo R->>R: Evaluate the route authorizer R-->>B: 302 to 127.0.0.1 loopback with one-time relay code B->>C: GET /callback with code and state C->>R: POST /login/token with code and PKCE verifier R-->>C: Sealed login credential swl_, valid 30 days C->>C: Store it in logins.json with mode 0600 Note over MC,S: Play, every session MC->>C: TCP connect to 127.0.0.1:25565 C->>R: POST /tickets with the sealed login R->>I: Refresh token or userinfo, re-check permission R-->>C: Ticket swt_, single use, 30 seconds C->>R: TLS ALPN sculkworm, HELLO role connect, route, ticket R-->>C: SERVER_HELLO ok C->>R: OPEN stream 1 R->>A: OPEN stream with subject, name, player address A->>S: TCP connect to 127.0.0.1:25565 A-->>R: ACCEPT R-->>C: ACCEPT MC<<->>S: Minecraft bytes in DATA frames, unchanged end to end ``` ### Agent registration ```mermaid sequenceDiagram autonumber participant Op as Tenant service participant API as Relay admin API participant R as Relay tunnel listener participant A as sculkworm-agent Op->>API: PUT /v1/routes/friends.play.example mode closed with authorizer API-->>Op: 201 route Op->>API: POST /v1/routes/friends.play.example/agent-token API-->>Op: 201 token swa_, shown once, stored as SHA-256 Op->>A: Install the token in the agent config A->>R: TLS, verify relay certificate, ALPN sculkworm A->>R: HELLO role agent, route, token R->>R: Look up token id, constant-time compare SHA-256 alt Token valid for this route R-->>A: SERVER_HELLO ok with session id loop Every 15 seconds without traffic A->>R: PING R-->>A: PONG end else Invalid, revoked or other route R-->>A: SERVER_HELLO unauthorized, then close A->>A: Wait 5 minutes before retrying end ``` ## 2. Terminology and invariants | Term | Meaning | | --- | --- | | **Open route** | Today's route: hostname to backend `host:port`, no authentication. Default mode. | | **Closed route** | A route with `mode: "closed"` and an authorizer. It has no `target`; its backend is whatever its agent serves. | | **Agent** | `sculkworm-agent`, next to the Minecraft server. Holds one agent token for one route. | | **Connect** | `sculkworm-connect`, the player's CLI. Holds the player's sealed logins. | | **Authorizer** | The per-route rule that says which IdP identities may play ([section 6](#6-authorizer-configuration)). | | **Agent token** | `swa__`, minted by the admin API for one route. Authenticates an agent session. | | **Sealed login** | `swl_...`, a relay-encrypted blob that is the player's 30-day login for one route. Opaque to connect. | | **Ticket** | `swt_...`, a 30-second single-use credential minted from a sealed login after a fresh permission check. Opens one connect session. | | **Session** | One TLS connection on the tunnel listener after a successful `HELLO`. Agent session or connect session. | | **Stream** | One Minecraft TCP connection carried inside a session. | | **Subject** | The stable user id the IdP returns (`sub` claim, or the configured field for plain OAuth2). | Invariants. Every implementation and every test must keep these true: 1. **The relay is the only component that sees IdP client secrets.** They are read from the secrets file ([6.5](#65-secrets-file)), never written to the state file, never returned by any API, never logged, never sent to an agent or to connect. 2. **Connect never holds a usable IdP token.** IdP access and refresh tokens are stored only inside the sealed login, encrypted with a key only the relay has. The player cannot read or use them; a stolen sealed login is only useful through the relay, which re-checks permission and honours revocation. 3. **An agent token authorizes exactly one route**, the one it was minted for. A `HELLO` whose `route` differs from the token's route is `unauthorized`, even when both routes belong to the same tenant. 4. **A ticket authorizes exactly one connect session on exactly one route** and is consumed by the first `HELLO` that reaches the credential check ([3.2](#32-session-preface-hello-and-server_hello)), whether that `HELLO` then succeeds or not. 5. **Permission is checked at every tunnel start.** A tunnel start is every new player stream (`OPEN` on a connect session), not only every new session. Minting a ticket performs the IdP re-check ([5.7](#57-permission-re-check-at-every-tunnel-start)), and every `OPEN` repeats it unless the same login passed a check less than **60 seconds** earlier ([4.4](#44-connect-session-rules)). There is no grace period. 6. **Fail closed.** Any error in authentication, authorization, IdP contact or decoding denies access. 7. **The relay does not interpret Minecraft traffic after the Handshake.** Bytes inside streams pass through unchanged, including online-mode encryption and compression. The relay authenticates the IdP identity, not the Minecraft account ([9.4](#94-what-the-relay-does-not-protect-against)). 8. **Nothing crosses tenants.** A tenant's admin key can only see and change its own routes, tokens, agents and logins. Trust: | Component | Trusted for | Not trusted for | | --- | --- | --- | | Relay | Everything below; it is the root of trust. | — | | IdP | The identity it asserts for the subject. | Anything about Minecraft accounts. | | Agent | Serving its own route. | Any other route; anything it says about players. | | Connect | Nothing. It is the player's software. | Route choice beyond its ticket; any claim about identity. | | Minecraft client | Nothing. | The Handshake hostname (still an unauthenticated hint). | ## 3. Wire protocol: relay and agent ### 3.1 Transport - One TCP connection from the agent to the relay's tunnel listener, wrapped in **TLS 1.3 or 1.2** (1.3 preferred; the relay offers both, the agent must accept both). No plaintext fallback exists. - The agent sends **SNI** = the host of the relay URL and offers **ALPN `sculkworm`** (9 ASCII bytes). If the server does not select `sculkworm`, the agent must close the connection and treat it as a failed attempt. - **Certificate verification by the agent**, in this order: 1. **Roots.** By default the operating system's root store (`rustls-native-certs`). With `--ca-file ` the agent uses only the certificates in that file as roots instead (a self-signed relay certificate works when it is listed there: rustls accepts a self-signed end-entity certificate that is itself in the root store). 2. **Name.** The certificate must be valid for the SNI host. There is no option to skip this. 3. **Pin (optional).** With `--pin sha256/` (repeatable), the SHA-256 of the leaf certificate's DER `SubjectPublicKeyInfo` must equal one of the pins, in addition to steps 1 and 2. A mismatch fails the connection with `level=error event=tls_pin_mismatch`. Base64 is standard with padding, the format of HPKP and `curl --pinnedpubkey`. Pin test vector (P-256 key): ```text spki.der: 3059301306072a8648ce3d020106082a8648ce3d03010703420004347ca8c74ce3638b01474233972090ad94dcbedd1cad7841343743cb70c3f218f1fd67a51dc7756e25dc8ee4d2349e52c08be3d9d91816598c15e6148d0b7c03 pin: sha256/scUY6AoOIgMN0ItTzQXvQDoAjvk7zbfNJfPECDOtvB4= ``` Operators compute it in `sha256/` form with `printf 'sha256/%s\n' "$(openssl x509 -in cert.pem -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64)"`. - Connect uses the same transport and the same verification rules. ### 3.2 Session preface: HELLO and SERVER_HELLO Right after the TLS handshake the client (agent or connect) sends exactly one `HELLO`; the relay answers with exactly one `SERVER_HELLO`. Frames ([3.3](#33-frame-format)) follow only after a `SERVER_HELLO` with status `0`. `str16` means a 2-byte big-endian length followed by that many UTF-8 bytes. `HELLO` (client to relay): | Offset | Size | Field | Rules | | --- | --- | --- | --- | | 0 | 4 | magic | ASCII `SCWM` (`53 43 57 4d`). Anything else: close without a reply. | | 4 | 1 | min_version | Lowest protocol version the client speaks. `>= 1`. | | 5 | 1 | max_version | Highest version the client speaks. `>= min_version`. This spec defines version `1`. | | 6 | 1 | role | `1` agent, `2` connect. Anything else: status `2` `bad_hello`. | | 7 | 2 + n | route | `str16`, 1..=255 bytes. Normalized with `Domain::parse` before lookup. | | … | 2 + n | credential | `str16`, 1..=512 bytes. Agent: the agent token. Connect: the ticket. | | … | 2 + n | software | `str16`, 0..=64 bytes, for example `sculkworm-agent/0.4.0`. Logged after `sanitize_log_value`. | `SERVER_HELLO` (relay to client): | Offset | Size | Field | Rules | | --- | --- | --- | --- | | 0 | 4 | magic | ASCII `SCWM`. | | 4 | 1 | version | Version the relay chose: the highest version in `min_version..=max_version` it speaks. `0` when no version was agreed (status `1`, or a status sent before the version check). | | 5 | 2 | status | See the table below. | | 7 | 2 + n | detail | `str16`, 0..=1024 bytes. Status `0`: the session id (16 lowercase hex characters). Otherwise a human-readable message. | | Status | Name | When | Client behaviour | | --- | --- | --- | --- | | `0` | `ok` | Session established. | Start framing. | | `1` | `unsupported_version` | No common version. | Agent and connect print the detail and exit with code `2`. | | `2` | `bad_hello` | Malformed `HELLO`, bad role, field too long. | Treat as a bug: log and retry with backoff. | | `3` | `unauthorized` | Agent token unknown, revoked or for another route; ticket unknown, expired, already used or for another route. | Agent: wait 5 minutes. Connect: mint a new ticket once, then report to the player. | | `4` | `unknown_route` | Route does not exist or is not closed. | Report and stop. | | `5` | `agent_offline` | Connect only: no agent session for the route. | Connect answers the local Minecraft client with the offline message ([4.6](#46-what-a-vanilla-minecraft-client-sees)). | | `6` | `rate_limited` | A limit in [9.2](#92-rate-limits-and-caps) was hit. | Back off at least 30 seconds. | | `7` | `busy` | Relay at `SCULKWORM_MAX_CONNECTIONS` or shutting down. | Back off with the normal schedule. | **Check order.** The relay checks a `HELLO` in this order and answers with the first status that applies, so every implementation gives the same answer to the same input: 1. `magic` is `SCWM`; otherwise close without a reply. 2. A common version exists; otherwise status `1`. 3. Every length is in range, `role` is `1` or `2`, and no bytes follow `software`; otherwise status `2`. 4. The source IP is not blocked for `HELLO` failures and is under its tunnel connection cap ([9.2](#92-rate-limits-and-caps)); otherwise status `6`. **A ticket is not consumed at this step or before it.** 5. Credential: connect's ticket is looked up and deleted (consumed) here, then must be unexpired and bound to the `HELLO` route; the agent token's id must exist and its hash and route must match. Otherwise status `3`. 6. The route exists, is closed and is active ([section 8](#8-state-and-persistence-changes)); otherwise status `4`. 7. Connect only: the route has an agent session; otherwise status `5`. 8. Connect only: the subject is under its connect session cap for the route; otherwise status `6`. 9. The relay is not shutting down; otherwise status `7`. Every failure at steps 3, 5 and 6 counts as one `HELLO` failure for the source IP. Timing and size rules: - `SCULKWORM_HANDSHAKE_TIMEOUT_SECONDS` runs from TCP accept to a complete `HELLO` (TLS handshake included). When it expires the relay closes the connection silently. The relay never reads more than 844 bytes of `HELLO` (its maximum size: 7 fixed bytes plus three `str16` fields of at most 255, 512 and 64 bytes). - After any non-zero status the relay sends TLS `close_notify` and closes. - Agent and connect wait at most **10 seconds** from sending `HELLO` for a complete `SERVER_HELLO`, then close the connection and count a failed attempt. - **Version negotiation** is the `min_version`/`max_version` pair. A future version `2` client sends `min=1,max=2`; a version `1` relay answers `version=1` and both speak version 1. The ALPN id stays `sculkworm` across versions. Test vectors (the agent token is `swa_0123456789abcdef_AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8`, the ticket is `swt_ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj8`; spaces separate fields and are not on the wire): ```text hello.agent: 5343574d 010101 0014 667269656e64732e706c61792e6578616d706c65 0040 7377615f303132333435363738396162636465665f41414543417751464267634943516f4c4441304f4478415245684d554652595847426b6147787764486838 0014 7363756c6b776f726d2d6167656e742f74657374 hello.connect: 5343574d 010102 0014 667269656e64732e706c61792e6578616d706c65 002f 7377745f494345694979516c4a69636f4b536f724c4330754c7a41784d6a4d304e5459334f446b364f7a7739506a38 0016 7363756c6b776f726d2d636f6e6e6563742f74657374 server-hello.ok: 5343574d 01 0000 0010 30313233343536373839616263646566 server-hello.unsupported: 5343574d 00 0001 0025 72656c617920737065616b732070726f746f636f6c2076657273696f6e73203120746f2031 server-hello.unauthorized: 5343574d 01 0003 0013 696e76616c6964206167656e7420746f6b656e ``` `hello.agent` is route `friends.play.example`, the agent token above and software `sculkworm-agent/test`. `server-hello.unsupported` carries the detail `relay speaks protocol versions 1 to 1`; `server-hello.unauthorized` carries `invalid agent token`. ### 3.3 Frame format After `SERVER_HELLO` status `0`, both directions are a sequence of frames. Every frame has an 8-byte header: | Offset | Size | Field | Rules | | --- | --- | --- | --- | | 0 | 1 | type | Frame type, table below. Unknown type: connection error `protocol_error`. | | 1 | 1 | flags | Must be `0` in version 1. Non-zero: connection error `protocol_error`. | | 2 | 2 | length | Payload length in bytes, `0..=16384`. Larger: connection error `protocol_error`. | | 4 | 4 | stream_id | `0` for session frames, `1..=4294967295` for stream frames. | | 8 | length | payload | As defined per type. | | Type | Name | stream_id | Payload | Direction | | --- | --- | --- | --- | --- | | `1` | `OPEN` | non-zero | Agent session: `subject` str16 (1..=255), `name` str16 (0..=255), `peer` str16 (0..=64). Connect session: empty. | Opener to peer | | `2` | `ACCEPT` | non-zero | Empty. | Answer to `OPEN` | | `3` | `DATA` | non-zero | Stream bytes, `1..=16384`. | Both | | `4` | `WINDOW` | non-zero | `increment` u32, `1..=2147483647`. | Both | | `5` | `CLOSE` | non-zero | Empty. Half-close: the sender sends no more `DATA` on this stream. | Both | | `6` | `RESET` | non-zero | `code` u16, `message` str16 (0..=1024). Aborts the stream in both directions. | Both | | `7` | `PING` | `0` | Exactly 8 opaque bytes. | Both | | `8` | `PONG` | `0` | The 8 bytes of the `PING` it answers. | Both | | `9` | `GOAWAY` | `0` | `code` u16, `message` str16 (0..=1024). | Both | A payload whose length does not match its type's layout (for example `WINDOW` with 3 bytes, `ACCEPT` with any bytes, a `str16` running past the payload, trailing bytes after the last field) is a connection error `protocol_error`. A stream frame with `stream_id` 0 or a session frame with a non-zero `stream_id` is a connection error `protocol_error`. A **connection error** means: send `GOAWAY` with the code, then close the TLS connection; every open stream of the session is reset. A **stream error** means: send `RESET` with the code on that stream only. Frame test vectors (header, then payload fields): ```text frame.open-agent: 0100002c00000001 0011 3830333531313130323234363738393132 0004 616c6578 0011 3230332e302e3131332e373a3531323334 frame.open-connect: 0100000000000001 frame.accept: 0200000000000001 frame.data: 0300002800000001 10008106093132372e302e302e3163dd02 160004416c657800000000000000000000000000000000 frame.window: 0400000400000001 00010000 frame.close: 0500000000000001 frame.reset: 0600001600000003 0001 0012 636f6e6e656374696f6e2072656675736564 frame.ping: 0700000800000000 0001020304050607 frame.pong: 0800000800000000 0001020304050607 frame.goaway-normal: 0900000400000000 0000 0000 frame.goaway-replaced: 0900002a00000000 0006 0026 616e6f74686572206167656e7420636f6e6e656374656420666f72207468697320726f757465 ``` - `frame.open-agent`: stream 1, subject `80351110224678912`, name `alex`, peer `203.0.113.7:51234`. - `frame.data`: stream 1 carrying a Minecraft Handshake (protocol 769, host `127.0.0.1`, port 25565, intent login) followed by Login Start for `Alex` with a zero UUID, exactly as the local client sent them to connect. - `frame.window`: stream 1, increment 65536. - `frame.reset`: stream 3, code `1` `connect_failed`, message `connection refused`. - `frame.goaway-replaced`: code `6` `replaced`, message `another agent connected for this route`. ### 3.4 Streams - **Who opens.** In an agent session only the relay opens streams. In a connect session only connect opens streams. An `OPEN` from the wrong side is a connection error `protocol_error`. - **Stream ids.** The opener uses `1` for its first stream and exactly the previous id plus one for each new stream; ids are never reused within a session. An `OPEN` with any other id is a connection error `protocol_error`. When the next id would exceed `4294967295`: in an agent session the relay sends `GOAWAY` `normal` and the agent reconnects as after any lost session; in a connect session connect sends `GOAWAY` `normal` and opens a new session with a new ticket. - **Lifecycle.** `OPEN` → `ACCEPT` (or `RESET`) → `DATA`/`WINDOW` in both directions → each side sends `CLOSE` once when its read side of the TCP connection reaches EOF. A stream is finished when both `CLOSE`s were sent and received, or when one `RESET` was sent or received. After that its id is dead. Frames for a dead id are discarded without a reply (the peer may have sent them before it saw the `RESET` or `CLOSE`). Any frame other than `OPEN` for an id that was never opened (greater than the highest id the opener has used) is a connection error `protocol_error`. - **Before `ACCEPT`.** The opener may send `DATA` right after `OPEN` without waiting for `ACCEPT` (this keeps the Minecraft Handshake on the first round trip), counted against the initial window. - **Agent on `OPEN`.** The agent connects to its configured local target with a 5-second timeout. On success it sends `ACCEPT`, then writes any buffered `DATA` in order. On failure it sends `RESET` code `1` `connect_failed` with the OS error text. - **Relay bridging.** For each connect stream the relay first performs the permission check of [4.4](#44-connect-session-rules), then opens one stream on the route's agent session and forwards `DATA`, `CLOSE` and `RESET` between the two in order. `OPEN` from connect becomes `OPEN` to the agent with the subject and name of the session's login and the player's TCP peer address as seen by the relay. The relay sends `ACCEPT` to connect only when the agent's `ACCEPT` arrives, and forwards the agent's `RESET` if that comes instead. `WINDOW` is per hop: the relay never forwards a `WINDOW` frame; it grants window on each hop by the rule of [3.5](#35-flow-control). - **Waiting for `ACCEPT`.** Connect waits at most **10 seconds** after `OPEN` for `ACCEPT`; then it sends `RESET` code `0` `cancel` and answers the local client as in [4.6](#46-what-a-vanilla-minecraft-client-sees). The relay applies the same 10 seconds to the agent and then resets both halves with code `1` `connect_failed`. - **Concurrency caps.** At most 8 open streams per connect session and 1024 per agent session. An `OPEN` beyond the cap is answered with `RESET` code `5` `refused`. - **Stream errors** (`RESET` code `4` `protocol_error` on that stream): `DATA` after the peer's `CLOSE` on that stream; a second `CLOSE` from the same side; `ACCEPT` sent by the opener; a second `ACCEPT`; `DATA` from the accepting side before its `ACCEPT`. `ACCEPT` for a finished id is discarded like any frame for a dead id. - **Unknown codes.** A `RESET` with a code not in the table below is handled as `0` `cancel`; a `GOAWAY` with an unknown code is handled as `2` `internal_error`. Both are logged with the numeric code. - **`PONG`** that answers no outstanding `PING` is ignored. Stream `RESET` codes: | Code | Name | Meaning | | --- | --- | --- | | `0` | `cancel` | The sender no longer wants the stream (for example the local TCP socket errored). | | `1` | `connect_failed` | The agent could not connect to the local Minecraft server. | | `2` | `agent_gone` | The relay lost the agent session that carried the other half of this stream. | | `3` | `flow_control` | The peer sent more `DATA` than its window allowed. | | `4` | `protocol_error` | A stream-level rule above was broken. | | `5` | `refused` | Stream cap reached, or the session is draining after `GOAWAY`. | | `6` | `revoked` | The player's access was revoked while the stream was open ([7.6](#76-revoke-player-logins)), or the permission check of a new stream failed with `login_expired`, `login_revoked`, `login_invalid` or `not_admitted`. The message is the error message of [5.7](#57-permission-re-check-at-every-tunnel-start). | | `7` | `idp_unavailable` | The permission check of a new stream could not reach the IdP ([5.7](#57-permission-re-check-at-every-tunnel-start) step 4). | ### 3.5 Flow control Every stream has an independent **send window** in each direction. - The initial window is **262144 bytes** (256 KiB) per direction for every stream, fixed in version 1. - A sender must not have more `DATA` payload bytes outstanding than its current window. Each `DATA` frame decreases the window by its payload length; each `WINDOW` frame received increases it by `increment`. - A receiver **consumes** bytes when it has written them to the next hop (the local TCP socket for agent and connect, the other session's stream for the relay). Once it has consumed at least **65536 bytes** on a stream since its last `WINDOW` for that stream, it sends `WINDOW` with `increment` = the exact number of bytes consumed since then. - A window above `2147483647` after an increment, or `DATA` beyond the window, is a stream error `flow_control`. - `OPEN`, `ACCEPT`, `CLOSE`, `RESET`, `PING`, `PONG`, `GOAWAY` and `WINDOW` are not flow-controlled. - **Relay memory bound.** Because the relay only grants window when it has forwarded the bytes, it buffers at most 256 KiB per stream per direction. The relay must not read from a session faster than it can queue, but it must keep reading control frames: a stream blocked on window never blocks other streams of the same session. - **Write scheduling.** Control frames (`PONG`, `WINDOW`, `RESET`, `GOAWAY`, `PING`) are written before queued `DATA`. `DATA` is written round-robin across streams, one frame per stream per turn. ### 3.6 Keepalive - Each side sends `PING` when it has **received** no frame for **15 seconds**. The 8 payload bytes are chosen by the sender (a counter is fine). - On `PING` a side answers `PONG` with the same 8 bytes, ahead of queued `DATA`. - Each side closes the connection when it has received **no frame at all for 45 seconds**, logging `event=session_timeout`. It does not send `GOAWAY` first. - TCP keepalive is not relied on. `TCP_NODELAY` is set on both ends. ### 3.7 GOAWAY `GOAWAY` means: the sender will accept no new `OPEN` and will open no new stream. Streams already open continue until they finish. The sender closes the connection when its last stream finishes, or 30 seconds after `GOAWAY`, whichever comes first (`5` seconds when the relay is shutting down, matching its drain timeout). **`replaced` and `session_expired` are the exceptions:** they have no time limit; the sender closes the session only when its last stream finishes, so players on the old agent or on an expired connect session are never cut off. `revoked` closes the session right away, as does `protocol_error`. | Code | Name | Sent by | When | | --- | --- | --- | --- | | `0` | `normal` | Any | Clean shutdown or stream ids exhausted. | | `1` | `protocol_error` | Any | A connection error from [3.3](#33-frame-format) or [3.4](#34-streams). Close right away. | | `2` | `internal_error` | Any | Unexpected failure. | | `3` | `revoked` | Relay | The agent token or the player's login was revoked. Every open stream is reset with code `6`; close right away. | | `4` | `session_expired` | Relay | A connect session reached its maximum age ([4.4](#44-connect-session-rules)). | | `5` | `route_changed` | Relay | The route was deleted or switched to open mode. Every open stream is reset; close right away. | | `6` | `replaced` | Relay | A newer agent session for the same route was established ([3.8](#38-reconnect-backoff-and-agent-replacement)). | ### 3.8 Reconnect, backoff and agent replacement - The agent keeps exactly one session to the relay. When it is lost (TLS error, timeout, EOF, or any `GOAWAY` other than `replaced`) the agent reconnects with **full-jitter exponential backoff**: wait a uniformly random time in `[0, b]` where `b` starts at 1 second, doubles after each failed attempt and is capped at **60 seconds**. A session that stayed up for 60 seconds resets `b` to 1 second. - `SERVER_HELLO` status `3` `unauthorized` waits a fixed **5 minutes** and logs `level=error event=agent_unauthorized`. Status `1` exits with code `2`. - **One agent session per route.** When an agent authenticates for a route that already has a session, the new session becomes the route's agent at once: new streams go to it, and the old session receives `GOAWAY` `replaced` and keeps its open streams until they finish. This lets an operator restart or move the agent without cutting players on the old process off immediately. - **An agent that receives `GOAWAY` `replaced`** logs `level=error event=agent_replaced`, keeps serving its open streams until the relay closes the session, then **exits with code `3` and does not reconnect**. Two agents configured with the same token would otherwise replace each other forever. Service managers must not restart on exit code `3` (systemd: `RestartPreventExitStatus=3`). - **Agent disconnect with live streams.** Minecraft TCP state cannot move to another session. When an agent session is lost, the relay resets every bridged connect stream with `RESET` code `2` `agent_gone`; connect then closes the local TCP socket (the player sees "Connection lost"). New `OPEN`s on connect sessions of that route are answered with `RESET` code `2` until an agent is back; new connect `HELLO`s get status `5` `agent_offline`. - **Relay restart.** All sessions drop. Agents reconnect with the backoff above. Tickets in memory are lost; connect mints a new one on the next play (sealed logins survive restarts because the login keys are on disk). ## 4. Wire protocol: connect and relay ### 4.1 Choosing the route The route is the **explicit `route` field of `HELLO`**, not the hostname inside the Minecraft Handshake. The local Minecraft client connects to `127.0.0.1`, so its Handshake names connect's listener, not the server (see `frame.data`). Connect forwards the Handshake bytes unchanged; the Minecraft server behind the agent sees `127.0.0.1` as the server address, as it would for a local connection. The relay checks that the `HELLO` route equals the route the ticket was minted for, after `Domain::parse` normalization on both sides. A mismatch is status `3`. ### 4.2 Discovering the relay `sculkworm-connect play ` needs the relay URL of the route: 1. If `--relay ` is given, use it. 2. Else, if `logins.json` has an entry for the route, use its `relay`. 3. Else, send a Minecraft status ping (protocol `769`, intent `1`) to `:` (port default `25565`; no SRV lookup in version 1) and read the `sculkworm.relay` string from the status JSON ([4.6](#46-what-a-vanilla-minecraft-client-sees)). The URL must be `https://`. Connect prints it and asks `Log in through https://relay.example? [y/N]` before the first login, because the status ping is not authenticated ([9.1](#91-threat-model)). `--yes` skips the prompt. ### 4.3 Tunnel ticket - **Format:** `swt_` followed by the unpadded base64url encoding of 32 random bytes from the OS CSPRNG (47 ASCII characters in total). - **TTL:** 30 seconds from minting. - **Single use:** the relay deletes the ticket when a `HELLO` reaches step 5 of the check order in [3.2](#32-session-preface-hello-and-server_hello), before checking expiry or route. A `HELLO` refused earlier (bad version, malformed, rate-limited) does not consume it. A second use is status `3`. - **Binding:** the ticket records the route, the sealed login's login id, the subject and the display name. It is valid only for that route. - **Storage:** relay memory only, keyed by SHA-256 of the ticket string. At most 10000 live tickets; minting beyond that is `503 busy`. Expired tickets are swept every 10 seconds. - **Minting:** `POST /tickets` ([5.6](#56-public-http-endpoints)), which performs the permission re-check of [5.7](#57-permission-re-check-at-every-tunnel-start). ### 4.4 Connect session rules - Connect opens a session lazily, when the first local Minecraft TCP connection arrives, and reuses it for further local connections (one stream each; the server list ping and the join are two streams). It closes the session when the session has had no open stream for **60 seconds**. - **Permission check on every `OPEN`.** The relay keeps, per connect session, the login the ticket was minted from and the time of the last successful permission check for that login id (minting the ticket counts as one). On each `OPEN` it runs [5.7](#57-permission-re-check-at-every-tunnel-start) steps 2 to 5 for that login unless the last successful check is less than **60 seconds** old. On failure it answers `RESET` code `6` `revoked` or `7` `idp_unavailable` and opens nothing towards the agent. Refreshed IdP tokens go into the login cache of [5.7](#57-permission-re-check-at-every-tunnel-start) and reach connect with its next ticket. - A connect session lives at most **12 hours**. Then the relay sends `GOAWAY` `session_expired`; open streams continue, and connect mints a new ticket for the next local connection. The per-`OPEN` check is what enforces revocation; the 12-hour cap bounds how long one ticket's binding (route, login id) is trusted. - When a route's `authorizer_id` changes, the relay sends `GOAWAY` `revoked` to every connect session of that route and resets their open streams with code `6`: logins made under the old authorizer are no longer valid ([5.4](#54-sealed-login)). - **Timeouts in connect:** 10 seconds for `SERVER_HELLO` ([3.2](#32-session-preface-hello-and-server_hello)), 10 seconds for `ACCEPT` ([3.4](#34-streams)), and **15 seconds** for each HTTP request to the relay (`/tickets`, `/login/token`, `/login/device`, `/logout`), after which the request counts as failed and connect reports `the relay did not answer`. - Connect sends `OPEN` with an empty payload, then `DATA` with the bytes it read from the local socket, including the Handshake. ### 4.5 Connect's local listener - Default `127.0.0.1:25565`, configurable with `--listen `. If the port is taken, connect exits with code `2` and a message naming `--listen`. Connect refuses a non-loopback address unless `--listen-any` is given. - Connect reads the local Handshake before opening a stream (with `parse_handshake` from `src/handshake.rs`, 10 second timeout) so it knows the intent if it must answer by itself. - `--add-server[=]` adds or updates an entry in Minecraft's `servers.dat`: bare `--add-server` targets the OS default `.minecraft` directory (never consuming the next argument), while `--add-server=` targets an existing Minecraft directory (`--add-server=`) or a `servers.dat` file (`--add-server=/servers.dat`), expanding a leading `~` or `~/` (`~\` on Windows) against `HOME` (`USERPROFILE` on Windows). It never creates directories, refuses existing files not named `servers.dat`, rejects non-regular files and files over 4 MiB before reading, and follows a symlinked `servers.dat` in place (performing the lock, temp-file write, permission copy, and rename in the resolved target's directory). Every entry whose `name` matches the route has its `ip` updated to the listen address (rewriting unspecified bind addresses `0.0.0.0` / `[::]` to loopback `127.0.0.1` / `[::1]` with the same port). `servers.dat` is uncompressed NBT (root compound, `servers` list of compounds with string `name`, string `ip`). Connect writes it atomically (temp file and rename) under a mandatory exclusive advisory lock, cleaning up stale sibling temp files while holding the lock, and keeps every other entry and field byte for byte. Minecraft holds the server list in memory and writes it back when edited in game, so run `--add-server` while Minecraft is closed. ### 4.6 What a vanilla Minecraft client sees When a Minecraft client connects to the relay's **public Minecraft port** with the hostname of a **closed** route, the relay never forwards anything. It answers by itself, based on the Handshake intent: - **Status (`1`).** The relay reads the Status Request (`01 00`), answers with a Status Response, then answers one Ping Request with a Pong Response carrying the same 8 bytes, then closes. `version.protocol` echoes the protocol number of the client's Handshake, so the client does not show "incompatible version". `sculkworm.relay` is the relay's `SCULKWORM_PUBLIC_URL` and `sculkworm.route` the normalized route. - **Login (`2`) and transfer (`3`).** The relay sends a Login Disconnect (packet `0x00` in the login state, one JSON text component string) and closes. It does not wait for Login Start. Exact JSON (no whitespace, keys in this order, `\n` is the JSON escape): ```text status: {"version":{"name":"sculkworm","protocol":769},"players":{"max":0,"online":0},"description":{"text":"Closed server: join it with sculkworm-connect\nsculkworm-connect play friends.play.example"},"sculkworm":{"relay":"https://relay.example","route":"friends.play.example"}} login: {"text":"friends.play.example only admits players who log in with sculkworm-connect.\nRun: sculkworm-connect play friends.play.example\nThen join 127.0.0.1 in Minecraft."} offline: {"text":"friends.play.example is offline: its server is not connected to the relay."} ``` Packet bytes (Minecraft VarInt length, VarInt packet id, then fields; spaces separate packets): ```text mc.client-status: 1b00810614667269656e64732e706c61792e6578616d706c6563dd01 0100 0901000001a217ba1200 mc.status-response: 9202008f027b2276657273696f6e223a7b226e616d65223a227363756c6b776f726d222c2270726f746f636f6c223a3736397d2c22706c6179657273223a7b226d6178223a302c226f6e6c696e65223a307d2c226465736372697074696f6e223a7b2274657874223a22436c6f736564207365727665723a206a6f696e2069742077697468207363756c6b776f726d2d636f6e6e6563745c6e7363756c6b776f726d2d636f6e6e65637420706c617920667269656e64732e706c61792e6578616d706c65227d2c227363756c6b776f726d223a7b2272656c6179223a2268747470733a2f2f72656c61792e6578616d706c65222c22726f757465223a22667269656e64732e706c61792e6578616d706c65227d7d mc.pong-response: 0901000001a217ba1200 mc.client-login: 1b00810614667269656e64732e706c61792e6578616d706c6563dd02 160004416c657800000000000000000000000000000000 mc.login-disconnect: ae0100ab017b2274657874223a22667269656e64732e706c61792e6578616d706c65206f6e6c792061646d69747320706c61796572732077686f206c6f6720696e2077697468207363756c6b776f726d2d636f6e6e6563742e5c6e52756e3a207363756c6b776f726d2d636f6e6e65637420706c617920667269656e64732e706c61792e6578616d706c655c6e5468656e206a6f696e203132372e302e302e3120696e204d696e6563726166742e227d mc.offline-disconnect: 5700557b2274657874223a22667269656e64732e706c61792e6578616d706c65206973206f66666c696e653a2069747320736572766572206973206e6f7420636f6e6e656374656420746f207468652072656c61792e227d ``` `mc.client-status` is what the client sends (Handshake for `friends.play.example:25565` intent 1, Status Request, Ping Request with payload `1795694400000`); the relay answers `mc.status-response` then `mc.pong-response`. `mc.client-login` is Handshake intent 2 plus Login Start; the relay answers `mc.login-disconnect`. **Connect** answers the local client by itself in two cases, with the same packet shapes: - `SERVER_HELLO` status `5` or `RESET` code `2` before any `DATA` came back: intent login gets `mc.offline-disconnect`; intent status gets a Status Response whose `description.text` is the offline text and which has no `sculkworm` key. - Any other failure before the stream is accepted (no login, ticket refused, IdP down): intent login gets a Login Disconnect whose text is the error message connect also prints in its terminal; status gets the same text as `description.text`. After the relay or connect has written its reply it shuts down its write side and closes the socket after at most 2 seconds. ## 5. Login flow for connect ### 5.1 Choice: loopback redirect, device flow as fallback Connect uses an **OAuth-style authorization code flow between connect and the relay**, with a **loopback redirect** (`http://127.0.0.1:/callback`, RFC 8252 section 7.3) and **PKCE S256**. The relay runs its own, independent authorization code flow with the IdP. Reason: players run Minecraft on a desktop with a browser, and the loopback flow is one click with no code to type. Fallback for machines without a browser (connect running on a home server, SSH sessions): `sculkworm-connect login --device`, or automatically when opening the browser fails (no `DISPLAY`/`WAYLAND_DISPLAY` on Linux, or the opener command exits non-zero). Connect then uses the **device flow** ([5.5](#55-device-flow-fallback)): it prints a URL and a code to open on any other device, and polls the relay. ### 5.2 Relay configuration for the public side | Variable | Default | Meaning | | --- | --- | --- | | `SCULKWORM_TUNNEL_LISTEN` | *(unset: closed mode disabled)* | TLS listener for tunnels and the public HTTPS endpoints. Docker suggestion `0.0.0.0:8443`, published as `443`. | | `SCULKWORM_TLS_CERT_FILE` | *(required with the listener)* | PEM certificate chain. Reloaded on `SIGHUP`. | | `SCULKWORM_TLS_KEY_FILE` | *(required with the listener)* | PEM private key (PKCS#8, PKCS#1 or SEC1). Reloaded on `SIGHUP`. | | `SCULKWORM_PUBLIC_URL` | *(required with the listener)* | External `https://` URL of the tunnel listener, no path, for example `https://relay.example`. Used for redirect URIs and in the status JSON. | | `SCULKWORM_SECRETS_FILE` | *(required with the listener)* | Path of the secrets file ([6.5](#65-secrets-file)). | | `SCULKWORM_IDP_ALLOW_PRIVATE` | `0` | `1` lets IdP requests reach private and loopback addresses ([6.6](#66-requests-to-identity-providers)). | The IdP redirect URI the operator registers is `${SCULKWORM_PUBLIC_URL}/login/callback`, for every route and every IdP. ### 5.3 Loopback flow, step by step 1. Connect binds `127.0.0.1:0` (an ephemeral port) for the callback, generates `state` (32 random bytes, base64url) and a PKCE `code_verifier` (32 random bytes, base64url, 43 characters), and computes `code_challenge = base64url(SHA-256(code_verifier))`. RFC 7636 vector: verifier `dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk` gives challenge `E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM`. 2. Connect opens the browser (`xdg-open` on Linux, `open` on macOS, `rundll32 url.dll,FileProtocolHandler` on Windows) at `GET /login/start` ([5.6](#56-public-http-endpoints)) and prints the same URL in case the browser does not open. 3. The relay validates the parameters, stores a pending flow in memory (10 minutes TTL) with its own random IdP `state`, its own IdP PKCE verifier, the OIDC `nonce` (OIDC only) and connect's parameters, and redirects to the IdP. 4. The IdP redirects back to `/login/callback`. The relay looks up the pending flow by IdP `state` (single use), exchanges the code with the client secret and its PKCE verifier, establishes the subject ([6.2](#62-oidc-clients), [6.3](#63-oauth2-clients)), and evaluates the authorizer. If the player is not allowed it shows an HTML page with `You are signed in as , but does not admit this account.` and stops. 5. On success the relay creates a **relay code** `swc_` + base64url(32 random bytes), valid **60 seconds**, single use, bound to connect's `redirect_uri` and `code_challenge`, and redirects the browser to `?code=&state=`. 6. Connect's callback server compares `state` (constant time), answers the browser with a small HTML page `Logged in. You can close this tab.`, stops listening, and calls `POST /login/token` with the code and the verifier. 7. The relay returns the sealed login; connect stores it ([5.8](#58-storage-on-the-player-machine)). Connect gives up after 5 minutes without a callback. ### 5.4 Sealed login The sealed login is the relay-issued refresh credential. It is self-contained so the relay keeps no per-login state beyond revocations. - **Plaintext:** compact JSON with exactly these keys: | Key | Type | Meaning | | --- | --- | --- | | `lid` | string | Login id: 16 lowercase hex characters from 8 random bytes. Used for logout and in logs. | | `route` | string | Normalized route. | | `aid` | string | Authorizer id of the route when the login was made ([7.2](#72-route-objects)). A login made under a replaced authorizer is invalid. | | `sub` | string | Subject at the IdP. | | `name` | string | Display name at login time. | | `iat` | integer | Unix seconds when the login was made. | | `exp` | integer | `iat + 2592000` (30 days). Never extended by refreshes. | | `idp` | object | `at` access token, `at_exp` its expiry in Unix seconds, `rt` refresh token or `""` when the IdP gave none. | - **Encoding:** `swl_` + base64url without padding of `header || nonce || ciphertext_and_tag`, where `header` is two bytes `01` (format version) and the key id (`01`..`ff`), `nonce` is 12 random bytes, and the AEAD is **ChaCha20-Poly1305** (RFC 8439) with the 32-byte login key named by the key id and additional data `sculkworm-login` (15 ASCII bytes) followed by the 2 header bytes. - **Keys:** from the secrets file `login_keys` ([6.5](#65-secrets-file)); the highest id seals, every listed id opens. Removing a key invalidates every login sealed with it. - **Any failure to open** (bad prefix, bad base64, unknown key id, tag mismatch, bad JSON, missing key) is `401 login_invalid`. Test vector. Key `404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f` with id `01`, nonce `606162636465666768696a6b`, plaintext: ```json {"lid":"0123456789abcdef","route":"friends.play.example","aid":"fedcba9876543210","sub":"80351110224678912","name":"alex","iat":1795694400,"exp":1798286400,"idp":{"at":"at-example","at_exp":1796299200,"rt":"rt-example"}} ``` seals to: ```text swl_AQFgYWJjZGVmZ2hpamut3Ws1a8JXOpR0dgFWVXwiQJpCbXRJu0bUgRKHhjhLQDdAQL9uBLuCd1hbqprNWUqKArTjcXqXERiaDC2C2vOY3T8otO8BOoYS9QD8osm_Nv3eNBQ0Vc6v-0ctgGNxNZZGAgq4cK3gIKX5b8ENM9Lf5IgjtTZJKhRqwELEb2rqXX2Ps9kfh3ZQxcfnQTV-kgpRilhMrhOgEtyxsGAY-SLQNOAiOrN4-_MxosgQVmJ2bTF4095VemMV70_Yj_hkkw2NCtyxm4NlG2IsK8z-4MZFAWTRrO0VJHmgtCZ5PeYx23lPNeLz3oHT21jKjw ``` ### 5.5 Device flow fallback The device flow follows RFC 8628, with the protections of its section 5.4 against remote phishing: the player always types the code, and the approval page says who will be able to play. 1. Connect calls `POST /login/device` with `{"route":"friends.play.example"}`. 2. The relay answers `200` with `{"device_code":"swd_","user_code":"WDJB-MJHT","verification_uri":"https://relay.example/login/device","expires_in":600,"interval":5}`. `user_code` is 8 characters from `BCDFGHJKLMNPQRSTVWXZ` (no vowels, no digits) shown as `XXXX-XXXX`; the relay accepts it case-insensitively, with or without the dash. There is no `verification_uri_complete`. 3. Connect prints `Open https://relay.example/login/device on any device, sign in and type the code WDJB-MJHT.` 4. `GET /login/device` shows a form with a text field for the code. It sets a cookie `__Host-swdev=; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=600` and puts the same value in a hidden form field `csrf`. A `user_code` query parameter is ignored: the code must be typed. 5. The form posts to `POST /login/device/approve` with `user_code` and `csrf`. The relay requires, before looking at the code: the `__Host-swdev` cookie is present and equals `csrf` (constant time), and the `Sec-Fetch-Site` header, when the browser sends it, is `same-origin`. Any failure is a `403` HTML page `This form expired. Open https://relay.example/login/device again.` The code must then be pending (`404` HTML page otherwise), and the relay shows a confirmation page: > **Log in to friends.play.example?** Only continue if you started this login yourself on another device. Whoever > started it will play as you. > > [Continue] [Cancel] **Continue** is another form post to `/login/device/approve` with `user_code`, `csrf` and `confirm=1`, checked the same way. It sets a second random cookie `__Host-swdevcb=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=600` (`SameSite=Lax` so the browser sends it on the cross-site top-level GET back from the IdP) and stores its SHA-256 on the pending device flow, then redirects to the IdP like `/login/start`. For device flows the relay adds `prompt=consent` to the authorize request (OIDC and the Discord preset), so the IdP asks the player again even with an existing session. **Cancel** marks the code denied. 6. On `GET /login/callback` for a device flow, the relay first requires the `__Host-swdevcb` cookie and compares its SHA-256 in constant time against the value recorded on `confirm=1`, and always clears the cookie (`Max-Age=0`) on the response. If the cookie is missing or does not match (for example if an attacker confirmed their own code and sent the IdP authorize URL to a victim), the relay marks the device code denied (`access_denied` on poll) and shows a `403` error page. Otherwise the callback marks the device code as approved (or denied) and shows `Done. Go back to the device where you ran sculkworm-connect.` instead of redirecting to a loopback address. 7. Connect polls `POST /login/token` with `{"grant_type":"device_code","device_code":"swd_…"}` every `interval` seconds and receives `authorization_pending`, `slow_down` (add 5 seconds to the interval), `access_denied`, `expired_token`, or the sealed login. The device code is consumed when it returns the sealed login: a later poll with it gets `invalid_grant`. ### 5.6 Public HTTP endpoints Served on the tunnel listener for ALPN `http/1.1` or no ALPN. HTTP/1.1 only. Every response has `Cache-Control: no-store`. Every HTML page the relay renders HTML-escapes each interpolated value (`&`, `<`, `>`, `"`, `'`), carries no script, and is sent with `Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'` (pages without a form omit `form-action 'self'`), `X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`. The device confirmation page also lists the origin of the identity provider's authorization endpoint after `'self'` (`form-action 'self' https://idp.example`): the confirm post is answered with a redirect to that endpoint, and Chromium applies `form-action` to redirects, so without it the browser blocks the login after the code is spent. JSON errors use the admin API envelope `{"error":{"code":"…","message":"…"}}`. Bodies are capped at 16 KiB, header and body reads at 10 seconds, as on the admin API. | Method and path | Parameters | Success | Errors | | --- | --- | --- | --- | | `GET /healthz` | — | `200 {"status":"ok"}` | — | | `GET /login/start` | Query: `route`, `redirect_uri` (must be `http://127.0.0.1:/callback` or `http://[::1]:/callback`), `state` (16..=128 characters from the base64url alphabet `A-Z a-z 0-9 - _`), `code_challenge` (43 chars base64url), `code_challenge_method=S256` | `302` to the IdP | `400` HTML page for a bad parameter; `404` HTML page for an unknown or open route | | `GET /login/callback` | Query from the IdP: `code`, `state`, or `error` | `302` to the loopback URI, or HTML result page for device flows | HTML page for IdP errors, unknown state, not admitted | | `POST /login/device` | JSON `{"route"}` | `200` device response above | `404 unknown_route`, `429 rate_limited` | | `GET /login/device` | — | `200` HTML form; sets the `__Host-swdev` cookie | — | | `POST /login/device/approve` | Form body (`application/x-www-form-urlencoded`) `user_code`, `csrf`, optional `confirm=1` or `cancel=1`, plus the `__Host-swdev` cookie | Without `confirm`: `200` confirmation page. With `confirm=1`: `302` to the IdP. With `cancel=1`: `200` HTML page | `403` HTML when cookie, `csrf` or `Sec-Fetch-Site` fail; `404` HTML for unknown or expired code | | `POST /login/token` | JSON `{"grant_type":"authorization_code","code","code_verifier","redirect_uri"}` or `{"grant_type":"device_code","device_code"}` | `200 {"login":"swl_…","route":"friends.play.example","subject":"80351110224678912","name":"alex","expires_at":"2026-12-26T12:00:00Z"}` | `400 invalid_grant` (unknown, used or expired code, verifier or redirect mismatch), `400 authorization_pending`, `400 slow_down`, `400 access_denied`, `400 expired_token`, `400 invalid_json` | | `POST /tickets` | Header `Authorization: Bearer swl_…`; JSON `{"route"}` | `200 {"ticket":"swt_…","expires_in":30,"login":"swl_…"}`; `login` is present only when the sealed login changed (rotated IdP tokens) and connect must replace its stored copy | `401 login_invalid`, `401 login_expired`, `401 login_revoked`, `403 not_admitted`, `404 unknown_route`, `409 route_mismatch` (login is for another route), `429 rate_limited`, `503 idp_unavailable`, `503 busy` | | `POST /logout` | Header `Authorization: Bearer swl_…` | `204`; the login id goes into the revoked logins until its `exp`; a `lid` that is already revoked answers `204` without writing state | `401 login_invalid`, `429 rate_limited`, `503 busy` | `state`, `code_verifier`, the relay code and the device code are compared in constant time. The `redirect_uri` given to `/login/token` must equal the one given to `/login/start` byte for byte. ### 5.7 Permission re-check at every tunnel start `POST /tickets` performs, in order, and stops at the first failure. The per-`OPEN` check of [4.4](#44-connect-session-rules) runs steps 2 to 5 with the login of the session. 1. Open the sealed login (`401 login_invalid`). Check `exp > now` (`401 login_expired`). If the **login cache** (below) has an entry for this `lid`, use the cached plaintext instead of the presented one: it carries the newest IdP tokens. 2. Check the route exists, is closed and equals `route` in the body and in the login (`404 unknown_route`, `409 route_mismatch`). Check `aid` equals the route's current authorizer id (`401 login_invalid`, message `the server changed its login settings; log in again`). 3. Check revocation: `lid` not in the revoked logins, `iat` after the route's `revoked_before`, and `iat` after the subject's entry in `revoked_subjects` (`401 login_revoked`). 4. **Contact the IdP**: - If `at_exp > now + 60` the relay calls the userinfo endpoint with the access token. `200` with the same subject passes. `401` falls through to the refresh step. - Otherwise, or after that `401`, the relay uses the refresh token at the token endpoint, then calls userinfo with the new access token. A new refresh token, if returned, replaces the old one. - With no refresh token and an expired access token: `401 login_expired`. - IdP answers `400 invalid_grant` or `401`: `401 login_expired` (the player must log in again). - Network error, timeout (5 seconds per IdP request) or `5xx`: **`503 idp_unavailable`**. No grace period: an IdP outage stops new tunnel starts for that route, and already open sessions keep running ([decision log](#11-decision-log)). 5. Evaluate the authorizer against the fresh userinfo (`403 not_admitted`). When the route's authorizer has `allow.discord_guild`, this step also calls `GET https://discord.com/api/users/@me/guilds` with the access token that step 4 just used or obtained, and admits only if the list holds an object whose `id` equals the configured guild id. A failure of that call is handled like any other IdP failure in step 4 (`401` is `login_expired`, a network error, timeout or `5xx` is `503 idp_unavailable`), never an admit. 6. Mint the ticket. If the `idp` tokens used are newer than the ones in the presented blob (step 4 refreshed them now or a cached entry was used), re-seal the login with the same `lid`, `iat` and `exp` and return it as `login`. **Refresh rotation.** Many IdPs (Discord included) rotate the refresh token on every use and reject the old one, but the sealed login is a stateless blob that connect may still hold in its old form. The relay therefore: - runs at most **one** IdP refresh per `lid` at a time (single flight): a second request for the same `lid` waits for the running one (up to its 5-second IdP timeout) and uses its result; - keeps, in memory, a **login cache** from `lid` to the newest plaintext (with its rotated tokens) for **5 minutes** after each refresh; any request presenting an older blob with the same `lid` within that time uses the cached plaintext and receives the newer sealed login; - caps the cache at 10000 entries, evicting the oldest; an evicted or expired entry only matters if connect lost the newer blob, and then the old refresh token fails at the IdP and the player logs in again (`401 login_expired`). ### 5.8 Storage on the player machine One file, `logins.json`: | OS | Path | | --- | --- | | Linux and other Unix | `$XDG_CONFIG_HOME/sculkworm/logins.json`, default `~/.config/sculkworm/logins.json` | | macOS | `~/Library/Application Support/sculkworm/logins.json` | | Windows | `%APPDATA%\sculkworm\logins.json` | - Unix: directory mode `0700`, file mode `0600`, created with those modes (not chmod after writing). If an existing file is readable by group or others, connect refuses to use it and prints the `chmod 600` command. Windows: the file inherits the per-user ACL of `%APPDATA%`; connect does not change ACLs. - Written with temp file in the same directory, `fsync`, rename. - Content: only relay-issued data, never an IdP token in the clear: ```json { "version": 1, "logins": { "friends.play.example": { "relay": "https://relay.example", "login": "swl_…", "subject": "80351110224678912", "name": "alex", "expires_at": "2026-12-26T12:00:00Z" } } } ``` - `sculkworm-connect logout ` calls `POST /logout` (a failure is printed but the local entry is still removed) and deletes the entry. `sculkworm-connect logout --all` does it for every entry. - `401 login_expired`, `login_revoked` or `login_invalid` from `/tickets` deletes the entry and starts a new login. ## 6. Authorizer configuration A closed route has exactly one authorizer. A tenant sets it with the route in `PUT /v1/routes/{host}` ([section 7](#7-admin-api-additions)). The authorizer only says **which client** to log in with, **which scopes** to ask for and **who is admitted**. Everything that decides where the client secret goes (the IdP's URLs, the client id and secret) lives in a **client** entry of the operator's secrets file ([6.5](#65-secrets-file)), which tenants cannot write. A tenant can therefore never make the relay send a client secret to a URL of the tenant's choosing. Unknown fields are rejected everywhere. ### 6.1 Authorizer object ```json { "type": "oauth2", "client": "discord-main", "allow": { "discord_guild": "613425648685547541" } } ``` ```json { "type": "oidc", "client": "example-oidc", "scopes": ["openid", "profile", "groups"], "allow": { "claim": "groups", "any_of": ["minecraft"] } } ``` ```json { "type": "oidc", "client": "sculk-main", "allow": { "sculk_server": "6uabltcpud3qpiy5" } } ``` ```json { "type": "fixed-list", "client": "discord-main", "subjects": ["80351110224678912", "41771983423143937"] } ``` | Field | Types | Rules | | --- | --- | --- | | `type` | all | Required. `oidc`, `oauth2` or `fixed-list`. `oidc` and `oauth2` must name a client of that kind; `fixed-list` may name either kind. | | `client` | all | Required. Name of an entry in the secrets file `clients` map whose `tenant` is the caller or `*`. | | `scopes` | all | Optional. Default: the client's default scopes ([6.5](#65-secrets-file)). For an `oidc` client the list must contain `openid`. 0..=20 strings of 1..=128 bytes without spaces. | | `allow` | `oidc`, `oauth2` | Optional. Absent: every identity the client's IdP authenticates is admitted. Forms below. | | `subjects` | `fixed-list` | Required, 1..=1000 unique strings of 1..=255 bytes, compared byte for byte with the subject. | `allow` forms: - `{"claim": "", "any_of": ["…"]}` for `oidc`, `{"field": "", "any_of": ["…"]}` for `oauth2`. The name is 1..=64 bytes and names a top-level member of the userinfo JSON; `any_of` holds 1..=100 strings. A string member matches if it equals one value; an array member matches if any string element equals one value; a missing member or any other type does not match. - `{"sculk_server": ""}`, only for an `oidc` authorizer. The server id is 1..=64 bytes without whitespace or control characters. The relay adds the `sculk:servers` scope automatically if it is not already in the effective scopes, and admits the player if the userinfo `sculk_servers` JSON array contains an object with `id == ` and `is_player == true` (the claim emitted by a sculk.network OIDC provider for members holding `server.play`). A missing, malformed, or non-array `sculk_servers` claim is not admitted. **Trust requirement:** `sculk_server` is only sound when the OIDC client's `issuer` is a sculk.network instance (where `sculk_servers` is authoritative and provider-controlled, never user-editable); using it against another OIDC provider that lets end users set or edit the `sculk_servers` claim would allow them to admit themselves. - `{"discord_guild": ""}`, only for an `oauth2` client with `preset: "discord"`. The relay adds the `guilds` scope and admits the player if `GET https://discord.com/api/users/@me/guilds` lists an object whose `id` equals the guild id. ### 6.2 OIDC clients An OIDC client ([6.5](#65-secrets-file)) names an `issuer`. The relay fetches `/.well-known/openid-configuration` and requires `issuer` in the document to equal the configured value exactly, plus `authorization_endpoint`, `token_endpoint` and `userinfo_endpoint`. `token_endpoint` and `userinfo_endpoint` (the URLs that receive the client secret and access tokens) must have the same origin (scheme, host and port) as the issuer, unless the client entry lists them explicitly in `endpoints`, which then replace the discovered values. When to fetch: - When a route that uses the client is saved through the admin API (an uncached or failed document makes the `PUT` fail with `422 invalid_authorizer`, message `authorizer: discovery failed for : `). - Lazily on first use after startup, and again when the cached document is older than 24 hours. A failed fetch at that point is `503 idp_unavailable` for the request that needed it and is retried on the next request. Subject: the `sub` claim of the ID token, which must equal `sub` in userinfo on every re-check. The relay validates the ID token's `iss`, `aud` (contains the client id), `exp` and `nonce`, and takes it from the TLS-protected token response of the token endpoint, so it does not verify the JWS signature (OIDC Core 3.1.3.7 allows this for the code flow over TLS). Display name: `preferred_username`, else `name`, else `sub`. ### 6.3 OAuth2 clients Plain OAuth 2.0 with a userinfo endpoint, for providers without OIDC. The client entry either sets `preset: "discord"` or lists `authorize_url`, `token_url`, `userinfo_url`, `subject_field` and `name_field`. The Discord preset means: | Field | Value | | --- | --- | | `authorize_url` | `https://discord.com/oauth2/authorize` | | `token_url` | `https://discord.com/api/oauth2/token` | | `userinfo_url` | `https://discord.com/api/users/@me` | | default scopes | `["identify"]` | | `subject_field` | `id` | | `name_field` | `username` | `subject_field` and `name_field` are top-level members of the userinfo JSON. The subject value must be a non-empty string or an integer (an integer is formatted in decimal); anything else is `403 not_admitted` with the message `the identity provider returned no usable user id`. Every flow uses PKCE S256 towards the IdP and sends the client secret to the token endpoint with `client_secret_basic` (HTTP Basic) or, when the client sets `"auth": "client_secret_post"`, in the form body. ### 6.4 Validation errors The admin API returns `422 invalid_authorizer` with one of these messages: | Message | Condition | | --- | --- | | `authorizer is required for a closed route` | `mode` is `closed` and `authorizer` is absent. | | `authorizer is not allowed on an open route` | `mode` is `open` and `authorizer` is present. | | `unknown authorizer type ""` | `type` is not `fixed-list`, `oidc` or `oauth2`. | | `authorizer: unknown field ""` | Any unknown field, at any depth. | | `authorizer: is required` | A required field is missing. | | `authorizer: client "" is not in the secrets file` | `client` names no entry in `clients`, or an entry whose `tenant` is another tenant (the message is the same, so a tenant cannot probe other tenants' client names). | | `authorizer: client "" is an client` | `type` is `oidc` with an `oauth2` client or the reverse. | | `authorizer: oidc scopes must include openid` | `scopes` of an `oidc` client without `openid`. | | `authorizer: scopes are invalid` | Bad `scopes` list. | | `authorizer: discovery failed for : ` | Discovery failed; `` is one of `timeout`, `tls`, `http_`, `invalid_document`, `issuer_mismatch`, `endpoint_origin_mismatch`, `forbidden_address`. | | `authorizer: subjects must hold 1 to 1000 unique values` | Bad `subjects`. | | `authorizer: allow. is invalid` | A malformed `allow` object, an invalid `sculk_server` id (must be 1..=64 bytes without whitespace or control characters), or `discord_guild` with a client that is not the Discord preset. | ### 6.5 Secrets file `SCULKWORM_SECRETS_FILE` is a JSON file the operator writes by hand. The relay reads it at startup and on `SIGHUP`, and never writes it. On Unix the relay refuses to start with `level=error event=secrets_error error="secrets file must not be readable by group or others"` unless the mode is `0600` or `0400`. ```json { "login_keys": { "1": "QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl8" }, "clients": { "discord-main": { "tenant": "sculk", "kind": "oauth2", "preset": "discord", "client_id": "1234567890", "client_secret": "replace-me" }, "forgejo": { "tenant": "*", "kind": "oauth2", "authorize_url": "https://git.example/login/oauth/authorize", "token_url": "https://git.example/login/oauth/access_token", "userinfo_url": "https://git.example/api/v1/user", "subject_field": "id", "name_field": "login", "scopes": ["read:user"], "client_id": "sculkworm", "client_secret_env": "SCULKWORM_FORGEJO_SECRET" }, "example-oidc": { "tenant": "partner", "kind": "oidc", "issuer": "https://accounts.example.com", "client_id": "sculkworm", "client_secret_env": "SCULKWORM_OIDC_SECRET", "auth": "client_secret_post" } } } ``` | Field | Rules | | --- | --- | | `login_keys` | Required, 1..=255 entries. Key: decimal id `1`..`255`. Value: base64url (no padding) of exactly 32 random bytes (`head -c 32 /dev/urandom \| basenc --base64url \| tr -d '='`). The highest id seals new logins. | | `clients.` | Name: 1..=64 bytes of `[a-z0-9-]`. | | `tenant` | Required. A tenant name from `SCULKWORM_TENANTS_FILE`, or `"*"` to let every tenant use the client. | | `kind` | Required. `oidc` or `oauth2`. | | `issuer` | `oidc`: required `https://` URL without query or fragment. | | `endpoints` | `oidc`: optional object with `authorization`, `token` and `userinfo` `https://` URLs (all three), which replace the discovered endpoints. | | `preset` | `oauth2`: optional, only `discord`. With a preset, `authorize_url`, `token_url`, `userinfo_url`, `subject_field` and `name_field` must be absent. | | `authorize_url`, `token_url`, `userinfo_url` | `oauth2` without a preset: required `https://` URLs. | | `subject_field`, `name_field` | `oauth2` without a preset: required, 1..=64 bytes. | | `scopes` | Optional default scopes for authorizers that do not set their own. Default: `["openid", "profile"]` for `oidc`, the preset's scopes for Discord, `[]` otherwise. | | `client_id` | Required. | | `client_secret`, `client_secret_env` | Exactly one. `client_secret_env` names an environment variable that must be set and non-empty at load time. | | `auth` | Optional. `client_secret_basic` (default) or `client_secret_post`. | Errors are logged as `level=error event=secrets_error error=""` and exit with code `2` at startup. Messages follow the pattern `client "": `, for example `client "forgejo": token_url must be an https URL`, `client "discord-main": tenant is required (use "*" for every tenant)`, `client "discord-main": preset "discord" does not allow token_url`, `client "x": unknown preset "github"`, `client "x": exactly one of client_secret or client_secret_env is required`, `client "x": environment variable SCULKWORM_X is not set`, and `login_keys: key 1 must be 32 bytes of base64url`. On `SIGHUP` a file that fails validation leaves the old secrets active and logs `level=error event=reload_failed`. A reload is also refused, with the same log line, when it would remove a client a route uses (`client "" is used by route `) or set a used client's `tenant` to a tenant other than the route's owner and other than `*` (`client "" is used by route of tenant `). What happens at startup when the file and the state disagree is in [section 8](#8-state-and-persistence-changes). Secrets are never written to the state file, never returned by any API (route objects carry only the client name), and never logged: log lines name the client, never its id or secret. ### 6.6 Requests to identity providers Every HTTP request the relay makes to an IdP (discovery, token, userinfo, Discord guilds): - Uses HTTPS with the OS root store and a 5-second timeout for the whole request. - Resolves the host first and refuses to connect when any resolved address is loopback, private (RFC 1918), link-local (`169.254.0.0/16`, `fe80::/10`), CGNAT (`100.64.0.0/10`), unique local (`fc00::/7`), unspecified or multicast, unless the operator sets `SCULKWORM_IDP_ALLOW_PRIVATE=1` (for an IdP on the operator's own network). The refused request fails with reason `forbidden_address`. The relay connects to the address it checked, so DNS cannot change between the check and the connection. - Does not follow redirects. A `3xx` answer is a failure with reason `http_`. - Reads at most 1 MiB of response body. ## 7. Admin API additions All existing endpoints, request bodies and responses stay valid. A client that never sends `mode` keeps creating and seeing open routes; every route object now also carries `mode`, and closed routes carry the fields of [7.2](#72-route-objects) instead of `target`. The [TypeScript SDK](https://docs.sculk.network/nightly/sculkworm/sdk/js.md) ignores unknown fields and `parseRoute` accepts a route without `target` when `mode` is `closed`, so a list with both kinds parses. The OpenAPI file and [api.md](https://docs.sculk.network/nightly/sculkworm/api.md) describe the same fields. ### 7.1 Route request `PUT /v1/routes/{host}` body: | Field | Required | Rules | | --- | --- | --- | | `mode` | No | `open` (default) or `closed`. | | `target` | `open` only | As today. With `mode: "closed"`: `422 invalid_target`, message `a closed route has no target`. | | `authorizer` | `closed` only | [Section 6](#6-authorizer-configuration). | `max_routes` counts open and closed routes together. `allowed_targets` applies only to open routes, since a closed route's backend is chosen by its agent. Switching a route between modes is a normal `PUT`; leaving closed mode sends `GOAWAY` `route_changed` to its sessions, deletes its agent token and its revocations. ### 7.2 Route objects ```json {"host":"friends.play.sculk.network","mode":"closed","tenant":"sculk","authorizer":{"type":"oauth2","client":"discord-main","allow":{"discord_guild":"613425648685547541"}},"authorizer_id":"fedcba9876543210","agent_token":{"id":"0123456789abcdef","created_at":"2026-11-27T10:00:00Z"},"agent_connected":true} ``` ```json {"host":"survival.play.sculk.network","mode":"open","target":"10.0.0.10:25565","tenant":"sculk"} ``` - `active`: `true`, or `false` with `inactive_reason` as in [section 8](#8-state-and-persistence-changes). Closed routes only. - `authorizer_id`: 16 hex characters, new random value whenever the authorizer changes. The relay compares the parsed authorizer (as a typed value, with defaults applied), not the raw JSON text, so reordering keys or adding whitespace in a `PUT` keeps the id and the players' logins. Logins carry it ([5.4](#54-sealed-login)), so changing who may play invalidates existing logins. - `agent_token`: `null` when no token was minted. - `PUT` with an unchanged body returns `200` without rewriting state, as today. Responses are `201` or `200` as today. ### 7.3 Mint an agent token `POST /v1/routes/{host}/agent-token` (no body). Mints a new token for a closed route the caller owns and replaces any previous one; the previous token stops working at once and its agent session gets `GOAWAY` `revoked`. ```text HTTP/1.1 201 Created content-type: application/json {"token":"swa_0123456789abcdef_AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8","id":"0123456789abcdef","created_at":"2026-11-27T10:00:00Z"} ``` - Format: `swa_` + `id` (16 lowercase hex characters from 8 random bytes) + `_` + base64url of 32 random bytes. - The token is in this response only. The relay stores `id` and the lowercase hex SHA-256 of the **whole token string**. For the token above that is `3710e97d7ffe5e799ff2aad6d389f4c602facf7900bfd2c7cde880b1cd9f7a95`. - On `HELLO` the relay parses `id`, finds the route's stored token, and compares the SHA-256 of the presented token with the stored hash using `subtle::ConstantTimeEq`. An unknown id, a different route, or a mismatch all give status `3`. - Errors: `404 not_found` (no such route of the caller), `409 route_not_closed`, `500 persist_failed`. `DELETE /v1/routes/{host}/agent-token`: `204`, or `404 not_found` when the route or its token does not exist. The agent session, if any, gets `GOAWAY` `revoked`. ### 7.4 List connected agents `GET /v1/agents`: every agent session of the caller's routes, sorted by host. ```json {"agents":[{"host":"friends.play.sculk.network","session":"0123456789abcdef","token_id":"0123456789abcdef","peer":"198.51.100.4:40122","software":"sculkworm-agent/0.4.0","connected_at":"2026-11-27T10:00:05Z","streams":2}]} ``` A route with an old session still draining after `GOAWAY replaced` lists both. ### 7.5 Route state check `GET /v1/routes/{host}` returns the object of [7.2](#72-route-objects), with `agent_connected` computed live. ### 7.6 Revoke player logins `POST /v1/routes/{host}/revoke-logins`, `Content-Type: application/json`: | Body | Effect | | --- | --- | | `{}` | Sets the route's `revoked_before` to now: every login made before this instant fails at the next `/tickets`. | | `{"subject":"80351110224678912"}` | Records `revoked_subjects[subject] = now` for the route: that subject's existing logins fail. They may log in again if the authorizer still admits them, so pair this with an authorizer change to keep them out. | Either way the relay also resets every open stream and closes every connect session of the affected logins with `GOAWAY` `revoked` (open streams get `RESET` code `6`), so revocation takes effect immediately and not only at the next connection. Response: `200 {"host":"friends.play.sculk.network","revoked_before":"2026-11-27T10:00:00Z"}` or `200 {"host":"…","subject":"…","revoked_at":"…"}`. Errors: `404 not_found`, `409 route_not_closed`, `422 invalid_subject` (empty or over 255 bytes), `422 too_many_revocations` (the route already has 10000 revoked subjects), `500 persist_failed`. ### 7.7 New error codes | HTTP status | `error.code` | Cause | | --- | --- | --- | | `409` | `route_not_closed` | Agent token or revocation endpoint on an open route. | | `422` | `invalid_authorizer` | Any message from [6.4](#64-validation-errors). | | `422` | `invalid_mode` | `mode` is neither `open` nor `closed`. | | `422` | `invalid_subject` | Bad `subject` in `revoke-logins`. | | `422` | `too_many_revocations` | The route already holds 10000 `revoked_subjects`. | | `503` | `closed_mode_disabled` | `mode: "closed"` or a closed-route endpoint while `SCULKWORM_TUNNEL_LISTEN` is unset. | Tenant scope: every new endpoint authenticates as today and returns `404 not_found` for routes outside the caller's scope or owned by another tenant, never revealing that they exist. Static routes (from `SCULKWORM_ROUTES_FILE`) are always open; the routes file format does not change. ## 8. State and persistence changes `STATE_VERSION` becomes **2**. The relay reads versions 1 and 2 and always writes 2. ```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" }, "revoked_before": "2026-11-27T10:00:00Z", "revoked_subjects": { "41771983423143937": "2026-11-27T11:00:00Z" }, "revoked_logins": { "0123456789abcdef": "2026-12-26T12:00:00Z" } } ] } ``` - **Migration from version 1.** A version 1 file is read as version 2 with `mode: "open"` on every route; the next write stores version 2. No file is rewritten at startup only to change the version. A version 1 binary refuses a version 2 file (`unsupported state version 2`), so downgrading needs the backup the operator made before upgrading; the release notes of the version that ships this say so. - **Persisted:** route mode, authorizer JSON (no secrets: it only names clients), `authorizer_id`, agent token `id`, `sha256` and `created_at`, `revoked_before`, `revoked_subjects`, and `revoked_logins` (login id to the login's `exp`; entries are dropped at load and at write once their `exp` has passed). - **Memory only:** sessions, streams, tickets, pending login flows, relay codes, device codes, OIDC discovery documents, rate-limit counters. A relay restart drops them; [3.8](#38-reconnect-backoff-and-agent-replacement) says what each side does. - **Inactive closed routes.** A mistake in the secrets file must never delete routes. At startup, a closed route whose authorizer names a client that is missing from the secrets file, or whose `tenant` is neither the route's tenant nor `*`, is **kept in state but inactive**: the relay logs `level=warn event=closed_route_inactive host= reason=unknown_client` (or `reason=client_tenant_mismatch`), answers `HELLO`s for it with status `4`, answers `/login/*` and `/tickets` with `404 unknown_route`, and gives vanilla clients the login disconnect of [4.6](#46-what-a-vanilla-minecraft-client-sees). It becomes active again on the next `SIGHUP` or restart that finds the client. The same applies, with `reason=closed_mode_disabled`, to closed routes in state while `SCULKWORM_TUNNEL_LISTEN` is unset. `GET /v1/routes/{host}` shows `"active": false` and the reason on such routes. Today's `state_route_dropped` reasons (`unknown_tenant`, `host_out_of_scope`, `target_not_allowed`) still apply and still drop. - Writes keep today's temp file, `fsync`, rename, and the same write lock as route changes. ## 9. Security considerations ### 9.1 Threat model | Threat | Mitigation | Residual risk | | --- | --- | --- | | **Stolen agent token** | Works for one route only. Stored hashed; shown once. The operator mints a new one (`POST …/agent-token`), which revokes the old one and kicks its session. `GET /v1/agents` shows the unexpected `peer`. | Until rotated, the thief can serve that route: players would join the thief's server. The thief cannot read other routes, logins or secrets. | | **Stolen ticket** | 30 seconds, single use, one route. Only sent inside TLS. | A thief faster than the player gets one session on that route as that player. | | **Replayed ticket** | Deleted on first presentation, success or not. | None. | | **Stolen sealed login** (malware on the player's machine) | Usable only through the relay, which re-checks the IdP and honours revocation; file mode `0600`. The IdP tokens inside are encrypted. | The thief can play as the player until logout, revocation, IdP-side revocation or expiry. | | **Malicious player floods** | Limits in [9.2](#92-rate-limits-and-caps); the global `SCULKWORM_MAX_CONNECTIONS` also counts tunnel sessions. | A distributed flood still needs a network firewall, as today. | | **IdP outage** | Fail closed: `503 idp_unavailable`, connect shows the reason. Open sessions keep running. | Nobody new can join that route during the outage. | | **Tenant redirects a client secret** (sets an IdP URL to its own server to receive another tenant's or the operator's client secret) | IdP URLs live only in the operator's secrets file, in the client entry; authorizers only name a client. A client is usable only by its `tenant` (or every tenant with an explicit `*`). OIDC token and userinfo endpoints must share the issuer's origin unless listed by the operator. | None while the operator controls the secrets file. | | **SSRF through IdP URLs** | [6.6](#66-requests-to-identity-providers): private, loopback, link-local, CGNAT and ULA addresses refused, no redirects followed, 1 MiB body cap. | An operator who sets `SCULKWORM_IDP_ALLOW_PRIVATE=1` accepts it for their own network. | | **Device-code phishing** (an attacker starts a device flow and gets a player to approve it, or confirms their own code and sends the IdP authorize URL to a victim) | The player must type the code; the page warns that whoever started the login will play as them; `prompt=consent` at the IdP; approval needs the `__Host-swdev` cookie, the matching `csrf` field and a same-origin `Sec-Fetch-Site`, so another site cannot submit it; `confirm=1` also sets a random `__Host-swdevcb` (`SameSite=Lax`) cookie whose SHA-256 is verified on `/login/callback`, so a copied IdP redirect URL cannot be completed in a victim's browser (it fails `403` and marks the code denied). | A player who reads the warning and still types an attacker's code into their own browser lets the attacker play as them on that route. | | **Route hijack by another tenant** | Domain scopes, as today; agent tokens are per route; tickets and logins carry the route; `aid` binds logins to the authorizer. | None beyond today's tenant-key compromise. | | **Fake relay in status JSON** | Connect shows the relay URL and asks before the first login; TLS verifies it from then on. | A player who accepts a malicious URL logs into the attacker's relay with the attacker's IdP app; the real relay's secrets and logins are not exposed. | | **Relay compromise** | — | Total for routes on that relay: the attacker has the client secrets, login keys (can mint logins for any subject), can serve or read any route's traffic. Mitigate with one IdP client per tenant, `client_secret_env`, and rotating secrets and login keys after an incident. Minecraft online-mode encryption still protects play traffic of online-mode servers against passive reading. | | **Minecraft login encryption** | Passes through unchanged; the relay never parses stream bytes. | Offline-mode servers have no encryption; the tunnel's TLS covers the relay hops only, and the relay sees plaintext Minecraft traffic. | | **Open redirect or code theft in the login flow** | `redirect_uri` must be loopback; relay code is single use, 60 seconds, bound to PKCE. | None known. | | **CSRF into `/login/callback`** | IdP `state` is single use and bound to the pending flow. | None known. | ### 9.2 Rate limits and caps Defaults, all configurable later through `SCULKWORM_*` variables named after the limit. Token buckets refill evenly. | Limit | Default | Response | | --- | --- | --- | | Tunnel connections per source IP (TCP connections open at once) | 16 | TCP close before TLS | | `HELLO` failures per source IP | 10 per minute, then blocked for 10 minutes | Status `6` | | `/login/start` + `/login/device` per source IP (IPv6 `/64`) | 20 per minute | `429 rate_limited` | | `/login/token` per source IP (IPv6 `/64`) | 120 per minute | `429 slow_down` | | `/login/device/approve` per source IP (IPv6 `/64`) | 20 per minute | `429` HTML | | `/login/device/approve` per user code | 5 per minute | `429` HTML | | `/login/device/approve` global lookup misses | 120 per minute | `429` HTML | | Pending device codes | 10000 in memory (1000 per route) | `503 busy` | | `/tickets` per source IP | 30 per minute | `429 rate_limited` | | `/tickets` per login id | 10 per minute | `429 rate_limited` | | `/logout` per source IP | 10 per minute | `429 rate_limited` | | `revoked_logins` per route | 10000 entries | `/logout` beyond the cap returns `503 busy` until expired entries are dropped; the admin API's `revoke-logins` (whole route) still works | | `revoked_subjects` per route | 10000 entries | `422 too_many_revocations` from `revoke-logins` | | Connect sessions per subject per route | 4 at once | Status `6` | | Streams per connect session | 8 at once | `RESET` code `5` | | Streams per agent session | 1024 at once | `RESET` code `5` | | Pending login flows | 10000 in memory | `503 busy` | | Live tickets | 10000 in memory | `503 busy` | ### 9.3 Log redaction - Never logged: client secrets, login keys, agent tokens, tickets, sealed logins, relay codes, device codes, IdP access, refresh and ID tokens, PKCE verifiers, `state` values, `Authorization` headers. - Logged instead: agent token `token_id`, login `lid`, route, `subject` and `name` (through `sanitize_log_value`), peer address, session id. - URLs are logged without query strings. IdP error bodies are logged at most 200 bytes, through `sanitize_log_value`. - New events: `agent_connected`, `agent_disconnected`, `agent_unauthorized`, `connect_session`, `stream_open`, `stream_closed` (with `bytes_up`, `bytes_down`), `login`, `login_denied`, `ticket`, `ticket_denied` (with `reason` = the error code), `idp_unavailable`, `logins_revoked`. ### 9.4 What the relay does not protect against - **It does not authenticate the Minecraft account.** It proves an IdP identity. Who plays under which Minecraft name is up to the server: keep `online-mode=true`, and use the whitelist as well if names matter. The agent passes `subject` and `name` to the server only as information in `OPEN`; a future in-server mod may use them. - It does not stop an admitted player from sharing their computer or their login with someone else. - It does not hide player traffic from the relay operator on offline-mode servers. - It does not protect the Minecraft server from an admitted player (griefing, exploits). - It does not protect against a compromised IdP or IdP account. ## 10. Implementation ### 10.1 Layout in `crates/sculkworm` | Path | Content | | --- | --- | | `src/tunnel/frame.rs` | `HELLO`, `SERVER_HELLO`, frame encode and decode as pure functions over byte slices. No I/O. | | `src/tunnel/session.rs` | Multiplexer: one task per session, stream table, windows, keepalive, `GOAWAY`. Generic over `AsyncRead + AsyncWrite`. | | `src/tunnel/tls.rs` | rustls client and server configs, pin check, certificate reload. | | `src/tunnel/listener.rs` | Relay tunnel listener: TLS accept, ALPN split, agent and connect session handling. | | `src/auth/` | Secrets file (`secrets.rs`), IdP HTTP rules (`idp_http.rs`), authorizers, IdP clients (`oidc.rs`, `oauth2.rs`), sealed logins, tickets, public HTTP handlers. | | `src/closed.rs` | Answers to vanilla clients on closed routes (status, pong, login disconnect). | | `src/bin/sculkworm-agent.rs` | Agent binary. | | `src/bin/sculkworm-connect.rs` | Connect binary. | | `src/main.rs` | Relay binary, unchanged name. | | `tests/vectors.rs` | Every hex vector of this page, byte for byte, through the public encode and decode functions. | | `tests/tunnel.rs` | Relay, agent and connect in one process over loopback with an `rcgen` certificate and a mock IdP. | The Docker image ships only the relay. Build the agent and connect binaries with `cargo build --release --locked --bins`. ### 10.2 Dependencies Checked on crates.io on 2026-11-26 with `cargo info`, built together with the existing dependencies for `x86_64-unknown-linux-musl` in the Dockerfile's builder image. No OpenSSL and no `aws-lc` in the tree. | Crate | Version | Why | | --- | --- | --- | | `rustls` | `=0.23.46`, `default-features = false`, features `ring`, `std`, `tls12` | TLS client and server. `ring` builds with the musl image unchanged. | | `tokio-rustls` | `=0.26.6`, `default-features = false`, features `ring`, `tls12` | Async TLS streams on tokio. | | `rustls-native-certs` | `=0.8.5` | OS root store for agent and connect. | | `rustls-pki-types` | `=1.16.0`, feature `std` | PEM parsing of certificates and keys (`pem` module), no `rustls-pemfile`. | | `rustls-webpki` | `=0.103.17`, `default-features = false`, features `std`, `ring` | `EndEntityCert::subject_public_key_info()` for pins. Already in the tree through rustls. | | `ring` | `=0.17.14` | CSPRNG, SHA-256, ChaCha20-Poly1305 for sealed logins. Already in the tree through rustls. | | `base64` | `=0.23.1` | base64url for tokens, tickets, logins, PKCE. | | `form_urlencoded` | `=1.2.3` | Query strings and token endpoint form bodies. | | `hyper` | `=1.13.0`, add feature `client` | IdP HTTP calls over `tokio-rustls`, avoiding `reqwest` and its tree. | | `rcgen` | `=0.14.10`, `default-features = false`, features `crypto`, `pem`, `ring` (dev-dependency) | Test certificates. | `flate2` is not needed: `servers.dat` is uncompressed NBT. ## 11. Decision log | Decision | Alternative | Reason | | --- | --- | --- | | Custom framing | yamux | Nine frame types fit on one page with test vectors; Java needs no library and the spec cannot drift with a crate. | | 8-byte fixed header, u16 length | VarInt lengths | Fixed offsets are trivial in Java (`DataInputStream`) and simple to validate. | | 16 KiB max payload | 64 KiB | Matches the TLS record size; keeps latency fair between streams. | | Per-stream window 256 KiB, `WINDOW` after 64 KiB consumed | Session-level window only | Stops one slow player from blocking others and bounds relay memory per stream. | | No session-level window | Both levels | Stream caps (1024 or 8) times 256 KiB bound memory already. | | Credentials in `HELLO`, before framing | An `AUTH` frame | One round trip, and the relay never runs the multiplexer for an unauthenticated peer. | | One TLS port, ALPN split between tunnel and HTTPS | Two ports | One port to open and one certificate; ALPN is in every TLS stack, including Java's. | | TLS 1.2 and 1.3 | 1.3 only | Older Java runtimes in launchers still default to 1.2. | | Pin on SPKI SHA-256, base64 | Certificate fingerprint | Survives certificate renewal with the same key; same format as `curl --pinnedpubkey`. | | Route from `HELLO` field | Hostname in the Minecraft Handshake | The local client connects to `127.0.0.1`, so the Handshake does not name the server. | | Handshake forwarded unchanged | Rewrite the host to the route | Keeps the relay out of the Minecraft protocol; servers do not route on it. | | Ticket 30 s, single use, memory only | Longer, reusable | Limits theft and replay; restarts only cost one re-mint. | | Sealed login (stateless, encrypted) | Server-side login table | No per-login state to persist; revocation lists are small. | | ChaCha20-Poly1305 via `ring` | AES-GCM | Constant-time in software everywhere; `ring` is already in the tree for rustls. | | IdP tokens inside the sealed login | Store them on the relay | Keeps the relay stateless per login while connect still cannot read them. | | Login lifetime fixed at 30 days from login | Sliding expiry | The operator's decision; a fixed end is easier to reason about. | | Re-check with userinfo, refresh when needed | Refresh on every start | Fewer refresh-token rotations; still a live IdP call every start. | | No grace period on IdP outage | Accept last good result for N minutes | Fail closed by default; revoking must always win. Open sessions keep running, which covers short blips. | | Loopback redirect | Device flow first | One click on a desktop; device flow is the automatic fallback for headless machines. | | Relay runs its own PKCE with the IdP | Pass connect's challenge through | The relay is the IdP client and must hold the verifier; connect never sees an IdP code. | | ID token not signature-checked | Fetch JWKS and verify | Token comes over TLS from the token endpoint (OIDC Core 3.1.3.7); avoids a JOSE dependency. | | `client_secret_basic` default | `client_secret_post` | RFC 6749 says servers must support Basic; `auth` overrides for the rest. | | Discord preset with optional guild check | Generic OAuth2 only | Friends' servers usually gate on a Discord server; it is the first real use. | | Secrets in a separate `0600` file with env references | Secrets in the state file or API | Secrets never pass through the API or the state file. | | `authorizer_id` in logins | Keep logins across authorizer changes | Changing who may play must not leave old logins valid. | | One agent session per route, newest wins | Several agents with load balancing | Simple; restarts do not cut existing players; multi-agent is not needed for one server. | | Agent disconnect resets streams | Resume streams | TCP state cannot move between sessions. | | Vanilla clients get a status and disconnect message | Silent close | Players learn what to do; costs a few bytes. | | `version.protocol` echoes the client | Fixed number | Avoids the "incompatible version" label. | | `hyper` client for IdP calls | `reqwest` | Already a dependency; keeps the tree small. | | Agent and connect as `src/bin` in the same crate | Separate crates | Shares the codec and handshake parser; one release product. | | IdP URLs, client id and secret in a secrets-file client entry; authorizers only name a client | URLs in the tenant's authorizer | A tenant-chosen `token_url` would receive the client secret. | | Client `tenant` required, `*` explicit | Absent means every tenant | Sharing a secret across tenants must be a deliberate choice. | | OIDC token and userinfo endpoints must share the issuer's origin unless listed | Trust discovery fully | A tampered or hostile discovery document cannot divert the secret. | | Refuse private addresses for IdP requests unless `SCULKWORM_IDP_ALLOW_PRIVATE=1`; no redirects | Allow any address | The relay must not become an SSRF probe into its own network. | | Device flow: typed code, no `verification_uri_complete`, warning page, `prompt=consent` | Prefilled link | RFC 8628 5.4: a prefilled link makes remote phishing one click. | | Device approval protected by a `__Host-` double-submit cookie and `Sec-Fetch-Site` | No CSRF protection | The relay has no session; without it any site can approve an attacker's code. | | `GOAWAY replaced` has no time limit; the replaced agent exits with code `3` | Reconnect after any `GOAWAY` | Two agents sharing a token would replace each other forever; old players must not be cut. | | Refresh single flight per `lid` plus a 5-minute login cache | Rotate blindly | Rotating IdPs reject reused refresh tokens; a stateless blob may be presented twice. | | Permission re-check on every connect `OPEN`, cached 60 s per login | Only at ticket minting | Sessions live up to 12 hours; revocation and IdP changes must apply to every new player stream. | | A secrets-file mistake leaves routes inactive, never dropped | Drop the route at load | Fixing a typo must not cost the tenant its routes and agent tokens. | | Fixed `HELLO` check order; a ticket is consumed only at the credential step | Consume first | Rate-limited or malformed `HELLO`s must not burn a player's ticket; equal inputs give equal answers. | | `WINDOW` per hop, `ACCEPT` relayed only after the agent's | Forward `WINDOW` end to end | Each hop has its own buffer; forwarding would break the relay memory bound. | | Stream ids must be exactly previous plus one | Any increasing id | One rule, trivially checked, no gaps to track. | | Handshake timeout from TCP accept, 10 s for `SERVER_HELLO` and `ACCEPT`, 15 s per HTTP call | Unbounded waits | A slow TLS handshake must not hold a relay slot; connect must always answer the local client. | ## 12. Open items that need the operator One message can answer all of these: 1. **Discord application.** Create an application at `https://discord.com/developers/applications`, add the redirect `https:///login/callback`, and hand over the client id and client secret (secret through a secret channel, never in chat or the repository). 2. **Public relay hostname and certificate** for the tunnel listener (for example `relay.sculk.network`), and how the certificate is renewed (ACME by a sidecar, or a provided file). 3. **Port.** Confirm the tunnel listener publishes on `443`, or name another port. 4. **First guild for the Discord check**, if the first closed server gates on a Discord server membership. 5. **Downgrade note.** Accept that state version 2 cannot be read by older relays (back up `state.json` before upgrading), as described in [section 8](#8-state-and-persistence-changes). --- Source: https://docs.sculk.network/nightly/sculkworm/verification.md # Real-client verification This runbook covers the automated client checks under `tests/clients/` (open mode, `servers.dat` NBT writer, and closed-mode release-binary end-to-end) and the manual checks that still need a human with real external credentials, a real browser, or a real Minecraft Java Edition / Prism Launcher client. ## 1. Automated checks (offline, no Mojang or Discord account) Install the pinned `minecraft-protocol` (`1.68.0`) / `prismarine-nbt` harness and run all five suites against compiled `sculkworm`, `sculkworm-agent`, and `sculkworm-connect` binaries: ```sh cargo build --locked --bins npm --prefix tests/clients ci --no-audit --no-fund node tests/clients/run-all.mjs ``` Pass `SCULKWORM_BIN_DIR=/path/to/bin-dir` to test release or musl binaries instead of `target/debug/` (every suite resolves binaries through the shared helper in `tests/clients/harness.mjs`: `SCULKWORM_BIN_DIR` first, then explicit per-binary overrides `SCULKWORM_BIN` / `SCULKWORM_AGENT_BIN` / `SCULKWORM_CONNECT_BIN` or the directory of `SCULKWORM_BIN`, then `target/debug/`). CI runs `cargo build --release --locked --bins --target x86_64-unknown-linux-musl` and executes all five suites against those static musl binaries via `SCULKWORM_BIN_DIR`. | Suite | What it proves | What it does not prove | | --- | --- | --- | | `tests/clients/offline-play.mjs` | Real `minecraft-protocol` (`1.68.0`) 1.21.4 (protocol `769`) status pings to two backends, unknown-host zero-byte close, and offline-mode Login → Configuration → Play (`system_chat` + 3 keepalive roundtrips + clean disconnect) through the relay. | Real vanilla Java client binary. | | `tests/clients/online-encrypted.mjs` | Online-mode RSA-1024 Encryption Request/Response, `POST /session/minecraft/join` and `GET /session/minecraft/hasJoined` against `dev/mock-mojang`, AES-128-CFB8 stream activation in both directions, and encrypted Configuration + Play (`system_chat` + 3 keepalive roundtrips) through the relay. | Real `sessionserver.mojang.com`, Microsoft OAuth tokens, Mojang-signed chat keys, or real vanilla launcher. | | `tests/clients/handshake-26.4-srv.mjs` | Wire-level Minecraft 26.4 `_o` (origin, both `%3A` and literal `:`), `_id`, `\0FML\0`, Transfer intent (`3`), 1024-character host strings, verbatim Handshake replay, and pre-26.4 SRV target rejection against the real relay binary. | Real Minecraft 26.4 or pre-26.4 vanilla client DNS/SRV behavior. | | `tests/clients/servers-dat.mjs` | Real `sculkworm-connect play --add-server` writing uncompressed NBT `servers.dat` parsed back by `prismarine-nbt`: missing nested directory creation, empty file handling, appending alongside existing entries/extra root tags, byte-identical idempotent re-runs, in-place `ip` update preserving extra server fields (`icon`, `acceptTextures`, `hidden`), and default `.minecraft` directory discovery. | Rendering in a real Minecraft / Prism Launcher Multiplayer list. | | `tests/clients/closed-e2e.mjs` | Full end-to-end closed mode across the compiled `sculkworm`, `sculkworm-agent`, and `sculkworm-connect` binaries with a loopback HTTPS mock OIDC IdP: OIDC discovery on `PUT /v1/routes/{host}`, `POST .../agent-token`, `sculkworm-agent` with `--ca-file` + SPKI `--pin`, `GET /v1/agents`, vanilla closed-route status ping on port 25565, `sculkworm-connect login --device` (CSRF cookie, `Sec-Fetch-Site`, `confirm=1`, `__Host-swdevcb`, `prompt=consent`), loopback browser redirect login, `sculkworm-connect play --add-server`, real `minecraft-protocol` status ping + Play session through the tunnel, and `logout`. | Real Discord OAuth2 app, real browser UI rendering, Java sync-jar agent, or real Prism/Minecraft 26.4 client. | ## 2. Closed-mode end-to-end run against release binaries Executed locally on 2026-11-27 against optimized release binaries (`cargo build --release --locked --bins`): ```sh cargo build --release --locked --bins SCULKWORM_BIN_DIR="$PWD/target/release" node tests/clients/run-all.mjs ``` Real output from the release binaries (`closed-e2e.mjs` and the full client suite): ```text [step1] PUT /v1/routes/friends.play.example -> 201 {"active":true,"agent_connected":false,"agent_token":null,"authorizer":{"allow":{"any_of":["minecraft"],"claim":"groups"},"client":"mock-oidc","scopes":["openid","profile"],"type":"oidc"},"authorizer_id":"a36e0b5c286c1fd2","host":"friends.play.example","mode":"closed","tenant":"sculk"} [step2] POST agent-token -> 201 token_id=0d35c60dc471b165 prefix=swa_0d35c60d... [step3] GET /v1/agents -> {"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"}]} [step4] vanilla MC status ping -> {"version":{"name":"sculkworm","protocol":769},"players":{"max":0,"online":0},"description":{"text":"Closed server: join it with sculkworm-connect\nsculkworm-connect play friends.play.example"},"sculkworm":{"relay":"https://127.0.0.1:44267","route":"friends.play.example"}} [step5a] connect --device prompt: Open https://127.0.0.1:44267/login/device on any device, sign in and type the code KCXB-SMXC. [step5b] connect --device finished: Logged in to friends.play.example as alex (subject user-alex-42, expires 2026-12-27T09:06:30Z) [step6a] connect loopback start URL captured (route=friends.play.example) [step6b] connect loopback finished: Logged in to friends.play.example as alex (subject user-alex-42, expires 2026-12-27T09:06:35Z) [step7a] servers.dat -> {"servers":[{"ip":"127.0.0.1:35817","name":"friends.play.example"}]} [step7b] tunneled MC status ping -> {"version":{"name":"1.21.4","protocol":769},"players":{"max":20,"online":0,"sample":[]},"description":{"text":"Closed tunnel backend"},"latency":2} [step7c] tunneled MC play -> player=AlexClosed chat="Welcome AlexClosed to Closed tunnel backend" keepalives=3 [step8] logout -> ok (logins remaining: 0) [closed-e2e] OK [offline-play] OK version=1.21.4 protocol=769 host=survival.play.example motd="Survival offline backend" player=SculkPlayer chat="Welcome SculkPlayer to Survival offline backend" keepalives_client=3 keepalives_server=3 [online-encrypted] OK version=1.21.4 protocol=769 host=online.play.example player=Notch uuid=069a79f4-44e9-4726-a5be-fca90e38aaf5 encrypted=true session_calls="POST /session/minecraft/join 204, GET /session/minecraft/hasJoined 200" keepalives_client=3 keepalives_server=3 [handshake-26.4-srv] OK cases=6 version=1.21.4+wire-778 origin=play.origin.example direct=alpha.play.example pre264_srv_target_rejected=relay.edge.example [servers-dat] OK cases=6 route=friends.play.example fresh=127.0.0.1:39321 appended=127.0.0.1:38235 updated=127.0.0.1:37165 idempotent_bytes=198 ``` ## 3. What still needs a human operator Automated suites use a loopback mock OIDC IdP, recorded Discord API fixtures, synthetic HTTP requests in place of a browser, `dev/mock-mojang`, and `minecraft-protocol`. The following items are **not** verified automatically and still require a human with real accounts and UIs (do not invent credentials): 1. **Real Discord application login.** Register a real Discord application at `https://discord.com/developers/applications` with redirect URI `https:///login/callback` (see [tunnel.md section 12](https://docs.sculk.network/nightly/sculkworm/tunnel.md#12-open-items-that-need-the-operator)), put its `client_id` and `client_secret` in `secrets.json`, configure a closed route with `preset: "discord"` (and optional `allow.discord_guild`), and run `sculkworm-connect play ` end to end against `discord.com`. 2. **Real browser rendering of the device and confirmation pages.** Open `https:///login/device` in a real desktop/mobile browser, type the `XXXX-XXXX` user code, verify the visual layout and phishing warning on the confirmation screen, check that `SameSite=Strict` (`__Host-swdev`) and `SameSite=Lax` (`__Host-swdevcb`) cookies work across the IdP redirect back to `/login/callback`, and verify the final completion and denial HTML pages. 3. **Java sync-jar tunnel agent against a real browser login.** Run the Java `clients/sync` pre-launch tunnel client against a live relay with a real browser OAuth/OIDC/Discord login and confirm it carries Minecraft traffic cleanly through Prism Launcher. 4. **Real Prism Launcher / Minecraft 1.21.x and 26.4 runs.** Verify online-mode Mojang login, the Multiplayer server list reading `servers.dat` written by `--add-server`, Minecraft 26.4 `_o` / `_id` Handshake host parameters, and pre-26.4 DNS `SRV` behavior using the manual runbook below. ## 4. Manual Prism Launcher runbook Run these checks when you want real-client proof for **online-mode login with Mojang**, **Minecraft 26.4 `_o` / `_id`**, and **pre-26.4 DNS `SRV` behavior**. ### Prerequisites - Prism Launcher signed in with a real Microsoft/Minecraft account. - Two Prism instances: **1.21.4** (or latest **1.21.x**) and **26.4** (or a **26.4 Snapshot 1+** build). - One online-mode Minecraft backend (Vanilla, Paper, or Fabric) matching each version you test, listening on e.g. `127.0.0.1:25581` (1.21.x) and `127.0.0.1:25582` (26.4). - A running `sculkworm` relay pointing at those backends: ```sh cat > /tmp/verify-routes.json <<'EOF' { "routes": { "v121.play.example": "127.0.0.1:25581", "v264.play.example": "127.0.0.1:25582", "srv.play.example": "127.0.0.1:25582" } } EOF SCULKWORM_LISTEN=0.0.0.0:25565 \ SCULKWORM_ROUTES_FILE=/tmp/verify-routes.json \ ./target/release/sculkworm 2>&1 | tee /tmp/sculkworm-verify.log ``` In a second terminal, tail the relay log and highlight `host=` so you can read the exact route key on every ping and join: ```sh tail -f /tmp/sculkworm-verify.log | grep --line-buffered -E 'event=(route|unknown_host|handshake_rejected|closed)' | grep --line-buffered --color=always -E 'host=[^ ]+|$' ``` ### DNS / hosts setup - **Direct hostname checks (A / `/etc/hosts`)**: add `127.0.0.1 v121.play.example v264.play.example` to `/etc/hosts` (or publish a wildcard `A` record `*.play.example -> `). - **SRV record checks (real DNS required — `/etc/hosts` cannot serve `SRV`)**: publish two records in a zone you control, replacing `play.example` with your domain: 1. `relay.play.example` `A` → `` 2. `_minecraft._tcp.srv.play.example` `SRV` `0 5 25565 relay.play.example.` (target must differ from `srv.play.example` so the client exercises SRV redirection). Add `srv.play.example` to `routes.json`, and do **not** add `relay.play.example`. ### Test cases in Prism In each Prism instance, open **Multiplayer → Add Server**, enter the address below, refresh the server list (Status ping), then click **Join Server** (Login + Play) and check the highlighted `host=` in the log tail. | Case | Prism instance | Server Address | Expected relay log line | | --- | --- | --- | --- | | 1. Online-mode 1.21.x | 1.21.4 / 1.21.x | `v121.play.example` | `event=route host=v121.play.example target=... intent=status` then `intent=login` (player enters world with Mojang auth) | | 2. 26.4 `_id` parameter | 26.4 | `test123@v264.play.example` | `event=route host=v264.play.example target=... intent=status` then `intent=login` (backend sees `?_id=test123` if `allowed-connection-ids=test123`) | | 3. 26.4 SRV `_o` origin | 26.4 | `srv.play.example` (via SRV → `relay.play.example`) | `event=route host=srv.play.example target=... intent=status` and `intent=login` (`_o` overrides `relay.play.example`) | | 4. Pre-26.4 SRV behavior | 1.21.4 / 1.21.x | `srv.play.example` (via SRV → `relay.play.example`) | Record what `host=` actually shows for **both** Status ping and Login (expected per MC-278651: `host=srv.play.example` on Status, `event=unknown_host host=relay.play.example` on Login) | ### Operator results table Fill in one row per test run and attach or commit the results when updating [protocol.md](https://docs.sculk.network/nightly/sculkworm/protocol.md#verification-status): | Date | Client version & launcher | Case | Route key seen (`host=`) | Status / Login OK | Notes | | --- | --- | --- | --- | --- | --- | | YYYY-MM-DD | Prism / Vanilla 1.21.x | 1. Online-mode direct | | | | | YYYY-MM-DD | Prism / Vanilla 26.4 | 2. `_id` (`id@host`) | | | | | YYYY-MM-DD | Prism / Vanilla 26.4 | 3. SRV `_o` | | | | | YYYY-MM-DD | Prism / Vanilla 1.21.x | 4. Pre-26.4 SRV | | | | --- Source: https://docs.sculk.network/nightly/sculkworm/contributing.md # Contributing to Sculkworm Sculkworm is a standalone Rust crate (`crates/sculkworm`) with unit tests (`src/`) and TCP integration tests (`tests/relay.rs`). ## Toolchain and prerequisites - Rust toolchain pinned in [rust-toolchain.toml](https://github.com/YellowUmbrellaDev/sculk.network/blob/26cfdac/crates/sculkworm/rust-toolchain.toml) (`1.100.0`, with `rustfmt` and `clippy`) - `musl-tools` and the `x86_64-unknown-linux-musl` Rust target (only for static release builds outside Docker) - Docker Engine (only for testing the container build) - Node.js 22.18 or later (only for regenerating assets or running a live `minecraft-protocol` smoke check) ## Build from source Run all Cargo commands from `crates/sculkworm`: ```sh cargo build --locked ``` For an optimized release binary: ```sh cargo build --release --locked ``` For a static Linux musl binary (matching CI and [Dockerfile](https://github.com/YellowUmbrellaDev/sculk.network/blob/26cfdac/crates/sculkworm/Dockerfile)): ```sh rustup target add x86_64-unknown-linux-musl CC_x86_64_unknown_linux_musl=musl-gcc cargo build --release --locked --target x86_64-unknown-linux-musl ``` ## Checks and tests ### Format, lint, and Rust tests Run the same Rust checks CI executes: ```sh cargo fmt --check cargo clippy --all-targets -- -D warnings cargo test --locked ``` `cargo test --locked` runs the 21 unit tests in `src/` and the 8 integration tests in `tests/relay.rs`: ```text test result: ok. 21 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out ... test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out ``` ### Live check with a real `minecraft-protocol` client To verify the compiled release binary against a real `minecraft-protocol` client (version `1.21.4`) instead of synthetic TCP fixtures: 1. Build the release binary: ```sh cargo build --release --locked ``` 2. Run a local status-ping test (for example with the two-backend Node script in [Getting started](https://docs.sculk.network/nightly/sculkworm/getting-started.md#2-start-two-local-minecraft-status-backends), or with `prototypes/sculkworm-relay` if present in your checkout) pointing `SCULKWORM_ROUTES_FILE` at a temporary `routes.json` and `SCULKWORM_LISTEN=127.0.0.1:25592`. 3. Confirm each hostname reaches its matching backend, `unknown` hostnames close with zero bytes, and stderr emits `event=listening`, `event=route`, `event=closed`, and `event=unknown_host`. ### Container smoke test Build the Docker image and confirm it starts cleanly with a minimal routes file: ```sh docker build -t sculkworm . ROUTES_FILE="$(mktemp)" printf '{"routes":{"smoke.example":"127.0.0.1:1"}}\n' > "$ROUTES_FILE" chmod 644 "$ROUTES_FILE" docker run -d --name sculkworm-smoke \ -v "$ROUTES_FILE:/etc/sculkworm/routes.json:ro" \ sculkworm docker logs sculkworm-smoke docker rm -f sculkworm-smoke rm -f "$ROUTES_FILE" ``` ## Code layout | File | Responsibility | | --- | --- | | `src/lib.rs` | Public module exports and `RunningRelay` lifecycle handle (`start`, `shutdown`). | | `src/main.rs` | CLI entrypoint, `SCULKWORM_*` startup wiring, `SIGHUP` route reload loop, and `SIGTERM`/`SIGINT` handling. | | `src/config.rs` | `Config::from_env` / `from_lookup`, environment variable parsing, defaults, and bounds checks. | | `src/domain.rs` | `Domain` normalization, `HostField` parsing (`\0` FML suffix, 26.4 query string, `_o` origin, `_id`), and percent-decoding. | | `src/handshake.rs` | Streaming VarInt and Minecraft Handshake (`0x00`) parser, `MAX_HANDSHAKE_PACKET_LEN` (`4096`), legacy ping detection, and `HandshakeError`. | | `src/routes.rs` | `Target` validation (`host:port` / `[ipv6]:port`), strict `routes.json` deserialization, and `RwLock`-backed `RouteTable`. | | `src/relay.rs` | `Relay::serve` accept loop, `Semaphore` concurrency cap, handshake timeout, backend DNS/TCP connect, byte replay, bidirectional splice, and `sanitize_log_value`. | | `tests/relay.rs` | End-to-end TCP integration tests (routing, 1-byte fragmentation, unknown host, timeouts, unreachable backend, live table swap, connection cap, handle drop). | ## Conventions - **Exact-pinned dependencies**: every crate in [Cargo.toml](https://github.com/YellowUmbrellaDev/sculk.network/blob/26cfdac/crates/sculkworm/Cargo.toml) uses an exact version constraint (`=X.Y.Z`) and [Cargo.lock](https://github.com/YellowUmbrellaDev/sculk.network/blob/26cfdac/crates/sculkworm/Cargo.lock) is committed. Pass `--locked` to `cargo build` and `cargo test`. - **No `.unwrap()` in non-test code**: return typed errors (`ConfigError`, `RoutesError`, `HandshakeError`) or handle poisoned locks explicitly (as in `RouteTable` with `unwrap_or_else(|e| e.into_inner())`). Keep `.unwrap()` inside `#[cfg(test)]` and `tests/` only. - **Structured stderr logs**: emit single-line `level= event= key=value` records to stderr. Pass every untrusted client string through `sanitize_log_value` (`src/relay.rs`) and format OS or parse errors with `{:?}`. - **Documentation in sync**: - Environment variables live in `src/config.rs` and are documented in [docs/configuration.md](https://docs.sculk.network/nightly/sculkworm/configuration.md). - Route validation errors live in `src/routes.rs` and are documented in [docs/configuration.md](https://docs.sculk.network/nightly/sculkworm/configuration.md#routes-file-validation-errors). - Handshake framing and rejection reasons live in `src/handshake.rs` and `src/domain.rs` and are documented in [docs/protocol.md](https://docs.sculk.network/nightly/sculkworm/protocol.md). - Visual assets (`assets/icon-64.png`, `assets/logo-288.png`, `assets/logo.svg`, `assets/banner.png`, `assets/social.png`, `assets/mark.svg`) are generated deterministically by `assets/gen-logo.mjs` and `assets/gen-banner.mjs`. - Use relative links only so every page resolves on GitHub and passes `node ../../scripts/check-doc-links.mjs .` from the crate root (or `node scripts/check-doc-links.mjs crates/sculkworm` from the repository root). `pnpm lint` does not check this crate's links, so run one of these yourself. It does parse every Mermaid diagram under `crates/` (`scripts/check-mermaid.mjs`), so a diagram GitHub cannot render fails the build. ## Releases Sculkworm is released from this monorepo with its own version and tags (`sculkworm-v0.3.0`), by the same `release` workflow as sculk.network. [The release guide](https://docs.sculk.network/nightly/sculk/releases.md) has the model and the steps. In short: - Every night, if anything under `src/`, `Cargo.toml`, `Cargo.lock`, `rust-toolchain.toml` or `Dockerfile` changed and `ci-ok` passed on `main`, the workflow publishes `sculkworm-vX.Y.0-nightly..` and the image tags `:X.Y.0-nightly..` and `:nightly`. - A maintainer promotes the latest nightly to a stable release with `gh workflow run release --ref main -f channel=stable -f product=sculkworm`. It publishes `:X.Y.0`, `:X.Y` and `:latest`. - The version lives in the tag and the image's `org.opencontainers.image.version` label. Leave `Cargo.toml` at `0.1.0`, and do not keep a changelog: the GitHub Release notes list the commits that touched Sculkworm. CI in `.github/workflows/ci.yml` runs `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, `cargo test --locked`, a static `x86_64-unknown-linux-musl` build, and a Docker smoke run on every pull request touching `crates/sculkworm/`.