subs

package
v0.1.39 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: AGPL-3.0 Imports: 42 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 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); 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

View Source
const EventSharedSuspect = "subscription_shared_suspect"

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

func Handler(src Source, decoy http.Handler, cfg Config) http.Handler

Handler returns the subscription endpoint. decoy answers everything that is not a valid request for a known token.

func IsBrowser

func IsBrowser(ua string) bool

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

type Auditor interface {
	Audit(ctx context.Context, now time.Time, e store.AuditEntry) error
}

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 effective DNS preset of a user for the dns section of the Mihomo profile; 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
	SharedNets  int           // distinct client networks per token per day before the event; default 8
	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
}

DefaultPresets reads and writes the instance default DNS preset (owned by the DNS module, shown in the subscription settings as default_dns_preset_id); *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

type Effective interface {
	Effective(ctx context.Context, userID string) (dns.Preset, dns.Source, error)
}

Effective resolves the DNS preset of a user; *dns.Service implements it.

type Events

type Events interface {
	InsertEvent(ctx context.Context, e store.EventRow) error
}

Events receives the "link shared" signal; *store.Store 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

type Routing interface {
	HappRouting(ctx context.Context, userID string) (string, error)
}

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

func HappRouting(e Effective) Routing

HappRouting makes the Routing of the handler from the DNS module: the `routing` header value is the user's effective preset (user, group, instance default, built-in) 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) Handler

func (s *Service) Handler() (string, http.Handler)

Handler returns the Connect path and handler of SubscriptionService.

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.

type Source

type Source interface {
	Subscription(ctx context.Context, token string) (access.SubView, error)
}

Source resolves a token; *access.Service implements it.

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

type TokenChecker interface {
	CheckSubscriptionToken(ctx context.Context, token string) error
}

TokenChecker lets a Source confirm a cached link without building the subscription view.

Jump to

Keyboard shortcuts

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