# Protocol

Wire specification for `vagus/1`, implemented in `pkg/connector/protocol`, `pkg/relay`, `pkg/connector`, `pkg/pin`, `pkg/noise`, and `pkg/session`. For trust boundaries and threat analysis, see [Security and threat model](https://vagus.neuroplast.io/docs/security). For HTTPS ticket admission, see [Browser admission](https://vagus.neuroplast.io/docs/admission).

## Identity key and route ID

Each connector has an Ed25519 key pair (PKCS#8 `PRIVATE KEY` PEM, mode `0600`, when created by `vagus keygen` or `vagus bootstrap`).

```text
RouteID(pubKey) = lowercase(base32_no_padding(SHA-256(raw_32_byte_ed25519_public_key)))
```

RFC 4648 base32 without `=` padding yields 52 lowercase DNS-safe characters, combined with `-domain` as `<route-id>.<domain>`.

## Control link and admission (`vagus/1`)

The connector dials the relay's control UDP port over QUIC with:

- TLS 1.3 (`MinVersion: tls.VersionTLS13`, `CurvePreferences: [tls.SecP384r1MLKEM1024]`, exposed as `protocol.KeyExchange`)
- ALPN `vagus/1`
- `EnableDatagrams: true`
- `InitialPacketSize: 1452`
- `DisablePathMTUDiscovery: true`
- `KeepAlivePeriod: 10s`

Both `vagus relay` (on `-control`) and `vagus connect` (`connector.Dial`, `connector.Probe`) require hybrid P-384 + ML-KEM-1024 (`SecP384r1MLKEM1024`, IANA `0x11ED`); the relay rejects connectors offering only `X25519MLKEM768`. The relay's HTTPS listener (`-https`) and `vagus handoff serve` require `X25519MLKEM768`.

### Control messages

Control messages are MessagePack maps keyed by field name, written back-to-back on a stream without outer length framing. Message type is determined by position on the stream; unknown map fields are ignored.

| Message | Sender | Fields |
| --- | --- | --- |
| `hello` | Connector | `mode`: `"stream"` or `"datagram"`; `key`: 32-byte Ed25519 public key (`bin`); `sessions`: accepts browser WebSocket sessions (`bool`) |
| `challenge` | Relay | `nonce`: 32 random bytes (`bin`) |
| `proof` | Connector | `signature`: 64-byte Ed25519 signature (`bin`) |
| `admitted` | Relay | Empty map `{}` |
| `statement` | Connector | `statement`: signed statement, 1 to 4,096 bytes (`bin`) |
| `stored` | Relay | Empty map `{}` |
| `session` | Relay | `origin`: page `Origin` header, up to 256 bytes (`str`) |

Admission runs on the first bidirectional stream opened by the connector under a 10-second deadline on both ends (`hello`, `challenge`, `proof`, `admitted`). Readers enforce limits before allocating: at most 8 map fields, strings up to 16 bytes (256 bytes for `session.origin`), and per-field byte limits.

### Admission handshake

<!-- docs:figure text=admission-handshake.ans text-narrow=admission-handshake-tall.ans svg-narrow=admission-handshake-tall.svg -->
![Admission handshake between vagus connect and vagus relay: QUIC and TLS 1.3 handshake with ALPN vagus/1 and SecP384r1MLKEM1024, connector verifies relay cert, sends hello with mode, key, and sessions, relay generates a 32-byte nonce and sends challenge, both derive a 32-byte TLS exporter transcript bound to nonce and mode, connector sends Ed25519 proof signature, relay verifies and registers the route, replies admitted, and packet forwarding begins.](https://vagus.neuroplast.io/docs/_files/docs/admission-handshake.svg)

Wire specifics:

- The relay rejects `mode: "datagram"` unless QUIC datagrams were negotiated.
- Channel binding uses TLS 1.3 `ExportKeyingMaterial` with label `"EXPORTER-vagus-admission-stream"` or `"EXPORTER-vagus-admission-datagram"`, context equal to the 32-byte `nonce`, and length 32. `proof` is a pure Ed25519 signature (`crypto.Hash(0)`) over that 32-byte transcript.
- If an older control link is registered under `RouteID(key)`, the relay reassigns the route to the new link and closes the older link with application error `4` (`ErrReplaced`). If the relay is at its connector limit or overloaded, it closes the new link with application error `3` (`ErrRelayFull`).
- When an admitted control link closes, the relay deletes the connector registration and tears down its active client routes.

### Statements

An admitted connector publishes its route statement (`pkg/pin`) by opening a new bidirectional stream, writing `statement`, and waiting for `stored`. If the route's identity key did not sign the statement, the relay resets the stream with stream error `1` (`ErrStatementRefused`). The relay serves the latest valid statement at `GET /v1/statements/<route-id>` while the control link stays up.

A statement is a MessagePack map `{statement, signature}`:

- `statement`: raw bytes of an encoded MessagePack map `{key, leaves, noise, data}` containing `key` (32-byte Ed25519 public key), `leaves` (1 to 4 maps `{sha256, not_before, not_after}` with MessagePack timestamps), `noise` (0 to 4 maps `{key, not_before, not_after}` containing 32-byte X25519 static keys for `Noise_NKhfs_25519+MLKEM1024_ChaChaPoly_SHA256`), and `data` (optional application bytes, up to 2,048 bytes).
- `signature`: Ed25519 signature over `"vagus statement v1\x00"` concatenated with the raw `statement` bytes.

Verifiers check `RouteID(key)` against the expected route ID and verify `signature` over the exact received `statement` bytes (never a re-encoding) before trusting any field. Leaves and Noise keys are accepted only while valid and issued for less than 14 days. Shared Go and JS test vectors are in `pkg/pin/testdata/vectors.json`.

### Passes

A pass is a MessagePack map `{pass, signature}` (at most 256 bytes):

- `pass`: raw bytes of an encoded MessagePack map `{route, client, not_before, not_after}` with the route's 32-byte Ed25519 identity key, the client's 32-byte Ed25519 public key, and MessagePack validity timestamps.
- `signature`: route identity key's Ed25519 signature over `"vagus pass v1\x00"` concatenated with the raw `pass` bytes.

A pass-authenticated ticket request is a `POST /v1/routes/<route-id>` with `Content-Type: application/vnd.vagus.admission+msgpack` (at most 512 bytes) containing a MessagePack map `{pass, at, signature}`: the pass bytes, the request timestamp (`at`, whole milliseconds), and the client key's Ed25519 signature over `"vagus admission v1\x00" || lowercase("<route-id>.<domain>") || 0x00 || uint64_be(unix_ms(at))`. Shared Go and JS test vectors are in `pkg/pin/testdata/admissions.json`.

### Clearances

A clearance is a MessagePack map `{clearance, mac}`:

- `clearance`: raw bytes of an encoded MessagePack map `{client, not_before, not_after}` (32-byte Ed25519 client public key and MessagePack timestamps).
- `mac`: HMAC-SHA256 under the relay's random in-memory key over `"vagus clearance v1\x00" || origin || 0x00 || clearance`.

The client submits a clearance in the same `pass` field of a ticket request. Only the relay process that issued it can verify it.

### Round-trip probe

`connector.Probe` opens a control connection, sends `hello` with a throwaway key, waits for `challenge`, and closes the connection without claiming a route.

## Client SNI routing and data flow

<!-- docs:figure text=sni-routing.ans text-narrow=sni-routing-tall.ans svg-narrow=sni-routing-tall.svg -->
![Client SNI routing and data flow across QUIC v1 or v2 client, vagus relay, vagus connect, and QUIC service: client sends Initial UDP datagrams of at least 1200 bytes, relay decrypts Initial with version salt and DCID, reassembles CRYPTO frames up to 8 packets and 16 KiB to read SNI, allocates a 32-bit return-route ID and maps client IP:port, forwards buffered original Initials tagged with the return-route ID to vagus connect, which opens a connected UDP socket and writes untouched Initials to the QUIC service; return datagrams follow the reverse path using the return-route ID, and subsequent packets bypass Initial inspection via the client address map.](https://vagus.neuroplast.io/docs/_files/docs/sni-routing.svg)

### QUIC Initial inspection

When a datagram arrives on `-public` from an unknown `IP:port`:

- Accepts only datagrams of at least 1,200 bytes with QUIC v1 (`0x00000001`, header nibble `0xc0`) or QUIC v2 (`0x6b3343cf`, nibble `0xd0`) client Initial headers.
- Derives the client Initial secret from the destination connection ID and version salt (`quic ` labels for v1, `quicv2 ` for v2; AES-128-GCM per [RFC 9001 §5.2](https://www.rfc-editor.org/rfc/rfc9001.html#section-5.2) and [RFC 9369 §3](https://www.rfc-editor.org/rfc/rfc9369.html#section-3)).
- Walks `PADDING` (`0`), `PING` (`1`), and `CRYPTO` (`6`) frames into a 16 KiB buffer while buffering up to 8 original datagrams so multi-packet post-quantum `ClientHello` flights (with ML-KEM key shares) reassemble cleanly. Unexpected frame types discard the pending flight.
- Once contiguous `CRYPTO` bytes cover `ClientHello` (type `1`), scans extensions for `server_name` (extension `0`, host name type `0`), lowercases it, strips `.<domain>`, binds `clientAddr -> route` and `returnRouteID -> route` (verifying/consuming an admission ticket if enabled), and enqueues all buffered original datagrams untouched onto the connector's 128-packet outbound queue.

For each new return-route ID, `vagus connect` opens a dedicated connected UDP socket (`net.DialUDP`) to `-backend`, expiring after 2 minutes (`RouteLifetime`) of bidirectional inactivity, up to 1,024 active routes per connector (`MaxRoutes`). See [Routing constraints](https://vagus.neuroplast.io/docs/operations#routing-constraints) for ECH, migration, and tuple-binding limits.

## Framing modes

Every forwarded inner UDP datagram starts with a 4-byte big-endian non-zero `uint32` return-route ID prefix.

### Stream mode

Default (`-mode stream`). Reuses the bidirectional admission QUIC stream:

| Field | Size | Encoding |
| --- | --- | --- |
| Record length | 2 bytes | Big-endian `uint16`, equal to `4 + len(payload)` (max `65535`) |
| Return-route ID | 4 bytes | Big-endian non-zero `uint32` |
| Inner UDP payload | 1 to 65,531 bytes | Untouched client/service QUIC datagram |

Records must be 5 to 65,535 bytes total. Writes have a 5-second deadline; a failure closes the control link with application error `1` (`"packet stream write failed"`). QUIC stream segmentation splits large records across outer packets automatically.

### Datagram mode

Enabled with `-mode datagram`. Uses QUIC `DATAGRAM` frames (RFC 9221):

| Field | Size | Encoding |
| --- | --- | --- |
| Return-route ID | 4 bytes | Big-endian non-zero `uint32` |
| Inner UDP payload | Variable | Untouched client/service QUIC datagram |

No length prefix is needed because `DATAGRAM` frames preserve message boundaries. Because PMTUD is disabled at a 1,452-byte outer UDP payload, `4 + len(payload)` must fit within `MaxDatagramPayloadSize`. Oversized packets (`*quic.DatagramTooLargeError`) are dropped without closing the link and logged once per control link.

## WebSocket fallback sessions

When UDP is blocked, the Wasm browser client can connect to a connector advertising `hello.sessions = true` (`connector.WithSessions`) over a WebSocket to the relay's HTTPS listener:

1. The client opens `wss://<relay-host>/v1/sessions/<ticket>` (when admission is enabled; single-use ticket bound to client IP and allowed `Origin`) or `wss://<relay-host>/v1/sessions/<route-id>` otherwise. WebSocket TLS ends at the relay (with `X25519MLKEM768` enforced).
2. The relay opens a bidirectional QUIC stream on the connector's control link, writes a `session` control message containing the page's `Origin`, and relays bytes bidirectionally between WebSocket binary messages and the stream without inspecting them. Normal WebSocket close sends stream FIN; abnormal close resets the stream.
3. Over that byte stream, each Noise message is prefixed with a 2-byte big-endian length. Client and service run `Noise_NKhfs_25519+MLKEM1024_ChaChaPoly_SHA256` (`pkg/noise`, Noise NK revision 34 with hybrid forward secrecy `hfs` revision 1 and ML-KEM-1024) against a static X25519 key listed in the route's signed statement, with prologue `"vagus session v2\x00" || routeID` (hello overhead: 1,632 B; reply overhead: 1,632 B). Handshake payloads are empty (`{}` on reply); once transport keys (derived from both X25519 and ephemeral ML-KEM-1024) are established, the client sends `{path}` (starting with `/`, up to 1,024 bytes) in the first transport message so the path is post-quantum encrypted as well. The connector tries each key from `SetNoiseKeys` so sessions continue working across key rotation.
4. Every subsequent Noise transport message contains one `pkg/session` frame: either a data frame (`0x00` + 4-byte big-endian stream ID + payload bytes) or a control frame (`0x01` + MessagePack map `{kind, stream, credit, code, reason}`):

| `kind` | Meaning |
| --- | --- |
| `open` | Opens `stream` (odd IDs from browser, even IDs from service, monotonically increasing) |
| `credit` | Grants `credit` additional receive bytes on `stream` (or session-wide when `stream` is `0`) |
| `fin` | Half-closes sender's write side on `stream` |
| `reset` | Aborts sender's write side on `stream` with `code` |
| `stop` | Tells peer to stop writing on `stream` with `code` |
| `close` | Closes the session with `code` and optional `reason` (up to 256 bytes) |
| `ping` | Keepalive sent after 30 seconds without outbound traffic |

Initial flow-control windows are 256 KiB per stream and 1 MiB per session; exceeding either closes the session. Streams beyond 128 open or 32 queued for accept are refused with `stop` and `reset` (code `0x52`). A service without capacity closes the session with code `0x42`; protocol violations close with code `0x01`.
