store

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: AGPL-3.0 Imports: 16 Imported by: 0

Documentation

Overview

Package store is the SQLite-backed persistence layer. The DB is the single source of truth; the Xray config is always derived from it.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func InspectDB

func InspectDB(path string) (users, admins int, secret string, err error)

InspectDB opens the database file at path read-only and reports whether it's a usable rospanel database, along with its user/admin counts and configured secret path. A non-nil error means the file isn't a valid panel DB (missing, corrupt, or — the classic empty-backup case — a header with no tables because the data was left in an unbacked-up WAL).

Types

type Store

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

Store wraps the SQLite connection pool.

func Open

func Open(path string) (*Store, error)

Open opens (creating if needed) the SQLite database at path, applies pragmas, and runs pending migrations.

func (*Store) ActiveDeviceCounts added in v0.3.0

func (s *Store) ActiveDeviceCounts(since int64) (map[int64]int, error)

ActiveDeviceCounts returns how many distinct source IPs were seen per user since the given unix timestamp (typically now - DeviceOnlineWindow).

func (*Store) AddConnection

func (s *Store) AddConnection(userID int64, ip string, ts int64) error

AddConnection records activity from a source IP for a user (upserting the per-IP row) and bumps the user's last_seen.

func (*Store) AddDailyTraffic

func (s *Store) AddDailyTraffic(userID int64, day string, up, down int64) error

AddDailyTraffic adds up/down deltas to a user's row for the given UTC day.

func (*Store) Checkpoint

func (s *Store) Checkpoint() error

Checkpoint flushes the write-ahead log into the main database file and truncates it, so an on-disk copy (e.g. a backup) captures all committed data. Without this a live backup would copy a near-empty .db with everything still in the uncheckpointed .db-wal (which backups intentionally exclude).

func (*Store) ClearUserTelegramChat added in v0.3.0

func (s *Store) ClearUserTelegramChat(userID int64) error

ClearUserTelegramChat unlinks a VPN user's Telegram chat.

func (*Store) ClearUserTgLinkCode added in v0.4.0

func (s *Store) ClearUserTgLinkCode(userID int64) error

ClearUserTgLinkCode burns a user's pending Telegram bind code (after a successful link or on demand).

func (*Store) Close

func (s *Store) Close() error

Close releases the database.

func (*Store) CountAdmins

func (s *Store) CountAdmins() (int, error)

CountAdmins returns the number of admin accounts.

func (*Store) CountUsersOnPlan added in v0.4.0

func (s *Store) CountUsersOnPlan(planID int64) (int, error)

CountUsersOnPlan returns how many users currently have this plan assigned.

func (*Store) CreateAdmin

func (s *Store) CreateAdmin(username, passwordHash string) (int64, error)

CreateAdmin inserts an admin with the given username and password hash.

func (*Store) CreatePaymentOrder added in v0.4.0

func (s *Store) CreatePaymentOrder(userID, planID int64, amountRub int) (*model.PaymentOrder, error)

func (*Store) CreateSession

func (s *Store) CreateSession(adminID int64, ttl time.Duration) (string, error)

CreateSession issues a new opaque session token for an admin and stores only its HMAC hash. The raw token is returned to set as a cookie.

func (*Store) CreateUser

func (s *Store) CreateUser(name, uuid, password, subToken string, dataLimit, expireAt int64, deviceLimit int) (*model.User, error)

CreateUser inserts a user with one credential set (UUID for VLESS, password for Trojan + Hysteria2), a subscription token, and optional quota/expiry.

func (*Store) DeleteSession

func (s *Store) DeleteSession(token string) error

DeleteSession revokes a session by its raw token.

func (*Store) DeleteSessionsForAdmin added in v0.4.0

func (s *Store) DeleteSessionsForAdmin(adminID int64) error

DeleteSessionsForAdmin revokes every session for an admin.

func (*Store) DeleteSessionsForAdminExcept

func (s *Store) DeleteSessionsForAdminExcept(adminID int64, keepToken string) error

DeleteSessionsForAdminExcept revokes every session belonging to an admin except the one identified by keepToken — used after a credential change so a previously stolen cookie can't outlive the change, while the admin doing the change stays logged in.

func (*Store) DeleteTariffPlan added in v0.4.0

func (s *Store) DeleteTariffPlan(id int64) error

func (*Store) DeleteUser

func (s *Store) DeleteUser(id int64) error

DeleteUser removes a user.

func (*Store) DeleteUsers added in v0.7.0

func (s *Store) DeleteUsers(ids []int64) (int64, error)

DeleteUsers removes many users in one statement, returning how many were deleted.

func (*Store) GetAdminAuth

func (s *Store) GetAdminAuth(username string) (id int64, hash string, err error)

GetAdminAuth returns the admin id and password hash for a username.

func (*Store) GetAdminHash

func (s *Store) GetAdminHash(id int64) (string, error)

GetAdminHash returns an admin's current password hash by id (for re-authenticating a credential change against the current password).

func (*Store) GetPaymentOrder added in v0.4.0

func (s *Store) GetPaymentOrder(id int64) (*model.PaymentOrder, error)

func (*Store) GetPaymentOrderByProvider added in v0.6.0

func (s *Store) GetPaymentOrderByProvider(provider, providerID string) (*model.PaymentOrder, error)

GetPaymentOrderByProvider finds a pending-or-any order by its external id.

func (*Store) GetSettings

func (s *Store) GetSettings() (*model.Settings, error)

GetSettings returns the singleton settings row.

func (*Store) GetTariffPlan added in v0.4.0

func (s *Store) GetTariffPlan(id int64) (*model.TariffPlan, error)

func (*Store) GetUser added in v0.3.0

func (s *Store) GetUser(id int64) (*model.User, error)

GetUser returns one user by id.

func (*Store) GetUserBySubToken

func (s *Store) GetUserBySubToken(token string) (*model.User, error)

GetUserBySubToken resolves a subscription token to its user.

func (*Store) GetUserByTelegramChatID added in v0.3.0

func (s *Store) GetUserByTelegramChatID(chatID int64) (*model.User, error)

GetUserByTelegramChatID resolves a linked Telegram chat to its VPN user.

func (*Store) GetUserByTgLinkCode added in v0.4.0

func (s *Store) GetUserByTgLinkCode(code string) (*model.User, error)

GetUserByTgLinkCode resolves a pending one-time Telegram bind code to its user, rejecting codes that are blank, unknown, or expired.

func (*Store) ListPaymentOrders added in v0.4.0

func (s *Store) ListPaymentOrders(status string, limit int) ([]model.PaymentOrder, error)

func (*Store) ListTariffPlans added in v0.4.0

func (s *Store) ListTariffPlans(includeDisabled bool) ([]model.TariffPlan, error)

ListTariffPlans returns plans sorted for display.

func (*Store) ListUsers

func (s *Store) ListUsers() ([]model.User, error)

ListUsers returns all users, newest first.

func (*Store) LookupSession

func (s *Store) LookupSession(token string) (adminID int64, username string, ok bool)

LookupSession resolves a raw session token to its admin. Expired sessions are deleted and treated as invalid.

func (*Store) MarkConfigApplied

func (s *Store) MarkConfigApplied() error

MarkConfigApplied bumps the config revision and clears any prior error.

func (*Store) MustChangePassword

func (s *Store) MustChangePassword() (bool, error)

MustChangePassword reports whether the admin must replace the default password before the rest of the panel unlocks (set at first-run bootstrap, cleared on the first password change).

func (*Store) PendingProviderOrders added in v0.6.0

func (s *Store) PendingProviderOrders(limit int) ([]model.PaymentOrder, error)

PendingProviderOrders returns pending orders that were started through a payment provider (for the polling fallback). Stale ones (older than maxAge seconds) are skipped — the caller marks them cancelled.

func (*Store) RecentConnections

func (s *Store) RecentConnections(userID int64, limit int) ([]model.Connection, error)

RecentConnections returns a user's source IPs, most recent first.

func (*Store) ReencryptSensitiveFields added in v0.4.0

func (s *Store) ReencryptSensitiveFields() error

ReencryptSensitiveFields migrates legacy plaintext secrets to enc:v1: at-rest blobs.

func (*Store) ResetDailyStats

func (s *Store) ResetDailyStats() error

ResetDailyStats clears the entire per-day traffic history.

func (*Store) ResetTraffic

func (s *Store) ResetTraffic(id, lastUp, lastDown int64) error

ResetTraffic zeroes a user's usage (so a "limited" user works again) and re-baselines the raw counters to the supplied live Xray values, so the next stats poll measures the delta from now. Passing 0/0 would make the poll re-add the user's whole lifetime Xray total straight back onto the freshly-zeroed usage. Does not touch enabled or expiry — an expired user stays expired.

func (*Store) ResetUserQuota

func (s *Store) ResetUserQuota(id, now, lastUp, lastDown int64) error

ResetUserQuota zeroes a user's usage and records the reset time (automatic reset scheduler). It re-baselines the raw counters to the supplied live Xray values so the next stats poll measures the delta from now — passing 0/0 would make the poll re-add the whole lifetime total back. enabled/expiry untouched; status is derived on read.

func (*Store) SaveTariffPlan added in v0.4.0

func (s *Store) SaveTariffPlan(p *model.TariffPlan) error

func (*Store) SetACMEProvider

func (s *Store) SetACMEProvider(provider, eabKID, eabHMAC string) error

SetACMEProvider persists the ACME CA selection and (for ZeroSSL) the External Account Binding credentials. An empty provider defaults to "letsencrypt".

func (*Store) SetAdminEvents added in v0.7.0

func (s *Store) SetAdminEvents(mask int64) error

SetAdminEvents persists the admin notification bitmask (model.AdminEvent* flags).

func (*Store) SetAntiDPI

func (s *Store) SetAntiDPI(tlsFragment, tlsMin13, blockQUIC bool, realityMaxTimeDiff int) error

SetAntiDPI persists the anti-DPI transport-hardening settings (Settings → Подключения): client-config shaping (TLS fragmentation, QUIC block) and the server-inbound knobs (TLS 1.3 floor, REALITY anti-replay window + donor port).

func (*Store) SetBillingSettings added in v0.4.0

func (s *Store) SetBillingSettings(st *model.Settings) error

func (*Store) SetConfigError

func (s *Store) SetConfigError(msg string) error

SetConfigError records the last failed config-apply error.

func (*Store) SetDecoyTemplate

func (s *Store) SetDecoyTemplate(name string) error

SetDecoyTemplate persists the masquerade (decoy) template slug.

func (*Store) SetFingerprints

func (s *Store) SetFingerprints(vless, trojan, reality string) error

SetFingerprints persists the per-connection uTLS fingerprints used in links.

func (*Store) SetHysteriaPorts

func (s *Store) SetHysteriaPorts(port, hopStart, hopEnd int, interval string) error

SetHysteriaPorts persists the Hysteria2 base port, hop range, and hop interval.

func (*Store) SetMustChangePassword

func (s *Store) SetMustChangePassword(must bool) error

SetMustChangePassword sets or clears the forced-password-change gate.

func (*Store) SetOpera

func (s *Store) SetOpera(enabled bool, country string, port int) error

SetOpera persists the Opera VPN egress settings (enable flag, region, and the local proxy port the opera-proxy helper listens on).

func (*Store) SetPanelName added in v0.5.0

func (s *Store) SetPanelName(name string) error

func (*Store) SetPanelTheme added in v0.5.0

func (s *Store) SetPanelTheme(themeJSON string) error

func (*Store) SetPaymentOrderProvider added in v0.6.0

func (s *Store) SetPaymentOrderProvider(id int64, provider, providerID, payURL string) error

SetPaymentOrderProvider links an order to an external provider payment.

func (*Store) SetPaymentOrderStatus added in v0.4.0

func (s *Store) SetPaymentOrderStatus(id int64, status string, paidAt int64) error

func (*Store) SetPaymentSettings added in v0.6.0

func (s *Store) SetPaymentSettings(st *model.Settings) error

SetPaymentSettings persists the payment-provider config (secrets encrypted).

func (*Store) SetPaymentWebhookSecret added in v0.6.0

func (s *Store) SetPaymentWebhookSecret(secret string) error

SetPaymentWebhookSecret stores the random webhook URL segment.

func (*Store) SetProtocolEnabled

func (s *Store) SetProtocolEnabled(name string, enabled bool) error

SetProtocolEnabled flips a single protocol's on/off toggle.

func (*Store) SetProxyMode

func (s *Store) SetProxyMode(enabled bool, typ string, port int, user, pass string) error

SetProxyMode persists the forward-proxy inbound configuration.

func (*Store) SetRealityKeys

func (s *Store) SetRealityKeys(priv, pub, shortID, serviceName string) error

SetRealityKeys persists a freshly generated REALITY keypair, shortId, and gRPC service name.

func (*Store) SetRealityPorts

func (s *Store) SetRealityPorts(port int, dest string) error

SetRealityPorts persists the REALITY port and destination (SNI/serverName).

func (*Store) SetResetPeriod

func (s *Store) SetResetPeriod(id int64, period string, now int64) error

SetResetPeriod sets a user's automatic quota-reset period and anchors the cycle at now.

func (*Store) SetRoutingConfig

func (s *Store) SetRoutingConfig(cfg model.RoutingConfig) error

SetRoutingConfig persists the structured routing configuration as JSON.

func (*Store) SetSecretPath

func (s *Store) SetSecretPath(p string) error

SetSecretPath persists the hidden panel path segment.

func (*Store) SetSetupDone

func (s *Store) SetSetupDone(done bool) error

SetSetupDone marks the first-run wizard as completed.

func (*Store) SetSubSettings

func (s *Store) SetSubSettings(st *model.Settings) error

SetSubSettings persists the subscription delivery settings.

func (*Store) SetSubToken added in v0.3.0

func (s *Store) SetSubToken(id int64, token string) error

SetSubToken replaces a user's subscription capability token. The old URL stops working immediately; protocol credentials (UUID/password) are unchanged.

func (*Store) SetTLS

func (s *Store) SetTLS(host, sni, mode, certPath, keyPath string) error

SetTLS persists host/SNI/cert configuration (used on first boot).

func (*Store) SetTLSMode

func (s *Store) SetTLSMode(mode, host, sni, acmeEmail string) error

SetTLSMode persists the TLS mode, domain (host), SNI and ACME e-mail.

func (*Store) SetTelegramBot added in v0.2.0

func (s *Store) SetTelegramBot(enabled bool, token, cron string) error

SetTelegramBot persists the bot's enable flag, token, and backup schedule (a 5-field cron expression in the operator timezone; empty disables scheduling).

func (*Store) SetTelegramChats added in v0.2.0

func (s *Store) SetTelegramChats(csv string) error

SetTelegramChats replaces the comma-separated set of authorized chat IDs.

func (*Store) SetTelegramLinkCode added in v0.2.0

func (s *Store) SetTelegramLinkCode(code string) error

SetTelegramLinkCode stores (or clears, with "") the pending one-time linking code.

func (*Store) SetTelegramUserBot added in v0.3.0

func (s *Store) SetTelegramUserBot(enabled bool, token string, regEnabled bool) error

SetTelegramUserBot persists the public user bot's enable flag, token, and the self-registration toggle.

func (*Store) SetTimezone

func (s *Store) SetTimezone(tz string) error

SetTimezone persists the operator's IANA timezone (e.g. "Europe/Moscow").

func (*Store) SetUserEnabled

func (s *Store) SetUserEnabled(id int64, enabled bool) error

SetUserEnabled sets the independent manual on/off flag. Expiry/quota are separate and never change this.

func (*Store) SetUserLimits

func (s *Store) SetUserLimits(id, dataLimit, expireAt int64, deviceLimit int) error

SetUserLimits sets the data limit (bytes), expiry (unix, 0 = none), and the simultaneous device cap (0 = unlimited). Does not touch the manual enabled flag; status is derived on read.

func (*Store) SetUserName

func (s *Store) SetUserName(id int64, name string) error

SetUserName updates a user's display name.

func (*Store) SetUserPlan added in v0.4.0

func (s *Store) SetUserPlan(userID, planID int64, trialUsed bool) error

func (*Store) SetUserTelegramChat added in v0.3.0

func (s *Store) SetUserTelegramChat(userID, chatID int64) error

SetUserTelegramChat links a Telegram chat to a VPN user, first detaching the chat from any other user (one chat ⇒ at most one account).

func (*Store) SetUserTgLinkCode added in v0.4.0

func (s *Store) SetUserTgLinkCode(userID int64, code string) error

SetUserTgLinkCode stores (or clears, with "") a user's pending Telegram bind code, stamping the issue time so it can expire.

func (*Store) SetUsersEnabled added in v0.7.0

func (s *Store) SetUsersEnabled(ids []int64, enabled bool) (int64, error)

SetUsersEnabled flips the manual enabled flag for many users in one statement, returning how many rows changed. Empty ids is a no-op.

func (*Store) SetWSPath

func (s *Store) SetWSPath(p string) error

SetWSPath persists the Trojan-WS path.

func (*Store) SetWarp

func (s *Store) SetWarp(st *model.Settings) error

SetWarp persists the WARP enabled flag plus the provisioned account fields.

func (*Store) SetXrayDNS

func (s *Store) SetXrayDNS(dns string) error

SetXrayDNS persists the operator's Xray DNS servers.

func (*Store) StatsByUser

func (s *Store) StatsByUser(from, to string) ([]model.UserTotal, error)

StatsByUser returns each user's traffic total over the period (users with no traffic appear with zeros), busiest first.

func (*Store) StatsSeries

func (s *Store) StatsSeries(userID int64, from, to string) ([]model.DailyPoint, error)

StatsSeries returns per-day totals between from and to (inclusive, YYYY-MM-DD). userID == 0 aggregates across all users.

func (*Store) TouchLastSeen

func (s *Store) TouchLastSeen(userID, ts int64) error

TouchLastSeen updates a user's last activity time (used by the poller too).

func (*Store) UpdateAdminPassword

func (s *Store) UpdateAdminPassword(id int64, passwordHash string) error

UpdateAdminPassword replaces an admin's password hash.

func (*Store) UpdateAdminUsername

func (s *Store) UpdateAdminUsername(id int64, username string) error

UpdateAdminUsername changes an admin's login name.

func (*Store) UpdateTraffic

func (s *Store) UpdateTraffic(id, addUp, addDown, lastUp, lastDown int64) error

UpdateTraffic adds deltas to lifetime totals and records the raw counters.

func (*Store) UsersWithExpiredPlan added in v0.4.0

func (s *Store) UsersWithExpiredPlan(now int64) ([]model.User, error)

func (*Store) WorkingUsers

func (s *Store) WorkingUsers(now int64) ([]model.User, error)

WorkingUsers returns users that should be in the proxy config right now: manually enabled AND not expired AND within their data limit AND within their device limit. enabled is an independent manual flag — expiry/quota/devices never change it, they just exclude the user from the config here.

Jump to

Keyboard shortcuts

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