# 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_<id>_<secret>`, 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 <pem>` 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/<base64>` (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/<base64>` 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 <host[:port]>` needs the relay URL of the route:

1. If `--relay <url>` 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 `<host>:<port>` (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 <ip:port>`. 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[=<path>]` 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=<path>` targets an existing
  Minecraft directory (`--add-server=<dir>`) or a `servers.dat` file (`--add-server=<dir>/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:<random port>/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 <name>, but <route> 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
   `<redirect_uri>?code=<relay code>&state=<connect 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_<base64url 32 bytes>","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=<base64url of 32 random bytes>; 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=<base64url of 32 random bytes>; 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:<port>/callback` or `http://[::1]:<port>/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 <route>` 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": "<name>", "any_of": ["…"]}` for `oidc`, `{"field": "<name>", "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": "<server id>"}`, 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 == <server 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": "<guild id>"}`, 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
`<issuer>/.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 <issuer>: <reason>`).
- 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>"` | `type` is not `fixed-list`, `oidc` or `oauth2`. |
| `authorizer: unknown field "<field>"` | Any unknown field, at any depth. |
| `authorizer: <field> is required` | A required field is missing. |
| `authorizer: client "<name>" 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 "<name>" is an <kind> 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 <issuer>: <reason>` | Discovery failed; `<reason>` is one of `timeout`, `tls`, `http_<status>`, `invalid_document`, `issuer_mismatch`, `endpoint_origin_mismatch`, `forbidden_address`. |
| `authorizer: subjects must hold 1 to 1000 unique values` | Bad `subjects`. |
| `authorizer: allow.<field> 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 <path>
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>` | 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="<message>"` and exit with code `2` at startup. Messages
follow the pattern `client "<name>": <field> <problem>`, 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 "<name>" is used by route <host>`) or set a used client's `tenant` to a tenant other than the route's owner
and other than `*` (`client "<name>" is used by route <host> of tenant <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_<status>`.
- 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=<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://<relay public host>/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).
