On this page
  1. Components
  2. A request through a tunnel
  3. A webhook through an inbox
  4. Code layout
  5. Data
  6. The client
  7. Operations

Architecture

How a request or a webhook travels from the internet to localhost, and how the code is organised. Companions: Protocol (wire format), HTTP API (HTTP APIs), Security, ADR 0003 (single node), ADR 0004 (layering).

Components

                 ┌──────────────────────────── Tunnex server (one process) ─────────────────────────────┐
 <sub>.domain ──▶│ Edge                                     │ Control plane (FastAPI)                   │◀── connect.domain
 (reverse proxy: │  tunnels: policies · rate limits ·       │  accounts · tokens · teams · invites ·    │    console, CLI,
  TLS, no        │  interstitial · SSO · streaming proxy    │  inboxes · events · replay · audit ·      │    /v2/connect
  buffering)     │  inboxes: verify · store · ack · publish │  device login · SSO · web console         │
                 │                    │                     │ Tunnel handshake ─┐                       │
                 │  Registry of live tunnels and listeners ◀┴───────────────────┘   Dispatcher ─────────│
                 │  (in memory)                                 per-listener queue, cursors, retries   │
                 └─────────────────────────────────────┬───────────────────────────────────────────────┘
 public TCP ports ────────────────────────────────────▶│ PostgreSQL (SQLAlchemy async, Alembic)
                                                        ▼
                       one WebSocket per client, protocol v2 (binary frames, streams, flow control)
                                                        │
                 ┌────────────────────────── tunnex client (developer machine, container, CI) ───────────┐
                 │ Session: HTTP/WS/TCP forwarders → local app · inbox deliveries → --forward             │
                 │ Recorder → local store (~/.tunnex) ◀── Inspector :4040 · MCP server · CLI              │
                 └────────────────────────────────────────────────────────────────────────────────────────┘

The server dispatches by Host: <sub>.<domain> goes to the edge (a live tunnel, or an inbox), everything else (connect.<domain>, health checks) to the control plane. Server routes therefore never shadow paths of user applications; the edge reserves only /_tunnex/* on tunnel hosts.

A request through a tunnel

  1. GET https://myapp.example.com/api/orders reaches the reverse proxy (TLS, no buffering), then the server. The client IP comes from X-Forwarded-For only if the peer is a trusted proxy.
  2. The edge finds the live tunnel for myapp in the registry (an offline page otherwise) and applies, in order: IP allowlist → path allowlist → rate limit (plan, optionally lowered by the policy) → stream limit → the anonymous-tunnel interstitial (browser navigations only) → credentials: API key, basic auth or an SSO cookie, otherwise an SSO redirect, a WWW-Authenticate challenge or 401.
  3. Forwarded headers are rebuilt: hop-by-hop headers, incoming X-Tunnex-*, consumed credentials and Tunnex cookies are removed; X-Forwarded-*, X-Real-IP and identity headers (X-Tunnex-Email, X-Tunnex-Key-Id) are added.
  4. The edge opens a stream on the tunnel's multiplexer and pumps the body as DATA frames; if the caller goes away, it resets the stream.
  5. The client buffers up to 8 MiB of body (so it can be replayed from the inspector) and streams the rest, then forwards to the local app through a pooled httpx client (no redirects followed, Host rewritten for dev servers by default). The response streams back unchanged (content encoding preserved).
  6. Recording: the server keeps metadata only (a batched request log and daily usage); the client records the full exchange (first 1 MiB of each body) in its local SQLite store for the inspector. A request still running after 1 s appears as pending.

A webhook through an inbox

  1. POST https://acme-stripe.example.com/webhooks reaches the edge, which finds the inbox (cached configuration with the decrypted secret).
  2. IP allowlist → per-inbox rate limit → body size limit → signature check → the acknowledgement decision (401 for an invalid signature when the inbox rejects them; Slack's URL challenge).
  3. The event is stored first (PostgreSQL), then acknowledged to the provider with x-tunnex-event-id, and published to the dispatcher.
  4. The dispatcher queues it for every online listener with a matching subscription. Each listener connection has one queue and one worker, so deliveries to it are sequential and ordered. A delivery is an http stream on the listener's connection; the subscription's cursor moves only after the local app answered. A local connection failure is retried with backoff while the listener stays connected.
  5. On connect, and when a queue overflows, the dispatcher loads events after the cursor from the database (catch-up). Replays go through the same path without moving cursors. Timestamped signatures are re-signed for catch-up and replay deliveries.

Code layout

Both packages follow the same layering (ADR 0004); dependencies point inwards only.

Layer Client (tunnex/) Server (tunnex_server/)
Shared kernel protocol/ (frames, multiplexer, version negotiation) · domain/ (names, filters, policy builder, body capture) — imported by the server too
Domain (pure rules, no I/O, mypy --strict) domain/: errors, names, claims, policy, teams, tokens, accounts, audit, redirects, webhooks/ (signatures, inbox rules)
Application services connection/ (session, forwarders, recorder), runtime.py, control.py (API client) services/: accounts, tokens, device, domains, tunnels, teams, invites, inboxes, events, subscriptions, dispatcher, handshake, sso, usage, audit
Adapters cli/, inspector/ (local API + UI), store/ (SQLite), mcp_server.py, configfile.py, profile.py api/ (FastAPI routers), edge/ (raw ASGI edge), transport/ (WebSocket endpoint, registry, TCP), db/ (models, migrations)
Composition root cli/run.py composition.py (build_services, build_app), main.py

Rules the code keeps:

  • Domain modules do not import SQLAlchemy, FastAPI or asyncio; they take values and return values or raise domain errors (domain/errors.py), which the adapters map to HTTP statuses or protocol error codes.
  • Services receive their collaborators in the constructor (no globals); composition.py is the only place that builds them. Tests build the same graph with other settings.
  • SQLAlchemy models are the persistence model and are used directly by services — a deliberate trade-off for a small codebase: no second set of entities to keep in sync (ADR 0004).
  • Modules stay under ~350 lines; ruff (extended rule set) and mypy run in CI, strict on the shared kernel and the server domain.

Data

Table What
users Accounts: scrypt password hash (computed in a thread pool), linked GitHub id, session_epoch to revoke cookies
api_tokens SHA-256 of the token, prefix, scopes, expiry, last use
device_codes tunnex login device flow
domains Reserved (account quota) and ephemeral (24 h claim) subdomains; inboxes own theirs
tunnel_sessions, request_logs, usage_daily Connection history, request metadata (7-day retention), daily usage
teams, team_members, team_invites Teams, roles, one-time invite codes (stored hashed)
inboxes Provider, AES-GCM-encrypted secret, acknowledgement, retention, IP allowlist
webhook_events Stored requests (headers, body, verification result) until retention
subscriptions, deliveries Listener cursors and filters; every delivery attempt with status and timing
audit_events Who did what to accounts, tokens, teams, inboxes

Migrations are expand/contract (see Self-hosting).

The client

  • Runtime owns the local store, the inspector server and one session per tunnel or listener. It publishes their state to the store every few seconds, so any inspector or MCP server on the machine sees every tunnel.
  • Inspector (127.0.0.1:4040): a Host allowlist against DNS rebinding, no CORS, writes need a custom header and a same-origin Origin; replay is limited to the tunnel's own local target (no SSRF).
  • MCP server (tunnex mcp serve, stdio): tools wrap the runtime, the store and the control API.
  • Headless: tunnex start reads tunnex.yaml (see Configuration); the client image runs it by default.

Operations

Health (/healthz, /readyz), graceful drain on SIGTERM, JSON logs with correlation fields, Prometheus metrics and backups are described in Self-hosting.

Edit this page on GitLab