subsettings

package
v0.2.0-dev.4 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: AGPL-3.0 Imports: 24 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 subsettings holds the subscription settings of the installation (SubscriptionService): names and texts, the apps the public user page recommends, the server-name template and the format rules. They are stored as one protojson value in the setting table under Key, validated on the way in, and read at request time through a small cache that Update invalidates.

default_dns_preset_id and link_dns are not part of the stored document: the DNS module owns the instance default preset and the offer for the link apps (one source of truth), and SubscriptionService reads and writes them through that module.

Index

Constants

View Source
const (
	MaxResponseHeaders = 20
	MaxHeaderName      = 64
	MaxHeaderValue     = 1000
	MaxHeadersBytes    = 4096
)

Limits of the owner's own response headers (SubscriptionSettings.response_headers). The total is the bytes of all names and values as they are sent, with the separators: what one answer can carry at most if every entry applies to it. A reverse proxy in front of the panel buffers a response's headers in 4 or 8 KiB, and the panel's own headers take about 1 KiB of that.

View Source
const (
	MaxMihomoTemplates      = 20
	MaxMihomoTemplateBytes  = 64 << 10
	MaxMihomoTemplatesBytes = 256 << 10
	MaxMihomoTemplateName   = 60
)

Limits enforced by Validate.

View Source
const (
	WarnNoServerGroup      = "no_server_group"      // no group takes the person's servers
	WarnOwnDNS             = "own_dns"              // the template has a dns section: the person's DNS preset is not applied
	WarnPresetRulesSkipped = "preset_rules_skipped" // the person's preset has rules (ads, split, countries) that a template does not get
	WarnOwnAuto            = "own_auto"             // the template has its own Auto: the panel adds none
	WarnUnknownRuleTarget  = "unknown_rule_target"  // Arg: the last field of a rule that no proxy, group or core name carries
	WarnUnused             = "unused"               // the template names no group: nobody gets it
)

The codes of MihomoWarning.Code; the admin words them (web/src/i18n/subs.ts).

View Source
const (
	MaxRoutingProfiles     = 20
	MaxRoutingProfileBytes = 32 << 10
	MaxRoutingInput        = 128 << 10
	MaxRoutingName         = 60
	MaxRoutingHeaderValue  = 3000
)

The owner's own routing profiles for Happ and INCY (SubscriptionSettings.routing_profiles). Both apps take the same profile: a JSON object of known fields, which they get as a link `<scheme>://routing/(add|onadd)/<base64 of the JSON>` in the `routing` header or on a line of the subscription body (Happ: happ.su/main/dev-docs/routing; INCY: docs.incy.cc/en/routing, read 2026-11-18; neither says where the app stops reading).

What a save keeps. The owner pastes a link, a bare base64 or the JSON; the panel reads it into RoutingDoc, which holds only the fields the two apps document, with the types the docs show, and stores the JSON it writes out of that, never the pasted text. A field it does not know is dropped and named to the owner (an app may add one; it cannot get through unread, and a profile of someone else's tool shows what was left out). A value of a known field that has the wrong type, or an address that is not https where the app downloads a file, is a refusal that says which one. What the owner's text cannot do is put any other text in the answer: the header is the fixed prefix and base64.

Size. A profile is at most MaxRoutingProfileBytes of JSON as stored. The link goes in the `routing` header while it is at most MaxRoutingHeaderValue bytes: a reverse proxy buffers the headers of an answer in 4 or 8 KiB, the panel's own take about 1 KiB, and the owner's own response headers may take 4096 more; what is left of 8 KiB is 3 KiB. A longer link goes on a line of the body, which both apps read (the docs of both show a routing line beside the servers).

View Source
const (
	MaxRules = 50
	MaxApps  = 30
)

Limits enforced by Validate.

View Source
const AutoName = "Auto"

AutoName is the group the panel adds over the servers of a person; a template refers to it by this name.

View Source
const DefaultNameTemplate = "{flag} {country} · {profile}"

DefaultNameTemplate is the server-name template of a fresh install and of an empty template: the country and profile, so servers using different protocols or exits stay recognizable in the client's list. Migration 00035 moves installations off the previous "{flag} {country}" default.

View Source
const DefaultUpdateHours = 12

DefaultUpdateHours is what an interval of 0 means.

View Source
const Key = "subscription_settings"

Key is the setting-table key of the stored document.

Variables

View Source
var CoreNames = []string{"DIRECT", "REJECT", "REJECT-DROP", "PASS", "COMPATIBLE", "GLOBAL"}

CoreNames are the adapters of the Mihomo core: a proxy or group with one of these names would be shadowed by it.

View Source
var ErrInvalid = errors.New("invalid subscription settings")

ErrInvalid wraps every validation failure (the RPC maps it to INVALID_ARGUMENT).

View Source
var ErrNoServers = errors.New("mihomo template: no servers")

ErrNoServers: a template is put around servers; without any there is nothing to put, and an empty url-test breaks the profile.

Functions

func ApplyMihomoTemplate

func ApplyMihomoTemplate(text string, servers []MihomoServer, opt MihomoOptions) ([]byte, error)

ApplyMihomoTemplate puts the servers of a person into a template: they go first in `proxies` (a name the template or the core has gets " ·" added, the template's names are never changed), then `Auto` and `dns` as described at the top of this file. The template is read anew each call (the stored document is shared: its nodes are not modified). The result is the document to send.

ponytail: a read, a decode of the names and an encode on every request (about 6 ms of wasm CPU for a 14 KB template, 27 ms for 64 KiB). If that ever costs too much: remember the nodes per template text and copy them deeply.

func CheckMihomoTemplate

func CheckMihomoTemplate(text string, autoOn bool) error

CheckMihomoTemplate is the save of one template's text, without its name and groups: it returns the first thing a save refuses. autoOn is link_auto_select of the document.

func CheckResponseHeaders

func CheckResponseHeaders(list []*adminv1.ResponseHeader) ([]*adminv1.ResponseHeader, error)

CheckResponseHeaders normalizes a copy of list and checks it as a save does (for the preview of an unsaved list); the returned list is the normalized copy.

func DNSChoice added in v0.1.17

func DNSChoice(s *adminv1.SubscriptionSettings) bool

DNSChoice reports whether people may pick the DNS of each server on the public page (DnsService.SetNodeDnsOptions says what is offered). Settings stored before the key existed have none: absent means off, a new feature does not switch itself on.

func Defaults

func Defaults() *adminv1.SubscriptionSettings

Defaults are the settings of a fresh install: on Windows and macOS kl!ck leads the page (recommended, with its klick://add link) and Happ follows; on iOS and Android Happ is recommended with the happ://add link; AmneziaVPN for the Amnezia kind on every platform, from the store on a phone; Mihomo clients (kl!ck is one) get the YAML profile; users may manage their own AmneziaWG devices on the page.

func FillRoutingInfo

func FillRoutingInfo(s *adminv1.SubscriptionSettings)

FillRoutingInfo sets the info of each entry of the settings (shown to the admin; never stored).

func LinkAWG added in v0.1.80

func LinkAWG(s *adminv1.SubscriptionSettings) bool

LinkAWG reports whether Mihomo profiles carry AmneziaWG servers. Settings stored before the switch existed have no key: absent means on, so an upgrade keeps today's behaviour.

func LinkAutoSelect

func LinkAutoSelect(s *adminv1.SubscriptionSettings) bool

LinkAutoSelect reports whether Mihomo and sing-box profiles include an automatic server group. Settings stored before the switch existed have no key: absent means on, so an upgrade keeps the current server list usable by default.

func Load

Load reads the stored settings; an install that never saved any gets Defaults(). The mode of the device limit, which has a setting of its own (see linkModeKey), is merged in: a panel that was never given one reads as TRACK.

func MigrateLinkDeviceLimit added in v0.1.39

func MigrateLinkDeviceLimit(ctx context.Context, st *store.Store) error

MigrateLinkDeviceLimit gives an installation the mode of its device limit, once: a panel that has users counts only (TRACK, so that nobody over the limit is cut off by an upgrade: the owner raises limits and switches to ENFORCE himself), a panel with none refuses from the start (ENFORCE). The setting is its own marker, written only when absent, so a mode the owner chose is never overwritten and isolates that start together agree on the first value. Idempotent.

func MigrateM3

func MigrateM3(ctx context.Context, st *store.Store) error

MigrateM3 gives an installation whose saved settings predate them the two Mihomo format rules (mihomo, clash -> Mihomo YAML), once: the marker setting sub_rules_m3 = 1 is written in the same transaction, so a rule the admin deletes later is not added back. An installation that never saved settings needs nothing (Defaults() has the rules); it only gets the marker. Idempotent and safe to call at every start.

func MigrateSingbox added in v0.1.40

func MigrateSingbox(ctx context.Context, st *store.Store) error

MigrateSingbox gives an installation whose saved settings predate the sing-box profile the rule `sing-box` -> sing-box JSON, once, at the end of the list: the marker setting sub_rules_singbox = 1 is written in the same transaction, so a rule the admin deletes later is not added back. The apps this rule catches (SFA, SFI) got a link list they cannot read before, so there is nothing to lose. A rule of the same User-Agent text (any case), whatever its format, is the admin's and is left alone. An installation that never saved settings needs nothing (Defaults() has the rule); it only gets the marker. Idempotent and safe to call at every start.

func MihomoAutoGroup

func MihomoAutoGroup(name string, members []string) *yaml.Node

MihomoAutoGroup is the url-test group over members (the one definition of it: the built-in profile and a template both use it).

func MihomoTemplateFor

func MihomoTemplateFor(s *adminv1.SubscriptionSettings, groupID string) *adminv1.MihomoTemplate

MihomoTemplateFor is the template of a group: the first that names it (the save allows one group in one template only).

func Normalize

func Normalize(s *adminv1.SubscriptionSettings)

Normalize trims the free-text fields in place (what Update stores).

func PagePassword

func PagePassword(s *adminv1.SubscriptionSettings) bool

PagePassword reports whether the user's page asks for its password (see package pagepass). Settings stored before the key existed have none: absent means on, so an upgrade protects every page.

func Parse added in v0.1.26

func Parse(value string) (*adminv1.SubscriptionSettings, error)

Parse reads a stored subscription-settings document. Missing documents should use Defaults instead.

func RoutingInfoOf

func RoutingInfoOf(profile string, dropped []string) (*adminv1.RoutingInfo, error)

RoutingInfoOf says in numbers what a profile holds (what the admin shows); the profile is the stored JSON, dropped the names a preview of a pasted text found (nil for a stored entry).

func RoutingProfileFor

func RoutingProfileFor(s *adminv1.SubscriptionSettings, groupID string) *adminv1.RoutingProfile

RoutingProfileFor is the profile of a person by their main group: the profile that names the group, else the one for all groups, else none. A person in several groups is decided by the main group alone (the extra groups name nothing here), the way the own response headers and the Mihomo templates are. The save keeps a group in one profile and one profile for all groups, so a person gets one profile at most.

func RoutingProfileOf

func RoutingProfileOf(input string) (*adminv1.RoutingProfile, error)

RoutingProfileOf reads an input into the entry the settings store, with its info: the canonical JSON, the mode of a link, the fields left out. The groups are the caller's.

func RoutingProfilesDiffer

func RoutingProfilesDiffer(a, b []*adminv1.RoutingProfile, skip func(id string) bool) bool

RoutingProfilesDiffer says whether two lists give people different routing: a profile by its name (any case), its stored JSON, its mode and its groups as a set (those that skip says to leave out). The order is not compared: a group has one profile at most.

func SelfService

func SelfService(s *adminv1.SubscriptionSettings) bool

SelfService reports whether users may add, rotate and revoke their own AmneziaWG devices on the public page. Settings stored before the key existed have none: absent means on.

func SentValue

func SentValue(value string, b64 bool) string

SentValue is the value as it goes out: the text itself, or "base64:" and its base64 (the way the panel sends the title).

func SetProxyName

func SetProxyName(m *yaml.Node, name string)

SetProxyName replaces the name of a proxy mapping with a quoted scalar (the key exists: the caller found it).

func UniqueName

func UniqueName(name string, taken map[string]bool) string

UniqueName makes a proxy name safe: not one of the core's adapter names (any case) and not taken yet. The name is added to taken.

func Validate

func Validate(s *adminv1.SubscriptionSettings) error

Validate checks a whole document; nil = storable.

Types

type Cache

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

Cache serves the settings to the subscription handler: one database read per TTL, dropped by Update.

func NewCache

func NewCache(st *store.Store, log *slog.Logger) *Cache

NewCache makes the cache. log may be nil. It also runs MigrateM3, MigrateSingbox and MigrateLinkDeviceLimit (the panel builds the cache once at start, in both editions); a failure is logged and the next start tries again.

func NewCacheWithoutMigrations added in v0.1.41

func NewCacheWithoutMigrations(st *store.Store, log *slog.Logger) *Cache

NewCacheWithoutMigrations is NewCache that leaves the data migrations to the Worker that owns them: the edge's public Worker only reads, and spends no database reads on them when it starts. log may be nil.

func (*Cache) ClientAPIEnabled

func (c *Cache) ClientAPIEnabled(ctx context.Context) bool

ClientAPIEnabled reports whether the owner enabled client API discovery; it shares the subscription settings cache.

func (*Cache) Get

Get returns the settings; the result is shared and must not be modified. A subscription fetch must not fail over settings: when the document cannot be read, the last good copy is kept (the next call reads again), and the defaults are returned without being cached. The read does not end with the caller's context: one app that gave up on a slow panel must not decide what everyone else is served for the next minute.

func (*Cache) Invalidate

func (c *Cache) Invalidate()

Invalidate drops the cached copy.

func (*Cache) ProbeReports added in v0.1.51

func (c *Cache) ProbeReports(ctx context.Context) bool

ProbeReports says whether the panel takes the reports of the kl!ck probe (store.SettingClientProbe), as cached with the settings: a switch reaches the subscription answers within the TTL. Off while nothing could be read yet.

func (*Cache) Update

Update validates, stores and caches s (a copy is stored; s itself is not kept). See UpdateRevoking.

func (*Cache) UpdateRevoking added in v0.1.39

UpdateRevoking is Update that also says how many people lost their shared device to a switch to STRICT, which revokes them in the same batch that stores the mode (the caller tells the nodes). s.link_device_limit unset leaves the stored mode as it is; the returned settings always carry the mode in force.

type MihomoOptions

type MihomoOptions struct {
	// AutoSelect adds the Auto group (link_auto_select), unless the template has a name Auto.
	AutoSelect bool
	// DNS is the dns section to add when the template has none (absent or null); nil adds nothing.
	DNS *yaml.Node
}

MihomoOptions are the choices of the document and of the person that apply to a template.

type MihomoServer

type MihomoServer struct {
	Node *yaml.Node
	Name string
}

MihomoServer is one server of a person for a template: its proxy mapping (it has a `name` key) and the name it wants.

type MihomoWarning

type MihomoWarning struct{ Code, Arg string }

MihomoWarning is one finding of a template that does not stop a save: the profile works, and the owner should look.

func MihomoTemplateWarnings

func MihomoTemplateWarnings(text string, autoOn bool) []MihomoWarning

MihomoTemplateWarnings are what the owner should look at in a template that the save accepts (which codes: the Warn constants). preset_rules_skipped and unused need more than the text and are the caller's. A text that does not read gives none.

type RoutingDNS

type RoutingDNS struct {
	RemoteType, RemoteDomain, RemoteIP, DomesticType, DomesticDomain, DomesticIP string
	Hosts                                                                        map[string]string
}

RoutingDNS are the DNS fields a person's DNS preset puts into the owner's profile (dns.ProfileDNS, without the import).

type RoutingDoc

type RoutingDoc struct {
	Name              string            `json:"Name"`
	GlobalProxy       string            `json:"GlobalProxy,omitempty"`
	LastUpdated       string            `json:"LastUpdated,omitempty"`
	RemoteDNSType     string            `json:"RemoteDNSType,omitempty"`
	RemoteDNSDomain   string            `json:"RemoteDNSDomain,omitempty"`
	RemoteDNSIP       string            `json:"RemoteDNSIP,omitempty"`
	RemoteDns         string            `json:"RemoteDns,omitempty"`
	DomesticDNSType   string            `json:"DomesticDNSType,omitempty"`
	DomesticDNSDomain string            `json:"DomesticDNSDomain,omitempty"`
	DomesticDNSIP     string            `json:"DomesticDNSIP,omitempty"`
	DomesticDns       string            `json:"DomesticDns,omitempty"`
	DnsHosts          map[string]string `json:"DnsHosts,omitempty"`
	FakeDNS           string            `json:"FakeDNS,omitempty"`
	DirectSites       []string          `json:"DirectSites"`
	DirectIp          []string          `json:"DirectIp"`
	ProxySites        []string          `json:"ProxySites"`
	ProxyIp           []string          `json:"ProxyIp"`
	BlockSites        []string          `json:"BlockSites"`
	BlockIp           []string          `json:"BlockIp"`
	Geoipurl          string            `json:"Geoipurl,omitempty"`
	Geositeurl        string            `json:"Geositeurl,omitempty"`
	DomainStrategy    string            `json:"DomainStrategy,omitempty"`
	UseChunkFiles     *bool             `json:"useChunkFiles,omitempty"`
}

RoutingDoc is the profile as the panel writes it: the fields of the docs, in their order. The six rule lists are always written (an empty list is `[]`), the rest only when the profile has them.

func RoutingDocOf

func RoutingDocOf(e *adminv1.RoutingProfile) (RoutingDoc, bool)

RoutingDocOf is the profile of an entry (the stored JSON read back; false for an entry that does not read).

func (RoutingDoc) Canonical

func (d RoutingDoc) Canonical() string

Canonical is the JSON the panel stores and sends for the profile.

func (d RoutingDoc) Link(scheme string, onlyAdd bool) string

Link is the link of the profile for an app: scheme "happ" or "incy", `onadd` (add and turn on) or `add` (add only). Standard padded base64, as in the examples of both apps. The scheme is the caller's constant, never data.

func (RoutingDoc) WithDNS

func (d RoutingDoc) WithDNS(x RoutingDNS) RoutingDoc

WithDNS is the profile with the resolvers of a person's preset in place of its own (and without the older aliases of the address, which would contradict them); the host pins of the preset are added to the profile's, the preset's winning. The rules stay the owner's. A zero x (no preset the app can take) leaves the profile as it is.

type RoutingParsed

type RoutingParsed struct {
	Doc     RoutingDoc
	Mode    string
	Dropped []string
}

RoutingParsed is what an input gives: the profile, the mode a link said ("add", "onadd", "" for a bare profile) and the names of the fields that were left out.

func ParseRoutingInput

func ParseRoutingInput(in string) (RoutingParsed, error)

ParseRoutingInput reads what the owner pasted: an app link (`happ://routing/onadd/<base64>`, `incy://…`, `://routing/add/…`: the scheme may be anything), a bare base64 of the JSON, or the JSON itself. The errors say what is wrong with the text.

type SentHeader

type SentHeader struct {
	Name, Value string
	Base64      bool
}

SentHeader is one own header as an answer carries it.

func ResponseHeadersFor

func ResponseHeadersFor(s *adminv1.SubscriptionSettings, groupID string, format adminv1.SubFormat) []SentHeader

ResponseHeadersFor are the own headers the answer of one format carries for a person of one group, in the order of the list; when two entries of one name apply, the first wins. The caller sends them with a successful subscription answer only.

Jump to

Keyboard shortcuts

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