Documentation
¶
Overview ¶
Package subs serves the public subscription endpoint: GET <prefix>/<token> returns base64 of the user's client lines (hysteria2:// and vless:// URIs) with the headers Happ and other Xray/sing-box apps read, or, for a client the settings send to the Mihomo format, a Mihomo YAML profile (mihomo.go), to the Xray JSON format an array of Xray configs (xrayjson.go), to the sing-box format a sing-box profile (singbox.go; a hidden ?format=xray-json|sing-box on the link picks one of the two for a request); a browser gets the user page. Under the same prefix the page's self-service endpoints manage the user's AmneziaWG devices (devices.go). Unknown tokens get the decoy, so the endpoint cannot be told from any other path of the site.
Abuse protection, all in memory and bounded, none of it logging a token or an address:
- token guessing: after MissLimit unknown tokens from one client network within MissWindow, that network gets only the decoy for BlockFor, even for valid tokens;
- per token: fetches within MinInterval are answered from a cache of the rendered response (no database work), and more than MaxPerHour fetches an hour get a 429;
- link sharing: distinct client networks (/24, /48) seen per token per day are counted (never stored as addresses), and above SharedNets one subscription_shared_suspect event is written for that day;
- self-service writes (add, configs, rotate, revoke, rename a device, pick a DNS): a separate per-token counter, MaxWritesPerHour an hour, so that the fetch budget above is not shared with them.
Index ¶
- Constants
- func Choose(set *adminv1.SubscriptionSettings, ua string) (rule int, format adminv1.SubFormat, browser bool)
- func Handler(src Source, decoy http.Handler, cfg Config) http.Handler
- func IsBrowser(ua string) bool
- func IsLinkPreview(ua string) bool
- func PreviewHandler(src Previewer, cfg Config) func(w http.ResponseWriter, r *http.Request, userID string)
- type Auditor
- type Config
- type DefaultPresets
- type Devices
- type Effective
- type Events
- type FormatSource
- type PageDNS
- type Previewer
- type Routing
- type Service
- func (s *Service) GetSubscriptionSettings(ctx context.Context, ...) (*connect.Response[adminv1.GetSubscriptionSettingsResponse], error)
- func (s *Service) Handler() (string, http.Handler)
- func (s *Service) ListClients(context.Context, *connect.Request[adminv1.ListClientsRequest]) (*connect.Response[adminv1.ListClientsResponse], error)
- func (s *Service) NotifyWith(n StateNotifier)
- func (s *Service) TestUserAgent(ctx context.Context, req *connect.Request[adminv1.TestUserAgentRequest]) (*connect.Response[adminv1.TestUserAgentResponse], error)
- func (s *Service) UpdateSubscriptionSettings(ctx context.Context, ...) (*connect.Response[adminv1.UpdateSubscriptionSettingsResponse], error)
- type Source
- type StateNotifier
- type TokenChecker
Constants ¶
EventSharedSuspect is the event code written when one link is used from many networks.
Variables ¶
This section is empty.
Functions ¶
func Choose ¶
func Choose(set *adminv1.SubscriptionSettings, ua string) (rule int, format adminv1.SubFormat, browser bool)
Choose picks what a client gets: the first rule whose ua_contains is a case-insensitive substring of the User-Agent, else the user page for a browser-like User-Agent, else the base64 URI list. rule is the index into settings.Rules (-1 = fallback); browser tells the fallback took the browser branch.
func Handler ¶
Handler returns the subscription endpoint. decoy answers everything that is not a valid request for a known token.
func IsBrowser ¶
IsBrowser reports a browser-like User-Agent: "Mozilla/" plus a rendering engine token, and none of the well-known VPN clients. Heuristic; an unusual client is steered with a rule in the settings.
func IsLinkPreview ¶ added in v0.1.42
IsLinkPreview reports a link-preview bot or a crawler: it is not an app, gets nothing of the subscription and takes no device of the person.
func PreviewHandler ¶
func PreviewHandler(src Previewer, cfg Config) func(w http.ResponseWriter, r *http.Request, userID string)
PreviewHandler returns the admin preview of the user page: what the user with this id would see, framed by the admin UI (frame-ancestors 'self'). The caller checks the admin session; the handler never sees a token.
Types ¶
type Auditor ¶
Auditor writes an audit row; *store.Store implements it. Optional: Config.Events that has it gets the lockouts.
type Config ¶
type Config struct {
// Prefix is the secret path prefix the handler is mounted under ("/k3xq8"). It is stripped from the
// request path when present, so the handler works whether or not the mux already stripped it.
Prefix string
// Title is the subscription name apps show (profile-title) when neither the settings nor Brand give one.
Title string
// BaseURL is the public subscription address up to and including the prefix ("https://sub.example.com/k3xq8");
// the user's link is BaseURL + "/" + token. Empty: derived from the request (Host, TLS), good enough for tests.
BaseURL string
// Settings is the subscription settings cache (what the admin edits); nil = the built-in defaults.
Settings *subsettings.Cache
// Brand returns the instance brand at request time (a rename shows up without a restart, within
// BrandTTL); nil = a brand named Title.
Brand func(ctx context.Context) (instance.Settings, error)
// Routing, if set, adds the Happ `routing` header for Happ-like clients.
Routing Routing
// DNS resolves the DNS preset of a user's link apps for the dns section of the Mihomo, Xray JSON and sing-box profiles; nil =
// the Routing when it can do that (HappRouting's can), else the profile has no dns section.
DNS Effective
// Dist holds the build with sub.html (the user page); nil = the embedded web/dist. When the page is not
// there or has the wrong shape, browsers get the base64 list and one line is logged.
Dist fs.FS
// ClientIP returns the client address of a request; the default is auth.ClientIPFrom of the request
// context (the public listener resolves it under the trusted-proxy rules). An invalid address
// (unknown client) is never limited or counted.
ClientIP func(*http.Request) netip.Addr
// Events, if set, receives subscription_shared_suspect events. Log, if set, gets their write errors.
Events Events
Log *slog.Logger
// AfterResponse runs work that must not delay a response (on Cloudflare the Worker waits for it); nil = a goroutine.
AfterResponse func(func())
// Limiter is the shared backend for security-sensitive subscription limits. Nil uses bounded in-memory state.
Limiter securitylimit.Limiter
// Now is the clock (tests); default time.Now.
Now func() time.Time
MissLimit int // unknown tokens per MissWindow before the block; default 20
MissWindow time.Duration // default 1 minute
BlockFor time.Duration // default 15 minutes
MinInterval time.Duration // cache lifetime of a token's data; default 10 seconds
MaxPerHour int // fetches per token per hour; default 60
MaxKeys int // clients and tokens tracked per table (memory bound); default securitylimit.DefaultMaxKeysPerName
// MaxWritesPerHour is the self-service writes (device add, configs, rotate, revoke, rename, pick a DNS) per token an hour;
// default 20, negative = no limit. Separate from MaxPerHour.
MaxWritesPerHour int
BrandTTL time.Duration // how long a read of the brand is reused; default 5 seconds
// PageKey is the key of the page passwords and their cookies (vault.Derive(pagepass.KeyLabel)). Empty = the
// page never asks for a password. With a key, the page and its self-service calls are gated while the
// settings say so (subsettings.PagePassword); the subscription itself never is.
PageKey []byte
// UnlockTries is how many password entries one token, and one client network, get within UnlockWindow before
// the answer is "try later"; defaults 5 and 10 minutes, UnlockTries negative = no limit.
UnlockTries int
UnlockWindow time.Duration
}
Config of the handler. Zero values of the limits mean the defaults below; a negative value switches that protection off.
type DefaultPresets ¶
type DefaultPresets interface {
DefaultPresetID(ctx context.Context) (string, error)
SetDefaultPresetID(ctx context.Context, id string) error
LinkOptions(ctx context.Context) (*adminv1.LinkDnsOptions, error)
SetLinkOptions(ctx context.Context, o *adminv1.LinkDnsOptions) error
}
DefaultPresets reads and writes the instance default DNS preset and the offer for the link apps (owned by the DNS module, shown in the subscription settings as default_dns_preset_id and link_dns); *dns.Service implements it.
type Devices ¶
type Devices interface {
AddAWGDevice(ctx context.Context, by, userID, profileID, platform, label string) (store.AccessAWGDevice, []access.DeviceConfig, error)
DeviceConfigs(ctx context.Context, by, owner, deviceID string) (store.AccessAWGDevice, []access.DeviceConfig, error)
RotateDevice(ctx context.Context, by, owner, deviceID string) (store.AccessAWGDevice, []access.DeviceConfig, error)
RelabelDevice(ctx context.Context, owner, deviceID, label string) (store.AccessAWGDevice, error)
RevokeOwnDevice(ctx context.Context, by, owner, deviceID string) error
}
Devices is what the endpoints call; *access.Service implements it. A Source that does not leaves the endpoints off.
type Effective ¶
Effective resolves the DNS preset of a user's link apps (dns.LinkDNS: the person's pick for them, the user's, the group's, the offer's default, the instance's); *dns.Service implements it.
type FormatSource ¶
type FormatSource interface {
SubscriptionWith(ctx context.Context, token string, opt access.SubOptions) (access.SubView, error)
}
FormatSource is a Source that can also render a client format (the Mihomo profile needs the proxies of the Mihomo format); *access.Service implements it. A Source without it serves the Mihomo rule the base64 list.
type PageDNS ¶ added in v0.1.17
type PageDNS interface {
SetPageDNS(ctx context.Context, userID string, c access.PageDNSChoice) error
}
PageDNS is what the call does; *access.Service implements it. A Source that does not leaves the endpoint off.
type Previewer ¶
type Previewer interface {
PreviewSubscription(ctx context.Context, userID string) (access.SubView, string, error)
}
Previewer supplies a user's data for the admin preview; *access.Service implements it.
type Routing ¶
Routing supplies the Happ `routing` header value for a user (the effective DNS preset rendered as a Happ routing profile); the DNS module implements it. "" = send no header.
func HappRouting ¶
HappRouting makes the Routing of the handler from the DNS module: the `routing` header value is the preset of the user's link apps as a Happ routing profile. An error (Happ cannot express any main server of the preset) leaves the header out.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service implements SubscriptionService: the settings document, the list of client apps the registered protocol plugins support, and the "which format does this User-Agent get" probe. The session and the role (readonly reads, owner and helper write) are enforced by the HTTP server for every procedure.
func NewService ¶
func NewService(st *store.Store, settings *subsettings.Cache, reg *protocols.Registry, brand func(ctx context.Context) (instance.Settings, error), dns DefaultPresets, log *slog.Logger) *Service
NewService builds the service; settings is the cache the public handler reads too, brand the loader of the instance brand (for effective_title).
func (*Service) GetSubscriptionSettings ¶
func (*Service) ListClients ¶
func (*Service) NotifyWith ¶ added in v0.1.39
func (s *Service) NotifyWith(n StateNotifier)
NotifyWith sets who hears about devices that a switch of the device limit to STRICT revoked.
func (*Service) TestUserAgent ¶
func (*Service) UpdateSubscriptionSettings ¶
type StateNotifier ¶ added in v0.1.39
type StateNotifier interface{ StateChanged() }
StateNotifier is told that credentials left the database and the nodes must hear about it; the fleet implements it.