server

package
v1.6.10 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 51 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.

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.

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.

Index

Constants

View Source
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.

View Source
const (
	// TTLNever keeps the key until it is explicitly decremented to zero.
	TTLNever = time.Duration(0)
)

Variables

View Source
var ErrEmailTaken = errors.New("etunnel: email already registered")

ErrEmailTaken indicates an account already exists for the email.

View Source
var ErrSubdomainTaken = errors.New("etunnel: subdomain already in use")

ErrSubdomainTaken is returned when a live tunnel already holds a subdomain.

View Source
var ErrUnknownTier = errors.New("etunnel: unknown tier")

ErrUnknownTier indicates registration with an undefined tier.

Functions

func DefaultTiers

func DefaultTiers() map[string]*Tier

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

func T added in v1.6.0

func T(lang, key string) string

T looks up key in lang's dictionary, falling back to English, then to the key itself (a missing English key is a bug the completeness test catches; the runtime fallback keeps pages renderable regardless).

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.

func (*Account) EverPaid added in v1.3.0

func (a *Account) EverPaid() bool

EverPaid reports whether the account has ever had a paid subscription (currently paid or lapsed). Retention/GC logic must never delete such an account: it carries payment history and an OAuth binding.

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

func (s *AccountStore) PruneInactive(olderThan time.Duration, now time.Time) int

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

	// 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

func (r *Registry) Acquire(sub string, s *Session) error

Acquire assigns sub to s. If a dead session still holds it, it is replaced.

func (*Registry) Count

func (r *Registry) Count() int

Count returns the number of live tunnels.

func (*Registry) Lookup

func (r *Registry) Lookup(sub string) *Session

Lookup returns the live session for sub, or nil.

func (*Registry) Release

func (r *Registry) Release(sub string, s *Session)

Release frees sub if it is currently held by s.

func (*Registry) Snapshot

func (r *Registry) Snapshot() []*Session

Snapshot returns all live sessions.

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 New

func New(cfg Config) (*Server, error)

New builds a Server from cfg.

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) Handler

func (s *Server) Handler() http.Handler

Handler returns the main HTTP handler (useful for tests and embedding).

func (*Server) HealthzHandler added in v1.4.0

func (s *Server) HealthzHandler() http.Handler

HealthzHandler serves /healthz on the main listener: 200 when the node is accepting tunnels, 503 while draining.

func (*Server) Run

func (s *Server) Run(ctx context.Context) error

Run starts all listeners and blocks until ctx is done.

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) Close

func (s *Session) Close(reason string)

Close terminates the session: flush streams, free the subdomain.

func (*Session) CloseReason

func (s *Session) CloseReason() string

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

func (*Session) ExpiresAt

func (s *Session) ExpiresAt() time.Time

ExpiresAt returns the tunnel expiry (zero when unlimited).

func (*Session) Hostname

func (s *Session) Hostname() string

Hostname returns the full tunnel hostname (sub + base domain).

func (*Session) IsCustom

func (s *Session) IsCustom() bool

IsCustom reports whether the tunnel holds a plan-gated custom subdomain.

func (*Session) OpenStream

func (s *Session) OpenStream() *Stream

OpenStream registers a new server-initiated stream, or nil if the session is closing or over its stream limit.

func (*Session) Plan

func (s *Session) Plan() string

Plan returns the tier name.

func (*Session) RemoteIP

func (s *Session) RemoteIP() string

RemoteIP returns the SDK client IP.

func (*Session) Subdomain

func (s *Session) Subdomain() string

Subdomain returns the assigned subdomain label.

func (*Session) URL

func (s *Session) URL() string

URL returns the public URL of the tunnel.

type ShortDomain added in v1.6.0

type ShortDomain struct {
	Len       int       `json:"len"`
	ExpiresAt time.Time `json:"expiresAt"`
}

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 TierFile

type TierFile map[string]Tier

TierFile is the on-disk format for custom tier definitions.

Jump to

Keyboard shortcuts

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