Documentation
¶
Overview ¶
Package store owns the panel's database, embedded migrations, and the plain-SQL queries the other modules use.
Index ¶
- Constants
- Variables
- func AWGHwidHash(deviceID string) []byte
- func Clip(s string, n int) string
- func HWIDHash(userID, canonHWID string) []byte
- func LinkModeOf(stored string) string
- func NewID(prefix string) string
- func RetainedKeyAAD(profileID, nodeID string) string
- func SchemaVersions(ctx context.Context, path string) (db, binary int64, err error)
- func WithAuditSource(ctx context.Context, source string) context.Context
- type APIToken
- type AWGDeviceAdd
- type AWGImplicitWant
- type AWGIssue
- type Access
- func (a Access) AWGDevice(ctx context.Context, deviceID string) (AccessAWGDevice, error)
- func (a Access) AWGDeviceScope(ctx context.Context, deviceID string) (AccessAWGDeviceScope, error)
- func (a Access) AWGDevices(ctx context.Context, userID string) ([]AccessAWGDevice, error)
- func (a Access) AWGDevicesPerProfile(ctx context.Context, groupID, userID string) (map[string]int, error)
- func (a Access) AddAWGDevice(ctx context.Context, add AWGDeviceAdd, now time.Time, issue AWGIssue) (int, error)
- func (a Access) AddUsage(ctx context.Context, id string, bytes uint64) error
- func (a Access) BlockDevice(ctx context.Context, id string, now time.Time) (string, error)
- func (a Access) BlockedDevices(ctx context.Context, userID string) ([]AccessBlockedDevice, error)
- func (a Access) BumpProfileEpoch(ctx context.Context, profileID string) error
- func (a Access) CreateGroup(ctx context.Context, g AccessGroup) error
- func (a Access) CreateInbound(ctx context.Context, i AccessInbound) error
- func (a Access) CreateProfile(ctx context.Context, p AccessProfile) error
- func (a Access) CreateUser(ctx context.Context, u AccessUser, dev AccessDevice, creds []AccessCred) error
- func (a Access) DailyTraffic(ctx context.Context, userID string, from time.Time) (map[int64]uint64, error)
- func (a Access) DeleteGroup(ctx context.Context, id, moveTo string) error
- func (a Access) DeleteInbound(ctx context.Context, id string, now time.Time, ...) error
- func (a Access) DeleteProfile(ctx context.Context, id string, now time.Time) error
- func (a Access) DeleteUsers(ctx context.Context, ids []string) (int, error)
- func (a Access) DesiredCreds(ctx context.Context, nodeID string) ([]AccessDesiredCred, error)
- func (a Access) Device(ctx context.Context, id string) (AccessDevice, error)
- func (a Access) DeviceCounts(ctx context.Context, ids []string) (map[string]int, error)
- func (a Access) Devices(ctx context.Context, userID string) ([]AccessDevice, error)
- func (a Access) EnsureLinkAWGCreds(ctx context.Context, dev AccessDevice, limit int, now time.Time, ...) (LinkDeviceResult, error)
- func (a Access) EnsureLinkDevice(ctx context.Context, dev AccessDevice, limit int, now time.Time, ...) (LinkDeviceResult, error)
- func (a Access) ExistingNodeIDs(ctx context.Context, ids []string) (map[string]bool, error)
- func (a Access) Group(ctx context.Context, id string) (AccessGroup, error)
- func (a Access) Groups(ctx context.Context) ([]AccessGroup, error)
- func (a Access) HasUserWithTokenHash(ctx context.Context, hash []byte) (bool, error)
- func (a Access) Inbound(ctx context.Context, id string) (AccessInbound, error)
- func (a Access) InboundsFull(ctx context.Context, nodeID string) ([]AccessInboundFull, error)
- func (a Access) InboundsOfNode(ctx context.Context, nodeID string) ([]AccessInbound, error)
- func (a Access) InboundsOfProfile(ctx context.Context, profileID string) ([]AccessInbound, error)
- func (a Access) ListUsers(ctx context.Context, q AccessUserQuery) ([]AccessUser, bool, AccessUserCounts, error)
- func (a Access) Node(ctx context.Context, id string) (AccessNode, error)
- func (a Access) NodeTraffic(ctx context.Context, userID string, since time.Time) ([]AccessNodeTraffic, error)
- func (a Access) Nodes(ctx context.Context) ([]AccessNode, error)
- func (a Access) Profile(ctx context.Context, id string) (AccessProfile, error)
- func (a Access) ProfileHasPeers(ctx context.Context, profileID string) (bool, error)
- func (a Access) ProfileLiveAWG(ctx context.Context, profileID string, limit int) (n int, users []string, err error)
- func (a Access) ProfileUsers(ctx context.Context, profileID string, happ, amnezia bool) ([]AccessBrief, error)
- func (a Access) Profiles(ctx context.Context) ([]AccessProfile, error)
- func (a Access) RecordDeviceConfig(ctx context.Context, credID string, epoch *int64, sig map[string]string) error
- func (a Access) RenameDevice(ctx context.Context, deviceID, label string) error
- func (a Access) ResetUserPeriod(ctx context.Context, id string, oldPeriodStart, periodStart time.Time, ...) error
- func (a Access) ResetUserTraffic(ctx context.Context, id, status string) error
- func (a Access) RetainedKey(ctx context.Context, profileID, nodeID string) (AccessRetainedKey, error)
- func (a Access) RevokeDevice(ctx context.Context, id string, now time.Time) (string, error)
- func (a Access) RotateAWGDevice(ctx context.Context, deviceID string, now time.Time, issue AWGIssue) (string, error)
- func (a Access) SetInboundBuildError(ctx context.Context, id, msg string, now time.Time) error
- func (a Access) SetSubToken(ctx context.Context, id string, hash, enc []byte) error
- func (a Access) SetUserExpiry(ctx context.Context, id string, t time.Time) error
- func (a Access) SetUserStatus(ctx context.Context, id, status string) error
- func (a Access) SetUsersDisabled(ctx context.Context, ids []string, disabled bool) error
- func (a Access) SharedLinkUsers(ctx context.Context) (int, error)
- func (a Access) SubscriptionData(ctx context.Context, userID, groupID string, since time.Time, active bool, ...) (SubscriptionData, error)
- func (a Access) TouchDevice(ctx context.Context, id string, now, not time.Time, osVersion, client string) error
- func (a Access) UnblockDevice(ctx context.Context, id string) (string, error)
- func (a Access) UpdateGroup(ctx context.Context, id string, name *string, profileIDs *[]string, ...) error
- func (a Access) UpdateInbound(ctx context.Context, i AccessInbound, resetState bool, now time.Time) error
- func (a Access) UpdateProfile(ctx context.Context, p AccessProfile, expectedVersion uint32, ...) (AccessProfile, error)
- func (a Access) UpdateUser(ctx context.Context, u AccessUser, setNodes bool) error
- func (a Access) User(ctx context.Context, id string) (AccessUser, error)
- func (a Access) UserByTokenHash(ctx context.Context, hash []byte) (AccessUser, error)
- func (a Access) UserStates(ctx context.Context, ids []string) ([]AccessUserState, error)
- func (a Access) UsersByIDs(ctx context.Context, ids []string) ([]AccessUser, error)
- func (a Access) UsersProtocolsSince(ctx context.Context, ids []string, since time.Time) (map[string][]string, error)
- type AccessAWGDevice
- type AccessAWGDeviceScope
- type AccessBlockedDevice
- type AccessBrief
- type AccessCred
- type AccessDesiredCred
- type AccessDevice
- type AccessGroup
- type AccessInbound
- type AccessInboundFull
- type AccessLimitError
- type AccessNode
- type AccessNodeTraffic
- type AccessProfile
- type AccessRetainedKey
- type AccessUser
- type AccessUserCounts
- type AccessUserQuery
- type AccessUserSort
- type AccessUserState
- type Admin
- type AdminLogin
- type AuditEntry
- type AuditQuery
- type AuditRow
- type AuthCeremony
- type AwgPrepareRow
- type BlocklistCheck
- type CARow
- type CertRow
- type CertState
- type CheckSample
- type CodeMatch
- type CountryCheck
- type DNS
- func (d DNS) Create(ctx context.Context, p DNSPreset) error
- func (d DNS) DefaultID(ctx context.Context) (string, error)
- func (d DNS) Delete(ctx context.Context, id string) error
- func (d DNS) EffectiveData(ctx context.Context, userID string) (DNSEffectiveData, error)
- func (d DNS) Exists(ctx context.Context, id string) (bool, error)
- func (d DNS) Get(ctx context.Context, id string) (DNSPreset, error)
- func (d DNS) LinkOptions(ctx context.Context) ([]LinkDNSOption, error)
- func (d DNS) List(ctx context.Context) ([]DNSPreset, error)
- func (d DNS) Lookup(ctx context.Context) (DNSLookup, error)
- func (d DNS) NodeExists(ctx context.Context, nodeID string) (bool, error)
- func (d DNS) NodeName(ctx context.Context, nodeID string) (string, error)
- func (d DNS) NodeNames(ctx context.Context) (map[string]string, error)
- func (d DNS) NodeOptions(ctx context.Context) (map[string][]NodeDNSOption, error)
- func (d DNS) ResetUserNodeChoices(ctx context.Context, userID string) (int, error)
- func (d DNS) SetDefaultID(ctx context.Context, id string) error
- func (d DNS) SetLinkOptions(ctx context.Context, presetIDs []string, defaultID string) error
- func (d DNS) SetNodeOptions(ctx context.Context, nodeID string, presetIDs []string, defaultID string) error
- func (d DNS) SetUserLinkChoice(ctx context.Context, userID, presetID string, now time.Time) error
- func (d DNS) SetUserNodeChoice(ctx context.Context, userID, nodeID, presetID string, now time.Time) error
- func (d DNS) SubscriptionData(ctx context.Context, userID string) (DNSSubscriptionData, error)
- func (d DNS) Update(ctx context.Context, p DNSPreset) error
- func (d DNS) UserCounts(ctx context.Context) (map[string]int, error)
- func (d DNS) UserNodeChoices(ctx context.Context, userID string) (map[string]UserNodeDNS, error)
- func (d DNS) UserRefs(ctx context.Context, userID string) (own, group string, err error)
- type DNSEffectiveData
- type DNSLookup
- type DNSPreset
- type DNSSubscriptionData
- type DailyRow
- type DoctorAccept
- type DoctorRow
- type EngineRow
- type EnrollResult
- type EventFilter
- type EventRow
- type FleetCredRef
- type FleetHourRow
- type FleetInboundCert
- type FleetInboundRow
- type FleetLive
- type FleetSessionRef
- type FleetStatsIn
- type FleetStatsOut
- type FleetTop
- type FleetTraffic
- type GateRollback
- type HealthAWGSignal
- type HealthAlert
- type HealthDeviceLimitSignal
- type HealthNodeFlapSignal
- type HealthNodeHourSignal
- type HealthSignalBatch
- type HealthTorrentSignal
- type HealthUserSignal
- type HelloInfo
- type InboundApplied
- type LastUpdateRow
- type LinkDNSOption
- type LinkDeviceResult
- type LinkIssue
- type LoginFailure
- type MCPPlan
- type NodeDNSOption
- type NodeFactsRow
- type NodeHealthSummary
- type NodeLiveRow
- type NodePatch
- type NodeProvisionEvent
- type NodeProvisionJob
- type NodeRow
- type NodeServerAccess
- type NodeUpdateScheduleRow
- type PanelBackupSettings
- type Passkey
- type PasswordCred
- type PlanStateError
- type PortCheck
- type ProbeCredIssue
- type ProbeCredRow
- type RecoveryTokenOffer
- type RolloutRow
- type Session
- type SetupTokenOffer
- type StepRow
- type Stmt
- type StmtResult
- type Store
- func (s *Store) APITokenBySecretHash(ctx context.Context, h []byte) (APIToken, error)
- func (s *Store) AcceptDoctor(ctx context.Context, a DoctorAccept) (bool, error)
- func (s *Store) Access() Access
- func (s *Store) ActiveAlerts(ctx context.Context) ([]HealthAlert, error)
- func (s *Store) ActiveRollout(ctx context.Context) (RolloutRow, error)
- func (s *Store) AddNodeToRunningRollout(ctx context.Context, rolloutID, version string, built int64, stage int, ...) error
- func (s *Store) AddPasskey(ctx context.Context, p Passkey, now time.Time) error
- func (s *Store) AddPassword(ctx context.Context, c PasswordCred, now time.Time) error
- func (s *Store) Admin(ctx context.Context, id string) (Admin, error)
- func (s *Store) AdminCount(ctx context.Context) (int, error)
- func (s *Store) AdminHasPassword(ctx context.Context, adminID string) (bool, error)
- func (s *Store) AdminLogins(ctx context.Context) ([]AdminLogin, error)
- func (s *Store) AdvanceTOTPStep(ctx context.Context, adminID string, step int64) (bool, error)
- func (s *Store) AlertCounts(ctx context.Context, now time.Time) (active, critical int, err error)
- func (s *Store) AlertHistory(ctx context.Context, since time.Time, nodeID string, limit int) ([]HealthAlert, error)
- func (s *Store) AnyPassword(ctx context.Context) (bool, error)
- func (s *Store) ApproveMCPPlanWithSecret(ctx context.Context, id, adminID string, secret []byte, now time.Time) (MCPPlan, error)
- func (s *Store) Audit(ctx context.Context, now time.Time, e AuditEntry) error
- func (s *Store) AwgPrepareFinish(ctx context.Context, nodeID string, ok bool, at int64, code, reason string) (switched bool, err error)
- func (s *Store) AwgPrepareStarted(ctx context.Context, nodeID string, since int64) error
- func (s *Store) BeginApply(ctx context.Context, id, tokenID, tool string, paramsHash, confirmHash []byte, ...) (MCPPlan, error)
- func (s *Store) BindTelegramChat(ctx context.Context, adminID string, chatID int64, now time.Time) error
- func (s *Store) BlocklistHistory(ctx context.Context, since time.Time) ([]BlocklistCheck, error)
- func (s *Store) CAs(ctx context.Context) ([]CARow, error)
- func (s *Store) CertStatus(ctx context.Context, serial string, now time.Time) (CertState, error)
- func (s *Store) CheckSetupToken(ctx context.Context, hash []byte, now time.Time) error
- func (s *Store) ClaimNodeProvisionJob(ctx context.Context, now time.Time) (NodeProvisionJob, bool, error)
- func (s *Store) ClearLoginFailures(ctx context.Context, login string) error
- func (s *Store) ClearPendingNodeServerPassword(ctx context.Context, nodeID string) error
- func (s *Store) ClearTelegramBot(ctx context.Context) (dropped int, err error)
- func (s *Store) Close() error
- func (s *Store) CommitPendingNodeServerPassword(ctx context.Context, nodeID string, encryptedCurrent []byte, ownerChosen bool, ...) error
- func (s *Store) CompleteNodeProvisionJob(ctx context.Context, id string, access NodeServerAccess, now time.Time) error
- func (s *Store) ConsumeAuthCeremony(ctx context.Context, id string) (bool, error)
- func (s *Store) ConsumeRecoveryToken(ctx context.Context, hash []byte, now time.Time) (bool, error)
- func (s *Store) CountryVerdictChanges(ctx context.Context, country string, since time.Time) ([]CountryCheck, error)
- func (s *Store) CreateAPIToken(ctx context.Context, t APIToken, secretHash []byte) error
- func (s *Store) CreateEnrollment(ctx context.Context, n *NodeRow, nodeID string, tokenHash []byte, ...) (NodeRow, error)
- func (s *Store) CreateFirstAdmin(ctx context.Context, tokenHash []byte, now time.Time, a Admin, p Passkey) error
- func (s *Store) CreateFirstAdminPassword(ctx context.Context, tokenHash []byte, now time.Time, a Admin, c PasswordCred) error
- func (s *Store) CreateMCPPlan(ctx context.Context, p MCPPlan, maxOpenPerToken, maxAwaiting int) error
- func (s *Store) CreateNodeProvisionJob(ctx context.Context, job NodeProvisionJob) error
- func (s *Store) CreatePasswordSession(ctx context.Context, sess Session, checked PasswordCred) error
- func (s *Store) CreateRollout(ctx context.Context, r RolloutRow, steps []StepRow) error
- func (s *Store) CreateRolloutAndClearSchedules(ctx context.Context, r RolloutRow, steps []StepRow, nodeIDs []string) error
- func (s *Store) CreateScheduledRollout(ctx context.Context, r RolloutRow, steps []StepRow, ...) error
- func (s *Store) CreateSession(ctx context.Context, sess Session) error
- func (s *Store) CreateWarpAccount(ctx context.Context, a WarpAccountRow) error
- func (s *Store) DNS() DNS
- func (s *Store) DailyRows(ctx context.Context, inboundID string) ([]DailyRow, error)
- func (s *Store) DecideMCPPlan(ctx context.Context, id, adminID string, approve bool, now time.Time) (MCPPlan, error)
- func (s *Store) DeleteAdminSession(ctx context.Context, adminID string, tokenHash []byte) (bool, error)
- func (s *Store) DeleteBlocklistChecks(ctx context.Context) error
- func (s *Store) DeleteNodeUpdateSchedule(ctx context.Context, nodeID string) (bool, error)
- func (s *Store) DeleteNodeUpdateScheduleIfMatches(ctx context.Context, r NodeUpdateScheduleRow) (bool, error)
- func (s *Store) DeleteOtherSessions(ctx context.Context, adminID string, keep []byte) (int, error)
- func (s *Store) DeletePasskey(ctx context.Context, adminID, id string) error
- func (s *Store) DeleteSession(ctx context.Context, tokenHash []byte) error
- func (s *Store) DeleteSettings(ctx context.Context, keys ...string) error
- func (s *Store) DeleteTSPUChecks(ctx context.Context) error
- func (s *Store) DeleteWarpAccount(ctx context.Context, nodeID string) error
- func (s *Store) DoctorAccepts(ctx context.Context, nodeID string) ([]DoctorAccept, error)
- func (s *Store) DoctorResults(ctx context.Context, nodeID string) ([]DoctorRow, error)
- func (s *Store) DownloadStep(ctx context.Context, nodeID string) ([]byte, string, error)
- func (s *Store) DropStaleAccepts(ctx context.Context, nodeID string) error
- func (s *Store) DueNodeUpdateSchedules(ctx context.Context, now time.Time) ([]NodeUpdateScheduleRow, error)
- func (s *Store) Enroll(ctx context.Context, tokenHash, keyHash []byte, now time.Time, ...) (EnrollResult, error)
- func (s *Store) Events(ctx context.Context, f EventFilter) (out []EventRow, hasMore bool, err error)
- func (s *Store) ExpireMCPPlans(ctx context.Context, now time.Time) (int, error)
- func (s *Store) FailAuthCeremony(ctx context.Context, id string, maxTries int) (bool, error)
- func (s *Store) FailWithheldInbounds(ctx context.Context, nodeID string, ids []string, reason string, now time.Time) error
- func (s *Store) FinishApply(ctx context.Context, id string, ok bool, ...) error
- func (s *Store) FinishCancelledNodeProvisionJob(ctx context.Context, id string, now time.Time) (bool, error)
- func (s *Store) FleetDeviceModels(ctx context.Context, ids []string) (map[string]string, error)
- func (s *Store) FleetEnabledInbounds(ctx context.Context) (map[string]map[string]string, error)
- func (s *Store) FleetHours(ctx context.Context, sinceHour int64) ([]FleetHourRow, error)
- func (s *Store) FleetInbound(ctx context.Context, inboundID string) (FleetInboundRow, error)
- func (s *Store) FleetInbounds(ctx context.Context, nodeID string, onlyEnabled bool) ([]FleetInboundRow, error)
- func (s *Store) FleetNodeProtocols(ctx context.Context) (map[string][]string, error)
- func (s *Store) FleetTopUsers(ctx context.Context, nodeID string, sinceHour int64, limit int) ([]FleetTop, error)
- func (s *Store) FleetUserNames(ctx context.Context, ids []string) (map[string]string, error)
- func (s *Store) ForgetNodeServerAccess(ctx context.Context, nodeID string) error
- func (s *Store) GateRollbacks(ctx context.Context) (map[string]GateRollback, error)
- func (s *Store) GetAPIToken(ctx context.Context, id string) (APIToken, error)
- func (s *Store) GetAuthCeremony(ctx context.Context, id string, now time.Time) (AuthCeremony, error)
- func (s *Store) GetMCPPlan(ctx context.Context, id string) (MCPPlan, error)
- func (s *Store) HasUsers(ctx context.Context) (bool, error)
- func (s *Store) HealthAlert(ctx context.Context, id string) (HealthAlert, error)
- func (s *Store) HealthSignals(ctx context.Context, now time.Time) (HealthSignalBatch, error)
- func (s *Store) IngestEvent(ctx context.Context, nodeID, instance string, seq uint64, now time.Time, ...) (dup bool, err error)
- func (s *Store) IngestStats(ctx context.Context, in FleetStatsIn) (FleetStatsOut, error)
- func (s *Store) InsertBlocklistChecks(ctx context.Context, rows []BlocklistCheck) error
- func (s *Store) InsertCA(ctx context.Context, c CARow, now time.Time) error
- func (s *Store) InsertCountryChecks(ctx context.Context, rows []CountryCheck) error
- func (s *Store) InsertEvent(ctx context.Context, e EventRow) error
- func (s *Store) InsertProbeCred(ctx context.Context, r ProbeCredRow, now time.Time) error
- func (s *Store) InsertProbeCredIdx(ctx context.Context, inboundID, profileID string, maxIdx int, now time.Time, ...) error
- func (s *Store) InsertResolvedAlert(ctx context.Context, a HealthAlert) error
- func (s *Store) InsertSample(ctx context.Context, c CheckSample) error
- func (s *Store) InsertTSPUChecks(ctx context.Context, rows []TSPUCheck) error
- func (s *Store) LastAuditByNode(ctx context.Context, action string) (map[string]time.Time, error)
- func (s *Store) LastCountryCheckAt(ctx context.Context) (time.Time, error)
- func (s *Store) LastNodeEventCode(ctx context.Context, nodeID string, codes ...string) (string, error)
- func (s *Store) LastTSPUCheckAt(ctx context.Context, vantage string) (time.Time, error)
- func (s *Store) LatestRollout(ctx context.Context) (RolloutRow, error)
- func (s *Store) LinkCertificates(ctx context.Context, nodeID string, now time.Time) ([]CertRow, error)
- func (s *Store) ListAPITokens(ctx context.Context) ([]APIToken, error)
- func (s *Store) ListApprovals(ctx context.Context, now time.Time, awaitingOnly bool, historyLimit int) (rows []MCPPlan, awaiting int, err error)
- func (s *Store) ListAudit(ctx context.Context, source string, beforeID int64, limit int) ([]AuditRow, error)
- func (s *Store) ListAuditQuery(ctx context.Context, q AuditQuery) ([]AuditRow, error)
- func (s *Store) LoginFailures(ctx context.Context, login string, now time.Time, window time.Duration) (LoginFailure, error)
- func (s *Store) MCPPlanByConfirm(ctx context.Context, tokenID string, confirmHash []byte) (MCPPlan, error)
- func (s *Store) MarkNodeUpdateSchedulesMissed(ctx context.Context, cutoff, now time.Time) (int64, error)
- func (s *Store) MarkStepSent(ctx context.Context, x *StepRow) (bool, error)
- func (s *Store) MuteAlert(ctx context.Context, id string, until time.Time) (HealthAlert, error)
- func (s *Store) Node(ctx context.Context, id string) (NodeRow, error)
- func (s *Store) NodeApplied(ctx context.Context, id string, session uint64, drift bool, rev uint64, ...) error
- func (s *Store) NodeDecoyBundle(ctx context.Context, hash string) ([]byte, error)
- func (s *Store) NodeDesired(ctx context.Context, id string, rev uint64, hash string, digest []byte) error
- func (s *Store) NodeDisconnected(ctx context.Context, id string, session uint64, seen, now time.Time) error
- func (s *Store) NodeEventSince(ctx context.Context, nodeID, code string, since time.Time, toBuilt int64) (bool, error)
- func (s *Store) NodeFacts(ctx context.Context, id string) (NodeFactsRow, error)
- func (s *Store) NodeHello(ctx context.Context, id string, session uint64, h HelloInfo, now time.Time) (prev NodeRow, ackedSeq uint64, err error)
- func (s *Store) NodeInSync(ctx context.Context, id string, session uint64, rev uint64, hash string) error
- func (s *Store) NodeLive(ctx context.Context, now time.Time, nodeID string, view bool) ([]NodeLiveRow, error)
- func (s *Store) NodeProvisionEvents(ctx context.Context, jobID string, after int64, limit int) ([]NodeProvisionEvent, int64, error)
- func (s *Store) NodeProvisionJob(ctx context.Context, id string) (NodeProvisionJob, error)
- func (s *Store) NodeProvisionJobState(ctx context.Context, id string) (string, error)
- func (s *Store) NodeProvisionJobs(ctx context.Context, limit int) ([]NodeProvisionJob, error)
- func (s *Store) NodeProvisionJobsPending(ctx context.Context) (bool, error)
- func (s *Store) NodeProvisionJobsQueued(ctx context.Context) (bool, error)
- func (s *Store) NodeServerAccess(ctx context.Context, nodeID string) (NodeServerAccess, error)
- func (s *Store) NodeServerAccesses(ctx context.Context) ([]NodeServerAccess, error)
- func (s *Store) NodeUpdateSchedules(ctx context.Context) (map[string]NodeUpdateScheduleRow, error)
- func (s *Store) NodeWithSentDigest(ctx context.Context, id string) (NodeRow, []byte, error)
- func (s *Store) Nodes(ctx context.Context, includeRetired bool) ([]NodeRow, error)
- func (s *Store) OfferRecoveryToken(ctx context.Context, hash []byte, expires time.Time) (RecoveryTokenOffer, error)
- func (s *Store) OfferSetupToken(ctx context.Context, hash []byte, expires time.Time) (SetupTokenOffer, error)
- func (s *Store) OnlineDevices(ctx context.Context, now time.Time) ([][2]string, error)
- func (s *Store) OpenAlert(ctx context.Context, a HealthAlert, reopenWithin time.Duration, now time.Time) (out HealthAlert, reopened bool, err error)
- func (s *Store) PanelBackupSettings(ctx context.Context) (PanelBackupSettings, error)
- func (s *Store) PasskeyByCredentialID(ctx context.Context, credID []byte) (Passkey, error)
- func (s *Store) PasskeysByAdmin(ctx context.Context, adminID string) ([]Passkey, error)
- func (s *Store) PasswordByAdmin(ctx context.Context, adminID string) (PasswordCred, error)
- func (s *Store) PasswordByLogin(ctx context.Context, login string) (PasswordCred, error)
- func (s *Store) PendingEnrollmentExpiry(ctx context.Context, nodeID string, now time.Time) (time.Time, error)
- func (s *Store) PortChecks(ctx context.Context, nodeIDs ...string) ([]PortCheck, error)
- func (s *Store) ProbeCred(ctx context.Context, inboundID string) (ProbeCredRow, error)
- func (s *Store) PruneBlocklistChecks(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneCountryChecks(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneEvents(ctx context.Context, now time.Time, info, other time.Duration, batch int) (int64, error)
- func (s *Store) PruneHealth(ctx context.Context, now time.Time, samples, daily, alerts time.Duration) (int64, error)
- func (s *Store) PruneRevokedDevices(ctx context.Context, cutoff time.Time, batch int) (int64, error)
- func (s *Store) PruneRollouts(ctx context.Context, keep int, cutoff time.Time) (int64, error)
- func (s *Store) PruneTSPUChecks(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PurgeSessions(ctx context.Context, now time.Time, idle time.Duration) error
- func (s *Store) PutAuthCeremony(ctx context.Context, c AuthCeremony, now time.Time, maxPerSource, maxTotal int) error
- func (s *Store) PutDoctor(ctx context.Context, nodeID string, rows []DoctorRow, replace bool, ...) error
- func (s *Store) PutPortChecks(ctx context.Context, checks []PortCheck) error
- func (s *Store) PutSetupToken(ctx context.Context, hash []byte, expires time.Time) error
- func (s *Store) PutTCPChecks(ctx context.Context, nodeID string, checks []TCPCheck) error
- func (s *Store) RecentBlocklistChecks(ctx context.Context, nodeIDs ...string) ([]BlocklistCheck, error)
- func (s *Store) RecentCountryChecks(ctx context.Context, perNode int, nodeIDs ...string) ([]CountryCheck, error)
- func (s *Store) RecentSamples(ctx context.Context, inboundID string, n int) ([]CheckSample, error)
- func (s *Store) RecentTSPUChecks(ctx context.Context, nodeIDs ...string) ([]TSPUCheck, error)
- func (s *Store) RecordDeviceLimitReached(ctx context.Context, userID string, used, limit int, mode string, refused bool, ...) error
- func (s *Store) RecordLoginFailure(ctx context.Context, login string, now time.Time, maxFailures int, ...) (LoginFailure, error)
- func (s *Store) RecordPanelBackupRun(ctx context.Context, now time.Time, succeeded bool, errorCode string) error
- func (s *Store) RecoveryTokenLive(ctx context.Context, hash []byte, now time.Time) (bool, error)
- func (s *Store) ReleaseLease(ctx context.Context, name, holder string) error
- func (s *Store) RenewCert(ctx context.Context, c CertRow, fromSerial string, now time.Time, ...) error
- func (s *Store) ReplaceWarpAccount(ctx context.Context, a WarpAccountRow) error
- func (s *Store) RequestCancelNodeProvisionJob(ctx context.Context, id string, now time.Time) (state string, changed bool, err error)
- func (s *Store) RequeueNodeProvisionJobs(ctx context.Context, now time.Time) error
- func (s *Store) ResetPasswordLogin(ctx context.Context, c PasswordCred, create bool, clearLocks []string, ...) (int, error)
- func (s *Store) ResolveAlert(ctx context.Context, id, resolution string, now time.Time) (bool, error)
- func (s *Store) RetireNode(ctx context.Context, id string, now time.Time) error
- func (s *Store) RetryNodeProvisionJob(ctx context.Context, id, from string, secret []byte, now time.Time) error
- func (s *Store) RevokeAPIToken(ctx context.Context, id, by string, now time.Time) (APIToken, error)
- func (s *Store) Rollout(ctx context.Context, id string) (RolloutRow, error)
- func (s *Store) RolloutSteps(ctx context.Context, rolloutID string) ([]StepRow, error)
- func (s *Store) RollupDaily(ctx context.Context, now time.Time) error
- func (s *Store) SamplesSince(ctx context.Context, since time.Time) ([]CheckSample, error)
- func (s *Store) SavePanelBackupSettings(ctx context.Context, v PanelBackupSettings, now time.Time) error
- func (s *Store) SaveStep(ctx context.Context, x *StepRow) error
- func (s *Store) SaveSubscriptionSettings(ctx context.Context, kv map[string]string, mode string, now time.Time) (revoked int, err error)
- func (s *Store) SessionStepUp(ctx context.Context, tokenHash []byte, now time.Time) error
- func (s *Store) SessionWithAdmin(ctx context.Context, tokenHash []byte) (Session, Admin, error)
- func (s *Store) SessionsByAdmin(ctx context.Context, adminID string) ([]Session, error)
- func (s *Store) SetAwgPrepare(ctx context.Context, nodeID string, r AwgPrepareRow) error
- func (s *Store) SetBandwidthIfUnset(ctx context.Context, id string, mbps int) (bool, error)
- func (s *Store) SetInboundAwgHealth(ctx context.Context, nodeID, inboundID, healthJSON string, at time.Time) error
- func (s *Store) SetInboundCert(ctx context.Context, nodeID, inboundID, pin string, notAfter, now time.Time) error
- func (s *Store) SetLastUpdateIfNewer(ctx context.Context, nodeID string, l LastUpdateRow) error
- func (s *Store) SetNodeDecoyBundle(ctx context.Context, nodeID, hash string, archive []byte) (NodeRow, error)
- func (s *Store) SetNodeDecoyMode(ctx context.Context, nodeID, mode string) (NodeRow, error)
- func (s *Store) SetNodeUpdateSchedule(ctx context.Context, r NodeUpdateScheduleRow) error
- func (s *Store) SetNodesDecoyMode(ctx context.Context, nodeIDs []string, mode string) ([]NodeRow, error)
- func (s *Store) SetPasswordHash(ctx context.Context, adminID, hash string) error
- func (s *Store) SetPendingNodeServerPassword(ctx context.Context, nodeID string, encrypted []byte, generated bool, ...) error
- func (s *Store) SetRolloutStatus(ctx context.Context, id string, from []string, status, pauseKey string, ...) (bool, error)
- func (s *Store) SetSettingIfChanged(ctx context.Context, key, value string) error
- func (s *Store) SetSettings(ctx context.Context, kv map[string]string) error
- func (s *Store) SetSettingsIfAbsent(ctx context.Context, kv map[string]string) (map[string]string, error)
- func (s *Store) SetStepAnswer(ctx context.Context, nodeID, requestID, answer string) (bool, error)
- func (s *Store) SetTOTPSecret(ctx context.Context, adminID string, sealed []byte, step int64) error
- func (s *Store) SetTelegramBot(ctx context.Context, b TelegramBotRow, now time.Time) (dropped int, err error)
- func (s *Store) SetTelegramEnabled(ctx context.Context, adminID string, enabled bool) error
- func (s *Store) SetWarpAttention(ctx context.Context, nodeID, reason string, now time.Time) error
- func (s *Store) SetWarpEnabled(ctx context.Context, nodeID string, enabled bool, now time.Time) error
- func (s *Store) SetWarpHealth(ctx context.Context, nodeID, healthJSON string, at time.Time) error
- func (s *Store) Setting(ctx context.Context, key string) (string, error)
- func (s *Store) SettingValues(ctx context.Context, keys []string) (map[string]string, error)
- func (s *Store) SetupTokenStatus(ctx context.Context, now time.Time) (adminExists bool, expiry time.Time, tokenExists bool, err error)
- func (s *Store) SkipPendingSteps(ctx context.Context, rolloutID, errorKey string, now time.Time) error
- func (s *Store) SkipSeq(ctx context.Context, nodeID, instance string, seq uint64, now time.Time) error
- func (s *Store) SnapshotDatabase(ctx context.Context, path string) error
- func (s *Store) TCPChecks(ctx context.Context, nodeIDs ...string) ([]TCPCheck, error)
- func (s *Store) TSPUHistory(ctx context.Context, vantage string, perNode int, nodeIDs ...string) ([]TSPUCheck, error)
- func (s *Store) TSPUHistorySince(ctx context.Context, vantage string, since time.Time, perNode int, ...) ([]TSPUCheck, error)
- func (s *Store) TakeLease(ctx context.Context, name, holder string, ttl time.Duration, now time.Time) (bool, error)
- func (s *Store) TakeMCPPlanOwnerSecret(ctx context.Context, id, tokenID, tool string) ([]byte, error)
- func (s *Store) TelegramBot(ctx context.Context) (TelegramBotRow, error)
- func (s *Store) TelegramLink(ctx context.Context, adminID string) (TelegramLinkRow, error)
- func (s *Store) TelegramLinkByChat(ctx context.Context, chatID int64) (TelegramLinkRow, error)
- func (s *Store) TelegramLinks(ctx context.Context) ([]TelegramLinkRow, error)
- func (s *Store) TouchAPIToken(ctx context.Context, id string, now time.Time, ip, via string) error
- func (s *Store) TouchAlert(ctx context.Context, a HealthAlert, now time.Time) error
- func (s *Store) TouchPasskey(ctx context.Context, credID []byte, signCount uint32, flags byte, ...) error
- func (s *Store) TouchSession(ctx context.Context, tokenHash []byte, now time.Time) error
- func (s *Store) UnacceptDoctor(ctx context.Context, nodeID, checkID string) (bool, error)
- func (s *Store) UnlinkTelegram(ctx context.Context, adminID string) (bool, error)
- func (s *Store) UpdateNode(ctx context.Context, id string, p NodePatch) (NodeRow, error)
- func (s *Store) UpdateNodeDecoyAgentState(ctx context.Context, nodeID, mode, hash string) error
- func (s *Store) UpdateRunningNodeProvisionJob(ctx context.Context, id, state, phase, errorCode string, secret []byte, ...) error
- func (s *Store) UpdateRunningNodeProvisionJobWithEvent(ctx context.Context, id, state, phase, errorCode string, secret []byte, ...) error
- func (s *Store) UpdateWarpRefresh(ctx context.Context, nodeID string, r WarpRefresh, now time.Time) error
- func (s *Store) UpgradePasswordHash(ctx context.Context, adminID, oldHash, newHash string) (bool, error)
- func (s *Store) WarpAccount(ctx context.Context, nodeID string) (WarpAccountRow, error)
- func (s *Store) WarpAccounts(ctx context.Context) ([]WarpAccountRow, error)
- type SubscriptionData
- type TCPCheck
- type TSPUCheck
- type TelegramBotRow
- type TelegramLinkRow
- type UserNodeDNS
- type WarpAccountRow
- type WarpRefresh
Constants ¶
const ( // SettingLinkDeviceLimit is the setting that holds the mode (see subsettings, which also exposes it as // SubscriptionSettings.link_device_limit). SettingLinkDeviceLimit = "link_device_limit" LinkModeTrack = "track" LinkModeEnforce = "enforce" LinkModeStrict = "strict" )
The mode of the device limit (SettingLinkDeviceLimit) is stored as one of these words. A panel that was never given one counts only: the step-2 behaviour, and what every installation starts as (MigrateLinkDeviceLimit picks the real one).
const ( DeviceKindLink = "link" DeviceKindKey = "key" )
Device kinds (device.kind). A key is an AmneziaVPN key made by AddAWGDevice; a link device is anything that takes the subscription link, whatever credentials it holds (the shared device, and a device per HWID that an app reports).
const ( RoleOwner = "owner" RoleHelper = "helper" RoleReadonly = "readonly" )
Roles stored in admin.role.
const ( AwgPrepareRunning = "running" AwgPrepareDone = "done" AwgPrepareFailed = "failed" )
States of AwgPrepareRow.State.
const ( DNSSourceUser = "user" DNSSourceGroup = "group" DNSSourceDefault = "default" )
DNS source names of the effective preset.
const ( RenewWindow = time.Hour RenewMax = 4 // certificates issued to one node (enrolment or renewal) inside RenewWindow, the new one excluded )
const ( PlanPlanned = "planned" PlanAwaiting = "awaiting" PlanApproved = "approved" PlanRejected = "rejected" PlanExpired = "expired" PlanApplying = "applying" PlanApplied = "applied" PlanFailed = "failed" PlanCancelled = "cancelled" )
Plan statuses, the values of mcp_plan.status.
const ( // PlanTTL is how long a plan (and, for a dangerous one, the owner's decision) stays valid. PlanTTL = 10 * time.Minute // ApplyStuckAfter is how long a plan may stay `applying` before the sweep gives up on it (a crash mid-call). ApplyStuckAfter = 5 * time.Minute // PlanKeep is how long finished plans stay before the sweep deletes them. PlanKeep = 30 * 24 * time.Hour )
const ( AuditPanel = "panel" AuditBot = "bot" AuditMCP = "mcp" AuditAPI = "api" )
Audit sources, the values of audit.source.
const ( ProfileReadonly = "readonly" ProfileOperator = "operator" ProfileAdmin = "admin" )
Token profiles, the values of api_token.profile. The auth package maps them to roles.
const ( RolloutRunning = "running" RolloutPaused = "paused" RolloutDone = "done" RolloutCancelled = "cancelled" RolloutFailed = "failed" StepPending = "pending" StepSent = "sent" StepGating = "gating" StepPassed = "passed" StepFailed = "failed" StepRolledBack = "rolled_back" StepSkipped = "skipped" )
Rollout and step states as stored (migration 00013).
const ( WarpRegistered = "registered" WarpImported = "imported" )
WARP account sources, the values of warp_account.source.
const DNSBuiltinDefaultID = "dns_builtin_ru_split"
DNSBuiltinDefaultID is the preset every install starts with as its default (Russia split).
const LinkEvictAfter = 30 * 24 * time.Hour
LinkEvictAfter is how long a link device must have been silent to give up its place to a new HWID (ENFORCE and STRICT).
const MaxLiveTokens = 50
MaxLiveTokens is the number of unrevoked, unexpired tokens the panel holds at most.
const MaxProvisionAttempts = 3
MaxProvisionAttempts is how many times a worker may claim one job. A job still running when the worker restarts for the MaxProvisionAttempts-th time fails with job_interrupted instead of being requeued; a retry starts the count again.
Variables ¶
var ( // ErrAccessExists is returned when a unique name or key is already taken. ErrAccessExists = errors.New("store: already exists") // ErrAccessVersion is returned when an optimistic-concurrency version does not match. ErrAccessVersion = errors.New("store: version mismatch") // ErrAccessInUse is returned when a row cannot be deleted because others still depend on it. ErrAccessInUse = errors.New("store: in use") )
var ( // ErrAccessBlocked is returned when the HWID of a new device was blocked by the owner (device.blocked_at). ErrAccessBlocked = errors.New("store: device blocked") ErrNoSharedDevice = errors.New("store: no shared device in strict mode") )
var ( ErrAuthCeremonyNotFound = errors.New("auth ceremony not found") ErrAuthCeremonyLimit = errors.New("too many pending ceremonies") )
var ( // ErrEnrollToken: the token is unknown, expired or already used (and not a valid replay). ErrEnrollToken = errors.New("store: enrollment token unknown, expired or used") // ErrNodeRetired: the node exists but was retired. ErrNodeRetired = errors.New("store: node retired") // ErrConflict: a unique constraint was violated (node name). ErrConflict = errors.New("store: conflict") )
Errors of the enrollment path.
var ( // ErrPlanState: the plan is not in a state the call needs. The error is a *PlanStateError that carries the // status found (errors.As); errors.Is(err, ErrPlanState) is true for it. ErrPlanState = errors.New("store: plan is in another state") // ErrTooManyPlans: the token holds too many open plans, or too many plans wait for the owner. ErrTooManyPlans = errors.New("store: too many open plans") )
var ( // ErrNotFound is returned when a looked-up row does not exist. ErrNotFound = errors.New("store: not found") // ErrSetupClosed is returned when the first admin cannot be created: the token is // unknown, used or expired, or an admin already exists. ErrSetupClosed = errors.New("store: setup closed") )
var ( // ErrNameTaken: another unrevoked token already has this name (case insensitive). ErrNameTaken = errors.New("store: token name taken") // ErrTokenLimit: MaxLiveTokens unrevoked, unexpired tokens already exist. ErrTokenLimit = errors.New("store: too many tokens") )
var ErrAccessSubnetFull = errors.New("store: subnet full")
ErrAccessSubnetFull is returned when the client network of a profile has no free peer index.
var ErrCannotBlock = errors.New("store: this device cannot be blocked")
ErrCannotBlock is returned when the device cannot be blocked: only a link device that reported a HWID has a hash a block can name (the shared device and an AmneziaVPN key have none).
var ErrDNSExists = errors.New("store: dns preset name taken")
ErrDNSExists is returned when a preset name is already taken.
var ErrLastMethod = errors.New("store: last sign-in method")
ErrLastMethod is returned when removing a credential would leave the admin unable to sign in.
var ErrLoginTaken = errors.New("store: login taken")
ErrLoginTaken: another admin signs in with this login.
var ErrNodeDecoyBundleMissing = errors.New("node has no uploaded decoy bundle")
var ErrRenewRefused = errors.New("store: certificate renewal refused")
ErrRenewRefused: the certificate that asked for a renewal is no longer valid for its node (revoked, expired, unknown, or the node is retired), or the node already got RenewMax certificates in the last RenewWindow.
var GroupTones = []string{"lavender", "sand", "sage", "rose", "sky", "mint"}
GroupTones is the palette of a group's colour, in the order the admin offers it and the order a new group takes the least used tone in (ties go to the earlier one). Sky and mint come last: they are also the Link and Keys chips.
Functions ¶
func AWGHwidHash ¶
AWGHwidHash is the hwid_hash of an AWG device: NULL belongs to the implicit per-user device (one per user, a unique index), so an explicit device gets a synthetic hash that never equals the hash of a real HWID header.
func Clip ¶
Clip returns s as valid UTF-8 of at most n bytes, cut on a rune boundary. Text that comes from a node or a browser header is clipped with it before it is stored: a byte-wise cut can end inside a multi-byte character, and an invalid string makes every proto3 response that carries it fail to marshal.
func HWIDHash ¶ added in v0.1.39
HWIDHash is the hwid_hash of a device that reported a HWID: sha256 over a versioned label, the user id and the canonical HWID (access.CanonHWID). The user id salts it, so one phone on two subscriptions is not linked and a leaked database holds no raw HWID (a raw HWID plus the link is a device's keys). It never equals AWGHwidHash.
func LinkModeOf ¶ added in v0.1.39
LinkModeOf is the mode a stored value names; anything else, and nothing, is LinkModeTrack.
func RetainedKeyAAD ¶
RetainedKeyAAD is the vault AAD of a retained server key: bound to the pair, not to the inbound that is gone.
func SchemaVersions ¶ added in v0.1.15
SchemaVersions are the newest migration applied to the database file at path, read without migrating it, and the newest one this binary carries. goose accepts a database newer than the binary, whose code would not know its tables: a restore compares the two first.
func WithAuditSource ¶
WithAuditSource returns ctx marking every audit row written with it, whose entry names no source, as coming from source (AuditAPI or AuditMCP: a call made with an API token). Modules pass the request context to Audit, so their rows carry the source of the call without knowing about tokens. An unknown source is ignored.
Types ¶
type APIToken ¶
type APIToken struct {
ID, Name, Profile, Hint string
RatePerMin int
CreatedBy, CreatedByName string // admin id; the display name is resolved on reads ("" when the admin is gone)
RevokedBy string
CreatedAt, ExpiresAt time.Time
RevokedAt, LastUsedAt time.Time
LastUsedIP, LastUsedVia string
}
APIToken is one api_token row. A zero time means "unset".
type AWGDeviceAdd ¶
type AWGDeviceAdd struct {
Device AccessDevice // ID, UserID, Platform, Model, CreatedAt
ProfileID string
MaxIdx int // the largest peer index of the profile's client network
Limit int // the user's device limit
}
AWGDeviceAdd describes a new AWG device.
type AWGImplicitWant ¶
AWGImplicitWant asks for an AWG credential of one profile on the request's link device.
type AWGIssue ¶
type AWGIssue func(idx int) (cred AccessCred, publicKey string, err error)
AWGIssue makes the credential of one peer once its index is known: it fills ID, Protocol, SecretEnc and DataJSON (the store sets the owner, the profile and the epoch) and returns the peer's public key. It runs once per attempt between the candidate read and guarded write, so it must not access the database. Treat its result as provisional: do not keep it; only credentials returned by the store after commit or read back from the store are real.
type Access ¶
type Access struct {
// contains filtered or unexported fields
}
Access is the query set of the access module.
func (Access) AWGDeviceScope ¶ added in v0.1.26
AWGDeviceScope reads the device and the related user, group, profile and live inbounds in one fixed batch.
func (Access) AWGDevices ¶
AWGDevices returns the live AWG devices of a user, oldest first. FirstSeenAt and LastSeenAt are zero while the device has never connected.
func (Access) AWGDevicesPerProfile ¶
func (a Access) AWGDevicesPerProfile(ctx context.Context, groupID, userID string) (map[string]int, error)
AWGDevicesPerProfile counts the live explicit AWG devices (AmneziaVPN keys) per profile, of the users of a group (groupID) or of one user (userID); the other argument is "".
func (Access) AddAWGDevice ¶
func (a Access) AddAWGDevice(ctx context.Context, add AWGDeviceAdd, now time.Time, issue AWGIssue) (int, error)
AddAWGDevice inserts an AWG device with its credential and peer: limit check, index, credential and rows in one guarded batch. It returns the peer index. *AccessLimitError when the user has Limit devices already, ErrAccessSubnetFull when the network is used up, ErrNotFound when the user or profile is gone.
func (Access) AddUsage ¶
AddUsage adds bytes to a user's usage in the current period. The fleet module does the same inside its stats transaction; this exists for callers that have no transaction of their own.
func (Access) BlockDevice ¶ added in v0.1.39
BlockDevice revokes a live link device that reported a HWID, like RevokeDevice, and marks it blocked: the hash is not born again (ErrAccessBlocked from EnsureLinkDevice) until UnblockDevice. It returns the device's user. ErrNotFound when there is no live device, ErrCannotBlock for the shared device and for a key.
func (Access) BlockedDevices ¶ added in v0.1.39
BlockedDevices lists the blocked devices of a user, the newest block first.
func (Access) BumpProfileEpoch ¶
BumpProfileEpoch marks every device of the profile that already received a config as stale (something on the nodes changed that an issued config cannot survive).
func (Access) CreateGroup ¶
func (a Access) CreateGroup(ctx context.Context, g AccessGroup) error
CreateGroup inserts a group with its profile set. ErrAccessExists on a name clash, ErrNotFound when a profile id does not exist.
func (Access) CreateInbound ¶
func (a Access) CreateInbound(ctx context.Context, i AccessInbound) error
CreateInbound inserts an inbound; ErrAccessExists when the profile is already on the node, ErrNotFound when the profile or node does not exist.
The inbound takes over the retained server key of its (profile, node), if there is one (RetainedKey): the row is deleted in the same transaction, so the key is never on both sides.
func (Access) CreateProfile ¶
func (a Access) CreateProfile(ctx context.Context, p AccessProfile) error
CreateProfile inserts a profile; ErrAccessExists when the name is taken.
func (Access) CreateUser ¶
func (a Access) CreateUser(ctx context.Context, u AccessUser, dev AccessDevice, creds []AccessCred) error
CreateUser inserts a user with its node list and, when creds are given, a shared device holding them, in one transaction. The panel gives none: a device is made by the first fetch of an app (EnsureLinkDevice), and without credentials no device is made, so it is not counted against the device limit. ErrAccessExists on a name (or token) clash, ErrNotFound when the group or a node does not exist.
func (Access) DailyTraffic ¶
func (a Access) DailyTraffic(ctx context.Context, userID string, from time.Time) (map[int64]uint64, error)
DailyTraffic returns bytes (up + down) per UTC day since `from`, keyed by the day's Unix start.
func (Access) DeleteGroup ¶
DeleteGroup removes a group without users; ErrAccessInUse otherwise. A non-empty moveTo first moves the group's users there, in the same transaction (ErrNotFound when that group does not exist).
func (Access) DeleteInbound ¶
func (a Access) DeleteInbound(ctx context.Context, id string, now time.Time, retain func(stateEnc []byte, profileID, nodeID string) ([]byte, error)) error
DeleteInbound removes an inbound. With retain set and key material on the inbound, the key moves to awg_retained_key in the same transaction (replacing an older row of the pair, unless the node is retired): retain turns the inbound's vault blob into the blob for RetainedKeyAAD, and returns nil to keep nothing (an unreadable key must not make the inbound undeletable).
func (Access) DeleteProfile ¶
DeleteProfile removes a profile that has no inbounds; ErrAccessInUse otherwise. The AWG credentials and peers of the profile go with it (foreign keys); the explicit AWG devices that held them are revoked, so none stays behind as an empty shell.
func (Access) DeleteUsers ¶
DeleteUsers deletes users (devices, credentials, node list and traffic rows cascade) and returns the number deleted.
func (Access) DesiredCreds ¶
DesiredCreds returns the candidate credentials of every enabled inbound of a node.
func (Access) Device ¶ added in v0.1.39
Device returns a live (not revoked) device, with or without credentials; ErrNotFound when there is none.
func (Access) DeviceCounts ¶
DeviceCounts returns the number of devices per user that count against the device limit: not revoked and holding at least one live credential (a device without any is an empty shell, e.g. the implicit device of a user of the Amnezia app only, created by an older version).
func (Access) Devices ¶
Devices returns the non-revoked devices of a user that hold a live credential, with their credential protocols.
func (Access) EnsureLinkAWGCreds ¶ added in v0.1.39
func (a Access) EnsureLinkAWGCreds(ctx context.Context, dev AccessDevice, limit int, now time.Time, want []AWGImplicitWant) (LinkDeviceResult, error)
EnsureLinkAWGCreds gives the request's link device (dev.HWIDHash, nil for the shared one) an AWG credential for every wanted profile that it has none for, and returns the device's full live credential set plus the credentials it added. A subscription in the Mihomo format carries AmneziaWG proxies, so the device that fetches it needs a peer per profile. A device that does not exist is born here, as in EnsureLinkDevice (the person with only the AmneziaVPN access and a HWID-reporting Mihomo app has no other credential to be born with): taken over from the shared device, or new under the ceiling of the stored mode (*AccessLimitError at it, a silent device replaced past it, ErrAccessBlocked, ErrNoSharedDevice: see linkDeviceState.birth); limit is the user's device limit. A subscription fetch must not fail for them.
func (Access) EnsureLinkDevice ¶ added in v0.1.39
func (a Access) EnsureLinkDevice(ctx context.Context, dev AccessDevice, limit int, now time.Time, issue LinkIssue) (LinkDeviceResult, error)
EnsureLinkDevice makes the request's link device (dev.HWIDHash, nil for the shared device) exist and hold every credential issue returns for it, in one guarded batch, and reads the device back. A device that exists is only filled; the first HWID of a user whose shared device holds credentials takes the shared device over, credentials unchanged; otherwise a device is born, unless the user already has as many live devices as the stored mode allows for it (linkCeiling of limit, the user's device limit): *AccessLimitError, or, for a HWID in ENFORCE and STRICT, the oldest link device silent for LinkEvictAfter is revoked in the same batch and its place taken (LinkDeviceResult.Replaced). A device is never born empty: with nothing to issue and no device the result is empty and nothing is written. Concurrent calls decide through the batch's guards and retry on what the winner left (see retryGuarded): two new HWIDs at the ceiling make one device, the same HWID twice makes one, two adoptions make one, two evictions of one silent device make one, a block or a mode switch between the read and the write is read by the repeat. ErrNotFound when the user is gone; ErrAccessBlocked and ErrNoSharedDevice as in birth.
func (Access) ExistingNodeIDs ¶
ExistingNodeIDs returns those of ids that exist.
func (Access) Groups ¶
func (a Access) Groups(ctx context.Context) ([]AccessGroup, error)
Groups returns all groups with their profile ids and user counts, ordered by name.
func (Access) HasUserWithTokenHash ¶ added in v0.1.23
HasUserWithTokenHash checks a subscription token without loading the user's view.
func (Access) InboundsFull ¶
InboundsFull returns every inbound joined with its profile and node, in the order they were created (rowid breaks a tie within a second); nodeID non-empty restricts it to one node. Retired nodes are excluded. This is the subscription's order, and the server names are numbered in it ("Germany", "Germany 2"): a server added later never takes the name of an older one. Deleting a server still renumbers the ones after it; a stored ordinal would keep them.
func (Access) InboundsOfNode ¶
InboundsOfNode returns the inbounds of a node.
func (Access) InboundsOfProfile ¶
InboundsOfProfile returns the inbounds of a profile.
func (Access) ListUsers ¶
func (a Access) ListUsers(ctx context.Context, q AccessUserQuery) ([]AccessUser, bool, AccessUserCounts, error)
ListUsers returns one page in the requested total order (up to Limit users plus a flag telling whether more follow) and the chip counts. LIKE is case-insensitive for ASCII only.
func (Access) NodeTraffic ¶
func (a Access) NodeTraffic(ctx context.Context, userID string, since time.Time) ([]AccessNodeTraffic, error)
NodeTraffic returns a user's traffic per node and protocol since the given time.
func (Access) Nodes ¶
func (a Access) Nodes(ctx context.Context) ([]AccessNode, error)
Nodes returns all nodes that are not retired, ordered by name.
func (Access) ProfileHasPeers ¶
ProfileHasPeers reports whether the profile ever handed out a tunnel address (live or in quarantine): its client networks are then fixed.
func (Access) ProfileLiveAWG ¶
func (a Access) ProfileLiveAWG(ctx context.Context, profileID string, limit int) (n int, users []string, err error)
ProfileLiveAWG counts the live credentials of explicit AWG devices of a profile (the configs an x-critical change breaks) and lists the names of their owners, at most limit, ordered.
func (Access) ProfileUsers ¶
func (a Access) ProfileUsers(ctx context.Context, profileID string, happ, amnezia bool) ([]AccessBrief, error)
ProfileUsers lists users whose group contains the profile and whose app toggles allow it: happ and amnezia say which toggles count (derived from the protocol's Clients()). Ordered by name.
func (Access) Profiles ¶
func (a Access) Profiles(ctx context.Context) ([]AccessProfile, error)
Profiles returns all profiles ordered by name.
func (Access) RecordDeviceConfig ¶ added in v0.1.26
func (a Access) RecordDeviceConfig(ctx context.Context, credID string, epoch *int64, sig map[string]string) error
RecordDeviceConfig records what the credential's device received: the profile epoch of the config (never lowered; nil leaves it) and the DNS the key now holds per node id, replacing the stored one (nil leaves it), which is what "stale DNS" is measured against.
func (Access) RenameDevice ¶
RenameDevice sets the label (device.model) of a live device that has a name of its own, a key or a link device that reported a HWID; ErrNotFound when there is none (the shared device is no one's device to name).
func (Access) ResetUserPeriod ¶
func (a Access) ResetUserPeriod(ctx context.Context, id string, oldPeriodStart, periodStart time.Time, status string) error
ResetUserPeriod starts a new quota period only if it is still the period the caller read. Usage added after a concurrent reset is left intact.
func (Access) ResetUserTraffic ¶ added in v0.1.31
ResetUserTraffic clears current usage and stores a recomputed status without changing period_start.
func (Access) RetainedKey ¶
func (a Access) RetainedKey(ctx context.Context, profileID, nodeID string) (AccessRetainedKey, error)
RetainedKey returns the retained server key of the pair, or ErrNotFound.
func (Access) RevokeDevice ¶
RevokeDevice soft-deletes a live device and its credentials and returns its user id; ErrNotFound when the device does not exist or is already revoked.
func (Access) RotateAWGDevice ¶
func (a Access) RotateAWGDevice(ctx context.Context, deviceID string, now time.Time, issue AWGIssue) (string, error)
RotateAWGDevice replaces a live AWG credential while keeping its peer index (and tunnel address). A guarded batch revokes the old credential and peer before inserting the new pair. It returns the device's user. ErrNotFound when there is no such live AWG device.
func (Access) SetInboundBuildError ¶
SetInboundBuildError records that the inbound's desired spec could not be built (corrupt profile, unreadable secrets) so the node page shows it: state failed and last_error text. It writes only when that is news, because the desired state is recomputed on every change and stats tick.
func (Access) SetSubToken ¶
SetSubToken replaces the subscription token of a user.
func (Access) SetUserExpiry ¶
SetUserExpiry sets a user's term end (zero = never).
func (Access) SetUserStatus ¶
SetUserStatus stores a recomputed status.
func (Access) SetUsersDisabled ¶
SetUsersDisabled flips the admin switch of several users.
func (Access) SharedLinkUsers ¶ added in v0.1.39
SharedLinkUsers counts the people who have a live shared link device with credentials: the ones STRICT turns away.
func (Access) SubscriptionData ¶ added in v0.1.26
func (a Access) SubscriptionData(ctx context.Context, userID, groupID string, since time.Time, active bool, now time.Time, hwidHash []byte) (SubscriptionData, error)
SubscriptionData reads everything a subscription view needs in one read batch. hwidHash selects the request's own device (SubscriptionData.Device): nil for an app that sends no HWID.
func (Access) TouchDevice ¶
func (a Access) TouchDevice(ctx context.Context, id string, now, not time.Time, osVersion, client string) error
TouchDevice sets last_seen_at unless it is already newer than `not`: a throttle for write-on-read. A fetch that reports an OS version or a client records them too (the empty ones leave the stored values).
func (Access) UnblockDevice ¶ added in v0.1.39
UnblockDevice lets the hash of a blocked device register again and returns its user; ErrNotFound when the device is not blocked. The device itself stays revoked: its app gets a device and keys of its own on the next fetch.
func (Access) UpdateGroup ¶
func (a Access) UpdateGroup(ctx context.Context, id string, name *string, profileIDs *[]string, dnsPresetID, color *string) error
UpdateGroup renames a group, replaces its profile set and/or its DNS preset, sets its colour (nil = unchanged, "" = none).
func (Access) UpdateInbound ¶
func (a Access) UpdateInbound(ctx context.Context, i AccessInbound, resetState bool, now time.Time) error
UpdateInbound writes the admin-editable fields and the spec version of i (matched by ID). When resetState is set the state goes back to pending (enabled) or disabled, until the node reports again.
func (Access) UpdateProfile ¶
func (a Access) UpdateProfile(ctx context.Context, p AccessProfile, expectedVersion uint32, bumpInbounds, bumpEpoch bool, now time.Time) (AccessProfile, error)
UpdateProfile writes name, settings and secrets of p (matched by ID) when its stored version equals expectedVersion, bumps the version and, with bumpInbounds, the spec_version of the profile's inbounds. With bumpEpoch it also raises critical_epoch in the same transaction: every device that received its config before is then "stale" (an x-critical change of an AWG profile). ErrAccessVersion on mismatch, ErrAccessExists on a name clash. Returns the stored row.
func (Access) UpdateUser ¶
UpdateUser writes every admin-editable column of u (matched by ID) and its status. setNodes also replaces the explicit node list with u.NodeIDs. Usage counters are left alone (the fleet increments them). ErrAccessExists on a name clash, ErrNotFound when the user, group or a node does not exist.
func (Access) UserByTokenHash ¶
UserByTokenHash finds the user of a subscription token hash (sha256), or ErrNotFound.
func (Access) UserStates ¶
UserStates returns the state columns of the given users, or of all users when ids is nil.
func (Access) UsersByIDs ¶
UsersByIDs returns the existing users among ids, ordered by name.
type AccessAWGDevice ¶
type AccessAWGDevice struct {
AccessDevice
ProfileID, ProfileName, ProfileSettingsJSON string // the settings without secrets: enough for the version
CredID, DataJSON, PublicKey string
SecretEnc []byte // vault, AAD = CredID
Idx int
ConfigEpoch, CriticalEpoch int64
// DNSSig is written by RecordDeviceConfig for each node config the device receives; anything else reads as nothing recorded.
DNSSig map[string]string
// DNSStale lists the nodes where the DNS that applies to the person is not the one the key holds. The store leaves it
// empty: only the access module knows what applies.
DNSStale []string
}
AccessAWGDevice is a live AWG device with its one live credential and peer.
func (AccessAWGDevice) Stale ¶
func (d AccessAWGDevice) Stale() bool
Stale reports whether the profile changed in a way that breaks the config the device last received.
type AccessAWGDeviceScope ¶ added in v0.1.26
type AccessAWGDeviceScope struct {
Device AccessAWGDevice
User AccessUser
Group AccessGroup
Profile AccessProfile
Inbounds []AccessInboundFull
}
AccessAWGDeviceScope is the read-only state needed to render one device's configs.
type AccessBlockedDevice ¶ added in v0.1.39
type AccessBlockedDevice struct {
ID, Platform, Model, Client, Fingerprint string
BlockedAt time.Time
}
AccessBlockedDevice is a device the owner blocked. Fingerprint is the first 6 hex characters of its hash: the HWID itself is never stored.
type AccessCred ¶
type AccessCred struct {
ID, DeviceID, UserID, Protocol string
ProfileID string
SecretEnc []byte // vault, AAD = ID
DataJSON string
ConfigEpoch int64
CreatedAt time.Time
}
AccessCred is one device x protocol credential. ProfileID binds an AWG credential to its profile ("" for hysteria2); ConfigEpoch is the profile critical_epoch the device last received a config for.
type AccessDesiredCred ¶
type AccessDesiredCred struct {
InboundID, CredID, UserID, DeviceID, Protocol, DataJSON string
SpeedLimitBps uint64 // the person's limit (user.speed_limit_bps)
DeviceSpeedLimitBps uint64 // one device's limit (user.device_speed_limit_bps)
ExpiresAt time.Time
AppHapp, AppAmnezia bool
}
AccessDesiredCred is a live credential that may go to a node: its user is active, belongs to a group with the inbound's profile and has the node selected. The caller still checks the app toggles against the protocol's Clients().
type AccessDevice ¶
type AccessDevice struct {
ID, UserID, Platform, Model, OSVersion string
Client string // the app: first token of its User-Agent
Kind string // DeviceKindLink or DeviceKindKey; read back by scanAccessDevice, set on insert by AWG
UsedBytes uint64 // all-time traffic of the device (device.used_bytes)
// Fingerprint is the first 6 hex characters of a link device's hash, to tell two phones of one model apart; empty for the
// shared device and for keys.
Fingerprint string
Implicit bool // hwid_hash IS NULL
// HWIDHash is the hash of the device's HWID (HWIDHash): set for a link device that reported one, nil for the shared
// device. A request's device is looked up by it (EnsureLinkDevice, SubscriptionData).
HWIDHash []byte
// AWG marks a device created by AddAWGDevice: a synthetic hwid_hash (AWGHwidHash) and first/last seen 0 =
// "never connected" until the fleet records a handshake.
AWG bool
FirstSeenAt, LastSeenAt, CreatedAt time.Time
Protocols []string // protocols with a live credential
}
AccessDevice is one device of a user: the shared device of the apps that report no HWID, a device per HWID (a link device), or an AWG device that holds its own keys.
type AccessGroup ¶
type AccessGroup struct {
ID, Name string
ProfileIDs []string
UserCount int
CreatedAt time.Time
DNSPresetID string // "" = the instance default
// Color is a tone of GroupTones, "" = none picked. CreateGroup fills in the least used tone when it is empty.
Color string
}
AccessGroup is an access group: a named set of profiles.
type AccessInbound ¶
type AccessInbound struct {
ID, ProfileID, NodeID string
PortOverride uint16 // 0 = none
TLSServerNameOverride string
Enabled bool
SpecVersion uint64
State string // pending | active | failed | disabled
LastError string
CertPinSHA256 string
CertNotAfter time.Time
CreatedAt, UpdatedAt time.Time
// Plugin-neutral material of the inbound (AWG: the server key pair). PluginStateEnc is the vault blob (AAD =
// inbound id) and nil for hysteria2; PluginPublicJSON is "{}" when there is none.
PluginStateEnc []byte
PluginPublicJSON string
// The last agent.v1.AwgHealth the node reported, as protojson ("" = never), and when.
AwgHealthJSON string
AwgHealthAt time.Time
}
AccessInbound is a profile deployed on a node. The fleet module updates State, LastError and the certificate fields from the node's results.
type AccessInboundFull ¶
type AccessInboundFull struct {
Inbound AccessInbound
Profile AccessProfile
Node AccessNode
}
AccessInboundFull is an inbound with its profile and node.
type AccessLimitError ¶
AccessLimitError is returned when the user already has as many devices as the limit allows. Limit is the ceiling that was reached (twice the user's limit for a HWID in TRACK mode); Mode is the link-device mode it was decided under ("" for a key).
func (*AccessLimitError) Error ¶
func (e *AccessLimitError) Error() string
type AccessNode ¶
type AccessNode struct {
ID, Name, Address, CountryCode, Location, Provider string
BandwidthMbps int
State string // pending | active | retired
LastSeenAt time.Time
AgentCaps []string
}
AccessNode is the part of a node row the access module reads (the fleet module owns the table).
type AccessNodeTraffic ¶
AccessNodeTraffic is a user's traffic on one node and protocol.
type AccessProfile ¶
type AccessProfile struct {
ID, Protocol, Name, SettingsJSON string
SecretsEnc []byte
Version uint32
CreatedAt, UpdatedAt time.Time
}
AccessProfile is a protocol preset. SettingsJSON holds no secrets; SecretsEnc is the vault blob (AAD = ID) of the x-secret values.
type AccessRetainedKey ¶
AccessRetainedKey is the server key of a (profile, node) whose inbound was removed. StateEnc is the vault blob under RetainedKeyAAD.
type AccessUser ¶
type AccessUser struct {
ID, Name, SubscriptionName, GroupID, GroupName string
Disabled bool
Status string // active | disabled | expired | limited (derived, see access.ComputeStatus)
AppHapp, AppAmnezia bool
AllNodes bool
QuotaBytes uint64 // 0 = unlimited
QuotaReset string // none | day | week | month | rolling_month
PeriodStart time.Time
UsedBytes uint64
ExpiresAt time.Time // zero = never
DeviceLimit int
SpeedLimitBps uint64 // the person's limit: all their devices on one node together (0 = none)
DeviceSpeedLimitBps uint64 // one device's limit (0 = none)
SubTokenHash, SubTokenEnc []byte
LastSeenAt time.Time
LastNodeID string
CreatedAt time.Time
NodeIDs []string // rows of user_node; meaningful while AllNodes is false
DNSPresetID string // "" = inherit (group, then the instance default)
GroupDNSPresetID string // the user's group's preset, read-only here ("" = none)
}
AccessUser is a user row with its group name and explicit node list.
type AccessUserCounts ¶
type AccessUserCounts struct{ All, Online, Expiring, OverQuota, DevicesUsed, DevicesOnline, OverDeviceLimit int }
AccessUserCounts are the filter chip badges for one query, ignoring the filter itself.
type AccessUserQuery ¶
type AccessUserQuery struct {
Filter string
Query string
GroupID string
Sort AccessUserSort
Descending bool
After string // name after which the page starts ("" = first page)
Offset int // rows skipped after After, for numbered pages
Limit int
OnlineIDs []string // users currently online (fleet), for the "online" filter and its count
OnlineDeviceIDs []string // devices with a session now (fleet), for the devices_online count of subscription devices
Now time.Time
DeviceOnlineAfter time.Time // AWG devices with a newer handshake count as online
}
AccessUserQuery is a list request. Filter is "", "online", "expiring", "over_quota" or "over_device_limit".
type AccessUserSort ¶ added in v0.1.39
type AccessUserSort int
AccessUserSort follows the UserSort wire values. Zero means the default name order.
const ( AccessUserSortUnspecified AccessUserSort = iota AccessUserSortName AccessUserSortTraffic AccessUserSortExpiry AccessUserSortLastSeen AccessUserSortDevices AccessUserSortGroup AccessUserSortStatus )
type AccessUserState ¶
type AccessUserState struct {
ID, Status, QuotaReset string
Disabled bool
QuotaBytes, UsedBytes uint64
ExpiresAt, PeriodStart time.Time
}
AccessUserState is what the status sweep needs about a user.
type Admin ¶
type Admin struct {
ID string
DisplayName string
Role string
UserHandle []byte // WebAuthn user.id
CreatedAt time.Time
}
Admin is a panel administrator.
type AdminLogin ¶
AdminLogin is an admin with its password login, for the operator's command line.
type AuditEntry ¶
type AuditEntry struct {
Actor string // admin id, or "anonymous"
Action string
Params string // JSON object without secrets; "" means {}
Result string
Source string // AuditPanel (default), AuditBot, AuditMCP or AuditAPI
IP string // client address the action came from, "" if none
}
AuditEntry is one audit-log row.
type AuditQuery ¶
type AuditQuery struct {
Source string
BeforeID int64
Limit int
Actions, Prefixes []string
Failed bool
}
AuditQuery is one page of the audit log: newest first, id < BeforeID (0 = from the newest), at most Limit rows. Source keeps one source ("" = all). Actions and Prefixes keep the rows whose action is one of Actions or starts with one of Prefixes (both empty = every action). Failed keeps the rows whose result is not "ok".
type AuditRow ¶
type AuditRow struct {
ID int64
Time time.Time
Actor string
ActorName string // the admin's display name, or the token's name for "token:<id>" / "mcp:<id>"; "" if neither exists
Action string
Params string
Result string
Source string
IP string
}
AuditRow is an audit entry as listed in the UI.
type AuthCeremony ¶ added in v0.1.26
type AuthCeremony struct {
ID string
Kind string
Source string
SessionData string
TokenHash []byte
AdminID string
AdminUserHandle []byte
Name string
Login string
PasswordHash string
TOTPEncrypted []byte
Tries int
ExpiresAt time.Time
}
AuthCeremony is the persisted server-side half of an authentication ceremony. SessionData is JSON; transient secrets such as a setup TOTP seed are sealed by auth.
type AwgPrepareRow ¶
type AwgPrepareRow struct {
State string `json:"state,omitempty"` // "" | running | done | failed
Since int64 `json:"since,omitempty"` // running: when it began; done / failed: when it ended
// Want: the admin chose the kernel module for this node, so the panel sets awg_backend to "kernel" when the build is
// done. Cleared by any later choice of a backend.
Want bool `json:"want,omitempty"`
Code string `json:"code,omitempty"` // failed: the node's code (timeout, apt_lock, step_failed, ...)
Reason string `json:"reason,omitempty"` // failed: one short English sentence
}
AwgPrepareRow is what the panel knows about the build of the AmneziaWG kernel module on a node (migration 00019). The zero value is "nothing was ever asked".
type BlocklistCheck ¶ added in v0.1.41
type BlocklistCheck struct {
NodeID, RKNSubnet, ListedBy, CDNProvider, CDNRegion string
InRKN bool
At, ListsAt time.Time
}
BlocklistCheck is what the block lists said about one node's address at one time (migration 00067). ListedBy is a comma separated list of the lists that hold the address ("antifilter_ipsum,antifilter_community"); ListsAt is the date of the newest list that was used.
type CARow ¶
type CARow struct {
ID, CertPEM, Fingerprint string
KeyEnc []byte // vault, AAD = ID
NotBefore, NotAfter time.Time
Active bool
}
CARow is one panel_ca row.
type CertRow ¶
type CertRow struct {
Serial, NodeID, CAID, PEM string
NotBefore, NotAfter time.Time
IssuedAt time.Time
}
CertRow is one node_cert row (public material only).
type CertState ¶
type CertState struct {
NodeID, NodeState string
NotAfter time.Time
Revoked bool // revoked at or before the asked time (a scheduled revocation is not yet one)
}
CertState is what the panel knows about an issued certificate.
type CheckSample ¶
type CheckSample struct {
InboundID string
At time.Time
Status int
LatencyMS uint32
ConnectMS, ResponseMS uint32 // migration 00065; 0 = not measured
ExitIP, ExitCountry, ErrorCode, ErrorDetail string
}
CheckSample is one finished round of the synthetic checker. Status: 1 ok, 2 degraded, 3 failed.
type CodeMatch ¶
CodeMatch keeps the events whose code is one of Codes or starts with one of Prefixes, or whose severity is at least MinSeverity (0 = severity does not count); Not keeps the others instead.
type CountryCheck ¶ added in v0.1.41
CountryCheck is one round of the country check for one node (migration 00066). Verdict is ok | tcp_blocked | blocked | unknown; Detail is the JSON the health module writes and reads (per probe network, ASN, city and answers).
type DNS ¶
type DNS struct {
// contains filtered or unexported fields
}
DNS is the query set of the dns module.
func (DNS) DefaultID ¶
DefaultID returns the instance default preset id as stored ("" = the built-in default).
func (DNS) Delete ¶
Delete removes a preset and clears it from every user and group that used it, in one transaction. Refusing built-ins and the instance default is the caller's job. ErrNotFound when the id is unknown.
func (DNS) EffectiveData ¶ added in v0.1.26
EffectiveData reads a person's preset, the instance default and what applies to their link apps in one batch.
func (DNS) LinkOptions ¶ added in v0.1.43
func (d DNS) LinkOptions(ctx context.Context) ([]LinkDNSOption, error)
LinkOptions returns what the owner offers for the link apps, in order.
func (DNS) List ¶
List returns every preset: the built-ins in their fixed order (the sort column), then the custom ones by name.
func (DNS) NodeExists ¶ added in v0.1.17
NodeExists reports whether a node id exists (retired nodes included).
func (DNS) NodeName ¶ added in v0.1.17
NodeName is the name the owner gave a node; ErrNotFound when there is none.
func (DNS) NodeOptions ¶ added in v0.1.17
NodeOptions returns the offered presets of every node, in the owner's order.
func (DNS) ResetUserNodeChoices ¶ added in v0.1.17
ResetUserNodeChoices removes every pick of a person, per node and for the link apps, and says how many there were.
func (DNS) SetDefaultID ¶
SetDefaultID stores the instance default ("" = the built-in default). The caller checks that it exists.
func (DNS) SetLinkOptions ¶ added in v0.1.43
SetLinkOptions replaces what the owner offers for the link apps: presetIDs in order, defaultID (one of them, or "") as the default. The caller checked the ids. ErrNotFound when a preset is gone. Picks of presets no longer offered stay (they do nothing while the preset is not offered).
func (DNS) SetNodeOptions ¶ added in v0.1.17
func (d DNS) SetNodeOptions(ctx context.Context, nodeID string, presetIDs []string, defaultID string) error
SetNodeOptions replaces what a node offers: presetIDs in order, defaultID (one of them, or "") as the default. The caller checked the ids. ErrNotFound when the node or a preset is gone. Picks of people for presets that are no longer offered stay (they do nothing while the preset is not offered).
func (DNS) SetUserLinkChoice ¶ added in v0.1.43
SetUserLinkChoice records a person's pick for the link apps (replacing the earlier one); presetID "" removes it. ErrNotFound when the user or the preset is gone.
func (DNS) SetUserNodeChoice ¶ added in v0.1.17
func (d DNS) SetUserNodeChoice(ctx context.Context, userID, nodeID, presetID string, now time.Time) error
SetUserNodeChoice records a person's pick (replacing the earlier one); presetID "" removes it. ErrNotFound when the user, node or preset is gone.
func (DNS) SubscriptionData ¶ added in v0.1.26
SubscriptionData reads a person's effective preset, node offers and choices in one batch.
func (DNS) Update ¶
Update replaces the editable fields of a preset (the built-ins too). ErrNotFound, ErrDNSExists.
func (DNS) UserCounts ¶
UserCounts returns, per preset id, how many users it is effective for (direct, via group or default).
func (DNS) UserNodeChoices ¶ added in v0.1.17
UserNodeChoices returns what one person picked, by node id.
type DNSEffectiveData ¶ added in v0.1.26
type DNSEffectiveData struct {
OwnPresetID, GroupPresetID string
DefaultID string
Presets []DNSPreset
// LinkOptions is what the owner offers for the link apps, in order (migration 00069); LinkPick is what the person picked
// for them ("" = nothing, offered or not) and LinkPickMs when (Unix milliseconds).
LinkOptions []LinkDNSOption
LinkPick string
LinkPickMs int64
}
DNSEffectiveData is the independent state needed to resolve a person's effective preset, and the preset of their link apps.
type DNSLookup ¶
type DNSLookup struct {
Names map[string]string // preset id -> name
DefaultID string // the instance default that exists, else the built-in default
}
DNSLookup is what resolving an effective preset needs: the names of the existing presets and the instance default.
type DNSPreset ¶
type DNSPreset struct {
ID, Name, Description string
Builtin, IPv4Only bool
SplitDirect bool // the split rules' domains bypass the VPN (Happ)
Transport string // preferred transport: plain, dot or doh
ServersJSON, SplitJSON string
CreatedAt, UpdatedAt time.Time
}
DNSPreset is a preset row. ServersJSON and SplitJSON are validated by the dns module before they get here.
type DNSSubscriptionData ¶ added in v0.1.26
type DNSSubscriptionData struct {
DNSEffectiveData
NodeOptions map[string][]NodeDNSOption
UserChoices map[string]UserNodeDNS
}
DNSSubscriptionData also carries the per-node offers and this person's picks for a subscription page.
type DailyRow ¶
type DailyRow struct {
InboundID string
Day time.Time // 00:00 UTC
OK, Failed, Degraded int
P50MS, P95MS uint32
}
DailyRow is one health_check_daily row.
type DoctorAccept ¶
type DoctorAccept struct {
NodeID, CheckID, DetailCode string
By, ByName string // admin id, and the admin's display name ("" when the admin is gone)
At time.Time
}
DoctorAccept is one accepted warning.
type DoctorRow ¶
type DoctorRow struct {
NodeID, CheckID string
Status int // agent.proto DoctorStatus: 1 ok, 2 warn, 3 fail, 4 skip
TitleKey, Detail string
DetailCode string // agent.proto DoctorResult.detail_code; "" from an agent that predates it
Params map[string]string
FixID string
Measured time.Time
Received time.Time
}
DoctorRow is one stored DoctorResult.
type EngineRow ¶
type EngineRow struct{ Protocol, Version string }
EngineRow is one engine a node runs.
type EnrollResult ¶
type EnrollResult struct {
NodeID string
Cert CertRow
Replay bool // the same certificate as before, returned for a retried request
}
EnrollResult is what a successful Enroll returns.
type EventFilter ¶
type EventFilter struct {
NodeID, UserID string
MinSeverity int
BeforeID int64 // events with id < BeforeID; 0 = newest
Limit int
Match *CodeMatch // nil = any code
}
EventFilter selects events; zero values mean "any".
type EventRow ¶
type EventRow struct {
ID int64
Time time.Time
Severity int // 1 info, 2 warning, 3 error
Code, Source string // source: agent | panel | admin
NodeID, NodeName, UserID, UserName, DeviceID, InboundID string
ProfileName, Protocol string
Params map[string]string
SrcInstance string // agent events: dedup
SrcSeq uint64
}
EventRow is one row of the event log. NodeName/UserName and ProfileName/Protocol (the profile of InboundID, "" once the inbound is gone) are filled by Events only.
type FleetCredRef ¶
type FleetCredRef struct{ UserID, DeviceID, Protocol string }
FleetCredRef is what a credential id resolves to (credentials are soft-deleted, so revoked ones resolve).
type FleetHourRow ¶
FleetHourRow is one node_traffic_hour row.
type FleetInboundCert ¶ added in v0.1.27
FleetInboundCert is a certificate reported for one inbound in a StatsBatch.
type FleetInboundRow ¶
type FleetInboundRow struct {
ID, ProfileID, ProfileName, Protocol string
ProfileVersion uint32
Settings string // settings_json, secrets NOT merged
SecretsEnc []byte // vault, AAD = ProfileID; nil if the profile has no secrets
PortOverride uint16
TLSNameOverride string
SpecVersion uint64
Enabled bool
State, LastError string
CertPin string
CertNotAfter time.Time
// Plugin-neutral material (migration 00014): the vault blob of the inbound (AAD = inbound id; nil for hysteria2) and
// the public JSON ("{}" = none), and the last agent.v1.AwgHealth the node reported as protojson ("" = never).
PluginStateEnc []byte
PluginPublic string
AwgHealthJSON string
AwgHealthAt time.Time
}
FleetInboundRow is one inbound of a node joined with its profile.
type FleetLive ¶ added in v0.1.29
type FleetLive struct {
Apply bool
Drift bool
SampleAt int64
RxBps uint64
TxBps uint64
CPUPct int64
UsersJSON string
// DevicesJSON is UsersJSON per device: device id -> the start of its newest session.
DevicesJSON string
LiveJSON string
}
FleetLive is one sanitized projection built from a StatsBatch and its resolved credentials.
type FleetSessionRef ¶
FleetSessionRef is one open session of a StatsBatch (used for the hourly peaks and AWG device touches).
type FleetStatsIn ¶
type FleetStatsIn struct {
NodeID, Instance string
Session uint64
Seq uint64
Now time.Time
HourStart int64 // bucket hour (multiple of 3600), already clamped by the caller
Traffic []FleetTraffic
Sessions []FleetSessionRef
Certs []FleetInboundCert
// Live builds the session projection inside each guarded attempt. It must not mutate captured state.
Live func(refs map[string]FleetCredRef) FleetLive
}
FleetStatsIn is one reliable StatsBatch to commit.
type FleetStatsOut ¶
type FleetStatsOut struct {
Duplicate bool // seq already committed: nothing was written
Refs map[string]FleetCredRef // every credential of the batch that resolved
Skipped int // deltas dropped: unknown credential, or inbound not on this node
Probe int // deltas of the health probe system credential, ignored on purpose (not an anomaly)
Users []string // users whose used_bytes grew (for the access module's status recompute)
}
FleetStatsOut is the outcome of IngestStats.
type FleetTraffic ¶
FleetTraffic is one TrafficDelta of a StatsBatch.
type GateRollback ¶
type GateRollback struct {
ErrorKey string // the gate's code: probe_failed, inbound_failed, not_committed, state_not_applied, ...
ToBuilt int64 // the build the rollout shipped
At time.Time
}
GateRollback is a rollout step the panel rolled back because the node failed its gate.
type HealthAWGSignal ¶ added in v0.1.27
type HealthAWGSignal struct {
DeviceID, UserID, UserName, Status string
CreatedAt, LastHandshakeAt time.Time
ConfigEpoch, CriticalEpoch int64
}
HealthAWGSignal holds the live device data used by never_connected and stale_key.
type HealthAlert ¶
type HealthAlert struct {
ID, Kind string
Severity int // 1 info, 2 warning, 3 critical
NodeID, Subject string
Params map[string]string
TitleKey, WhyKey string
FirstSeen, LastSeen time.Time
OpenedAt time.Time // start of the current episode: FirstSeen until the alert is re-opened, then the re-open
ResolvedAt time.Time // zero = active
Resolution string
MutedUntil time.Time // zero = not muted
CreatedAt time.Time
}
HealthAlert is one health_alert row. Kind is the lower-case name of the alert kind ("no_traffic").
type HealthDeviceLimitSignal ¶ added in v0.1.39
HealthDeviceLimitSignal is the device_limit_reached events of one user in the last 24 hours that turned an app away (params refused = 1): how many, when the last was, and the count and limit it saw.
type HealthNodeFlapSignal ¶ added in v0.1.46
HealthNodeFlapSignal is how often a node lost its link (node_blip) or got a new agent process soon after the last connect (agent_restarted) in the last hour.
type HealthNodeHourSignal ¶ added in v0.1.27
HealthNodeHourSignal is one peak_users value for the current hour or the same hour on a prior day.
type HealthSignalBatch ¶ added in v0.1.27
type HealthSignalBatch struct {
Users []HealthUserSignal
AWGDevices []HealthAWGSignal
NodeHours []HealthNodeHourSignal
Torrents []HealthTorrentSignal
// DeviceLimits are the people refused at their device limit; the sightings TRACK writes are history only and are not here.
DeviceLimits []HealthDeviceLimitSignal
NodeFlaps []HealthNodeFlapSignal
}
HealthSignalBatch contains the stored inputs for user and fleet impact alerts.
type HealthTorrentSignal ¶ added in v0.1.28
type HealthTorrentSignal struct {
UserID, NodeID string
Count int
LastAt time.Time
Evidence string
DstPorts []string
}
HealthTorrentSignal is the torrent_attempt events of one user on one node in the last 24 hours: how many, when the last was, what the last one matched (Evidence, "" from an older agent) and the distinct destination ports seen.
type HealthUserSignal ¶ added in v0.1.27
type HealthUserSignal struct {
ID, Name, Status string
LastTrafficAt, SubscriptionFetchAt time.Time
AccessEndedAt time.Time // expiry time, or the last traffic time for a quota limit
}
HealthUserSignal holds the stored activity timestamps used by user alerts.
type HelloInfo ¶
type HelloInfo struct {
AgentVersion string
APIVersion uint32
Instance string
BootAt time.Time
Facts NodeFactsRow
// Built is Hello.built, Caps Hello.capabilities. LastUpdateJSON is Hello.last_update as JSON (LastUpdateRow);
// "" = the Hello carried none, which keeps what is stored (the agent reports an outcome once).
Built int64
Caps []string
LastUpdateJSON string
DecoyMode string
DecoyHash string
}
HelloInfo is what a Hello tells the panel.
type InboundApplied ¶
InboundApplied is one InboundResult as stored on the inbound row.
type LastUpdateRow ¶
type LastUpdateRow struct {
Outcome string `json:"outcome"`
FromVersion string `json:"from_version"`
FromBuilt int64 `json:"from_built"`
ToVersion string `json:"to_version"`
ToBuilt int64 `json:"to_built"`
Reason string `json:"reason"`
AtUnix int64 `json:"at_unix"`
}
LastUpdateRow is Hello.last_update as stored on the node row (JSON). Outcome is "ok", "rolled_back" or "failed".
type LinkDNSOption ¶ added in v0.1.43
LinkDNSOption is one preset the owner offers for the link apps.
type LinkDeviceResult ¶ added in v0.1.39
type LinkDeviceResult struct {
Device AccessDevice
Creds []AccessCred
Added []AccessCred
FullProfiles []string // EnsureLinkAWGCreds: the profiles whose client network has no free address
// Replaced is the id of the silent device whose place the new one took (ENFORCE and STRICT), "" when none was.
Replaced string
// Born: the device is new (not found, not taken over from the shared one).
Born bool
}
LinkDeviceResult is the request's device and its live credentials as the batch (or the read that found nothing to do) left them, plus the credentials this call added: Added is what nodes have not heard of.
type LinkIssue ¶ added in v0.1.39
type LinkIssue func(deviceID string, have map[string]bool) ([]AccessCred, error)
LinkIssue makes the credentials a link device is missing. deviceID is the device they will belong to and have the protocols it already holds. It runs once per attempt between the read and the guarded write, so it must not touch the database, and its result is provisional: only what the store returns after the commit is real.
type LoginFailure ¶
LoginFailure is the effective lockout state of a login name.
type MCPPlan ¶
type MCPPlan struct {
ID, TokenID, TokenName, TokenProfile, Tool string
ParamsJSON, FactsJSON, Summary, Danger string
Reason, InnerRef string
ParamsHash, ConfirmHash []byte
NeedsApproval bool
Status string
CreatedAt, ExpiresAt, DecidedAt time.Time
AppliedAt time.Time // while applying: when it began; after: when it finished
DecidedBy, DecidedByName string
Result, Error string
// What came of it as a code the admin UI words itself, and its values (a JSON object of strings); "" before the end.
OutcomeCode, OutcomeParams string
}
MCPPlan is one mcp_plan row together with the names of its token and its decider.
type NodeDNSOption ¶ added in v0.1.17
NodeDNSOption is one preset the owner offers on a node.
type NodeFactsRow ¶
type NodeFactsRow struct {
Hostname, OS, Kernel, Arch string
CPUCount uint32
RAMTotal, DiskTotal uint64
Virt string
HasIPv6 bool
Engines []EngineRow
}
NodeFactsRow is the host facts block reported in Hello.
type NodeHealthSummary ¶ added in v0.1.49
type NodeHealthSummary struct {
NoTraffic bool `json:"no_traffic"`
Failed int `json:"failed"`
Total int `json:"total"`
DoctorFail string `json:"doctor_fail"`
}
NodeHealthSummary is the compact synthetic-check and doctor status copied to the edge admin role through a setting.
type NodeLiveRow ¶ added in v0.1.29
type NodeLiveRow struct {
NodeID string
State string
LastSeenAt time.Time
AgentCaps []string
Exists bool
Session int64
Drift bool
SampleAt int64
RxBps int64
TxBps int64
CPUPct int64
UsersJSON string
LiveJSON string
Connected bool
}
NodeLiveRow is one node and its live projection, if it has one.
type NodePatch ¶
type NodePatch struct {
Name, Address, CountryCode, Location, Provider, Notes *string
DNSResolvers *[]string
LivenessTimeoutS, ApplyTimeoutS, DialTimeoutS *int
AwgBackend *string // "auto" | "kernel" | "userspace"
TorrentBlockerEnabled *bool
BandwidthMbps *int
ClientIPv6 *bool
}
NodePatch updates the admin-editable fields; nil = unchanged.
type NodeProvisionEvent ¶
NodeProvisionEvent is a redacted, stable-code progress event.
type NodeProvisionJob ¶
type NodeProvisionJob struct {
ID, NodeID, Name, Address, CountryCode, Location, Provider string
SSHHost, HostFingerprint string
SSHPort uint16
Secret []byte
State, Phase, ErrorCode, CreatedBy string
CreatedAt, UpdatedAt time.Time
}
NodeProvisionJob is durable metadata for one owner-requested SSH installation. Secret is ciphertext produced by vault.Vault and is never returned by RPC methods.
type NodeRow ¶
type NodeRow struct {
ID, Name, Address, CountryCode, Location, Provider, Notes string
DNSResolvers []string
LivenessTimeoutS, ApplyTimeoutS, DialTimeoutS int
State string // pending | active | retired
CertSerial string
AgentVersion string
APIVersion int
BootAt, LastSeenAt, LastConnectedAt, LastDisconnectedAt time.Time // zero = never
AgentInstanceID string
LastSeq uint64
DesiredRevision uint64
DesiredHash string
AppliedRevision uint64
AppliedHash string
CreatedAt time.Time
RetiredAt time.Time
// From the last Hello: Hello.built, Hello.capabilities and Hello.last_update as JSON
// ("" = never reported; see LastUpdateRow).
AgentBuilt int64
AgentCaps []string
LastUpdateJSON string
// AwgBackend is the node setting "auto" | "kernel" | "userspace" (migration 00014), sent to agents that list awg/1.
AwgBackend string
// AwgPrepareJSON is the state of the automatic kernel-module build (migration 00019, see AwgPrepareRow); "" = never asked.
AwgPrepareJSON string
// TorrentBlockerEnabled is the per-node recognized BitTorrent traffic setting (migration 00036).
TorrentBlockerEnabled bool
// ClientIPv6 is the per-node "IPv6 for clients" switch (migration 00046); true (the default, what every node did
// before) lets clients leave over IPv6.
ClientIPv6 bool
// BandwidthMbps is the optional symmetric network capacity used to report node utilization (migration 00039).
BandwidthMbps int
// DecoyMode is the configured per-node site. DecoyBundleHash names the uploaded own bundle; agent fields come from Hello.
DecoyMode, DecoyBundleHash, DecoyAgentMode, DecoyAgentHash string
}
NodeRow is one node row.
func (NodeRow) AwgPrepare ¶
func (n NodeRow) AwgPrepare() AwgPrepareRow
AwgPrepare is the node's preparation state.
func (NodeRow) LastUpdate ¶
func (n NodeRow) LastUpdate() (LastUpdateRow, bool)
LastUpdate is what the node reported about its last self-update; false when it never did.
type NodeServerAccess ¶
type NodeServerAccess struct {
NodeID, NodeName, SSHHost, SSHUser, HostFingerprint string
SSHPort uint16
Password, PendingPassword []byte
ConfiguredAt time.Time
PasswordGenerated, NodeRetired bool
}
NodeServerAccess contains public connection metadata and vault ciphertext. Callers must never return Password or PendingPassword from an API response. NodeName is the node's current name and NodeRetired its state (both read from node); PasswordGenerated says the panel generated the saved password.
type NodeUpdateScheduleRow ¶ added in v0.1.8
type NodeUpdateScheduleRow struct {
NodeID, ToVersion, CreatedBy string
ToBuilt, ScheduledAt int64
TimezoneOffsetMinutes int32
CreatedAt time.Time
// MissedAt is when the schedule was marked missed (Unix seconds), 0 while it may still start.
MissedAt int64
}
NodeUpdateScheduleRow is an owner-scheduled rollout of one signed agent bundle to one node. ScheduledAt is an absolute UTC Unix time; TimezoneOffsetMinutes preserves the wall-clock context.
type PanelBackupSettings ¶
type PanelBackupSettings struct {
AccountID, Jurisdiction, Bucket, AccessKeyID, AgeRecipient string
SecretAccessKey []byte
Enabled bool
IntervalHours, RetentionDays int
LastSuccess time.Time
LastErrorCode string
UpdatedAt time.Time
}
PanelBackupSettings contains the saved R2 configuration. SecretAccessKey is vault ciphertext and must never be returned by an admin RPC.
type Passkey ¶
type Passkey struct {
ID string
AdminID string
CredentialID []byte
PublicKey []byte
AttestationType string
SignCount uint32
AAGUID []byte
Transports []string
Flags byte // raw authenticator data flags
Name string
CreatedAt time.Time
LastUsedAt time.Time // zero if never used to sign in
}
Passkey is a stored WebAuthn credential.
type PasswordCred ¶
type PasswordCred struct {
AdminID string
Login string // lower case
Hash string // argon2id PHC string
TOTPSecret []byte // sealed by the caller (vault); the store never sees the plain secret
TOTPStep int64 // last accepted 30 s step
}
PasswordCred is an admin's password + authenticator-code credential.
type PlanStateError ¶
type PlanStateError struct{ Status string }
PlanStateError is ErrPlanState with the status that was found. A plan past its expires_at reports "expired" even before the sweep has marked it.
func (*PlanStateError) Error ¶
func (e *PlanStateError) Error() string
func (*PlanStateError) Is ¶
func (e *PlanStateError) Is(target error) bool
type PortCheck ¶ added in v0.1.28
type PortCheck struct {
NodeID, Address string
Port uint16
Sent, Got uint32
Verdict, Sender string
CheckedAt, BadAt time.Time
}
PortCheck is the latest conclusive UDP delivery result for one node address and port.
type ProbeCredIssue ¶
type ProbeCredIssue func(idx int) (ProbeCredRow, error)
ProbeCredIssue makes the credential of an inbound once its peer index is known: it fills CredID, SecretEnc and DataJSON (the store sets InboundID and AWGIdx). It runs once per attempt between the candidate read and guarded write, so it must not access the database. Treat its result as provisional: do not keep it; only credentials returned by the store after commit or read back from the store are real.
type ProbeCredRow ¶
ProbeCredRow is the system credential of one inbound. AWGIdx is the peer index of the credential's tunnel address in the profile's client network (migration 00020); 0 for a protocol without an address (hysteria2).
type RecoveryTokenOffer ¶ added in v0.1.49
RecoveryTokenOffer is what OfferRecoveryToken found after offering the hash.
type RolloutRow ¶
type RolloutRow struct {
ID, Status, ToVersion string
ToBuilt int64
Manifest, Signature []byte
BatchSize int
PauseKey string
PauseParams map[string]string
CreatedBy string
CreatedAt, FinishedAt time.Time // FinishedAt zero while active
}
RolloutRow is one rollout of a signed bundle.
type Session ¶
type Session struct {
TokenHash []byte
AdminID string
CreatedAt time.Time
LastSeenAt time.Time
ExpiresAt time.Time
IP string
UserAgent string
StepUpAt time.Time // last proof of a sign-in factor in this session (signing in counts)
}
Session is a signed-in browser session. Only the SHA-256 of the cookie token is stored.
type SetupTokenOffer ¶ added in v0.1.35
type SetupTokenOffer struct {
AdminExists bool // an admin exists: nothing was offered
Found bool // the token's row exists
Expires time.Time // when the row (this offer or an earlier one) stops working
Used bool // the row was consumed
}
SetupTokenOffer is what OfferSetupToken found after its insert.
type StepRow ¶
type StepRow struct {
RolloutID, NodeID, NodeName string
Stage int
State string
RequestID string
RequestAt time.Time
Answer string
DownloadSHA string
FromVersion string
FromBuilt int64
PreFailed []string // inbound ids that were FAILED before the update
SentAt, AckedAt time.Time
ReconnectedAt, FinishedAt time.Time
ErrorKey string
Params map[string]string
// contains filtered or unexported fields
}
StepRow is one node's turn in a rollout.
type Stmt ¶ added in v0.1.25
type Stmt struct {
Query string
Args []any
// Returning collects rows after the statement runs. Every returned column must
// have a plain unique name: a table column or an expression with AS name.
Returning bool
}
Stmt is one statement in an atomic store batch.
type StmtResult ¶ added in v0.1.25
StmtResult is the outcome of one statement in an atomic store batch.
type Store ¶
Store wraps the writer and read pools. The VPS backend uses one writer connection and a read pool; the D1 backend uses the same binding for both pools.
func Open ¶
Open opens (creating if needed) the database at path and applies migrations. The database file is created with mode 0600 (SQLite gives the -wal and -shm files the same mode); an existing file with wider permissions is tightened.
func (*Store) APITokenBySecretHash ¶
APITokenBySecretHash finds the token for SHA-256 of a presented secret (revoked and expired ones too: the caller says why it refuses). ErrNotFound if there is none.
func (*Store) AcceptDoctor ¶
AcceptDoctor stores (or renews) an acceptance, in one statement and only while the stored result of the check is still a WARN (2) with that detail code; false when it is not (a newer report changed it, and DropStaleAccepts may have run).
func (*Store) ActiveAlerts ¶
func (s *Store) ActiveAlerts(ctx context.Context) ([]HealthAlert, error)
ActiveAlerts returns every unresolved alert.
func (*Store) ActiveRollout ¶
func (s *Store) ActiveRollout(ctx context.Context) (RolloutRow, error)
ActiveRollout is the RUNNING or PAUSED rollout, ErrNotFound when there is none.
func (*Store) AddNodeToRunningRollout ¶ added in v0.1.14
func (s *Store) AddNodeToRunningRollout(ctx context.Context, rolloutID, version string, built int64, stage int, x StepRow) error
AddNodeToRunningRollout inserts a manually selected node as its own stage after stage, shifting later stages down the rollout plan. The update and its release must still be current, and consuming the node's schedule is atomic.
func (*Store) AddPasskey ¶
AddPasskey stores another passkey for an existing admin.
func (*Store) AddPassword ¶
AddPassword gives an admin who has none a password login (c.Login lower case, c.Hash and the sealed c.TOTPSecret). ErrLoginTaken when another admin has the login, ErrAccessExists when this admin already has a password login, ErrNotFound for an unknown admin.
func (*Store) AdminCount ¶
AdminCount returns the number of admins.
func (*Store) AdminHasPassword ¶
AdminHasPassword reports whether the admin can sign in with a password.
func (*Store) AdminLogins ¶
func (s *Store) AdminLogins(ctx context.Context) ([]AdminLogin, error)
AdminLogins lists every admin, oldest first, with its password login and how many passkeys it has.
func (*Store) AdvanceTOTPStep ¶
AdvanceTOTPStep records step as used. It returns false if step is not newer than the last accepted one, which is how a code is made single-use (also across racing requests).
func (*Store) AlertCounts ¶
AlertCounts counts the active alerts that feed the badge: not muted, severity warning or critical. Alerts about people (access_ended, user_connection, torrent, device_limit) are not problems of a node and have their own list on Health, so they are left out: the badge is the number of problems of the fleet.
func (*Store) AlertHistory ¶
func (s *Store) AlertHistory(ctx context.Context, since time.Time, nodeID string, limit int) ([]HealthAlert, error)
AlertHistory returns alerts resolved since `since`, newest resolution first; nodeID "" = all.
func (*Store) AnyPassword ¶
AnyPassword reports whether any admin can sign in with a password (the sign-in page offers the password form only then).
func (*Store) ApproveMCPPlanWithSecret ¶ added in v0.1.15
func (s *Store) ApproveMCPPlanWithSecret(ctx context.Context, id, adminID string, secret []byte, now time.Time) (MCPPlan, error)
ApproveMCPPlanWithSecret is DecideMCPPlan's approval that also stores what the owner entered for the apply (vault ciphertext: the node_install SSH password), in the same compare-and-swap. TakeMCPPlanOwnerSecret hands it out once.
func (*Store) Audit ¶
Audit appends a row to the audit log. An entry without a Source takes the one of WithAuditSource, else AuditPanel.
func (*Store) AwgPrepareFinish ¶
func (s *Store) AwgPrepareFinish(ctx context.Context, nodeID string, ok bool, at int64, code, reason string) (switched bool, err error)
AwgPrepareFinish records the end of a build. When it succeeded and the admin still wants the module (Want) the node's awg_backend becomes "kernel" in the same transaction (switched = true): this is the only place the panel switches a node to the kernel module by itself, and only after the node said the module is built, loaded and verified. A failure changes nothing but the record.
func (*Store) AwgPrepareStarted ¶
AwgPrepareStarted records that a build is running (the node said so, or the admin asked and the node accepted). A build that is already recorded as running keeps its start time.
func (*Store) BeginApply ¶
func (s *Store) BeginApply(ctx context.Context, id, tokenID, tool string, paramsHash, confirmHash []byte, now time.Time) (MCPPlan, error)
BeginApply is the compare-and-swap planned|approved -> applying that lets exactly one caller run a plan. It needs the plan to belong to tokenID, to be for tool, to carry the given confirm hash and params hash (both are also checked against SHA-256 of the stored params_json, so a tampered row is refused) and to be unexpired. A plan that is not there for this token and tool is ErrNotFound: one answer, no oracle. A plan in another state is a *PlanStateError (ErrPlanState) with the status found. applied_at is set to now (the start).
func (*Store) BindTelegramChat ¶ added in v0.1.23
func (s *Store) BindTelegramChat(ctx context.Context, adminID string, chatID int64, now time.Time) error
BindTelegramChat links the chat to the admin, alerts on. The admin's earlier chat is replaced; so is the earlier owner of this chat (one chat, one admin). ErrNotFound: no such admin.
func (*Store) BlocklistHistory ¶ added in v0.1.43
BlocklistHistory reads every check since a time, oldest first inside a node, ordered by node id: the node, the time and whether a list held the address (InRKN, ListedBy). The lists are compared every 6 hours, so a week is a few dozen rows a node.
func (*Store) CertStatus ¶
CertStatus looks up an issued certificate by serial for the TLS handshake, per-RPC checks and the periodic check of a running stream. ErrNotFound if the panel never issued it.
func (*Store) CheckSetupToken ¶
CheckSetupToken returns ErrSetupClosed unless hash is an unused, unexpired setup token and no admin exists yet. It does not consume the token.
func (*Store) ClaimNodeProvisionJob ¶
func (s *Store) ClaimNodeProvisionJob(ctx context.Context, now time.Time) (NodeProvisionJob, bool, error)
ClaimNodeProvisionJob atomically claims the oldest queued job for the single panel worker and counts the attempt.
func (*Store) ClearLoginFailures ¶
ClearLoginFailures forgets the failures of login after a successful sign-in.
func (*Store) ClearPendingNodeServerPassword ¶
ClearPendingNodeServerPassword discards a replacement that could not be applied while the old login still works.
func (*Store) ClearTelegramBot ¶ added in v0.1.23
ClearTelegramBot forgets the bot and every link; dropped says how many links went.
func (*Store) CommitPendingNodeServerPassword ¶
func (s *Store) CommitPendingNodeServerPassword(ctx context.Context, nodeID string, encryptedCurrent []byte, ownerChosen bool, now time.Time) error
CommitPendingNodeServerPassword promotes the verified node-bound ciphertext and removes its recovery copy. ownerChosen says the owner typed the promoted password (it clears the generated mark); a recovered pending value leaves it.
func (*Store) CompleteNodeProvisionJob ¶
func (s *Store) CompleteNodeProvisionJob(ctx context.Context, id string, access NodeServerAccess, now time.Time) error
CompleteNodeProvisionJob clears the temporary job secret and retains the verified SSH credential in the encrypted access table in the same transaction as the completion event.
func (*Store) ConsumeAuthCeremony ¶ added in v0.1.27
ConsumeAuthCeremony deletes a ceremony, returning whether this call won.
func (*Store) ConsumeRecoveryToken ¶ added in v0.1.49
ConsumeRecoveryToken atomically spends an unused, unexpired recovery token. The row remains so a used token can never be offered again, even if the same secret is accidentally uploaded later.
func (*Store) CountryVerdictChanges ¶ added in v0.1.43
func (s *Store) CountryVerdictChanges(ctx context.Context, country string, since time.Time) ([]CountryCheck, error)
CountryVerdictChanges reads the rounds of one country since a time that changed a node's verdict: the first round of every node and each round whose verdict differs from the one before it, oldest first inside a node, ordered by node id. Only the node, the time and the verdict: the Reachability page's history needs no more, and a week of rounds every 10 minutes is a thousand rows a node that would otherwise cross the D1 binding.
func (*Store) CreateAPIToken ¶
CreateAPIToken stores a new token whose secret hashes to secretHash. The name must be free among the unrevoked tokens (ErrNameTaken) and fewer than MaxLiveTokens live ones may exist (ErrTokenLimit); both checks are SQL guards on the insert statement. t.CreatedAt is "now" for the cap.
func (*Store) CreateEnrollment ¶
func (s *Store) CreateEnrollment(ctx context.Context, n *NodeRow, nodeID string, tokenHash []byte, createdBy string, now, expires time.Time) (NodeRow, error)
CreateEnrollment issues an enrollment token. With n != nil it also creates the (pending) node in the same batch (ErrConflict when the name is taken); otherwise nodeID must be an existing, non-retired node (re-enrollment). Older unused tokens of the node stop working. The returned node is the current row.
func (*Store) CreateFirstAdmin ¶
func (s *Store) CreateFirstAdmin(ctx context.Context, tokenHash []byte, now time.Time, a Admin, p Passkey) error
CreateFirstAdmin atomically consumes the setup token and inserts the first admin and its passkey. It returns ErrSetupClosed if the token is not valid any more or an admin already exists, so a token can never create two admins.
func (*Store) CreateFirstAdminPassword ¶
func (s *Store) CreateFirstAdminPassword(ctx context.Context, tokenHash []byte, now time.Time, a Admin, c PasswordCred) error
CreateFirstAdminPassword is CreateFirstAdmin for an admin whose first credential is a password + authenticator code instead of a passkey. A login name that is taken (it cannot be, before the first admin exists) is reported like any other insert error.
func (*Store) CreateMCPPlan ¶
func (s *Store) CreateMCPPlan(ctx context.Context, p MCPPlan, maxOpenPerToken, maxAwaiting int) error
CreateMCPPlan stores a new plan. Status must be planned (a safe tool) or awaiting (needs_approval). ID, ParamsHash (SHA-256 of ParamsJSON) and the expiry (CreatedAt + PlanTTL) are filled in when empty; ConfirmHash is required. A token may hold maxOpenPerToken open plans, and a new awaiting plan counts against maxAwaiting awaiting ones in the whole panel (ErrTooManyPlans). A revoked token cannot make plans (*PlanStateError cancelled).
func (*Store) CreateNodeProvisionJob ¶
func (s *Store) CreateNodeProvisionJob(ctx context.Context, job NodeProvisionJob) error
CreateNodeProvisionJob persists an owner-confirmed SSH installation request.
func (*Store) CreatePasswordSession ¶
func (s *Store) CreatePasswordSession(ctx context.Context, sess Session, checked PasswordCred) error
CreatePasswordSession is CreateSession for a password + code sign-in: the row goes in only while the admin's password and authenticator secret are still the ones the sign-in checked, else ErrNotFound. A reset or re-bind that lands between the check and this insert (and ends every session) then cannot be outlived by a session of the old credentials.
func (*Store) CreateRollout ¶
CreateRollout stores a rollout and its steps in one atomic batch. ErrConflict when another rollout is active (the unique index 00013 allows one RUNNING or PAUSED rollout).
func (*Store) CreateRolloutAndClearSchedules ¶ added in v0.1.8
func (s *Store) CreateRolloutAndClearSchedules(ctx context.Context, r RolloutRow, steps []StepRow, nodeIDs []string) error
CreateRolloutAndClearSchedules atomically starts an owner-triggered rollout and removes any scheduled update for nodes that it will update. A later timer must not undo that choice.
func (*Store) CreateScheduledRollout ¶ added in v0.1.8
func (s *Store) CreateScheduledRollout(ctx context.Context, r RolloutRow, steps []StepRow, schedule NodeUpdateScheduleRow) error
CreateScheduledRollout atomically starts a scheduled node update and consumes the exact schedule it was based on. A concurrent reschedule or cancellation makes this fail safely.
func (*Store) CreateSession ¶
CreateSession inserts a session. Signing in is itself a proof of a factor, so StepUpAt starts at CreatedAt.
func (*Store) CreateWarpAccount ¶
func (s *Store) CreateWarpAccount(ctx context.Context, a WarpAccountRow) error
CreateWarpAccount stores a new account. ErrConflict when the node already has one (one per node: delete first), ErrNotFound when there is no such node.
func (*Store) DailyRows ¶
DailyRows returns the aggregates of an inbound (all when inboundID is empty), oldest day first.
func (*Store) DecideMCPPlan ¶
func (s *Store) DecideMCPPlan(ctx context.Context, id, adminID string, approve bool, now time.Time) (MCPPlan, error)
DecideMCPPlan is the owner's answer to a plan awaiting approval: a compare-and-swap awaiting -> approved or rejected that also needs the plan unexpired and its token unrevoked. ErrNotFound for an unknown id, *PlanStateError (ErrPlanState) with the status found when the plan is not awaiting any more.
func (*Store) DeleteAdminSession ¶
func (s *Store) DeleteAdminSession(ctx context.Context, adminID string, tokenHash []byte) (bool, error)
DeleteAdminSession ends one of the admin's sessions; it reports whether there was one.
func (*Store) DeleteBlocklistChecks ¶ added in v0.1.41
DeleteBlocklistChecks forgets every stored check (Disconnect).
func (*Store) DeleteNodeUpdateSchedule ¶ added in v0.1.8
DeleteNodeUpdateSchedule removes a node's schedule and reports whether one existed.
func (*Store) DeleteNodeUpdateScheduleIfMatches ¶ added in v0.1.8
func (s *Store) DeleteNodeUpdateScheduleIfMatches(ctx context.Context, r NodeUpdateScheduleRow) (bool, error)
DeleteNodeUpdateScheduleIfMatches removes only the schedule observed by a worker. A concurrent reschedule must survive.
func (*Store) DeleteOtherSessions ¶
DeleteOtherSessions ends every session of the admin except keep, returning how many.
func (*Store) DeletePasskey ¶
DeletePasskey removes one of the admin's passkeys. It returns ErrNotFound if the admin has no such passkey and ErrLastMethod if it is the only way the admin can sign in.
func (*Store) DeleteSession ¶
DeleteSession removes a session (logout or expiry).
func (*Store) DeleteSettings ¶ added in v0.1.42
DeleteSettings removes the settings; a key that is not there is ignored.
func (*Store) DeleteTSPUChecks ¶ added in v0.1.42
DeleteTSPUChecks forgets every stored row (Disconnect).
func (*Store) DeleteWarpAccount ¶
DeleteWarpAccount removes the account. ErrNotFound when the node has none.
func (*Store) DoctorAccepts ¶
DoctorAccepts lists the acceptances of one node, or of every node for "".
func (*Store) DoctorResults ¶
DoctorResults returns the stored results of one node, or of every node for "" (ordered by node, check).
func (*Store) DownloadStep ¶ added in v0.1.48
DownloadStep returns the pinned manifest and token digest only while the node has a SENT step in an active rollout.
func (*Store) DropStaleAccepts ¶
DropStaleAccepts removes the acceptances of a node that its stored doctor results no longer match: the check turned FAIL (3), or it is a WARN (2) with another detail code. Run after storing a report.
func (*Store) DueNodeUpdateSchedules ¶ added in v0.1.8
func (s *Store) DueNodeUpdateSchedules(ctx context.Context, now time.Time) ([]NodeUpdateScheduleRow, error)
DueNodeUpdateSchedules returns the earliest schedules whose requested time has arrived and that were not missed.
func (*Store) Enroll ¶
func (s *Store) Enroll(ctx context.Context, tokenHash, keyHash []byte, now time.Time, issue func(nodeID string) (CertRow, error)) (EnrollResult, error)
Enroll consumes a one-time token. keyHash is sha256 of the CSR public key; issue signs a certificate for the node after the reads and before the guarded batch (only for a first use). Errors: ErrEnrollToken, ErrNodeRetired. A repeat with the same token and key within 10 minutes of first use returns the stored certificate. Every other certificate of the node is revoked (re-enrollment).
func (*Store) Events ¶
func (s *Store) Events(ctx context.Context, f EventFilter) (out []EventRow, hasMore bool, err error)
Events returns events newest first, names resolved from the node/user rows (a missing row leaves the name empty). hasMore reports that more rows exist beyond Limit.
func (*Store) ExpireMCPPlans ¶
ExpireMCPPlans is the once-a-minute sweep: unapplied plans past their expiry become expired; plans stuck in applying for ApplyStuckAfter (the panel restarted mid-call: the outcome is unknown and an apply is never resumed) become failed; finished plans older than PlanKeep are deleted; an owner secret left on a plan that can no longer be applied is cleared. It returns how many rows it touched.
func (*Store) FailAuthCeremony ¶ added in v0.1.27
FailAuthCeremony advances one recoverable code failure and deletes the ceremony at the limit.
func (*Store) FailWithheldInbounds ¶
func (s *Store) FailWithheldInbounds(ctx context.Context, nodeID string, ids []string, reason string, now time.Time) error
FailWithheldInbounds marks inbounds the panel did not send to a node (its agent lacks a capability) as failed with the reason. The reconcile calls it, because an agent that is sent nothing answers nothing and the row would stay pending for ever. It writes only what differs, so a repeated call changes no row.
func (*Store) FinishApply ¶
func (s *Store) FinishApply(ctx context.Context, id string, ok bool, result, errText, outcomeCode, outcomeParams string, now time.Time) error
FinishApply ends an apply: applying -> applied (ok, with result) or failed (errText), with the outcome as a code and its values (a JSON object of strings, "" = none). An owner secret still there is cleared. *PlanStateError if the plan is not applying (the sweep may have given up on it).
func (*Store) FinishCancelledNodeProvisionJob ¶
func (s *Store) FinishCancelledNodeProvisionJob(ctx context.Context, id string, now time.Time) (bool, error)
FinishCancelledNodeProvisionJob clears credentials after an active worker stops. The remote host may already have received some installation commands.
func (*Store) FleetDeviceModels ¶
FleetDeviceModels resolves device ids to "platform model" labels.
func (*Store) FleetEnabledInbounds ¶
FleetEnabledInbounds returns the enabled inbounds of every node with the name of the profile each deploys: node id -> inbound id -> profile name. One query for the whole fleet: the Overview and the node list ask on every poll, and the status of a node needs them (no profiles at all, which profile failed, how many there are).
func (*Store) FleetHours ¶
FleetHours returns the hourly rollup since the given hour (Overview, node cards).
func (*Store) FleetInbound ¶
FleetInbound returns one inbound by id, or ErrNotFound.
func (*Store) FleetInbounds ¶
func (s *Store) FleetInbounds(ctx context.Context, nodeID string, onlyEnabled bool) ([]FleetInboundRow, error)
FleetInbounds returns the inbounds of a node ordered by id.
func (*Store) FleetNodeProtocols ¶
FleetNodeProtocols returns the distinct protocols of the enabled inbounds per node.
func (*Store) FleetTopUsers ¶
func (s *Store) FleetTopUsers(ctx context.Context, nodeID string, sinceHour int64, limit int) ([]FleetTop, error)
FleetTopUsers returns the top users of a node by bytes since the given hour ("top today").
func (*Store) FleetUserNames ¶
FleetUserNames resolves user ids to names (missing ids are absent from the result).
func (*Store) ForgetNodeServerAccess ¶ added in v0.1.15
ForgetNodeServerAccess deletes the saved access of a retired node, its sealed password included: the owner's explicit decision, since retiring keeps it. ErrNotFound: no saved access; ErrConflict: the node is not retired.
func (*Store) GateRollbacks ¶
GateRollbacks returns, per node, the newest step that ended rolled back by the gate: a rolled_back step whose error key is neither the owner's (manual) nor the agent's own (rolled_back_by_agent).
func (*Store) GetAPIToken ¶
GetAPIToken returns one token. ErrNotFound if there is none.
func (*Store) GetAuthCeremony ¶ added in v0.1.27
func (s *Store) GetAuthCeremony(ctx context.Context, id string, now time.Time) (AuthCeremony, error)
GetAuthCeremony reads one live row without consuming it.
func (*Store) GetMCPPlan ¶
GetMCPPlan returns one plan with its stored status. ErrNotFound if there is none.
func (*Store) HealthAlert ¶
HealthAlert returns one alert or ErrNotFound.
func (*Store) HealthSignals ¶ added in v0.1.27
HealthSignals reads the user, AWG, hourly fleet, torrent, device-limit and node-flap inputs in one read batch.
func (*Store) IngestEvent ¶
func (s *Store) IngestEvent(ctx context.Context, nodeID, instance string, seq uint64, now time.Time, e EventRow) (dup bool, err error)
IngestEvent stores one reliable agent Event and node.last_seq in one atomic batch. dup reports that the seq was already committed.
func (*Store) IngestStats ¶
func (s *Store) IngestStats(ctx context.Context, in FleetStatsIn) (FleetStatsOut, error)
IngestStats commits one StatsBatch in one read batch and one guarded write batch together with node.last_seq (agent.proto "RELIABLE MESSAGES"): traffic buckets and hourly peaks, user usage, inbound certificates, and device touches. seq == 0 (not a reliable message) skips the dedup and the counter update.
func (*Store) InsertBlocklistChecks ¶ added in v0.1.41
func (s *Store) InsertBlocklistChecks(ctx context.Context, rows []BlocklistCheck) error
InsertBlocklistChecks stores the rows of one check in one statement. A row for the same node and second is replaced.
func (*Store) InsertCountryChecks ¶ added in v0.1.41
func (s *Store) InsertCountryChecks(ctx context.Context, rows []CountryCheck) error
InsertCountryChecks stores the rows of one round in one statement. A row for the same node and second is replaced.
func (*Store) InsertEvent ¶
InsertEvent appends an event (for panel and admin events; other modules may use it too).
func (*Store) InsertProbeCred ¶
InsertProbeCred stores a credential unless the inbound already has one (two callers racing: the first wins, both then read the same row back with ProbeCred). ErrNotFound when the inbound does not exist.
func (*Store) InsertProbeCredIdx ¶
func (s *Store) InsertProbeCredIdx(ctx context.Context, inboundID, profileID string, maxIdx int, now time.Time, issue ProbeCredIssue) error
InsertProbeCredIdx stores the credential of an inbound whose credential holds a tunnel address (AWG): the peer index comes from the profile's allocator, the same one the devices use. A guarded batch protects the index and credential together, so a device added at the same moment cannot get the same address. An inbound that has a credential already keeps it (two callers racing: the first wins, both then read the same row back with ProbeCred). ErrNotFound when the inbound does not exist, ErrAccessSubnetFull when the network has no free index.
func (*Store) InsertResolvedAlert ¶
func (s *Store) InsertResolvedAlert(ctx context.Context, a HealthAlert) error
InsertResolvedAlert writes a history-only record (HOST_BLIP): an alert that never was active.
func (*Store) InsertSample ¶
func (s *Store) InsertSample(ctx context.Context, c CheckSample) error
InsertSample stores a round. A second round of the same inbound in the same second replaces the first.
func (*Store) InsertTSPUChecks ¶ added in v0.1.42
InsertTSPUChecks stores the rows of one run in one statement. A row for the same node, vantage and second is replaced.
func (*Store) LastAuditByNode ¶
LastAuditByNode returns, per params.node_id, the time of the newest audit row of an action.
func (*Store) LastCountryCheckAt ¶ added in v0.1.41
LastCountryCheckAt is the time of the newest stored round of any node, zero when there is none.
func (*Store) LastNodeEventCode ¶
func (s *Store) LastNodeEventCode(ctx context.Context, nodeID string, codes ...string) (string, error)
LastNodeEventCode returns the code of the newest event of the node among codes ("" if none). Used to emit node_down once per outage without extra state.
func (*Store) LastTSPUCheckAt ¶ added in v0.1.42
LastTSPUCheckAt is the time of the newest row from one vantage, zero when there is none.
func (*Store) LatestRollout ¶
func (s *Store) LatestRollout(ctx context.Context) (RolloutRow, error)
LatestRollout is the newest rollout of any status, ErrNotFound when there never was one.
func (*Store) LinkCertificates ¶ added in v0.1.26
func (s *Store) LinkCertificates(ctx context.Context, nodeID string, now time.Time) ([]CertRow, error)
LinkCertificates returns the node certificates that mTLS would still accept at now, including a previous certificate inside the renewal grace period. Retired nodes have no acceptable certificates.
func (*Store) ListAPITokens ¶
ListAPITokens returns every token, newest first, revoked and expired ones included.
func (*Store) ListApprovals ¶
func (s *Store) ListApprovals(ctx context.Context, now time.Time, awaitingOnly bool, historyLimit int) (rows []MCPPlan, awaiting int, err error)
ListApprovals returns the plans that need the owner (needs_approval = 1): those awaiting a decision first (oldest first), then up to historyLimit others, newest first (0 = 50, at most 200), unless awaitingOnly. The status of a plan past its expiry is reported as expired whether or not the sweep ran. awaiting counts the plans still awaiting at now.
func (*Store) ListAudit ¶
func (s *Store) ListAudit(ctx context.Context, source string, beforeID int64, limit int) ([]AuditRow, error)
ListAudit returns up to limit rows, newest first, with id < beforeID (0 = from the newest), optionally only those of one source ("" = all).
func (*Store) ListAuditQuery ¶
ListAuditQuery returns the rows of q.
func (*Store) LoginFailures ¶
func (s *Store) LoginFailures(ctx context.Context, login string, now time.Time, window time.Duration) (LoginFailure, error)
LoginFailures returns the lockout state of login (zero value if it has none).
func (*Store) MCPPlanByConfirm ¶
func (s *Store) MCPPlanByConfirm(ctx context.Context, tokenID string, confirmHash []byte) (MCPPlan, error)
MCPPlanByConfirm finds the plan of a token by SHA-256 of its confirm token. The status is the stored one: compare ExpiresAt with the clock. ErrNotFound if the token has no such plan.
func (*Store) MarkNodeUpdateSchedulesMissed ¶ added in v0.1.15
func (s *Store) MarkNodeUpdateSchedulesMissed(ctx context.Context, cutoff, now time.Time) (int64, error)
MarkNodeUpdateSchedulesMissed marks the schedules whose time was before cutoff and that have not started: they never start by themselves afterwards. It returns how many it marked.
func (*Store) MarkStepSent ¶ added in v0.1.48
MarkStepSent moves a pending step to SENT only while its rollout is running and the loaded snapshot is current.
func (*Store) MuteAlert ¶
MuteAlert sets (or, with a zero until, clears) the mute of an active alert and returns it. ErrNotFound when the alert does not exist, ErrConflict when it is already resolved.
func (*Store) NodeApplied ¶
func (s *Store) NodeApplied(ctx context.Context, id string, session uint64, drift bool, rev uint64, hash string, in []InboundApplied, now time.Time) error
NodeApplied records an ApplyResult: the node's applied revision/hash and per-inbound outcome.
func (*Store) NodeDecoyBundle ¶ added in v0.1.36
NodeDecoyBundle reads a bundle by its content address and verifies the stored bytes.
func (*Store) NodeDesired ¶
func (s *Store) NodeDesired(ctx context.Context, id string, rev uint64, hash string, digest []byte) error
NodeDesired stores the desired revision and hash (kept across panel restarts so revisions stay monotonic: an older revision leaves the node row alone) and, in the same batch, the digest of what was sent, which carries its own revision.
func (*Store) NodeDisconnected ¶
func (s *Store) NodeDisconnected(ctx context.Context, id string, session uint64, seen, now time.Time) error
NodeDisconnected records the end of the session that still owns the live row.
func (*Store) NodeEventSince ¶
func (s *Store) NodeEventSince(ctx context.Context, nodeID, code string, since time.Time, toBuilt int64) (bool, error)
NodeEventSince reports whether the node has an event with this code at or after since (Unix seconds compare). A non-zero toBuilt also requires the event's to_built parameter, when it has one, to be that build (an event without the parameter, from an older agent, is judged by time alone).
func (*Store) NodeHello ¶
func (s *Store) NodeHello(ctx context.Context, id string, session uint64, h HelloInfo, now time.Time) (prev NodeRow, ackedSeq uint64, err error)
NodeHello records a (re)connect: the node becomes active, facts are stored, and the reliable-message counter is reset when the agent instance changed. prev is the row before the update (for blip/restart detection); ackedSeq is the highest committed seq of this instance. ErrNodeRetired for retired nodes.
func (*Store) NodeInSync ¶ added in v0.1.45
func (s *Store) NodeInSync(ctx context.Context, id string, session uint64, rev uint64, hash string) error
NodeInSync records a node whose Hello reported the state the panel wants: its applied revision and hash, and no drift in the session's live row.
func (*Store) NodeLive ¶ added in v0.1.29
func (s *Store) NodeLive(ctx context.Context, now time.Time, nodeID string, view bool) ([]NodeLiveRow, error)
NodeLive lists node live projections. An empty nodeID lists every node; view includes live_json.
func (*Store) NodeProvisionEvents ¶
func (s *Store) NodeProvisionEvents(ctx context.Context, jobID string, after int64, limit int) ([]NodeProvisionEvent, int64, error)
NodeProvisionEvents returns events after the given cursor and the final cursor.
func (*Store) NodeProvisionJob ¶
NodeProvisionJob returns one job without unsealing its secret.
func (*Store) NodeProvisionJobState ¶ added in v0.1.1
NodeProvisionJobState reads only the durable worker state, without loading the encrypted credential blob.
func (*Store) NodeProvisionJobs ¶
NodeProvisionJobs returns the most recently changed jobs, newest first.
func (*Store) NodeProvisionJobsPending ¶ added in v0.1.35
NodeProvisionJobsPending reports whether any install job is queued, running or being cancelled: the edge cron wakes the provisioner only then.
func (*Store) NodeProvisionJobsQueued ¶ added in v0.1.35
NodeProvisionJobsQueued reports whether a job waits for a worker.
func (*Store) NodeServerAccess ¶
NodeServerAccess returns one node's encrypted SSH credential and public metadata.
func (*Store) NodeServerAccesses ¶
func (s *Store) NodeServerAccesses(ctx context.Context) ([]NodeServerAccess, error)
NodeServerAccesses lists access metadata in stable name order, live nodes before retired ones of the same name.
func (*Store) NodeUpdateSchedules ¶ added in v0.1.8
NodeUpdateSchedules returns all pending schedules indexed by node id, missed ones included.
func (*Store) NodeWithSentDigest ¶ added in v0.1.27
NodeWithSentDigest returns one node and its last-sent digest in one read batch.
func (*Store) OfferRecoveryToken ¶ added in v0.1.49
func (s *Store) OfferRecoveryToken(ctx context.Context, hash []byte, expires time.Time) (RecoveryTokenOffer, error)
OfferRecoveryToken offers the current Worker secret once, for thirty minutes from the first offer. It keeps every hash's first expiry across isolates, so superseded, expired, or used rows can never be revived by re-offering a hash.
func (*Store) OfferSetupToken ¶ added in v0.1.35
func (s *Store) OfferSetupToken(ctx context.Context, hash []byte, expires time.Time) (SetupTokenOffer, error)
OfferSetupToken makes hash a setup token for whoever deploys the panel (the hash comes from the deploy tool, the panel never sees the token). One batch inserts the row only while no admin exists and keeps an existing row as it is, so concurrent isolates offer it once and an expired or used token is never revived; a second statement reads back the admin count and the row.
func (*Store) OnlineDevices ¶ added in v0.1.39
OnlineDevices lists the devices that have a session on a connected node as (device id, node id) pairs, in node order. It reads node_live.devices only, not the live_json of the view.
func (*Store) OpenAlert ¶
func (s *Store) OpenAlert(ctx context.Context, a HealthAlert, reopenWithin time.Duration, now time.Time) (out HealthAlert, reopened bool, err error)
OpenAlert records that the condition of a holds. A resolved alert of the same key that ended less than reopenWithin ago is re-opened (id and first_seen stay, so flapping does not fill the history; opened_at moves to now, the start of the new episode); otherwise a row is inserted. The active-alert unique index makes concurrent opens update the same row instead of duplicating it.
func (*Store) PanelBackupSettings ¶
func (s *Store) PanelBackupSettings(ctx context.Context) (PanelBackupSettings, error)
func (*Store) PasskeyByCredentialID ¶
PasskeyByCredentialID returns the passkey with the given WebAuthn credential id.
func (*Store) PasskeysByAdmin ¶
PasskeysByAdmin lists an admin's passkeys.
func (*Store) PasswordByAdmin ¶
PasswordByAdmin returns the password credential of an admin, or ErrNotFound.
func (*Store) PasswordByLogin ¶
PasswordByLogin returns the credential for a (lower-case) login name, or ErrNotFound.
func (*Store) PendingEnrollmentExpiry ¶
func (s *Store) PendingEnrollmentExpiry(ctx context.Context, nodeID string, now time.Time) (time.Time, error)
PendingEnrollmentExpiry returns when the newest usable enrollment token of the node expires; the zero time if there is none.
func (*Store) PortChecks ¶ added in v0.1.28
PortChecks reads stored results, ignoring rows whose node address has since changed. With no nodeIDs it returns every current result.
func (*Store) PruneBlocklistChecks ¶ added in v0.1.41
PruneBlocklistChecks deletes the checks older than the cut and returns how many went.
func (*Store) PruneCountryChecks ¶ added in v0.1.41
PruneCountryChecks deletes the rounds older than the cut and returns how many went.
func (*Store) PruneEvents ¶
func (s *Store) PruneEvents(ctx context.Context, now time.Time, info, other time.Duration, batch int) (int64, error)
PruneEvents deletes events older than info (severity 1) and older than other (severity 2 and 3), in batches so the single writer is never held for long. It returns the number of rows removed.
func (*Store) PruneHealth ¶
func (s *Store) PruneHealth(ctx context.Context, now time.Time, samples, daily, alerts time.Duration) (int64, error)
PruneHealth deletes check rounds older than samples, aggregates older than daily and alerts resolved longer ago than alerts. It returns the number of rows removed.
func (*Store) PruneRevokedDevices ¶ added in v0.1.39
func (s *Store) PruneRevokedDevices(ctx context.Context, cutoff time.Time, batch int) (int64, error)
PruneRevokedDevices deletes devices revoked before cutoff and not blocked (a block is kept for good), at most batch rows at a time, until none is left or ctx ends. A device row is referenced by its credentials, which cascade (and their AmneziaWG peers with them); a device that still holds a live credential, which a revoke never leaves, is skipped. It returns how many rows it removed.
func (*Store) PruneRollouts ¶
PruneRollouts deletes finished rollouts (their steps go with them) that are older than cutoff and are not among the newest keep finished ones. An active rollout is never touched. It returns how many were removed.
func (*Store) PruneTSPUChecks ¶ added in v0.1.42
PruneTSPUChecks deletes the rows older than the cut and returns how many went.
func (*Store) PurgeSessions ¶
PurgeSessions deletes sessions past their absolute expiry or idle for longer than idle.
func (*Store) PutAuthCeremony ¶ added in v0.1.26
func (s *Store) PutAuthCeremony(ctx context.Context, c AuthCeremony, now time.Time, maxPerSource, maxTotal int) error
PutAuthCeremony prunes up to 100 expired rows, then inserts only while both caps allow it.
func (*Store) PutDoctor ¶
func (s *Store) PutDoctor(ctx context.Context, nodeID string, rows []DoctorRow, replace bool, now time.Time) error
PutDoctor stores results of one node: replace drops the node's other rows first (a full report), otherwise the rows are merged by check id (a partial one). Received is set on every row.
func (*Store) PutPortChecks ¶ added in v0.1.28
PutPortChecks replaces the latest conclusive results in one atomic multi-row statement.
func (*Store) PutSetupToken ¶
PutSetupToken stores a new one-time setup token hash and drops older unused ones, so only the latest printed link works.
func (*Store) PutTCPChecks ¶ added in v0.1.35
PutTCPChecks replaces a node's TCP check rows with checks (all of one node) in one batch. An empty list clears them.
func (*Store) RecentBlocklistChecks ¶ added in v0.1.41
func (s *Store) RecentBlocklistChecks(ctx context.Context, nodeIDs ...string) ([]BlocklistCheck, error)
RecentBlocklistChecks reads the newest check of every node (or of the given nodes), ordered by node id.
func (*Store) RecentCountryChecks ¶ added in v0.1.41
func (s *Store) RecentCountryChecks(ctx context.Context, perNode int, nodeIDs ...string) ([]CountryCheck, error)
RecentCountryChecks reads up to perNode newest rounds of every node (or of the given nodes), newest first inside a node.
func (*Store) RecentSamples ¶
RecentSamples returns the newest n rounds of an inbound, newest first (to rebuild the fail streak after a restart).
func (*Store) RecentTSPUChecks ¶ added in v0.1.42
RecentTSPUChecks reads the newest row of every node and vantage (of the given nodes only, when there are any), ordered by node id and vantage.
func (*Store) RecordDeviceLimitReached ¶ added in v0.1.27
func (s *Store) RecordDeviceLimitReached(ctx context.Context, userID string, used, limit int, mode string, refused bool, now time.Time) error
RecordDeviceLimitReached adds one user-history event per user per hour, per kind: a refusal (refused: an app was turned away at the limit) and a sighting (TRACK let the device in past the limit) are counted apart, so a sighting does not hide the refusal that follows it in the same hour. Only the refusals open the device-limit alert (HealthSignals). mode is the link-device mode the decision was made in ("" for an AmneziaVPN key, which has no mode). The read skips repeated writes; the conditional insert protects concurrent refusals from adding duplicate rows.
func (*Store) RecordLoginFailure ¶
func (s *Store) RecordLoginFailure(ctx context.Context, login string, now time.Time, maxFailures int, window, lock time.Duration) (LoginFailure, error)
RecordLoginFailure counts one failed sign-in for login. Reaching maxFailures failures within window locks the login for lock. It also drops stale rows, so the table cannot grow without bound from names an attacker makes up.
func (*Store) RecordPanelBackupRun ¶
func (*Store) RecoveryTokenLive ¶ added in v0.1.49
RecoveryTokenLive reports whether hash is an unused, unexpired recovery token. It does not consume the token.
func (*Store) ReleaseLease ¶ added in v0.1.48
ReleaseLease deletes name only if holder still owns it.
func (*Store) RenewCert ¶
func (s *Store) RenewCert(ctx context.Context, c CertRow, fromSerial string, now time.Time, grace time.Duration) error
RenewCert records a certificate issued by Renew and makes it the node's current one. The node's other certificates are scheduled for revocation grace after now (a lost response must not lock the agent out, a stolen key must not live out its 30 days): revoked_at is set in the future and CertStatus honours it from then on. A certificate that is already scheduled keeps its earlier time, so renewing again with the old certificate does not extend it.
One guarded batch (the mTLS Renew and the link's renew frame both end here): fromSerial, the certificate that presented the request, must still be valid for this node at now (a certificate inside a renewal's grace may renew: the agent retries after a lost answer; a re-enrolment or retirement revokes outright, so a renewal that read its clock before that commit still cannot pass), and the node must not be retired. A re-enrolment or retirement that committed before this batch therefore cannot be undone by a renewal that was already in flight. The node also gets at most RenewMax certificates per RenewWindow, so a stolen key cannot grow node_cert without bound. Refusal: ErrRenewRefused.
func (*Store) ReplaceWarpAccount ¶
func (s *Store) ReplaceWarpAccount(ctx context.Context, a WarpAccountRow) error
ReplaceWarpAccount swaps the account of the node for a new one in one atomic batch (a re-registration: the old account must survive a failure to store the new one). ErrNotFound when the node has no account.
func (*Store) RequestCancelNodeProvisionJob ¶
func (s *Store) RequestCancelNodeProvisionJob(ctx context.Context, id string, now time.Time) (state string, changed bool, err error)
RequestCancelNodeProvisionJob atomically stops queued work or requests cancellation of the active worker. The returned state is either cancelled or cancel_requested.
func (*Store) RequeueNodeProvisionJobs ¶
RequeueNodeProvisionJobs restores interrupted work after a panel restart: a running job goes back to the queue, unless it has already been claimed MaxProvisionAttempts times, in which case it fails with job_interrupted and its secret is erased like on any other failure.
func (*Store) ResetPasswordLogin ¶
func (s *Store) ResetPasswordLogin(ctx context.Context, c PasswordCred, create bool, clearLocks []string, now time.Time, audit AuditEntry) (int, error)
ResetPasswordLogin is the operator's way back in (mistgate auth reset-login), in one atomic batch: c becomes the admin's password login (a new password and authenticator secret for its existing login, or a new login when create is set), the lockouts named in clearLocks are lifted, every session of the admin ends, and the audit row is written. The last accepted authenticator step of an existing login never goes back. It returns how many sessions ended.
func (*Store) ResolveAlert ¶
func (s *Store) ResolveAlert(ctx context.Context, id, resolution string, now time.Time) (bool, error)
ResolveAlert ends an active alert. It reports false when the alert was not active any more.
func (*Store) RetireNode ¶
RetireNode marks the node retired, revokes every certificate and kills unused enrollment tokens. The row, its traffic and its events stay, and so does its saved server access: the sealed password may be the only copy (a generated one), so only the owner's ForgetNodeServerAccess deletes it. ErrNotFound / ErrNodeRetired as appropriate.
func (*Store) RetryNodeProvisionJob ¶ added in v0.1.15
func (s *Store) RetryNodeProvisionJob(ctx context.Context, id, from string, secret []byte, now time.Time) error
RetryNodeProvisionJob requeues a failed or cancelled job with a freshly sealed credential. It changes the job only while it is still in the state the caller read (from): a double submit cannot requeue a job a worker has already claimed (ErrConflict). ErrNameTaken: a live node or another active install took the name meanwhile.
func (*Store) RevokeAPIToken ¶
RevokeAPIToken revokes a token and cancels its open plans in one transaction. It is idempotent: a second call changes nothing (the first revoker and time stay) and returns the token. ErrNotFound for an unknown id. The partial unique index on the name is freed by the revocation.
func (*Store) RolloutSteps ¶
RolloutSteps lists the steps of a rollout by stage, then node name.
func (*Store) RollupDaily ¶
RollupDaily aggregates the stored rounds of every UTC day that has ended before now into health_check_daily. A day that already has a row is left alone, so it runs safely every hour. The raw rounds live 25 h, which covers a whole finished day for an hour after midnight. A panel that was down for more than an hour after midnight loses that day's aggregate for the hours already pruned (it is computed from what is left); nothing reads the aggregates yet.
func (*Store) SamplesSince ¶
SamplesSince returns every stored round at or after since, oldest first, per inbound.
func (*Store) SavePanelBackupSettings ¶
func (s *Store) SavePanelBackupSettings(ctx context.Context, v PanelBackupSettings, now time.Time) error
SavePanelBackupSettings replaces owner-editable settings while retaining the last successful run and status.
func (*Store) SaveStep ¶
SaveStep overwrites the mutable fields of a step. A row read by RolloutSteps is a compare-and-set on the state and recorded-answer identity; a caller that did not read the row saves without that guard.
func (*Store) SaveSubscriptionSettings ¶ added in v0.1.39
func (s *Store) SaveSubscriptionSettings(ctx context.Context, kv map[string]string, mode string, now time.Time) (revoked int, err error)
SaveSubscriptionSettings stores settings (kv) and the mode of the device limit ("" = leave it) in one batch. Switching to LinkModeStrict revokes every live shared link device in the same batch, like RevokeDevice does for one (the device, the quarantine of its AmneziaWG addresses, its credentials), so that no fetch can find the mode and a shared device together: one that decided on the old mode fails linkModeGuard and repeats. revoked is how many people lost a shared device (STRICT only).
func (*Store) SessionStepUp ¶
SessionStepUp records that the session proved a sign-in factor at now.
func (*Store) SessionWithAdmin ¶
SessionWithAdmin returns the session for a token hash together with its admin.
func (*Store) SessionsByAdmin ¶
SessionsByAdmin lists an admin's sessions, most recently used first. Expired ones are included until PurgeSessions removes them; callers filter by the clock they trust.
func (*Store) SetAwgPrepare ¶
SetAwgPrepare replaces the state (the zero value clears it).
func (*Store) SetBandwidthIfUnset ¶ added in v0.1.20
SetBandwidthIfUnset stores a measured capacity only while the field is still 0 (never measured, never typed): the one automatic write of a value, and never over what an admin entered, even if they did it while the measurement ran. It reports whether the value was stored.
func (*Store) SetInboundAwgHealth ¶
func (s *Store) SetInboundAwgHealth(ctx context.Context, nodeID, inboundID, healthJSON string, at time.Time) error
SetInboundAwgHealth keeps the last agent.v1.AwgHealth (protojson) a node reported for one of its inbounds, for the inbound view (Inbound.awg, with the report time for "stale" captions). The node id is part of the match: a node can only write its own inbounds. An inbound that is gone changes nothing.
func (*Store) SetInboundCert ¶
func (s *Store) SetInboundCert(ctx context.Context, nodeID, inboundID, pin string, notAfter, now time.Time) error
SetInboundCert stores the certificate an inbound serves as the node's stats report it (an ACME certificate appears and renews after the ApplyResult was sent). Only an enabled inbound of this node, and only when the value differs.
func (*Store) SetLastUpdateIfNewer ¶
SetLastUpdateIfNewer stores l as the node's last update unless the stored one is newer: a Hello that carried a later outcome must not be overwritten by an event that arrives late.
func (*Store) SetNodeDecoyBundle ¶ added in v0.1.36
func (s *Store) SetNodeDecoyBundle(ctx context.Context, nodeID, hash string, archive []byte) (NodeRow, error)
SetNodeDecoyBundle stores a normalized bundle by content hash and selects it as this node's own site.
func (*Store) SetNodeDecoyMode ¶ added in v0.1.36
SetNodeDecoyMode changes one node's selected site. The caller checks that panel mode is available in this edition.
func (*Store) SetNodeUpdateSchedule ¶ added in v0.1.8
func (s *Store) SetNodeUpdateSchedule(ctx context.Context, r NodeUpdateScheduleRow) error
SetNodeUpdateSchedule creates or replaces the pending schedule for a node (a replaced schedule is no longer missed).
func (*Store) SetNodesDecoyMode ¶ added in v0.1.36
func (s *Store) SetNodesDecoyMode(ctx context.Context, nodeIDs []string, mode string) ([]NodeRow, error)
SetNodesDecoyMode updates a set of nodes in one database batch. Own mode is allowed only where a bundle was uploaded.
func (*Store) SetPasswordHash ¶
SetPasswordHash replaces the password of an admin's password login; ErrNotFound if the admin has none.
func (*Store) SetPendingNodeServerPassword ¶
func (s *Store) SetPendingNodeServerPassword(ctx context.Context, nodeID string, encrypted []byte, generated bool, now time.Time) error
SetPendingNodeServerPassword journals an encrypted replacement before it is sent to the server. A generated one marks the access as holding a panel-generated password at once: from here on the server may already use it.
func (*Store) SetRolloutStatus ¶
func (s *Store) SetRolloutStatus(ctx context.Context, id string, from []string, status, pauseKey string, params map[string]string, finished time.Time) (bool, error)
SetRolloutStatus moves a rollout to status only if it is currently in one of from (a compare-and-set: two callers cannot both win). pauseKey and params describe a pause and are cleared by any other status. It reports whether the row changed; finished is recorded for the terminal statuses.
func (*Store) SetSettingIfChanged ¶ added in v0.1.49
SetSettingIfChanged stores a setting only when its value differs. The upsert is one statement so D1 does not need a read before the write, and the conditional update avoids rewriting an unchanged value.
func (*Store) SetSettings ¶
SetSettings upserts several settings in one transaction.
func (*Store) SetSettingsIfAbsent ¶ added in v0.1.35
func (s *Store) SetSettingsIfAbsent(ctx context.Context, kv map[string]string) (map[string]string, error)
SetSettingsIfAbsent stores each setting of kv that has no value yet and returns the stored value of every key of kv (the supplied one, or the one that was there first). Isolates that generate the same first-run settings at the same time all end up with the stored ones.
func (*Store) SetStepAnswer ¶ added in v0.1.48
SetStepAnswer records the first result for the current request while its node step belongs to an active rollout.
func (*Store) SetTOTPSecret ¶
SetTOTPSecret replaces the authenticator secret (sealed by the caller) of an admin's password login. The last accepted step never goes back, so a code that was used once stays used. ErrNotFound if the admin has none.
func (*Store) SetTelegramBot ¶ added in v0.1.23
func (s *Store) SetTelegramBot(ctx context.Context, b TelegramBotRow, now time.Time) (dropped int, err error)
SetTelegramBot stores the bot. When it is another bot than the one stored, every chat link is deleted with it (chat ids belong to a bot); dropped says how many.
func (*Store) SetTelegramEnabled ¶ added in v0.1.23
SetTelegramEnabled switches the admin's alerts; ErrNotFound when the admin has no chat.
func (*Store) SetWarpAttention ¶
SetWarpAttention records why the owner has to decide ("" = nothing to decide). ErrNotFound when no account.
func (*Store) SetWarpEnabled ¶
func (s *Store) SetWarpEnabled(ctx context.Context, nodeID string, enabled bool, now time.Time) error
SetWarpEnabled pauses or resumes the account. ErrNotFound when the node has no account.
func (*Store) SetWarpHealth ¶
SetWarpHealth stores the last WarpHealth the node reported (protojson, "" is not allowed). The account's updated_at is not touched: health arrives every stats batch and is not a change of the account.
func (*Store) SettingValues ¶ added in v0.1.26
SettingValues returns the stored values among keys. Missing settings are omitted.
func (*Store) SetupTokenStatus ¶ added in v0.1.26
func (s *Store) SetupTokenStatus(ctx context.Context, now time.Time) (adminExists bool, expiry time.Time, tokenExists bool, err error)
SetupTokenStatus reports whether setup is complete and the expiry of an unused, unexpired setup token, using one query.
func (*Store) SkipPendingSteps ¶
func (s *Store) SkipPendingSteps(ctx context.Context, rolloutID, errorKey string, now time.Time) error
SkipPendingSteps turns every PENDING step of a rollout into SKIPPED with errorKey (cancel).
func (*Store) SkipSeq ¶
func (s *Store) SkipSeq(ctx context.Context, nodeID, instance string, seq uint64, now time.Time) error
SkipSeq marks the reliable message seq of the node's current agent instance as processed without applying its effects, for a batch that cannot be stored (the node gets its Ack and moves on).
func (*Store) SnapshotDatabase ¶
SnapshotDatabase creates a consistent SQLite snapshot at a new path. VACUUM INTO includes committed WAL data without copying live -wal/-shm files.
func (*Store) TCPChecks ¶ added in v0.1.35
TCPChecks reads the stored TCP check rows. With no nodeIDs it returns every node's rows.
func (*Store) TSPUHistory ¶ added in v0.1.42
func (s *Store) TSPUHistory(ctx context.Context, vantage string, perNode int, nodeIDs ...string) ([]TSPUCheck, error)
TSPUHistory reads the newest perNode rows of every node from one vantage (of the given nodes only, when there are any), newest first within a node, ordered by node id. The alert reads the last few runs from it.
func (*Store) TSPUHistorySince ¶ added in v0.1.44
func (s *Store) TSPUHistorySince(ctx context.Context, vantage string, since time.Time, perNode int, nodeIDs ...string) ([]TSPUCheck, error)
TSPUHistorySince reads up to perNode rows from the requested window for every node from one vantage. Filtering by the window before ranking keeps a burst of recent tests from crowding older rows out of a history view.
func (*Store) TakeLease ¶ added in v0.1.48
func (s *Store) TakeLease(ctx context.Context, name, holder string, ttl time.Duration, now time.Time) (bool, error)
TakeLease atomically takes name for holder until now+ttl, if no current lease exists or it has expired.
func (*Store) TakeMCPPlanOwnerSecret ¶ added in v0.1.15
func (s *Store) TakeMCPPlanOwnerSecret(ctx context.Context, id, tokenID, tool string) ([]byte, error)
TakeMCPPlanOwnerSecret hands out, once, what the owner entered when approving plan id of tool for tokenID, and clears it: only while that plan is applying with a recorded human decision. ErrNotFound otherwise (nothing stored, already taken, another token or tool, or a plan in another state).
func (*Store) TelegramBot ¶ added in v0.1.23
func (s *Store) TelegramBot(ctx context.Context) (TelegramBotRow, error)
TelegramBot is the stored bot; ErrNotFound when none is set.
func (*Store) TelegramLink ¶ added in v0.1.23
TelegramLink is one admin's chat; ErrNotFound when the admin has none.
func (*Store) TelegramLinkByChat ¶ added in v0.1.23
TelegramLinkByChat is the link of a chat; ErrNotFound when no admin uses it.
func (*Store) TelegramLinks ¶ added in v0.1.23
func (s *Store) TelegramLinks(ctx context.Context) ([]TelegramLinkRow, error)
TelegramLinks lists every linked chat, oldest first.
func (*Store) TouchAPIToken ¶
TouchAPIToken records a use of the token: when, from which address and over which channel ("api" or "mcp").
func (*Store) TouchAlert ¶
TouchAlert records that the condition of an active alert still holds and refreshes what may change with the diagnosis (severity, texts, params). A mute ends when the severity rises: it was muted at the milder level.
func (*Store) TouchPasskey ¶
func (s *Store) TouchPasskey(ctx context.Context, credID []byte, signCount uint32, flags byte, now time.Time) error
TouchPasskey records a successful sign-in: new signature counter, flags (backup state may change) and last-used time.
func (*Store) TouchSession ¶
TouchSession bumps last_seen_at.
func (*Store) UnacceptDoctor ¶
UnacceptDoctor removes an acceptance; false when there was none.
func (*Store) UnlinkTelegram ¶ added in v0.1.23
UnlinkTelegram forgets the admin's chat; it reports whether there was one.
func (*Store) UpdateNode ¶
UpdateNode applies the patch and returns the new row. ErrConflict on a name clash.
func (*Store) UpdateNodeDecoyAgentState ¶ added in v0.1.36
UpdateNodeDecoyAgentState stores the mode/hash confirmed by SetDecoy. Hello remains the recovery source after a reconnect.
func (*Store) UpdateRunningNodeProvisionJob ¶
func (s *Store) UpdateRunningNodeProvisionJob(ctx context.Context, id, state, phase, errorCode string, secret []byte, now time.Time) error
UpdateRunningNodeProvisionJob only changes a job that is still running, so it cannot undo a concurrent owner cancellation or overwrite a terminal result.
func (*Store) UpdateRunningNodeProvisionJobWithEvent ¶
func (s *Store) UpdateRunningNodeProvisionJobWithEvent(ctx context.Context, id, state, phase, errorCode string, secret []byte, eventCode string, now time.Time) error
UpdateRunningNodeProvisionJobWithEvent updates an active job and its redacted journal atomically, without reverting a cancel_requested state.
func (*Store) UpdateWarpRefresh ¶
func (s *Store) UpdateWarpRefresh(ctx context.Context, nodeID string, r WarpRefresh, now time.Time) error
UpdateWarpRefresh replaces the connection facts of the account and clears "needs attention". ErrNotFound when the node has no account.
func (*Store) UpgradePasswordHash ¶ added in v0.1.34
func (s *Store) UpgradePasswordHash(ctx context.Context, adminID, oldHash, newHash string) (bool, error)
UpgradePasswordHash replaces the hash of an admin's password login with newHash only while it is still oldHash (re-hashing an older profile at sign-in must not undo a password change made meanwhile). One statement: safe on D1.
func (*Store) WarpAccount ¶
WarpAccount returns the account of a node or ErrNotFound.
func (*Store) WarpAccounts ¶
func (s *Store) WarpAccounts(ctx context.Context) ([]WarpAccountRow, error)
WarpAccounts returns every account (for the node list badges and the desired state of all nodes).
type SubscriptionData ¶ added in v0.1.26
type SubscriptionData struct {
Up, Down uint64
Devices []AccessDevice
AWG []AccessAWGDevice
// Device is "the device of this request": the live link device with the request's hwid_hash (the shared device for
// none) and its live credentials. The zero value: there is none (yet).
Device AccessDevice
DeviceCreds []AccessCred
// LinkMode is the stored mode of the device limit (LinkModeTrack, LinkModeEnforce or LinkModeStrict), read in the same batch.
// Blocked: the owner blocked the HWID this request reports (always false for a request without one).
LinkMode string
Blocked bool
Group AccessGroup
Inbounds []AccessInboundFull
LiveNodes []NodeLiveRow
// OnlineDevices maps each device of the user that has a session on a connected node to those nodes (node order).
OnlineDevices map[string][]string
}
SubscriptionData reads the independent rows a subscription view needs in one store batch. The access rows are omitted for a user who is not active, because the view returns before it reads them.
func (SubscriptionData) LinkRefusal ¶ added in v0.1.39
LinkRefusal is what the snapshot of a subscription fetch already says about a request whose device does not exist yet, decided without a write: ErrAccessBlocked, ErrNoSharedDevice (STRICT, no HWID), or *AccessLimitError (ENFORCE and STRICT: the user is at the limit and no silent device could give its place away). nil: the store has to decide (a device is there, has room, or may take a silent one's place; TRACK always goes there). It is the first half of linkDeviceState.birth on the data SubscriptionData read, so a refused request costs the one read batch and nothing else. limit is the user's device limit. The rule of a place and of replacing one is birth's; a snapshot taken before a writer changed it is corrected there.
type TCPCheck ¶ added in v0.1.35
type TCPCheck struct {
NodeID, Role, Profile string
Port uint16
ALPN bool // the listener answers TLS-ALPN-01 (a Hysteria2 site, a VLESS TLS front or "self" on 443)
Verdict, Reason string
Sender string
CheckedAt time.Time
}
TCPCheck is one row of the latest TCP port check of a node: whether a connection to Port reaches Mistgate. Verdict is ours | other | busy | refused | timeout, or "" with a Reason when the port could not be probed.
type TSPUCheck ¶ added in v0.1.42
type TSPUCheck struct {
NodeID, Vantage, Verdict, DetailJSON string
DPIHop int
ControlOK bool
At time.Time
}
TSPUCheck is what a probe node's TSPU probe said about one node at one time (migration 00068). Vantage is the id of the node that probed. Verdict is blocked | open | partial | unknown; DetailJSON is one entry per port.
type TelegramBotRow ¶ added in v0.1.23
TelegramBotRow is the stored bot. Token is vault ciphertext and must never be returned by an admin RPC.
type TelegramLinkRow ¶ added in v0.1.23
type TelegramLinkRow struct {
AdminID, AdminName, Role string
ChatID int64
Enabled bool
LinkedAt time.Time
}
TelegramLinkRow is one admin's chat with the admin's name and role.
type UserNodeDNS ¶ added in v0.1.17
UserNodeDNS is a person's pick on one node. UpdatedMs is Unix milliseconds (see the migration).
type WarpAccountRow ¶
type WarpAccountRow struct {
NodeID, Source string
SecretEnc []byte
PeerPublicKey string
EndpointV4, EndpointV6 string // IP literals, no port
Ports []uint16
AddressV4, AddressV6 string
MTU int
ClientID string // base64; its first three bytes are the "reserved" bytes
UseReserved bool
AccountType string
Enabled bool
TOSURL, TOSAcceptedBy string
TOSAcceptedAt time.Time // zero for an import
RegisteredWith string
Attention string // reason code while the owner has to decide; "" = fine
HealthJSON string // last agent.v1.WarpHealth (protojson); "" = never reported
HealthAt time.Time
CreatedAt, UpdatedAt time.Time
}
WarpAccountRow is one warp_account row.
Source Files
¶
- access.go
- access_awg.go
- access_linkdevice.go
- access_linkmode.go
- access_profile.go
- access_user.go
- admin.go
- authceremony.go
- authpw.go
- awg_prepare.go
- backup.go
- batch.go
- batch_native.go
- country_blocklist_check.go
- country_check.go
- country_tspu_check.go
- dns.go
- doctor_accept.go
- fleet_ca.go
- fleet_desired.go
- fleet_enabled.go
- fleet_events.go
- fleet_m3.go
- fleet_node.go
- fleet_stats.go
- health.go
- health_signals.go
- job_lease.go
- mcpplan.go
- node_decoy.go
- node_dns.go
- node_live.go
- open_sqlite.go
- port_check.go
- provision.go
- session.go
- store.go
- telegram.go
- text.go
- token.go
- update.go
- update_schedule.go
- warp.go