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 BridgeCapacity(pool uint32) uint32
- func BridgeNearFull(clients, pool uint32) bool
- func BridgePool(prev uint32, prevAt int64, clients uint32, bps uint64, now time.Time) (uint32, int64)
- func CapabilityPresent(caps []string, want string) bool
- func CleanDisplayText(s string, max int) string
- func Clip(s string, n int) string
- func DeviceKindName(kind string) string
- func FollowUpTokenID(adminID string) string
- func GroupGetsNode(disabledNodeIDs []string, nodeID string) bool
- func HWIDHash(userID, canonHWID string) []byte
- func InboundLive(enabled bool, state, nodeState string) bool
- func IsPanelEventCode(code string) bool
- func LinkModeOf(stored string) string
- func LinkWindowHours(requested uint32) int
- func NewClientDebugID() string
- func NewID(prefix string) string
- func NodeJournalWindowHours(requested uint32) int
- func NodeProvisionCredentialsAAD(jobID string) string
- func NodeServerAccessPasswordAAD(nodeID string) string
- func OwnProbeRef(p OwnProbe) string
- func ParseNetworkMode(value string) uint32
- func PendingNodeServerPasswordAAD(nodeID string) string
- func ProtocolAnswers(probeOK, checked time.Time) bool
- func RelayPathNetwork(protocol string) string
- func RelayTargetInbound(protocol string, cdn bool) bool
- func RetainedKeyAAD(profileID, nodeID string) string
- func ScheduledTokenID(adminID string) string
- func SchemaVersions(ctx context.Context, path string) (db, binary int64, err error)
- func UnsafeDisplayRune(r rune) bool
- func UsableIPv6(s string) (string, bool)
- func ValidRelayMode(mode string) bool
- func WithAuditActor(ctx context.Context, adminID, actor string) context.Context
- func WithAuditSource(ctx context.Context, source string) context.Context
- type APIToken
- type AWGDeviceAdd
- type AWGImplicitWant
- type AWGIssue
- type AWGPathFailure
- type AWGPathFull
- 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) AddTelegramKey(ctx context.Context, add TelegramKeyAdd, now time.Time) error
- func (a Access) AddTrustTunnelKey(ctx context.Context, add TrustTunnelKeyAdd, now time.Time) 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) ClientAPIStats(ctx context.Context) (ClientAPIStats, error)
- func (a Access) ClientCompatDevices(ctx context.Context, userID string) ([]ClientCompatDevice, error)
- func (a Access) CountLinkAWGKeys(ctx context.Context) (int, 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) CreateUserWithKeys(ctx context.Context, u AccessUser, keys ...AccessKeyDevice) 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, now time.Time) (AccessDevice, error)
- func (a Access) DeviceCounts(ctx context.Context, ids []string, now time.Time) (map[string]AccessDeviceCounts, error)
- func (a Access) Devices(ctx context.Context, userID string, now time.Time) ([]AccessDevice, error)
- func (a Access) EnrolLinkDevice(ctx context.Context, dev AccessDevice, limit int, now time.Time, ...) (LinkDeviceResult, error)
- func (a Access) EnsureEnrolledLinkDevice(ctx context.Context, dev AccessDevice, now time.Time, issue LinkIssue, ...) (LinkDeviceResult, error)
- func (a Access) EnsureKeyPathCred(ctx context.Context, deviceID, profileID, path string, maxIdx int, ...) (AccessCred, bool, 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) HasUserCredentialOnNode(ctx context.Context, nodeID, userID string) (bool, 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) LinkDeviceByKeyHash(ctx context.Context, keyHash []byte) (AccessDevice, LinkDeviceKeyOwner, 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) NodeAudience(ctx context.Context, nodeID string) (map[string]int, 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, ...) ([]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) RelayAudienceUsers(ctx context.Context, nodeIDs []string) ([]AccessUser, error)
- func (a Access) RelayReachabilityUsers(ctx context.Context) ([]RelayReachabilityUser, error)
- func (a Access) RelayStaticAWGDeviceCounts(ctx context.Context, profileIDs []string) (map[string]map[string]uint64, error)
- func (a Access) RemoveProfileInbounds(ctx context.Context, profileID string, nodeIDs []string, deleteProfile bool, ...) ([]AccessInbound, 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) RevokeEnrolledLinkDevice(ctx context.Context, dev AccessDevice, now time.Time) error
- func (a Access) RevokeLinkAWGCreds(ctx context.Context, dev AccessDevice, now time.Time) (int, error)
- func (a Access) RevokeTelegramKey(ctx context.Context, userID string, now time.Time) (bool, error)
- func (a Access) RevokeTrustTunnelKey(ctx context.Context, userID string, now time.Time) (bool, error)
- func (a Access) RotateAWGDevice(ctx context.Context, deviceID string, now time.Time, issue AWGIssue) (string, error)
- func (a Access) RotateTelegramKey(ctx context.Context, userID string, cred AccessCred, now time.Time) (string, error)
- func (a Access) SetInboundBuildError(ctx context.Context, id, msg string, now time.Time) error
- func (a Access) SetLinkDeviceKeyHash(ctx context.Context, userID, deviceID string, ...) (bool, error)
- func (a Access) SetNodeShare(ctx context.Context, nodeID string, c NodeShareChoice, 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) SubTokenHashes(ctx context.Context) ([][32]byte, error)
- func (a Access) SubscriptionData(ctx context.Context, userID, groupID string, since time.Time, active bool, ...) (SubscriptionData, error)
- func (a Access) TelegramKey(ctx context.Context, userID string) (AccessDevice, AccessCred, error)
- func (a Access) TelegramKeyUsers(ctx context.Context, ids []string) (map[string]string, error)
- func (a Access) TouchDevice(ctx context.Context, id string, now, not time.Time, osVersion, client string) error
- func (a Access) TrustTunnelKey(ctx context.Context, userID string) (AccessDevice, AccessCred, 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) UpdateGroupWithDisabledNodes(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 AccessDeviceCounts
- type AccessGroup
- type AccessInbound
- type AccessInboundFull
- type AccessKeyDevice
- 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 AssistantFollowUp
- type AssistantProviderChoice
- type AuditEntry
- type AuditQuery
- type AuditRow
- type AuthCeremony
- type AwgPrepareRow
- type BlocklistCheck
- type CARow
- type CertRow
- type CertState
- type CheckSample
- type ClientAPIStats
- type ClientCompatDevice
- type ClientDebugIntake
- type ClientDebugLine
- type ClientDebugRateError
- type ClientDebugRow
- type ClientProbeCount
- type ClientProbeKindCount
- type ClientProbeNetwork
- type ClientProbeResult
- 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 DebugCaptureRow
- type DebugLineFilter
- type DebugLineIn
- type DebugLineRow
- type DecoyFileRef
- type DecoySiteInUseError
- type DecoySiteInfo
- type DecoySiteRow
- type DecoyVersionRow
- type DoctorAccept
- type DoctorRow
- type EngineRow
- type EnrollResult
- type EventFilter
- type EventRow
- type ExtCheck
- type ExtCheckTime
- type FleetConnectionNode
- type FleetCredRef
- type FleetHourRow
- type FleetInboundCert
- type FleetInboundRow
- type FleetJournal
- type FleetLink
- type FleetLive
- type FleetNetwork
- type FleetNetworkInbound
- type FleetNetworkNode
- type FleetNetworkSums
- type FleetNodeLinkSum
- type FleetPersonNetwork
- type FleetSessionRef
- type FleetStatsIn
- type FleetStatsOut
- type FleetTop
- type FleetTraffic
- type GateRollback
- type HealthAWGSignal
- type HealthAlert
- type HealthCrashSignal
- type HealthDeviceLimitSignal
- type HealthNodeFlapSignal
- type HealthNodeHourSignal
- type HealthSignalBatch
- type HealthTorrentSignal
- type HealthUserSignal
- type HelloInfo
- type HelloKexDevice
- type HelloKexFleet
- type HelloKexSums
- type HostHour
- type HostSample
- type HostSampleExt
- type IPv6Check
- type IPv6Doctor
- type IPv6Row
- type IPv6State
- type IPv6Verdict
- type InboundApplied
- type LastUpdateRow
- type LinkClientSums
- type LinkDNSOption
- type LinkDeviceKeyOwner
- type LinkDeviceResult
- type LinkHourSums
- type LinkInboundSums
- type LinkIssue
- type LinkReasons
- type LoginFailure
- type MCPPlan
- type NewDecoySite
- type NodeApplyMeta
- type NodeDNSOption
- type NodeDNSRun
- type NodeFactsRow
- type NodeHealthSummary
- type NodeJournalFilter
- type NodeJournalRow
- type NodeLinkReadRow
- type NodeLinkReport
- type NodeLiveRow
- type NodePatch
- type NodeProvisionEvent
- type NodeProvisionJob
- type NodeRow
- type NodeServerAccess
- type NodeShare
- type NodeShareChoice
- type NodeTraceRow
- type NodeUpdateScheduleRow
- type OsRolloutRow
- type OsStatusRow
- type OsStepRow
- type OwnProbe
- type PanelBackupSettings
- type PanelSSHKey
- type Passkey
- type PasswordCred
- type PathProbeRow
- type PathSpeedRow
- type PathSpeedStartUsage
- type PlanStateError
- type PortCheck
- type ProbeCredIssue
- type ProbeCredRow
- type RecoveryTokenOffer
- type Relay
- type RelayApplied
- type RelayBridgeCheck
- type RelayBridgeSideCheck
- type RelayCheck
- type RelayCounterUpdate
- type RelayCounters
- type RelayFilter
- type RelayLink
- type RelayModeDecision
- type RelayModeInput
- type RelayMonitorCheck
- type RelayPatch
- type RelayReachability
- func (r RelayReachability) NodeReachedThroughRelays(nodeID string, directBlocked map[string]bool) bool
- func (r RelayReachability) RelayHealthy(id string) bool
- func (r RelayReachability) UserGiven(userID, inboundID string) bool
- func (r RelayReachability) UserHasHealthyRelay(userID, inboundID string) bool
- type RelayReachabilityGroup
- type RelayReachabilityInbound
- type RelayReachabilityInput
- type RelayReachabilityRelay
- type RelayReachabilityUser
- type RelayStage
- type RolloutRow
- type RuntimeInbound
- type ScheduledTask
- type ScheduledTaskNext
- type ScheduledTaskRun
- type ScheduledTaskSchedule
- 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) AcquireAssistantTurn(ctx context.Context, conversationID, adminID, leaseID string, ...) (bool, error)
- func (s *Store) ActiveAlerts(ctx context.Context) ([]HealthAlert, error)
- func (s *Store) ActiveOsRollout(ctx context.Context) (OsRolloutRow, error)
- func (s *Store) ActiveRollout(ctx context.Context) (RolloutRow, error)
- func (s *Store) AddDecoySiteVersion(ctx context.Context, now time.Time, id string, b *decoy.Bundle, by string) (site DecoySiteRow, nodeIDs []string, changed bool, err error)
- func (s *Store) AddNodeDNSRun(ctx context.Context, r NodeDNSRun) error
- func (s *Store) AddNodeToRunningRollout(ctx context.Context, rolloutID, version string, built int64, stage int, ...) error
- func (s *Store) AddNodeTrace(ctx context.Context, fromID, toID string, at time.Time, resultJSON string) 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) AddPathProbe(ctx context.Context, fromID, toID, kind string, at time.Time, ...) error
- func (s *Store) AddPathSpeed(ctx context.Context, fromID, toID, direction string, at time.Time, ...) error
- func (s *Store) AddPathSpeedStart(ctx context.Context, actorID, fromID, toID string, at time.Time) error
- func (s *Store) AddTrafficParams(ctx context.Context, nodeID string, now time.Time, params map[string]string) 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) AppendDebugChunk(ctx context.Context, nodeID, id string, chunkSeq uint32, lines []DebugLineIn, ...) (stored int, ok bool, err error)
- func (s *Store) AppendDebugLines(ctx context.Context, nodeID, id string, lines []DebugLineIn, secrets []string, ...) (stored int, ok bool, err error)
- func (s *Store) ApproveMCPPlanWithSecret(ctx context.Context, id, adminID string, secret []byte, now time.Time) (MCPPlan, error)
- func (s *Store) ArmAssistantFollowUps(ctx context.Context) (int64, error)
- func (s *Store) AssignDecoySite(ctx context.Context, id string, nodeIDs []string) ([]NodeRow, error)
- func (s *Store) AssistantFollowUp(ctx context.Context, adminID, id string) (AssistantFollowUp, error)
- func (s *Store) AssistantFollowUps(ctx context.Context, adminID, conversationID string) ([]AssistantFollowUp, error)
- func (s *Store) AssistantRetention(ctx context.Context, now time.Time) error
- func (s *Store) AssistantStopRequested(ctx context.Context, conversationID, leaseID string) (bool, 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) (bool, error)
- func (s *Store) AwgPrepareFinishTransition(ctx context.Context, nodeID string, ok bool, at int64, code, reason string) (switched, failedTransition bool, err error)
- func (s *Store) AwgPrepareStarted(ctx context.Context, nodeID string, since int64) error
- func (s *Store) BackfillDecoyVersions(ctx context.Context) error
- func (s *Store) BeginApply(ctx context.Context, id, tokenID, tool string, paramsHash, confirmHash []byte, ...) (MCPPlan, error)
- func (s *Store) BeginDebugCapture(ctx context.Context, row DebugCaptureRow, now time.Time) 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) CancelAssistantMCPPlan(ctx context.Context, id, tokenID string, now time.Time) (bool, error)
- func (s *Store) CancelClientDebug(ctx context.Context, id string, now time.Time) (ClientDebugRow, 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) ClaimAssistantFollowUp(ctx context.Context, id, leaseID string, now, until time.Time) (bool, error)
- func (s *Store) ClaimNodeProvisionJob(ctx context.Context, now time.Time) (NodeProvisionJob, bool, error)
- func (s *Store) ClaimScheduledTask(ctx context.Context, run ScheduledTaskRun, leaseID string, ...) (bool, error)
- func (s *Store) ClearLoginFailures(ctx context.Context, login string) error
- func (s *Store) ClearOwnProbeJobs(ctx context.Context) 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) ClientDebug(ctx context.Context, id string, now time.Time) (ClientDebugRow, error)
- func (s *Store) ClientDebugAdmitUnasked(ctx context.Context, deviceID string, now time.Time) error
- func (s *Store) ClientDebugLines(ctx context.Context, id string, f DebugLineFilter) ([]DebugLineRow, []string, error)
- func (s *Store) ClientDebugList(ctx context.Context, userID string, now time.Time) ([]ClientDebugRow, error)
- func (s *Store) ClientProbeCounts(ctx context.Context, since time.Time) ([]ClientProbeCount, error)
- func (s *Store) ClientProbeKindCounts(ctx context.Context, since time.Time) ([]ClientProbeKindCount, error)
- func (s *Store) ClientProbeTotals(ctx context.Context, since time.Time) (int, time.Time, error)
- func (s *Store) Close() error
- func (s *Store) CommitPendingNodeServerPassword(ctx context.Context, nodeID string, encryptedCurrent []byte, ...) error
- func (s *Store) CompleteNodeProvisionJob(ctx context.Context, id string, access NodeServerAccess, now time.Time) error
- func (s *Store) CompleteOwnProbeJob(ctx context.Context, id, jobID, version, reference string, now time.Time, ...) error
- func (s *Store) ConfirmOwnProbeNetwork(ctx context.Context, id, operator string) 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, family int, since time.Time) ([]CountryCheck, error)
- func (s *Store) CreateAPIToken(ctx context.Context, t APIToken, secretHash []byte) error
- func (s *Store) CreateClientDebug(ctx context.Context, row ClientDebugRow, now time.Time) (ClientDebugRow, error)
- func (s *Store) CreateDecoySite(ctx context.Context, now time.Time, in NewDecoySite) (DecoySiteRow, 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) CreateOsRollout(ctx context.Context, r OsRolloutRow, steps []OsStepRow) error
- func (s *Store) CreateOwnProbe(ctx context.Context, p OwnProbe) error
- func (s *Store) CreatePanelSSHKeyIfAbsent(ctx context.Context, key PanelSSHKey) (bool, error)
- func (s *Store) CreatePasswordSession(ctx context.Context, sess Session, checked PasswordCred) error
- func (s *Store) CreateRelay(ctx context.Context, r Relay, now time.Time) 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) DailyRowsSince(ctx context.Context, since time.Time) ([]DailyRow, error)
- func (s *Store) DebugCapture(ctx context.Context, id string) (DebugCaptureRow, error)
- func (s *Store) DebugCaptures(ctx context.Context, nodeID string, now time.Time) ([]DebugCaptureRow, error)
- func (s *Store) DebugLines(ctx context.Context, id string, f DebugLineFilter) ([]DebugLineRow, []string, error)
- func (s *Store) DecideMCPPlan(ctx context.Context, id, adminID string, approve bool, now time.Time) (MCPPlan, error)
- func (s *Store) DeclineClientDebug(ctx context.Context, deviceID, id string, now time.Time) (ClientDebugRow, error)
- func (s *Store) DecoySite(ctx context.Context, id string) (DecoySiteRow, error)
- func (s *Store) DecoySiteBundle(ctx context.Context, id string, seq int) (*decoy.Bundle, DecoyVersionRow, error)
- func (s *Store) DecoySiteInfoOf(ctx context.Context, id string) (DecoySiteInfo, error)
- func (s *Store) DecoySiteNodes(ctx context.Context, id string) ([]NodeRow, error)
- func (s *Store) DecoySiteVersions(ctx context.Context, id string) ([]DecoyVersionRow, error)
- func (s *Store) DecoySites(ctx context.Context) ([]DecoySiteInfo, error)
- func (s *Store) DeferAssistantFollowUp(ctx context.Context, id, leaseID string, next time.Time, counted bool) error
- func (s *Store) DeleteAdminSession(ctx context.Context, adminID string, tokenHash []byte) (bool, error)
- func (s *Store) DeleteAssistantConversation(ctx context.Context, adminID, id string) (bool, error)
- func (s *Store) DeleteAssistantConversations(ctx context.Context, adminID string, all bool) (int64, error)
- func (s *Store) DeleteAssistantFollowUp(ctx context.Context, adminID, conversationID, id string, now time.Time) (bool, error)
- func (s *Store) DeleteAssistantMemory(ctx context.Context, id, adminID string) (bool, error)
- func (s *Store) DeleteAssistantMemoryAll(ctx context.Context, adminID string) (int64, error)
- func (s *Store) DeleteBlocklistChecks(ctx context.Context) error
- func (s *Store) DeleteClientDebug(ctx context.Context, id string, now time.Time) (ClientDebugRow, error)
- func (s *Store) DeleteClientProbeReports(ctx context.Context) error
- func (s *Store) DeleteDecoySite(ctx context.Context, id string) error
- func (s *Store) DeleteExtChecks(ctx context.Context, sources ...string) 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) DeleteRelay(ctx context.Context, id string) error
- func (s *Store) DeleteScheduledTask(ctx context.Context, id string) (bool, error)
- func (s *Store) DeleteSession(ctx context.Context, tokenHash []byte) error
- func (s *Store) DeleteSettings(ctx context.Context, keys ...string) error
- func (s *Store) DeleteStaleAssistantBudgetReservations(ctx context.Context, before, now time.Time) (int64, error)
- func (s *Store) DeleteTSPUChecks(ctx context.Context) error
- func (s *Store) DeleteWarpAccount(ctx context.Context, nodeID string) error
- func (s *Store) DevicesHelloKex(ctx context.Context, since time.Time) (map[string]HelloKexSums, error)
- func (s *Store) DismissAlert(ctx context.Context, id string, now time.Time) (HealthAlert, 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) DropDebugCapture(ctx context.Context, id string) error
- func (s *Store) DropStaleAccepts(ctx context.Context, nodeID string) error
- func (s *Store) DueAssistantFollowUps(ctx context.Context, now time.Time, limit int) ([]AssistantFollowUp, error)
- func (s *Store) DueNodeUpdateSchedules(ctx context.Context, now time.Time) ([]NodeUpdateScheduleRow, error)
- func (s *Store) DueOwnProbe(ctx context.Context, id string, now time.Time) error
- func (s *Store) DueScheduledTasks(ctx context.Context, now time.Time, limit int) ([]ScheduledTask, error)
- func (s *Store) EnabledScheduledTaskSchedules(ctx context.Context) ([]ScheduledTaskSchedule, error)
- func (s *Store) Enroll(ctx context.Context, tokenHash, keyHash []byte, now time.Time, ...) (EnrollResult, error)
- func (s *Store) EnrollOwnProbe(ctx context.Context, tokenHash, secretHash []byte, asn uint32, ...) (OwnProbe, error)
- func (s *Store) EnsureAssistantFollowUpToken(ctx context.Context, adminID, profile string, now time.Time) (APIToken, error)
- func (s *Store) EnsureAssistantToken(ctx context.Context, adminID, profile string, now time.Time) (APIToken, error)
- func (s *Store) EnsureNodeBridgePath(ctx context.Context, nodeID, path string) (string, error)
- func (s *Store) EnsureScheduledToken(ctx context.Context, adminID string, now time.Time) (APIToken, 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) ExtVerdictChanges(ctx context.Context, since time.Time) ([]ExtCheck, 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) FinishAssistantFollowUp(ctx context.Context, id, leaseID string) error
- func (s *Store) FinishCancelledNodeProvisionJob(ctx context.Context, id string, now time.Time) (bool, error)
- func (s *Store) FinishDebugCapture(ctx context.Context, nodeID, id, reason string, nodeDropped uint32) error
- func (s *Store) FinishScheduledRun(ctx context.Context, run ScheduledTaskRun, leaseID string, next time.Time) error
- func (s *Store) FleetConnectionNodes(ctx context.Context) ([]FleetConnectionNode, 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) FleetNetworkHourSums(ctx context.Context, since, previousSince, until time.Time, nodeID string, ...) ([]FleetNetworkSums, error)
- func (s *Store) FleetNetworkNodes(ctx context.Context) ([]FleetNetworkNode, error)
- func (s *Store) FleetNodeLinkSums(ctx context.Context, since time.Time) ([]FleetNodeLinkSum, 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) GetAssistantToken(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) HasPendingTelegramLinkCode(ctx context.Context, now time.Time) (bool, error)
- func (s *Store) HasRelaysOnNode(ctx context.Context, nodeID string) (bool, 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) HelloKex(ctx context.Context, since time.Time, limit int) (HelloKexFleet, error)
- func (s *Store) IPv6Doctor(ctx context.Context, nodeID string) (IPv6Doctor, error)
- func (s *Store) IPv6Doctors(ctx context.Context) (map[string]IPv6Doctor, error)
- func (s *Store) IngestEvent(ctx context.Context, nodeID, instance string, seq uint64, now time.Time, ...) (dup bool, err error)
- func (s *Store) IngestEventBounded(ctx context.Context, nodeID, instance string, seq uint64, now time.Time, ...) (dup, overLimit bool, err error)
- func (s *Store) IngestStats(ctx context.Context, in FleetStatsIn) (FleetStatsOut, error)
- func (s *Store) InsertAssistantFollowUp(ctx context.Context, f AssistantFollowUp) error
- func (s *Store) InsertAssistantMemory(ctx context.Context, id, adminID string, sealed []byte, byAssistant bool, ...) 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) InsertClientProbeReport(ctx context.Context, report string, at time.Time, n ClientProbeNetwork, ...) (int64, error)
- func (s *Store) InsertCountryChecks(ctx context.Context, rows []CountryCheck) error
- func (s *Store) InsertEvent(ctx context.Context, e EventRow) error
- func (s *Store) InsertExtChecks(ctx context.Context, rows []ExtCheck) error
- func (s *Store) InsertNodeServerAccess(ctx context.Context, access NodeServerAccess) 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) InsertScheduledTask(ctx context.Context, t ScheduledTask, max int) 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, family int) (time.Time, error)
- func (s *Store) LastExtCheckAt(ctx context.Context, source, nodeID string) (time.Time, error)
- func (s *Store) LastNodeEventCode(ctx context.Context, nodeID string, codes ...string) (string, error)
- func (s *Store) LastScheduledRuns(ctx context.Context) (map[string]ScheduledTaskRun, error)
- func (s *Store) LastTSPUCheckAt(ctx context.Context, vantage string) (time.Time, error)
- func (s *Store) LatestDebugCapture(ctx context.Context, nodeID string, now time.Time) (DebugCaptureRow, error)
- func (s *Store) LatestOsRollout(ctx context.Context) (OsRolloutRow, error)
- func (s *Store) LatestProbeSamples(ctx context.Context, nodeID string) ([]CheckSample, error)
- func (s *Store) LatestRollout(ctx context.Context) (RolloutRow, error)
- func (s *Store) LinkCertificates(ctx context.Context, nodeID string, now time.Time) (certs []CertRow, sealed bool, err 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) LockLoginFailure(ctx context.Context, login string, maxFailures int, now time.Time, ...) (LoginFailure, 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) MarkClientDebugRead(ctx context.Context, id, by string, now time.Time) (first bool, err error)
- func (s *Store) MarkNodeLinkSealed(ctx context.Context, id string) 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) NetworkMode(ctx context.Context) (uint32, error)
- func (s *Store) NextAssistantFollowUps(ctx context.Context, adminID string) (map[string]time.Time, 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) NodeApplyMetas(ctx context.Context, nodeID string) (map[string]NodeApplyMeta, error)
- func (s *Store) NodeDNSRuns(ctx context.Context, nodeID string) ([]NodeDNSRun, error)
- func (s *Store) NodeDecoyBundle(ctx context.Context, hash string) ([]byte, error)
- func (s *Store) NodeDecoyModeCounts(ctx context.Context) (map[string]int, 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) NodeHostHours(ctx context.Context, nodeID string, now time.Time, hours int) ([]HostHour, error)
- func (s *Store) NodeInSync(ctx context.Context, id string, session uint64, rev uint64, hash string) error
- func (s *Store) NodeJournal(ctx context.Context, filter NodeJournalFilter) ([]NodeJournalRow, error)
- func (s *Store) NodeLinkReports(ctx context.Context, nodeID string, since time.Time, byHour bool) ([]NodeLinkReport, error)
- func (s *Store) NodeLinkSums(ctx context.Context, nodeID string, since time.Time) ([]LinkInboundSums, 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) NodeRuntimeInbounds(ctx context.Context, nodeID string) ([]RuntimeInbound, error)
- func (s *Store) NodeServerAccess(ctx context.Context, nodeID string) (NodeServerAccess, error)
- func (s *Store) NodeServerAccesses(ctx context.Context) ([]NodeServerAccess, error)
- func (s *Store) NodeShares(ctx context.Context) (map[string]NodeShare, error)
- func (s *Store) NodeTraces(ctx context.Context, fromID, toID string, limit int) ([]NodeTraceRow, 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) NodesWithRelayLinks(ctx context.Context) ([]NodeRow, []RelayLink, error)
- func (s *Store) NoteSpeedTest(ctx context.Context, nodeID string, now time.Time) error
- func (s *Store) ObserveOwnProbeNetwork(ctx context.Context, id string, secretHash []byte, asn uint32, ...) (OwnProbe, 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) OpenClientDebug(ctx context.Context, deviceID string, now time.Time) (ClientDebugRow, bool, error)
- func (s *Store) OsJobEvents(ctx context.Context, nodeID, jobID string, since time.Time) ([]EventRow, error)
- func (s *Store) OsRebootsSince(ctx context.Context, since time.Time) (map[string][]time.Time, error)
- func (s *Store) OsRollout(ctx context.Context, id string) (OsRolloutRow, error)
- func (s *Store) OsRolloutSteps(ctx context.Context, rolloutID string) ([]OsStepRow, error)
- func (s *Store) OsStatus(ctx context.Context, nodeID string) (OsStatusRow, error)
- func (s *Store) OsStatuses(ctx context.Context) (map[string]OsStatusRow, error)
- func (s *Store) OwnProbe(ctx context.Context, id string) (OwnProbe, error)
- func (s *Store) OwnProbeBySecretHash(ctx context.Context, secretHash []byte) (OwnProbe, error)
- func (s *Store) OwnProbes(ctx context.Context) ([]OwnProbe, error)
- func (s *Store) PanelBackupSettings(ctx context.Context) (PanelBackupSettings, error)
- func (s *Store) PanelDecoySource(ctx context.Context) (string, error)
- func (s *Store) PanelSSHKey(ctx context.Context) (PanelSSHKey, 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) PathProbes(ctx context.Context, since time.Time, nodeID string, limit int) ([]PathProbeRow, error)
- func (s *Store) PathSpeedStartUsage(ctx context.Context, actorID, fromID, toID string, since time.Time) (PathSpeedStartUsage, error)
- func (s *Store) PathSpeeds(ctx context.Context, since time.Time, nodeID string, limit int) ([]PathSpeedRow, 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) ProbePackets(ctx context.Context, since time.Time) (map[string][2]uint64, error)
- func (s *Store) PruneAudit(ctx context.Context, before time.Time, batch int) (int64, error)
- func (s *Store) PruneBlocklistChecks(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneClientDebug(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneClientProbeReports(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneCountryChecks(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneDebugCaptures(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) PruneExtChecks(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneHealth(ctx context.Context, now time.Time, samples, daily, alerts time.Duration) (int64, error)
- func (s *Store) PruneLinkHours(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneNetworkHours(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneNodeHostHours(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneNodeJournal(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneNodeTrafficHours(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneOsRollouts(ctx context.Context, keep int, cutoff time.Time) (int64, error)
- func (s *Store) PrunePathProbes(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PrunePathSpeedStarts(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PrunePathSpeeds(ctx context.Context, before time.Time) (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) PruneScheduledTaskRuns(ctx context.Context, cutoff time.Time) (int64, error)
- func (s *Store) PruneTSPUChecks(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneTrafficBuckets(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneUserNetworks(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) PutOsStatus(ctx context.Context, nodeID, statusJSON string, ...) error
- func (s *Store) PutPortChecks(ctx context.Context, checks []PortCheck) error
- func (s *Store) PutPortChecksAndUDPPathLosses(ctx context.Context, checks []PortCheck, targetID string, ...) 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) ReceiveClientDebug(ctx context.Context, in ClientDebugIntake) (row ClientDebugRow, replay bool, err error)
- func (s *Store) RecentBlocklistChecks(ctx context.Context, nodeIDs ...string) ([]BlocklistCheck, error)
- func (s *Store) RecentCountryChecks(ctx context.Context, family, perNode int, nodeIDs ...string) ([]CountryCheck, error)
- func (s *Store) RecentExtCheckTimes(ctx context.Context, sources ...string) ([]ExtCheckTime, error)
- func (s *Store) RecentExtChecks(ctx context.Context, perNodeSource int, sources ...string) ([]ExtCheck, 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) ReconcileAssistantBudget(ctx context.Context, id, month, adminID string, provider int32, ...) error
- func (s *Store) RecordDeviceLimitReached(ctx context.Context, userID string, used, limit int, mode string, ...) error
- func (s *Store) RecordIPv6Check(ctx context.Context, nodeID string, c IPv6Check) error
- func (s *Store) RecordLoginFailure(ctx context.Context, login string, now time.Time, maxFailures int, ...) (LoginFailure, error)
- func (s *Store) RecordNodeApplyMeta(ctx context.Context, nodeID, status string, durationMS uint32, drift bool, ...) error
- func (s *Store) RecordPanelBackupRun(ctx context.Context, now time.Time, succeeded bool, errorCode string) error
- func (s *Store) RecordStepProgress(ctx context.Context, nodeID, requestID, phase string, rank int, ...) (bool, error)
- func (s *Store) RecoverAssistantFollowUps(ctx context.Context) (int64, error)
- func (s *Store) RecoverScheduledRuns(ctx context.Context, now time.Time) (int64, error)
- func (s *Store) RecoveryTokenLive(ctx context.Context, hash []byte, now time.Time) (bool, error)
- func (s *Store) RelayLink(ctx context.Context, id string) (RelayLink, error)
- func (s *Store) RelayLinks(ctx context.Context, f RelayFilter) ([]RelayLink, error)
- func (s *Store) RelayTodayBytesByNode(ctx context.Context, dayStart int64) (map[string]uint64, error)
- func (s *Store) RelaysApplied(ctx context.Context, nodeID string, rs []RelayApplied, now time.Time) error
- func (s *Store) ReleaseApply(ctx context.Context, id, previousStatus string) error
- func (s *Store) ReleaseAssistantTurn(ctx context.Context, conversationID, leaseID string) error
- func (s *Store) ReleaseLease(ctx context.Context, name, holder string) error
- func (s *Store) ReleaseLoginFailure(ctx context.Context, login string, maxFailures int) error
- func (s *Store) ReleaseRecoveryToken(ctx context.Context, hash []byte, usedAt time.Time) error
- func (s *Store) RenewCert(ctx context.Context, c CertRow, fromSerial string, now time.Time, ...) error
- func (s *Store) ReopenDismissedAlert(ctx context.Context, id string, now time.Time) (HealthAlert, error)
- func (s *Store) ReplaceWarpAccount(ctx context.Context, a WarpAccountRow) error
- func (s *Store) RequestAssistantStop(ctx context.Context, conversationID, adminID string, now time.Time) (bool, 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) ReserveAssistantBudget(ctx context.Context, id, month, adminID string, provider int32, model string, ...) (bool, 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) RetainAssistantConversations(ctx context.Context, cutoff time.Time) (int64, 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) RevertDecoySite(ctx context.Context, now time.Time, id string, seq int, by string) (site DecoySiteRow, nodeIDs []string, changed bool, err error)
- func (s *Store) RevokeAPIToken(ctx context.Context, id, by string, now time.Time) (APIToken, error)
- func (s *Store) RevokeAssistantToken(ctx context.Context, id, adminID string, now time.Time) error
- func (s *Store) RevokeOrphanPathCreds(ctx context.Context, now time.Time) (int64, error)
- func (s *Store) RevokeOwnProbe(ctx context.Context, id string) 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) SaveAssistantSettings(ctx context.Context, choices []AssistantProviderChoice, enabled bool, ...) error
- func (s *Store) SaveNetworkMode(ctx context.Context, mode uint32) error
- func (s *Store) SaveOsStep(ctx context.Context, x *OsStepRow) 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) ScheduledTask(ctx context.Context, id string) (ScheduledTask, error)
- func (s *Store) ScheduledTaskAlerts(ctx context.Context) ([]ScheduledTask, error)
- func (s *Store) ScheduledTaskRun(ctx context.Context, id string) (ScheduledTaskRun, error)
- func (s *Store) ScheduledTaskRuns(ctx context.Context, taskID string, limit int) ([]ScheduledTaskRun, error)
- func (s *Store) ScheduledTasks(ctx context.Context) ([]ScheduledTask, 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) SetAPITokenBulk(ctx context.Context, id string, allow bool, now time.Time) (APIToken, error)
- func (s *Store) SetAndDeleteSettings(ctx context.Context, kv map[string]string, keys ...string) error
- func (s *Store) SetAssistantConversationUnread(ctx context.Context, adminID, conversationID string, unread bool) 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) SetDecoySiteReady(ctx context.Context, now time.Time, id string, ready bool, by string) (DecoySiteRow, 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) SetNodeBridgePort(ctx context.Context, nodeID string, port uint16) error
- func (s *Store) SetNodeDecoyMode(ctx context.Context, nodeID, mode string) (NodeRow, error)
- func (s *Store) SetNodeServerPanelKey(ctx context.Context, nodeID, fingerprint string) error
- func (s *Store) SetNodeServerPasswordLogin(ctx context.Context, nodeID string, succeeded bool) 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) SetOsRolloutStatus(ctx context.Context, id string, from []string, status, pauseKey string, ...) (bool, error)
- func (s *Store) SetOwnProbeJob(ctx context.Context, id, jobID, jobJSON string, due time.Time) error
- func (s *Store) SetPanelDecoySource(ctx context.Context, source string) 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) SetRelayActiveMode(ctx context.Context, id, active, reason string, now time.Time) error
- func (s *Store) SetRelayBridge(ctx context.Context, id string, b *RelayBridgeCheck) error
- func (s *Store) SetRelayBridgePool(ctx context.Context, id string, pool uint32, at int64) error
- func (s *Store) SetRelayBridgeSide(ctx context.Context, id, side string, report *RelayBridgeSideCheck) error
- func (s *Store) SetRelayCheck(ctx context.Context, id string, c RelayCheck) error
- func (s *Store) SetRelayCounters(ctx context.Context, nodeID string, updates []RelayCounterUpdate) error
- func (s *Store) SetRelayDirectState(ctx context.Context, id string, streak uint32, at int64) error
- func (s *Store) SetRelayDirectStreak(ctx context.Context, id string, streak uint32) error
- func (s *Store) SetRelayMonitorCheck(ctx context.Context, id string, m RelayMonitorCheck) error
- func (s *Store) SetRolloutStatus(ctx context.Context, id string, from []string, status, pauseKey string, ...) (bool, error)
- func (s *Store) SetScheduledTaskConversation(ctx context.Context, id, conversationID string) error
- func (s *Store) SetScheduledTaskNext(ctx context.Context, id string, next time.Time) error
- func (s *Store) SetSettingAndScheduledTaskNexts(ctx context.Context, key, value string, nexts []ScheduledTaskNext) 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) SetTelegramLinkCode(ctx context.Context, hash, adminID string, expires time.Time) error
- func (s *Store) SetUDPFilteredAt(ctx context.Context, nodeID string, at time.Time) error
- func (s *Store) SetUDPFilteredCheckedAt(ctx context.Context, nodeID string, at time.Time) error
- func (s *Store) SetUDPFilteredState(ctx context.Context, nodeID string, at time.Time, senderID string) 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) SetWarpReach(ctx context.Context, nodeID, reachJSON 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) SkipPendingOsSteps(ctx context.Context, rolloutID, errorKey string, now time.Time) 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) SpeedTestTimes(ctx context.Context, nodeID string, since time.Time) ([]int64, 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) TakeAssistantRate(ctx context.Context, adminID string, minute int64, limit int) (bool, 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) TakeTelegramLinkCode(ctx context.Context, hash string, now time.Time) (string, 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) UDPFilteredAt(ctx context.Context, nodeID string) (time.Time, error)
- func (s *Store) UDPFilteredNodes(ctx context.Context) ([]UDPFilteredState, error)
- func (s *Store) UDPFilteredSender(ctx context.Context, nodeID string) (string, error)
- func (s *Store) UDPPathLosses(ctx context.Context, since time.Time) ([]UDPPathLoss, error)
- func (s *Store) UnacceptDoctor(ctx context.Context, nodeID, checkID string) (bool, error)
- func (s *Store) UnassignDecoySite(ctx context.Context, id string, nodeIDs []string, mode string) ([]NodeRow, error)
- func (s *Store) UnlinkTelegram(ctx context.Context, adminID string) (bool, error)
- func (s *Store) UnreadAssistantConversations(ctx context.Context, adminID string) (int, time.Time, error)
- func (s *Store) UpdateAssistantMemory(ctx context.Context, id, adminID string, sealed []byte, now time.Time) (bool, error)
- func (s *Store) UpdateDecoySite(ctx context.Context, now time.Time, id, name, note, by string) (DecoySiteRow, error)
- func (s *Store) UpdateIPv6(ctx context.Context, nodeID string, fn func(cur IPv6Row) (IPv6Row, error)) (next IPv6Row, changed bool, err 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) UpdateRelay(ctx context.Context, id string, p RelayPatch, now time.Time) 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) UpdateScheduledTask(ctx context.Context, t ScheduledTask) error
- func (s *Store) UpdateUDPPathLosses(ctx context.Context, targetID string, checkedSenders []string, ...) 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) UserHelloKex(ctx context.Context, userID string, since time.Time) ([]HelloKexDevice, error)
- func (s *Store) UserLinks(ctx context.Context, userID string, since time.Time) ([]UserLink, error)
- func (s *Store) UserLinksByHour(ctx context.Context, userID string, since time.Time, byHour bool) ([]UserLink, 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 TelegramKeyAdd
- type TelegramLinkRow
- type TrustTunnelKeyAdd
- type UDPFilteredState
- type UDPPathLoss
- type UserLink
- type UserNodeDNS
- type WarpAccountRow
- type WarpReachItem
- 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 ( // FollowUpsPerConversation and FollowUpsPerAdmin bound the follow-ups waiting at once. FollowUpsPerConversation = 3 FollowUpsPerAdmin = 20 )
const ( AwgPrepareRunning = "running" AwgPrepareDone = "done" AwgPrepareFailed = "failed" )
States of AwgPrepareRow.State.
const ( // ClientDebugRequestTTL is how long a request of the owner waits for the person. ClientDebugRequestTTL = 72 * time.Hour // ClientDebugKeep is how long a row and its lines are kept, counted from the request (the bundle sent unasked: from its receipt). ClientDebugKeep = 7 * 24 * time.Hour // ClientDebugPerDevice is how many received bundles of one device are kept: an answer to a request drops the device's oldest beyond // it, with its lines. It is also how many bundles a person keeps that they sent on their own, whatever devices sent them. ClientDebugPerDevice = 3 // ClientDebugMaxBundles is how many received bundles the panel keeps in all. A bundle sent unasked past it is refused // (ErrClientDebugFull); the owner's requests are never refused for it, but their bundles count. ClientDebugMaxBundles = 200 // ClientDebugMaxBytes is the most the received bundles may weigh together (what their records cost, ClientDebugRow.Bytes): a bundle // sent unasked that would pass it is refused like one past ClientDebugMaxBundles. ClientDebugMaxBytes = 256 << 20 // ClientDebugUnaskedEvery is the least time between two bundles a device sends unasked. ClientDebugUnaskedEvery = 10 * time.Minute // ClientDebugNoteRunes is the longest note of a request. ClientDebugNoteRunes = 200 // ClientDebugIDPrefix starts every id; no node capture's id does. ClientDebugIDPrefix = "dbr_" )
const ( // DebugCaptureKeep is how long a capture and its lines are kept. DebugCaptureKeep = 24 * time.Hour // DebugCapturesPerNode is how many captures of one node are kept: starting another drops the oldest beyond this. DebugCapturesPerNode = 5 // DebugMaxLines and DebugMaxBytes bound one capture on intake, whatever the node sends. DebugMaxLines = 20000 DebugMaxBytes = 4 << 20 // DebugRunGrace is how long past its end a running capture still waits for the node's report; after that it reads as expired. DebugRunGrace = 20 * time.Minute )
const ( DecoySiteLimit = 100 DecoyVersionLimit = 5 // PanelDecoySourceKey is the setting that says what the panel's own public site is: "builtin", "dir" or "site:<id>". PanelDecoySourceKey = "decoy_panel_source" DecoyStateDraft = "draft" DecoyStateReady = "ready" DecoySourceUpload = "upload" DecoySourceAssistant = "assistant" DecoySourceMCP = "mcp" MaxDecoyNameRunes = 60 MaxDecoyNoteRunes = 200 )
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 ( IPv6OK = "ok" // outbound IPv6 works, so the node has a working IPv6 uplink IPv6None = "none" // no global IPv6 address IPv6Broken = "broken" // an address, but outbound IPv6 fails (so does the inbound one) IPv6Unknown = "unknown" // the doctor has not reported yet IPv6AgentOld = "agent_old" // set by the readers: IPv6 works but the agent names no stable address (Addrs is empty) )
States of IPv6Doctor.State.
const ( IPv6ByPanel = "panel" IPv6ByGlobalping = "globalping" )
Who verified an address (IPv6Check.By), besides a node's id.
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 ( HostKeepHours = 90 * 24 HostMaxHours = 720 )
HostKeepHours is how long node_host_hour rows are kept (90 days); HostMaxHours is the longest window one read returns.
const ( )
The ways a node is handed out to groups (migration 00146). A group receives every node that is not on its disabled list; a node the owner holds back is on the list of every group that has not been given it, and of groups made later. The mode is read off that: hold_new_groups = 0 is all, otherwise listed while some group receives it and none when no group does.
const ( OsModeSecurity = "security" OsModeAll = "all" OsModeRebootOnly = "reboot_only" OsRebootNever = "never" OsRebootIfRequired = "if_required" OsRebootAlways = "always" OsStepPending = "pending" OsStepSent = "sent" OsStepRebooting = "rebooting" OsStepGating = "gating" OsStepPassed = "passed" OsStepFailed = "failed" OsStepSkipped = "skipped" )
Rollout modes and step states of an OS update as stored (migration 00130). The statuses are the agent rollout's.
const ( // PathProbeKeepHours is how long a path probe is kept (7 days). PathProbeKeepHours = 7 * 24 // NodeTraceKeep is how many traces of one pair are kept. NodeTraceKeep = 20 // NodeDNSRunKeep is how many resolver runs of one node are kept. NodeDNSRunKeep = 24 )
const ( RelayStageLeg = "leg" // the entry node to the exit's server RelayStagePath = "path" // a third node to the entry's forwarded port, counted at the exit RelayStageReverseReach = "reverse_reach" // the exit node to the entry's HTTPS site RelayStageReverseSpeed = "reverse_speed" // an explicit speed test from the exit node to the entry )
The stages of a check, as RelayCheck.Stage names them.
const ( RelayStageBridge = "bridge" RelayStageDirectSpeed = "direct_speed" )
const ( RelayModeAuto = "auto" // the owner's choice only: the panel picks dnat or reverse RelayModeDNAT = "dnat" // the entry dials the exit RelayModeReverse = "reverse" // the exit dials the entry )
The way a relay passes traffic on (migration 00141, relay.proto "TWO WAYS TO PASS ON"). Nothing here decides a way: the panel's controller (and the owner) write them, the desired state and the admin API read them.
const ( BridgePoolMin = 2 BridgePoolMax = 4 )
The pool of an exit's connections to an entry (BridgeDial.pool) and how the panel chooses it. Two connections do for most pairs (the bridge keeps its own waiting pairs on each and spreads people over them); four carry about twice the people and shield a pair from the loss of one connection, at the price of more waiting pairs. The panel raises the pool to 4 when either holds:
- the relay is busy: its forward carried 10 Mbit/s or more at the last reading (a fresh counter), or
- the bridge is nearly full: the entry carries 80 % or more of what two connections can (2 x BridgePeoplePerConn people), so that the people who come next are not turned away.
It goes back to 2 only after neither has held for 30 minutes and the entry carries under 40 % of what two connections can, so a load that moves around a threshold does not move the pool with it. The figure of people is the bridge's, the same for every relay of the pair, and so is the answer; a pair with several relays takes the largest pool any of them asks for.
const ( // ScheduledRunsKept is how many runs of one task the retention sweep keeps. ScheduledRunsKept = 50 // ScheduledRunsKeep is how long a run is kept at most. ScheduledRunsKeep = 30 * 24 * time.Hour // ScheduledFailingStreak is the number of failed runs in a row that opens SCHEDULED_TASK_FAILING. ScheduledFailingStreak = 3 )
const ( AuditPanel = "panel" AuditBot = "bot" AuditMCP = "mcp" AuditAPI = "api" AuditAssistant = "assistant" )
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 DefaultDeviceIdleAfterDays = 30
DefaultDeviceIdleAfterDays is used for installations created before the setting was added.
const DefaultNetworkMode uint32 = 0
DefaultNetworkMode is the mode of an installation whose owner has not chosen one: 0, nothing is collected. The setting has no place in the admin yet and no page that says what is kept, so collection waits for the owner's explicit choice.
const LinkEvictAfter = 30 * 24 * time.Hour
LinkEvictAfter is retained for older callers as the default idle interval.
const LinkKeepHours = 168
LinkKeepHours is how long link_hour rows live, and the most a connection RPC may look back.
const MaxLinkCount = maxLinkCount
MaxLinkCount is the per-counter bound shared by connection and network statistics.
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.
const (
// NodeJournalKeepHours is the journal retention and the largest window the RPC may read.
NodeJournalKeepHours = 7 * 24
)
const PathSpeedKeepHours = 7 * 24
PathSpeedKeepHours is how long a speed test result is kept (7 days).
const PortProbeTrust = 15 * time.Minute
PortProbeTrust is how long before a UDP port check a passing protocol probe through the same inbound still answers it: a hoster's filter can drop the test datagrams while real clients connect, and probes run every few minutes.
const SettingClientAPI = "client_api.enabled"
SettingClientAPI is the owner's switch of the client API; absent = off. It opens the discovery header on subscription app answers and enrolment by the link (POST <link>/client/enrol), nothing else: a device that is already enrolled does not depend on it (the refusal of a basic fetch that carries its HWID is made whatever the switch says, and the device's own calls will be too).
const SettingClientCompat = "client_compat.rules"
SettingClientCompat is the owner's changes to the client catalogue (access.ClientCompat): a JSON list of rules that differ from the built-in table, or are the owner's own. Absent = the built-in table as it is.
const SettingClientProbe = "client_probe.enabled"
SettingClientProbe is the switch of the kl!ck reports ("1" on, anything else off; absent = off). subsettings reads it with the subscription settings, in the same query, for the Probe-Report header; clientprobe changes it.
const SettingDeviceIdleAfterDays = "device_idle_after_days"
SettingDeviceIdleAfterDays is the subscription setting that controls when an unused device stops filling a place.
const SettingNetworkMode = "networks.mode"
const TelegramProtocol = "mtproto"
TelegramProtocol is the protocol id of the MTProto credential.
const TrustTunnelProtocol = "trusttunnel"
TrustTunnelProtocol is the protocol id of a person's official-app key.
const (
UDPFilteredCheckInterval = 24 * time.Hour
)
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") // ErrDeviceRevoked is returned when a device key belongs to a revoked device. ErrDeviceRevoked = errors.New("store: device revoked") // ErrDeviceEnrolled is returned by the basic paths (EnsureLinkDevice, EnsureLinkAWGCreds) for the HWID of an enrolled device: its // credentials leave only with its key, never to whoever sends the HWID with the link. ErrDeviceEnrolled = errors.New("store: device is enrolled in the client API") ErrNoSharedDevice = errors.New("store: no shared device in strict mode") // ErrNoLinkCredentials is returned by EnrolLinkDevice when the issuer has no credential to give: an enrolled device is never // left without any, and nothing was written. ErrNoLinkCredentials = errors.New("store: no credentials to issue to the enrolled device") )
var ( ErrAssistantLimit = errors.New("store: assistant limit reached") ErrAssistantConversationGone = errors.New("store: assistant conversation no longer exists") )
var ( // ErrFollowUpConversationLimit: the conversation already has FollowUpsPerConversation follow-ups waiting. ErrFollowUpConversationLimit = errors.New("store: too many follow-ups in the conversation") // ErrFollowUpAdminLimit: the admin already has FollowUpsPerAdmin follow-ups waiting. ErrFollowUpAdminLimit = errors.New("store: too many follow-ups of the admin") )
var ( ErrAuthCeremonyNotFound = errors.New("auth ceremony not found") ErrAuthCeremonyLimit = errors.New("too many pending ceremonies") )
var ( // ErrClientDebugOpen: the device already has an open request. ErrClientDebugOpen = errors.New("store: this device already has an open log request") // ErrClientDebugClosed: the request is not open any more (answered, cancelled, declined, expired). ErrClientDebugClosed = errors.New("store: the log request is not open") // ErrClientDebugNoRequest: no open request of this device has the id. ErrClientDebugNoRequest = errors.New("store: no open log request") // ErrClientDebugStillOpen: the request is open and has not run out; it is cancelled, not deleted. ErrClientDebugStillOpen = errors.New("store: the log request is still open") // ErrClientDebugFull: the panel keeps ClientDebugMaxBundles bundles already. ErrClientDebugFull = errors.New("store: the panel keeps as many logs as it takes") )
var ( ErrDecoySiteNotFound = errors.New("decoy site not found") ErrDecoyNameTaken = errors.New("decoy site name is taken") ErrDecoyNameInvalid = errors.New("decoy site name is empty, too long or has control characters") ErrDecoyNoteInvalid = errors.New("decoy site note is too long or has control characters") ErrDecoyLibraryFull = errors.New("decoy library is full") ErrDecoySiteDraft = errors.New("decoy site is a draft") ErrDecoyVersionNotFound = errors.New("decoy site version not found") ErrDecoyNotAssigned = errors.New("decoy site does not stand on this node") )
Refusals of the decoy library. They are here, not in decoy_site.go, because the fleet code that words them is built for the edge too (which keeps no library: the code that returns them is VPS-only).
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 ( // ErrRelayExists: the entry already forwards this server. ErrRelayExists = errors.New("store: relay exists") // ErrRelayPortTaken: another relay of the entry holds this network and port. ErrRelayPortTaken = errors.New("store: relay port taken") // ErrRelayNodes: the server or the entry is not there, is retired, or both are the same node. ErrRelayNodes = errors.New("store: relay needs a server and another, enrolled node") )
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 ErrDebugBusy = errors.New("store: a debug capture of this node is running")
ErrDebugBusy: a capture of this node is still running.
var ErrInvalidNetworkMode = errors.New("store: network mode must be 0, 1 or 2")
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 ErrScheduledTaskLimit = errors.New("store: too many scheduled tasks")
ErrScheduledTaskLimit is returned when the panel already holds the most tasks it allows.
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 BridgeCapacity ¶
BridgeCapacity is the most people a pool of this many connections carries at once (plugin.BridgePeoplePerConn a connection).
func BridgeNearFull ¶
BridgeNearFull says the entry carries 80 % or more of what the pool can.
func BridgePool ¶
func BridgePool(prev uint32, prevAt int64, clients uint32, bps uint64, now time.Time) (uint32, int64)
BridgePool is the pool to ask for, and when the reason for 4 last held, given what was asked before (0 = nothing yet).
func CapabilityPresent ¶
CapabilityPresent reports whether an agent capability list contains want.
func CleanDisplayText ¶
CleanDisplayText makes text from a subscriber or a node fit to show: invalid UTF-8 and UnsafeDisplayRune characters go, the ends are trimmed, and it is cut to max characters.
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 DeviceKindName ¶ added in v0.1.56
DeviceKindName returns the persisted kind as a lowercase enum name without a possible generated prefix.
func FollowUpTokenID ¶
FollowUpTokenID is the hidden identity of an admin's unattended assistant follow-up turns.
func GroupGetsNode ¶
GroupGetsNode is the one rule of which nodes a group hands out: every node except the ones on its disabled list. A node the owner holds back (NodeShare) is on the list of every group that was not given it, groups made later included, so the rule has no case for it. Every reader of a group's nodes asks here (or, in SQL, uses accGroupGetsNode).
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 InboundLive ¶ added in v0.1.65
InboundLive is the part of "an inbound is usable" that is not about a person: it is on and not failed, on an enrolled node. The access module's liveInbound and the relay rule (RelayLink.Live) are this one definition.
func IsPanelEventCode ¶
IsPanelEventCode reports codes reserved for panel-authored event rows. The source field is always set by the panel at ingestion, so an agent must not be able to make its event look like one of these transitions. A code both sides raise (stats_dropped: the agent's outbox overflowed, the panel refused a batch) is not reserved.
func LinkModeOf ¶ added in v0.1.39
LinkModeOf is the mode a stored value names; anything else, and nothing, is LinkModeTrack.
func LinkWindowHours ¶ added in v0.1.53
LinkWindowHours is the window of a connection RPC in hours: 0 means 24, and more than the retention is cut to it.
func NewClientDebugID ¶
func NewClientDebugID() string
NewClientDebugID is a new id: "dbr_" and 16 random bytes in base64url.
func NodeJournalWindowHours ¶ added in v0.1.55
NodeJournalWindowHours applies the admin RPC's bounded window: 0 means 24 hours and the maximum is retention.
func NodeProvisionCredentialsAAD ¶ added in v0.1.80
NodeProvisionCredentialsAAD binds a temporary install credential to its durable provisioning job.
func NodeServerAccessPasswordAAD ¶ added in v0.1.80
NodeServerAccessPasswordAAD binds a saved SSH password to its node.
func OwnProbeRef ¶
OwnProbeRef is the reference result of a probe's last finished round as the row keeps it: "blocked", "open", "fail" or "" (no round yet).
func ParseNetworkMode ¶
ParseNetworkMode returns the stored setting, or the default when it is absent or invalid.
func PendingNodeServerPasswordAAD ¶ added in v0.1.80
PendingNodeServerPasswordAAD binds an unverified replacement SSH password to its node.
func ProtocolAnswers ¶ added in v0.1.77
ProtocolAnswers reports whether a passing protocol probe at probeOK answers a port check at checked: after it, or at most PortProbeTrust before it.
func RelayPathNetwork ¶
func RelayTargetInbound ¶
func RetainedKeyAAD ¶
RetainedKeyAAD is the vault AAD of a retained server key: bound to the pair, not to the inbound that is gone.
func ScheduledTokenID ¶
ScheduledTokenID is the id of the hidden identity the scheduled tasks of an admin run with (internal/panel/tasks): a row like the assistant's (assistant_only, never issued, refused on every external route) with the operator profile, whatever the admin's role, so a task can read, run probes and prepare plans but never reach an admin tool. Its own id keeps it apart from the admin's assistant identity, which carries the admin's own profile.
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 UnsafeDisplayRune ¶
UnsafeDisplayRune reports a character that must not reach text shown to people: a control character, a bidirectional control or isolate, a zero-width space, a deprecated format character, a byte-order mark or a tag character. They reorder or hide the text around them. The joiner and the non-joiner (U+200D, U+200C) stay: Persian and Arabic words and emoji sequences need them.
func UsableIPv6 ¶ added in v0.1.66
UsableIPv6 is s as a global unicast IPv6 address, in its canonical spelling (not a unique-local, link-local or mapped IPv4 one).
func ValidRelayMode ¶
ValidRelayMode: the owner's choice (Relay.Mode) is one of the three words.
func WithAuditActor ¶
WithAuditActor replaces a signed-in admin's id with the named in-process actor in audit rows. It is set only by the assistant's trusted MCP bridge and leaves domain writes using the actual admin id.
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
AssistantOnly bool
AllowBulkUserChanges bool
}
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 ¶
type AWGImplicitWant struct {
ProfileID string
Path string // "" is direct; extra paths are "ipv6" or "relay:<entry node id>"
MaxIdx int
Issue AWGIssue
}
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 AWGPathFailure ¶
AWGPathFailure records a relay key that could not be issued without failing the direct credentials in the same request.
type AWGPathFull ¶
AWGPathFull names a skipped path credential whose profile has no free peer address.
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) AddTelegramKey ¶ added in v0.1.69
AddTelegramKey inserts the key device with its credential in one guarded batch. The device limit does not apply to it. ErrAccessExists when the user holds a key already, ErrNotFound when the user is gone.
func (Access) AddTrustTunnelKey ¶
AddTrustTunnelKey adds the person's one live TrustTunnel key. Unlike the Telegram key, it takes a device-limit place.
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) ClientAPIStats ¶
func (a Access) ClientAPIStats(ctx context.Context) (ClientAPIStats, error)
ClientAPIStats reads the three numbers in one query (the VPS and the edge editions alike).
func (Access) ClientCompatDevices ¶
func (a Access) ClientCompatDevices(ctx context.Context, userID string) ([]ClientCompatDevice, error)
ClientCompatDevices are the live, not blocked link devices that hold a live VLESS credential, with the user they belong to; userID non-empty restricts it to one person. A device without a VLESS credential is never handed a REALITY server, whatever its person's group holds. Revoked and blocked devices are gone from the subscription.
func (Access) CountLinkAWGKeys ¶ added in v0.1.80
CountLinkAWGKeys counts live AWG peers held by link devices, across all users. AmneziaVPN keys are separate devices and are not part of the subscription link's count, nor are the peers of the devices of the Mistgate app (they hold a key of their own and do not follow the owner's link switch).
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) CreateUserWithKeys ¶
func (a Access) CreateUserWithKeys(ctx context.Context, u AccessUser, keys ...AccessKeyDevice) error
CreateUserWithKeys inserts a user, its node selection, and zero or more devices with their credentials in one transaction. The devices go in as given (a key device carries Key and CreatedAt itself, like the implicit device of CreateUser).
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 ¶
func (Access) Devices ¶
Devices returns the non-revoked devices of a user that hold a live credential, with their credential protocols.
func (Access) EnrolLinkDevice ¶
func (a Access) EnrolLinkDevice(ctx context.Context, dev AccessDevice, limit int, now time.Time, issue LinkIssue) (LinkDeviceResult, error)
EnrolLinkDevice enrols one request device with credentials in the same guarded batch. It never adopts a shared device. A matching keyless device keeps its row while its old credentials and AWG peers are revoked/quarantined and fresh credentials and hashes are written. An already enrolled row is not replaced.
func (Access) EnsureEnrolledLinkDevice ¶
func (a Access) EnsureEnrolledLinkDevice(ctx context.Context, dev AccessDevice, now time.Time, issue LinkIssue, want []AWGImplicitWant, limits ...int) (LinkDeviceResult, error)
EnsureEnrolledLinkDevice fills an already enrolled link device with ordinary and per-profile credentials in one guarded write batch. The key hash, and that the device is still enrolled under the user's current link, are checked again in the batch, so a concurrent leave, block, re-key or link rotation cannot issue credentials to a stale request (ErrAccessExists). Basic link issuance keeps its key_hash IS NULL guards.
func (Access) EnsureKeyPathCred ¶
func (a Access) EnsureKeyPathCred(ctx context.Context, deviceID, profileID, path string, maxIdx int, now time.Time, issue AWGIssue) (AccessCred, bool, error)
EnsureKeyPathCred gives a static AWG device one peer for a relay entry of its profile. The direct key must still be live, and the relay is checked in the guarded insert so a concurrent delete cannot leave a new orphan path key behind.
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, ErrAccessBlocked, ErrNoSharedDevice: see linkDeviceState.birth); limit is the user's device limit. No existing device or credential is replaced to make room.
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 active devices as the stored mode allows for it (linkCeiling of limit, the user's device limit): *AccessLimitError. Idle devices keep their rows and credentials. 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, 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) HasUserCredentialOnNode ¶
HasUserCredentialOnNode checks the desired-access joins for one user without building the node's full credential list.
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) LinkDeviceByKeyHash ¶
func (a Access) LinkDeviceByKeyHash(ctx context.Context, keyHash []byte) (AccessDevice, LinkDeviceKeyOwner, error)
LinkDeviceByKeyHash finds a link device by its globally unique key hash and the owner's small projection (what sync needs). A live device comes back with its owner; a key of a removed device is ErrDeviceRevoked, of a blocked one ErrAccessBlocked, and an unknown key ErrNotFound. For the first two the device is empty (a caller cannot serve it by mistake) and only the owner is returned, so a caller can answer "removed" or "blocked" to the one who holds the key. Revoked rows keep their hashes: a key is never reusable.
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) NodeAudience ¶
NodeAudience counts, per group, the active people who would see a node when their group receives it: those who use every node or picked this one. The panel's own cache of what a share change does to people.
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, telegram, trustTunnel bool) ([]AccessBrief, error)
ProfileUsers lists users whose group contains the profile and whose app toggles allow it. 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) RelayAudienceUsers ¶
RelayAudienceUsers reads the subscription access fields for every person once. NodeIDs is limited to the candidate exits and entry, so callers can apply the same node-selection rule as subscriptions without a query per candidate.
func (Access) RelayReachabilityUsers ¶
func (a Access) RelayReachabilityUsers(ctx context.Context) ([]RelayReachabilityUser, error)
RelayReachabilityUsers reads, for every person, only what the relay rule needs: group, switch-off, node list. One light pass instead of the user list's counters, for a check that runs in the health loop.
func (Access) RelayStaticAWGDeviceCounts ¶
func (a Access) RelayStaticAWGDeviceCounts(ctx context.Context, profileIDs []string) (map[string]map[string]uint64, error)
RelayStaticAWGDeviceCounts counts live static AmneziaVPN keys by person and profile for the candidate AWG profiles.
func (Access) RemoveProfileInbounds ¶
func (a Access) RemoveProfileInbounds(ctx context.Context, profileID string, nodeIDs []string, deleteProfile bool, now time.Time, retain func(stateEnc []byte, profileID, nodeID string) ([]byte, error)) ([]AccessInbound, error)
RemoveProfileInbounds removes the inbounds of a profile on the given nodes in one transaction and returns them; a node that does not carry the profile is skipped. With deleteProfile the profile goes in the same transaction (its inbounds must all be among the removed ones, else ErrAccessInUse and nothing changes). Without it retain parks the server key of a per-device (AWG) inbound for the pair, as DeleteInbound does. ErrNotFound: no such profile; ErrConflict: the inbounds of the profile kept changing while this ran.
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) RevokeEnrolledLinkDevice ¶
func (a Access) RevokeEnrolledLinkDevice(ctx context.Context, dev AccessDevice, now time.Time) error
RevokeEnrolledLinkDevice removes a link device only while the key that authorized the request is still current. It uses the same revoke statements as the user's device page, so credentials are removed from desired node state and AWG peers are quarantined. A concurrent key rotation, block or removal makes this a no-op.
func (Access) RevokeLinkAWGCreds ¶ added in v0.1.80
func (a Access) RevokeLinkAWGCreds(ctx context.Context, dev AccessDevice, now time.Time) (int, error)
RevokeLinkAWGCreds drops the live AWG credentials of one link device and quarantines their peer indexes in one guarded batch. The device identity is checked in the database so an AmneziaVPN key can never be passed through accidentally, nor a device of the Mistgate app (one that holds a key): its AmneziaWG does not follow the owner's link switch.
func (Access) RevokeTelegramKey ¶ added in v0.1.69
RevokeTelegramKey revokes the user's Telegram key (see RevokeDevice) and reports whether there was one.
func (Access) RevokeTrustTunnelKey ¶
func (a Access) RevokeTrustTunnelKey(ctx context.Context, userID string, now time.Time) (bool, error)
RevokeTrustTunnelKey revokes the key's device and credential, freeing its device-limit place.
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) RotateTelegramKey ¶ added in v0.1.69
func (a Access) RotateTelegramKey(ctx context.Context, userID string, cred AccessCred, now time.Time) (string, error)
RotateTelegramKey replaces the credential of the user's key (the device stays, so its place and label do): the old one is revoked and cred, with the new secret, takes its place in one guarded batch. It returns the key's device. ErrNotFound when the user has no key.
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) SetLinkDeviceKeyHash ¶
func (a Access) SetLinkDeviceKeyHash(ctx context.Context, userID, deviceID string, expectedKeyHash, keyHash, enrolTokenHash []byte) (bool, error)
SetLinkDeviceKeyHash changes the key and enrol-token hashes only while the user's live link device has the expected current key hash (nil for a first set). The one-statement guard is atomic on both SQLite and D1.
func (Access) SetNodeShare ¶
func (a Access) SetNodeShare(ctx context.Context, nodeID string, c NodeShareChoice, now time.Time) error
SetNodeShare hands a node out as asked, in one transaction. ErrNodeRetired for a retired node, ErrNotFound for none.
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) SubTokenHashes ¶
SubTokenHashes returns the subscription token hashes (sha256) of every user.
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) TelegramKey ¶ added in v0.1.69
func (a Access) TelegramKey(ctx context.Context, userID string) (AccessDevice, AccessCred, error)
TelegramKey returns the user's live Telegram key: its device and credential. ErrNotFound when there is none.
func (Access) TelegramKeyUsers ¶ added in v0.1.69
TelegramKeyUsers maps the given users to the device of their Telegram key; users without one are absent.
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) TrustTunnelKey ¶
func (a Access) TrustTunnelKey(ctx context.Context, userID string) (AccessDevice, AccessCred, error)
TrustTunnelKey returns the person's live TrustTunnel key, or ErrNotFound.
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) UpdateGroupWithDisabledNodes ¶ added in v0.1.68
func (a Access) UpdateGroupWithDisabledNodes(ctx context.Context, id string, name *string, profileIDs *[]string, dnsPresetID, color *string, disabledNodeIDs *[]string) error
UpdateGroupWithDisabledNodes updates a group and optionally replaces its disabled node set.
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
// Relays are the relays that are on, and PathCreds the live extra-path keys of the device (path <> ”), read in the same batch:
// the configs through an entry need both, and a call of their own would cost the edge another round trip.
Relays []RelayLink
PathCreds []AccessCred
}
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
Path string // "" is the direct key; "relay:<node id>" is a relay key
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, AppTelegram, AppTrustTunnel bool
MistgateDevice bool // the credential belongs to a client-API-enrolled Mistgate device
}
AccessDesiredCred is a live credential that may go to a node: its user is active, belongs to a group with the inbound's profile, the node is enabled for the group, and the user selected the node or chose all nodes. 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
// Key marks an app key (Telegram, TrustTunnel or AmneziaVPN): kind key with a synthetic hwid_hash and no seen times.
Key bool
KeyHash, EnrolTokenHash []byte // client API hashes; nil until the device enrols
FirstSeenAt, LastSeenAt, CreatedAt time.Time
Idle bool
IdleSinceAt 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.
func (AccessDevice) IsTelegramKey ¶ added in v0.1.69
func (d AccessDevice) IsTelegramKey() bool
IsTelegramKey: the device is the person's Telegram key, which the device limit does not count.
type AccessDeviceCounts ¶
type AccessDeviceCounts struct{ Used, Idle int }
type AccessGroup ¶
type AccessGroup struct {
ID, Name string
ProfileIDs []string
DisabledNodeIDs []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 with an optional disabled-node set.
func (AccessGroup) GetsNode ¶
func (g AccessGroup) GetsNode(nodeID string) bool
GetsNode is GroupGetsNode for the group.
type AccessInbound ¶
type AccessInbound struct {
ID, ProfileID, NodeID string
PortOverride uint16 // 0 = none
TLSServerNameOverride string
Enabled bool
DirectInSubscriptions 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 AccessKeyDevice ¶
type AccessKeyDevice struct {
Device AccessDevice
Creds []AccessCred
}
AccessKeyDevice is one key device and its initial credentials, inserted with its new user.
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
// IPv6Entry is the node's IPv6 entry (nodes.ipv6_entry): the address of its "· IPv6" server, "" = off.
IPv6Entry string
// PublicLabel is the owner's short text for people (nodes.public_label): "" = none. Not the node's name.
PublicLabel string
// ClientIPv6 is the node's "IPv6 for clients" switch (nodes.client_ipv6); false also for a row that was not read from the table.
ClientIPv6 bool
// IPv6 is what the doctor's ipv6 check last said of the node's uplink (the state the node page words as "IPv6 at the hoster does
// not work"); the zero value means it has not reported. WarpIPv6 says the node's enabled WARP account has an IPv6 address, which is
// what makes the node route client IPv6 into WARP.
IPv6 IPv6Doctor
WarpIPv6 bool
}
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, AppTelegram, AppTrustTunnel 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)
// AppMistgateOff is the Mistgate app switch of the person, stored as "off" so that the zero value (a row nobody touched) keeps
// what the person had before the switch existed: the app works while the subscription link (AppHapp) is on.
AppMistgateOff bool
}
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, Telegram 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", "over_device_limit" or "telegram".
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 AssistantFollowUp ¶
type AssistantFollowUp struct {
ID string
ConversationID string
AdminID string
NoteEnc []byte // sealed by the assistant service
PlanID string // the plan whose apply starts the clock; "" = it counts from CreatedAt
DelayS int
NotifyTelegram bool
CreatedAt time.Time
DueAt time.Time // zero while it waits for its plan
LeaseID string
LeaseUntil time.Time
Attempts int
}
AssistantFollowUp is one row of assistant_follow_up.
type AssistantProviderChoice ¶
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, AuditAPI or AuditAssistant
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
Since time.Time
Actor, Contains string
}
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". Since keeps the rows at or after that time (zero = any age). Actor keeps the rows whose actor id or resolved name contains it, Contains the rows whose action contains it; both are literal substrings (LIKE: ASCII case-insensitive), "" = any.
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
UDPSent, UDPLost uint32 // migration 00080: the Hysteria2 check's QUIC packets; 0 = none
ExitIP, ExitCountry, ErrorCode, ErrorDetail string
}
CheckSample is one finished round of the synthetic checker. Status: 1 ok, 2 degraded, 3 failed.
type ClientAPIStats ¶
type ClientAPIStats struct{ People, PeopleOn, Devices int }
ClientAPIStats is who uses the Mistgate app: everybody, the people who have it on (the person's switch, and the subscription link on too, because the app rides on it) and the devices that are connected with a key of their own and not removed.
type ClientCompatDevice ¶
type ClientCompatDevice struct {
ID, UserID, Platform, Model, OSVersion, Client string
LastSeenAt time.Time
}
ClientCompatDevice is a subscription-link device as the client catalogue needs it: who, which app, when.
type ClientDebugIntake ¶
type ClientDebugIntake struct {
RequestID, NewID string
UserID, DeviceID string
App string
Lines []ClientDebugLine
Bytes, DroppedKV int
FirstMs, LastMs int64
Now time.Time
}
ClientDebugIntake is a bundle to store. RequestID names the open request it answers; empty = sent unasked (NewID is then its id).
type ClientDebugLine ¶
ClientDebugLine is one record of a bundle, cleaned. Level: 0 debug, 1 info, 2 warn, 3 error.
type ClientDebugRateError ¶
ClientDebugRateError: this device sent a bundle unasked less than ClientDebugUnaskedEvery ago; After is how long to wait.
func (*ClientDebugRateError) Error ¶
func (e *ClientDebugRateError) Error() string
type ClientDebugRow ¶
type ClientDebugRow struct {
ID, UserID, DeviceID string
Actor string // as stored: the admin who asked ("" for a bundle sent unasked)
ActorName string // the admin's display name, a token's name, else Actor
Unasked bool // the person sent it without a request
Note, Level string // "info" or "debug"
RequestedAt time.Time
ExpiresAt time.Time
// State is open, received, declined, cancelled, or expired (a request of the owner whose time passed: set at read, and by the next request).
State string
ClosedAt time.Time // zero while open
Records, Bytes int
DroppedKV int
FirstMs, LastMs int64
App string
ReadAt time.Time // zero until the owner reads a bundle
ReadBy string
UserName string
DevicePlatform string
DeviceModel, DeviceOS string
}
ClientDebugRow is one request or bundle. The names are resolved on read (empty when the person, the device or the admin is gone).
type ClientProbeCount ¶ added in v0.1.51
type ClientProbeCount struct {
NodeID string
ASN uint32
Operator, Country, Region string
Reports, OK, Freeze, TCPBlocked, Handshake int
NoAnswer int
Last time.Time
}
ClientProbeCount is what the reports since a time say of one node from one network (one AS, operator, country and region). A report counts once per node: OK when every result of the node in it was ok, and once in each verdict one of them got.
type ClientProbeKindCount ¶ added in v0.1.56
type ClientProbeKindCount struct {
NodeID, Kind string
Reports, OK, Freeze, TCPBlocked, Handshake int
NoAnswer, DLChecked, DLStalled int
Last time.Time
DelaySamples []uint32
}
ClientProbeKindCount is one node and server kind's report tally and download/delay samples over a window.
type ClientProbeNetwork ¶ added in v0.1.51
type ClientProbeNetwork struct {
VPN, DirectChecked bool
ASN uint32
Operator, Country, Region, NetworkType string
}
ClientProbeNetwork is the network a kl!ck report was made on, as the app saw it (migration 00075). Zero values are unknown.
type ClientProbeResult ¶ added in v0.1.51
ClientProbeResult is one server result of a report that matched a node. DetailJSON is what was measured.
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 (migrations 00066 and 00084). Verdict is ok | partial | tcp_blocked | blocked | unknown; Detail is the JSON the health module writes and reads (per probe network, ASN, city and answers). Family is the address family that was measured, 4 or 6; the zero value means 4 (what every row before migration 00084 is).
func (CountryCheck) FamilyOrV4 ¶ added in v0.1.64
func (c CountryCheck) FamilyOrV4() int
FamilyOrV4 is Family with the zero value read as IPv4.
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)
BlockAds bool // the apps drop the ad and tracker domains themselves (category-ads-all)
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 // latency_ms: the cold time of the whole round
ConnectP50MS, ConnectP95MS uint32
ResponseP50MS, ResponseP95MS uint32
JitterMS uint32 // standard deviation of response_ms
}
DailyRow is one health_check_daily row. The connect and response percentiles and the jitter are 0 for a day rolled up before migration 00105.
type DebugCaptureRow ¶
type DebugCaptureRow struct {
ID, NodeID, NodeName, Actor, Level string
Sources []string
DurationS int
StartedAt, EndsAt time.Time
State, EndReason string // running | done | expired (read time); "stopped", "expired", "shutdown" once done
Records, Bytes, Dropped int
LastChunkSeq int64
}
DebugCaptureRow is one capture. NodeName is resolved on read (empty when the node is gone).
type DebugLineFilter ¶
type DebugLineFilter struct {
MinLevel int
Source string
AfterSeq int64
// FromMs and ToMs bound the records' own times (unix milliseconds, both ends in); 0 leaves that side open.
FromMs, ToMs int64
Limit int
}
DebugLineFilter selects the lines of one capture. A text search is the caller's: it must run on the cleaned text of the answer.
type DebugLineIn ¶
DebugLineIn is one record as the node sent it. Level is agent.proto Severity (4 debug, 1 info, 2 warning, 3 error).
type DebugLineRow ¶
type DebugLineRow struct {
Seq, AtMs int64
Level int
Source, Message string
Attrs map[string]string
}
DebugLineRow is one stored record. Level: 0 debug, 1 info, 2 warn, 3 error.
type DecoyFileRef ¶
DecoyFileRef is a file of a version with its size, as kept in decoy_site_version.files_json.
type DecoySiteInUseError ¶
DecoySiteInUseError says where a site stands, which is why it cannot be deleted or put back to a draft.
func (*DecoySiteInUseError) Error ¶
func (e *DecoySiteInUseError) Error() string
type DecoySiteInfo ¶
type DecoySiteInfo struct {
DecoySiteRow
Version DecoyVersionRow
NodeCount int
}
DecoySiteInfo is a site with its current version and how many nodes serve it.
type DecoySiteRow ¶
type DecoySiteRow struct {
ID, Name, Note, Source, SourceLabel, State, BundleHash string
CreatedAt, UpdatedAt time.Time
CreatedBy, UpdatedBy string
}
DecoySiteRow is a site without its files.
type DecoyVersionRow ¶
type DecoyVersionRow struct {
SiteID string
Seq int
BundleHash string
CreatedAt time.Time
CreatedBy string
Size int
FileCount int
Files []DecoyFileRef
Title string
Warnings []decoy.Warning
Computed bool
}
DecoyVersionRow is one saved version of a site. Computed is false for a version made by the migration whose bundle has not been read yet (BackfillDecoyVersions).
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, ReceivedAt 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 ExtCheck ¶ added in v0.1.63
ExtCheck is one source's verdict for a node at a time (migration 00082). DetailJSON contains generic vantage details.
type ExtCheckTime ¶ added in v0.1.63
ExtCheckTime is the newest result time for one node and source, without loading its detail JSON.
type FleetConnectionNode ¶ added in v0.1.56
type FleetConnectionNode struct {
ID, Name, CountryCode string
AgentCaps []string
Inbounds []FleetInboundRow
}
FleetConnectionNode is the metadata GetFleetConnections needs, with its inbounds from the same read.
type FleetCredRef ¶
type FleetCredRef struct {
UserID, DeviceID, Protocol string
// OnNode: the credential's user belongs on this node by group, profile and node selection, or had traffic accepted
// from it in the last nodeUserWindow. A disabled user, a revoked device or a switched-off inbound still count, so the
// last batch a node sends after such a change is still booked. Zero when a ref is built without a lookup (tests).
OnNode bool
// RateBps is the strictest speed limit of the credential (its device's or its person's), 0 = unlimited.
RateBps uint64
}
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
DirectInSubscriptions 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 FleetJournal ¶ added in v0.1.55
type FleetJournal struct {
Level int32
Source, Message string
InboundID string
Attrs map[string]string
Count uint32
FirstAt, LastAt int64
}
FleetJournal is one agent.proto JournalEntry after the fleet guard has bounded its fields.
type FleetLink ¶ added in v0.1.53
type FleetLink struct {
CredID, InboundID string
Connects, Rejects, Drops, Stalls, OnlineS uint32
UnknownKeys, Hellos, Handshakes uint32
ClientCloses, Freezes, Quiet, Accepted, HellosForeign, RttSamples uint32
RttMSSum, PktsSent, PktsLost uint64
// links/3 (migration 00114)
HsUnfinished, TLSAlertsSent, TLSAlertsRecv, TLSCertRefused uint32
RealityFallback, AuthFailed, TCPStalls, TCPStalls16K uint32
Initiations, Responses, ResponsesUnmatched uint32
// vless-hello-kex/1 (migration 00127)
HelloPQ, HelloClassic, HelloUnknown uint32
// trusttunnel-refusals/1 (migration 00142): the inbound row's refusals, indexed like plugin.TunnelRefusal.
Tunnel [tunnelRefusalKinds]uint32
}
FleetLink is one LinkCounters row of a StatsBatch (agent.proto, capability "links/1"): the connection counters of one credential on one inbound since the previous batch. CredID "" is the inbound itself.
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 FleetNetwork ¶
type FleetNetwork struct {
InboundID string
ASN uint32
Attempts uint32
Unfinished uint32
Connects uint32
Broken uint32
People uint32
}
FleetNetwork is one NetworkCounters row of a StatsBatch.
type FleetNetworkInbound ¶
type FleetNetworkNode ¶
type FleetNetworkNode struct {
ID, Name, Address, CountryCode, NetworksDBSHA256 string
AgentCaps []string
Inbounds []FleetNetworkInbound
}
FleetNetworkNode is non-secret metadata needed by GetNetworks. Address is consumed only inside the panel to mark relay ASNs.
type FleetNetworkSums ¶
type FleetNetworkSums struct {
NodeID, InboundID string
ASN uint32
Attempts, Unfinished, Connects, Broken uint64
PeakPeople uint64
BaselineAttempts, BaselineUnfinished, BaselineConnects, BaselineBroken uint64
BaselinePeakPeople uint64
}
FleetNetworkSums contains the current window and the preceding window for one node, inbound and ASN.
type FleetNodeLinkSum ¶ added in v0.1.56
type FleetNodeLinkSum struct {
NodeID string
LinkInboundSums
}
FleetNodeLinkSum is one node and inbound's total over a window.
type FleetPersonNetwork ¶
FleetPersonNetwork is one person_networks row. CredID is resolved to a user before storage.
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
Links []FleetLink // connection counters (agent.proto LinkCounters), stored in the same hour bucket
Networks []FleetNetwork
PersonNetworks []FleetPersonNetwork
NetworksDBSHA256 string // digest the agent has loaded, from StatsBatch.networks_db_sha256
Journal []FleetJournal
JournalSecrets []string // this panel's secret names and path prefixes, removed before the journal is stored
Sessions []FleetSessionRef
Certs []FleetInboundCert
// Host is the batch's HostMetrics (nil = the agent sent none): folded into node_host_hour in the same batch.
Host *HostSample
// Live builds the session projection inside each guarded attempt. It must not mutate captured state.
Live func(refs map[string]FleetCredRef) FleetLive
// Span is the interval the node was credited for this batch; with it a credential's speed limit caps its delta
// (speedCeiling). 0 = no cap, for callers that do not know it.
Span time.Duration
}
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
InboundIDs []string // live inbounds currently assigned to this node
Skipped int // deltas and link rows dropped: unknown credential, or inbound not on this node
OffNode int // deltas dropped: the credential resolves but its user does not belong on this node
Clamped int // deltas counted at their credential's speed-limit ceiling instead of the reported size
Probe int // deltas and link rows 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 HealthCrashSignal ¶
HealthCrashSignal is how many crash restarts (agent_started with params crash = 1) a node's agent made in the last 30 minutes, and when the last was.
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
CrashLoops []HealthCrashSignal
// RelayLinks are the enabled relays with their latest client-eye result; read here so the evaluator costs no extra D1 call.
RelayLinks []RelayLink
}
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
NetworksDBSHA256 string
DecoyMode string
DecoyHash string
}
HelloInfo is what a Hello tells the panel.
type HelloKexDevice ¶
type HelloKexDevice struct {
DeviceID, UserID, UserName, Client, Platform string
PQ, Classic, Unknown uint64
LastHour time.Time
}
HelloKexDevice is one device's ClientHello counts over a window (link_hour hello_pq, hello_classic, hello_unknown from migration 00127, summed over every node, inbound and key of the device).
type HelloKexFleet ¶
type HelloKexFleet struct {
PQOnly, ClassicOnly, Mixed, UnknownOnly uint64
Classic []HelloKexDevice
}
HelloKexFleet is the fleet's ClientHellos by device: how many devices sent only post-quantum hellos, only classic ones, both, or only ones that could not be read, and the devices with classic hellos, most first.
type HelloKexSums ¶
type HelloKexSums struct{ PQ, Classic, Unknown uint64 }
HelloKexSums is one device's ClientHello counts over a window.
type HostHour ¶
type HostHour struct {
HourStart int64
Samples uint32
CPUAvg, CPUMax, SoftirqMax, LoadMax float64
RAMUsedMax, RAMTotal uint64
RxAvg, RxMax, TxAvg, TxMax uint64
SessionsMax uint32
// SessionsAvg is the mean people online over the hour's samples.
SessionsAvg float64
// ExtSamples is how many samples carried the resource fields; the fields below are 0 when it is 0 (an agent that
// predates them) and mean "not known", not "none".
ExtSamples uint32
StealAvg, StealMax, IOWaitMax float64
SwapUsedMax uint64
ConntrackMax, ConntrackLimit uint64
TCPSocketsMax uint32
NICSpeedMbps uint32
AgentCPUAvg, AgentCPUMax float64
AgentRSSMax uint64
}
HostHour is one hour of a node's host load: means and peaks.
type HostSample ¶
type HostSample struct {
CPUPct, SoftirqPct, Load1 float64
RAMUsed, RAMTotal uint64
RxBps, TxBps uint64
Sessions int
// Ext is set when the agent sent the resource fields (HostMetrics.agent present, migration 00110); without it the fields
// below are not known and are not folded in.
Ext *HostSampleExt
}
HostSample is one HostMetrics reading with the number of sessions of the same batch.
type HostSampleExt ¶
type HostSampleExt struct {
StealPct, IOWaitPct float64
SwapUsed uint64
ConntrackCount, ConntrackMax uint64
TCPSockets uint32
NICSpeedMbps uint32
AgentCPUPct float64
AgentRSS uint64
}
HostSampleExt is what an agent with the resource fields adds to a sample.
type IPv6Check ¶ added in v0.1.66
type IPv6Check struct {
Addr string `json:"addr"`
At int64 `json:"at"` // unix seconds
// By is the id of the node that sent the probes, IPv6ByPanel or IPv6ByGlobalping (which only proves that a connection
// opens, not that it reached this node). Empty when nothing could send.
By string `json:"by,omitempty"`
// Sender is By as a person reads it: the name the node had then, "panel" or "globalping".
Sender string `json:"sender,omitempty"`
Pass bool `json:"pass"`
// Code says why a check did not run or could not be trusted: node_offline, agent_too_old, nothing_to_check,
// no_ipv6_verifier, failed. Empty when the ports were probed (a refusing port is in Verdicts, not here).
Code string `json:"code,omitempty"`
Verdicts []IPv6Verdict `json:"verdicts,omitempty"`
}
IPv6Check is the outcome of one check of an IPv6 address of a node from outside (fleet.CheckIPv6): the node's own ports, probed with the same packets as the port check but sent to this address by another node that has working IPv6.
type IPv6Doctor ¶ added in v0.1.66
type IPv6Doctor struct {
State string
Iface string // the interface of the ::/0 route
// Src is the address the kernel picks for outbound IPv6 ("" if the agent could not say).
Src string
// Addrs are the stable global addresses of that interface, with the prefix length the host holds them with.
Addrs []netip.Prefix
}
IPv6Doctor is what the doctor's ipv6 check says of a node (internal/node/doctor checkIPv6).
func DoctorIPv6 ¶ added in v0.1.66
func DoctorIPv6(row *DoctorRow) IPv6Doctor
DoctorIPv6 reads the params of a doctor row of the ipv6 check: ipv6=no|yes, connect=ok|failed and, from agents that know the uplink, iface, src and addrs ("addr/plen,..."). nil = the doctor has not reported.
func (IPv6Doctor) FirstAddr ¶ added in v0.1.66
func (d IPv6Doctor) FirstAddr() string
FirstAddr is the address the node is measured on when nothing better is known: Src if it is stable, else the first stable address.
func (IPv6Doctor) Has ¶ added in v0.1.66
func (d IPv6Doctor) Has(addr string) bool
Has says whether the address is one of the doctor's stable addresses.
func (IPv6Doctor) Works ¶
func (d IPv6Doctor) Works() bool
Works says outbound IPv6 is known to work on the node: the check reported it and it passed. Anything else (no address, a broken uplink, no report yet) is false. It is the other side of the reasons the node page gives for an IPv6 entry that cannot be offered, no_ipv6, ipv6_broken and not_checked (fleet.ipv6Unavailable); agent_old is a working uplink, so it counts as working.
type IPv6State ¶ added in v0.1.66
type IPv6State struct {
// EnabledAt is when the current entry was enabled (unix seconds). Older documents have no timestamp.
EnabledAt int64 `json:"enabled_at,omitempty"`
// Checks are the latest outside checks, one per address, newest first.
Checks []IPv6Check `json:"checks,omitempty"`
}
IPv6State is the document in nodes.ipv6_json. Later steps of the feature add their fields to it (a pending address and its state, the address being retired and until when), so reading an older document needs no migration; a field that is absent reads as its zero value.
func ParseIPv6State ¶ added in v0.1.66
ParseIPv6State reads a document; an unreadable one is empty (it is the panel's own, written by IPv6State.JSON).
func (IPv6State) JSON ¶ added in v0.1.66
JSON is the document as it is stored: "{}" for an empty one, the same bytes for the same content.
type IPv6Verdict ¶ added in v0.1.66
type IPv6Verdict struct {
Net string `json:"net"` // tcp | udp
Port uint16 `json:"port"`
Verdict string `json:"verdict"`
}
IPv6Verdict is the answer for one port in an IPv6Check: tcp "ours", "other", "refused" or "timeout" (internal/tcpcheck), "reachable" when Globalping only connected; udp "ok", "lossy" or "broken".
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 LinkClientSums ¶ added in v0.1.56
type LinkClientSums struct {
Client, Platform string
Devices uint64
Connects, Rejects, Drops, Stalls, OnlineS uint64
Freezes, Quiet, RttMSSum, RttSamples, PktsSent, PktsLost uint64
}
LinkClientSums is one app and platform on an inbound over a window.
type LinkDNSOption ¶ added in v0.1.43
LinkDNSOption is one preset the owner offers for the link apps.
type LinkDeviceKeyOwner ¶
LinkDeviceKeyOwner is the user state needed by a client API device lookup: the id and the hash of the current link, which is all that sync needs to tell a moved link (the status it computes itself). It deliberately omits the sealed subscription token.
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
FullPaths []AWGPathFull // EnsureLinkAWGCreds: relay keys skipped because the profile network is full
FailedPaths []AWGPathFailure
// Replaced is kept for compatibility and is always empty; idle devices are retained.
Replaced string
// Born: the device is new (not found, not taken over from the shared one).
Born bool
// Used and Mode are what the attempt decided on: the user's live devices that count against the limit before this call, and the
// mode of the limit. Callers that report a limit reached (access.placed) need them without a second read.
Used int
Mode string
}
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 LinkHourSums ¶ added in v0.1.56
type LinkHourSums struct {
HourStart int64
Connects, Rejects, Drops, Stalls, OnlineS uint64
UnknownKeys, Hellos, Handshakes uint64
ClientCloses, Freezes, Quiet, Accepted, HellosForeign uint64
RttMSSum, RttSamples, PktsSent, PktsLost uint64
LinkReasons
}
LinkHourSums is one non-zero hour bucket for an inbound or device.
type LinkInboundSums ¶ added in v0.1.53
type LinkInboundSums struct {
InboundID string
Connects, Rejects, Drops, Stalls, UnknownKeys uint64
OnlineS, Hellos, Handshakes uint64
KeysStalled, KeysTried uint64
ClientCloses, Freezes, Quiet, Accepted, HellosForeign uint64
RttMSSum, RttSamples, PktsSent, PktsLost uint64
LinkReasons
}
LinkInboundSums is the counters of one inbound of a node over a window: its keys and its own row together. KeysStalled is the number of keys with a stall, KeysTried the number with a connect or a stall.
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 LinkReasons ¶
type LinkReasons struct {
HsUnfinished, TLSAlertsSent, TLSAlertsRecv, TLSCertRefused uint64
RealityFallback, AuthFailed, TCPStalls, TCPStalls16K uint64
Initiations, Responses, ResponsesUnmatched uint64
// Tunnel is trusttunnel-refusals/1 (migration 00142), indexed like plugin.TunnelRefusal; inbound rows only.
Tunnel [tunnelRefusalKinds]uint64
}
LinkReasons are the links/3 sums (migration 00114): why handshakes failed, where the engine could see it.
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 NewDecoySite ¶
NewDecoySite is the input of CreateDecoySite.
type NodeApplyMeta ¶
type NodeApplyMeta struct {
AppliedAt time.Time
Status string // "applied", "partial", "in_sync" or "" (never)
DurationMS uint32
DriftSince time.Time // zero = no drift
}
NodeApplyMeta is the when and the how of a node's last report of what it runs (migration 00100).
type NodeDNSOption ¶ added in v0.1.17
NodeDNSOption is one preset the owner offers on a node.
type NodeDNSRun ¶
NodeDNSRun is one run of the resolver check of 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 NodeJournalFilter ¶ added in v0.1.55
type NodeJournalFilter struct {
NodeID, Source, InboundID, Query, Code string
Since, Until time.Time
MinLevel int32
Limit int
}
NodeJournalFilter selects saved node journal entries. Since and Until are inclusive hour-window bounds.
type NodeJournalRow ¶ added in v0.1.55
type NodeJournalRow struct {
NodeID, NodeName, ProfileName string
HourStart int64
Level int32
Source, Message, InboundID string
Attrs map[string]string
Count uint32
FirstAt, LastAt int64
}
NodeJournalRow is one saved error kind with its display names resolved at read time.
type NodeLinkReadRow ¶ added in v0.1.56
type NodeLinkReadRow struct {
InboundID, Client, Platform string
HourStart int64
Devices uint64
Connects, Rejects, Drops, Stalls, OnlineS uint64
UnknownKeys, Hellos, Handshakes uint64
ClientCloses, Freezes, Quiet, Accepted, HellosForeign uint64
RttMSSum, RttSamples, PktsSent, PktsLost uint64
KeysStalled, KeysTried uint64
LinkReasons
}
NodeLinkReadRow is the flat row scanned from the single-query report above.
type NodeLinkReport ¶ added in v0.1.56
type NodeLinkReport struct {
Totals LinkInboundSums
Hours []LinkHourSums
Clients []LinkClientSums
}
NodeLinkReport is the totals and optional hour buckets of one inbound, plus its app breakdown.
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, PublicLabel *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
// Sharing is who the node is handed out to once installed; the zero value lets the panel decide (migration 00146).
Sharing NodeShareChoice
}
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
NetworksDBSHA256 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
// IPv6Entry is the address of the IPv6 entry (migration 00086): the node's "· IPv6" server in subscriptions connects to it;
// "" = off. IPv6JSON is the document around it (IPv6State, ipv6_entry.go).
IPv6Entry, IPv6JSON string
// PublicLabel is the short text the owner shows people in the Mistgate app next to the server (migration 00129); "" = none.
PublicLabel string
// LinkSealed is set once the node opened a sealed link session (migration 00134); a plain one is refused after that.
LinkSealed bool
// BridgePort is the TCP port of the node's site that the bridge of a reverse relay arrives at when the node is an entry; 0 = 443
// on the node's own site. BridgePath is the random path of the bridge ("" until the first reverse relay of the entry; migration
// 00141). It is the panel's: it goes to the two agents of a pair and nowhere else.
BridgePort uint16
BridgePath string
// DecoySiteID is the library site this node serves in mode "own" ("" = none; migration 00143). DecoyBundleHash follows the site's
// current version while it is set.
DecoySiteID string
// value decides by whether the node is the panel's first.
Share NodeShareChoice
}
NodeRow is one node row.
func (NodeRow) AwgPrepare ¶
func (n NodeRow) AwgPrepare() AwgPrepareRow
AwgPrepare is the node's preparation state.
func (NodeRow) BridgeEndpointPort ¶
BridgeEndpointPort is the TCP port the exits call on this node as an entry: its separate bridge site, or 443 on its own site.
func (NodeRow) IPv6 ¶ added in v0.1.66
IPv6 is the node's IPv6 document ({} reads as nothing known).
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
PanelKeyFingerprint string
SSHPort uint16
Password, PendingPassword []byte
ConfiguredAt time.Time
PasswordGenerated, PasswordLogin, 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 NodeShareChoice ¶
type NodeShareChoice struct {
}
NodeShareChoice is a share asked for. Mode "" leaves the choice to the panel when the node is made: the first node of the panel goes to every group, a later one to none.
func ParseNodeShareChoice ¶
func ParseNodeShareChoice(s string) NodeShareChoice
ParseNodeShareChoice reads what JSON wrote; anything unreadable is the automatic choice.
func (NodeShareChoice) JSON ¶
func (c NodeShareChoice) JSON() string
JSON is the choice as a job stores it ("" for the automatic one).
type NodeTraceRow ¶
NodeTraceRow is one stored trace of a pair.
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 OsRolloutRow ¶
type OsRolloutRow struct {
ID, Status, Mode, Reboot string
BatchSize int
PauseKey string
PauseParams map[string]string
CreatedBy string
CreatedAt, FinishedAt time.Time // FinishedAt zero while active
}
OsRolloutRow is one OS update rollout.
type OsStatusRow ¶
type OsStatusRow struct {
NodeID string
StatusJSON string
MeasuredAt time.Time
ReceivedAt time.Time
}
OsStatusRow is the latest stored snapshot received from one node.
type OsStepRow ¶
type OsStepRow struct {
RolloutID, NodeID, NodeName string
Stage int
State string
JobID string
Sends int
AckedAt time.Time
Phase string
PhaseAt time.Time
BootBefore time.Time
KernelFrom, KernelTo string
PreFailed []string
SentAt, RebootAt, BackAt time.Time
FinishedAt time.Time
ErrorKey string
Params map[string]string
// contains filtered or unexported fields
}
OsStepRow is one node's turn in an OS rollout.
type OwnProbe ¶
type OwnProbe struct {
ID, Name, City, Kind string
TokenHash, SecretHash []byte
TokenExpires time.Time
State string
ASN uint32
Operator, PinnedOperator, Version string
LastSeen, LastResult time.Time
ChecksDay int
ChecksDayAt time.Time
JobID, JobJSON string
JobDue time.Time
CreatedAt time.Time
CreatedBy string
}
OwnProbe is an owner-managed measurement point. TokenHash and SecretHash are always SHA-256 digests; the source address used to find ASN is intentionally not part of this row.
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 PanelSSHKey ¶ added in v0.1.74
PanelSSHKey is the panel-wide SSH identity. PrivateKey is vault ciphertext and is never returned by RPC methods.
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 PathProbeRow ¶
type PathProbeRow struct {
ID int64
FromID string
ToID string
Kind string
At time.Time
ResultJSON string
}
PathProbeRow is one stored path probe.
type PathSpeedRow ¶
type PathSpeedRow struct {
ID int64
FromID string
ToID string
Direction string
At time.Time
ResultJSON string
}
PathSpeedRow is one stored speed test.
type PathSpeedStartUsage ¶
PathSpeedStartUsage is the recent daily-limit usage for one caller and two nodes.
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, SenderVerdict string
ConfirmSender, ConfirmVerdict, Blame string
ConfirmSent, ConfirmGot uint32
CheckedAt, BadAt time.Time
ProtocolOKAt 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 Relay ¶ added in v0.1.65
type Relay struct {
ID, InboundID, ViaNodeID string
Network string // "tcp" | "udp": the network of the exit's server
Port uint16 // the port on the entry node
Enabled bool
// State is what the entry's agent made of the forward in its last ApplyResult: "pending" (not reported since it was
// switched on), "active" (installed) or "failed" (LastError says why). ToIP is the exit address it points at.
State, LastError, ToIP string
AppliedAt time.Time
CheckJSON string
CreatedAt, UpdatedAt time.Time
// The way the relay passes traffic on (migration 00141; the words of relay.proto Relay.mode and active_mode): Mode is the owner's
// choice ("auto", "dnat" or "reverse"), ActiveMode what stands now ("dnat" or "reverse"), ModeChangedAt when ActiveMode last
// changed (zero = never) and ModeReason why (relay.proto Relay.mode_reason).
Mode, ActiveMode, ModeReason string
ModeChangedAt time.Time
}
Relay is one forward as stored.
func (Relay) Bridge ¶
func (r Relay) Bridge() (RelayBridgeCheck, bool)
Bridge is the last report of the bridge of the relay; the second result is false when there is none.
func (Relay) BridgeSitePin ¶
BridgeSitePin is the pin of the entry's own bridge site on this port, "" when the entry has not reported one for this port (or not lately). It is the one source the exits' BridgeDial.pin_sha256 and the reverse_reach probe use for a separate bridge site.
func (Relay) Check ¶ added in v0.1.65
func (r Relay) Check() (RelayCheck, bool)
Check reads the relay's latest check; the second result is false when there is none.
func (Relay) DirectStreak ¶
DirectStreak is how many checks of the direct leg passed in a row while the relay stands in the reverse way (0 to 3).
func (Relay) DirectStreakAt ¶
DirectStreakAt is the last passing direct check counted toward returning to DNAT.
type RelayApplied ¶ added in v0.1.65
RelayApplied is one RelayResult of an ApplyResult.
type RelayBridgeCheck ¶
type RelayBridgeCheck struct {
Connected bool `json:"connected,omitempty"`
Conns uint32 `json:"conns,omitempty"`
RTTMS uint32 `json:"rtt_ms,omitempty"`
SinceUnix int64 `json:"since_unix,omitempty"`
Error string `json:"error,omitempty"`
AtUnix int64 `json:"at_unix,omitempty"` // when the panel last had a report
Entry *RelayBridgeSideCheck `json:"entry,omitempty"`
Exit *RelayBridgeSideCheck `json:"exit,omitempty"`
// Pool is the TLS connections the panel asks the exit to hold for this relay (2 or 4; 0 = not decided yet, which is 2), and
// PoolAt the last time the reason for 4 held. See BridgePool.
Pool uint32 `json:"pool,omitempty"`
PoolAt int64 `json:"pool_at,omitempty"`
}
RelayBridgeCheck is what the two agents of a pair last reported of the bridge of a relay: check_json.bridge. The panel merges the BridgeState of both sides into it (a bridge is connected when the exit holds a live connection).
type RelayBridgeSideCheck ¶
type RelayBridgeSideCheck struct {
Connected bool `json:"connected,omitempty"`
Conns uint32 `json:"conns,omitempty"`
RTTMS uint32 `json:"rtt_ms,omitempty"`
SinceUnix int64 `json:"since_unix,omitempty"`
Error string `json:"error,omitempty"`
AtUnix int64 `json:"at_unix,omitempty"`
// Clients is the people the entry carries through this bridge right now (BridgeState.clients_now; the entry's report only).
// One bridge serves every relay of the pair, so each relay of it shows the same figure.
Clients uint32 `json:"clients,omitempty"`
// SitePin and SitePort are what the entry's agent reports of the bridge site it runs itself (BridgeState.site_cert_pin_sha256
// and the port it was reported for): the pin the exits verify it by. The entry's report only; empty for a bridge on the site
// of an inbound. Not a secret (a hash of a certificate every visitor of the site is shown), and kept here, with the report it
// came with, because the panel process that builds the exit's desired state is not the one that heard the entry.
SitePin string `json:"site_pin,omitempty"`
SitePort uint16 `json:"site_port,omitempty"`
}
RelayBridgeSideCheck is the state one of the two agents most recently reported for this relay.
type RelayCheck ¶ added in v0.1.65
type RelayCheck struct {
At int64 `json:"at,omitempty"`
Network string `json:"network,omitempty"`
Port uint16 `json:"port,omitempty"`
To string `json:"to,omitempty"` // the exit's address:port
Leg RelayStage `json:"leg"`
Path RelayStage `json:"path"`
ReverseReach RelayStage `json:"reverse_reach,omitzero"`
ReverseSpeed RelayStage `json:"reverse_speed,omitzero"`
// DirectSpeed is the panel's own 8 MB proof of the direct way before a reverse relay returns to DNAT.
DirectSpeed RelayStage `json:"direct_speed,omitzero"`
// Bridge is derived from the agents' reports (Relay.BridgeStage) by whoever shows or uses the check; it is never stored.
Bridge RelayStage `json:"-"`
OK bool `json:"ok"` // the leg ran and no stage that ran failed
Stage string `json:"stage,omitempty"` // the first direct stage that failed
Monitor *RelayMonitorCheck `json:"monitor,omitempty"`
Counters *RelayCounters `json:"counters,omitempty"`
}
RelayCheck is what the last check of a relay found. Port and To are what it was made for: a relay moved to another port or pointed at another address is not covered by it.
func (RelayCheck) CanUse ¶ added in v0.1.73
func (c RelayCheck) CanUse() bool
CanUse says both stages passed or were explicitly skipped because the server identity is unverifiable.
func (RelayCheck) ReverseReachOK ¶
func (c RelayCheck) ReverseReachOK(now time.Time, endpointPort uint16) bool
ReverseReachOK says the exit reached the entry's bridge endpoint lately: a passing reverse_reach, not older than 15 minutes and not from the future, made for the endpoint the entry has NOW (port 0 on a stage is the 443 the first version probed).
func (*RelayCheck) Settle ¶ added in v0.1.65
func (c *RelayCheck) Settle()
Settle recomputes OK and Stage from the two stages. An unverifiable leg is not a failure: its owner may choose to enable the relay, while Verified remains false until both stages actually prove the server.
func (RelayCheck) Verified ¶ added in v0.1.65
func (c RelayCheck) Verified() bool
Verified: both stages ran and passed, the relay works from outside.
type RelayCounterUpdate ¶ added in v0.1.65
type RelayCounterUpdate struct {
RelayID string
Network string
Port uint16
RelayCounters
}
RelayCounterUpdate is one counter snapshot reported by the entry node.
type RelayCounters ¶ added in v0.1.65
type RelayCounters struct {
Bytes uint64 `json:"bytes"`
Packets uint64 `json:"packets"`
CountedUnix int64 `json:"counted_unix"`
PrevBytes uint64 `json:"prev_bytes,omitempty"`
PrevCountedUnix int64 `json:"prev_counted_unix,omitempty"`
TodayBytes uint64 `json:"today_bytes,omitempty"`
TodayDay int64 `json:"today_day,omitempty"`
}
RelayCounters is one snapshot of the named nft counter for a forward. Until the agent counts return traffic, its rate and day total describe only bytes sent toward the exit.
type RelayFilter ¶ added in v0.1.65
type RelayFilter struct {
ID string
ViaNodeID string // the entry node
NodeID string // either end
InboundID string // the exit's server
EnabledOnly bool
}
RelayFilter selects relays. The zero value selects all of them.
type RelayLink ¶ added in v0.1.65
type RelayLink struct {
Relay
// The exit: the node and the server (inbound) the forward leads to.
ExitNodeID, ExitNodeName, ExitNodeState string
ExitEnabled bool
ExitState string // the inbound's state
ProfileID, ProfileName, Protocol string
// The entry node.
ViaNodeName, ViaNodeState string
ViaNodeCaps []string
// The capabilities the exit's agent listed (the reverse way needs them at both ends).
ExitNodeCaps []string
// What a person's subscription needs of the entry: where to connect, its country (the label of the twin) and its capacity.
ViaNodeAddress, ViaNodeCountry string
ViaNodeBandwidthMbps int
}
RelayLink is a relay with what the panel knows of its two ends.
func (RelayLink) BridgeServed ¶
BridgeServed says the entry should run the bridge site for this relay: the relay may use the bridge at all (a TCP relay that is not the owner's DNAT-only choice), switched on or not, so that the site is up, and its pin known, before the first check that needs it and before the first time the exit has to dial. Capabilities are the caller's to check.
func (RelayLink) BridgeStage ¶
func (r RelayLink) BridgeStage(now time.Time) RelayStage
BridgeStage is the bridge stage of a check, derived from what the exit's agent reported (the entry's report says who is on the other side, not whether the bridge works for the exit): "ok" when it holds a connection and has for 10 seconds, "skipped" while the connection is younger, "fail" with the agent's word as the code, "disconnected" without a connection and "stale" when the last report is older than 90 seconds or none came. The time of an ok or skipped stage is the report's, so a caller that asks whether it is fresh asks whether the agent is still talking. A fail that comes from silence is stamped with now: the silence is the finding.
func (RelayLink) BridgeWanted ¶
BridgeWanted says the panel wants the exit to hold its connections to the entry for this relay now. The reverse way needs them; so does an owner who asked for it; and an automatic relay needs them ready, so that the controller can move it in seconds, when the direct way fails (the leg, or a flow that froze) and the exit reaches the entry, and for 30 minutes after it went back to direct (a flow that froze again is then moved back at once). Nothing else holds a bridge "just in case". endpointPort is the port the entry's bridge endpoint has now (NodeRow.BridgeEndpointPort); capabilities are the caller's to check.
func (RelayLink) Live ¶ added in v0.1.65
Live: the exit's server is usable, so the entry may forward to it. A relay is usable for a person when this holds, the person may use the server and the entry node is one of the person's nodes (access.relayUsable).
func (RelayLink) Proven ¶ added in v0.1.65
Proven: the relay's latest check found both stages passing, so the path from outside through the entry to the exit was seen to work. A relay with an unverifiable stage can be usable while not proven.
func (RelayLink) Usable ¶ added in v0.1.73
Usable says every stage either passed or was unverifiable. The caller checks whether the owner enabled the relay. A relay in the reverse way stands on the bridge BECAUSE its direct leg fails (or freezes): the leg is then no part of what makes it usable, the path through the bridge is. Without this the relay is taken out of every subscription at the moment it begins to work.
type RelayModeDecision ¶
type RelayModeDecision struct {
ActiveMode, ModeReason string
DirectStreak uint32
DirectStreakAt int64
Notify bool
// NeedDirectSpeed asks the caller to run the 8 MB proof of the direct way (entry to exit; CheckRelay stage direct_speed) and
// ask again with its result. The controller itself never runs anything.
NeedDirectSpeed bool
}
RelayModeDecision is the controller's proposed state. Notify is set only when desired state changes.
func EvaluateRelayMode ¶
func EvaluateRelayMode(in RelayModeInput) RelayModeDecision
EvaluateRelayMode implements the mode rules of the reverse-relay plan (§7). A check decides only while its own timestamp is fresh and not in the future; reverse reach is never borrowed from another stage, and nothing moves a relay without evidence of its own (the one exception, an owner's word, is also bounded by a working bridge).
Two things keep it from chattering. Leaving reverse for direct takes three direct-leg samples at least 30 minutes apart, a 30 minute stay, and an 8 MB flow of the direct way that the panel runs itself (the leg is only packets: it passes a way that freezes after 16 KB); a failed sample or a failed flow starts the count again. And going to direct because the bridge broke (the leg alive) needs two failed client rounds, so one reconnect of the bridge does not do it, and then forbids a freeze-only reason to come back to reverse for the same 30 minutes.
type RelayModeInput ¶
type RelayModeInput struct {
Mode, ActiveMode, ModeReason string
Network string
EntrySupported, ExitSupported bool
Now, ModeChangedAt time.Time
Leg, ReverseReach, Bridge RelayStage
Path, DirectSpeed RelayStage
DirectStreak uint32
DirectStreakAt int64
// The last client-eye round through the entry's port: when it failed, how many failed in a row, and the stage it
// pointed at ("freeze" when a flow stalled after the first kilobytes while the packets of the leg were fine).
MonitorFailAt int64
MonitorFailStreak uint32
MonitorStage string
}
RelayModeInput is the snapshot the relay mode controller is allowed to consider. It has no store or clock dependency.
type RelayMonitorCheck ¶ added in v0.1.65
type RelayMonitorCheck struct {
AtUnix int64 `json:"at_unix"`
OK bool `json:"ok"`
Stage string `json:"stage,omitempty"`
Code string `json:"code,omitempty"`
ResponseMS uint32 `json:"response_ms,omitempty"`
FailStreak uint32 `json:"fail_streak,omitempty"`
TargetKey string `json:"target_key,omitempty"`
AutoCheckAt int64 `json:"auto_check_at,omitempty"`
AutoCheckTargetKey string `json:"auto_check_target_key,omitempty"`
}
RelayMonitorCheck is the result of the client-eye probe through an enabled relay. The two automatic-check fields are panel bookkeeping and are deliberately not part of admin.v1.RelayMonitor.
type RelayPatch ¶ added in v0.1.65
type RelayPatch struct {
Enabled *bool
Port *uint16
Mode *string // the owner's choice, one of the Relay* mode words; changes no state of the forward
}
RelayPatch changes a relay; nil = unchanged.
type RelayReachability ¶
type RelayReachability struct {
Input RelayReachabilityInput
// contains filtered or unexported fields
}
RelayReachability applies the shared relay-only access rule to one snapshot of access state.
func NewRelayReachability ¶
func NewRelayReachability(in RelayReachabilityInput) RelayReachability
func (RelayReachability) NodeReachedThroughRelays ¶
func (r RelayReachability) NodeReachedThroughRelays(nodeID string, directBlocked map[string]bool) bool
func (RelayReachability) RelayHealthy ¶
func (r RelayReachability) RelayHealthy(id string) bool
func (RelayReachability) UserGiven ¶
func (r RelayReachability) UserGiven(userID, inboundID string) bool
func (RelayReachability) UserHasHealthyRelay ¶
func (r RelayReachability) UserHasHealthyRelay(userID, inboundID string) bool
type RelayReachabilityGroup ¶
type RelayReachabilityInput ¶
type RelayReachabilityInput struct {
NowUnix int64
HealthIntervalS uint32
Inbounds []RelayReachabilityInbound
Groups []RelayReachabilityGroup
Users []RelayReachabilityUser
Relays []RelayReachabilityRelay
}
RelayReachabilityInput is the access state needed to decide whether a node is reached only through relays.
type RelayReachabilityRelay ¶
type RelayReachabilityUser ¶
type RelayStage ¶ added in v0.1.65
type RelayStage struct {
Status string `json:"status,omitempty"`
Code string `json:"code,omitempty"`
Sender string `json:"sender,omitempty"`
Verdict string `json:"verdict,omitempty"`
Sent uint32 `json:"sent,omitempty"`
Got uint32 `json:"got,omitempty"`
At int64 `json:"at,omitempty"`
MB uint32 `json:"mb,omitempty"`
MbitS float64 `json:"mbit_s,omitempty"`
Bytes uint64 `json:"bytes,omitempty"`
ConnectMS uint32 `json:"connect_ms,omitempty"`
FirstByteMS uint32 `json:"first_byte_ms,omitempty"`
DurationMS uint32 `json:"duration_ms,omitempty"`
// Port is the TCP port of the bridge endpoint a reverse_reach probe was made for (0 for every other stage).
Port uint16 `json:"port,omitempty"`
}
RelayStage is one stage of a check. Status is "ok", "fail", "skipped" or "" (did not run); Code says why a stage failed or was skipped (the words of relay.proto RelayStage.code); Sender is the node id that sent the probe, or "panel".
func (RelayStage) Acceptable ¶ added in v0.1.73
func (s RelayStage) Acceptable() bool
Acceptable says the stage either proved the server or could not check it without finding a failure.
func (RelayStage) Unverifiable ¶ added in v0.1.73
func (s RelayStage) Unverifiable() bool
Unverifiable says the stage was skipped because it could not attribute a TLS identity to the server.
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 RuntimeInbound ¶
type RuntimeInbound struct {
NodeID, ID, ProfileName, Protocol string
Enabled bool
SpecVersion int64
State, LastError, AppliedSpecHash string
CertNotAfter time.Time
}
RuntimeInbound is one inbound row of a node as the runtime read needs it: the panel's side (enabled, spec version) and the last result the node reported for it (state, error, applied spec hash, certificate expiry).
type ScheduledTask ¶
type ScheduledTask struct {
ID string
Name string
Kind string // "check" or "assistant"
Enabled bool
ScheduleKind string // "every", "daily" or "weekly"
EveryMinutes int
MinuteOfDay int
Weekday int
Steps string // JSON, check tasks
PromptEnc []byte // sealed, assistant tasks
NotifyTelegram bool
ConversationID string
JitterS int
CreatedBy string
CreatedAt time.Time
UpdatedAt time.Time
NextRunAt time.Time // zero: not scheduled (disabled)
LeaseID string
LeaseUntil time.Time
LastManualAt time.Time
FailStreak int
FailReason string
Problem bool
ProblemSummary string
Version int64
}
ScheduledTask is one row of scheduled_task.
type ScheduledTaskNext ¶
ScheduledTaskNext is the next run time to write when the panel's schedule offset changes.
type ScheduledTaskRun ¶
type ScheduledTaskRun struct {
ID string
TaskID string
TaskVersion int64 // definition version read when this run was claimed; not part of the run history row
Trigger string // "schedule", "manual" or "missed"
Status string // "running", "ok", "problem", "failed" or "skipped"
Reason string
Summary string
Detail string // JSON
Actor string
StartedAt time.Time
FinishedAt time.Time
}
ScheduledTaskRun is one row of scheduled_task_run.
type ScheduledTaskSchedule ¶
type ScheduledTaskSchedule struct {
ID string
Kind string
EveryMinutes int
MinuteOfDay int
Weekday int
}
ScheduledTaskSchedule is the part of an enabled task needed to recalculate its next run.
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
AnswerWait time.Duration // effective command wait captured when the step was sent
ProgressPhase string
ProgressRank int
ProgressDownloaded uint64
ProgressTotal uint64
ProgressSpeed uint64
ProgressUpdatedUnix int64
ProgressError string
ProgressSource string
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.
func HostHourStmt ¶
func HostHourStmt(nodeID string, hourStart int64, s HostSample) Stmt
HostHourStmt folds one sample into the node's hour row: one upsert, run inside the batch that commits the stats, so it costs no round trip of its own.
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) AcquireAssistantTurn ¶
func (*Store) ActiveAlerts ¶
func (s *Store) ActiveAlerts(ctx context.Context) ([]HealthAlert, error)
ActiveAlerts returns every unresolved alert.
func (*Store) ActiveOsRollout ¶
func (s *Store) ActiveOsRollout(ctx context.Context) (OsRolloutRow, error)
ActiveOsRollout is the RUNNING or PAUSED OS rollout, ErrNotFound when there is none.
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) AddDecoySiteVersion ¶
func (s *Store) AddDecoySiteVersion(ctx context.Context, now time.Time, id string, b *decoy.Bundle, by string) (site DecoySiteRow, nodeIDs []string, changed bool, err error)
AddDecoySiteVersion saves a bundle as the newest version of a site and returns the nodes that serve the site (they hold the new hash now). changed is false when the bundle is the current version already.
func (*Store) AddNodeDNSRun ¶
func (s *Store) AddNodeDNSRun(ctx context.Context, r NodeDNSRun) error
AddNodeDNSRun stores a run (one per node and second) and drops the node's runs beyond the newest NodeDNSRunKeep.
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) AddNodeTrace ¶
func (s *Store) AddNodeTrace(ctx context.Context, fromID, toID string, at time.Time, resultJSON string) error
AddNodeTrace stores a trace and drops the pair's traces beyond the newest NodeTraceKeep.
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) AddPathProbe ¶
func (s *Store) AddPathProbe(ctx context.Context, fromID, toID, kind string, at time.Time, resultJSON string) error
AddPathProbe stores the result of one probe.
func (*Store) AddPathSpeed ¶
func (s *Store) AddPathSpeed(ctx context.Context, fromID, toID, direction string, at time.Time, resultJSON string) error
AddPathSpeed stores the result of one speed test.
func (*Store) AddPathSpeedStart ¶
func (s *Store) AddPathSpeedStart(ctx context.Context, actorID, fromID, toID string, at time.Time) error
AddPathSpeedStart reserves one test before it contacts either agent. Failed tests still count against the daily limits.
func (*Store) AddTrafficParams ¶
func (s *Store) AddTrafficParams(ctx context.Context, nodeID string, now time.Time, params map[string]string) error
AddTrafficParams puts the node's traffic over the last 24 hours and the last 7 days (up and down, all protocols, the hour in progress included, from the hourly rollup) in params as traffic_24h_bytes and traffic_7d_bytes. A node without rows has none: both are 0. It is one function for the events and the alerts that carry the two numbers.
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) AppendDebugChunk ¶
func (s *Store) AppendDebugChunk(ctx context.Context, nodeID, id string, chunkSeq uint32, lines []DebugLineIn, secrets []string, now time.Time) (stored int, ok bool, err error)
AppendDebugChunk stores a sequenced report chunk once. A retry of an accepted sequence is acknowledged without storing it again.
func (*Store) AppendDebugLines ¶
func (s *Store) AppendDebugLines(ctx context.Context, nodeID, id string, lines []DebugLineIn, secrets []string, now time.Time) (stored int, ok bool, err error)
AppendDebugLines stores a chunk of a running capture of this node, after the panel's own scrub: addresses, secret names, UUIDs, key-shaped values and hostnames. Only allow-listed attributes are kept, and every text is cut to a bound. Lines beyond DebugMaxLines or DebugMaxBytes are counted as dropped, not stored. A capture that is not running takes nothing: the second return value is false.
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) ArmAssistantFollowUps ¶
ArmAssistantFollowUps starts the clock of the follow-ups that wait for a plan: one whose plan was applied is due delay_s after the apply; one whose plan ended otherwise (failed, rejected, expired, dismissed, gone) goes. It returns how many went.
func (*Store) AssignDecoySite ¶
func (s *Store) AssignDecoySite(ctx context.Context, id string, nodeIDs []string) ([]NodeRow, error)
AssignDecoySite puts a ready site on nodes: their mode becomes "own" and they hold the site's current hash.
func (*Store) AssistantFollowUp ¶
func (s *Store) AssistantFollowUp(ctx context.Context, adminID, id string) (AssistantFollowUp, error)
AssistantFollowUp reads one follow-up of an admin; ErrNotFound when there is none.
func (*Store) AssistantFollowUps ¶
func (s *Store) AssistantFollowUps(ctx context.Context, adminID, conversationID string) ([]AssistantFollowUp, error)
AssistantFollowUps lists the follow-ups of an admin's conversation, the soonest first (those waiting for a plan last).
func (*Store) AssistantRetention ¶
func (*Store) AssistantStopRequested ¶
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) (bool, 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). failedTransition is true only when a requested running build moves to failed; callers use it for the owner notification.
func (*Store) AwgPrepareFinishTransition ¶
func (s *Store) AwgPrepareFinishTransition(ctx context.Context, nodeID string, ok bool, at int64, code, reason string) (switched, failedTransition bool, err error)
AwgPrepareFinishTransition also reports the requested running-to-failed transition for alert delivery.
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) BackfillDecoyVersions ¶
BackfillDecoyVersions works out the files, title and checks of the versions the migration created (they have none yet) from their bundles. A bundle that is missing or no longer valid leaves its version without checks, which is how a page shows it.
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) BeginDebugCapture ¶
BeginDebugCapture records a capture that the node is about to run. A running capture of the same node is ErrDebugBusy; the oldest captures beyond DebugCapturesPerNode (and their lines) are dropped in the same batch.
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) CancelAssistantMCPPlan ¶
func (*Store) CancelClientDebug ¶
func (s *Store) CancelClientDebug(ctx context.Context, id string, now time.Time) (ClientDebugRow, error)
CancelClientDebug withdraws an open request that has not run out. ErrNotFound: no such row; ErrClientDebugClosed: it is not open.
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) ClaimAssistantFollowUp ¶
func (s *Store) ClaimAssistantFollowUp(ctx context.Context, id, leaseID string, now, until time.Time) (bool, error)
ClaimAssistantFollowUp takes the follow-up's lease for one run until `until`: false when a run holds it or it is gone (or not due yet). A follow-up runs once: its row goes when the run ends (FinishAssistantFollowUp).
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) ClaimScheduledTask ¶
func (s *Store) ClaimScheduledTask(ctx context.Context, run ScheduledTaskRun, leaseID string, now, until, notBefore time.Time) (bool, error)
ClaimScheduledTask takes the task's lease for one run until `until`: false when another run holds it (one run of a task at a time), or, for a manual run (notBefore set), when the last manual run started after notBefore. The run row is written in the same batch, so a run exists exactly when its lease was taken.
func (*Store) ClearLoginFailures ¶
ClearLoginFailures forgets the failures of login after a successful sign-in.
func (*Store) ClearOwnProbeJobs ¶
ClearOwnProbeJobs removes queued work while preserving enrollment and counters.
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, every link, and every pending link code; dropped says how many links went.
func (*Store) ClientDebug ¶
ClientDebug returns one row, or ErrNotFound. An open request whose time passed reads as expired at now.
func (*Store) ClientDebugAdmitUnasked ¶
ClientDebugAdmitUnasked says whether a device may send a bundle on its own now: nil, a *ClientDebugRateError with the wait, or ErrClientDebugFull. It is the cheap check made before the body is read; ReceiveClientDebug makes it again in the write.
func (*Store) ClientDebugLines ¶
func (s *Store) ClientDebugLines(ctx context.Context, id string, f DebugLineFilter) ([]DebugLineRow, []string, error)
ClientDebugLines returns the records of a bundle, oldest first after AfterSeq, with the filter applied, and the sources the bundle holds. The text comes back as it was stored: the cleaning of a bundle happened on intake, and the node journal's scrubber (which turns state.json into <host> and a long path into <key>) is not applied to it. The caller filters by attribute key and passes the text through the panel's current secret names. A node capture's id finds no lines here: the ids do not meet.
func (*Store) ClientDebugList ¶
func (s *Store) ClientDebugList(ctx context.Context, userID string, now time.Time) ([]ClientDebugRow, error)
ClientDebugList lists the requests and bundles of a person (everyone when userID is empty), newest first, at most 100.
func (*Store) ClientProbeCounts ¶ added in v0.1.51
ClientProbeCounts reads the counts since a time, by node and network.
func (*Store) ClientProbeKindCounts ¶ added in v0.1.56
func (s *Store) ClientProbeKindCounts(ctx context.Context, since time.Time) ([]ClientProbeKindCount, error)
ClientProbeKindCounts reads one tally per node and kind, plus the measured delay samples needed for a median.
func (*Store) ClientProbeTotals ¶ added in v0.1.51
ClientProbeTotals is the number of reports since a time and when the newest came (zero: none).
func (*Store) CommitPendingNodeServerPassword ¶
func (s *Store) CommitPendingNodeServerPassword(ctx context.Context, nodeID string, encryptedCurrent []byte, ownerChosen, passwordLogin 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) CompleteOwnProbeJob ¶
func (s *Store) CompleteOwnProbeJob(ctx context.Context, id, jobID, version, reference string, now time.Time, interval time.Duration, count int) error
CompleteOwnProbeJob consumes one matching outstanding job and updates its counters. A replay or an older job cannot change the row. checks_day_at is the UTC day bucket's midnight. reference is what the round said of the reference address ("blocked", "open" or "fail"), kept until the next round.
func (*Store) ConfirmOwnProbeNetwork ¶
ConfirmOwnProbeNetwork pins the most recently observed ASN and restores the probe to active.
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, family int, since time.Time) ([]CountryCheck, error)
CountryVerdictChanges reads the rounds of one country and address family 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) CreateClientDebug ¶
func (s *Store) CreateClientDebug(ctx context.Context, row ClientDebugRow, now time.Time) (ClientDebugRow, error)
CreateClientDebug opens a request of the owner for a device with a key. ErrNotFound: the device is none, revoked or has no key; ErrClientDebugOpen: it has an open request that has not run out (one that has is expired by this call, in the same batch). row carries ID, DeviceID, Actor, Note and Level; the person and the times are set here.
func (*Store) CreateDecoySite ¶
func (s *Store) CreateDecoySite(ctx context.Context, now time.Time, in NewDecoySite) (DecoySiteRow, error)
CreateDecoySite saves a bundle as a new site with one version. Refused with ErrDecoyNameTaken, ErrDecoyLibraryFull or the invalid-text errors.
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) CreateOsRollout ¶
CreateOsRollout stores a rollout and its steps in one atomic batch. ErrConflict when another OS rollout is active (the unique index of migration 00130 allows one RUNNING or PAUSED).
func (*Store) CreateOwnProbe ¶
CreateOwnProbe creates a pending probe with the supplied one-time token digest.
func (*Store) CreatePanelSSHKeyIfAbsent ¶ added in v0.1.74
CreatePanelSSHKeyIfAbsent stores the first panel key. Concurrent callers read the row that won the insert.
func (*Store) CreatePasswordSession ¶
func (s *Store) CreatePasswordSession(ctx context.Context, sess Session, checked PasswordCred) error
CreatePasswordSession inserts a password + code sign-in session only while the checked credential is current and the login is not locked. The session insert and successful-sign-in failure reset share one atomic batch. The reset can also clear reservations for wrong checks already inside argon2. Only the handful admitted under this login's limit can finish uncounted. They remain counted against the per-source limit, and every successful sign-in still requires its second factor.
func (*Store) CreateRelay ¶ added in v0.1.65
CreateRelay stores a new relay, switched off and pending. The caller chose the id, the network and the port; the server and the entry must be two different nodes that are not retired. ErrRelayNodes, ErrRelayExists, ErrRelayPortTaken. The two unique keys of the table make both of the last two safe against a concurrent create, on SQLite and on D1.
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) DailyRowsSince ¶
DailyRowsSince returns the aggregates of every inbound for the days at or after since, oldest day first.
func (*Store) DebugCapture ¶
DebugCapture returns one capture, or ErrNotFound. A running capture whose report never came reads as expired at the real time.
func (*Store) DebugCaptures ¶
func (s *Store) DebugCaptures(ctx context.Context, nodeID string, now time.Time) ([]DebugCaptureRow, error)
DebugCaptures lists the captures of a node (every node when empty), newest first.
func (*Store) DebugLines ¶
func (s *Store) DebugLines(ctx context.Context, id string, f DebugLineFilter) ([]DebugLineRow, []string, error)
DebugLines returns the lines of a node's capture, oldest first after AfterSeq, with the filter applied, and the sources the capture holds. Every text goes through the node-journal scrubber once more.
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) DeclineClientDebug ¶
func (s *Store) DeclineClientDebug(ctx context.Context, deviceID, id string, now time.Time) (ClientDebugRow, error)
DeclineClientDebug is the person's refusal of the open request of this device. ErrClientDebugNoRequest: no such request is open.
func (*Store) DecoySiteBundle ¶
func (s *Store) DecoySiteBundle(ctx context.Context, id string, seq int) (*decoy.Bundle, DecoyVersionRow, error)
DecoySiteBundle reads the files of a version (seq 0 = the current one).
func (*Store) DecoySiteInfoOf ¶
DecoySiteInfoOf is DecoySites for one site.
func (*Store) DecoySiteNodes ¶
DecoySiteNodes lists the nodes (not retired) that serve the site.
func (*Store) DecoySiteVersions ¶
DecoySiteVersions lists the versions of a site, the newest first.
func (*Store) DecoySites ¶
func (s *Store) DecoySites(ctx context.Context) ([]DecoySiteInfo, error)
DecoySites lists every site with its current version and the number of nodes that serve it, most recently changed first.
func (*Store) DeferAssistantFollowUp ¶
func (s *Store) DeferAssistantFollowUp(ctx context.Context, id, leaseID string, next time.Time, counted bool) error
DeferAssistantFollowUp gives the lease back with a later time (the conversation was busy, the store failed); counted adds one to its attempts.
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) DeleteAssistantConversation ¶
func (*Store) DeleteAssistantConversations ¶
func (*Store) DeleteAssistantFollowUp ¶
func (s *Store) DeleteAssistantFollowUp(ctx context.Context, adminID, conversationID, id string, now time.Time) (bool, error)
DeleteAssistantFollowUp removes an admin's follow-up that no run holds at now; false when there is none (or it is running).
func (*Store) DeleteAssistantMemory ¶
func (*Store) DeleteAssistantMemoryAll ¶
func (*Store) DeleteBlocklistChecks ¶ added in v0.1.41
DeleteBlocklistChecks forgets every stored check (Disconnect).
func (*Store) DeleteClientDebug ¶
func (s *Store) DeleteClientDebug(ctx context.Context, id string, now time.Time) (ClientDebugRow, error)
DeleteClientDebug deletes a closed request or a bundle, with its lines, in one batch. ErrNotFound: no such row; ErrClientDebugStillOpen: it is open and has not run out. It returns the row as it was.
func (*Store) DeleteClientProbeReports ¶ added in v0.1.51
DeleteClientProbeReports forgets every stored report (Disconnect).
func (*Store) DeleteDecoySite ¶
DeleteDecoySite deletes a site that stands nowhere, with its versions and the bundles nothing else holds.
func (*Store) DeleteExtChecks ¶ added in v0.1.63
DeleteExtChecks forgets the selected sources, or every source when none are given.
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) DeleteRelay ¶ added in v0.1.65
DeleteRelay removes a relay. ErrNotFound.
func (*Store) DeleteScheduledTask ¶
DeleteScheduledTask deletes a task and its runs; false when there was none.
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) DeleteStaleAssistantBudgetReservations ¶
func (s *Store) DeleteStaleAssistantBudgetReservations(ctx context.Context, before, now time.Time) (int64, error)
DeleteStaleAssistantBudgetReservations removes stale calls and settled markers from earlier months.
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) DevicesHelloKex ¶
func (s *Store) DevicesHelloKex(ctx context.Context, since time.Time) (map[string]HelloKexSums, error)
DevicesHelloKex reads, in one statement, the ClientHello counts of every device that has any over [since, now], summed over the credentials, nodes (not retired ones) and inbounds of the device, by device id. Only ids and sums, no joins to the device or the person: the caller keeps the devices it lists and ignores the rest. The answer has one small row per device with a hello in the window, however long the list the caller shows.
func (*Store) DismissAlert ¶
DismissAlert closes an active alert as resolved with resolution "dismissed" (an admin's Close) and clears its mute. OpenAlert keeps it closed while the condition continues. ErrNotFound when the alert does not exist, ErrConflict when it is already resolved.
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) DropDebugCapture ¶
DropDebugCapture removes a capture the node did not accept (offline, too old, busy, refused): nothing ran, so nothing is kept and the per-node slots are not used up. A capture that has received lines stays.
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) DueAssistantFollowUps ¶
func (s *Store) DueAssistantFollowUps(ctx context.Context, now time.Time, limit int) ([]AssistantFollowUp, error)
DueAssistantFollowUps lists the follow-ups whose time has come and that no run holds, the most overdue first.
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) DueOwnProbe ¶
DueOwnProbe marks an active probe for a check at the next sync.
func (*Store) DueScheduledTasks ¶
func (s *Store) DueScheduledTasks(ctx context.Context, now time.Time, limit int) ([]ScheduledTask, error)
DueScheduledTasks lists the enabled tasks whose time has come and that no run holds, the most overdue first.
func (*Store) EnabledScheduledTaskSchedules ¶
func (s *Store) EnabledScheduledTaskSchedules(ctx context.Context) ([]ScheduledTaskSchedule, error)
EnabledScheduledTaskSchedules returns the schedules whose next runs need recalculating after an offset change.
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) EnrollOwnProbe ¶
func (s *Store) EnrollOwnProbe(ctx context.Context, tokenHash, secretHash []byte, asn uint32, operator, pin, version string, now time.Time) (OwnProbe, error)
EnrollOwnProbe atomically consumes a live one-use token. Only the token digest is accepted and the returned row contains the generated secret digest, never the secret itself.
func (*Store) EnsureAssistantFollowUpToken ¶
func (s *Store) EnsureAssistantFollowUpToken(ctx context.Context, adminID, profile string, now time.Time) (APIToken, error)
EnsureAssistantFollowUpToken creates the hidden identity used by unattended follow-up turns at the admin's own read profile.
func (*Store) EnsureAssistantToken ¶
func (s *Store) EnsureAssistantToken(ctx context.Context, adminID, profile string, now time.Time) (APIToken, error)
EnsureAssistantToken creates or refreshes the hidden, per-admin MCP identity used by the assistant. Its secret hash is random and the corresponding secret is never generated or issued. External bearer lookup excludes these rows; only auth's in-process assistant context can use the identity. Keeping a real api_token row binds MCP plans to the ordinary token/profile/approval machinery without creating a user-visible API token.
func (*Store) EnsureNodeBridgePath ¶
EnsureNodeBridgePath gives the node the path of its bridge when it has none and returns the one it has: two callers racing for the first reverse relay of an entry end with the same path. ErrNotFound when the node is gone or retired.
func (*Store) EnsureScheduledToken ¶
func (s *Store) EnsureScheduledToken(ctx context.Context, adminID string, now time.Time) (APIToken, error)
EnsureScheduledToken creates or refreshes the hidden identity of an admin's scheduled tasks (ScheduledTokenID): operator profile, no secret ever issued, named so the approval inbox and the audit read "Scheduled tasks".
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) ExtVerdictChanges ¶ added in v0.1.63
ExtVerdictChanges reads the first row in the window and each later source verdict change for every node.
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) FinishAssistantFollowUp ¶
FinishAssistantFollowUp removes the follow-up its run held: the conversation keeps what came of 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) FinishDebugCapture ¶
func (s *Store) FinishDebugCapture(ctx context.Context, nodeID, id, reason string, nodeDropped uint32) error
FinishDebugCapture ends a running capture of this node: done, with how it ended and what the node could not keep.
func (*Store) FinishScheduledRun ¶
func (s *Store) FinishScheduledRun(ctx context.Context, run ScheduledTaskRun, leaseID string, next time.Time) error
FinishScheduledRun records the outcome of a run and gives the lease back: the run's row, and on the task the next time, the failure count (a failed run adds one, ok and problem start it again, skipped leaves it, and so does a run the panel's stop interrupted) and the problem (set by a problem, cleared by ok; a failed or skipped run says nothing about it). A task deleted or given another lease meanwhile is left alone.
func (*Store) FleetConnectionNodes ¶ added in v0.1.56
func (s *Store) FleetConnectionNodes(ctx context.Context) ([]FleetConnectionNode, error)
FleetConnectionNodes reads every non-retired node and its inbounds in one query. It returns no credentials and of the profile settings only what decides which connection counters a VLESS inbound has (vlessVariantSQL, in Settings).
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) FleetNetworkHourSums ¶
func (s *Store) FleetNetworkHourSums(ctx context.Context, since, previousSince, until time.Time, nodeID string, limit int) ([]FleetNetworkSums, error)
FleetNetworkHourSums aggregates the current and previous equal windows, stopping after limit rows.
func (*Store) FleetNetworkNodes ¶
func (s *Store) FleetNetworkNodes(ctx context.Context) ([]FleetNetworkNode, error)
FleetNetworkNodes reads node and inbound metadata in one query without credentials or protocol secrets.
func (*Store) FleetNodeLinkSums ¶ added in v0.1.56
FleetNodeLinkSums reads all non-retired nodes' inbound totals from link_hour in one query.
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) GetAssistantToken ¶
GetAssistantToken is reserved for the in-process assistant authenticator. User-facing token APIs must use GetAPIToken.
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) HasPendingTelegramLinkCode ¶ added in v0.1.50
HasPendingTelegramLinkCode is the one-row check the edge tick uses before it starts a long poll.
func (*Store) HasRelaysOnNode ¶ added in v0.1.65
HasRelaysOnNode reports whether a relay leads to a server of the node: its inbound state decides whether the entry forwards, so the entry's desired state must follow what the node reports.
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, node-flap and relay inputs in one read batch.
func (*Store) HelloKex ¶
HelloKex reads every person's devices (helloKexDevices) and sorts them into the fleet's classes. The list of classic devices is cut to limit.
func (*Store) IPv6Doctor ¶ added in v0.1.66
IPv6Doctor reads the doctor's ipv6 check of one node.
func (*Store) IPv6Doctors ¶ added in v0.1.66
IPv6Doctors reads the doctor's ipv6 check of every node that has one, by node id: one small query for a list of nodes.
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) IngestEventBounded ¶
func (s *Store) IngestEventBounded(ctx context.Context, nodeID, instance string, seq uint64, now time.Time, e EventRow) (dup, overLimit bool, err error)
IngestEventBounded is IngestEvent under the daily budget of the event's class; overLimit reports that the row was dropped for it (node.last_seq still moves, so the node is acked).
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, device touches, and the connection counters. seq == 0 (not a reliable message) skips the dedup and the counter update.
func (*Store) InsertAssistantFollowUp ¶
func (s *Store) InsertAssistantFollowUp(ctx context.Context, f AssistantFollowUp) error
InsertAssistantFollowUp stores a follow-up in a conversation of its admin, unless the conversation is gone (ErrAssistantConversationGone) or a limit is reached (ErrFollowUpConversationLimit, ErrFollowUpAdminLimit). The limits are part of the insert itself, so two calls at once cannot pass them.
func (*Store) InsertAssistantMemory ¶
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) InsertClientProbeReport ¶ added in v0.1.51
func (s *Store) InsertClientProbeReport(ctx context.Context, report string, at time.Time, n ClientProbeNetwork, rows []ClientProbeResult) (int64, error)
InsertClientProbeReport stores one report in one statement (its rows go as one JSON argument: D1 binds at most 100 values) and returns how many rows it stored. The statement itself checks the switch (SettingClientProbe): a report that passed the check of the handler while Disconnect switched the source off and deleted the reports stores nothing (0).
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, country, family and second is replaced; the same second with another family or country is a row of its own.
func (*Store) InsertEvent ¶
InsertEvent appends an event (for panel and admin events; other modules may use it too).
func (*Store) InsertExtChecks ¶ added in v0.1.63
InsertExtChecks stores one set of rows in one statement. A row for the same node, source and second is replaced.
func (*Store) InsertNodeServerAccess ¶ added in v0.1.74
func (s *Store) InsertNodeServerAccess(ctx context.Context, access NodeServerAccess) error
InsertNodeServerAccess attaches credentials to a live enrolled node only when no access row exists yet.
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) InsertScheduledTask ¶
InsertScheduledTask stores a new task, unless the panel already holds max tasks (ErrScheduledTaskLimit).
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 in one address family, zero when there is none.
func (*Store) LastExtCheckAt ¶ added in v0.1.63
LastExtCheckAt is the newest time for one source and 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) LastScheduledRuns ¶
LastScheduledRuns is the newest run of every task that has one, by task id.
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) LatestDebugCapture ¶
func (s *Store) LatestDebugCapture(ctx context.Context, nodeID string, now time.Time) (DebugCaptureRow, error)
LatestDebugCapture is the newest capture of a node, or ErrNotFound.
func (*Store) LatestOsRollout ¶
func (s *Store) LatestOsRollout(ctx context.Context) (OsRolloutRow, error)
LatestOsRollout is the newest OS rollout of any status, ErrNotFound when there never was one.
func (*Store) LatestProbeSamples ¶ added in v0.1.77
LatestProbeSamples returns the newest stored health-check result for each current inbound. An empty nodeID means all inbounds; callers use it to compare the panel's protocol probe with the latest UDP port check without running probes.
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) (certs []CertRow, sealed bool, err 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. sealed is the node's link seal mark (node.link_sealed), read in the same query so a link accept stays one read.
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) LockLoginFailure ¶
func (s *Store) LockLoginFailure(ctx context.Context, login string, maxFailures int, now time.Time, window, lock time.Duration) (LoginFailure, error)
LockLoginFailure locks a live failure count once it has reached the maximum failed proofs.
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) MarkClientDebugRead ¶
func (s *Store) MarkClientDebugRead(ctx context.Context, id, by string, now time.Time) (first bool, err error)
MarkClientDebugRead records the owner's first read of a received bundle: read_at and read_by are set only while read_at is 0, so first is true for one caller only (the one that writes the audit row).
func (*Store) MarkNodeLinkSealed ¶
MarkNodeLinkSealed records that the node opened a sealed link session.
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) NetworkMode ¶
NetworkMode reads the operator setting. A missing row means DefaultNetworkMode.
func (*Store) NextAssistantFollowUps ¶
func (s *Store) NextAssistantFollowUps(ctx context.Context, adminID string) (map[string]time.Time, error)
NextAssistantFollowUps is, per conversation of an admin, the time of its next follow-up (those waiting for a plan left out).
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) NodeApplyMetas ¶
func (s *Store) NodeApplyMetas(ctx context.Context, nodeID string) (map[string]NodeApplyMeta, error)
NodeApplyMetas reads the apply metadata of one node, or of every node when nodeID is empty; a node without a row is absent.
func (*Store) NodeDNSRuns ¶
NodeDNSRuns returns a node's runs, oldest first.
func (*Store) NodeDecoyBundle ¶ added in v0.1.36
NodeDecoyBundle reads a bundle by its content address and verifies the stored bytes.
func (*Store) NodeDecoyModeCounts ¶
NodeDecoyModeCounts counts the nodes (not retired) in each decoy mode.
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) NodeHostHours ¶
func (s *Store) NodeHostHours(ctx context.Context, nodeID string, now time.Time, hours int) ([]HostHour, error)
NodeHostHours reads a node's hourly host load for the last hours (at most HostMaxHours), oldest first.
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) NodeJournal ¶ added in v0.1.55
func (s *Store) NodeJournal(ctx context.Context, filter NodeJournalFilter) ([]NodeJournalRow, error)
NodeJournal reads the matching entries from the hourly buckets that touch [since, until]. Query is a case-insensitive substring of message or attrs_json; LIKE metacharacters are escaped so they stay literal.
func (*Store) NodeLinkReports ¶ added in v0.1.56
func (s *Store) NodeLinkReports(ctx context.Context, nodeID string, since time.Time, byHour bool) ([]NodeLinkReport, error)
NodeLinkReports reads one node's totals, optional hour buckets and client breakdown in one query.
func (*Store) NodeLinkSums ¶ added in v0.1.53
func (s *Store) NodeLinkSums(ctx context.Context, nodeID string, since time.Time) ([]LinkInboundSums, error)
NodeLinkSums reads the counters of a node's inbounds over the hour buckets that touch [since, now], one row per inbound that has any. It is one read (a per-key subquery folds the keys). The handshakes of the panel's own checks (probe_handshakes) are taken off hellos and handshakes; the agent flushes those every 10 minutes and the probe's connects at once, so the window's edges may be off by a check or two, and the difference stops at zero.
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) NodeRuntimeInbounds ¶
NodeRuntimeInbounds lists the inbounds of one node, or of every node that is not retired when nodeID is empty, ordered by node and id. No pin, address or credential is read.
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) NodeShares ¶
NodeShares reads how every node is handed out, in one query.
func (*Store) NodeTraces ¶
func (s *Store) NodeTraces(ctx context.Context, fromID, toID string, limit int) ([]NodeTraceRow, error)
NodeTraces returns the traces of a pair, newest first, at most limit (0 = NodeTraceKeep).
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) NodesWithRelayLinks ¶ added in v0.1.65
NodesWithRelayLinks reads the non-retired nodes and the enabled relays in one batch: one D1 call, whatever the relay count.
func (*Store) NoteSpeedTest ¶
NoteSpeedTest records that the node ran a speed measurement that ended about now, and forgets the ones older than the longest window a capacity report reads.
func (*Store) ObserveOwnProbeNetwork ¶
func (s *Store) ObserveOwnProbeNetwork(ctx context.Context, id string, secretHash []byte, asn uint32, operator, version string, now time.Time) (OwnProbe, error)
ObserveOwnProbeNetwork records only the derived ASN and operator, and the version the probe reported (empty keeps the last one). The first request from an operator other than the pinned one moves an active probe to network_changed and clears its job; a probe in that state stays there, whatever network it comes from next, until the owner confirms (ConfirmOwnProbeNetwork).
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.
An alert an admin closed (resolution "dismissed") stays closed while its condition continues: when the latest dismissed row of the key was last seen within reopenWithin, at the same or a higher severity than a, and no alert of the key is active, only that row's last_seen moves and it is returned still resolved (the caller must not notify). A gap longer than reopenWithin, or a higher severity, opens a new alert; a dismissed row is never re-opened in place.
func (*Store) OpenClientDebug ¶
func (s *Store) OpenClientDebug(ctx context.Context, deviceID string, now time.Time) (ClientDebugRow, bool, error)
OpenClientDebug is the device's open request that has not run out at now.
func (*Store) OsJobEvents ¶
func (s *Store) OsJobEvents(ctx context.Context, nodeID, jobID string, since time.Time) ([]EventRow, error)
OsJobEvents returns, oldest first, the events an agent raised for one OS job (os_update_started, os_reboot_started, os_update_done, os_update_failed). They are the reliable record of how a job ended: the status snapshot is sent once and may be lost. An agent can raise one more than once; the caller reads them by job id and takes the first end it finds.
func (*Store) OsRebootsSince ¶
func (s *Store) OsRebootsSince(ctx context.Context, since time.Time) (map[string][]time.Time, error)
OsRebootsSince lists, per node, when the panel's OS jobs rebooted it (os_step.reboot_at) at or after since, oldest first. A step that never reached its reboot has no such time.
func (*Store) OsRolloutSteps ¶
OsRolloutSteps lists the steps of an OS rollout by stage, then node name.
func (*Store) OsStatuses ¶
OsStatuses returns the latest snapshot for every node. An empty map means none have reported yet.
func (*Store) OwnProbeBySecretHash ¶
OwnProbeBySecretHash authenticates a probe without reading or retaining its source address.
func (*Store) PanelBackupSettings ¶
func (s *Store) PanelBackupSettings(ctx context.Context) (PanelBackupSettings, error)
func (*Store) PanelDecoySource ¶
PanelDecoySource reads the panel's own site setting: "builtin", "dir", "site:<id>", or "" when it was never set.
func (*Store) PanelSSHKey ¶ added in v0.1.74
func (s *Store) PanelSSHKey(ctx context.Context) (PanelSSHKey, error)
PanelSSHKey returns the panel's SSH key record, or ErrNotFound before its first use.
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) PathProbes ¶
func (s *Store) PathProbes(ctx context.Context, since time.Time, nodeID string, limit int) ([]PathProbeRow, error)
PathProbes returns the probes since a time, newest first, at most limit (0 = 50). A node is matched as sender or target when nodeID is not empty.
func (*Store) PathSpeedStartUsage ¶
func (s *Store) PathSpeedStartUsage(ctx context.Context, actorID, fromID, toID string, since time.Time) (PathSpeedStartUsage, error)
PathSpeedStartUsage returns reservations after since for actorID and either node. The starts are ordered oldest first so the caller can calculate when a limit expires.
func (*Store) PathSpeeds ¶
func (s *Store) PathSpeeds(ctx context.Context, since time.Time, nodeID string, limit int) ([]PathSpeedRow, error)
PathSpeeds returns the tests since a time, newest first, at most limit (0 = 50). A node is matched as sender or target when nodeID is not empty.
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) ProbePackets ¶ added in v0.1.61
ProbePackets is, per inbound, the packets its node sent to the panel's health check and declared lost (probe_pkts_sent and probe_pkts_lost) over the hour buckets that touch [since, now]. Agents flush them every 10 minutes, so the newest are missing for up to that long. Inbounds without any are left out.
func (*Store) PruneAudit ¶
PruneAudit deletes a bounded number of audit rows per sweep so a large backlog cannot use the whole D1 budget. The audit_ts index serves each batch scan. Rows left after the last batch are removed on a later sweep.
func (*Store) PruneBlocklistChecks ¶ added in v0.1.41
PruneBlocklistChecks deletes the checks older than the cut and returns how many went.
func (*Store) PruneClientDebug ¶
PruneClientDebug deletes the rows requested before the cut, those whose person or device is gone, and the lines of all of them (lines are only ever written and deleted together with their row, in one batch, so none is left behind: the sweep does not scan the line table for strays). It returns how many rows went.
func (*Store) PruneClientProbeReports ¶ added in v0.1.51
PruneClientProbeReports deletes the rows 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, whatever their family, and returns how many went.
func (*Store) PruneDebugCaptures ¶
PruneDebugCaptures deletes the captures that started before the cut, and their lines.
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) PruneExtChecks ¶ added in v0.1.63
PruneExtChecks deletes rows older than the cut and returns how many went.
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) PruneLinkHours ¶ added in v0.1.53
PruneLinkHours deletes the hour buckets that end before the cut (the bucket holding the cut stays whole) and returns how many rows went.
func (*Store) PruneNetworkHours ¶
PruneNetworkHours deletes expired aggregate buckets using their hour index.
func (*Store) PruneNodeHostHours ¶
PruneNodeHostHours drops up to one batch of hour rows older than the cut (the hour bucket that touches the cut stays). Rows left after this batch are removed on a later sweep.
func (*Store) PruneNodeJournal ¶ added in v0.1.55
PruneNodeJournal keeps the whole hour bucket that touches the seven-day cut.
func (*Store) PruneNodeTrafficHours ¶
PruneNodeTrafficHours drops the per-node hourly traffic older than the cut (node_traffic_hour_hour serves the scan).
func (*Store) PruneOsRollouts ¶
PruneOsRollouts deletes finished OS rollouts (their steps go with them) older than cutoff that are not among the newest keep finished ones. An active rollout is never touched.
func (*Store) PrunePathProbes ¶
PrunePathProbes deletes the probes older than before.
func (*Store) PrunePathSpeedStarts ¶
PrunePathSpeedStarts deletes reservations older than the rolling daily window.
func (*Store) PrunePathSpeeds ¶
PrunePathSpeeds deletes the tests older than before.
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) PruneScheduledTaskRuns ¶
PruneScheduledTaskRuns keeps the last ScheduledRunsKept runs of a task and none older than cutoff (a running one stays), drops the runs of tasks that are gone, and bounds the conversation of an assistant task the same way: its messages older than cutoff and beyond the newest two per kept run go, with the plan cards older than cutoff. It returns the runs deleted.
func (*Store) PruneTSPUChecks ¶ added in v0.1.42
PruneTSPUChecks deletes the rows older than the cut and returns how many went.
func (*Store) PruneTrafficBuckets ¶
PruneTrafficBuckets drops the per-person hourly traffic older than the cut (traffic_bucket_hour, migration 00106, serves the scan).
func (*Store) PruneUserNetworks ¶
PruneUserNetworks deletes recent-network rows that have not been updated within retention.
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 expired rows, keeps separate budgets for anonymous and session-bound ceremonies, and evicts the oldest login ceremony when that class reaches its total budget. Setup ceremonies require a setup token, so anonymous login churn cannot evict them.
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) PutOsStatus ¶
func (s *Store) PutOsStatus(ctx context.Context, nodeID, statusJSON string, measuredAt, receivedAt time.Time) error
PutOsStatus replaces the node's latest snapshot. The caller validates the wire values before storage.
func (*Store) PutPortChecks ¶ added in v0.1.28
PutPortChecks replaces the latest conclusive results in one atomic multi-row statement.
func (*Store) PutPortChecksAndUDPPathLosses ¶ added in v0.1.73
func (s *Store) PutPortChecksAndUDPPathLosses(ctx context.Context, checks []PortCheck, targetID string, checkedSenders []string, losses []UDPPathLoss) error
PutPortChecksAndUDPPathLosses saves the node verdicts and their path attribution as one atomic batch.
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) ReceiveClientDebug ¶
func (s *Store) ReceiveClientDebug(ctx context.Context, in ClientDebugIntake) (row ClientDebugRow, replay bool, err error)
ReceiveClientDebug stores a bundle in one batch: the lines, the counters, the state, and the drop of the device's bundles beyond ClientDebugPerDevice (the oldest, with their lines). With RequestID the bundle answers that open request of the device; if it is answered already (by this bundle, a moment before) the stored row comes back with replay true and nothing is written; any other state is ErrClientDebugNoRequest. Without one it is a bundle the person sent on their own: refused with a *ClientDebugRateError within ClientDebugUnaskedEvery of the device's last, and with ErrClientDebugFull past ClientDebugMaxBundles or ClientDebugMaxBytes; it pushes out only the person's own unasked bundles beyond ClientDebugPerDevice.
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, family, perNode int, nodeIDs ...string) ([]CountryCheck, error)
RecentCountryChecks reads up to perNode newest rounds of one address family (4 or 6) of every node (or of the given nodes), newest first inside a node.
func (*Store) RecentExtCheckTimes ¶ added in v0.1.63
RecentExtCheckTimes reads only the newest result time for every node and source, optionally limited to sources.
func (*Store) RecentExtChecks ¶ added in v0.1.63
func (s *Store) RecentExtChecks(ctx context.Context, perNodeSource int, sources ...string) ([]ExtCheck, error)
RecentExtChecks reads up to perNodeSource newest rows of every node and source, optionally limited to sources.
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) ReconcileAssistantBudget ¶
func (s *Store) ReconcileAssistantBudget(ctx context.Context, id, month, adminID string, provider int32, input, output int64, amount float64, turn bool, now time.Time) error
ReconcileAssistantBudget records one call's usage even when cleanup removed its reservation while the provider was still running. The settled row is the idempotency marker that prevents a repeated reconciliation from adding usage twice.
func (*Store) RecordDeviceLimitReached ¶ added in v0.1.27
func (s *Store) RecordDeviceLimitReached(ctx context.Context, userID string, used, limit int, mode string, refused, wasIdle 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) RecordIPv6Check ¶ added in v0.1.66
RecordIPv6Check keeps a check as the newest of its address. It never changes the entry.
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) RecordNodeApplyMeta ¶
func (s *Store) RecordNodeApplyMeta(ctx context.Context, nodeID, status string, durationMS uint32, drift bool, now time.Time) error
RecordNodeApplyMeta stores NodeApplyMetaStmt. The node must exist.
func (*Store) RecordPanelBackupRun ¶
func (*Store) RecordStepProgress ¶
func (s *Store) RecordStepProgress(ctx context.Context, nodeID, requestID, phase string, rank int, downloaded, total, speed uint64, updatedUnix int64, progressError, source string) (bool, error)
RecordStepProgress atomically advances the progress of a currently SENT update step. The rank and byte conditions make delayed frames harmless even when they arrive through different edge isolates.
func (*Store) RecoverAssistantFollowUps ¶
RecoverAssistantFollowUps gives back the follow-ups a stopped panel left running: they run again (attempts says how often that happened). It runs once when the scheduler starts, before any run of its own.
func (*Store) RecoverScheduledRuns ¶
RecoverScheduledRuns ends the runs a stopped panel left behind: they read as failed ("interrupted"), and every lease is given back. It runs once when the scheduler starts, before any run of its own; an interruption is not counted as a failure.
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) RelayLink ¶ added in v0.1.65
RelayLink returns one relay with both ends, or ErrNotFound.
func (*Store) RelayLinks ¶ added in v0.1.65
RelayLinks lists the relays the filter selects with both ends, oldest first.
func (*Store) RelayTodayBytesByNode ¶
func (s *Store) RelayTodayBytesByNode(ctx context.Context, dayStart int64) (map[string]uint64, error)
RelayTodayBytesByNode sums the persisted daily forward increments of each entry's relays for one UTC day boundary. A relay deleted during the day takes its share with it: the day total lives in the relay row.
func (*Store) RelaysApplied ¶ added in v0.1.65
func (s *Store) RelaysApplied(ctx context.Context, nodeID string, rs []RelayApplied, now time.Time) error
RelaysApplied stores what the entry node reported for its forwards: ok -> active, else failed with the error. Only relays of this node that are switched on (a result for a relay switched off meanwhile is stale).
func (*Store) ReleaseApply ¶
ReleaseApply returns an apply refused before side effects to its previous open state (planned or approved). This is a compare-and-swap from applying, leaves expires_at untouched, and clears applied_at because no apply remains active. The prior status must match needs_approval; a plan in any other state returns *PlanStateError.
func (*Store) ReleaseAssistantTurn ¶
func (*Store) ReleaseLease ¶ added in v0.1.48
ReleaseLease deletes name only if holder still owns it.
func (*Store) ReleaseLoginFailure ¶
ReleaseLoginFailure removes one reserved attempt without clearing earlier failures and clears a lock when the remaining failure count drops below the limit.
func (*Store) ReleaseRecoveryToken ¶
ReleaseRecoveryToken gives back a token ConsumeRecoveryToken spent at usedAt, for a reset that failed after it: the person who holds the link has not got a new login yet. It touches only a token spent at exactly that time.
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) ReopenDismissedAlert ¶
func (s *Store) ReopenDismissedAlert(ctx context.Context, id string, now time.Time) (HealthAlert, error)
ReopenDismissedAlert undoes DismissAlert: the alert becomes active again. ErrNotFound when it does not exist, ErrConflict when it was not closed by an admin or another alert of the same key is active by now.
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) RequestAssistantStop ¶
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) ReserveAssistantBudget ¶
func (s *Store) ReserveAssistantBudget(ctx context.Context, id, month, adminID string, provider int32, model string, estimate, budget float64, now, reservationCutoff time.Time) (bool, error)
ReserveAssistantBudget performs the budget check and reservation as one guarded statement. Pending reservations and settled usage for the same provider/month are both included, so concurrent calls cannot spend the same headroom.
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) RetainAssistantConversations ¶
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) RevertDecoySite ¶
func (s *Store) RevertDecoySite(ctx context.Context, now time.Time, id string, seq int, by string) (site DecoySiteRow, nodeIDs []string, changed bool, err error)
RevertDecoySite saves an earlier version again as the newest one.
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) RevokeAssistantToken ¶
RevokeAssistantToken revokes a hidden assistant identity and cancels its pending MCP plans in one batch.
func (*Store) RevokeOrphanPathCreds ¶
RevokeOrphanPathCreds quarantines path peers whose path is gone: the relay through the entry node was deleted, or no inbound of the profile has an IPv6 entry any more.
func (*Store) RevokeOwnProbe ¶
RevokeOwnProbe invalidates both credentials and clears any job immediately.
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). Percentiles are nearest-rank over the rounds that measured the value (status != failed and the value > 0); jitter is the population standard deviation of response_ms over the same kind of rounds.
func (*Store) SamplesSince ¶
SamplesSince returns every stored round at or after since, oldest first, per inbound.
func (*Store) SaveAssistantSettings ¶
func (s *Store) SaveAssistantSettings(ctx context.Context, choices []AssistantProviderChoice, enabled bool, provider, effort, audience, fallback int32, notesEnc []byte, retention uint32, now time.Time) error
SaveAssistantSettings applies the provider choices and shared settings as one database batch on both store backends.
func (*Store) SaveNetworkMode ¶
SaveNetworkMode changes the setting and removes data made obsolete by the change in one write batch.
func (*Store) SaveOsStep ¶
SaveOsStep overwrites the mutable fields of a step. A row read by OsRolloutSteps is a compare-and-set on its state.
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) ScheduledTask ¶
ScheduledTask reads one task; ErrNotFound when there is none.
func (*Store) ScheduledTaskAlerts ¶
func (s *Store) ScheduledTaskAlerts(ctx context.Context) ([]ScheduledTask, error)
ScheduledTaskAlerts lists the enabled tasks that hold an alert condition: a problem, or ScheduledFailingStreak failures in a row. It is what the health evaluator reads on every pass (the due index keeps it cheap).
func (*Store) ScheduledTaskRun ¶
ScheduledTaskRun reads one run; ErrNotFound when there is none.
func (*Store) ScheduledTaskRuns ¶
func (s *Store) ScheduledTaskRuns(ctx context.Context, taskID string, limit int) ([]ScheduledTaskRun, error)
ScheduledTaskRuns lists a task's runs, newest first.
func (*Store) ScheduledTasks ¶
func (s *Store) ScheduledTasks(ctx context.Context) ([]ScheduledTask, error)
ScheduledTasks lists every task, oldest first.
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) SetAPITokenBulk ¶
func (s *Store) SetAPITokenBulk(ctx context.Context, id string, allow bool, now time.Time) (APIToken, error)
SetAPITokenBulk changes whether a live API token may change more than the ordinary fixed one-hour user budget.
func (*Store) SetAndDeleteSettings ¶
func (s *Store) SetAndDeleteSettings(ctx context.Context, kv map[string]string, keys ...string) error
SetAndDeleteSettings applies setting upserts and deletes in one atomic batch.
func (*Store) SetAssistantConversationUnread ¶
func (s *Store) SetAssistantConversationUnread(ctx context.Context, adminID, conversationID string, unread bool) error
SetAssistantConversationUnread marks a conversation read (opened) or unread (a follow-up answered in it).
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) SetDecoySiteReady ¶
func (s *Store) SetDecoySiteReady(ctx context.Context, now time.Time, id string, ready bool, by string) (DecoySiteRow, error)
SetDecoySiteReady marks a draft ready, or puts a site that stands nowhere back to a draft.
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) SetNodeBridgePort ¶
SetNodeBridgePort sets the TCP port of the node's site that the bridge arrives at (0 = 443 on the node's own site). ErrNotFound when the node is gone or retired.
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) SetNodeServerPanelKey ¶ added in v0.1.74
SetNodeServerPanelKey records a panel key only for a non-retired node with saved SSH access.
func (*Store) SetNodeServerPasswordLogin ¶ added in v0.1.74
func (s *Store) SetNodeServerPasswordLogin(ctx context.Context, nodeID string, succeeded bool) error
SetNodeServerPasswordLogin records whether the last explicit password proof succeeded for a live node.
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) SetOsRolloutStatus ¶
func (s *Store) SetOsRolloutStatus(ctx context.Context, id string, from []string, status, pauseKey string, params map[string]string, finished time.Time) (bool, error)
SetOsRolloutStatus moves a rollout to status only while it is in one of from (a compare-and-set). pauseKey and params describe a pause and are cleared by any other status. It reports whether the row changed.
func (*Store) SetOwnProbeJob ¶
SetOwnProbeJob replaces the outstanding target list. Addresses are trusted only because this list was built by the panel.
func (*Store) SetPanelDecoySource ¶
SetPanelDecoySource stores "builtin" or "dir", or "site:<id>" for a ready site.
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) SetRelayActiveMode ¶
func (s *Store) SetRelayActiveMode(ctx context.Context, id, active, reason string, now time.Time) error
SetRelayActiveMode records the way a relay stands in now and why (relay.proto Relay.mode_reason). The change time moves only when the way changes, so a repeated call with the same way and another reason keeps the time. ErrNotFound when the relay is gone.
func (*Store) SetRelayBridge ¶
SetRelayBridge stores the bridge report of a relay in check_json.bridge; nil removes it. ErrNotFound when the relay is gone.
func (*Store) SetRelayBridgePool ¶
SetRelayBridgePool stores the pool the panel asks of the exit for this relay (check_json.bridge.pool) and when the reason for it last held. D1 binds a number as REAL, so both are cast back to integers in SQL. ErrNotFound when the relay is gone.
func (*Store) SetRelayBridgeSide ¶
func (s *Store) SetRelayBridgeSide(ctx context.Context, id, side string, report *RelayBridgeSideCheck) error
SetRelayBridgeSide updates one agent's report without replacing the other side or the bridge check stage.
func (*Store) SetRelayCheck ¶ added in v0.1.65
SetRelayCheck stores the check of a relay. ErrNotFound when the relay is gone.
func (*Store) SetRelayCounters ¶ added in v0.1.65
func (s *Store) SetRelayCounters(ctx context.Context, nodeID string, updates []RelayCounterUpdate) error
SetRelayCounters updates the counter member for relays owned by nodeID. Reports from an older or switched-off forward cannot update another entry's relay or make a disabled relay appear to be carrying current traffic.
func (*Store) SetRelayDirectState ¶
SetRelayDirectState stores the streak and the timestamp of its latest sample. D1 returns JSON numbers as REAL, so both values are cast back to integers in SQL.
func (*Store) SetRelayDirectStreak ¶
SetRelayDirectStreak stores the count of good direct checks in check_json.direct_streak (0 removes it). ErrNotFound when the relay is gone.
func (*Store) SetRelayMonitorCheck ¶ added in v0.1.65
SetRelayMonitorCheck updates only check_json.monitor, leaving the leg/path check and counters intact.
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) SetScheduledTaskConversation ¶
SetScheduledTaskConversation remembers the conversation an assistant task writes into.
func (*Store) SetScheduledTaskNext ¶
SetScheduledTaskNext moves a task's next run (a start that found it overdue, a schedule that changed with the time zone).
func (*Store) SetSettingAndScheduledTaskNexts ¶
func (s *Store) SetSettingAndScheduledTaskNexts(ctx context.Context, key, value string, nexts []ScheduledTaskNext) error
SetSettingAndScheduledTaskNexts changes a setting and enabled tasks' next runs in one batch.
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 and pending link code is deleted with it (chat ids belong to a bot); dropped says how many links went.
func (*Store) SetTelegramEnabled ¶ added in v0.1.23
SetTelegramEnabled switches the admin's alerts; ErrNotFound when the admin has no chat.
func (*Store) SetTelegramLinkCode ¶ added in v0.1.50
func (s *Store) SetTelegramLinkCode(ctx context.Context, hash, adminID string, expires time.Time) error
SetTelegramLinkCode stores a one-time chat-link code by hash. There is at most one pending code for an admin.
func (*Store) SetUDPFilteredAt ¶ added in v0.1.77
SetUDPFilteredAt records or clears the latest paired source-filtered finding.
func (*Store) SetUDPFilteredCheckedAt ¶ added in v0.1.77
SetUDPFilteredCheckedAt records a periodic recheck attempt, including attempts that could not find a sender.
func (*Store) SetUDPFilteredState ¶ added in v0.1.77
func (s *Store) SetUDPFilteredState(ctx context.Context, nodeID string, at time.Time, senderID string) error
SetUDPFilteredState stores the timestamp and a sender for daily retries. Clearing the timestamp clears the sender too.
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) SetWarpReach ¶
SetWarpReach stores the node's latest WARP reach result (JSON, "" is not allowed). The account's updated_at is not touched: a result is not a change of the account. ErrNotFound when the node has no 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) SkipPendingOsSteps ¶
func (s *Store) SkipPendingOsSteps(ctx context.Context, rolloutID, errorKey string, now time.Time) error
SkipPendingOsSteps turns every PENDING step of a rollout into SKIPPED with errorKey (cancel).
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) SpeedTestTimes ¶
func (s *Store) SpeedTestTimes(ctx context.Context, nodeID string, since time.Time) ([]int64, error)
SpeedTestTimes is when the node's speed measurements ended since the given time, oldest first.
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) TakeAssistantRate ¶
func (s *Store) TakeAssistantRate(ctx context.Context, adminID string, minute int64, limit int) (bool, error)
TakeAssistantRate admits one turn in the current minute, with the counter shared by D1 isolates.
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) TakeTelegramLinkCode ¶ added in v0.1.50
func (s *Store) TakeTelegramLinkCode(ctx context.Context, hash string, now time.Time) (string, error)
TakeTelegramLinkCode atomically consumes a code before it expires. DELETE ... RETURNING makes concurrent polls single use.
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. The counter never goes down: two sign-ins that finish out of order must not leave the older count behind (it is what a cloned authenticator is caught by).
func (*Store) TouchSession ¶
TouchSession bumps last_seen_at.
func (*Store) UDPFilteredAt ¶ added in v0.1.77
UDPFilteredAt reads the last time a paired check found source-side filtering; zero means no finding is stored.
func (*Store) UDPFilteredNodes ¶ added in v0.1.77
func (s *Store) UDPFilteredNodes(ctx context.Context) ([]UDPFilteredState, error)
UDPFilteredNodes returns the nodes with a stored source-filtered finding.
func (*Store) UDPFilteredSender ¶ added in v0.1.77
UDPFilteredSender returns the sender that first participated in the paired finding, so later checks can reuse it.
func (*Store) UDPPathLosses ¶ added in v0.1.73
UDPPathLosses reads path-loss rows newer than since, with node names and countries for alerts and events.
func (*Store) UnacceptDoctor ¶
UnacceptDoctor removes an acceptance; false when there was none.
func (*Store) UnassignDecoySite ¶
func (s *Store) UnassignDecoySite(ctx context.Context, id string, nodeIDs []string, mode string) ([]NodeRow, error)
UnassignDecoySite takes a site off nodes that serve it; they go to mode (builtin or panel) and forget the site.
func (*Store) UnlinkTelegram ¶ added in v0.1.23
UnlinkTelegram forgets the admin's chat; it reports whether there was one.
func (*Store) UnreadAssistantConversations ¶
func (s *Store) UnreadAssistantConversations(ctx context.Context, adminID string) (int, time.Time, error)
UnreadAssistantConversations counts an admin's conversations a follow-up answered since they last opened them, and gives the time of their next follow-up (zero: none).
func (*Store) UpdateAssistantMemory ¶
func (*Store) UpdateDecoySite ¶
func (s *Store) UpdateDecoySite(ctx context.Context, now time.Time, id, name, note, by string) (DecoySiteRow, error)
UpdateDecoySite renames a site and changes its note.
func (*Store) UpdateIPv6 ¶ added in v0.1.66
func (s *Store) UpdateIPv6(ctx context.Context, nodeID string, fn func(cur IPv6Row) (IPv6Row, error)) (next IPv6Row, changed bool, err error)
UpdateIPv6 changes a node's IPv6 entry and document atomically: fn gets the current pair and returns the next one (or an error, which is returned as it is and writes nothing). The write is a compare-and-swap on both columns; when another writer got in between, fn runs again on what it left, so a decision is never made on a stale read. changed is false when fn returned the pair it was given. ErrNotFound for a missing or retired node, ErrConflict if it keeps losing.
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) UpdateRelay ¶ added in v0.1.65
UpdateRelay applies the patch. A change of the switch or the port puts the relay back to pending (the agent has not reported on the new forward yet). ErrNotFound, ErrRelayPortTaken.
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) UpdateScheduledTask ¶
func (s *Store) UpdateScheduledTask(ctx context.Context, t ScheduledTask) error
UpdateScheduledTask replaces a task's definition and its next run. A new definition starts with a clean state: the failure count and the problem of the old one go (the alerts they held close), and the next run tells again. A run in progress keeps its lease. ErrNotFound is returned for an unknown id; ErrConflict is returned when the caller's version is stale.
func (*Store) UpdateUDPPathLosses ¶ added in v0.1.73
func (s *Store) UpdateUDPPathLosses(ctx context.Context, targetID string, checkedSenders []string, losses []UDPPathLoss) error
UpdateUDPPathLosses replaces the result for senders in a completed two-node check of targetID. Senders present in losses are upserted; senders that ran but had no path loss have their old row removed.
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) UserHelloKex ¶
func (s *Store) UserHelloKex(ctx context.Context, userID string, since time.Time) ([]HelloKexDevice, error)
UserHelloKex is one person's devices with ClientHello counts over the window, by device id.
func (*Store) UserLinks ¶ added in v0.1.53
UserLinks reads a person's counters over the hour buckets that touch [since, now], per device, node and inbound, the ones with a counter only; device, then node name, then profile name. The device comes from the credential; an inbound or node that no longer exists has no row.
func (*Store) UserLinksByHour ¶ added in v0.1.56
func (s *Store) UserLinksByHour(ctx context.Context, userID string, since time.Time, byHour bool) ([]UserLink, error)
UserLinksByHour reads one person's rows and optional hour buckets, with device metadata from the same query.
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
// TelegramCred is the credential of the person's Telegram key (zero ID: they hold none). It is read for the links of the
// person's page, never for a request's device.
TelegramCred AccessCred
// TrustTunnelCred is the credential of the person's tt:// key, never of a link device.
TrustTunnelCred 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
// Relays are the relays that are switched on, with both ends (a person's twin servers follow them, access.relayUsable); read
// for an active user only.
Relays []RelayLink
// 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) IdleCount ¶
func (d SubscriptionData) IdleCount() int
IdleCount is the number of currently idle devices that would otherwise fill the device limit.
func (SubscriptionData) LimitCount ¶ added in v0.1.69
func (d SubscriptionData) LimitCount() int
LimitCount is how many of the person's devices fill the device limit: all of them but the Telegram key.
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 when a new or returning idle device cannot reclaim a place). nil means the store must make or refresh the device. It is the first half of linkDeviceState.birth on the data SubscriptionData read, so a refused request costs no additional reads.
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 TelegramKeyAdd ¶ added in v0.1.69
type TelegramKeyAdd struct {
Device AccessDevice // ID, UserID, Platform, Model, Client; the store sets the kind and CreatedAt
Cred AccessCred // ID, Protocol, SecretEnc, DataJSON; the store sets the owner, the device and CreatedAt
}
TelegramKeyAdd describes a new Telegram key.
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 TrustTunnelKeyAdd ¶
type TrustTunnelKeyAdd struct {
Device AccessDevice
Cred AccessCred
Limit int
}
TrustTunnelKeyAdd describes a single key device and its credential.
type UDPFilteredState ¶ added in v0.1.77
UDPFilteredState is a node whose latest paired port check found the source-filtered pattern.
type UDPPathLoss ¶ added in v0.1.73
type UDPPathLoss struct {
SenderID, TargetID, Ports string
Sent, Got uint32
OtherSenderID string
OtherGot uint32
CheckedAt time.Time
SenderName, SenderCountry string
TargetName string
OtherSenderName string
OtherSenderCountry string
// OpenPorts are the ports the sender delivered whole in the same run, set only when it got nothing at all through on
// the lost ones: a filter on the path (a hoster letting only UDP 443 in, say), not a lossy line.
OpenPorts string
}
UDPPathLoss is a persistent comparison between a sender whose packets were lost and one that delivered them.
type UserLink ¶ added in v0.1.53
type UserLink struct {
DeviceID, NodeID, NodeName, InboundID, ProfileName, Protocol string
PathKey, ViaNodeID, ViaCountry string
Platform, Client, Kind string
Connects, Rejects, Drops, Stalls, OnlineS uint64
ClientCloses, Freezes, Quiet, Accepted, HellosForeign uint64
RttMSSum, RttSamples, PktsSent, PktsLost uint64
LastHour time.Time
Hours []LinkHourSums
LinkReasons
// What decides which links/3 counters the row can have (connectiondiag.Variant): the VLESS security, transport and CDN host
// as a small JSON object ("" for other protocols), and the AmneziaWG backend of the inbound's last report ("" = none).
Variant, AwgBackend string
}
UserLink is the counters of one device of a person on one inbound of a node over a window. LastHour is the start of the newest hour with a counter.
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
ReachJSON string // the latest WARP reach result (migration 00144); "" = never
ReachAt time.Time
CreatedAt, UpdatedAt time.Time
}
WarpAccountRow is one warp_account row.
type WarpReachItem ¶
WarpReachItem is one site's answer of a WARP reach run (agent.proto "WARP REACH"): the verdict (ok, blocked, unreachable or error), the HTTP status of the page it is about (0 = none) and the time the request took.
Source Files
¶
- access.go
- access_awg.go
- access_linkdevice.go
- access_linkmode.go
- access_profile.go
- access_telegram.go
- access_trusttunnel.go
- access_user.go
- admin.go
- assistant.go
- assistant_follow_up.go
- audit_reqid.go
- authceremony.go
- authpw.go
- awg_prepare.go
- backup.go
- batch.go
- batch_native.go
- capability.go
- client_api.go
- client_compat.go
- client_debug.go
- client_probe_report.go
- connection_links.go
- country_blocklist_check.go
- country_check.go
- country_ext_check.go
- country_tspu_check.go
- debug_capture.go
- decoy_site.go
- decoy_site_errors.go
- device_idle.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
- hello_kex.go
- ipv6.go
- ipv6_entry.go
- job_lease.go
- link_hour.go
- mcpplan.go
- network_hour.go
- node_decoy.go
- node_dns.go
- node_journal.go
- node_live.go
- node_runtime.go
- node_share.go
- node_speedtest.go
- open_sqlite.go
- os_rollout.go
- os_status.go
- own_probe.go
- path_probe.go
- path_speed.go
- port_check.go
- provision.go
- relay.go
- relay_check.go
- relay_controller.go
- relay_mode.go
- relay_reachability.go
- scheduled_task.go
- scheduled_task_timezone.go
- session.go
- store.go
- telegram.go
- text.go
- token.go
- traffic_params.go
- traffic_prune.go
- trusttunnel_protocol.go
- udp_path_loss.go
- update.go
- update_schedule.go
- warp.go
- warp_reach.go