Documentation
¶
Overview ¶
CLI loopback authorization flow (RFC 8252 style, the "gcloud auth login" pattern): the SDK listens on a random 127.0.0.1 port, the server hands out a short-lived authorization URL, the user approves in a browser (reusing the existing OAuth session cookie), the browser lands back on the loopback port with a one-time code, and the SDK exchanges it for its API key and custom-domain list.
Two tokens, both HMAC-signed with the session key (so they survive a restart when SESSION_SECRET is set) and both short-lived:
device_code start -> grant payload "dev|nonce|redirect_uri|exp" TTL 10m code grant -> exchange payload "code|email|nonce|exp" TTL 5m, one-time
The code carries the device nonce, and exchange requires both tokens to agree on it: a code minted for one CLI flow cannot be redeemed inside another, and a redeemed code cannot be replayed.
Package server implements the etunnel tunnel server: WebSocket control sessions from SDK clients, HTTP(S) reverse proxying by hostname, plan-based limits (TTL / custom subdomains / bandwidth), accounts and TLS.
Tunnel policy: per-tunnel edge protection declared in the hello message (feature-gap analysis #1 and #3). Three independent, composable layers evaluated on every visitor request BEFORE any stream is opened:
basicAuth - HTTP Basic (401 + WWW-Authenticate on mismatch)
allowIPs - source CIDR allowlist (403 outside)
webhooks - signature verification for known webhook providers
(Stripe / GitHub / GitLab). Requests carrying a known
provider's signature header are verified against the raw
body and rejected 401 on mismatch; requests WITHOUT any
known signature header fall through to the other layers
(verification is hardening, not a blanket close).
Backward compatibility: an absent policy behaves exactly as before - old clients that never send hello.policy are unaffected.
Passkey (WebAuthn) support: users who are logged in (via OAuth or an existing session) can register one or more passkeys - platform authenticators (Touch ID, Windows Hello) or roaming keys (YubiKey) - and then sign in from the login page without any provider. The session minted by a successful passkey login is the same "et_session" cookie OAuth uses, so every downstream surface (portal, CLI grant, billing) works unchanged.
Storage: passkeys live on the Account (JSON store: automatic; PG: the passkeys jsonb column). Credential data is the decoded protocol.Credential, trimmed to what validation needs plus a user-chosen device name.
Ceremony session state is per-instance in-memory (5-minute TTL). The production topology is a single node; a multi-node cluster would need the begin/finish pair pinned to one node (sticky routing) or a shared store.
WSS source-IP bans for tunnel establishment (owner directive 2026-11-14): the public wildcard DNS is direct (no Cloudflare in front), so any WSS connect arriving FROM a Cloudflare range is a client hosted inside CF Workers/WARP - observed as ~2-minute open/close churning loops that squat free-tier tunnel slots. The default ban list is Cloudflare's published ranges (https://www.cloudflare.com/ips); ETUNNEL_BAN_RANGES overrides it with a comma-separated CIDR list ("-" disables).
This gates TUNNEL ESTABLISHMENT only - visitor HTTP traffic to existing tunnels is untouched (a visitor who happens to egress via WARP is not the target here; that is allowIPs' domain).
Index ¶
- Constants
- Variables
- func DefaultTiers() map[string]*Tier
- func T(lang, key string) string
- type Account
- type AccountStore
- func (s *AccountStore) CancelSubscription(email string) bool
- func (s *AccountStore) Create(email, tier string) (*Account, error)
- func (s *AccountStore) Delete(key string) bool
- func (s *AccountStore) DowngradeToFree(email string) bool
- func (s *AccountStore) ExpiredPaid(now time.Time) []string
- func (s *AccountStore) FindByProvider(provider, subject string) (*Account, bool)
- func (s *AccountStore) List() []*Account
- func (s *AccountStore) Lookup(key string) (*Account, bool)
- func (s *AccountStore) LookupEmail(email string) (*Account, bool)
- func (s *AccountStore) Mutate(email string, fn func(*Account)) bool
- func (s *AccountStore) PruneInactive(olderThan time.Duration, now time.Time) int
- func (s *AccountStore) ResetKey(email string) (string, bool)
- func (s *AccountStore) Snapshot(key string) (Account, bool)
- func (s *AccountStore) TryClaimDomain(email, dom string, mayClaim func(*Account) bool) bool
- type BillingConfig
- type ClusterConfig
- type Config
- type Counter
- type Passkey
- type PeerMeta
- type Registry
- type Router
- type Server
- type Session
- func (s *Session) Close(reason string)
- func (s *Session) CloseReason() string
- func (s *Session) ExpiresAt() time.Time
- func (s *Session) Hostname() string
- func (s *Session) IsCustom() bool
- func (s *Session) OpenStream() *Stream
- func (s *Session) Plan() string
- func (s *Session) RemoteIP() string
- func (s *Session) Subdomain() string
- func (s *Session) URL() string
- type ShortDomain
- type Stream
- type TLSConfig
- type Tier
- type TierFile
- type TunnelPolicy
- type WebhookRule
Constants ¶
const ( // TLSModeHTTP serves plain HTTP (development / behind your own TLS LB). TLSModeHTTP = "http" // TLSModeStatic loads a certificate/key pair from files and hot-reloads them. TLSModeStatic = "static" // TLSModeOnDemand issues per-hostname certificates via ACME HTTP-01 on // first request (requires port 80 to be reachable). TLSModeOnDemand = "ondemand" // TLSModeDNS issues a wildcard certificate via ACME DNS-01 at startup and // renews it (requires DNS provider credentials). TLSModeDNS = "dns" )
TLS modes.
const ( // TTLNever keeps the key until it is explicitly decremented to zero. TTLNever = time.Duration(0) )
Variables ¶
var ErrEmailTaken = errors.New("etunnel: email already registered")
ErrEmailTaken indicates an account already exists for the email.
var ErrSubdomainTaken = errors.New("etunnel: subdomain already in use")
ErrSubdomainTaken is returned when a live tunnel already holds a subdomain.
var ErrUnknownTier = errors.New("etunnel: unknown tier")
ErrUnknownTier indicates registration with an undefined tier.
Functions ¶
func DefaultTiers ¶
DefaultTiers returns the built-in tier set.
free : anonymous, random subdomain, 4h TTL, 1 Mbps starter : 72h TTL, 1 custom subdomain, 10 Mbps pro : 30d TTL, 5 custom subdomains, 10 Mbps
Types ¶
type Account ¶
type Account struct {
APIKey string `json:"apiKey"`
Email string `json:"email"`
Tier string `json:"tier"`
Created time.Time `json:"created"`
// OAuth identity (optional; anonymous email-registered accounts have none).
Provider string `json:"provider,omitempty"` // google | gitlab | apple
Subject string `json:"subject,omitempty"` // provider-stable user id
Name string `json:"name,omitempty"` // display name
// Custom subdomains the account owns (paid tiers, count-limited by tier).
Domains []string `json:"domains,omitempty"`
// ExpiresAt is when the paid subscription lapses; zero means no expiry
// (free tier, or an account granted a tier manually). The reaper in
// Server.startTierReaper downgrades expired accounts to free.
ExpiresAt time.Time `json:"expiresAt,omitempty"`
// PaidShort is the purchased entitlement to register 1-3 character
// subdomains (one-time purchase per subscription period; Free accounts
// can hold one without a paid tier).
PaidShort *ShortDomain `json:"paidShort,omitempty"`
// LapsedAt records when a paid subscription expired (zero = never paid).
// It survives the downgrade to free so retention logic can keep the
// account: a lapsed customer must never be garbage-collected like an
// anonymous free account - their payment history and OAuth binding are
// worth keeping for support, refunds and re-subscription.
LapsedAt time.Time `json:"lapsedAt,omitempty"`
// Passkeys are the account's WebAuthn credentials (server/webauthn.go);
// empty means none registered.
Passkeys []Passkey `json:"passkeys,omitempty"`
}
Account is a registered (paid-plan) identity identified by API key.
type AccountStore ¶
type AccountStore struct {
// contains filtered or unexported fields
}
AccountStore persists accounts in a JSON file.
func NewAccountStore ¶
func NewAccountStore(path string) (*AccountStore, error)
NewAccountStore creates a store, loading persisted accounts when path is set. A corrupt (torn/hand-edited) file no longer bricks the daemon (#18): the file is preserved as accounts.json.corrupt-<ts>, the store starts empty, and the event is surfaced via RecoveryNote for the server to log loudly.
func (*AccountStore) CancelSubscription ¶ added in v1.2.0
func (s *AccountStore) CancelSubscription(email string) bool
CancelSubscription downgrades the account to the free tier.
func (*AccountStore) Create ¶
func (s *AccountStore) Create(email, tier string) (*Account, error)
Create registers a new account and returns it with a fresh API key.
func (*AccountStore) Delete ¶
func (s *AccountStore) Delete(key string) bool
Delete removes an account by API key.
func (*AccountStore) DowngradeToFree ¶ added in v1.3.0
func (s *AccountStore) DowngradeToFree(email string) bool
DowngradeToFree sets the tier to free and clears the expiry.
func (*AccountStore) ExpiredPaid ¶ added in v1.3.0
func (s *AccountStore) ExpiredPaid(now time.Time) []string
ExpiredPaid returns emails of paid accounts whose subscription lapsed.
func (*AccountStore) FindByProvider ¶ added in v1.2.0
func (s *AccountStore) FindByProvider(provider, subject string) (*Account, bool)
FindByProvider resolves an account by OAuth provider + subject.
func (*AccountStore) List ¶
func (s *AccountStore) List() []*Account
List returns all accounts sorted by creation time.
func (*AccountStore) Lookup ¶
func (s *AccountStore) Lookup(key string) (*Account, bool)
Lookup resolves an API key to an account.
func (*AccountStore) LookupEmail ¶
func (s *AccountStore) LookupEmail(email string) (*Account, bool)
LookupEmail resolves an account by email.
func (*AccountStore) Mutate ¶ added in v1.2.0
func (s *AccountStore) Mutate(email string, fn func(*Account)) bool
Mutate applies fn to the account under the store lock and persists.
func (*AccountStore) PruneInactive ¶ added in v1.4.0
PruneInactive removes anonymous free accounts older than the retention window. Accounts that ever paid (EverPaid) or own custom subdomains are always kept - their history and OAuth bindings outlive the retention policy. No-op when retention is zero.
func (*AccountStore) ResetKey ¶ added in v1.2.0
func (s *AccountStore) ResetKey(email string) (string, bool)
ResetKey issues a fresh API key for the account (identity/tier preserved).
func (*AccountStore) Snapshot ¶ added in v1.3.0
func (s *AccountStore) Snapshot(key string) (Account, bool)
Snapshot resolves an API key to a deep copy of the account.
Lookup returns the store's live *Account; callers that read its fields outside s.mu (session handshake, stats) would race Mutate/SaveLocked writers. Snapshot hands back a value the caller owns, so concurrent tier or domain changes cannot tear a read (issue #4).
func (*AccountStore) TryClaimDomain ¶ added in v1.6.4
func (s *AccountStore) TryClaimDomain(email, dom string, mayClaim func(*Account) bool) bool
TryClaimDomain atomically adds dom to the account ONLY if no other account holds it (#101: the old lock-free subdomainTakenBy precheck raced a concurrent Mutate, allowing the same name on two accounts). The uniqueness check, the tier/entitlement gate and the append all run under one critical section; mayClaim runs inside the lock.
type BillingConfig ¶ added in v1.2.0
type BillingConfig struct {
StripeSecretKey string // sk_live_... / sk_test_...
StripeWebhookSecret string // whsec_...
PayPalClientID string
PayPalSecret string
PayPalEnv string // "live" or "sandbox" (default live)
PayPalWebhookID string // for webhook verification
NowPaymentsAPIKey string // crypto checkout (nowpayments.io)
NowPaymentsIPNSecret string
PublicBaseURL string // e.g. https://t.example.com (defaults to https://<Domain>)
}
BillingConfig holds provider credentials; empty fields disable a provider.
type ClusterConfig ¶ added in v1.4.0
type ClusterConfig struct {
Store *pgAccountStore // nil = keep the JSON store
Counter Counter // never nil (mem or redis)
Router Router // nil = single node
}
ClusterConfig holds the assembled components.
type Config ¶
type Config struct {
// Domain is the tunnel base domain, e.g. "t.example.com". Tunnels live at
// "<sub>.Domain".
Domain string
// AliasDomain serves a legacy domain alongside Domain during migrations:
// requests for <sub>.AliasDomain route to the same tunnels. TLS for the
// alias uses a static wildcard-<alias>.crt/key pair in the acme dir
// (not renewed - meant for deprecation windows).
AliasDomain string
// Addr is the main HTTPS listen address (":443"). When TLSMode is "http"
// this serves plain HTTP.
Addr string
// HTTPAddr is the plain-HTTP listen address (":80"): HTTP->HTTPS redirect
// and ACME HTTP-01 challenges. Empty disables it.
HTTPAddr string
// AdminAddr is the local admin/stats listen address.
AdminAddr string
// AdminToken, when set, is required as X-Admin-Token for admin endpoints.
AdminToken string
// TrustForwardedFor honours CF-Connecting-IP / X-Real-IP /
// X-Forwarded-For when resolving the visitor IP for tunnel policy
// allowIPs. Only for deployments behind a trusted reverse proxy that
// overwrites those headers; default false keeps the socket address as
// the only source of truth (#140).
TrustForwardedFor bool
// WSPath is the WebSocket endpoint path (default "/tunnel").
WSPath string
// PublicScheme overrides the URL scheme advertised in welcome messages
// ("https" normally, "http" when TLSMode is http).
PublicScheme string
TLS TLSConfig
// Tiers maps tier ID -> limits. Must contain the DefaultTier.
Tiers map[string]*Tier
// DefaultTier is the tier for anonymous (no API key) tunnels.
DefaultTier string
// DefaultPaidTier is the tier assigned to newly registered accounts.
DefaultPaidTier string
// AccountsFile persists registered accounts (API keys). Empty disables
// persistence (memory only).
AccountsFile string
// RequireToken rejects anonymous tunnels when true.
RequireToken bool
// MaxTunnelsPerIP limits concurrent anonymous tunnels per source IP. 0 = unlimited.
MaxTunnelsPerIP int
// MaxStreamsPerTunnel limits concurrent HTTP streams per tunnel. 0 = default 256.
MaxStreamsPerTunnel int
HeaderWaitTimeout time.Duration // wait for client response headers (default 30s)
StreamIdleTimeout time.Duration // per-write deadline when proxying bodies (default 10m)
// StreamStallTimeout bounds how long one stream may block the shared
// WebSocket reader waiting for its pump to drain. A stream that cannot
// drain in this window is reset on its own; without it one slow external
// consumer freezes every stream plus ping/pong handling and the session is
// killed at PingTimeout (issue #8). Default 30s, 0 disables the bound.
StreamStallTimeout time.Duration
PingInterval time.Duration // app-level ping interval (default 30s)
PingTimeout time.Duration // liveness threshold (default 150s)
}
Config configures a Server.
type Counter ¶ added in v1.4.0
type Counter interface {
// Incr adds delta to the key and returns the new value. Keys are
// namespaced by the caller ("ip:<addr>", "acct:<apikey>").
Incr(ctx context.Context, key string, delta int64) (int64, error)
// Decr is Incr with a negative delta, used on disconnect.
Decr(ctx context.Context, key string) error
// Get returns the current value (0 when unknown).
Get(ctx context.Context, key string) (int64, error)
// TTL applies an expiry to idle per-IP counters so a churning IP does not
// accumulate forever; per-account counters must use TTLNever.
SetTTL(ctx context.Context, key string, d time.Duration) error
}
Counter is a distributed counter used for the two global quotas: tunnels-per-IP (anonymous abuse) and tunnels-per-account (plan limits). The in-memory implementation is authoritative on a single node; the Redis implementation makes the limits global across a cluster.
type Passkey ¶ added in v1.6.9
type Passkey struct {
ID []byte `json:"id"` // credential ID (raw)
PubKey []byte `json:"pk"` // COSE public key
Attest string `json:"at"` // attestation statement format
AAGUID []byte `json:"aa"` // authenticator model id (empty for none)
SignCnt uint32 `json:"sc"` // signature counter (clone detection)
BE bool `json:"be"` // backup eligible
BS bool `json:"bs"` // backed up
Name string `json:"nm"` // user-chosen device name
Created time.Time `json:"ct"`
LastUsed time.Time `json:"lu,omitempty"`
}
Passkey is one stored WebAuthn credential on an account.
type PeerMeta ¶ added in v1.4.0
type PeerMeta struct {
ID string `json:"id"` // stable instance id (hostname or env)
Addr string `json:"addr"` // internal advertise address (host:port)
Subs []string `json:"subs"` // subdomains this peer currently owns
}
PeerMeta is what one instance advertises to the cluster.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry tracks live tunnels by subdomain.
func (*Registry) Acquire ¶
Acquire assigns sub to s. If a dead session still holds it, it is replaced.
type Router ¶ added in v1.4.0
type Router interface {
// Lookup returns the advertise address of the owner, or "" when we own it
// or nobody does (fresh subdomain: we take it and broadcast).
Lookup(sub string) string
// Claim broadcasts that we now own sub.
Claim(sub string)
// Release broadcasts that we no longer own sub (going away or tunnel died).
Release(sub string)
// Forward proxies an HTTP exchange to the peer that owns sub.
Forward(sub string, w http.ResponseWriter, r *http.Request) bool
// Close leaves the cluster and broadcasts the release of everything.
Close() error
}
Router resolves which peer owns a subdomain and forwards when it is not us. meshRouter implements it via memberlist gossip; stickyRouter via a shared routing table (Redis) for L7 load balancers.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is an etunnel tunnel server.
func (*Server) Accounts ¶
func (s *Server) Accounts() accountBackend
Accounts exposes the account store (for tests/tools).
func (*Server) Drain ¶ added in v1.4.0
func (s *Server) Drain()
Drain flips the node into draining state (healthz 503, no new tunnels) so the LB can remove it before the process stops. Called from Run on ctx cancellation (SIGTERM in systemd/k8s) before sessions are closed.
func (*Server) HealthzHandler ¶ added in v1.4.0
HealthzHandler serves /healthz on the main listener: 200 when the node is accepting tunnels, 503 while draining.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is one live tunnel: a single WebSocket connection from an SDK client, owning a set of multiplexed HTTP streams.
func (*Session) CloseReason ¶
CloseReason returns why the session ended ("" while running).
func (*Session) OpenStream ¶
OpenStream registers a new server-initiated stream, or nil if the session is closing or over its stream limit.
type ShortDomain ¶ added in v1.6.0
ShortDomain is the purchased entitlement to register premium short subdomains (1-3 characters). Len is the maximum name length covered.
type Stream ¶
type Stream struct {
// contains filtered or unexported fields
}
Stream is one multiplexed HTTP exchange inside a session. The server sends the Req meta message, then DATA/FIN frames carrying the request body; the client answers with Res meta then DATA/FIN frames carrying the response body (or switches to a raw byte pipe after a 101 upgrade).
type TLSConfig ¶
type TLSConfig struct {
Mode string // http | static | ondemand | dns
CertFile string // static mode
KeyFile string // static mode
// CacheDir stores ACME certificates and account keys.
CacheDir string
// ACMEEmail is the registration email for ACME CAs.
ACMEEmail string
// ACMECA selects the ACME directory: "prod" (default), "staging", or a URL.
ACMECA string
// DNSProvider selects the DNS-01 provider (dns mode): cloudflare | alidns | dnspod.
DNSProvider string
}
TLSConfig configures certificate management.
type Tier ¶
type Tier struct {
// Name is a human-readable plan name shown in welcome messages.
Name string `json:"name"`
// TTL is the maximum tunnel lifetime. Zero means unlimited.
TTL time.Duration `json:"ttl"`
// CustomDomains is how many custom subdomains an account on this tier may
// hold simultaneously. Zero means random subdomains only.
CustomDomains int `json:"customDomains"`
// Bandwidth is the tunnel bandwidth cap in bits per second (applied to the
// combined tunnel traffic). Zero means unlimited.
Bandwidth int `json:"bandwidth"`
// MaxTunnels is how many concurrent tunnels one account may hold. Zero
// means unlimited. Per-IP limits cover anonymous tunnels; without this a
// single key could hold every subdomain (issue #10).
MaxTunnels int `json:"maxTunnels,omitempty"`
}
Tier describes the limits applied to a tunnel.
type TunnelPolicy ¶ added in v1.6.13
type TunnelPolicy struct {
BasicUser string
BasicPass string
AllowIPs []*net.IPNet // parsed CIDRs (single IPs become /32 or /128)
Webhooks []WebhookRule
}
TunnelPolicy is the parsed hello.policy object.
type WebhookRule ¶ added in v1.6.13
WebhookRule pins one provider's verification secret.
Source Files
¶
- account.go
- account_pg.go
- acme_dns.go
- admin.go
- auth.go
- auth_cli.go
- cluster.go
- cluster_setup.go
- config.go
- counter_mem.go
- counter_redis.go
- i18n.go
- i18n_ar.go
- i18n_de.go
- i18n_domkeys.go
- i18n_en.go
- i18n_es.go
- i18n_fr.go
- i18n_it.go
- i18n_ja.go
- i18n_ko.go
- i18n_legal.go
- i18n_ptbr.go
- i18n_ru.go
- i18n_zh.go
- legal.go
- payments.go
- portal.go
- proxy.go
- quickstart.go
- registry.go
- resume.go
- router_mesh.go
- router_sticky.go
- server.go
- session.go
- session_pg.go
- telegram.go
- tls.go
- tunnel_policy.go
- webauthn.go
- wss_ban.go