relay

module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 23, 2026 License: AGPL-3.0

README

Relay

A 41tunnels project.

The server that lets your browser reach your own Amallo, anywhere.

Relay is the Go server that lets a browser talk to a user's own Amallo desktop agent over the open internet — without a VPN, and without the relay ever seeing plaintext.

Why this exists

amallo runs on a machine that's usually behind NAT/CGNAT with no inbound ports open, and a browser can't dial into it directly. Something has to sit in the middle.

The obvious answer, a VPN mesh like Tailscale/Headscale, doesn't fit: seat pricing charges per authenticated device on an app with many end users, and the actual problem is narrower than "join these two devices to one network" — it's just NAT traversal for one streamed connection. Relay is that narrower thing: a plain WebSocket relay, the same shape as the ngrok/Cloudflare Tunnel pattern, with none of the VPN machinery.

How it works

  1. amallo opens an outbound WebSocket to Relay on startup and keeps it parked — no inbound ports required, works behind CGNAT.
  2. The user pairs their browser to their agent once, by scanning a QR code amallo displays. That QR code carries a pairing ID and a shared secret; both sides derive an encryption key from it locally.
  3. web opens its own WebSocket to Relay, authenticated for that same pairing ID.
  4. Relay splices the two sockets together and forwards frames blindly. Past the handshake, everything it forwards is AES-GCM ciphertext — the relay is a byte pipe, not a party to the conversation.

If amallo's machine is asleep or offline, there's nothing to splice to; Relay reports that honestly (agent_offline) rather than hanging.

Relay also exposes an optional OpenAI-compatible HTTP endpoint (see spec/PROTOCOL.md §11) so a third-party client can call a paired agent's model directly, keyed by a per-agent token rather than the pairing secret.

The wire format — outer frame, control channel, pairing handshake, the OpenAI-compatible HTTP lane — is specified in full, with test vectors, in spec/PROTOCOL.md. That document is normative: web and amallo each implement it independently against the same testdata/vectors/, and where an implementation disagrees with the spec, the spec wins.

Repository layout

cmd/
  relay/       the server binary (config → wiring → listen → graceful shutdown)
  fakeagent/   a scriptable stand-in for amallo, for load/manual testing
  fakeclient/  a scriptable stand-in for web, for load/manual testing
  genvectors/  regenerates testdata/vectors/ from the reference implementation

internal/
  config/      env-var configuration, defaults, validation
  auth/        pairing/token authorization
  hub/         pair_id -> Pair bookkeeping; the agent/client socket splice
  wire/        outer frame + control/inner frame encoding
  proto/       handshake and session framing above the wire layer
  limits/      per-IP connection limiting, per-pair byte-rate limiting
  metrics/     Prometheus collectors
  logging/     structured logging setup
  server/      HTTP handlers: /v1/agent, /v1/client, /healthz, /stats,
               and the OpenAI-compatible HTTP endpoint
  testclient/  shared test-only WebSocket client used by cmd/fake*

spec/          spec/PROTOCOL.md, the normative wire protocol
testdata/      cross-implementation test vectors referenced by the spec

Running it

go run ./cmd/relay

Defaults are usable out of the box (see internal/config/config.go); override with RELAY_* environment variables for anything internet-facing. A few of the more consequential ones:

Variable Default Meaning
RELAY_ADDR :8080 Public listener
RELAY_METRICS_ADDR :9091 Prometheus listener — bind to loopback only
RELAY_ALLOWED_ORIGINS * WebSocket origin allowlist — wide open by default, since the pairing secret is what actually gates a connection, not the browser origin
RELAY_MAX_PAIRS 10000 Capacity cap on new pair creation
RELAY_TRUST_PROXY true Trust X-Forwarded-For from the reverse proxy in front
RELAY_HTTP_ENABLED true Serve the OpenAI-compatible HTTP endpoint

config.Load() fails loudly on a malformed value rather than silently falling back — a bad deploy config is caught at startup, not at 3am under load.

Tests
go vet ./...
go test -race ./...

Endpoints

Path Purpose
GET /v1/agent, GET /v1/client WebSocket upgrade endpoints for the two roles
GET /healthz Liveness probe, 200 ok
GET /stats Public dashboard of aggregate load — see below
GET /{token}/v1/... or Authorization: Bearer The OpenAI-compatible HTTP lane (§11), when RELAY_HTTP_ENABLED
Prometheus metrics Served on the separate RELAY_METRICS_ADDR listener — never public
/stats

A public, unauthenticated page showing how busy the relay currently is: active pairs, agents connected, clients connected, and process uptime. It's deliberately aggregate-only — no pairing IDs, tokens, or IP addresses are ever computed anywhere the handler can reach, so there's nothing confidential to expose by leaving it open. Add ?format=json (or send Accept: application/json) for a machine-readable version of the same numbers.

Deployment

Released versions are published to the GitHub Container Registry:

docker run --rm -p 8080:8080 ghcr.io/41tunnels/relay:latest

Images are tagged with the release version (:1.2.3) and :latest, for linux/amd64 and linux/arm64.

Relay is meant to sit behind a reverse proxy that terminates TLS and proxies WebSocket upgrades transparently — see Caddyfile.example, which also notes the two things a different proxy (nginx, Traefik) needs to get right: no idle-timeout on the public listener (agent sockets stay parked for hours), and no response buffering (SSE streaming depends on it).

docker-compose.yml shows the production shape: read-only root filesystem, all capabilities dropped, raised nofile for the socket count, and the Prometheus port bound to loopback only.

Non-negotiables baked into the design, regardless of deploy target: 30s pings with a bounded pong timeout, exponential backoff with jitter expected on both clients, bounded server-side buffering per connection (no backlog that outlives a slow consumer), and per-pair byte-rate limits so one noisy pairing can't starve another.

Releases

Relay uses semantic-release. Commit messages follow Conventional Commits (feat: → minor, fix: → patch, !/BREAKING CHANGE → major), and pushing to release/latest derives the next version, tags it, publishes GitHub release notes and pushes the image to GHCR. Version numbers are never bumped by hand.

A push that carries no release-worthy commits (docs, chores) tags nothing and publishes no image — the build step is skipped rather than re-pushing :latest over the same code. The version is stamped into the binary at build time and logged at startup, so a running container can be traced back to the tag it came from.

License

AGPL-3.0 — see LICENSE.

Directories

Path Synopsis
cmd
fakeagent command
Command fakeagent stands in for amallo when testing the relay (or, later, a real amallo) from outside the Go test binary — see the build plan's Steps 3-5.
Command fakeagent stands in for amallo when testing the relay (or, later, a real amallo) from outside the Go test binary — see the build plan's Steps 3-5.
fakeclient command
Command fakeclient stands in for web when testing the relay (or, later, a real amallo) from outside the Go test binary — see the build plan's Steps 3-5.
Command fakeclient stands in for web when testing the relay (or, later, a real amallo) from outside the Go test binary — see the build plan's Steps 3-5.
genvectors command
Command genvectors generates the shared cross-language test vectors consumed by the relay's own tests and vendored into amallo and web (see spec/PROTOCOL.md and the build plan's Step 1).
Command genvectors generates the shared cross-language test vectors consumed by the relay's own tests and vendored into amallo and web (see spec/PROTOCOL.md and the build plan's Step 1).
relay command
Command relay is the OpenCharUI relay server (spec/PROTOCOL.md).
Command relay is the OpenCharUI relay server (spec/PROTOCOL.md).
internal
auth
Package auth defines the relay's pluggable authorization seam.
Package auth defines the relay's pluggable authorization seam.
config
Package config loads and validates the relay's runtime configuration from environment variables (see the build plan's Step 2 and the deploy compose files).
Package config loads and validates the relay's runtime configuration from environment variables (see the build plan's Step 2 and the deploy compose files).
hub
Package hub implements pair registration and the two-connection splice: which agent socket and which client socket belong together, and the locking discipline that keeps that bookkeeping safe under concurrent connects/disconnects.
Package hub implements pair registration and the two-connection splice: which agent socket and which client socket belong together, and the locking discipline that keeps that bookkeeping safe under concurrent connects/disconnects.
limits
Package limits implements the relay's two rate controls: a per-pair byte budget (protects one pair's bandwidth from starving others sharing the host) and a per-IP connection-attempt budget (bounds the cost of unauthenticated upgrade attempts before a pair even exists).
Package limits implements the relay's two rate controls: a per-pair byte budget (protects one pair's bandwidth from starving others sharing the host) and a per-IP connection-attempt budget (bounds the cost of unauthenticated upgrade attempts before a pair even exists).
logging
Package logging sets up structured slog logging and provides PairTag, the one function every log call site touching a pair_id MUST go through.
Package logging sets up structured slog logging and provides PairTag, the one function every log call site touching a pair_id MUST go through.
metrics
Package metrics defines the relay's Prometheus collectors.
Package metrics defines the relay's Prometheus collectors.
proto
Package proto is a reference implementation of the OpenCharUI E2E handshake and AEAD session (spec/PROTOCOL.md §4-§6).
Package proto is a reference implementation of the OpenCharUI E2E handshake and AEAD session (spec/PROTOCOL.md §4-§6).
server
Package server wires the hub, auth, limits and metrics packages into an http.Handler serving the two upgrade endpoints (/v1/agent, /v1/client) and /healthz.
Package server wires the hub, auth, limits and metrics packages into an http.Handler serving the two upgrade endpoints (/v1/agent, /v1/client) and /healthz.
testclient
Package testclient is the shared connect/handshake/framing logic behind cmd/fakeagent and cmd/fakeclient — standalone processes that speak the real relay protocol (spec/PROTOCOL.md) for testing the relay, and later amallo and web, from outside the Go test binary.
Package testclient is the shared connect/handshake/framing logic behind cmd/fakeagent and cmd/fakeclient — standalone processes that speak the real relay protocol (spec/PROTOCOL.md) for testing the relay, and later amallo and web, from outside the Go test binary.
wire
Package wire implements the OpenCharUI relay wire format: the outer frame (relay-visible) and the inner frame (carried inside decrypted channel-0x01 payloads).
Package wire implements the OpenCharUI relay wire format: the outer frame (relay-visible) and the inner frame (carried inside decrypted channel-0x01 payloads).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL