service

package
v0.35.6 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: GPL-3.0 Imports: 44 Imported by: 1 module, 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

Index

Constants

View Source
const (
	SessionIdentityKey     = "session_identity"
	SessionIdentityVersion = 1
)
View Source
const (
	RoleAnonymous = "anonymous"
	RoleAdmin     = "admin"
	RoleUser      = "user"
)
View Source
const (
	PermissionAll             = "*"
	PermissionManagementAdmin = "management:admin"
	PermissionClientsCreate   = "clients:create"
	PermissionClientsRead     = "clients:read"
	PermissionClientsUpdate   = "clients:update"
	PermissionClientsDelete   = "clients:delete"
	PermissionClientsStatus   = "clients:status"
	PermissionTunnelsCreate   = "tunnels:create"
	PermissionTunnelsRead     = "tunnels:read"
	PermissionTunnelsUpdate   = "tunnels:update"
	PermissionTunnelsDelete   = "tunnels:delete"
	PermissionTunnelsControl  = "tunnels:control"
	PermissionHostsCreate     = "hosts:create"
	PermissionHostsRead       = "hosts:read"
	PermissionHostsUpdate     = "hosts:update"
	PermissionHostsDelete     = "hosts:delete"
	PermissionHostsControl    = "hosts:control"
	PermissionGlobalManage    = "global:manage"
)
View Source
const MaxLaunchForm = 64 << 10

MaxLaunchForm is the longest start command form a client or tunnel keeps.

Variables

View Source
var (
	ErrClientQRCodeTextRequired  = errors.New("missing qr code text")
	ErrClientQRCodeSecretInvalid = errors.New("invalid totp secret")
	ErrClientModifyFailed        = errors.New("client modify failed")
	ErrInvalidScheduler          = errors.New("invalid scheduler")
	ErrClientVKeyDuplicate       = errors.New("client verify key duplicate")
	ErrWebUsernameDuplicate      = errors.New("client web username duplicate")
	ErrInvalidRegistration       = errors.New("invalid registration")
	ErrReservedUsername          = errors.New("reserved username")
	ErrClientNotFound            = errors.New("client not found")
	ErrVirtualClientOperation    = errors.New("operation is not supported for virtual clients")
	ErrClientOffline             = errors.New("client is offline")
	ErrServerNotRunning          = errors.New("the server is not running")
	ErrClientUpdateUnsupported   = errors.New("client version does not support remote update")
	ErrServerUpdateUnavailable   = errors.New("server update is unavailable")
	ErrConfigReloadUnavailable   = errors.New("no server runs to reload the config")
	ErrServerUpdateRunning       = errors.New("server update is already running")
	ErrGeoDataUpdateRunning      = errors.New("geodata update is already running")
	ErrRegisterKeyInvalid        = errors.New("invalid registration key")
	ErrRegisterKeyDuplicate      = errors.New("registration key duplicate")
	ErrTunnelNotFound            = errors.New("tunnel not found")
	ErrLaunchFormTooLarge        = errors.New("start command form is too large")
	ErrHostNotFound              = errors.New("host not found")
	ErrHostExists                = errors.New("host already exists")
	ErrModeRequired              = errors.New("mode is required")
	ErrTunnelModeInvalid         = errors.New("unknown tunnel mode")
	ErrPortUnavailable           = errors.New("port unavailable")
	ErrTunnelLimitExceeded       = errors.New("tunnel limit exceeded")
	ErrAdminSetupRequired        = errors.New("admin login is not set up: set web_username and web_password in nps.conf")
	ErrInvalidCredentials        = errors.New("invalid credentials")
	ErrUnauthenticated           = errors.New("unauthenticated")
	ErrForbidden                 = errors.New("forbidden")
	ErrPageNotFound              = errors.New("page not found")
)
View Source
var ErrInvalidAccessList = errors.New("invalid access list rules")

ErrInvalidAccessList is wrapped by the errors that report rejected rules of an access list; the message names the list and the lines.

View Source
var ErrPortRange = errors.New("invalid port range")

ErrPortRange is a port range submitted when adding a tunnel that cannot be expanded; the wrapping error says why.

View Source
var ErrShapingUnavailable = errors.New("shaping reload unavailable")

ErrShapingUnavailable is a shaping reload without a running server.

Functions

func AdminSetupRequired added in v0.35.1

func AdminSetupRequired(cfg *servercfg.Snapshot) bool

AdminSetupRequired reports whether web_require_password blocks the admin login: the switch is on and the username is empty, or neither a password nor a TOTP secret is set.

func DefaultRolePermissions

func DefaultRolePermissions(role string) []string

func MarshalSessionIdentity

func MarshalSessionIdentity(identity *SessionIdentity) (string, error)

func MarshalSessionIdentityWithResolver

func MarshalSessionIdentityWithResolver(identity *SessionIdentity, resolver PermissionResolver) (string, error)

func ValidAuthKey

func ValidAuthKey(configKey, md5Key string, timestamp int, nowUnix int64) bool

Types

type AccessListInput added in v0.34.9

type AccessListInput struct {
	Priority int
	Black    string
	White    string
	// RegisteredOnly additionally requires visitor addresses to be
	// registered; the global settings ignore it.
	RegisteredOnly bool
}

AccessListInput holds the source access lists of a level as entered in the web interface, one rule per line.

type AddClientInput

type AddClientInput struct {
	VKey             string
	Remark           string
	User             string
	Password         string
	Compress         bool
	CompressAlg      string
	SchedulerDown    string
	SchedulerUp      string
	Shaping          bool
	Crypt            bool
	ConfigConnAllow  bool
	RateLimit        int
	MaxConn          int
	WebUserName      string
	WebPassword      string
	WebTotpSecret    string
	MaxTunnelNum     int
	FlowLimit        int64
	TimeLimit        string
	Access           AccessListInput
	RegisterKey      string
	RegisterMaxHours int
}

type AuthService

type AuthService interface {
	Authenticate(AuthenticateInput) (*SessionIdentity, error)
	RegisterUser(RegisterUserInput) (*RegisterUserResult, error)
}

type AuthenticateInput

type AuthenticateInput struct {
	Username string
	Password string
	TOTP     string
}

type AuthorizationService

type AuthorizationService interface {
	NormalizePrincipal(Principal) Principal
	ClientScope(Principal) ClientScope
	Permissions(Principal) []string
	Allows(Principal, string) bool
	ResolveClient(Principal, int) (int, error)
	RequirePermission(Principal, string) error
	RequireAdmin(Principal) error
	RequireClient(Principal, int) error
	RequireTunnel(Principal, int) error
	RequireHost(Principal, int) error
}

type Backend

type Backend struct {
	Repository Repository
	Runtime    Runtime
}

func NewBackend added in v0.35.0

func NewBackend(db *file.DbUtils, runtime Runtime) Backend

NewBackend is the backend of the store db and of runtime, the running server; a nil runtime means none runs.

type BridgeEndpoint

type BridgeEndpoint struct {
	Type string
	Addr string
	IP   string
	Port string
}

func BestBridge

func BestBridge(cfg *servercfg.Snapshot, host string) BridgeEndpoint

type BridgeTransport

type BridgeTransport struct {
	Enabled bool
	Type    string
	IP      string
	Port    string
	Addr    string
	ALPN    string
}

type CertSuggestion added in v0.35.0

type CertSuggestion struct {
	SourceID       int    `json:"source_id"`
	SourceHost     string `json:"source_host"`
	SourceLocation string `json:"source_location"`
	CertFile       string `json:"cert_file"`
	KeyFile        string `json:"key_file"`
}

CertSuggestion is an existing certificate a domain entry could use. The files are in the form the certificate fields of the form take.

type ClientQRCodeInput

type ClientQRCodeInput struct {
	Text    string
	Account string
	Secret  string
	AppName string
}

type ClientScope

type ClientScope struct {
	All             bool
	PrimaryClientID int
	ClientIDs       []int
}

type ClientService

type ClientService interface {
	SaveLaunchForm(id int, form string) error
	Kick(id int) error
	List(ListClientsInput) ListClientsResult
	Add(AddClientInput) (int, error)
	Ping(id int, remoteAddr string) (int, error)
	Get(id int) (*model.Client, error)
	Edit(EditClientInput) error
	Clear(id int, mode string, isAdmin bool) error
	ChangeStatus(id int, status bool) error
	RequestUpdate(id int) (int, error)
	Delete(id int) error
	BuildQRCode(ClientQRCodeInput) ([]byte, error)
	// RegisterVisitorIP registers ip for the client whose registration key
	// or verify key is key, for hours, at most the client's limit.
	RegisterVisitorIP(key, ip string, hours int) (clientID int, until time.Time, err error)
}

type ClientVisibility

type ClientVisibility struct {
	IsAdmin         bool
	PrimaryClientID int
	ClientIDs       []int
}

type ConfigBundle added in v0.35.0

type ConfigBundle struct {
	Version    int             `json:"version"`
	ExportedAt time.Time       `json:"exported_at"`
	Clients    []*model.Client `json:"clients"`
	Tunnels    []*model.Tunnel `json:"tunnels"`
	Hosts      []*model.Host   `json:"hosts"`
}

ConfigBundle is an export of the stored clients, tunnels and domain entries. The entries have the form of the json store and hold the secrets it holds; their Client fields are read for the id only.

type ConfigTransferService added in v0.35.0

type ConfigTransferService interface {
	Export() ([]byte, error)
	Import(ImportConfigInput) (ImportResult, error)
}

ConfigTransferService exports and imports the stored configuration.

type DefaultAuthService

type DefaultAuthService struct {
	Resolver       PermissionResolver
	ConfigProvider func() *servercfg.Snapshot
	Backend        Backend
}

func (DefaultAuthService) Authenticate

func (s DefaultAuthService) Authenticate(input AuthenticateInput) (*SessionIdentity, error)

func (DefaultAuthService) RegisterUser

type DefaultAuthorizationService

type DefaultAuthorizationService struct {
	Resolver PermissionResolver
	Backend  Backend
}

func (DefaultAuthorizationService) Allows

func (s DefaultAuthorizationService) Allows(principal Principal, permission string) bool

func (DefaultAuthorizationService) ClientScope

func (s DefaultAuthorizationService) ClientScope(principal Principal) ClientScope

func (DefaultAuthorizationService) NormalizePrincipal

func (s DefaultAuthorizationService) NormalizePrincipal(principal Principal) Principal

func (DefaultAuthorizationService) Permissions

func (s DefaultAuthorizationService) Permissions(principal Principal) []string

func (DefaultAuthorizationService) RequireAdmin

func (s DefaultAuthorizationService) RequireAdmin(principal Principal) error

func (DefaultAuthorizationService) RequireClient

func (s DefaultAuthorizationService) RequireClient(principal Principal, clientID int) error

func (DefaultAuthorizationService) RequireHost

func (s DefaultAuthorizationService) RequireHost(principal Principal, hostID int) error

func (DefaultAuthorizationService) RequirePermission

func (s DefaultAuthorizationService) RequirePermission(principal Principal, permission string) error

func (DefaultAuthorizationService) RequireTunnel

func (s DefaultAuthorizationService) RequireTunnel(principal Principal, tunnelID int) error

func (DefaultAuthorizationService) ResolveClient

func (s DefaultAuthorizationService) ResolveClient(principal Principal, requestedClientID int) (int, error)

type DefaultClientService

type DefaultClientService struct {
	ConfigProvider func() *servercfg.Snapshot
	Backend        Backend
}

func (DefaultClientService) Add

func (s DefaultClientService) Add(input AddClientInput) (int, error)

func (DefaultClientService) BuildQRCode

func (DefaultClientService) BuildQRCode(input ClientQRCodeInput) ([]byte, error)

func (DefaultClientService) ChangeStatus

func (s DefaultClientService) ChangeStatus(id int, status bool) error

func (DefaultClientService) Clear

func (s DefaultClientService) Clear(id int, mode string, isAdmin bool) error

func (DefaultClientService) Delete

func (s DefaultClientService) Delete(id int) error

func (DefaultClientService) Edit

func (DefaultClientService) Get

func (s DefaultClientService) Get(id int) (*model.Client, error)

func (DefaultClientService) Kick added in v0.35.0

func (s DefaultClientService) Kick(id int) error

Kick ends the sessions of client id. Its configuration stays, so an npc that reconnects by itself is back after its retry delay; to keep it out, use ChangeStatus.

func (DefaultClientService) List

func (DefaultClientService) Ping

func (s DefaultClientService) Ping(id int, remoteAddr string) (int, error)

func (DefaultClientService) RegisterVisitorIP added in v0.34.9

func (s DefaultClientService) RegisterVisitorIP(key, ip string, hours int) (int, time.Time, error)

func (DefaultClientService) RequestUpdate added in v0.34.9

func (s DefaultClientService) RequestUpdate(id int) (int, error)

RequestUpdate asks the connected npc of client id to update themselves to the latest release and returns how many were asked.

func (DefaultClientService) SaveLaunchForm added in v0.35.0

func (s DefaultClientService) SaveLaunchForm(id int, form string) error

SaveLaunchForm stores the start command form of client id; empty removes it.

type DefaultConfigTransferService added in v0.35.0

type DefaultConfigTransferService struct {
	Backend Backend
}

DefaultConfigTransferService goes through the same repository and runtime calls as creating the entries from the web.

func (DefaultConfigTransferService) Export added in v0.35.0

func (s DefaultConfigTransferService) Export() ([]byte, error)

func (DefaultConfigTransferService) Import added in v0.35.0

Import adds the entries of a bundle under new ids; nothing existing is replaced. A bundle that conflicts with what exists, or with itself, is refused as a whole. Conflicts found only while adding, such as a port that cannot be bound, undo what was added so far.

type DefaultGlobalService

type DefaultGlobalService struct {
	LoginPolicy LoginPolicyService
	Backend     Backend
}

func (DefaultGlobalService) BanList

func (s DefaultGlobalService) BanList() []LoginBanRecord

func (DefaultGlobalService) CleanBans

func (s DefaultGlobalService) CleanBans()

func (DefaultGlobalService) Get

func (s DefaultGlobalService) Get() *model.Glob

func (DefaultGlobalService) Save

func (DefaultGlobalService) Unban

func (s DefaultGlobalService) Unban(key string) bool

func (DefaultGlobalService) UnbanAll

func (s DefaultGlobalService) UnbanAll()

type DefaultIndexService

type DefaultIndexService struct {
	Backend Backend
}

func (DefaultIndexService) AddHost

func (s DefaultIndexService) AddHost(input HostInput) (HostMutation, error)

func (DefaultIndexService) AddTunnel

func (s DefaultIndexService) AddTunnel(input TunnelInput) (TunnelMutation, error)

func (DefaultIndexService) AddTunnels added in v0.35.0

func (s DefaultIndexService) AddTunnels(input TunnelInput) ([]TunnelMutation, error)

AddTunnels adds the tunnels of a submitted port field. A single port, or an empty field, is AddTunnel unchanged. A range or list (tcp and udp only) opens one tunnel per port with the settings of the form, the remark extended by "-port", and the target of each: a target line naming as many ports as the field pairs with them in order, one naming a single port serves them all. Either every tunnel is added or none is.

func (DefaultIndexService) ClearHost

func (s DefaultIndexService) ClearHost(id int, mode string) error

func (DefaultIndexService) ClearTunnel

func (s DefaultIndexService) ClearTunnel(id int, mode string) error

func (DefaultIndexService) DashboardData

func (s DefaultIndexService) DashboardData(force bool) map[string]any

func (DefaultIndexService) DeleteHost

func (s DefaultIndexService) DeleteHost(id int) error

func (DefaultIndexService) DeleteTunnel

func (s DefaultIndexService) DeleteTunnel(id int) error

func (DefaultIndexService) EditHost

func (s DefaultIndexService) EditHost(input HostInput) (HostMutation, error)

func (DefaultIndexService) EditTunnel

func (s DefaultIndexService) EditTunnel(input TunnelInput) (TunnelMutation, error)

func (DefaultIndexService) GetHost

func (s DefaultIndexService) GetHost(id int) (*model.Host, error)

func (DefaultIndexService) GetTunnel

func (s DefaultIndexService) GetTunnel(id int) (*model.Tunnel, error)

func (DefaultIndexService) ListHosts

func (s DefaultIndexService) ListHosts(input HostListInput) ([]*model.Host, int)

func (DefaultIndexService) ListTunnels

func (s DefaultIndexService) ListTunnels(input TunnelListInput) ([]*model.Tunnel, int)

func (DefaultIndexService) SaveTunnelLaunchForm added in v0.35.0

func (s DefaultIndexService) SaveTunnelLaunchForm(id int, form string) error

SaveTunnelLaunchForm stores the start command form of a point-to-point tunnel; empty removes it.

func (DefaultIndexService) ServiceAvailable added in v0.35.0

func (s DefaultIndexService) ServiceAvailable(client int, target string) bool

ServiceAvailable reports whether every target in target, one per line, that names a service is reported now by client; any other target is available.

func (DefaultIndexService) StartHost

func (s DefaultIndexService) StartHost(id int, mode string) error

func (DefaultIndexService) StartTunnel

func (s DefaultIndexService) StartTunnel(id int, mode string) error

func (DefaultIndexService) StopHost

func (s DefaultIndexService) StopHost(id int, mode string) error

func (DefaultIndexService) StopTunnel

func (s DefaultIndexService) StopTunnel(id int, mode string) error

func (DefaultIndexService) SuggestCert added in v0.35.0

func (s DefaultIndexService) SuggestCert(host string, excludeID, clientID int) *CertSuggestion

SuggestCert returns the certificate FindCertByHost's choice would give the name host, among entries with certificate files other than excludeID; with a clientID other than 0, among the entries of that client. Nil means none.

type DefaultLoginPolicy

type DefaultLoginPolicy struct {
	ConfigProvider func() *servercfg.Snapshot
	// contains filtered or unexported fields
}

DefaultLoginPolicy bans a key for login_ban_time seconds after each failure, and for login_ip_ban_time or login_user_ban_time seconds once it failed login_max_fail_times times within that period.

func NewDefaultLoginPolicy

func NewDefaultLoginPolicy(provider func() *servercfg.Snapshot) *DefaultLoginPolicy

func SharedLoginPolicy

func SharedLoginPolicy() *DefaultLoginPolicy

func (*DefaultLoginPolicy) AllowsIP added in v0.35.0

func (s *DefaultLoginPolicy) AllowsIP(ip string) bool

func (*DefaultLoginPolicy) BanList

func (s *DefaultLoginPolicy) BanList() []LoginBanRecord

func (*DefaultLoginPolicy) Clean

func (s *DefaultLoginPolicy) Clean()

func (*DefaultLoginPolicy) ClearUserFailures added in v0.35.0

func (s *DefaultLoginPolicy) ClearUserFailures(username string)

func (*DefaultLoginPolicy) IsIPBanned

func (s *DefaultLoginPolicy) IsIPBanned(ip string) bool

func (*DefaultLoginPolicy) IsUserBanned

func (s *DefaultLoginPolicy) IsUserBanned(username string) bool

func (*DefaultLoginPolicy) RecordIPFailure added in v0.35.0

func (s *DefaultLoginPolicy) RecordIPFailure(ip string)

func (*DefaultLoginPolicy) RecordUserFailure added in v0.35.0

func (s *DefaultLoginPolicy) RecordUserFailure(username, ip string)

func (*DefaultLoginPolicy) RemoveAllBans

func (s *DefaultLoginPolicy) RemoveAllBans()

func (*DefaultLoginPolicy) RemoveBan

func (s *DefaultLoginPolicy) RemoveBan(key string) bool

RemoveBan lifts the ban and forgets the failures of an address, an IPv6 prefix or a user name.

func (*DefaultLoginPolicy) Settings

type DefaultPageService

type DefaultPageService struct {
	Clients ClientService
	Globals GlobalService
	Index   IndexService
	System  SystemService
}

func (DefaultPageService) Build

type DefaultSystemService

type DefaultSystemService struct {
	Runtime Runtime
}

DefaultSystemService serves the system information of Runtime, the running server; a nil Runtime runs nothing and cannot be updated.

func (DefaultSystemService) BridgeDisplay

func (DefaultSystemService) BridgeDisplay(cfg *servercfg.Snapshot, host string) BridgeDisplay

func (DefaultSystemService) GeoDataStatus added in v0.34.9

func (DefaultSystemService) GeoDataStatus() GeoDataStatus

func (DefaultSystemService) Info

func (DefaultSystemService) RegisterManagementAccess

func (DefaultSystemService) RegisterManagementAccess(remoteAddr string, clientIDs []int, isAdmin bool)

func (DefaultSystemService) ReloadConfig added in v0.35.0

func (s DefaultSystemService) ReloadConfig() servercfg.Report

func (DefaultSystemService) ReloadShaping added in v0.35.5

func (s DefaultSystemService) ReloadShaping(ctx context.Context) (map[string]any, error)

func (DefaultSystemService) UpdateGeoData added in v0.34.9

func (s DefaultSystemService) UpdateGeoData(name string) (GeoDataStatus, error)

func (DefaultSystemService) UpdateServer added in v0.34.9

func (s DefaultSystemService) UpdateServer() (string, error)

type EditClientInput

type EditClientInput struct {
	ID                      int
	ReservedAdminUsername   string
	VKey                    string
	Remark                  string
	User                    string
	Password                string
	RateLimit               int
	MaxConn                 int
	WebUserName             string
	WebPassword             string
	WebTotpSecret           string
	MaxTunnelNum            int
	FlowLimit               int64
	TimeLimit               string
	Access                  AccessListInput
	RegisterKey             string
	RegisterMaxHours        int
	IsAdmin                 bool
	AllowUserChangeUsername bool
	Compress                bool
	CompressAlg             string
	SchedulerDown           string
	SchedulerUp             string
	Shaping                 bool
	// Crypt is the new setting of the encryption switch; nil keeps the stored one.
	Crypt           *bool
	ConfigConnAllow bool
	ResetFlow       bool
}

type GeoDataStatus added in v0.34.9

type GeoDataStatus struct {
	Files []GeoFileStatus
}

GeoDataStatus describes the geodata files of the access lists.

type GeoFileStatus added in v0.34.9

type GeoFileStatus struct {
	Name string
	Path string
	// Version is the release the file comes from, "" when unknown.
	Version string
	Exists  bool
	Size    int64
	ModTime string
}

GeoFileStatus describes one geodata file.

type GlobalService

type GlobalService interface {
	Save(SaveGlobalInput) error
	Get() *model.Glob
	BanList() []LoginBanRecord
	Unban(key string) bool
	UnbanAll()
	CleanBans()
}

type HostInput added in v0.35.0

type HostInput struct {
	ID             int
	ClientID       int
	IsAdmin        bool
	AllowUserLocal bool
	ResetFlow      bool
	Access         AccessListInput
	// Host holds the values of model.HostSettings as submitted.
	Host *model.Host
}

HostInput is a submitted host, as TunnelInput is a tunnel.

type HostListInput

type HostListInput struct {
	Offset   int
	Limit    int
	ClientID int
	Search   string
	Sort     string
	Order    string
}

type HostMutation

type HostMutation struct {
	ID       int
	ClientID int
}

type ImportConfigInput added in v0.35.0

type ImportConfigInput struct {
	Data []byte
	// ReservedAdminUsername cannot be a client's web login.
	ReservedAdminUsername string
}

ImportConfigInput is an import request.

type ImportResult added in v0.35.0

type ImportResult struct {
	Clients, Tunnels, Hosts int
}

ImportResult counts what an import added.

type IndexService

type IndexService interface {
	SaveTunnelLaunchForm(id int, form string) error
	DashboardData(force bool) map[string]any
	SuggestCert(host string, excludeID, clientID int) *CertSuggestion
	ListTunnels(TunnelListInput) ([]*model.Tunnel, int)
	ServiceAvailable(client int, target string) bool
	AddTunnel(TunnelInput) (TunnelMutation, error)
	AddTunnels(TunnelInput) ([]TunnelMutation, error)
	GetTunnel(id int) (*model.Tunnel, error)
	EditTunnel(TunnelInput) (TunnelMutation, error)
	StopTunnel(id int, mode string) error
	DeleteTunnel(id int) error
	StartTunnel(id int, mode string) error
	ClearTunnel(id int, mode string) error
	ListHosts(HostListInput) ([]*model.Host, int)
	GetHost(id int) (*model.Host, error)
	DeleteHost(id int) error
	StartHost(id int, mode string) error
	StopHost(id int, mode string) error
	ClearHost(id int, mode string) error
	AddHost(HostInput) (HostMutation, error)
	EditHost(HostInput) (HostMutation, error)
}

type ListClientsInput

type ListClientsInput struct {
	Offset     int
	Limit      int
	Search     string
	Sort       string
	Order      string
	Host       string
	Visibility ClientVisibility
}

type ListClientsResult

type ListClientsResult struct {
	Rows       []*model.Client
	Total      int
	BridgeType string
	BridgeAddr string
	BridgeIP   string
	BridgePort int
}

type LoginBanRecord

type LoginBanRecord struct {
	Key           string `json:"key"`
	FailTimes     int    `json:"fail_times"`
	LastLoginTime string `json:"last_login_time"`
	IsBanned      bool   `json:"is_banned"`
	BanType       string `json:"ban_type"`
}

type LoginPolicyService

type LoginPolicyService interface {
	Settings() LoginPolicySettings
	// AllowsIP applies login_acl_mode and login_acl_rules.
	AllowsIP(ip string) bool
	IsIPBanned(ip string) bool
	IsUserBanned(username string) bool
	RecordIPFailure(ip string)
	// RecordUserFailure counts a failure of username from the address ip,
	// which names the source when it leads to a ban.
	RecordUserFailure(username, ip string)
	// ClearUserFailures forgets the failures of a user who logged in.
	ClearUserFailures(username string)
	RemoveBan(key string) bool
	RemoveAllBans()
	// Clean frees the memory of expired failures and bans.
	Clean()
	BanList() []LoginBanRecord
}

LoginPolicyService counts failed logins per client address and per user name and bans those that fail too often.

type LoginPolicySettings

type LoginPolicySettings struct {
	BanTime      int64
	IPBanTime    int64
	UserBanTime  int64
	MaxFailTimes int
	MaxLoginBody int64
	MaxSkew      int64
}

func (LoginPolicySettings) LoginDelayMillis

func (s LoginPolicySettings) LoginDelayMillis() int64

type PageBuildInput

type PageBuildInput struct {
	Config     *servercfg.Snapshot
	Controller string
	Action     string
	Host       string
	IsAdmin    bool
	Username   string
	Params     map[string]string
}

type PageBuildResult

type PageBuildResult struct {
	Data map[string]any
}

type PageService

type PageService interface {
	Build(PageBuildInput) (PageBuildResult, error)
}

type PermissionResolver

type PermissionResolver interface {
	NormalizePrincipal(Principal) Principal
	NormalizeIdentity(*SessionIdentity) *SessionIdentity
	KnownRoles() []string
	KnownPermissions() []string
	PermissionCatalog() map[string][]string
}

func DefaultPermissionResolver

func DefaultPermissionResolver() PermissionResolver

type PortError added in v0.35.0

type PortError struct {
	Port int
	Err  error
}

PortError names the port of a batch whose check failed.

func (*PortError) Error added in v0.35.0

func (e *PortError) Error() string

func (*PortError) Unwrap added in v0.35.0

func (e *PortError) Unwrap() error

type Principal

type Principal struct {
	Kind          string
	SubjectID     string
	Username      string
	ClientIDs     []int
	Roles         []string
	Permissions   []string
	Attributes    map[string]string
	Authenticated bool
	IsAdmin       bool
}

type RegisterUserInput

type RegisterUserInput struct {
	Username string
	Password string
}

type RegisterUserResult

type RegisterUserResult struct {
	SubjectID string
	Username  string
	ClientIDs []int
}

type Repository

type Repository interface {
	RangeClients(func(*model.Client) bool)
	RangeTunnels(func(*model.Tunnel) bool)
	RangeHosts(func(*model.Host) bool)
	ListVisibleClients(ListClientsInput) ([]*model.Client, int)
	NextClientID() int
	NextTunnelID() int
	NextHostID() int
	CreateClient(*model.Client) error
	GetClient(int) (*model.Client, error)
	SaveClient(*model.Client) error
	PersistClients() error
	PersistGlobal() error
	DeleteClient(int) error
	VerifyUserName(string, int) bool
	VerifyVKey(string, int) bool
	ReplaceClientVKeyIndex(oldKey, newKey string, clientID int)
	CreateTunnel(*model.Tunnel) error
	GetTunnel(int) (*model.Tunnel, error)
	SaveTunnel(*model.Tunnel) error
	DeleteTunnelRecord(int) error
	CreateHost(*model.Host) error
	GetHost(int) (*model.Host, error)
	SaveHost(*model.Host, string) error
	FindReusableCert(host string, excludeID, clientID int) (*model.Host, error)
	PersistHosts() error
	DeleteHostRecord(int) error
	HostExists(*model.Host) bool
	GetGlobal() *model.Glob
	SaveGlobal(*model.Glob) error
	// ClientEntryCount is the number of tunnels and hosts of client.
	ClientEntryCount(*model.Client) int
	// GlobalDenied reports whether the global access lists deny addr, and
	// logs a denial; what names the listener in the log.
	GlobalDenied(addr, what string) bool
	ClientOwnsTunnel(int, int) bool
	ClientOwnsHost(int, int) bool
}

type Runtime

type Runtime interface {
	DashboardData(bool) map[string]any
	ListClients(offset, limit int, search, sort, order string, clientID int) ([]*model.Client, int)
	PingClient(int, string) int
	DisconnectClient(int)
	ClientConnected(int) bool
	// ClientLink describes how a client's core sessions are carried now;
	// nil without one.
	ClientLink(int) *model.ClientLink
	RequestClientUpdate(int) (int, error)
	VirtualServices() []bridge.VirtualService
	DeleteClientResources(int)
	GenerateTunnelPort(*model.Tunnel) int
	TunnelPortAvailable(*model.Tunnel) bool
	ListTunnels(offset, limit int, tunnelType string, clientID int, search, sort, order string) ([]*model.Tunnel, int)
	AddTunnel(*model.Tunnel) error
	StopTunnel(int) error
	StartTunnel(int) error
	DeleteTunnel(int) error
	ListHosts(offset, limit, clientID int, search, sort, order string) ([]*model.Host, int)
	RemoveHostCache(int)
	TunnelRunning(int) bool
	// CanUpdateSelf reports whether the server may be updated from the web.
	CanUpdateSelf() bool
	// UpdateSelf updates the server to the latest release and restarts it.
	UpdateSelf() (string, error)
	// ReloadConfig reloads the config file and reports what took effect.
	ReloadConfig() servercfg.Report
	// ReloadShaping fetches or reads the shaping bundle now and returns the
	// state of its source for the dashboard.
	ReloadShaping(context.Context) (map[string]any, error)
}

type SaveGlobalInput

type SaveGlobalInput struct {
	MaxConn int
	Access  AccessListInput
	// RateLimit limits all forwarded traffic together, in KB/s; 0 means
	// unlimited.
	RateLimit int
}

type Services

type Services struct {
	System      SystemService
	Permissions PermissionResolver
	Auth        AuthService
	Authz       AuthorizationService
	LoginPolicy LoginPolicyService
	Clients     ClientService
	Globals     GlobalService
	Index       IndexService
	Pages       PageService
	Config      ConfigTransferService
	// Repository is the store the services act on.
	Repository Repository
	// Runtime is the running server, or one that runs nothing.
	Runtime Runtime
}

Services groups the default application services behind replaceable interfaces. Swapping framework or storage backends should not require transport-layer rewrites.

func New

func New(db *file.DbUtils, runtime Runtime) Services

New returns the services of the store db and of runtime, the running server; a nil runtime means none runs.

type SessionIdentity

type SessionIdentity struct {
	Version       int               `json:"version"`
	Kind          string            `json:"kind,omitempty"`
	Provider      string            `json:"provider,omitempty"`
	SubjectID     string            `json:"subject_id,omitempty"`
	Username      string            `json:"username,omitempty"`
	ClientIDs     []int             `json:"client_ids,omitempty"`
	Roles         []string          `json:"roles,omitempty"`
	Permissions   []string          `json:"permissions,omitempty"`
	Attributes    map[string]string `json:"attributes,omitempty"`
	Authenticated bool              `json:"authenticated"`
	IsAdmin       bool              `json:"is_admin"`
}

func AutoAdminIdentity

func AutoAdminIdentity(cfg *servercfg.Snapshot) (*SessionIdentity, bool)

func NormalizeSessionIdentityWithResolver

func NormalizeSessionIdentityWithResolver(identity *SessionIdentity, resolver PermissionResolver) *SessionIdentity

func ParseSessionIdentity

func ParseSessionIdentity(raw string) (*SessionIdentity, error)

func ParseSessionIdentityWithResolver

func ParseSessionIdentityWithResolver(raw string, resolver PermissionResolver) (*SessionIdentity, error)

func (*SessionIdentity) Normalize

func (identity *SessionIdentity) Normalize() *SessionIdentity

type StaticPermissionResolver

type StaticPermissionResolver struct{}

func (StaticPermissionResolver) KnownPermissions

func (StaticPermissionResolver) KnownPermissions() []string

func (StaticPermissionResolver) KnownRoles

func (StaticPermissionResolver) KnownRoles() []string

func (StaticPermissionResolver) NormalizeIdentity

func (r StaticPermissionResolver) NormalizeIdentity(identity *SessionIdentity) *SessionIdentity

func (StaticPermissionResolver) NormalizePrincipal

func (StaticPermissionResolver) NormalizePrincipal(principal Principal) Principal

func (StaticPermissionResolver) PermissionCatalog

func (StaticPermissionResolver) PermissionCatalog() map[string][]string

type SystemInfo

type SystemInfo struct {
	Version string
	Year    int
	// CanUpdate tells whether the server can update itself from the web;
	// the update checks for a newer release when it runs.
	CanUpdate bool
	// UpdateAvailable tells that a newer release is known already.
	UpdateAvailable bool
}

type SystemService

type SystemService interface {
	Info() SystemInfo
	BridgeDisplay(*servercfg.Snapshot, string) BridgeDisplay
	// RegisterManagementAccess registers the address of a web login for the
	// clients the user manages, or every client for an administrator.
	RegisterManagementAccess(remoteAddr string, clientIDs []int, isAdmin bool)
	// UpdateServer updates the server to the latest release and restarts it
	// shortly. It returns the version updated to, or "" when the running
	// version is the latest.
	UpdateServer() (string, error)
	// GeoDataStatus describes the geodata files of the access lists.
	GeoDataStatus() GeoDataStatus
	// UpdateGeoData downloads the latest release of the geodata file called
	// name, geoip or geosite, or of geoip and the files present when name is
	// empty, and applies it.
	UpdateGeoData(name string) (GeoDataStatus, error)
	// ReloadConfig reloads the config file into the running server and
	// reports what took effect, what needs a restart and what failed.
	ReloadConfig() servercfg.Report
	// ReloadShaping fetches or reads the shaping bundle now and returns the
	// state of its source after it; the error is that of the reload.
	ReloadShaping(context.Context) (map[string]any, error)
}

type TunnelInput added in v0.35.0

type TunnelInput struct {
	ID             int
	ClientID       int
	IsAdmin        bool
	AllowUserLocal bool
	ResetFlow      bool
	Access         AccessListInput
	// PortSpec is the port field as submitted when adding; a range such as
	// 8000-8100,9000 opens one tunnel per port (AddTunnels). Empty or a
	// plain value is the single port Tunnel.Port holds.
	PortSpec string
	// PortRangeMax limits the ports one PortSpec may expand to; 0 for no limit.
	PortRangeMax int
	// Tunnel holds the values of model.TunnelSettings as submitted.
	Tunnel *model.Tunnel
}

TunnelInput is a submitted tunnel. ID and ResetFlow are only read when an existing tunnel is edited.

type TunnelListInput

type TunnelListInput struct {
	Offset   int
	Limit    int
	Type     string
	ClientID int
	Search   string
	Sort     string
	Order    string
}

type TunnelMutation

type TunnelMutation struct {
	ID       int
	ClientID int
	Mode     string
}

Jump to

Keyboard shortcuts

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