Skip to content
FlyCockpit
Tunnel/ Access Gates & CLI
Tunnel logo

Access Gates, CLI & Management API

TunnelRustMIT
Repository

Configure link, password, and public access modes, understand zone-host cookie isolation and instant mid-stream revocation, and use the tunnel CLI, /v1 REST API, and tnsvc_ service tokens.

Platforms: Linux (server & client) · macOS (client)

Every tunnel exposed through tunnel-server sits behind a reverse-proxy access gate before traffic is forwarded over Yamux to the local machine or sandbox.

Access Modes

Choose or change a tunnel’s access mode at creation (tunnel share, POST /v1/tunnels) or live (PATCH /v1/tunnels/{id}):

Mode Behavior Notes
link (default) Visitors must open a minted access link (https://<zone>/__access/{port}-{id}/{token}) to obtain a gate cookie session. Single-use by default (valid 10 min) or --reusable until expiry. One session covers all ports of that tunnel.
password Visitors sign in at https://<zone>/__login?to={port}-{id}&next=... with the tunnel’s username (default preview) and password. Access links still work. Only page loads (Sec-Fetch-Dest: document|iframe|frame, or Accept: text/html) redirect to /__login. API/CLI clients (curl, fetch, agents) get HTTP 401 ({"error":"password_required","message":"...","login_url":"..."}). No HTTP Basic.
public Anyone with the preview URL (https://{port}-{id}.<zone>) reaches the local port without a gate session. Allowed for the admin token, admins, members with can_public, or when limits.allow_public_for_clients = true. Otherwise returns HTTP 403 public_not_allowed.

Dashboard Owner Sign-In (Open)

On the web UI’s Tunnels page, clicking Open on one of your own tunnels requests a single-use, 1-minute owner link (POST /ui/api/tunnels/{id}/open) and opens the preview already authenticated—even when preview_zone is on a separate registrable domain from ui_host. Owner links cover only the requested port, allow a 10-second same-IP retry for browser reconnects, and never redeem on HEAD requests. Admins viewing other users’ tunnels get Visit (normal gate) or can mint an audited access link under Links.

Zone-Host Sign-In Separation and Browser Defenses

All authentication routes—/__access/{port}-{id}/{token} and /__login—exist only on the preview zone apex (https://<preview_zone>), never on individual {port}-{id}.<preview_zone> preview hosts. This keeps untrusted preview pages and service workers completely isolated from access tokens and login forms.

  • Partitioned gate cookie: Redeeming a link or signing in sets a Secure, HttpOnly, Partitioned, SameSite=None cookie scoped to the tunnel. A session created inside an iframe belongs strictly to that parent site’s CHIPS storage partition; opening the preview directly in a top-level tab requires its own sign-in.
  • Framing control (frame_ancestors): Defaults to an empty list (previews can be framed only by their own origin). List explicit HTTPS parent origins during setup or in config.toml; allowing any site requires explicit --frame-ancestors '*'.
  • Cross-preview Origin protection: On WebSocket upgrades and state-changing requests carrying a gate cookie, the gate verifies Origin and allows only the tunnel’s own preview hosts, explicit frame_ancestors entries (* does not count), requests with no Origin (non-browser clients), and top-level cross-site form posts (such as OAuth form_post callbacks). Requests from any other preview host receive HTTP 403.
  • Inline gate favicon: Gate error and sign-in pages embed the padlock icon inline so browsers never leak pre-auth /favicon.ico requests.

Instant Mid-Stream Revocation

Revoking access cuts in-flight traffic immediately, not just future requests. Whenever any of the following occur:

  • An access link is revoked (tunnel unlink, DELETE /v1/access-links/{id})
  • The tunnel’s access mode or password changes
  • The tunnel is deleted, expires (swept within 15 s), rotates its token, or disconnects
  • The owning user hits their monthly traffic cap
  • A gate session expires

every active HTTP request, chunked download, SSE stream, upload, and WebSocket on that tunnel stops relaying immediately and rechecks authorization:

  • Streaming responses (SSE, downloads) are aborted mid-body so clients see a broken transfer instead of a falsely complete response.
  • Uploads are severed and the upstream connection closed.
  • Requests still waiting for origin headers receive 401; WebSockets close immediately.
  • Each cut increments the tunnel_access_cuts_total Prometheus counter.

The sole exception is an unauthenticated CORS OPTIONS preflight (stripped of cookies and body), which holds no session to revoke.

tunnel CLI Reference

Logged-In Machine Commands

After running tunnel login, credentials are stored in $XDG_CONFIG_HOME/tunnel/login.json (default ~/.config/tunnel/login.json, mode 0600).

Command Description
tunnel login [https://<ui_host>] With a URL: browser-approved RFC 8628 device flow (--name, --no-browser). Without a URL: prompts for a one-time tnenr_...@<host> code from tunnel-server client add.
tunnel share <port>... [flags] Create or reuse the machine’s shared tunnel and expose local ports. Flags: --name "<label>" (max 80 chars), --link (default), --public, --password [--username <name>] (reads TUNNEL_SHARE_PASSWORD or prompts), --ttl <30m|8h|2d|never> (default 8h), --for[=<dur>] (exclusive with --ttl; default 1h; creates a new foreground tunnel that deletes itself on exit/SIGTERM), --target <ip>, --json.
tunnel link [flags] Mint an additional access link for the current shared tunnel. Flags: --port <port>, --reusable, --ttl <dur> (default 10m), --label <text>, --json.
tunnel links [--json] List active links on the shared tunnel (IDs, labels, usage, expiry; link URLs are never stored server-side).
tunnel unlink <id> Revoke one access link and immediately terminate all sessions and streams derived from it.
tunnel unshare [port...] Stop sharing specific ports, or delete the shared tunnel and stop the daemon when no ports are given.
tunnel status [--json] Show daemon state (connecting, connected, revoked, replaced, stopped), tunnel_id, host_template, ports, mode, name, login_url (in password mode), ice_file, and features.
tunnel logout Revoke this machine’s server login via DELETE /v1/login (ending its tunnels) and remove local login.json.
tunnel help agent Print the built-in agent operating guide (docs/agent/SKILL.md).

Sandbox and Supervised Daemon Commands

Inside sandboxes or CI jobs, pass a tunnel token via TUNNEL_TOKEN (never via command-line arguments):

# Automatic background daemon mode
TUNNEL_TOKEN=tntun_... tunnel expose 3000 5173
tunnel expose 3000 --target 10.20.0.2          # dial a VM IP literal instead of loopback
tunnel unexpose 5173
tunnel ice --format json|env|file [--fresh]
tunnel ice --exec -- npm run dev              # launch process with TURN_*/ICE_* env vars
tunnel stop                                   # stop daemon and forget ports (also deletes shared tunnel)

# Foreground supervised daemon mode (e.g. systemd unit on a sandbox host)
tunnel --state-dir /run/user/1000/tunnels/sbx-1 daemon

On Linux, the daemon marks itself non-dumpable (PR_SET_DUMPABLE=0) so other processes of the same user cannot inspect its token through /proc or ptrace. Place --state-dir on tmpfs (such as /run/user/<uid>/...) if the persisted state.json (mode 0600) should never touch disk.

Environment Variables and Exit Codes

Variable Meaning
TUNNEL_TOKEN Tunnel token (tntun_...). Refused without the tntun_ prefix.
TUNNEL_SERVER Server URL (wss://tunnel.example.com, https://..., or bare host). Falls back to logged-in server, daemon state, then build-time TUNNEL_DEFAULT_SERVER.
TUNNEL_TARGET_HOST IPv4 or IPv6 literal dialed instead of loopback (hostnames are refused).
TUNNEL_STATE_DIR Absolute path for daemon socket, lock, and state (same as --state-dir). Default: $XDG_RUNTIME_DIR/tunnel or /tmp/tunnel-<uid>.
TUNNEL_ICE_FILE Path kept fresh with current ICE JSON (default /run/tunnel/ice.json if writable, else <state-dir>/ice.json).
TUNNEL_ICE_PORT Local ICE HTTP endpoint port on 127.0.0.1 (default 47801; authenticated with Authorization: Bearer $TUNNEL_ICE_TOKEN).
TUNNEL_SHARE_PASSWORD Non-interactive password for tunnel share --password.
RUST_LOG Log verbosity (daemon default info, CLI commands warn).
Exit Code Meaning
0 Success.
1 Runtime error (printed to stderr as tunnel: ...).
2 Invalid CLI arguments.
3 Revoked: tunnel expired/deleted or token rejected. Do not auto-restart; create a new tunnel.
4 Replaced: another client connected with the same token (e.g. after token rotation or duplicate start).

REST /v1 Management API

The management API is served on api_host (and ui_host when enabled) with full OpenAPI metadata at GET /v1/openapi.json. Authenticate with Authorization: Bearer <token>:

  • tnadm_... (Admin token): Full control over all tunnels, clients, and services; exempt from per-client quotas.
  • tncli_... (Client token): Scoped to tunnels and links created by that enrolled machine, subject to account and per-client limits.
  • tnsvc_... (Service token): API-only credential for platforms like wssp, scoped to its own tunnels and max_tunnels quota.

List endpoints accept limit (default 100, range 1–500) and cursor (pass the previous response’s next_cursor; omitted on the last page). GET /v1/tunnels also supports exact-match ?label=<value>.

Method & Endpoint Caller Purpose
GET /v1/openapi.json Public OpenAPI 3 schema document.
GET /v1/server Admin / Client / Service Discover API, control, gate, and UI origins, host_template, and caller limits.
POST /v1/tunnels, GET /v1/tunnels Admin / Client / Service Create a tunnel (returns tntun_ once) or list owned tunnels.
GET / PATCH / DELETE /v1/tunnels/{id} Admin / Owner Inspect, update (name, access, ttl_s, never_expires, inject_ice), or delete a tunnel.
POST /v1/tunnels/{id}/token Admin / Owner Rotate the tntun_ token (closes existing connection with exit code 4).
POST / GET /v1/tunnels/{id}/access-links Admin / Owner Mint a new access link (url returned once) or list active links.
DELETE /v1/access-links/{id} Admin / Owner Revoke an access link and cut active sessions immediately.
POST /v1/tunnels/{id}/turn-credentials Admin / Owner Mint fresh WebRTC TURN REST credentials for a tunnel.
POST / GET /v1/clients, PATCH / DELETE /v1/clients/{name} Admin Create headless enrollment code (tnenr_), list, rename, or revoke enrolled machines.
POST /v1/clients/enroll Enrollment code Exchange a one-time tnenr_ code for a long-lived tncli_ token.
POST /v1/device/code, POST /v1/device/token Public (RFC 8628) Browser-approved device login flow for tunnel login.
DELETE /v1/login Client Self-revoke the calling machine’s tncli_ login and end its tunnels.
POST / GET /v1/services, PATCH / DELETE /v1/services/{name}, POST /v1/services/{name}/token Admin Manage tnsvc_ service credentials, quotas, and token rotation.

Service Tokens (tnsvc_) for Sandbox Platforms (wssp)

When integrating Tunnel with an automated sandbox host such as WS Sandbox Proxy (wssp), mint a dedicated tnsvc_ service credential instead of sharing the admin token:

# Create a service credential with a 200-tunnel cap (writes mode 0600 file instead of printing)
sudo tunnel-server service add wssp --max-tunnels 200 --token-file /etc/wssp/tunnel.token

# Inspect, resize, rotate, or revoke service credentials
sudo tunnel-server service list
sudo tunnel-server service set wssp --max-tunnels 500
sudo tunnel-server service rotate wssp --token-file /etc/wssp/tunnel-new.token
sudo tunnel-server service delete wssp

A tnsvc_ token can create, update, rotate, and delete only the tunnels it owns (up to its max_tunnels limit; HTTP 429 tunnel_quota beyond that) and mint/revoke their access links. It cannot manage clients, users, or other services, and user-account traffic caps never apply to it. Hand each sandbox only its individual tntun_ token via TUNNEL_TOKEN, and rotate that token (POST /v1/tunnels/{id}/token) whenever a sandbox moves to another host.