httpserver

package
v0.2.0-dev.10 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: AGPL-3.0 Imports: 41 Imported by: 0 modules, 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

Package httpserver wires the panel's HTTP surface: the public listener (decoy site, the admin UI/API when it is reached by secret host or secret path prefix, the secret public mounts such as subscriptions, and the agent endpoint selected by a secret TLS SNI name) and an optional separate admin listener.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewDecoy

func NewDecoy(dir string) http.Handler

NewDecoy returns the handler for a secret mount (the subscription endpoint) to answer with whatever is not its own: the same 404 the public listener gives every unknown path, for any path and method. It is not the decoy site itself: a mount sees its prefix stripped, so the site's "/" page would answer the bare prefix with 200 and tell a guessed prefix from a wrong one.

func NewDecoyFor

func NewDecoyFor(dir string, st *store.Store) http.Handler

NewDecoyFor is NewDecoy for a panel that has the library of decoy sites: the 404 is the one of the site the owner chose for the panel, like the public listener's, so a secret mount cannot be told from a stranger's path.

func NewLogoHandler

func NewLogoHandler(st *store.Store, log *slog.Logger) http.Handler

NewLogoHandler serves the brand logo without a session: GET/HEAD, image/svg+xml, 404 when there is no custom logo. The SVG was sanitised on the way in; the headers also keep it inert if someone opens it as a page (no script, no sandbox escape) and let the browser revalidate by ETag. Mount it wherever a public page needs the logo.

func NewTooMany

func NewTooMany(dir string) func(w http.ResponseWriter, r *http.Request, retry time.Duration)

NewTooMany returns the 429 of the decoy site (429.html of the decoy dir, else the built-in page, Retry-After in whole seconds). A secret mount answers with it when a stranger has failed too often, so the limit looks like the one of the site.

func NewTooManyFor

func NewTooManyFor(dir string, st *store.Store) func(w http.ResponseWriter, r *http.Request, retry time.Duration)

NewTooManyFor is NewTooMany for a panel that has the library of decoy sites (see NewDecoyFor).

Types

type AdminHandler

type AdminHandler struct {
	Path    string
	Handler http.Handler
}

AdminHandler is one more handler under the admin API, usually a Connect service but sometimes a plain HTTP route. Path is its prefix and is served at /api<Path> behind the session middleware, so handlers can rely on auth.AdminFrom.

type AdminPage

type AdminPage struct {
	Path    string
	Handler http.Handler
}

AdminPage is a server-rendered page on the authenticated admin surface. Path must be an exact path without a trailing slash; both forms are served without redirects so a secret admin prefix is preserved.

type Config

type Config struct {
	// AdminHost, if set, serves the admin on the public listener for requests whose Host
	// is exactly this name (mode a). Everything else on that host gets the decoy.
	AdminHost string
	// AdminPrefix, if set ("/" + secret + "/"), serves the admin on the public listener
	// under that path prefix (mode b).
	AdminPrefix string
	// DecoyDir holds the decoy site; empty means the built-in "coming soon" page.
	DecoyDir string
	// TrustedOrigins are browser origins allowed to make state-changing requests to the
	// admin in addition to same-origin (the WebAuthn origins; in dev the Vite server).
	TrustedOrigins []string
	// Dist is the SPA build; nil means the embedded web/dist.
	Dist fs.FS
	Log  *slog.Logger

	// AdminHandlers are further admin API services (nodes, users, profiles ...), mounted
	// with AuthService and InstanceService behind the session middleware.
	AdminHandlers []AdminHandler
	// AdminPages are Go-rendered pages mounted on the signed-in admin surface. They use
	// the same owner-only session policy as unknown admin procedures and do not accept API tokens.
	AdminPages []AdminPage
	// PublicMounts maps secret prefixes ("/" + secret + "/", like AdminPrefix) on the
	// public listener to public handlers, e.g. the subscription endpoint. The handler sees
	// the path with the prefix (minus its trailing slash) stripped. Everything outside the
	// admin and these prefixes is the decoy.
	PublicMounts map[string]http.Handler

	// Limits are the per-client request limits of the public listener, the admin surface and
	// the agent endpoint; zero values mean the defaults.
	Limits Limits

	// AgentSNI, AgentTLS and AgentHandler serve the node agents on the public TLS
	// listener. A TLS handshake whose server name is AgentSNI gets the tls.Config AgentTLS
	// returns for that ClientHello (server certificate from the panel's own CA, client
	// certificates, ...), and the requests on such a connection go to AgentHandler. The
	// listener's read/write deadlines are lifted only for a stream opened with a verified
	// client certificate (agent streams are long-lived); the unauthenticated Enroll call, and
	// anything else without a certificate, keeps them and a small body limit.
	// Requests that did not arrive on such a connection never reach AgentHandler. The
	// endpoint exists only when AgentTLS and AgentHandler are both set (AgentSNI alone is
	// accepted, so the name can be carried before the fleet module is wired in).
	AgentSNI     string
	AgentTLS     func(*tls.ClientHelloInfo) (*tls.Config, error)
	AgentHandler http.Handler

	// AgentLinkPrefix and AgentLinkHandler serve the signed WebSocket transport on the public listener.
	// The prefix is a stored secret path; unrelated paths continue to the decoy and public mounts.
	AgentLinkPrefix  string
	AgentLinkHandler http.Handler

	// ReservedPrefixes are secret path prefixes that another Worker of the edge serves (the edge splits the panel into
	// Workers that each serve one surface). They are not served here; New only checks that none of them overlaps what is.
	// Empty entries are ignored.
	ReservedPrefixes []string

	// UserPagePreview, if set, serves GET <admin>/preview/user-page/<user id>: the public user page as that user
	// would see it, for the admin to show in a frame. The server checks the session and the right to see the user's
	// link (GetSubscriptionLink: helper or owner, never a token) and validates the id; the function writes the
	// response (its own CSP with frame-ancestors 'self').
	UserPagePreview func(w http.ResponseWriter, r *http.Request, userID string)

	// AdminURL and SubscriptionBase are where the admin is reached and the base of the subscription links, as `mistgate
	// setup` stored them: InstanceService shows them to the owner (Settings -> Domains), read-only.
	AdminURL, SubscriptionBase string

	// MCP, if set, builds the handler of the MCP endpoint from the in-process admin API: the services
	// behind the session middleware, request paths without the "/api" prefix. The result is served at <admin>/mcp, and only
	// on the admin surface (behind the secret prefix, host or separate listener): never on the decoy side, the public mounts
	// or the agent endpoint. The handler authenticates its own requests (a bearer token, never a cookie). nil: no endpoint.
	MCP func(api http.Handler) http.Handler
	// AdminAPIReady is called with the authenticated in-process API after all handlers have been registered. Internal
	// services that act through the same API can bind here without depending on the HTTP listener.
	AdminAPIReady func(api http.Handler)
	// Metrics, if set, is asked first for <admin>/metrics on the admin surface only. It authenticates its own requests (a
	// bearer secret of its own, never a session) and returns false, having written nothing, while the owner has the endpoint
	// off: the request then gets what any unknown admin path gets. nil: no endpoint (the Cloudflare edition).
	Metrics func(w http.ResponseWriter, r *http.Request) bool
	// RPCStats, if set, is told about every admin API call (/api/...) when it ends: its status, how long it took and whether
	// it was a stream (rpcstat.Window, read by OpsService.GetPanelResources). The VPS edition only.
	RPCStats interface {
		Record(status int, d time.Duration, stream bool)
	}
}

Config selects how the admin UI and API are reachable and what else the panel serves.

type Limits

type Limits struct {
	Public Rate // decoy site, robots.txt and the public mounts (subscriptions)
	Admin  Rate // the admin UI and API, whichever way it is reached
	Agent  Rate // the node agent endpoint
	// MaxKeys bounds the clients tracked per limit (memory); the least recently seen is forgotten first.
	MaxKeys int
}

Limits are the request limits per client network (IPv4 address, IPv6 /64). Over the limit a request is answered with a 429 that looks like a web server's own, with Retry-After. A long-lived stream counts once, when it is opened.

type Rate

type Rate struct {
	PerSecond float64
	Burst     int
}

Rate is a token bucket per client: Burst requests at once, then PerSecond. The zero value means the default; a negative PerSecond switches the limit off.

type ServeOptions

type ServeOptions struct {
	Public      string // address of the main listener (decoy, and admin in modes a/b)
	Admin       string // optional separate admin listener address
	AgentListen string // optional separate TLS listener for the agent endpoint (dev; needs the agent hooks)
	TLSCert     string // optional; applies to the public listener
	TLSKey      string
	// ACMEDomains get Let's Encrypt certificates on the public listener (TLS-ALPN-01, so it
	// must be reachable on port 443), with the cache in ACMEDir. ACMEHTTP, if set (":80"), is
	// a listener for HTTP-01 and the http -> https redirect.
	ACMEDomains []string
	ACMEEmail   string
	ACMEDir     string
	ACMEHTTP    string
}

ServeOptions are the listener settings for Serve.

type Server

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

Server builds the HTTP handlers.

func New

func New(cfg Config, a *auth.Service, st *store.Store) (*Server, error)

New validates cfg and builds the server. st is the panel database (instance settings, logo).

func NewPublic added in v0.1.41

func NewPublic(cfg Config, st *store.Store) (*Server, error)

NewPublic builds a server without an admin: the secret public mounts, the agent link and the decoy, with the client address taken from the TCP peer (no proxy is trusted). The Workers of the edge that serve only a public surface use it, so the admin code is not part of them. cfg must carry no admin, agent endpoint, MCP or preview setting.

func (*Server) AdminListener

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

AdminListener is the handler for a separate admin listener (mode c): prefix "/".

func (*Server) Public

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

Public is the handler for the main listener. Agent connections go to the agent handler; non-canonical paths, unknown hosts, wrong or missing prefixes and unknown paths all get the decoy.

func (*Server) Serve

func (s *Server) Serve(ctx context.Context, o ServeOptions) error

Serve runs the listeners until ctx is cancelled, then shuts them down gracefully.

Directories

Path Synopsis
Package ratelimit holds the in-memory, bounded-memory state behind the public surface's abuse protection: a keyed map that evicts its least recently used entry when full, and a token bucket limiter built on it.
Package ratelimit holds the in-memory, bounded-memory state behind the public surface's abuse protection: a keyed map that evicts its least recently used entry when full, and a token bucket limiter built on it.

Jump to

Keyboard shortcuts

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