etunnel

package
v1.6.13 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 21 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

etunnel SDK for Go (reference client)

Go Reference Go

The canonical client, and the only one that is not buffer-based:

  • Streaming bodies - responses are relayed chunk by chunk, flushes are preserved, Transfer-Encoding: chunked and server-sent events work.
  • WebSocket pass-through - a 101 Switching Protocols response hijacks both sides into a raw byte pipe, so a realtime service behind a tunnel behaves exactly as it does locally.
  • No dependencies outside the standard library (github.com/coder/websocket).

The other 19 languages in ../sdks/ are buffer-based ports of the same wire protocol; they cover webhooks, dashboards and APIs.

Install

go get github.com/topcheer/etunnel/sdk@latest

Embed in your app

package main

import (
	"context"
	"log"

	"github.com/topcheer/etunnel/sdk"
)

func main() {
	tunnel, err := etunnel.Connect(context.Background(), etunnel.Options{
		Server:    "wss://t.etun.uk/tunnel",
		LocalAddr: "127.0.0.1:3000",
	})
	if err != nil {
		log.Fatal(err)
	}
	defer tunnel.Close("app exiting")

	log.Printf("public URL: %s", tunnel.URL())

	// Tunnel.Done() closes when the server drops the tunnel (TTL expiry, kick).
	// Start your own server here, or block:
	select {}
}
flowchart LR
  V["visitor"] -->|HTTPS| E["etunneld"]
  E -->|"wss /tunnel"| S["sdk.Connect"]
  S -->|"HTTP/1.1 streaming"| L["localhost:3000"]
  E -.->|"101 upgrade: raw pipe"| L

CLI

go install github.com/topcheer/etunnel/cmd/etunnel@latest
etunnel -server wss://t.etun.uk/tunnel 3000

etunnel prints TUNNEL_URL: https://<subdomain>.<domain> and keeps the tunnel open until Ctrl-C; -token and -subdomain select a paid plan.

API

Symbol Returns / effect
Connect(ctx, Options) (*Tunnel, error) - returns after the server's welcome
ConnectReconnecting(ctx, Options) (*ReconnectingTunnel, error) - first dial fails fast, then supervises forever
ReconnectingTunnel.URL() / Subdomain() / Attempts() last-known facts across reconnects
ReconnectingTunnel.Tunnel() current *Tunnel (nil while a reconnect is in flight)
ReconnectingTunnel.Done() closed when the supervisor stops (user close, parent ctx, permanent error)
ReconnectingTunnel.Close(reason) stops the supervisor; no reconnect follows
Tunnel.URL() string - public HTTPS URL
Tunnel.Hostname() / Subdomain() / Plan() connection facts
Tunnel.ExpiresAt() time.Time - plan TTL deadline
Tunnel.Done() <-chan struct{} closed when the tunnel ends
Tunnel.CloseReason() why the server closed it (ttl_expired, kicked, ...)
Tunnel.Close(reason) graceful shutdown; the subdomain is freed immediately
APIError policy rejection during handshake (Code + Message)
Login(ctx, server, openBrowser) (*Credentials, error) - browser authorization: returns the account's APIToken, Subdomains, Plan for persistence (see below)
Login (browser authorization)

Login runs the CLI loopback flow so a desktop app can get an API token without copy-pasting keys: it binds a random 127.0.0.1 port, asks the server for an authorization URL, opens the user's browser there (the openBrowser callback; nil uses open/xdg-open and prints the URL when headless), waits for the browser to land back on the loopback port with a one-time code (5-minute TTL, single use), and exchanges it:

creds, err := etunnel.Login(ctx, "https://t.etun.uk", nil)
if err != nil { ... }
// creds.APIToken, creds.Subdomains, creds.Plan - persist these and pass
// Options{Token: creds.APIToken, ...} on every future Connect.

Free accounts get the token with an empty Subdomains list. The whole flow times out after 10 minutes; the server's approval page requires the portal session, so no new credential surface is introduced.

Options
Field Meaning
Server tunnel endpoint; a bare host gets wss:// and /tunnel
LocalAddr local service address, "127.0.0.1:3000" (":3000" also works)
Token paid-plan API key
Subdomain custom subdomain, requires a paid plan
Client free-form client identifier sent in hello
OnLog func(format string, args ...any) lifecycle log sink
OnReconnect called after each successful reconnect (func(url string, attempt int))
ReconnectMinBackoff / ReconnectMaxBackoff backoff bounds for ConnectReconnecting (defaults 500ms / 30s, doubling, +-10% jitter, reset after a successful reconnect)
Reconnecting

ConnectReconnecting dials once (so bad credentials fail fast with the real error) and then rebuilds the tunnel whenever it drops, replaying the server's signed resumeToken so the same subdomain is reclaimed instead of re-randomised (token lifetime is 30 minutes server-side; after that the server assigns a fresh subdomain). Retrying stops permanently on errors that cannot fix themselves (unauthorized, subdomain_plan, subdomain_invalid, bad_message).

DefaultServer is the connect target when Server is empty. Override it at build time for an internal deployment:

go build -ldflags "-X github.com/topcheer/etunnel/sdk.DefaultServer=wss://tunnel.internal/tunnel" ./cmd/etunnel

Behaviour details

  • Header hygiene - hop-by-hop headers (Connection, Keep-Alive, Transfer-Encoding, Upgrade, Proxy-*, TE, Trailer) are stripped in both directions. etunneld is the edge: it sets X-Forwarded-For and X-Forwarded-Proto itself and discards any client-supplied value.
  • Streams - one WebSocket carries many concurrent streams, each with a 32-bit id. The server sends req metadata, then binary data frames, then fin; a client can answer with rst to abort.
  • Liveness - application-level ping/pong plus WebSocket pings. A stalled stream is reset individually instead of freezing the tunnel.
  • Grace - Close(reason) sends bye, waits for the writer to drain and closes the socket. Dropping the process has the same effect server-side.

Environment variables

Variable Meaning Default
ETUNNEL_SERVER tunnel server WebSocket URL wss://t.etun.uk/tunnel
ETUNNEL_LOCAL local port or host:port (CLI) 3000
ETUNNEL_TOKEN paid-plan API key (CLI) -
ETUNNEL_SUBDOMAIN requested subdomain (CLI, paid plans) random

The Connect API itself takes everything through Options; the environment variables are read by cmd/etunnel.

Tests

Race-detector-enabled end-to-end tests live at the repository root - they start an in-process etunneld and drive it with this SDK, the CLI and raw HTTP/WebSocket clients:

go test -race ./...

See also

Documentation

Overview

Package etunnel is the Go SDK for etunnel tunnels: expose a local service on the public internet with one call.

t, err := etunnel.Connect(ctx, etunnel.Options{Server: "wss://t.example.com/tunnel", LocalAddr: ":8080"})
fmt.Println(t.URL()) // https://quick-fox-42.t.example.com

Login: the CLI loopback authorization flow (see server/auth_cli.go).

The SDK listens on a random 127.0.0.1 port, asks the server for an authorization URL, opens the user's browser there, waits for the browser to land back on the loopback port with a one-time code, and exchanges it for the account's API token and custom-domain list. The caller persists the returned Credentials and passes APIToken as Options.Token on future Connect calls.

Index

Constants

View Source
const (
	DefaultReconnectMinBackoff = 500 * time.Millisecond
	DefaultReconnectMaxBackoff = 30 * time.Second
)

Reconnect defaults.

View Source
const LoginTimeout = 10 * time.Minute

LoginTimeout bounds the whole flow: browser open, user login (if needed) and approval. The server's own code lives 5 minutes; 10 minutes here covers a login detour.

Variables

View Source
var DefaultServer = "wss://t.etun.uk/tunnel"

DefaultServer is the connect target when Options.Server is empty; overridable at link time: -ldflags "-X etunnel/sdk.DefaultServer=wss://t.example.com/tunnel"

View Source
var ErrUnsupportedProto = errors.New("etunnel: server protocol too new")

ErrUnsupportedProto is returned when the server speaks a strictly newer wire protocol than this SDK. Retrying cannot fix it; the reconnecting supervisor treats it as permanent.

Functions

func NormalizeServerURL

func NormalizeServerURL(s string) string

NormalizeServerURL canonicalizes a server address into a ws(s) URL.

Types

type APIError

type APIError struct {
	Code    string
	Message string
}

APIError is a policy error returned by the server during handshake.

func (*APIError) Error

func (e *APIError) Error() string

type Credentials added in v1.6.6

type Credentials struct {
	// APIToken authenticates tunnel creation (Options.Token).
	APIToken string `json:"api_token"`
	// Subdomains are the account's custom domains (empty for free tier).
	Subdomains []string `json:"subdomains"`
	// Plan is the account tier ("free", ...).
	Plan string `json:"plan"`
	// ExpiresAt is 0: API tokens do not lapse on their own.
	ExpiresAt int64 `json:"expires_at"`
}

Credentials is what Login returns and what applications persist.

func Login added in v1.6.6

func Login(ctx context.Context, server string, openBrowser func(string) error) (*Credentials, error)

Login runs the loopback authorization flow against server (e.g. "https://t.etun.uk"). openBrowser may be nil; headless environments get the URL printed to stderr instead.

type Options

type Options struct {
	// Server is the tunnel server endpoint, e.g. "wss://t.example.com/tunnel".
	// A bare host gets "wss://" and "/tunnel" defaults.
	Server string
	// LocalAddr is the local service address to expose ("127.0.0.1:8080").
	LocalAddr string
	// Subdomain requests a static subdomain (a free key may hold one;
	// paid keys hold more).
	Subdomain string
	// Token is an API key (free keys unlock one static subdomain).
	Token string
	// Client is a free-form client identification string.
	Client string
	// Policy declares per-tunnel edge protection enforced by the server
	// before any visitor request reaches the local service. Nil = legacy.
	Policy *TunnelPolicy
	// OnLog, when set, receives lifecycle log lines.
	OnLog func(format string, args ...any)
	// ReconnectMinBackoff / ReconnectMaxBackoff bound the exponential backoff
	// used by ConnectReconnecting (defaults 500ms / 30s).
	ReconnectMinBackoff time.Duration
	ReconnectMaxBackoff time.Duration
	// OnReconnect, when set, fires after each successful reconnect with the
	// attempt number and the new public URL.
	OnReconnect func(attempt int, url string)
	// contains filtered or unexported fields
}

Options configures a tunnel.

type ReconnectingTunnel added in v1.3.0

type ReconnectingTunnel struct {
	// contains filtered or unexported fields
}

ReconnectingTunnel keeps a tunnel alive across disconnects. It is safe for concurrent use; every accessor proxies to the current underlying tunnel.

func ConnectReconnecting added in v1.3.0

func ConnectReconnecting(ctx context.Context, opts Options) (*ReconnectingTunnel, error)

ConnectReconnecting dials once (returning the first error, so bad credentials fail fast rather than looping forever) and then supervises the connection in the background.

func (*ReconnectingTunnel) Attempts added in v1.3.0

func (r *ReconnectingTunnel) Attempts() int

Attempts reports how many successful reconnects have happened.

func (*ReconnectingTunnel) Close added in v1.3.0

func (r *ReconnectingTunnel) Close(reason string)

Close stops the supervisor and the current tunnel. No reconnect follows.

func (*ReconnectingTunnel) Done added in v1.3.0

func (r *ReconnectingTunnel) Done() <-chan struct{}

Done is closed when the supervisor stops: the user called Close, the parent context ended, or reconnecting failed permanently.

func (*ReconnectingTunnel) String added in v1.3.0

func (r *ReconnectingTunnel) String() string

String renders the tunnel for logs.

func (*ReconnectingTunnel) Subdomain added in v1.3.0

func (r *ReconnectingTunnel) Subdomain() string

Subdomain returns the current subdomain label.

func (*ReconnectingTunnel) Tunnel added in v1.3.0

func (r *ReconnectingTunnel) Tunnel() *Tunnel

Tunnel returns the current underlying tunnel, or nil while a reconnect is in flight. Accessors like ResumeToken/CloseReason live on it.

func (*ReconnectingTunnel) URL added in v1.3.0

func (r *ReconnectingTunnel) URL() string

URL returns the live public URL (last known while reconnecting).

type Tunnel

type Tunnel struct {
	// contains filtered or unexported fields
}

Tunnel is one live reverse tunnel.

func Connect

func Connect(ctx context.Context, opts Options) (*Tunnel, error)

Connect establishes a reverse tunnel and returns it once the server has assigned a public hostname.

func (*Tunnel) Close

func (t *Tunnel) Close(reason string)

Close shuts the tunnel down.

func (*Tunnel) CloseReason

func (t *Tunnel) CloseReason() string

CloseReason returns why the tunnel ended ("" while running).

func (*Tunnel) Done

func (t *Tunnel) Done() <-chan struct{}

Done is closed when the tunnel ends (server closed it, TTL expired, connection lost or Close was called).

func (*Tunnel) ExpiresAt

func (t *Tunnel) ExpiresAt() time.Time

ExpiresAt returns the tunnel expiry reported by the server (zero = none).

func (*Tunnel) Hostname

func (t *Tunnel) Hostname() string

Hostname returns the public hostname.

func (*Tunnel) Plan

func (t *Tunnel) Plan() string

Plan returns the plan name reported by the server.

func (*Tunnel) ResumeToken added in v1.3.0

func (t *Tunnel) ResumeToken() string

ResumeToken returns the server-signed token that lets a later connection reclaim this tunnel's subdomain (empty when the server does not issue one).

func (*Tunnel) Subdomain

func (t *Tunnel) Subdomain() string

Subdomain returns the assigned subdomain label.

func (*Tunnel) URL

func (t *Tunnel) URL() string

URL returns the public URL of the tunnel.

type TunnelPolicy added in v1.6.13

type TunnelPolicy struct {
	// BasicAuth protects the tunnel with HTTP Basic ("user:pass").
	BasicAuth string `json:"basicAuth,omitempty"`
	// AllowIPs restricts visitors to these CIDRs / plain IPs.
	AllowIPs []string `json:"allowIPs,omitempty"`
	// Webhooks verifies signatures of the listed providers at the edge;
	// verified requests carry X-Etunnel-Webhook to the local service.
	Webhooks []WebhookRule `json:"webhooks,omitempty"`
}

TunnelPolicy is the SDK-side declaration of per-tunnel edge protection. It serializes into hello.policy and is enforced by the server: visitor requests are checked at the edge BEFORE any stream reaches the local service. Every layer is optional; zero fields = no policy is sent.

// demo behind a password
etunnel.Connect(etunnel.Options{..., Policy: &etunnel.TunnelPolicy{BasicAuth: "u:p"}})
// Stripe webhooks verified at the edge
Policy: &etunnel.TunnelPolicy{Webhooks: []etunnel.WebhookRule{{Provider: "stripe", Secret: "whsec_..."}}}

type WebhookRule added in v1.6.13

type WebhookRule struct {
	Provider string `json:"provider"`
	Secret   string `json:"secret"`
}

WebhookRule pins one provider's verification secret. Providers: stripe (Stripe-Signature, 5-min tolerance), github (X-Hub-Signature-256), gitlab (X-Gitlab-Token).

Jump to

Keyboard shortcuts

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