service

package
v1.5.11 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2026 License: GPL-3.0 Imports: 72 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AuditSeverityInfo = "info"
	AuditSeverityWarn = "warn"
)
View Source
const (
	// FailoverType is the panel/DB outbound type for an auto-failover group. It
	// is transformed to a sing-box "selector" at the core-assembly seam.
	FailoverType = "failover"
	// DirectTag is the conventional tag of the seeded direct outbound used as
	// the all-down fallback.
	DirectTag = "direct"
	// DefaultProbeTarget is the out-of-the-box HTTP liveness-probe target.
	DefaultProbeTarget = "https://www.gstatic.com/generate_204"
	// DefaultInterval is the default per-group probe interval.
	DefaultInterval = 30 * time.Second
	// MinInterval is the lowest accepted probe interval.
	MinInterval = 5 * time.Second
	// DefaultHysteresis is the default consecutive-healthy-sample count required
	// before failing back to a higher-priority member.
	DefaultHysteresis = 2
)

Failover group shared constants - the single source of truth referenced by the assembler, validation, the failover manager and the frontend contract.

View Source
const (
	ObservabilityBucket2s  ObservabilityBucket = "2s"
	ObservabilityBucket30s ObservabilityBucket = "30s"
	ObservabilityBucket1m  ObservabilityBucket = "1m"
	ObservabilityBucket5m  ObservabilityBucket = "5m"

	ObservabilityMetricCPU    ObservabilityMetric = "cpu"
	ObservabilityMetricRAM    ObservabilityMetric = "ram"
	ObservabilityMetricNetIn  ObservabilityMetric = "net_in"
	ObservabilityMetricNetOut ObservabilityMetric = "net_out"
)
View Source
const (
	TelegramBackupTriggerManual    = "manual"
	TelegramBackupTriggerScheduled = "scheduled"
)
View Source
const (
	TelegramBackupMagic           = "SUI-TGBKP\x00"
	TelegramBackupEnvelopeVersion = byte(1)
	TelegramBackupKDFArgon2ID     = byte(1)
)
View Source
const SessionRegenerateKey = "__sui_session_regenerate__"

SessionRegenerateKey is a session value the login flow sets to ask the session store to mint a fresh session ID on the next Save, preventing session fixation (the pre-auth CSRF session would otherwise keep its ID after authentication). It lives here so both the api login handler and the web session store share a single source of truth without an import cycle (web imports api).

View Source
const StoredSecretMarker = "••• stored •••"

#nosec G101 -- UI placeholder text shown in place of a stored secret, not a credential.

Variables

View Source
var (
	ErrTelegramBackupDecryptionFailed = errors.New("decryption_failed")
	ErrTelegramBackupInvalidEnvelope  = errors.New("invalid_backup_envelope")
)
View Source
var AuditSyncForTest bool
View Source
var LastUpdate int64

LastUpdate is kept as a compatibility mirror for older in-package tests and integrations. New code should use the injected Runtime last-update store (Runtime.updates) via the ConfigService setLastUpdate/getLastUpdate methods.

Deprecated: use the injected Runtime last-update store.

Functions

func AuditDroppedTotal

func AuditDroppedTotal() uint64

func BuildTelegramBackupEnvelope

func BuildTelegramBackupEnvelope(plaintext []byte, passphrase []byte) ([]byte, error)

Backup envelope layout, fixed for version 1:

magic          10 bytes  "SUI-TGBKP\x00"
version         1 byte   currently 0x01
kdf-id          1 byte   0x01 = Argon2id
kdf-params     16 bytes  for Argon2id:
                         uint32 memoryKiB, uint32 iterations,
                         uint8 parallelism, 7 reserved zero bytes
salt           16 bytes  random per envelope
nonce          12 bytes  AES-GCM nonce, random per envelope
ciphertext+tag  N bytes  AES-256-GCM output

AES-GCM authenticates the whole header through nonce as AAD.

func CheckPendingUpdate added in v1.5.9

func CheckPendingUpdate(execPath string) bool

CheckPendingUpdate runs at startup before the marker is cleared: it counts how many times a freshly-applied binary has failed to reach a clean boot and, past the threshold, restores the backup so a verified-but-unbootable release cannot brick the panel (SR-012). Returns true if a rollback was performed.

func ClearPendingUpdate added in v1.5.9

func ClearPendingUpdate(execPath string)

ClearPendingUpdate removes the pending-update marker. The freshly-booted new binary calls this once it has started successfully, so a clean boot does not trigger a rollback.

func ContextWithTelegramBackupActor

func ContextWithTelegramBackupActor(ctx context.Context, actor string) context.Context

func DirectFallbackTag added in v1.5.9

func DirectFallbackTag(tx *gorm.DB) string

DirectFallbackTag returns the tag of a direct-type outbound to use as the all-down fallback, preferring the conventional "direct" tag; "" when none.

func EncryptTelegramBackup

func EncryptTelegramBackup(plain []byte) ([]byte, []byte, error)

func EnsureFailoverSchema added in v1.5.9

func EnsureFailoverSchema(db *gorm.DB) error

EnsureFailoverSchema creates the observability-only failover_state table. It is non-authoritative (sing-box CacheFile is the stickiness authority); losing it never affects failover correctness, only post-restart UI history.

func FailoverLiveSnapshot added in v1.5.10

func FailoverLiveSnapshot() map[string]FailoverStatusEntry

FailoverLiveSnapshot returns the per-group live status, sorted by tag for a deterministic payload.

func IsTelegramBackupEnvelope

func IsTelegramBackupEnvelope(data []byte) bool

func IsValidObservabilityBucket

func IsValidObservabilityBucket(bucket ObservabilityBucket) bool

func IsValidObservabilityMetric

func IsValidObservabilityMetric(metric ObservabilityMetric) bool

func NewPaidSubHTTPClient added in v1.5.7

func NewPaidSubHTTPClient(timeout time.Duration) (*http.Client, error)

NewPaidSubHTTPClient builds the HTTP client the paid-subscriptions bot uses, honoring its OWN transport config (independent from the admin notifier): either its own proxy (paidSubProxy*) or a sing-box outbound (paidSubOutboundTag). The longer timeout accommodates getUpdates long-polling.

func OpenTelegramBackupEnvelope

func OpenTelegramBackupEnvelope(envelope []byte, passphrase []byte) ([]byte, error)

func ParseTelegramReportCron

func ParseTelegramReportCron(spec string) (cron.Schedule, error)

func PruneFailoverLiveStatus added in v1.5.10

func PruneFailoverLiveStatus(keep []string)

PruneFailoverLiveStatus drops live entries for groups not in keep, so the snapshot stays bounded as failover groups are deleted. keep=nil clears all.

func RecordListenFallbackAudit

func RecordListenFallbackAudit(component string, requestedAddr string, fallbackAddr string, bindErr error) error

func RegisterSubscriptionCacheInvalidator added in v1.5.10

func RegisterSubscriptionCacheInvalidator(fn func())

func RegisterWSTokenInvalidationHook

func RegisterWSTokenInvalidationHook(name string, fn func() int)

func ReplaceDefaultRuntimeForTest

func ReplaceDefaultRuntimeForTest(runtime *Runtime) func()

func RestoreBackup added in v1.5.9

func RestoreBackup(execPath string) error

RestoreBackup restores <execPath>.bak over execPath (rollback, SR-012).

func SetDefaultRuntime

func SetDefaultRuntime(runtime *Runtime)

func SetFailoverLiveStatus added in v1.5.10

func SetFailoverLiveStatus(entry FailoverStatusEntry)

SetFailoverLiveStatus records one failover group's current live status.

func StopAuditWriter

func StopAuditWriter(ctx context.Context) error

func StopRestartManager

func StopRestartManager()

func StopTelegramNotifier

func StopTelegramNotifier(ctx context.Context) error

func StopTokenUseDebouncer

func StopTokenUseDebouncer(ctx context.Context) error

func ValidateIssuableIP added in v1.5.8

func ValidateIssuableIP(raw string) error

ValidateIssuableIP is the exported wrapper around the package-private validator, kept for callers outside the service package.

func WriteFailoverMemberStates added in v1.5.9

func WriteFailoverMemberStates(db *gorm.DB, states []FailoverMemberState) error

WriteFailoverMemberStates upserts the per-member health for a group. A nil db (e.g. in unit tests without an initialized database) is a no-op.

Types

type AuditEvent

type AuditEvent struct {
	Actor     string
	Event     string
	Resource  string
	Severity  string
	IP        string
	UserAgent string
	Details   map[string]any
}

type AuditService

type AuditService struct {
	Runtime *Runtime
}

func (*AuditService) List

func (s *AuditService) List(limit int) ([]model.AuditEvent, error)

func (*AuditService) ListPage

func (s *AuditService) ListPage(cursor uint64, limit int) ([]model.AuditEvent, uint64, error)

func (*AuditService) ListPageFiltered

func (s *AuditService) ListPageFiltered(cursor uint64, limit int, event string, severity string, since int64, until int64) ([]model.AuditEvent, uint64, error)

func (*AuditService) Prune

func (s *AuditService) Prune(retentionDays int) error

func (*AuditService) Record

func (s *AuditService) Record(event AuditEvent) error

type ClientService

type ClientService struct {
	Runtime *Runtime
}

func (*ClientService) DepleteClients

func (s *ClientService) DepleteClients() (inboundIds []uint, err error)

func (*ClientService) Get

func (s *ClientService) Get(id string) (*[]model.Client, error)

func (*ClientService) GetAll

func (s *ClientService) GetAll() (*[]model.Client, error)

func (*ClientService) ResetClients

func (s *ClientService) ResetClients(tx *gorm.DB, dt int64) ([]uint, error)

func (*ClientService) RotateSubSecret

func (s *ClientService) RotateSubSecret(id string) (string, error)

func (*ClientService) Save

func (s *ClientService) Save(tx *gorm.DB, act string, data json.RawMessage, hostname string) ([]uint, error)

func (*ClientService) UpdateClientsOnInboundAdd

func (s *ClientService) UpdateClientsOnInboundAdd(tx *gorm.DB, initIds string, inboundId uint, hostname string) error

func (*ClientService) UpdateClientsOnInboundDelete

func (s *ClientService) UpdateClientsOnInboundDelete(tx *gorm.DB, id uint, tag string) error

func (*ClientService) UpdateLinksByInboundChange

func (s *ClientService) UpdateLinksByInboundChange(tx *gorm.DB, inbounds *[]model.Inbound, hostname string, oldTag string) error

type ConfigService

func NewConfigService

func NewConfigService(core *core.Core) *ConfigService

func NewConfigServiceWithRuntime

func NewConfigServiceWithRuntime(runtime *Runtime) *ConfigService

func (*ConfigService) CheckChanges

func (s *ConfigService) CheckChanges(lu string) (bool, error)

func (*ConfigService) CheckOutbound

func (s *ConfigService) CheckOutbound(tag string, link string) core.CheckOutboundResult

func (*ConfigService) CheckOutboundWithContext

func (s *ConfigService) CheckOutboundWithContext(ctx context.Context, tag string, link string) core.CheckOutboundResult

func (*ConfigService) FailoverStatus added in v1.5.9

func (s *ConfigService) FailoverStatus() ([]FailoverStatusEntry, error)

FailoverStatus reports every failover group's live active member (authoritative, read from the running core via GroupNow) plus per-member health from the crash-safe failover_state table (so the answer is meaningful immediately after a restart, before the first new probe).

func (*ConfigService) GetChanges

func (s *ConfigService) GetChanges(actor string, chngKey string, count string) []model.Changes

func (*ConfigService) GetConfig

func (s *ConfigService) GetConfig(data string) (*[]byte, error)

func (*ConfigService) IsCoreRunning

func (s *ConfigService) IsCoreRunning() bool

func (*ConfigService) RestartCore

func (s *ConfigService) RestartCore() error

RestartCore is invoked from user actions; it bypasses the cooldown so the caller observes the true start status. It waits for any in-flight core operation instead of being silently skipped.

func (*ConfigService) Save

func (s *ConfigService) Save(obj string, act string, data json.RawMessage, initUsers string, loginUser string, hostname string) (objs []string, err error)

func (*ConfigService) StartCore

func (s *ConfigService) StartCore() error

StartCore is the cron-friendly variant: it respects the cooldown so a failing core does not get hammered every 5 seconds.

func (*ConfigService) StopCore

func (s *ConfigService) StopCore() error

type CoreProvider

type CoreProvider interface {
	Core() *core.Core
}

type CoreProviderFunc

type CoreProviderFunc func() *core.Core

func (CoreProviderFunc) Core

func (f CoreProviderFunc) Core() *core.Core

type CoreSample

type CoreSample struct {
	DateTime int64                  `json:"dateTime"`
	Core     map[string]interface{} `json:"core"`
}

func AggregateCoreSamples

func AggregateCoreSamples(samples []CoreSample, dateTime int64) CoreSample

type DeleteUserResult added in v1.5.6

type DeleteUserResult struct {
	User              model.User
	DeletedTokenCount int64
}

type DoctorClientRequest added in v1.5.8

type DoctorClientRequest struct {
	ClientID uint   `json:"clientId"`
	Target   string `json:"target,omitempty"`
}

type DoctorItem added in v1.5.8

type DoctorItem struct {
	ID       string         `json:"id"`
	Title    string         `json:"title"`
	Severity DoctorSeverity `json:"severity"`
	Message  string         `json:"message"`
	Action   string         `json:"action,omitempty"`
	Details  any            `json:"details,omitempty"`
}

type DoctorReport added in v1.5.8

type DoctorReport struct {
	Status     DoctorSeverity `json:"status"`
	Summary    string         `json:"summary"`
	Items      []DoctorItem   `json:"items"`
	RanAt      int64          `json:"ranAt"`
	DurationMS int64          `json:"durationMs"`
}

type DoctorService added in v1.5.8

type DoctorService struct {
	Runtime *Runtime
}

func (*DoctorService) DiagnoseClient added in v1.5.8

func (s *DoctorService) DiagnoseClient(req DoctorClientRequest, hostname string) (DoctorReport, error)

func (*DoctorService) Run added in v1.5.8

func (s *DoctorService) Run(hostname string) DoctorReport

type DoctorSeverity added in v1.5.8

type DoctorSeverity string
const (
	DoctorSeverityOK    DoctorSeverity = "ok"
	DoctorSeverityWarn  DoctorSeverity = "warn"
	DoctorSeverityError DoctorSeverity = "error"
)

type EndpointService

type EndpointService struct {
	WarpService
	Runtime *Runtime
}

func (*EndpointService) GetAll

func (o *EndpointService) GetAll() (*[]map[string]interface{}, error)

func (*EndpointService) GetAllConfig

func (o *EndpointService) GetAllConfig(db *gorm.DB) ([]json.RawMessage, error)

func (*EndpointService) RemoveEndpointsFromCore added in v1.5.8

func (s *EndpointService) RemoveEndpointsFromCore(tags []string) error

RemoveEndpointsFromCore removes the given endpoint tags from the running core. Missing tags are tolerated so removals stay idempotent.

func (*EndpointService) RestartEndpoints added in v1.5.8

func (s *EndpointService) RestartEndpoints(tx *gorm.DB, ids []uint) error

RestartEndpoints replaces the given endpoints inside the running core (remove by tag, then add the committed definition).

func (*EndpointService) Save

func (s *EndpointService) Save(tx *gorm.DB, act string, data json.RawMessage) (*entityCoreChange, error)

type FailoverDecision added in v1.5.9

type FailoverDecision struct {
	Target       string
	ShouldSwitch bool
	AllDown      bool
	Reason       string // priority | failover | failback | sticky | all_down_direct | all_down_hold
}

FailoverDecision is the pure output: which member should be active and why.

func SelectFailoverMember added in v1.5.9

func SelectFailoverMember(in FailoverDecisionInput) FailoverDecision

SelectFailoverMember decides the active member for a failover group from a health snapshot. It is a pure function (no I/O, no clock, no core) so it is exhaustively table-testable. Policy: strict priority; failover-down is immediate (one failed probe = a 15s timeout); failback-up is gated by Hysteresis consecutive healthy samples; sticky otherwise; all-down routes to DirectFallback when set, else holds the senior member.

type FailoverDecisionInput added in v1.5.9

type FailoverDecisionInput struct {
	Members        []string                // ordered priority; index 0 = primary
	Health         map[string]MemberHealth // keyed by member tag (priority members only)
	Current        string                  // current active member (= GroupNow()); "" if unknown
	Hysteresis     int                     // >= 1; consecutive-up samples required for failback
	DirectFallback string                  // direct outbound tag used when all members are down; "" if none
}

FailoverDecisionInput is the pure input to the failover selection decision.

type FailoverGroupConfig added in v1.5.9

type FailoverGroupConfig struct {
	Tag         string
	Members     []string
	ProbeTarget string
	Interval    time.Duration
	Hysteresis  int
	Enabled     bool
}

FailoverGroupConfig is the manager-facing view of a failover group: its ordered members plus the resolved probe settings.

func LoadFailoverGroups added in v1.5.9

func LoadFailoverGroups(db *gorm.DB) ([]FailoverGroupConfig, error)

LoadFailoverGroups returns every Type:"failover" group with its resolved probe settings. Malformed rows are skipped so one broken group never stalls the rest.

type FailoverMemberState added in v1.5.9

type FailoverMemberState struct {
	GroupTag    string `gorm:"column:group_tag;primaryKey"`
	MemberTag   string `gorm:"column:member_tag;primaryKey"`
	Healthy     bool   `gorm:"column:healthy"`
	ConsecUp    int    `gorm:"column:consec_up"`
	ConsecDown  int    `gorm:"column:consec_down"`
	LastProbeAt int64  `gorm:"column:last_probe_at"`
}

FailoverMemberState is one row of the failover_state table.

func ReadFailoverMemberStates added in v1.5.9

func ReadFailoverMemberStates(db *gorm.DB, groupTag string) ([]FailoverMemberState, error)

ReadFailoverMemberStates returns the stored health rows for a group.

func (FailoverMemberState) TableName added in v1.5.9

func (FailoverMemberState) TableName() string

type FailoverMemberStatus added in v1.5.9

type FailoverMemberStatus struct {
	Tag      string `json:"tag"`
	Healthy  bool   `json:"healthy"`
	Priority int    `json:"priority"`
}

FailoverMemberStatus is the per-member view returned to the panel.

type FailoverStatusEntry added in v1.5.9

type FailoverStatusEntry struct {
	Tag     string                 `json:"tag"`
	Active  string                 `json:"active"`
	AllDown bool                   `json:"allDown"`
	Members []FailoverMemberStatus `json:"members"`
}

FailoverStatusEntry is the per-group status returned to the panel: the live active member (from the running selector) plus per-member health.

type InboundService

type InboundService struct {
	ClientService
	Runtime *Runtime
}

func (*InboundService) FromIds

func (s *InboundService) FromIds(ids []uint) ([]*model.Inbound, error)

func (*InboundService) Get

func (s *InboundService) Get(ids string) (*[]map[string]interface{}, error)

func (*InboundService) GetAll

func (s *InboundService) GetAll() (*[]map[string]interface{}, error)

func (*InboundService) GetAllConfig

func (s *InboundService) GetAllConfig(db *gorm.DB) ([]json.RawMessage, error)

func (*InboundService) RemoveInboundsFromCore added in v1.5.8

func (s *InboundService) RemoveInboundsFromCore(tags []string) error

RemoveInboundsFromCore removes the given inbound tags from the running core and closes their tracked connections. Missing tags are tolerated so removals stay idempotent; with no running core there is nothing to remove.

func (*InboundService) RestartInbounds

func (s *InboundService) RestartInbounds(tx *gorm.DB, ids []uint) error

func (*InboundService) Save

func (s *InboundService) Save(tx *gorm.DB, act string, data json.RawMessage, initUserIds string, hostname string) (*entityCoreChange, error)

func (*InboundService) UpdateOutJsons

func (s *InboundService) UpdateOutJsons(tx *gorm.DB, inboundIds []uint, hostname string) error

type IpCertStatus added in v1.5.8

type IpCertStatus struct {
	Enabled       bool    `json:"enabled"`
	TargetIP      string  `json:"targetIp"`
	ApplyTarget   string  `json:"applyTarget"`
	Issued        bool    `json:"issued"`
	NotAfter      string  `json:"notAfter"`
	LastIssue     string  `json:"lastIssue"`
	DaysRemaining float64 `json:"daysRemaining"`
	CertPath      string  `json:"certPath"`
}

IpCertStatus is the read model returned to the API/frontend.

type IpCertificateService added in v1.5.8

type IpCertificateService struct {
	Runtime  *Runtime
	Settings *SettingService
	// contains filtered or unexported fields
}

IpCertificateService issues and renews a Let's Encrypt TLS certificate for a bare IP address (RFC 8738 / shortlived profile) entirely in-process via go-acme/lego, then applies it to the panel HTTPS listener or an inbound TLS profile. All network/ACME code sits behind the acmeIssuer seam so the orchestration is unit-testable without touching Let's Encrypt.

func (*IpCertificateService) GetStatus added in v1.5.8

func (s *IpCertificateService) GetStatus() (IpCertStatus, error)

GetStatus reports the current managed-certificate state for the UI.

func (*IpCertificateService) IssueForCLI added in v1.5.8

func (s *IpCertificateService) IssueForCLI(ctx context.Context, ip, email string, port int) (IpCertStatus, error)

IssueForCLI obtains a certificate from a one-shot CLI process and points the panel HTTPS cert settings at the new files. Unlike IssueNow it never restarts the panel - a CLI invocation has no live runtime, and the management script (s-ui.sh) stops the panel before issuance and starts it afterwards, which is what reloads the web certificate. The apply target is always the panel.

func (*IpCertificateService) IssueNow added in v1.5.8

func (s *IpCertificateService) IssueNow(ctx context.Context, ip, email string, port int, applyTarget, hostname string) (IpCertStatus, error)

IssueNow obtains a fresh certificate for ip and applies it to applyTarget. hostname is the request host used for inbound link regeneration ("" is fine for the panel target and for cron-driven renewals). Used by the renewal cron running inside the live panel, so a "panel" target also triggers a panel restart to reload the web certificate.

func (*IpCertificateService) RenewIfNeeded added in v1.5.8

func (s *IpCertificateService) RenewIfNeeded(ctx context.Context) (bool, error)

RenewIfNeeded re-issues the managed certificate when auto-renew is enabled and the remaining validity has dropped below the threshold. It reuses the stored target/email/port/apply-target and the persisted ACME account.

type LastUpdateStore

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

func NewLastUpdateStore

func NewLastUpdateStore() *LastUpdateStore

func (*LastUpdateStore) Get

func (s *LastUpdateStore) Get() int64

func (*LastUpdateStore) Set

func (s *LastUpdateStore) Set(value int64)

type LogQuery

type LogQuery struct {
	Count  int
	Level  string
	Source string
	Filter string
}

func ParseLogQuery

func ParseLogQuery(count string, level string, source string, filter string) (LogQuery, error)

type MemberHealth added in v1.5.9

type MemberHealth struct {
	ConsecutiveUp   int
	ConsecutiveDown int
}

MemberHealth is the rolling probe outcome for a single failover member.

type ObservabilityBucket

type ObservabilityBucket string

func ParseObservabilityBucket

func ParseObservabilityBucket(raw string) (ObservabilityBucket, error)

type ObservabilityMetric

type ObservabilityMetric string

func ParseObservabilityMetric

func ParseObservabilityMetric(raw string) (ObservabilityMetric, error)

type ObservabilityMetricSample

type ObservabilityMetricSample struct {
	DateTime int64   `json:"dateTime"`
	Value    float64 `json:"value"`
}

type ObservabilitySample

type ObservabilitySample struct {
	DateTime int64                  `json:"dateTime"`
	CPU      float64                `json:"cpu"`
	Memory   map[string]interface{} `json:"memory"`
	Network  map[string]interface{} `json:"network"`
}

func AggregateObservabilitySamples

func AggregateObservabilitySamples(samples []ObservabilitySample, dateTime int64) ObservabilitySample

type ObservabilityService

type ObservabilityService struct {
	ServerService
	SettingService
}

func (*ObservabilityService) CoreHistory

func (s *ObservabilityService) CoreHistory() []CoreSample

func (*ObservabilityService) CoreHistoryForBucket

func (s *ObservabilityService) CoreHistoryForBucket(bucket ObservabilityBucket) ([]CoreSample, error)

func (*ObservabilityService) CoreHistoryForBucketSince

func (s *ObservabilityService) CoreHistoryForBucketSince(bucket ObservabilityBucket, since int64) ([]CoreSample, error)

func (*ObservabilityService) CurrentCoreSample

func (s *ObservabilityService) CurrentCoreSample() CoreSample

func (*ObservabilityService) CurrentObservabilitySample

func (s *ObservabilityService) CurrentObservabilitySample() ObservabilitySample

func (*ObservabilityService) History

func (*ObservabilityService) HistoryForBucket

func (s *ObservabilityService) HistoryForBucket(bucket ObservabilityBucket) ([]ObservabilitySample, error)

func (*ObservabilityService) HistoryForBucketSince

func (s *ObservabilityService) HistoryForBucketSince(bucket ObservabilityBucket, since int64) ([]ObservabilitySample, error)

func (*ObservabilityService) MetricHistory

func (*ObservabilityService) RecordCoreSample

func (s *ObservabilityService) RecordCoreSample(bucket ObservabilityBucket, sample CoreSample) error

func (*ObservabilityService) RecordObservabilitySample

func (s *ObservabilityService) RecordObservabilitySample(bucket ObservabilityBucket, sample ObservabilitySample) error

type OutboundService

type OutboundService struct {
	Runtime *Runtime
}

func (*OutboundService) GetAll

func (o *OutboundService) GetAll() (*[]map[string]interface{}, error)

func (*OutboundService) GetAllConfig

func (o *OutboundService) GetAllConfig(db *gorm.DB) ([]json.RawMessage, error)

func (*OutboundService) RemoveOutboundsFromCore added in v1.5.8

func (s *OutboundService) RemoveOutboundsFromCore(tags []string) error

RemoveOutboundsFromCore removes the given outbound tags from the running core. Missing tags are tolerated so removals stay idempotent.

func (*OutboundService) RestartOutbounds added in v1.5.8

func (s *OutboundService) RestartOutbounds(tx *gorm.DB, ids []uint) error

RestartOutbounds replaces the given outbounds inside the running core (remove by tag, then add the committed definition).

func (*OutboundService) Save

func (s *OutboundService) Save(tx *gorm.DB, act string, data json.RawMessage) (*entityCoreChange, error)

type PanelLoadSettings added in v1.5.10

type PanelLoadSettings struct {
	Config      string
	SubURI      string
	SubJsonURI  string
	SubClashURI string
	TrafficAge  int
}

type PanelService

type PanelService struct {
	RestartScheduler RestartScheduler
	Runtime          *Runtime
}

func NewPanelService

func NewPanelService(restartScheduler RestartScheduler) *PanelService

func (*PanelService) RestartPanel

func (s *PanelService) RestartPanel(delay time.Duration) error

type PanelUpdateService added in v1.5.9

type PanelUpdateService struct {
	Runtime *Runtime
}

func (*PanelUpdateService) Apply added in v1.5.9

func (s *PanelUpdateService) Apply(target ReleaseTarget, initiator string) error

Apply starts an update to target. Only one update may run at a time (FR-012). It returns immediately; progress is observed via Status() (the client polls GET /api/update/status). The caller MUST have already validated step-up auth (SR-010), the target version (FR-016), and that target is newer (FR-013).

func (*PanelUpdateService) InProgress added in v1.5.9

func (s *PanelUpdateService) InProgress() bool

InProgress reports whether an update is currently running.

func (*PanelUpdateService) Status added in v1.5.9

func (s *PanelUpdateService) Status() UpdateJob

Status returns a snapshot of the current/last update job (idle if none).

type ReleaseTarget added in v1.5.9

type ReleaseTarget struct {
	Channel      string
	Tag          string
	Version      string
	Prerelease   bool
	ReleaseNotes string
	ReleaseURL   string
	Platform     string
	AssetURL     string
	ChecksumURL  string
}

ReleaseTarget is a concrete release selected for a channel, consumed by the panel self-update apply path. URLs are built from a fixed template (SR-004).

type RestartScheduler

type RestartScheduler interface {
	ScheduleRestart(delay time.Duration) error
}

type Runtime

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

func DefaultRuntime

func DefaultRuntime() *Runtime

func NewRuntime

func NewRuntime(coreInstance *core.Core) *Runtime

func NewRuntimeWithCoreProvider

func NewRuntimeWithCoreProvider(provider CoreProvider) *Runtime

func (*Runtime) Core

func (r *Runtime) Core() *core.Core

func (*Runtime) RestartScheduler

func (r *Runtime) RestartScheduler() RestartScheduler

func (*Runtime) SetCore

func (r *Runtime) SetCore(coreInstance *core.Core)

func (*Runtime) SetCoreProvider

func (r *Runtime) SetCoreProvider(provider CoreProvider)

type ServerService

type ServerService struct {
	Runtime *Runtime
}

func (*ServerService) GenKeypair

func (s *ServerService) GenKeypair(keyType string, options string) []string

func (*ServerService) GetCpuPercent

func (s *ServerService) GetCpuPercent() float64

func (*ServerService) GetDatabaseInfo

func (s *ServerService) GetDatabaseInfo() map[string]int64

func (*ServerService) GetDiskIO

func (s *ServerService) GetDiskIO() map[string]interface{}

func (*ServerService) GetDiskInfo

func (s *ServerService) GetDiskInfo() map[string]interface{}

func (*ServerService) GetLogs

func (s *ServerService) GetLogs(count string, level string) []string

func (*ServerService) GetLogsFiltered

func (s *ServerService) GetLogsFiltered(count string, level string, source string, filter string) ([]string, error)

func (*ServerService) GetMemInfo

func (s *ServerService) GetMemInfo() map[string]interface{}

func (*ServerService) GetNetInfo

func (s *ServerService) GetNetInfo() map[string]interface{}

func (*ServerService) GetSingboxInfo

func (s *ServerService) GetSingboxInfo() map[string]interface{}

func (*ServerService) GetStatus

func (s *ServerService) GetStatus(request string) *map[string]interface{}

func (*ServerService) GetSwapInfo

func (s *ServerService) GetSwapInfo() map[string]interface{}

func (*ServerService) GetSystemInfo

func (s *ServerService) GetSystemInfo() map[string]interface{}

type ServicesService

type ServicesService struct {
	Runtime *Runtime
}

func (*ServicesService) GetAll

func (s *ServicesService) GetAll() (*[]map[string]interface{}, error)

func (*ServicesService) GetAllConfig

func (s *ServicesService) GetAllConfig(db *gorm.DB) ([]json.RawMessage, error)

func (*ServicesService) RemoveServicesFromCore added in v1.5.8

func (s *ServicesService) RemoveServicesFromCore(tags []string) error

RemoveServicesFromCore removes the given service tags from the running core. Missing tags are tolerated so removals stay idempotent; with no running core there is nothing to remove.

func (*ServicesService) RestartServices

func (s *ServicesService) RestartServices(tx *gorm.DB, ids []uint) error

func (*ServicesService) Save

func (s *ServicesService) Save(tx *gorm.DB, act string, data json.RawMessage) (*entityCoreChange, error)

type SettingService

type SettingService struct {
}

func (*SettingService) ClearWebDomainAndAddress added in v1.5.6

func (s *SettingService) ClearWebDomainAndAddress() error

ClearWebDomainAndAddress clears the panel domain, listen address and web URI. It restores access by IP on all interfaces when a wrong domain or listen address was configured and locked the panel out. A panel restart is required for the change to take effect.

func (*SettingService) ConfigBlobChanged added in v1.5.8

func (s *SettingService) ConfigBlobChanged(tx *gorm.DB, config json.RawMessage) (bool, error)

ConfigBlobChanged reports whether saving the given config would change the stored blob. It compares against the exact persisted representation (SaveConfig's MarshalIndent form), so a byte-identical re-save is detected reliably and any doubt counts as changed.

func (*SettingService) GetAllSetting

func (s *SettingService) GetAllSetting() (*map[string]string, error)

func (*SettingService) GetAuditRetentionDays

func (s *SettingService) GetAuditRetentionDays() (int, error)

func (*SettingService) GetCertFile

func (s *SettingService) GetCertFile() (string, error)

func (*SettingService) GetConfig

func (s *SettingService) GetConfig() (string, error)

func (*SettingService) GetCookieKeys

func (s *SettingService) GetCookieKeys() ([][]byte, error)

func (*SettingService) GetFinalSubURI

func (s *SettingService) GetFinalSubURI(host string) (string, error)

func (*SettingService) GetForceCookieSecure

func (s *SettingService) GetForceCookieSecure() (bool, error)

func (*SettingService) GetIPHistoryRetentionDays

func (s *SettingService) GetIPHistoryRetentionDays() (int, error)

func (*SettingService) GetIPShowRaw

func (s *SettingService) GetIPShowRaw() (bool, error)

func (*SettingService) GetInstallSalt

func (s *SettingService) GetInstallSalt() ([]byte, error)

func (*SettingService) GetIpCertApplyTarget added in v1.5.8

func (s *SettingService) GetIpCertApplyTarget() (string, error)

func (*SettingService) GetIpCertCertPath added in v1.5.8

func (s *SettingService) GetIpCertCertPath() (string, error)

func (*SettingService) GetIpCertChallengePort added in v1.5.8

func (s *SettingService) GetIpCertChallengePort() (int, error)

func (*SettingService) GetIpCertEmail added in v1.5.8

func (s *SettingService) GetIpCertEmail() (string, error)

func (*SettingService) GetIpCertEnabled added in v1.5.8

func (s *SettingService) GetIpCertEnabled() (bool, error)

func (*SettingService) GetIpCertKeyPath added in v1.5.8

func (s *SettingService) GetIpCertKeyPath() (string, error)

func (*SettingService) GetIpCertLastIssue added in v1.5.8

func (s *SettingService) GetIpCertLastIssue() (string, error)

func (*SettingService) GetIpCertNotAfter added in v1.5.8

func (s *SettingService) GetIpCertNotAfter() (string, error)

func (*SettingService) GetIpCertTargetIP added in v1.5.8

func (s *SettingService) GetIpCertTargetIP() (string, error)

func (*SettingService) GetKeyFile

func (s *SettingService) GetKeyFile() (string, error)

func (*SettingService) GetListen

func (s *SettingService) GetListen() (string, error)

func (*SettingService) GetObservabilityMemoryCapMB

func (s *SettingService) GetObservabilityMemoryCapMB() (int, error)

func (*SettingService) GetPaidSubAutoInbounds added in v1.5.7

func (s *SettingService) GetPaidSubAutoInbounds() ([]uint, error)

GetPaidSubAutoInbounds returns the admin-selected inbound ids that newly auto-registered clients are assigned to. Invalid JSON yields an empty list (auto-registration then has nothing to assign and is effectively disabled).

func (*SettingService) GetPaidSubAutoRegister added in v1.5.7

func (s *SettingService) GetPaidSubAutoRegister() (bool, error)

func (*SettingService) GetPaidSubBotPollSeconds added in v1.5.7

func (s *SettingService) GetPaidSubBotPollSeconds() (int, error)

func (*SettingService) GetPaidSubBotToken added in v1.5.7

func (s *SettingService) GetPaidSubBotToken() (string, error)

func (*SettingService) GetPaidSubCryptoBotEnabled added in v1.5.7

func (s *SettingService) GetPaidSubCryptoBotEnabled() (bool, error)

func (*SettingService) GetPaidSubCryptoBotToken added in v1.5.7

func (s *SettingService) GetPaidSubCryptoBotToken() (string, error)

func (*SettingService) GetPaidSubCurrency added in v1.5.7

func (s *SettingService) GetPaidSubCurrency() (string, error)

func (*SettingService) GetPaidSubEnabled added in v1.5.7

func (s *SettingService) GetPaidSubEnabled() (bool, error)

func (*SettingService) GetPaidSubExternalEnabled added in v1.5.7

func (s *SettingService) GetPaidSubExternalEnabled() (bool, error)

func (*SettingService) GetPaidSubExternalUrlTemplate added in v1.5.7

func (s *SettingService) GetPaidSubExternalUrlTemplate() (string, error)

func (*SettingService) GetPaidSubGreeting added in v1.5.7

func (s *SettingService) GetPaidSubGreeting() (string, error)

func (*SettingService) GetPaidSubMaxClients added in v1.5.7

func (s *SettingService) GetPaidSubMaxClients() (int, error)

func (*SettingService) GetPaidSubOrderTTLMinutes added in v1.5.7

func (s *SettingService) GetPaidSubOrderTTLMinutes() (int, error)

func (*SettingService) GetPaidSubOutboundTag added in v1.5.7

func (s *SettingService) GetPaidSubOutboundTag() (string, error)

func (*SettingService) GetPaidSubPayMasterEnabled added in v1.5.7

func (s *SettingService) GetPaidSubPayMasterEnabled() (bool, error)

func (*SettingService) GetPaidSubPayMasterToken added in v1.5.7

func (s *SettingService) GetPaidSubPayMasterToken() (string, error)

func (*SettingService) GetPaidSubRefundRevoke added in v1.5.7

func (s *SettingService) GetPaidSubRefundRevoke() (bool, error)

GetPaidSubRefundRevoke reports the admin policy for the bot's user-initiated Stars auto-refund: when true (default), a successful refund also rolls back the days/traffic that order granted (anti-abuse: buy → refund → keep using). The user never chooses this; the panel refund button has its own per-refund toggle.

func (*SettingService) GetPaidSubStarsEnabled added in v1.5.7

func (s *SettingService) GetPaidSubStarsEnabled() (bool, error)

func (*SettingService) GetPaidSubStartRateLimitPerMin added in v1.5.7

func (s *SettingService) GetPaidSubStartRateLimitPerMin() (int, error)

func (*SettingService) GetPaidSubStripeEnabled added in v1.5.7

func (s *SettingService) GetPaidSubStripeEnabled() (bool, error)

func (*SettingService) GetPaidSubStripeToken added in v1.5.7

func (s *SettingService) GetPaidSubStripeToken() (string, error)

func (*SettingService) GetPaidSubTransportMode added in v1.5.7

func (s *SettingService) GetPaidSubTransportMode() (string, error)

func (*SettingService) GetPaidSubTrialDays added in v1.5.7

func (s *SettingService) GetPaidSubTrialDays() (int, error)

func (*SettingService) GetPaidSubTrialVolumeGB added in v1.5.7

func (s *SettingService) GetPaidSubTrialVolumeGB() (int, error)

func (*SettingService) GetPaidSubUpdateOffset added in v1.5.7

func (s *SettingService) GetPaidSubUpdateOffset() (int64, error)

func (*SettingService) GetPaidSubYooKassaEnabled added in v1.5.7

func (s *SettingService) GetPaidSubYooKassaEnabled() (bool, error)

func (*SettingService) GetPaidSubYooKassaToken added in v1.5.7

func (s *SettingService) GetPaidSubYooKassaToken() (string, error)

func (*SettingService) GetPort

func (s *SettingService) GetPort() (int, error)

func (*SettingService) GetSecret

func (s *SettingService) GetSecret() ([]byte, error)

func (*SettingService) GetSessionGeneration

func (s *SettingService) GetSessionGeneration() (string, error)

func (*SettingService) GetSessionMaxAge

func (s *SettingService) GetSessionMaxAge() (int, error)

func (*SettingService) GetSessionSameSiteStrict added in v1.5.6

func (s *SettingService) GetSessionSameSiteStrict() (bool, error)

func (*SettingService) GetSubAnnounce

func (s *SettingService) GetSubAnnounce() (string, error)

func (*SettingService) GetSubCertFile

func (s *SettingService) GetSubCertFile() (string, error)

func (*SettingService) GetSubClashEnable

func (s *SettingService) GetSubClashEnable() (bool, error)

func (*SettingService) GetSubClashExt

func (s *SettingService) GetSubClashExt() (string, error)

func (*SettingService) GetSubClashPath

func (s *SettingService) GetSubClashPath() (string, error)

func (*SettingService) GetSubClashURI

func (s *SettingService) GetSubClashURI() (string, error)

func (*SettingService) GetSubDomain

func (s *SettingService) GetSubDomain() (string, error)

func (*SettingService) GetSubEncode

func (s *SettingService) GetSubEncode() (bool, error)

func (*SettingService) GetSubJsonDirectRules

func (s *SettingService) GetSubJsonDirectRules() (bool, error)

func (*SettingService) GetSubJsonEnable

func (s *SettingService) GetSubJsonEnable() (bool, error)

func (*SettingService) GetSubJsonExt

func (s *SettingService) GetSubJsonExt() (string, error)

func (*SettingService) GetSubJsonFragment

func (s *SettingService) GetSubJsonFragment() (string, error)

func (*SettingService) GetSubJsonMux

func (s *SettingService) GetSubJsonMux() (bool, error)

func (*SettingService) GetSubJsonNoises

func (s *SettingService) GetSubJsonNoises() (string, error)

func (*SettingService) GetSubJsonPath

func (s *SettingService) GetSubJsonPath() (string, error)

func (*SettingService) GetSubJsonURI

func (s *SettingService) GetSubJsonURI() (string, error)

func (*SettingService) GetSubKeyFile

func (s *SettingService) GetSubKeyFile() (string, error)

func (*SettingService) GetSubLinkEnable

func (s *SettingService) GetSubLinkEnable() (bool, error)

func (*SettingService) GetSubListen

func (s *SettingService) GetSubListen() (string, error)

func (*SettingService) GetSubNameInRemark

func (s *SettingService) GetSubNameInRemark() (bool, error)

func (*SettingService) GetSubPath

func (s *SettingService) GetSubPath() (string, error)

func (*SettingService) GetSubPort

func (s *SettingService) GetSubPort() (int, error)

func (*SettingService) GetSubProfileUrl

func (s *SettingService) GetSubProfileUrl() (string, error)

func (*SettingService) GetSubRateLimitPerIP

func (s *SettingService) GetSubRateLimitPerIP() (int, error)

func (*SettingService) GetSubSecretRequired

func (s *SettingService) GetSubSecretRequired() (bool, error)

func (*SettingService) GetSubShowInfo

func (s *SettingService) GetSubShowInfo() (bool, error)

func (*SettingService) GetSubSupportUrl

func (s *SettingService) GetSubSupportUrl() (string, error)

func (*SettingService) GetSubTitle

func (s *SettingService) GetSubTitle() (string, error)

func (*SettingService) GetSubURI

func (s *SettingService) GetSubURI() (string, error)

func (*SettingService) GetSubUpdates

func (s *SettingService) GetSubUpdates() (int, error)

func (*SettingService) GetTelegramBackupCron

func (s *SettingService) GetTelegramBackupCron() (string, error)

func (*SettingService) GetTelegramBackupEnabled

func (s *SettingService) GetTelegramBackupEnabled() (bool, error)

func (*SettingService) GetTelegramBackupExcludeTables

func (s *SettingService) GetTelegramBackupExcludeTables() (string, error)

func (*SettingService) GetTelegramBackupMaxSizeMB

func (s *SettingService) GetTelegramBackupMaxSizeMB() (int, error)

func (*SettingService) GetTelegramBackupPassphraseBytes

func (s *SettingService) GetTelegramBackupPassphraseBytes() ([]byte, error)

func (*SettingService) GetTelegramCpuThreshold

func (s *SettingService) GetTelegramCpuThreshold() (int, error)

func (*SettingService) GetTelegramEnabled

func (s *SettingService) GetTelegramEnabled() (bool, error)

func (*SettingService) GetTelegramNotifyCpu

func (s *SettingService) GetTelegramNotifyCpu() (bool, error)

func (*SettingService) GetTelegramReport

func (s *SettingService) GetTelegramReport() (bool, error)

func (*SettingService) GetTelegramReportCron

func (s *SettingService) GetTelegramReportCron() (string, error)

func (*SettingService) GetTimeLocation

func (s *SettingService) GetTimeLocation() (*time.Location, error)

func (*SettingService) GetTrafficAge

func (s *SettingService) GetTrafficAge() (int, error)

func (*SettingService) GetUpdateChannel added in v1.5.9

func (s *SettingService) GetUpdateChannel() string

GetUpdateChannel returns the persisted self-update channel, defaulting to "main" when unset or invalid. Channel constants and validation live in the config package (config.UpdateChannelMain / config.NormalizeUpdateChannel).

func (*SettingService) GetWebDomain

func (s *SettingService) GetWebDomain() (string, error)

func (*SettingService) GetWebPath

func (s *SettingService) GetWebPath() (string, error)

func (*SettingService) GetWebURI

func (s *SettingService) GetWebURI() (string, error)

func (*SettingService) HasTelegramBackupPassphrase

func (s *SettingService) HasTelegramBackupPassphrase() (bool, error)

func (*SettingService) LoadPanelSettingsForData added in v1.5.10

func (s *SettingService) LoadPanelSettingsForData(host string) (PanelLoadSettings, error)

func (*SettingService) ResealSecretSettings added in v1.5.7

func (s *SettingService) ResealSecretSettings() (int, error)

ResealSecretSettings re-encrypts every encrypted secret setting that still opens under a non-preferred (DB-derived) box so it becomes recoverable only with the out-of-database SUI_SECRETBOX_KEY. This closes the gap where a value written before SUI_SECRETBOX_KEY was adopted stays decryptable from the database alone (its key is derived from the plaintext settings.secret row).

It is:

  • a NO-OP when SUI_SECRETBOX_KEY is unset (candidates[0] would itself be the DB-derived box, so re-sealing would not improve at-rest protection);
  • idempotent (a row already sealed under candidates[0] is skipped);
  • fail-safe per row (a row that decrypts under no candidate is left untouched, never corrupted).

A row is only rewritten after it successfully decrypts, and it is re-sealed with that exact recovered plaintext, so the round-trip cannot lose data. Once re-sealed under SUI_SECRETBOX_KEY a value can no longer be recovered from the database alone - that is the intended hardening. Returns the rows re-sealed.

func (*SettingService) ResetSettings

func (s *SettingService) ResetSettings() error

func (*SettingService) RotateSessionGeneration

func (s *SettingService) RotateSessionGeneration() (string, error)

func (*SettingService) Save

func (s *SettingService) Save(tx *gorm.DB, data json.RawMessage) error

func (*SettingService) SaveConfig

func (s *SettingService) SaveConfig(tx *gorm.DB, config json.RawMessage) error

func (*SettingService) SetConfig

func (s *SettingService) SetConfig(config string) error

func (*SettingService) SetIpCertEnabled added in v1.5.8

func (s *SettingService) SetIpCertEnabled(v bool) error

SetIpCertEnabled toggles cron auto-renewal. The CLI enables it on a successful issue ("issue and forget") and exposes an explicit disable.

func (*SettingService) SetPaidSubUpdateOffset added in v1.5.7

func (s *SettingService) SetPaidSubUpdateOffset(offset int64) error

func (*SettingService) SetPort

func (s *SettingService) SetPort(port int) error

func (*SettingService) SetSubPath

func (s *SettingService) SetSubPath(subPath string) error

func (*SettingService) SetSubPort

func (s *SettingService) SetSubPort(subPort int) error

func (*SettingService) SetUpdateChannel added in v1.5.9

func (s *SettingService) SetUpdateChannel(channel string) error

SetUpdateChannel persists the self-update channel after validating it.

func (*SettingService) SetWebPath

func (s *SettingService) SetWebPath(webPath string) error

type SingBoxConfig

type SingBoxConfig struct {
	Log          json.RawMessage   `json:"log"`
	Dns          json.RawMessage   `json:"dns"`
	Ntp          json.RawMessage   `json:"ntp"`
	Inbounds     []json.RawMessage `json:"inbounds"`
	Outbounds    []json.RawMessage `json:"outbounds"`
	Services     []json.RawMessage `json:"services"`
	Endpoints    []json.RawMessage `json:"endpoints"`
	Route        json.RawMessage   `json:"route"`
	Experimental json.RawMessage   `json:"experimental"`
}

type StatsService

type StatsService struct {
	Runtime *Runtime
}

func (*StatsService) DelOldStats

func (s *StatsService) DelOldStats(days int) error

func (*StatsService) GetInboundTrafficSummary added in v1.5.10

func (s *StatsService) GetInboundTrafficSummary(limitHours int, bucketCount int, endTime int64) (TrafficSummary, error)

func (*StatsService) GetOnlines

func (s *StatsService) GetOnlines() (onlines, error)

func (*StatsService) GetStats

func (s *StatsService) GetStats(resource string, tag string, limit int) ([]model.Stats, error)

func (*StatsService) SaveStats

func (s *StatsService) SaveStats(enableTraffic bool) (err error)

type TagReference added in v1.5.8

type TagReference struct {
	Kind    string
	Locator string
	Lazy    bool
}

TagReference describes one place in the stored configuration that points at a tag. Lazy references are resolved by the core on every use, so replacing the target under the same tag is safe; eager ones are captured once at adapter construction and would keep pointing at a closed adapter.

type TelegramBackupEnvelopeHeader

type TelegramBackupEnvelopeHeader struct {
	Version      byte
	KDFID        byte
	KDFParams    TelegramBackupKDFParams
	RawKDFParams [telegramBackupKDFParamsSize]byte
	Salt         [telegramBackupSaltSize]byte
	Nonce        [telegramBackupNonceSize]byte
}

func ParseTelegramBackupEnvelopeHeader

func ParseTelegramBackupEnvelopeHeader(envelope []byte) (TelegramBackupEnvelopeHeader, error)

type TelegramBackupKDFParams

type TelegramBackupKDFParams struct {
	MemoryKiB   uint32
	Iterations  uint32
	Parallelism uint8
}

type TelegramBackupResult

type TelegramBackupResult struct {
	Success           bool     `json:"success"`
	Filename          string   `json:"filename,omitempty"`
	Trigger           string   `json:"trigger,omitempty"`
	ErrorClass        string   `json:"errorClass,omitempty"`
	PayloadSizeBytes  int64    `json:"-"`
	EnvelopeSizeBytes int64    `json:"-"`
	ExcludedTables    []string `json:"-"`
}

type TelegramBackupService

type TelegramBackupService struct {
	SettingService
	TelegramService
	AuditService
}

func (*TelegramBackupService) RunOnce

func (s *TelegramBackupService) RunOnce(ctx context.Context, trigger string) (result TelegramBackupResult)

type TelegramChatDetectionResult added in v1.5.11

type TelegramChatDetectionResult struct {
	Success    bool   `json:"success"`
	ChatID     string `json:"chatID,omitempty"`
	ChatType   string `json:"chatType,omitempty"`
	Title      string `json:"title,omitempty"`
	Username   string `json:"username,omitempty"`
	ErrorClass string `json:"errorClass,omitempty"`
}

type TelegramResult

type TelegramResult struct {
	Success    bool          `json:"success"`
	ErrorClass string        `json:"errorClass,omitempty"`
	RetryAfter time.Duration `json:"-"`
}

type TelegramService

type TelegramService struct {
	SettingService
	Runtime *Runtime
}

func (*TelegramService) DetectTelegramChat added in v1.5.11

func (s *TelegramService) DetectTelegramChat(tokenOverride string) TelegramChatDetectionResult

func (*TelegramService) NotifyTelegramEvent

func (s *TelegramService) NotifyTelegramEvent(event string, fields map[string]string)

func (*TelegramService) SendTelegramDocument

func (s *TelegramService) SendTelegramDocument(filename string, data []byte, caption string) TelegramResult

func (*TelegramService) TestTelegram

func (s *TelegramService) TestTelegram() TelegramResult

type TlsService

type TlsService struct {
	InboundService
	ServicesService
	Runtime *Runtime
}

func (*TlsService) GetAll

func (s *TlsService) GetAll() ([]model.Tls, error)

func (*TlsService) Save

func (s *TlsService) Save(tx *gorm.DB, action string, data json.RawMessage, hostname string) (inboundIds []uint, serviceIds []uint, err error)

Save persists a TLS change inside tx and returns the ids of inbounds and services that reference the edited TLS row. The caller hot-reloads them after the transaction commits, so the running core picks up the new certificate from committed state without a full restart (and without the pre-commit reload window where a rollback would leave the core ahead of the database).

type TrafficBucket added in v1.5.10

type TrafficBucket struct {
	StartTime int64 `json:"startTime"`
	EndTime   int64 `json:"endTime"`
	Download  int64 `json:"download"`
	Upload    int64 `json:"upload"`
}

type TrafficSummary added in v1.5.10

type TrafficSummary struct {
	StartTime int64           `json:"startTime"`
	EndTime   int64           `json:"endTime"`
	Range     int             `json:"range"`
	Buckets   []TrafficBucket `json:"buckets"`
	Download  int64           `json:"download"`
	Upload    int64           `json:"upload"`
}

type UpdateJob added in v1.5.9

type UpdateJob struct {
	ID          string      `json:"id"`
	Channel     string      `json:"channel"`
	FromVersion string      `json:"fromVersion"`
	ToVersion   string      `json:"toVersion"`
	Stage       UpdateStage `json:"stage"`
	Error       string      `json:"error,omitempty"`
	StartedAt   int64       `json:"startedAt"`
	Initiator   string      `json:"initiator,omitempty"`
}

UpdateJob is the ephemeral, in-memory state of the single allowed update.

type UpdateStage added in v1.5.9

type UpdateStage string

UpdateStage is the current step of an in-flight panel self-update.

const (
	UpdateStageIdle        UpdateStage = "idle"
	UpdateStageDownloading UpdateStage = "downloading"
	UpdateStageVerifying   UpdateStage = "verifying"
	UpdateStageApplying    UpdateStage = "applying"
	UpdateStageRestarting  UpdateStage = "restarting"
	UpdateStageFailed      UpdateStage = "failed"
)

type UserService

type UserService struct {
	Runtime *Runtime
}

func (*UserService) AddToken

func (s *UserService) AddToken(username string, expiry int64, desc string, scope string) (string, error)

func (*UserService) AddUser added in v1.5.6

func (s *UserService) AddUser(actorUsername string, currentPass string, newUsername string, newPassword string) (*model.User, error)

func (*UserService) ChangePass

func (s *UserService) ChangePass(username string, oldPass string, newUser string, newPass string) error

ChangePass updates the credentials of the user identified by username. The caller passes the AUTHENTICATED session user's name (never a client-supplied id), so an admin can only change their own account, not another admin's.

func (*UserService) CheckUser

func (s *UserService) CheckUser(username string, password string, remoteIP string) (*model.User, bool)

CheckUser is a pure query (Command-Query Separation): it validates the credentials and returns the user plus whether the stored hash needs migration. It performs NO writes - recording the login is RecordLogin's job.

func (*UserService) DeleteToken

func (s *UserService) DeleteToken(id string) error

func (*UserService) DeleteUser added in v1.5.6

func (s *UserService) DeleteUser(actorUsername string, currentPass string, targetID string) (DeleteUserResult, error)

func (*UserService) GetFirstUser

func (s *UserService) GetFirstUser() (*model.User, error)

func (*UserService) GetUserTokens

func (s *UserService) GetUserTokens(username string) (*[]model.Tokens, error)

func (*UserService) GetUsers

func (s *UserService) GetUsers() (*[]model.User, error)

func (*UserService) HashAPIToken

func (s *UserService) HashAPIToken(token string) (string, error)

func (*UserService) LoadTokens

func (s *UserService) LoadTokens() ([]byte, error)

func (*UserService) Login

func (s *UserService) Login(username string, password string, remoteIP string) (string, error)

func (*UserService) RecordLogin added in v1.5.7

func (s *UserService) RecordLogin(username string, remoteIP string)

RecordLogin persists the most recent login timestamp + IP for an admin. Kept out of CheckUser so the query stays pure; best-effort (logged, never blocks).

func (*UserService) RecordTokenUse

func (s *UserService) RecordTokenUse(id uint, ip string) error

func (*UserService) SetTokenEnabled

func (s *UserService) SetTokenEnabled(id string, enabled bool) error

func (*UserService) UpdateFirstUser

func (s *UserService) UpdateFirstUser(username string, password string) error

func (*UserService) UserExists added in v1.5.6

func (s *UserService) UserExists(username string) (bool, error)

type VersionInfo

type VersionInfo struct {
	Current         string `json:"current"`
	Version         string `json:"version"`
	Channel         string `json:"channel,omitempty"`
	Latest          string `json:"latest,omitempty"`
	Prerelease      bool   `json:"prerelease,omitempty"`
	UpdateAvailable bool   `json:"updateAvailable,omitempty"`
	AssetAvailable  bool   `json:"assetAvailable,omitempty"`
	ReleaseURL      string `json:"releaseURL,omitempty"`
	ReleaseNotes    string `json:"releaseNotes,omitempty"`
	CheckedAt       int64  `json:"checkedAt,omitempty"`
	CheckError      string `json:"checkError,omitempty"`
}

type VersionService

type VersionService struct{}

func (*VersionService) CheckForChannel added in v1.5.9

func (s *VersionService) CheckForChannel(channel string, force bool) VersionInfo

CheckForChannel returns version status for a channel. force bypasses the cache (used by the explicit "Check updates" action).

func (*VersionService) GetVersionInfo

func (s *VersionService) GetVersionInfo() VersionInfo

GetVersionInfo reports the stable ("main") channel version status. Kept channel-agnostic for the existing /api/version consumers (backward compatible).

func (*VersionService) ResolveTarget added in v1.5.9

func (s *VersionService) ResolveTarget(channel string) (ReleaseTarget, error)

ResolveTarget returns the concrete release to update to on a channel, or an error if there is nothing newer or no installable artifact for this platform.

type WarpService

type WarpService struct{}

func (*WarpService) RegisterWarp

func (s *WarpService) RegisterWarp(ep *model.Endpoint) error

func (*WarpService) SetWarpLicense

func (s *WarpService) SetWarpLicense(old_license string, ep *model.Endpoint) error

Jump to

Keyboard shortcuts

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