Skip to content
FlyCockpit
Tunnel/ WebRTC & Operations
Tunnel logo

WebRTC, Email & Operations

TunnelRustMIT
Repository

Run Tunnel's built-in STUN/TURN WebRTC relay, configure optional SMTP notifications, monitor /healthz and Prometheus metrics, back up and restore SQLite, and rotate server secrets.

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

tunnel-server ships with an embedded STUN/TURN relay, optional SMTP delivery, health and Prometheus monitoring endpoints, online SQLite backup/restore, and zero-downtime secret rotation.

Built-In WebRTC STUN/TURN Relay

Enable WebRTC during setup (tunnel-server setup --webrtc true) or in config.toml under [webrtc]. Because the relay is built directly into tunnel-server, no external coturn daemon is needed and it runs seamlessly in rootless installs.

Listeners and Firewall Rules

Port / Protocol Purpose
UDP 3478 and TCP 3478 Standard STUN and TURN (webrtc.stun_port, configurable).
TCP 443 TURN-over-TLS multiplexed via SNI peek on turn.<host> (and TLS connections without SNI when webrtc.passthrough_no_sni = true). Covered automatically by the server’s wildcard certificate and DNS record.
UDP 49160–49999 Relayed media sockets on public_ipv4 (webrtc.relay_min_port through webrtc.relay_max_port, inclusive; 840 ports by default).

System installs open these ports in ufw/firewalld automatically; rootless installs print the exact rules to apply. Always open the same ports in your cloud provider firewall.

Quotas and Security Controls

  • Private-peer protection: Relays can never dial loopback, RFC 1918, link-local, or non-public addresses, nor any of the server’s own other ports. Relay-to-relay traffic stays in process.
  • Allocation & bandwidth caps:
    • Global ceiling: 1,200 active allocations (also bounded by your configured UDP port range).
    • Bandwidth: 3 Mbit/s combined (both directions) per relay allocation.
    • TCP/TLS connections: 1,000 concurrent connections max; unauthenticated TCP/TLS TURN connections are closed promptly.
    • Per-tunnel and per-source-IP quotas: 240 allocations each (IPv6 sources share a /64 quota). Exceeding a quota returns TURN error 486 (Allocation Quota Reached).
  • Immediate revocation: Deleting a tunnel immediately invalidates its TURN REST credentials (webrtc.static_auth_secret) and closes every open relay allocation for that tunnel.

ICE Injection and Server-Side Peers

  • Browser apps: When WebRTC and a tunnel’s inject_ice flag (default true) are enabled, the edge automatically injects fresh TURN credentials (default TTL browser_ttl_s = 3600) into HTML preview pages via a streaming <script> tag and updates the page’s CSP hash accordingly.
  • Server-side WebRTC peers (SFUs, aiortc, Pion, voice agents): The tunnel daemon keeps fresh credentials (sandbox_ttl_s = 86400) on disk and optionally on loopback HTTP:
    # Launch a dev server with TURN_URLS, TURN_USERNAME, TURN_CREDENTIAL, ICE_SERVERS_JSON, ICE_EXPIRES_AT, TUNNEL_ICE_FILE
    tunnel ice --exec -- npm run dev
    
    # Or evaluate into the current shell (note the semicolon; never pass the command inside eval)
    eval "$(tunnel ice --format env)"; npm run dev
    Long-running peers should re-read $TUNNEL_ICE_FILE (default /run/tunnel/ice.json or <state-dir>/ice.json) or poll GET $TUNNEL_ICE_URL (http://127.0.0.1:47801/ice) with Authorization: Bearer $TUNNEL_ICE_TOKEN before ICE_EXPIRES_AT. Automation services can also mint credentials via POST /v1/tunnels/{id}/turn-credentials.

Warning: Never commit TURN credentials, ICE JSON, or ephemeral preview hostnames into source code or .env files. Always read them at runtime.

Optional SMTP Mail Setup

Tunnel works completely without email (invite and reset links are copied and handed over manually). Configuring an SMTP relay enables mailed invites, email address confirmation, self-service Forgot password, and automated security notices.

# Interactive setup (prompts for host, port, user, hidden password, sender, sends test mail, saves, restarts)
sudo tunnel-server mail setup

# Scripted setup (pass password via $SMTP_PASS, never as a CLI flag)
IFS= read -rs SMTP_PASS && export SMTP_PASS
sudo -E tunnel-server mail setup --yes \
  --smtp-host email-smtp.us-east-1.amazonaws.com --smtp-port 587 \
  --smtp-user '<smtp-username>' --smtp-from 'Tunnel <tunnel@example.com>' \
  --smtp-test-to you@example.com

# Test or disable later
sudo tunnel-server mail test you@example.com
sudo tunnel-server mail off
  • Transport encryption: Port 465 uses implicit TLS from byte zero; all other ports (default 587) require STARTTLS. Plain unencrypted SMTP is refused except on loopback (localhost / 127.0.0.1 / ::1).
  • Diagnostics: mail test names the exact failing step (DNS lookup, connect, TLS, greeting, sign-in, sender, recipient, or message).
  • Behavior with mail enabled:
    • Invites: Can be emailed directly; registering through a mailed invite confirms that email address.
    • Forgot password: Sends a single-use 30-minute link to the account’s confirmed email (constant-shape responses to prevent enumeration; limited per IP, 1 per 2 minutes per account, and 60/min server-wide). If 2FA is enabled, the reset form requires a TOTP or recovery code and keeps 2FA enabled—email is never a second factor.
    • Security notices: Automatically emailed on password change/reset, 2FA toggle, machine approval/addition, role change, or email change.
    • Delivery runs in the background with a 60-second timeout and no retries; links always point strictly to ui_host and never contain TOTP secrets, recovery codes, or machine tokens.

Health Checks and Prometheus Metrics

/healthz Endpoint

GET https://<host>/healthz returns JSON with status, database, and certificate_days_left:

  • Returns HTTP 200 when SQLite responds and the TLS certificate has at least 7 full days remaining.
  • Returns HTTP 503 when the database is unreachable or the certificate is missing or within 7 days of expiry.

By default /healthz is open and omits the server version. Lock it down for uptime monitors with a dedicated health token:

sudo tunnel-server health-token set     # prints the bearer token once
sudo tunnel-server health-token clear   # reopens /healthz

Once set, callers must present Authorization: Bearer <health-token> or ?token=<health-token> (the admin token is rejected); authenticated responses also include version, and unauthenticated callers receive 404.

Prometheus Metrics

tunnel-server serves Prometheus text format on metrics_listen (127.0.0.1:9464 by default):

Metric Type Description
tunnel_tunnels_connected gauge Currently connected tunnel clients.
tunnel_streams_live gauge Active proxied HTTP requests and WebSockets.
tunnel_requests_total counter Total visitor requests reaching the edge.
tunnel_gate_denials_total counter Visitor requests denied by the access gate.
tunnel_lookups_shed_total counter Visitor lookups shed with 503 due to saturated lookup slots.
tunnel_access_cuts_total counter In-flight requests/WebSockets cut mid-stream due to revoked/expired access.
tunnel_access_redemptions_total counter Successful access-link redemptions and password logins.
tunnel_access_failures_total counter Rejected access-link or password attempts.
tunnel_turn_allocations gauge Active built-in TURN relay allocations.
tunnel_cert_not_after_seconds gauge Unix timestamp of current TLS certificate expiry.
tunnel_bytes_total{tunnel,direction} counter Relayed payload bytes per tunnel (direction="in" or "out").

Backup and Restore

# Write a consistent online SQLite backup (SQLite VACUUM INTO, created mode 0600)
sudo tunnel-server backup /var/backups/tunnel-$(date +%F).db

# Restore a backup (verifies integrity, schema, and seal key; stops service; swaps DB; restarts)
sudo tunnel-server restore /var/backups/tunnel-2026-11-27.db

Always back up three items together in secure off-site storage:

  1. The SQLite backup produced by tunnel-server backup <path>.
  2. config.toml (which holds ui_secret, DNS tokens, TURN secret, and SMTP settings).
  3. The certs/ directory inside data_dir (ACME account key and certificates).

Important: restore refuses any backup whose schema does not match the running binary, or whose sealed passwords/TOTP secrets were encrypted under an unknown ui_secret (unless that key is configured as ui_secret_previous). Before replacing the live database, restore saves the prior database as tunnel.db.before-restore-<timestamp>—delete these copies once verified, especially if they predate password/recovery-code sealing.

Secret Rotation and Certificate Maintenance

ui_secret seals all account and tunnel Argon2id password hashes, TOTP secrets, and SHA-256 recovery codes using AES-256-GCM under HKDF-SHA256 keys (and derives web UI CSRF tokens). Losing ui_secret permanently requires resetting every account/tunnel password and re-enrolling 2FA.

Rotating ui_secret

# Inspect seal health without changing anything (reports legacy or previous-key counts)
sudo tunnel-server secret check

# Rotate ui_secret: moves old secret to ui_secret_previous, generates new ui_secret, restarts service
sudo tunnel-server secret rotate

On restart after secret rotate, tunnel-server re-seals every password hash, recovery code, and TOTP secret inside a single atomic transaction before listening (rolling back and refusing startup on any corrupt seal or wrong key). Active web UI sessions remain signed in—just reload open tabs to receive refreshed CSRF tokens.

  • A second rotation is refused until the service has restarted and finished re-sealing under the new key (sealed-key-id tracks the active key in data_dir, and config.toml.lock serializes mutating admin commands).
  • Keep ui_secret_previous (and matching older config.toml backups) for as long as you retain database backups taken prior to rotation.

Rotating the Admin Token and Renewing Certificates

# Replace the admin bearer token (prints the new tnadm_ token once; invalidates the old one immediately)
sudo tunnel-server token rotate

# Manually check or force-renew the Let's Encrypt certificate (automatic renewal runs in the background)
sudo tunnel-server cert renew
sudo tunnel-server cert renew --force