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), the kl!ck app sends the reports of its local server check (probe.go) and a client enrols its device by the link (clientenrol.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:
- Per-client-network miss limit: a network that guesses too many unknown links is blocked for a while. A blocked network still gets every link the process knows to exist (TokenIndex), and a small budget of database checks for the rest.
- per token: fetches within MinInterval are answered from a cache of the rendered response (no database work), with hourly limits per token and client network and a larger per-token ceiling;
- 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-and-network counter and a larger per-token ceiling, 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 ClientAPI
- type ClientDebug
- type ClientDebugError
- type ClientDebugIn
- type ClientDebugRequest
- type ClientDebugResult
- type ClientEnrol
- type Config
- type DefaultPresets
- type Devices
- type Effective
- type Events
- type FormatSource
- type PageDNS
- type Previewer
- type ProbeStore
- type ProfilePreviewer
- 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) PreviewMihomoTemplate(ctx context.Context, ...) (*connect.Response[adminv1.PreviewMihomoTemplateResponse], error)
- func (s *Service) PreviewResponseHeaders(ctx context.Context, ...) (*connect.Response[adminv1.PreviewResponseHeadersResponse], error)
- func (s *Service) PreviewWith(p ProfilePreviewer)
- 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
- type TokenIndex
Constants ¶
const ( // ClientDebugMaxWire is the most bytes of a delivery on the wire (gzip), ClientDebugMaxText the most after unpacking, and // ClientDebugReadWindow how long the body may take to arrive: the listener's own 30 seconds cut a megabyte on a slow line. ClientDebugMaxWire = 1 << 20 ClientDebugMaxText = 4 << 20 ClientDebugReadSpan = 2 * time.Minute )
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 ClientAPI ¶
type ClientAPI interface {
ClientDeviceByKey(ctx context.Context, keyHash []byte) (store.AccessDevice, store.LinkDeviceKeyOwner, error)
ClientSubscription(ctx context.Context, dev store.AccessDevice, hint access.DeviceHint, caps []string) (access.SubView, error)
ClientLeaveDevice(ctx context.Context, dev store.AccessDevice) error
}
ClientAPI is what GET <base>/sync and POST <base>/leave call; *access.Service implements it. A Source that does not leaves the endpoints to the decoy.
type ClientDebug ¶
type ClientDebug interface {
// Open is the device's open request, for sync.
Open(ctx context.Context, deviceID string, now time.Time) (ClientDebugRequest, bool, error)
// Admit says, before the body is read, whether a delivery may come: a *ClientDebugError (409 no_request, 429, 503 debug_full)
// when not. When the request is answered already (a repeat of a delivery the panel took) it returns that answer instead.
Admit(ctx context.Context, dev store.AccessDevice, requestID string, now time.Time) (*ClientDebugResult, error)
// Receive reads, checks, cleans and stores the delivery. A *ClientDebugError carries a refusal.
Receive(ctx context.Context, in ClientDebugIn) (ClientDebugResult, error)
// Decline is the person's refusal of an open request.
Decline(ctx context.Context, dev store.AccessDevice, requestID string, now time.Time) (string, error)
}
ClientDebug keeps the logs people send; internal/panel/clientdebug.Service implements it. Nil = the edition takes none.
type ClientDebugError ¶
ClientDebugError is a refusal of the debug routes with the answer it is: the status, the code of the JSON body, a message that holds no value of the request, and for 429 and 503 how long to wait. Any other error is a 500.
func (*ClientDebugError) Error ¶
func (e *ClientDebugError) Error() string
type ClientDebugIn ¶
type ClientDebugIn struct {
Device store.AccessDevice
RequestID string
UserAgent string
Body io.Reader
Now time.Time
}
ClientDebugIn is a delivery whose body (unpacked, at most ClientDebugMaxText+1 bytes) has not been read yet. RequestID is empty for a bundle the person sends on their own.
type ClientDebugRequest ¶
ClientDebugRequest is an open request of the owner as sync tells the person.
type ClientDebugResult ¶
ClientDebugResult is what a delivery stored.
type ClientEnrol ¶
type ClientEnrol interface {
ClientDeviceByKey(ctx context.Context, keyHash []byte) (store.AccessDevice, store.LinkDeviceKeyOwner, error)
EnrolLinkDevice(ctx context.Context, userID, token string, hint access.DeviceHint, keyHash []byte) (store.LinkDeviceResult, error)
ReenrolLinkDevice(ctx context.Context, userID, deviceID, token string, expectedKeyHash, keyHash []byte) (bool, error)
}
ClientEnrol is what POST <link>/client/enrol calls; *access.Service implements it. A Source that does not leaves the endpoint off (the decoy answers a valid link, as for any path the panel does not have).
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
// ClientASN is an in-process lookup against the VPS edition's networks table. It is called only for X-Mistgate-Direct: 1;
// nil in the edge edition and when no trusted table is loaded.
ClientASN func(netip.Addr) uint32
// 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
// ProbeReports keeps the reports of the kl!ck probe (POST <prefix>/<token>/probe). The owner's switch is read with the
// settings (Settings.ProbeReports); while it is on, the app answers carry Probe-Report. Nil = the panel takes none.
ProbeReports ProbeStore
// ClientDebug keeps the logs people send for support (POST <prefix>/client/debug, internal/panel/clientdebug); sync tells the app
// about it. Nil in the Cloudflare edition: sync says debug.intake false and the route answers 403 debug_off.
ClientDebug ClientDebug
// ClientDebugSlotWait is how long a delivery of logs waits for the one slot of the process (it unpacks, cleans and stores one at a
// time); zero = 8 seconds. ClientDebugAttemptsPerHour is how many deliveries a person may bring to the reading of the body in an
// hour, broken ones too; zero = 6, negative = no limit.
ClientDebugSlotWait time.Duration
ClientDebugAttemptsPerHour int
// ClientDebugReaders is how many bodies of deliveries of logs are read at once (each is held in memory up to ClientDebugMaxWire, from
// one device at a time); one more is refused with 503 retry before its body is read. Zero = 8.
ClientDebugReaders int
// 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 and client network per hour; default 60; token ceiling is 600
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 and client
// network an hour; default 20, with a 100 per-token ceiling. Negative disables both. Separate from MaxPerHour.
MaxWritesPerHour int
// MaxEnrolsPerHour is the client API enrolments (POST <link>/client/enrol) per link an hour, on top of the writes above;
// default enrolPerHour, negative = no limit (tests).
MaxEnrolsPerHour 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 client network get within UnlockWindow before the answer is
// "try later"; defaults 5 and 10 minutes, with a 50 per-token ceiling. UnlockTries negative disables both.
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 ProbeStore ¶ added in v0.1.51
type ProbeStore interface {
InsertClientProbeReport(ctx context.Context, report string, at time.Time, n store.ClientProbeNetwork, rows []store.ClientProbeResult) (int64, error)
}
ProbeStore keeps the reports of the kl!ck probe (clientprobe); *store.Store implements it.
type ProfilePreviewer ¶
type ProfilePreviewer interface {
PreviewSubscriptionWith(ctx context.Context, userID string, opt access.SubOptions) (access.SubView, error)
}
ProfilePreviewer supplies a user's view for the admin's preview of a Mihomo profile (it writes nothing); *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) PreviewMihomoTemplate ¶
func (s *Service) PreviewMihomoTemplate(ctx context.Context, req *connect.Request[adminv1.PreviewMihomoTemplateRequest]) (*connect.Response[adminv1.PreviewMihomoTemplateResponse], error)
PreviewMihomoTemplate builds the Mihomo profile one person would get from the editor's draft of a template, the way the answer of their link builds it, and says what the owner should look at. It reads the person's view without writing (no device, no credential), and the servers of the person come out with their name, type, address and port only: the owner sees where the servers went in the template, not the keys of the person.
func (*Service) PreviewResponseHeaders ¶
func (s *Service) PreviewResponseHeaders(ctx context.Context, req *connect.Request[adminv1.PreviewResponseHeadersRequest]) (*connect.Response[adminv1.PreviewResponseHeadersResponse], error)
PreviewResponseHeaders says which of the own headers of the list one person's answer carries for a User-Agent: the answer format that User-Agent is served by the saved rules, the person's group and whether their subscription serves them at all.
func (*Service) PreviewWith ¶
func (s *Service) PreviewWith(p ProfilePreviewer)
PreviewWith sets where the views of the Mihomo template preview come from (the access module).
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.
type TokenChecker ¶ added in v0.1.23
TokenChecker lets a Source confirm a cached link without building the subscription view.
type TokenIndex ¶
TokenIndex lets a Source say that a token is one it knows exists, from memory, without a database call. For a request from a network blocked for guessing it is what tells a real link the process has not served yet from a guess: a token the index knows is served normally, and only the others spend the network's small budget of database checks (takeColdLookup).