# Browser admission

Browser admission restricts a relay so it opens routes only for web pages served from an operator-approved list of origins. It applies to every connector on that relay. Without admission, the relay routes directly by `<route-id>.<domain>`. Connectors and the control link work the same either way.

Enabling `-allow-origins` makes routing ticket-only for all clients. The relay opens a route only when a client dials `<ticket>.<route-id>.<domain>` from the IP address that received the ticket. Direct dials to `<route-id>.<domain>` (including native clients like `quic-echo` or Go programs) are silently dropped and time out. Use a separate relay without `-allow-origins` if you need direct native QUIC access. With `-debug`, the relay logs a count of dropped unticketed Initial packets at most once every 10 seconds.

## Relay setup

Enable browser admission on `vagus relay` with `-https` and `-allow-origins`:

```sh
vagus relay \
  -public 0.0.0.0:443 \
  -control 0.0.0.0:19451 \
  -https 0.0.0.0:443 \
  -domain relay.example.com \
  -allow-origins https://app.example.com,https://admin.example.com \
  -cert control.pem \
  -key control.key
```

The relay uses `-cert` and `-key` for both HTTPS and connector control links (for example `control.relay.example.com`), so browsers must trust the certificate via Web PKI.

Expose TCP `443` alongside the public UDP port, route both directly to the same relay process, and preserve the client's real IP address. The relay binds tickets to the TCP peer address and ignores `X-Forwarded-For` or similar headers. Putting HTTPS behind a CDN or splitting TCP and UDP across IPv4/IPv6 breaks IP binding.

Configure DNS so `<ticket>.<route-id>.<domain>` resolves to the relay (verify two-label wildcard support with your DNS provider, or add a wildcard under `<route-id>.<domain>`). Application TLS still terminates at your service, which must accept the ticketed SNI and HTTP authority. Pinned leaves (`vagus connect -leaf-dir`) do not require a hostname match; clients that opt out of pinning need a CA-trusted certificate covering `*.<route-id>.<domain>`.

To run admission without `-https`, pass `-admission :19453 -allow-origins ...`. Override the default rate limit with `-admission-rate N`. Origins must be exact serialized origins (scheme, host, and non-default port) with no paths, trailing slashes, or wildcards. HTTP loopback origins (`http://localhost`, `http://127.0.0.1`, `http://[::1]`) are allowed for local development. In [Docker Compose](https://github.com/neuroplastio/vagus/blob/main/examples/compose/docker-compose.yaml), set `ADMISSION_ORIGINS`. Embedded Go relays configure `relay.Options.HTTPS` and `relay.Options.Admission`.

## Client usage

Pass the service's normal URL (`https://<route-id>.<domain>/...`) to `dial` with `admission: true`. The browser client fetches a fresh ticket for each dial and connects to `<ticket>.<route-id>.<domain>`, preserving the path, port, and query string:

```js
import { dial } from "./client.mjs";

const session = await dial(backendURL, {
  relayURL: "https://control.relay.example.com",
  admission: true,
  signal,
});
```

In TinyGo, call `browser.Dial(ctx, backendURL, browser.Options{RelayURL: relayURL, Admission: true})`, or pass `{ relayURL, admission: true }` to `install()`. If the page uses a CSP, allow the relay's HTTPS origin, the WebTransport origins, and `'unsafe-webtransport-hashes'` in `connect-src`.

## Ticket lifecycle

1. The browser sends a CORS `POST` to `/v1/routes/<route-id>`. The relay verifies `Origin` against `-allow-origins` and requires [Fetch Metadata](https://www.w3.org/TR/fetch-metadata/) (`Sec-Fetch-Mode: cors` and `Sec-Fetch-Dest: empty`). `OPTIONS` preflights never issue tickets.
2. If the connector is attached, the relay returns HTTP `201` (`Cache-Control: no-store`) with a random 128-bit hex ticket label, plus the base64-encoded route statement in the `Vagus-Statement` header when available (saving a separate `/v1/statements/<route-id>` fetch). The ticket is bound to the client's source IP and the current connector session, and expires after 30 seconds or if the connector disconnects.
3. On the public UDP socket, packets from unknown source IPs without an outstanding ticket are dropped before QUIC Initial decryption. When a valid packet arrives, the relay checks that `ClientHello` offers `h3` and that SNI matches `<ticket>.<route-id>.<domain>`, then consumes the ticket atomically.
4. Once opened, the route forwards encrypted datagrams for that client `IP:port` with the standard 2-minute idle timeout. The 30-second ticket lifetime applies only to opening the route; established sessions stay open past it.

Every relay with an HTTPS listener also serves route statements at `GET /v1/statements/<route-id>` with `Access-Control-Allow-Origin: *` (no `Origin` check, since statements are self-authenticating).

Fetch Metadata and the `h3` ALPN filter casual scripts, but custom native clients can forge both. Admission gates UDP route creation only; your service must still check WebTransport `Origin` headers and authenticate users.

## Limits and HTTP responses

| Limit / Status | Value / Meaning |
| --- | --- |
| Ticket issuance rate | 30 attempts/min per IPv4 address or IPv6 `/64` (`-admission-rate`), 4,096 buckets |
| Outstanding tickets | 8 per IP, 4,096 total; 30-second expiry |
| Statement reads (`GET /v1/statements/<id>`) | 120/min per IPv4 address or IPv6 `/64` |
| Pass / clearance requests | 10/min per client key; 4,096 keys total (1,024 per route or per origin) |
| Turnstile Siteverify | 4-second timeout, 32 concurrent verifications |
| HTTP `401` | Pass or clearance rejected (client falls back to `getChallenge`, or retries once on clock skew > 1 min) |
| HTTP `429` | Rate limit or table cap exceeded |
| HTTP `503` (`Retry-After: 60`) | Relay overloaded on memory |

Clients behind shared NAT share one IPv4 rate budget, and changing mobile IPs requires a new dial.

## Passes and clearances

When a relay requires a challenge (such as Turnstile), passes and clearances let clients skip repeating the challenge on every dial. Both are signed on each request by a client-owned Ed25519 key (stored as a non-extractable WebCrypto key in browsers) and verified against `<route-id>.<domain>` within 2 minutes of the relay's clock with single-use timestamp replay protection ([wire format](https://vagus.neuroplast.io/docs/protocol#passes)).

| | Route pass | Relay clearance |
| --- | --- | --- |
| Issued by | Service (`pin.SignPass`) | Relay (`Vagus-Clearance` header after passing a challenge) |
| Scope | One route (paired/known client) | Any route on that relay from the same `Origin` |
| Lifetime | Set by service (`notBefore`, `notAfter`) | 12 hours default (`relay.Admission.ClearanceLifetime`) |
| Survives relay restart | Yes | No (relay HMAC key is in memory only) |
| Privacy | Relay sees the client's public key across ticket requests | Relay sees the client's public key while the clearance lasts |

`Origin`, Fetch Metadata, per-IP rate limits, and ticket caps still apply. Neither a pass nor a clearance authorizes a client at the application layer; to revoke a client, reject it in your service and stop issuing passes.

### Using a pass

```js
const session = await dial(backendURL, {
  relayURL: "https://control.relay.example.com",
  admission: true,
  pass, // signed by the service
  signAdmission: m => crypto.subtle.sign("Ed25519", clientKey.privateKey, m).then(s => new Uint8Array(s)),
  getChallenge, // fallback if the pass is rejected
});
```

In TinyGo, set `browser.Options.Pass` and `SignAdmission`.

### Requesting and reusing a clearance

Send the client's 32-byte Ed25519 public key in `clearanceKey` (`Vagus-Clearance-Key` header) alongside `getChallenge`, store the returned clearance from `onClearance`, and pass it back in `pass` on future dials:

```js
const session = await dial(backendURL, {
  relayURL,
  admission: true,
  getChallenge,
  clearanceKey: publicKeyBytes,
  onClearance: c => store(c),
  signAdmission,
});
```

In TinyGo, set `browser.Options.ClearanceKey`, `OnClearance`, and `SignAdmission`. When `SignAdmission` is set and a dial falls back to WebSocket, it reuses the clearance from the first ticket so the user solves at most one challenge per dial.

## Turnstile verification

To gate ticket requests behind Cloudflare Turnstile, create a widget for your allowed page hostnames, mount its secret file read-only on the relay host, and pass `-turnstile-secret-file=/run/secrets/turnstile`. Put the public site key in your web page. When configured, every ticket request without a valid pass or clearance must pass Turnstile verification. Cloudflare receives the challenge token and client IP; when unconfigured, the relay makes no outbound requests.

Render or execute the widget per dial with `action: "vagus_route"` and `cData` set to the route ID, and return the token from `getChallenge(endpointID, signal)`:

```js
async function getChallenge(endpointID, signal) {
  signal?.throwIfAborted();
  let widget;
  let abort;
  try {
    return await new Promise((resolve, reject) => {
      abort = () => reject(signal.reason);
      signal?.addEventListener("abort", abort, { once: true });
      widget = turnstile.render("#challenge", {
        sitekey: PUBLIC_SITE_KEY,
        action: "vagus_route",
        cData: endpointID,
        callback: resolve,
        "error-callback": () => reject(new Error("Challenge failed")),
        "expired-callback": () => reject(new Error("Challenge expired")),
      });
    });
  } finally {
    signal?.removeEventListener("abort", abort);
    if (widget !== undefined) turnstile.remove(widget);
  }
}
```

Pass `{ relayURL, admission: true, getChallenge }` to `dial` (or to `install` for TinyGo). The relay calls Cloudflare [Siteverify](https://developers.cloudflare.com/turnstile/get-started/server-side-validation/) and checks `success`, hostname, `action`, and `cData`. Timeouts or mismatches reject admission. Turnstile deters scripted abuse, though an automated browser on an allowed origin can still request tickets.
