Documentation
¶
Overview ¶
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.
Index ¶
- Constants
- Variables
- func DefaultTiers() map[string]*Tier
- 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) ResetKey(email string) (string, bool)
- func (s *AccountStore) Snapshot(key string) (Account, bool)
- type BillingConfig
- type Config
- type Registry
- 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 Stream
- type TLSConfig
- type Tier
- type TierFile
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.
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"`
// 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"`
}
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.
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) 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).
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 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 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 Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is an etunnel tunnel server.
func (*Server) Accounts ¶
func (s *Server) Accounts() *AccountStore
Accounts exposes the account store (for tests/tools).
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 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.