Documentation
¶
Overview ¶
Package store owns the panel's SQLite database: one writer connection, a read pool, embedded goose migrations and the plain-SQL queries the other modules use.
Index ¶
- Constants
- Variables
- func AWGHwidHash(deviceID string) []byte
- func Clip(s string, n int) string
- func NewID(prefix string) string
- func RetainedKeyAAD(profileID, nodeID string) string
- func WithAuditSource(ctx context.Context, source string) context.Context
- type APIToken
- type AWGDeviceAdd
- type AWGImplicitWant
- type AWGIssue
- type Access
- func (a Access) AWGDevice(ctx context.Context, deviceID string) (AccessAWGDevice, error)
- func (a Access) 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) AddCreds(ctx context.Context, creds []AccessCred) error
- func (a Access) AddDevice(ctx context.Context, d AccessDevice, creds []AccessCred) error
- func (a Access) AddUsage(ctx context.Context, id string, bytes uint64) error
- func (a Access) BumpProfileEpoch(ctx context.Context, profileID string) error
- func (a Access) CreateGroup(ctx context.Context, g AccessGroup) error
- func (a Access) CreateInbound(ctx context.Context, i AccessInbound) error
- func (a Access) CreateProfile(ctx context.Context, p AccessProfile) error
- func (a Access) CreateUser(ctx context.Context, u AccessUser, dev AccessDevice, creds []AccessCred) error
- func (a Access) DailyTraffic(ctx context.Context, userID string, from time.Time) (map[int64]uint64, error)
- func (a Access) DeleteGroup(ctx context.Context, id, moveTo string) error
- func (a Access) DeleteInbound(ctx context.Context, id string, now time.Time, ...) error
- func (a Access) DeleteProfile(ctx context.Context, id string, now time.Time) error
- func (a Access) DeleteUsers(ctx context.Context, ids []string) (int, error)
- func (a Access) DesiredCreds(ctx context.Context, nodeID string) ([]AccessDesiredCred, error)
- func (a Access) DeviceCounts(ctx context.Context, ids []string) (map[string]int, error)
- func (a Access) DeviceCreds(ctx context.Context, deviceID string) ([]AccessCred, error)
- func (a Access) Devices(ctx context.Context, userID string) ([]AccessDevice, error)
- func (a Access) EnsureImplicitAWGCreds(ctx context.Context, userID string, dev AccessDevice, now time.Time, ...) (int, 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) ImplicitDevice(ctx context.Context, userID string) (AccessDevice, error)
- func (a Access) Inbound(ctx context.Context, id string) (AccessInbound, error)
- func (a Access) InboundsFull(ctx context.Context, nodeID string) ([]AccessInboundFull, error)
- func (a Access) InboundsOfNode(ctx context.Context, nodeID string) ([]AccessInbound, error)
- func (a Access) InboundsOfProfile(ctx context.Context, profileID string) ([]AccessInbound, error)
- func (a Access) ListUsers(ctx context.Context, q AccessUserQuery) ([]AccessUser, bool, AccessUserCounts, error)
- func (a Access) Node(ctx context.Context, id string) (AccessNode, error)
- func (a Access) NodeTraffic(ctx context.Context, userID string, since time.Time) ([]AccessNodeTraffic, error)
- func (a Access) Nodes(ctx context.Context) ([]AccessNode, error)
- func (a Access) Profile(ctx context.Context, id string) (AccessProfile, error)
- func (a Access) ProfileHasPeers(ctx context.Context, profileID string) (bool, error)
- func (a Access) ProfileLiveAWG(ctx context.Context, profileID string, limit int) (n int, users []string, err error)
- func (a Access) ProfileUsers(ctx context.Context, profileID string, happ, amnezia bool) ([]AccessBrief, error)
- func (a Access) Profiles(ctx context.Context) ([]AccessProfile, error)
- func (a Access) RenameDevice(ctx context.Context, deviceID, label string) error
- func (a Access) ResetUserPeriod(ctx context.Context, id string, periodStart time.Time, status string) error
- func (a Access) RetainedKey(ctx context.Context, profileID, nodeID string) (AccessRetainedKey, error)
- func (a Access) RevokeDevice(ctx context.Context, id string, now time.Time) (string, error)
- func (a Access) RotateAWGDevice(ctx context.Context, deviceID string, now time.Time, issue AWGIssue) (string, error)
- func (a Access) SetConfigEpoch(ctx context.Context, credID string, epoch int64) error
- func (a Access) SetInboundBuildError(ctx context.Context, id, msg string, now time.Time) error
- func (a Access) SetSubToken(ctx context.Context, id string, hash, enc []byte) error
- func (a Access) SetUserExpiry(ctx context.Context, id string, t time.Time) error
- func (a Access) SetUserStatus(ctx context.Context, id, status string) error
- func (a Access) SetUsersDisabled(ctx context.Context, ids []string, disabled bool) error
- func (a Access) TouchDevice(ctx context.Context, id string, now, not time.Time) error
- func (a Access) UpdateGroup(ctx context.Context, id string, name *string, profileIDs *[]string, ...) error
- func (a Access) UpdateInbound(ctx context.Context, i AccessInbound, resetState bool, now time.Time) error
- func (a Access) UpdateProfile(ctx context.Context, p AccessProfile, expectedVersion uint32, ...) (AccessProfile, error)
- func (a Access) UpdateUser(ctx context.Context, u AccessUser, setNodes bool) error
- func (a Access) User(ctx context.Context, id string) (AccessUser, error)
- func (a Access) UserByTokenHash(ctx context.Context, hash []byte) (AccessUser, error)
- func (a Access) UserStates(ctx context.Context, ids []string) ([]AccessUserState, error)
- func (a Access) UserUsage(ctx context.Context, userID string, since time.Time) (up, down uint64, err 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 AccessBrief
- type AccessCred
- type AccessDesiredCred
- type AccessDevice
- type AccessGroup
- type AccessInbound
- type AccessInboundFull
- type AccessLimitError
- type AccessNode
- type AccessNodeTraffic
- type AccessProfile
- type AccessRetainedKey
- type AccessUser
- type AccessUserCounts
- type AccessUserQuery
- type AccessUserState
- type Admin
- type AdminLogin
- type AuditEntry
- type AuditQuery
- type AuditRow
- type AwgPrepareRow
- type CARow
- type CertRow
- type CertState
- type CheckSample
- type CodeMatch
- 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) Exists(ctx context.Context, id string) (bool, error)
- func (d DNS) Get(ctx context.Context, id string) (DNSPreset, error)
- func (d DNS) List(ctx context.Context) ([]DNSPreset, error)
- func (d DNS) Lookup(ctx context.Context) (DNSLookup, error)
- func (d DNS) SetDefaultID(ctx context.Context, id string) 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) UserRefs(ctx context.Context, userID string) (own, group string, err error)
- type DNSLookup
- type DNSPreset
- type DailyRow
- type DoctorAccept
- type DoctorRow
- type EngineRow
- type EnrollResult
- type EventFilter
- type EventRow
- type FleetCredRef
- type FleetHourRow
- type FleetInboundRow
- type FleetSessionRef
- type FleetStatsIn
- type FleetStatsOut
- type FleetTop
- type FleetTraffic
- type GateRollback
- type HealthAlert
- type HelloInfo
- type InboundApplied
- type LastUpdateRow
- type LoginFailure
- type MCPPlan
- type NodeFactsRow
- type NodePatch
- type NodeProvisionEvent
- type NodeProvisionJob
- type NodeRow
- type NodeServerAccess
- type PanelBackupSettings
- type Passkey
- type PasswordCred
- type PlanStateError
- type ProbeCredIssue
- type ProbeCredRow
- type RolloutRow
- type Session
- type StepRow
- type Store
- func (s *Store) APITokenBySecretHash(ctx context.Context, h []byte) (APIToken, error)
- func (s *Store) AcceptDoctor(ctx context.Context, a DoctorAccept) (bool, error)
- func (s *Store) Access() Access
- func (s *Store) ActiveAlerts(ctx context.Context) ([]HealthAlert, error)
- func (s *Store) ActiveRollout(ctx context.Context) (RolloutRow, error)
- func (s *Store) AddPasskey(ctx context.Context, p Passkey, now time.Time) error
- func (s *Store) AddPassword(ctx context.Context, c PasswordCred, now time.Time) error
- func (s *Store) Admin(ctx context.Context, id string) (Admin, error)
- func (s *Store) AdminCount(ctx context.Context) (int, error)
- func (s *Store) AdminHasPassword(ctx context.Context, adminID string) (bool, error)
- func (s *Store) AdminLogins(ctx context.Context) ([]AdminLogin, error)
- func (s *Store) AdvanceTOTPStep(ctx context.Context, adminID string, step int64) (bool, error)
- func (s *Store) AlertCounts(ctx context.Context, now time.Time) (active, critical int, err error)
- func (s *Store) AlertHistory(ctx context.Context, since time.Time, nodeID string, limit int) ([]HealthAlert, error)
- func (s *Store) AnyPassword(ctx context.Context) (bool, error)
- func (s *Store) Audit(ctx context.Context, now time.Time, e AuditEntry) error
- func (s *Store) AwgPrepareFinish(ctx context.Context, nodeID string, ok bool, at int64, code, reason string) (switched bool, err error)
- func (s *Store) AwgPrepareStarted(ctx context.Context, nodeID string, since int64) error
- func (s *Store) BeginApply(ctx context.Context, id, tokenID, tool string, paramsHash, confirmHash []byte, ...) (MCPPlan, error)
- func (s *Store) CAs(ctx context.Context) ([]CARow, error)
- func (s *Store) CertStatus(ctx context.Context, serial string, now time.Time) (CertState, error)
- func (s *Store) CheckSetupToken(ctx context.Context, hash []byte, now time.Time) error
- func (s *Store) ClaimNodeProvisionJob(ctx context.Context, now time.Time) (NodeProvisionJob, bool, error)
- func (s *Store) ClearLoginFailures(ctx context.Context, login string) error
- func (s *Store) ClearPendingNodeServerPassword(ctx context.Context, nodeID string) error
- func (s *Store) Close() error
- func (s *Store) CommitPendingNodeServerPassword(ctx context.Context, nodeID string, encryptedCurrent []byte, now time.Time) error
- func (s *Store) CompleteNodeProvisionJob(ctx context.Context, id string, access NodeServerAccess, now time.Time) error
- func (s *Store) CreateAPIToken(ctx context.Context, t APIToken, secretHash []byte) error
- func (s *Store) CreateEnrollment(ctx context.Context, n *NodeRow, nodeID string, tokenHash []byte, ...) (NodeRow, error)
- func (s *Store) CreateFirstAdmin(ctx context.Context, tokenHash []byte, now time.Time, a Admin, p Passkey) error
- func (s *Store) CreateFirstAdminPassword(ctx context.Context, tokenHash []byte, now time.Time, a Admin, c PasswordCred) error
- func (s *Store) CreateMCPPlan(ctx context.Context, p MCPPlan, maxOpenPerToken, maxAwaiting int) error
- func (s *Store) CreateNodeProvisionJob(ctx context.Context, job NodeProvisionJob) error
- func (s *Store) CreatePasswordSession(ctx context.Context, sess Session, checked PasswordCred) error
- func (s *Store) CreateRollout(ctx context.Context, r RolloutRow, steps []StepRow) error
- func (s *Store) CreateSession(ctx context.Context, sess Session) error
- func (s *Store) CreateWarpAccount(ctx context.Context, a WarpAccountRow) error
- func (s *Store) DNS() DNS
- func (s *Store) DailyRows(ctx context.Context, inboundID string) ([]DailyRow, error)
- func (s *Store) DecideMCPPlan(ctx context.Context, id, adminID string, approve bool, now time.Time) (MCPPlan, error)
- func (s *Store) DeleteAdminSession(ctx context.Context, adminID string, tokenHash []byte) (bool, error)
- func (s *Store) DeleteOtherSessions(ctx context.Context, adminID string, keep []byte) (int, error)
- func (s *Store) DeletePasskey(ctx context.Context, adminID, id string) error
- func (s *Store) DeleteSession(ctx context.Context, tokenHash []byte) error
- func (s *Store) DeleteWarpAccount(ctx context.Context, nodeID string) error
- func (s *Store) DoctorAccepts(ctx context.Context, nodeID string) ([]DoctorAccept, error)
- func (s *Store) DoctorResults(ctx context.Context, nodeID string) ([]DoctorRow, error)
- func (s *Store) DropStaleAccepts(ctx context.Context, nodeID string) error
- func (s *Store) Enroll(ctx context.Context, tokenHash, keyHash []byte, now time.Time, ...) (EnrollResult, error)
- func (s *Store) Events(ctx context.Context, f EventFilter) (out []EventRow, hasMore bool, err error)
- func (s *Store) ExpireMCPPlans(ctx context.Context, now time.Time) (int, error)
- func (s *Store) FailWithheldInbounds(ctx context.Context, nodeID string, ids []string, reason string, now time.Time) error
- func (s *Store) FinishApply(ctx context.Context, id string, ok bool, ...) error
- func (s *Store) FinishCancelledNodeProvisionJob(ctx context.Context, id string, now time.Time) (bool, error)
- func (s *Store) FleetDeviceModels(ctx context.Context, ids []string) (map[string]string, error)
- func (s *Store) FleetEnabledInbounds(ctx context.Context) (map[string]map[string]string, error)
- func (s *Store) FleetHours(ctx context.Context, sinceHour int64) ([]FleetHourRow, error)
- func (s *Store) FleetInbound(ctx context.Context, inboundID string) (FleetInboundRow, error)
- func (s *Store) FleetInbounds(ctx context.Context, nodeID string, onlyEnabled bool) ([]FleetInboundRow, error)
- func (s *Store) FleetNodeProtocols(ctx context.Context) (map[string][]string, error)
- func (s *Store) FleetTopUsers(ctx context.Context, nodeID string, sinceHour int64, limit int) ([]FleetTop, error)
- func (s *Store) FleetUserNames(ctx context.Context, ids []string) (map[string]string, error)
- func (s *Store) GateRollbacks(ctx context.Context) (map[string]GateRollback, error)
- func (s *Store) GetAPIToken(ctx context.Context, id string) (APIToken, error)
- func (s *Store) GetMCPPlan(ctx context.Context, id string) (MCPPlan, error)
- func (s *Store) HealthAlert(ctx context.Context, id string) (HealthAlert, error)
- func (s *Store) IngestEvent(ctx context.Context, nodeID, instance string, seq uint64, now time.Time, ...) (dup bool, err error)
- func (s *Store) IngestStats(ctx context.Context, in FleetStatsIn) (FleetStatsOut, error)
- func (s *Store) InsertCA(ctx context.Context, c CARow, now time.Time) error
- func (s *Store) InsertEvent(ctx context.Context, e EventRow) error
- func (s *Store) InsertProbeCred(ctx context.Context, r ProbeCredRow, now time.Time) error
- func (s *Store) InsertProbeCredIdx(ctx context.Context, inboundID, profileID string, maxIdx int, now time.Time, ...) error
- func (s *Store) InsertResolvedAlert(ctx context.Context, a HealthAlert) error
- func (s *Store) InsertSample(ctx context.Context, c CheckSample) error
- func (s *Store) LastAuditByNode(ctx context.Context, action string) (map[string]time.Time, error)
- func (s *Store) LastNodeEventCode(ctx context.Context, nodeID string, codes ...string) (string, error)
- func (s *Store) LatestRollout(ctx context.Context) (RolloutRow, error)
- func (s *Store) ListAPITokens(ctx context.Context) ([]APIToken, error)
- func (s *Store) ListApprovals(ctx context.Context, now time.Time, awaitingOnly bool, historyLimit int) (rows []MCPPlan, awaiting int, err error)
- func (s *Store) ListAudit(ctx context.Context, source string, beforeID int64, limit int) ([]AuditRow, error)
- func (s *Store) ListAuditQuery(ctx context.Context, q AuditQuery) ([]AuditRow, error)
- func (s *Store) LoginFailures(ctx context.Context, login string, now time.Time, window time.Duration) (LoginFailure, error)
- func (s *Store) MCPPlanByConfirm(ctx context.Context, tokenID string, confirmHash []byte) (MCPPlan, error)
- func (s *Store) MuteAlert(ctx context.Context, id string, until time.Time) (HealthAlert, error)
- func (s *Store) Node(ctx context.Context, id string) (NodeRow, error)
- func (s *Store) NodeApplied(ctx context.Context, id string, rev uint64, hash string, in []InboundApplied, ...) error
- func (s *Store) NodeDesired(ctx context.Context, id string, rev uint64, hash string) error
- func (s *Store) NodeDisconnected(ctx context.Context, id string, 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, h HelloInfo, now time.Time) (prev NodeRow, ackedSeq uint64, err 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) NodeServerAccess(ctx context.Context, nodeID string) (NodeServerAccess, error)
- func (s *Store) NodeServerAccesses(ctx context.Context) ([]NodeServerAccess, error)
- func (s *Store) Nodes(ctx context.Context, includeRetired bool) ([]NodeRow, error)
- func (s *Store) OpenAlert(ctx context.Context, a HealthAlert, reopenWithin time.Duration, now time.Time) (out HealthAlert, reopened bool, err error)
- func (s *Store) PanelBackupSettings(ctx context.Context) (PanelBackupSettings, error)
- func (s *Store) PasskeyByCredentialID(ctx context.Context, credID []byte) (Passkey, error)
- func (s *Store) PasskeysByAdmin(ctx context.Context, adminID string) ([]Passkey, error)
- func (s *Store) PasswordByAdmin(ctx context.Context, adminID string) (PasswordCred, error)
- func (s *Store) PasswordByLogin(ctx context.Context, login string) (PasswordCred, error)
- func (s *Store) PendingEnrollmentExpiry(ctx context.Context, nodeID string, now time.Time) (time.Time, error)
- func (s *Store) ProbeCred(ctx context.Context, inboundID string) (ProbeCredRow, error)
- func (s *Store) PruneEvents(ctx context.Context, now time.Time, info, other time.Duration, batch int) (int64, error)
- func (s *Store) PruneHealth(ctx context.Context, now time.Time, samples, daily, alerts time.Duration) (int64, error)
- func (s *Store) PruneRollouts(ctx context.Context, keep int, cutoff time.Time) (int64, error)
- func (s *Store) PurgeSessions(ctx context.Context, now time.Time, idle time.Duration) error
- func (s *Store) PutDoctor(ctx context.Context, nodeID string, rows []DoctorRow, replace bool, ...) error
- func (s *Store) PutSetupToken(ctx context.Context, hash []byte, expires time.Time) error
- func (s *Store) RecentSamples(ctx context.Context, inboundID string, n int) ([]CheckSample, error)
- func (s *Store) RecordLoginFailure(ctx context.Context, login string, now time.Time, maxFailures int, ...) (LoginFailure, error)
- func (s *Store) RecordPanelBackupRun(ctx context.Context, now time.Time, succeeded bool, errorCode string) error
- func (s *Store) RenewCert(ctx context.Context, c CertRow, now time.Time, grace time.Duration) error
- func (s *Store) ReplaceWarpAccount(ctx context.Context, a WarpAccountRow) error
- func (s *Store) RequestCancelNodeProvisionJob(ctx context.Context, id string, now time.Time) (state string, changed bool, err error)
- func (s *Store) RequeueNodeProvisionJobs(ctx context.Context, now time.Time) error
- func (s *Store) ResetPasswordLogin(ctx context.Context, c PasswordCred, create bool, clearLocks []string, ...) (int, error)
- func (s *Store) ResolveAlert(ctx context.Context, id, resolution string, now time.Time) (bool, error)
- func (s *Store) RetireNode(ctx context.Context, id string, now time.Time) error
- func (s *Store) RevokeAPIToken(ctx context.Context, id, by string, now time.Time) (APIToken, error)
- func (s *Store) Rollout(ctx context.Context, id string) (RolloutRow, error)
- func (s *Store) RolloutSteps(ctx context.Context, rolloutID string) ([]StepRow, error)
- func (s *Store) RollupDaily(ctx context.Context, now time.Time) error
- func (s *Store) SamplesSince(ctx context.Context, since time.Time) ([]CheckSample, error)
- func (s *Store) SavePanelBackupSettings(ctx context.Context, v PanelBackupSettings, now time.Time) error
- func (s *Store) SaveStep(ctx context.Context, x StepRow) error
- func (s *Store) SessionStepUp(ctx context.Context, tokenHash []byte, now time.Time) error
- func (s *Store) SessionWithAdmin(ctx context.Context, tokenHash []byte) (Session, Admin, error)
- func (s *Store) SessionsByAdmin(ctx context.Context, adminID string) ([]Session, error)
- func (s *Store) SetAwgPrepare(ctx context.Context, nodeID string, r AwgPrepareRow) error
- func (s *Store) 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) SetPasswordHash(ctx context.Context, adminID, hash string) error
- func (s *Store) SetPendingNodeServerPassword(ctx context.Context, nodeID string, encrypted []byte, now time.Time) error
- func (s *Store) SetRolloutStatus(ctx context.Context, id string, from []string, status, pauseKey string, ...) (bool, error)
- func (s *Store) SetSettings(ctx context.Context, kv map[string]string) error
- func (s *Store) SetTOTPSecret(ctx context.Context, adminID string, sealed []byte, step int64) error
- func (s *Store) SetWarpAttention(ctx context.Context, nodeID, reason string, now time.Time) error
- func (s *Store) SetWarpEnabled(ctx context.Context, nodeID string, enabled bool, now time.Time) error
- func (s *Store) SetWarpHealth(ctx context.Context, nodeID, healthJSON string, at time.Time) error
- func (s *Store) Setting(ctx context.Context, key string) (string, error)
- func (s *Store) 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) TouchAPIToken(ctx context.Context, id string, now time.Time, ip, via string) error
- func (s *Store) TouchAlert(ctx context.Context, a HealthAlert, now time.Time) error
- func (s *Store) TouchPasskey(ctx context.Context, credID []byte, signCount uint32, flags byte, ...) error
- func (s *Store) TouchSession(ctx context.Context, tokenHash []byte, now time.Time) error
- func (s *Store) UnacceptDoctor(ctx context.Context, nodeID, checkID string) (bool, error)
- func (s *Store) UpdateNode(ctx context.Context, id string, p NodePatch) (NodeRow, error)
- func (s *Store) UpdateNodeProvisionJob(ctx context.Context, id, state, phase, errorCode string, secret []byte, ...) error
- func (s *Store) UpdateNodeProvisionJobWithEvent(ctx context.Context, id, state, phase, errorCode string, secret []byte, ...) error
- func (s *Store) UpdateRunningNodeProvisionJob(ctx context.Context, id, state, phase, errorCode string, secret []byte, ...) error
- func (s *Store) UpdateRunningNodeProvisionJobWithEvent(ctx context.Context, id, state, phase, errorCode string, secret []byte, ...) error
- func (s *Store) UpdateWarpRefresh(ctx context.Context, nodeID string, r WarpRefresh, now time.Time) error
- func (s *Store) WarpAccount(ctx context.Context, nodeID string) (WarpAccountRow, error)
- func (s *Store) WarpAccounts(ctx context.Context) ([]WarpAccountRow, error)
- type WarpAccountRow
- type WarpRefresh
Constants ¶
const ( RoleOwner = "owner" RoleHelper = "helper" RoleReadonly = "readonly" )
Roles stored in admin.role.
const ( AwgPrepareRunning = "running" AwgPrepareDone = "done" AwgPrepareFailed = "failed" )
States of AwgPrepareRow.State.
const ( DNSSourceUser = "user" DNSSourceGroup = "group" DNSSourceDefault = "default" )
DNS source names of the effective preset.
const ( PlanPlanned = "planned" PlanAwaiting = "awaiting" PlanApproved = "approved" PlanRejected = "rejected" PlanExpired = "expired" PlanApplying = "applying" PlanApplied = "applied" PlanFailed = "failed" PlanCancelled = "cancelled" )
Plan statuses, the values of mcp_plan.status.
const ( // PlanTTL is how long a plan (and, for a dangerous one, the owner's decision) stays valid. PlanTTL = 10 * time.Minute // ApplyStuckAfter is how long a plan may stay `applying` before the sweep gives up on it (a crash mid-call). ApplyStuckAfter = 5 * time.Minute // PlanKeep is how long finished plans stay before the sweep deletes them. PlanKeep = 30 * 24 * time.Hour )
const ( AuditPanel = "panel" AuditBot = "bot" AuditMCP = "mcp" AuditAPI = "api" )
Audit sources, the values of audit.source.
const ( ProfileReadonly = "readonly" ProfileOperator = "operator" ProfileAdmin = "admin" )
Token profiles, the values of api_token.profile. The auth package maps them to roles.
const ( RolloutRunning = "running" RolloutPaused = "paused" RolloutDone = "done" RolloutCancelled = "cancelled" RolloutFailed = "failed" StepPending = "pending" StepSent = "sent" StepGating = "gating" StepPassed = "passed" StepFailed = "failed" StepRolledBack = "rolled_back" StepSkipped = "skipped" )
Rollout and step states as stored (migration 00013).
const ( WarpRegistered = "registered" WarpImported = "imported" )
WARP account sources, the values of warp_account.source.
const DNSBuiltinDefaultID = "dns_builtin_ru_split"
DNSBuiltinDefaultID is the preset every install starts with as its default (Russia split).
const MaxLiveTokens = 50
MaxLiveTokens is the number of unrevoked, unexpired tokens the panel holds at most.
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 ( // ErrEnrollToken: the token is unknown, expired or already used (and not a valid replay). ErrEnrollToken = errors.New("store: enrollment token unknown, expired or used") // ErrNodeRetired: the node exists but was retired. ErrNodeRetired = errors.New("store: node retired") // ErrConflict: a unique constraint was violated (node name). ErrConflict = errors.New("store: conflict") )
Errors of the enrollment path.
var ( // ErrPlanState: the plan is not in a state the call needs. The error is a *PlanStateError that carries the // status found (errors.As); errors.Is(err, ErrPlanState) is true for it. ErrPlanState = errors.New("store: plan is in another state") // ErrTooManyPlans: the token holds too many open plans, or too many plans wait for the owner. ErrTooManyPlans = errors.New("store: too many open plans") )
var ( // ErrNotFound is returned when a looked-up row does not exist. ErrNotFound = errors.New("store: not found") // ErrSetupClosed is returned when the first admin cannot be created: the token is // unknown, used or expired, or an admin already exists. ErrSetupClosed = errors.New("store: setup closed") )
var ( // ErrNameTaken: another unrevoked token already has this name (case insensitive). ErrNameTaken = errors.New("store: token name taken") // ErrTokenLimit: MaxLiveTokens unrevoked, unexpired tokens already exist. ErrTokenLimit = errors.New("store: too many tokens") )
var ErrAccessSubnetFull = errors.New("store: subnet full")
ErrAccessSubnetFull is returned when the client network of a profile has no free peer index.
var ErrDNSExists = errors.New("store: dns preset name taken")
ErrDNSExists is returned when a preset name is already taken.
var ErrLastMethod = errors.New("store: last sign-in method")
ErrLastMethod is returned when removing a credential would leave the admin unable to sign in.
var ErrLoginTaken = errors.New("store: login taken")
ErrLoginTaken: another admin signs in with this login.
Functions ¶
func AWGHwidHash ¶
AWGHwidHash is the hwid_hash of an AWG device: NULL belongs to the implicit per-user device (one per user, a unique index), so an explicit device gets a synthetic hash that never equals the hash of a real HWID header.
func Clip ¶
Clip returns s as valid UTF-8 of at most n bytes, cut on a rune boundary. Text that comes from a node or a browser header is clipped with it before it is stored: a byte-wise cut can end inside a multi-byte character, and an invalid string makes every proto3 response that carries it fail to marshal.
func RetainedKeyAAD ¶
RetainedKeyAAD is the vault AAD of a retained server key: bound to the pair, not to the inbound that is gone.
func WithAuditSource ¶
WithAuditSource returns ctx marking every audit row written with it, whose entry names no source, as coming from source (AuditAPI or AuditMCP: a call made with an API token). Modules pass the request context to Audit, so their rows carry the source of the call without knowing about tokens. An unknown source is ignored.
Types ¶
type APIToken ¶
type APIToken struct {
ID, Name, Profile, Hint string
RatePerMin int
CreatedBy, CreatedByName string // admin id; the display name is resolved on reads ("" when the admin is gone)
RevokedBy string
CreatedAt, ExpiresAt time.Time
RevokedAt, LastUsedAt time.Time
LastUsedIP, LastUsedVia string
}
APIToken is one api_token row. A zero time means "unset".
type AWGDeviceAdd ¶
type AWGDeviceAdd struct {
Device AccessDevice // ID, UserID, Platform, Model, CreatedAt
ProfileID string
MaxIdx int // the largest peer index of the profile's client network
Limit int // the user's device limit
}
AWGDeviceAdd describes a new AWG device.
type AWGImplicitWant ¶
AWGImplicitWant asks for an AWG credential of one profile on the implicit 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 inside the write transaction: no database access of its own.
type Access ¶
type Access struct {
// contains filtered or unexported fields
}
Access is the query set of the access module.
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 transaction. 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) AddCreds ¶
func (a Access) AddCreds(ctx context.Context, creds []AccessCred) error
AddCreds inserts credentials for an existing device (ErrAccessExists when one is already live).
func (Access) AddDevice ¶
func (a Access) AddDevice(ctx context.Context, d AccessDevice, creds []AccessCred) error
AddDevice inserts a device with its credentials (ErrAccessExists on a live implicit device race).
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) BumpProfileEpoch ¶
BumpProfileEpoch marks every device of the profile that already received a config as stale (something on the nodes changed that an issued config cannot survive).
func (Access) CreateGroup ¶
func (a Access) CreateGroup(ctx context.Context, g AccessGroup) error
CreateGroup inserts a group with its profile set. ErrAccessExists on a name clash, ErrNotFound when a profile id does not exist.
func (Access) CreateInbound ¶
func (a Access) CreateInbound(ctx context.Context, i AccessInbound) error
CreateInbound inserts an inbound; ErrAccessExists when the profile is already on the node, ErrNotFound when the profile or node does not exist.
The inbound takes over the retained server key of its (profile, node), if there is one (RetainedKey): the row is deleted in the same transaction, so the key is never on both sides.
func (Access) CreateProfile ¶
func (a Access) CreateProfile(ctx context.Context, p AccessProfile) error
CreateProfile inserts a profile; ErrAccessExists when the name is taken.
func (Access) CreateUser ¶
func (a Access) CreateUser(ctx context.Context, u AccessUser, dev AccessDevice, creds []AccessCred) error
CreateUser inserts a user with its node list, implicit device and credentials in one transaction. The implicit device exists only to hold credentials: with none (a user of the Amnezia app only) it is not created and not counted against the device limit. ErrAccessExists on a name (or token) clash, ErrNotFound when the group or a node does not exist.
func (Access) DailyTraffic ¶
func (a Access) DailyTraffic(ctx context.Context, userID string, from time.Time) (map[int64]uint64, error)
DailyTraffic returns bytes (up + down) per UTC day since `from`, keyed by the day's Unix start.
func (Access) DeleteGroup ¶
DeleteGroup removes a group without users; ErrAccessInUse otherwise. A non-empty moveTo first moves the group's users there, in the same transaction (ErrNotFound when that group does not exist).
func (Access) DeleteInbound ¶
func (a Access) DeleteInbound(ctx context.Context, id string, now time.Time, retain func(stateEnc []byte, profileID, nodeID string) ([]byte, error)) error
DeleteInbound removes an inbound. With retain set and key material on the inbound, the key moves to awg_retained_key in the same transaction (replacing an older row of the pair, unless the node is retired): retain turns the inbound's vault blob into the blob for RetainedKeyAAD, and returns nil to keep nothing (an unreadable key must not make the inbound undeletable).
func (Access) DeleteProfile ¶
DeleteProfile removes a profile that has no inbounds; ErrAccessInUse otherwise. The AWG credentials and peers of the profile go with it (foreign keys); the explicit AWG devices that held them are revoked, so none stays behind as an empty shell.
func (Access) DeleteUsers ¶
DeleteUsers deletes users (devices, credentials, node list and traffic rows cascade) and returns the number deleted.
func (Access) DesiredCreds ¶
DesiredCreds returns the candidate credentials of every enabled inbound of a node.
func (Access) DeviceCounts ¶
DeviceCounts returns the number of devices per user that count against the device limit: not revoked and holding at least one live credential (a device without any is an empty shell, e.g. the implicit device of a user of the Amnezia app only, created by an older version).
func (Access) DeviceCreds ¶
DeviceCreds returns the live credentials of a device.
func (Access) Devices ¶
Devices returns the non-revoked devices of a user that hold a live credential, with their credential protocols.
func (Access) EnsureImplicitAWGCreds ¶
func (a Access) EnsureImplicitAWGCreds(ctx context.Context, userID string, dev AccessDevice, now time.Time, want []AWGImplicitWant) (int, error)
EnsureImplicitAWGCreds gives the user's implicit device (created from dev when there is none) an AWG credential for every wanted profile that it has none for, and returns how many it added. A subscription in the Mihomo format has no device identity, so every Mihomo client of the user shares this one peer per profile. The device limit is not checked: a subscription fetch must not fail because of it (the implicit device is one per user, so the limit is exceeded by at most one).
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) ImplicitDevice ¶
ImplicitDevice returns the live implicit device of a user, or ErrNotFound.
func (Access) InboundsFull ¶
InboundsFull returns every inbound joined with its profile and node, in the order they were created (rowid breaks a tie within a second); nodeID non-empty restricts it to one node. Retired nodes are excluded. This is the subscription's order, and the server names are numbered in it ("Germany", "Germany 2"): a server added later never takes the name of an older one. Deleting a server still renumbers the ones after it; a stored ordinal would keep them.
func (Access) InboundsOfNode ¶
InboundsOfNode returns the inbounds of a node.
func (Access) InboundsOfProfile ¶
InboundsOfProfile returns the inbounds of a profile.
func (Access) ListUsers ¶
func (a Access) ListUsers(ctx context.Context, q AccessUserQuery) ([]AccessUser, bool, AccessUserCounts, error)
ListUsers returns one page ordered by name (up to Limit users plus a flag telling whether more follow) and the chip counts. LIKE is case-insensitive for ASCII only.
func (Access) NodeTraffic ¶
func (a Access) NodeTraffic(ctx context.Context, userID string, since time.Time) ([]AccessNodeTraffic, error)
NodeTraffic returns a user's traffic per node and protocol since the given time.
func (Access) Nodes ¶
func (a Access) Nodes(ctx context.Context) ([]AccessNode, error)
Nodes returns all nodes that are not retired, ordered by name.
func (Access) ProfileHasPeers ¶
ProfileHasPeers reports whether the profile ever handed out a tunnel address (live or in quarantine): its client networks are then fixed.
func (Access) ProfileLiveAWG ¶
func (a Access) ProfileLiveAWG(ctx context.Context, profileID string, limit int) (n int, users []string, err error)
ProfileLiveAWG counts the live credentials of explicit AWG devices of a profile (the configs an x-critical change breaks) and lists the names of their owners, at most limit, ordered.
func (Access) ProfileUsers ¶
func (a Access) ProfileUsers(ctx context.Context, profileID string, happ, amnezia bool) ([]AccessBrief, error)
ProfileUsers lists users whose group contains the profile and whose app toggles allow it: happ and amnezia say which toggles count (derived from the protocol's Clients()). Ordered by name.
func (Access) Profiles ¶
func (a Access) Profiles(ctx context.Context) ([]AccessProfile, error)
Profiles returns all profiles ordered by name.
func (Access) RenameDevice ¶
RenameDevice sets the label (device.model) of a live AWG device; ErrNotFound when there is none.
func (Access) ResetUserPeriod ¶
func (a Access) ResetUserPeriod(ctx context.Context, id string, periodStart time.Time, status string) error
ResetUserPeriod starts a new quota period: usage back to zero, status as given.
func (Access) RetainedKey ¶
func (a Access) RetainedKey(ctx context.Context, profileID, nodeID string) (AccessRetainedKey, error)
RetainedKey returns the retained server key of the pair, or ErrNotFound.
func (Access) RevokeDevice ¶
RevokeDevice soft-deletes a live device and its credentials and returns its user id; ErrNotFound when the device does not exist or is already revoked.
func (Access) RotateAWGDevice ¶
func (a Access) RotateAWGDevice(ctx context.Context, deviceID string, now time.Time, issue AWGIssue) (string, error)
RotateAWGDevice replaces the credential of a live AWG device by a new one with the SAME peer index (the same tunnel address): the old credential is revoked and its peer released in the same transaction, so one desired state removes the old public key and adds the new one. It returns the device's user. ErrNotFound when there is no such live AWG device.
func (Access) SetConfigEpoch ¶
SetConfigEpoch records that the credential's device received a config of the given profile epoch (never lowers it).
func (Access) SetInboundBuildError ¶
SetInboundBuildError records that the inbound's desired spec could not be built (corrupt profile, unreadable secrets) so the node page shows it: state failed and last_error text. It writes only when that is news, because the desired state is recomputed on every change and stats tick.
func (Access) SetSubToken ¶
SetSubToken replaces the subscription token of a user.
func (Access) SetUserExpiry ¶
SetUserExpiry sets a user's term end (zero = never).
func (Access) SetUserStatus ¶
SetUserStatus stores a recomputed status.
func (Access) SetUsersDisabled ¶
SetUsersDisabled flips the admin switch of several users.
func (Access) TouchDevice ¶
TouchDevice sets last_seen_at unless it is already newer than `not`: a throttle for write-on-read.
func (Access) UpdateGroup ¶
func (a Access) UpdateGroup(ctx context.Context, id string, name *string, profileIDs *[]string, dnsPresetID *string) error
UpdateGroup renames a group, replaces its profile set and/or its DNS preset (nil = unchanged, "" = none).
func (Access) UpdateInbound ¶
func (a Access) UpdateInbound(ctx context.Context, i AccessInbound, resetState bool, now time.Time) error
UpdateInbound writes the admin-editable fields and the spec version of i (matched by ID). When resetState is set the state goes back to pending (enabled) or disabled, until the node reports again.
func (Access) UpdateProfile ¶
func (a Access) UpdateProfile(ctx context.Context, p AccessProfile, expectedVersion uint32, bumpInbounds, bumpEpoch bool, now time.Time) (AccessProfile, error)
UpdateProfile writes name, settings and secrets of p (matched by ID) when its stored version equals expectedVersion, bumps the version and, with bumpInbounds, the spec_version of the profile's inbounds. With bumpEpoch it also raises critical_epoch in the same transaction: every device that received its config before is then "stale" (an x-critical change of an AWG profile). ErrAccessVersion on mismatch, ErrAccessExists on a name clash. Returns the stored row.
func (Access) UpdateUser ¶
UpdateUser writes every admin-editable column of u (matched by ID) and its status. setNodes also replaces the explicit node list with u.NodeIDs. Usage counters are left alone (the fleet increments them). ErrAccessExists on a name clash, ErrNotFound when the user, group or a node does not exist.
func (Access) UserByTokenHash ¶
UserByTokenHash finds the user of a subscription token hash (sha256), or ErrNotFound.
func (Access) UserStates ¶
UserStates returns the state columns of the given users, or of all users when ids is nil.
func (Access) UserUsage ¶
func (a Access) UserUsage(ctx context.Context, userID string, since time.Time) (up, down uint64, err error)
UserUsage sums a user's traffic buckets since the given time (hour granularity).
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
}
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 AccessCred ¶
type AccessCred struct {
ID, DeviceID, UserID, Protocol string
ProfileID string
SecretEnc []byte // vault, AAD = ID
DataJSON string
ConfigEpoch int64
CreatedAt time.Time
}
AccessCred is one device x protocol credential. ProfileID binds an AWG credential to its profile ("" for hysteria2); ConfigEpoch is the profile critical_epoch the device last received a config for.
type AccessDesiredCred ¶
type AccessDesiredCred struct {
InboundID, CredID, UserID, DeviceID, Protocol, DataJSON string
SpeedLimitBps uint64
ExpiresAt time.Time
AppHapp, AppAmnezia bool
}
AccessDesiredCred is a live credential that may go to a node: its user is active, belongs to a group with the inbound's profile and has the node selected. The caller still checks the app toggles against the protocol's Clients().
type AccessDevice ¶
type AccessDevice struct {
ID, UserID, Platform, Model, OSVersion string
Implicit bool // hwid_hash IS NULL
// AWG marks a device created by AddAWGDevice: a synthetic hwid_hash (AWGHwidHash) and first/last seen 0 =
// "never connected" until the fleet records a handshake.
AWG bool
FirstSeenAt, LastSeenAt, CreatedAt time.Time
Protocols []string // protocols with a live credential
}
AccessDevice is one device of a user: the implicit per-user device of subscription fetches (no HWID) or an AWG device that holds its own keys.
type AccessGroup ¶
type AccessGroup struct {
ID, Name string
ProfileIDs []string
UserCount int
CreatedAt time.Time
DNSPresetID string // "" = the instance default
}
AccessGroup is an access group: a named set of profiles.
type AccessInbound ¶
type AccessInbound struct {
ID, ProfileID, NodeID string
PortOverride uint16 // 0 = none
TLSServerNameOverride string
Enabled bool
SpecVersion uint64
State string // pending | active | failed | disabled
LastError string
CertPinSHA256 string
CertNotAfter time.Time
CreatedAt, UpdatedAt time.Time
// Plugin-neutral material of the inbound (AWG: the server key pair). PluginStateEnc is the vault blob (AAD =
// inbound id) and nil for hysteria2; PluginPublicJSON is "{}" when there is none.
PluginStateEnc []byte
PluginPublicJSON string
// The last agent.v1.AwgHealth the node reported, as protojson ("" = never), and when.
AwgHealthJSON string
AwgHealthAt time.Time
}
AccessInbound is a profile deployed on a node. The fleet module updates State, LastError and the certificate fields from the node's results.
type AccessInboundFull ¶
type AccessInboundFull struct {
Inbound AccessInbound
Profile AccessProfile
Node AccessNode
}
AccessInboundFull is an inbound with its profile and node.
type AccessLimitError ¶
type AccessLimitError struct{ Used, Limit int }
AccessLimitError is returned when the user already has as many devices as the limit allows.
func (*AccessLimitError) Error ¶
func (e *AccessLimitError) Error() string
type AccessNode ¶
type AccessNode struct {
ID, Name, Address, CountryCode, Location, Provider string
State string // pending | active | retired
}
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, GroupID, GroupName string
Disabled bool
Status string // active | disabled | expired | limited (derived, see access.ComputeStatus)
AppHapp, AppAmnezia bool
AllNodes bool
QuotaBytes uint64 // 0 = unlimited
QuotaReset string // none | day | week | month | rolling_month
PeriodStart time.Time
UsedBytes uint64
ExpiresAt time.Time // zero = never
DeviceLimit int
SpeedLimitBps uint64
SubTokenHash, SubTokenEnc []byte
LastSeenAt time.Time
LastNodeID string
CreatedAt time.Time
NodeIDs []string // rows of user_node; meaningful while AllNodes is false
DNSPresetID string // "" = inherit (group, then the instance default)
GroupDNSPresetID string // the user's group's preset, read-only here ("" = none)
}
AccessUser is a user row with its group name and explicit node list.
type AccessUserCounts ¶
type AccessUserCounts struct{ All, Online, Expiring, OverQuota 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
After string // name after which the page starts ("" = first page)
Limit int
OnlineIDs []string // users currently online (fleet), for the "online" filter and its count
Now time.Time
}
AccessUserQuery is a list request. Filter is "", "online", "expiring" or "over_quota".
type AccessUserState ¶
type AccessUserState struct {
ID, Status, QuotaReset string
Disabled bool
QuotaBytes, UsedBytes uint64
ExpiresAt, PeriodStart time.Time
}
AccessUserState is what the status sweep needs about a user.
type Admin ¶
type Admin struct {
ID string
DisplayName string
Role string
UserHandle []byte // WebAuthn user.id
CreatedAt time.Time
}
Admin is a panel administrator.
type AdminLogin ¶
AdminLogin is an admin with its password login, for the operator's command line.
type AuditEntry ¶
type AuditEntry struct {
Actor string // admin id, or "anonymous"
Action string
Params string // JSON object without secrets; "" means {}
Result string
Source string // AuditPanel (default), AuditBot, AuditMCP or AuditAPI
IP string // client address the action came from, "" if none
}
AuditEntry is one audit-log row.
type AuditQuery ¶
type AuditQuery struct {
Source string
BeforeID int64
Limit int
Actions, Prefixes []string
Failed bool
}
AuditQuery is one page of the audit log: newest first, id < BeforeID (0 = from the newest), at most Limit rows. Source keeps one source ("" = all). Actions and Prefixes keep the rows whose action is one of Actions or starts with one of Prefixes (both empty = every action). Failed keeps the rows whose result is not "ok".
type AuditRow ¶
type AuditRow struct {
ID int64
Time time.Time
Actor string
ActorName string // the admin's display name, or the token's name for "token:<id>" / "mcp:<id>"; "" if neither exists
Action string
Params string
Result string
Source string
IP string
}
AuditRow is an audit entry as listed in the UI.
type 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 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
ExitIP, ExitCountry, ErrorCode, ErrorDetail string
}
CheckSample is one finished round of the synthetic checker. Status: 1 ok, 2 degraded, 3 failed.
type CodeMatch ¶
CodeMatch keeps the events whose code is one of Codes or starts with one of Prefixes, or whose severity is at least MinSeverity (0 = severity does not count); Not keeps the others instead.
type 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) List ¶
List returns every preset: the built-ins in their fixed order (the sort column), then the custom ones by name.
func (DNS) SetDefaultID ¶
SetDefaultID stores the instance default ("" = the built-in default). The caller checks that it exists.
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).
type DNSLookup ¶
type DNSLookup struct {
Names map[string]string // preset id -> name
DefaultID string // the instance default that exists, else the built-in default
}
DNSLookup is what resolving an effective preset needs: the names of the existing presets and the instance default.
type DNSPreset ¶
type DNSPreset struct {
ID, Name, Description string
Builtin, IPv4Only bool
SplitDirect bool // the split rules' domains bypass the VPN (Happ)
Transport string // preferred transport: plain, dot or doh
ServersJSON, SplitJSON string
CreatedAt, UpdatedAt time.Time
}
DNSPreset is a preset row. ServersJSON and SplitJSON are validated by the dns module before they get here.
type DailyRow ¶
type DailyRow struct {
InboundID string
Day time.Time // 00:00 UTC
OK, Failed, Degraded int
P50MS, P95MS uint32
}
DailyRow is one health_check_daily row.
type DoctorAccept ¶
type DoctorAccept struct {
NodeID, CheckID, DetailCode string
By, ByName string // admin id, and the admin's display name ("" when the admin is gone)
At time.Time
}
DoctorAccept is one accepted warning.
type DoctorRow ¶
type DoctorRow struct {
NodeID, CheckID string
Status int // agent.proto DoctorStatus: 1 ok, 2 warn, 3 fail, 4 skip
TitleKey, Detail string
DetailCode string // agent.proto DoctorResult.detail_code; "" from an agent that predates it
Params map[string]string
FixID string
Measured time.Time
Received time.Time
}
DoctorRow is one stored DoctorResult.
type EngineRow ¶
type EngineRow struct{ Protocol, Version string }
EngineRow is one engine a node runs.
type EnrollResult ¶
type EnrollResult struct {
NodeID string
Cert CertRow
Replay bool // the same certificate as before, returned for a retried request
}
EnrollResult is what a successful Enroll returns.
type EventFilter ¶
type EventFilter struct {
NodeID, UserID string
MinSeverity int
BeforeID int64 // events with id < BeforeID; 0 = newest
Limit int
Match *CodeMatch // nil = any code
}
EventFilter selects events; zero values mean "any".
type EventRow ¶
type EventRow struct {
ID int64
Time time.Time
Severity int // 1 info, 2 warning, 3 error
Code, Source string // source: agent | panel | admin
NodeID, NodeName, UserID, UserName, DeviceID, InboundID string
ProfileName, Protocol string
Params map[string]string
SrcInstance string // agent events: dedup
SrcSeq uint64
}
EventRow is one row of the event log. NodeName/UserName and ProfileName/Protocol (the profile of InboundID, "" once the inbound is gone) are filled by Events only.
type FleetCredRef ¶
type FleetCredRef struct{ UserID, DeviceID, Protocol string }
FleetCredRef is what a credential id resolves to (credentials are soft-deleted, so revoked ones resolve).
type FleetHourRow ¶
FleetHourRow is one node_traffic_hour row.
type FleetInboundRow ¶
type FleetInboundRow struct {
ID, ProfileID, ProfileName, Protocol string
ProfileVersion uint32
Settings string // settings_json, secrets NOT merged
SecretsEnc []byte // vault, AAD = ProfileID; nil if the profile has no secrets
PortOverride uint16
TLSNameOverride string
SpecVersion uint64
Enabled bool
State, LastError string
CertPin string
CertNotAfter time.Time
// Plugin-neutral material (migration 00014): the vault blob of the inbound (AAD = inbound id; nil for hysteria2) and
// the public JSON ("{}" = none), and the last agent.v1.AwgHealth the node reported as protojson ("" = never).
PluginStateEnc []byte
PluginPublic string
AwgHealthJSON string
AwgHealthAt time.Time
}
FleetInboundRow is one inbound of a node joined with its profile.
type FleetSessionRef ¶
type FleetSessionRef struct{ CredID, InboundID string }
FleetSessionRef is one open session of a StatsBatch (used for the hourly peaks).
type FleetStatsIn ¶
type FleetStatsIn struct {
NodeID, Instance string
Seq uint64
Now time.Time
HourStart int64 // bucket hour (multiple of 3600), already clamped by the caller
Traffic []FleetTraffic
Sessions []FleetSessionRef
}
FleetStatsIn is one reliable StatsBatch to commit.
type FleetStatsOut ¶
type FleetStatsOut struct {
Duplicate bool // seq already committed: nothing was written
Refs map[string]FleetCredRef // every credential of the batch that resolved
Skipped int // deltas dropped: unknown credential, or inbound not on this node
Probe int // deltas of the health probe system credential, ignored on purpose (not an anomaly)
Users []string // users whose used_bytes grew (for the access module's status recompute)
}
FleetStatsOut is the outcome of IngestStats.
type FleetTraffic ¶
FleetTraffic is one TrafficDelta of a StatsBatch.
type GateRollback ¶
type GateRollback struct {
ErrorKey string // the gate's code: probe_failed, inbound_failed, 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 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
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 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
}
HelloInfo is what a Hello tells the panel.
type InboundApplied ¶
InboundApplied is one InboundResult as stored on the inbound row.
type LastUpdateRow ¶
type LastUpdateRow struct {
Outcome string `json:"outcome"`
FromVersion string `json:"from_version"`
FromBuilt int64 `json:"from_built"`
ToVersion string `json:"to_version"`
ToBuilt int64 `json:"to_built"`
Reason string `json:"reason"`
AtUnix int64 `json:"at_unix"`
}
LastUpdateRow is Hello.last_update as stored on the node row (JSON). Outcome is "ok", "rolled_back" or "failed".
type 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 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 NodePatch ¶
type NodePatch struct {
Name, Address, CountryCode, Location, Provider, Notes *string
DNSResolvers *[]string
LivenessTimeoutS, ApplyTimeoutS, DialTimeoutS *int
AwgBackend *string // "auto" | "kernel" | "userspace"
}
NodePatch updates the admin-editable fields; nil = unchanged.
type NodeProvisionEvent ¶
NodeProvisionEvent is a redacted, stable-code progress event.
type NodeProvisionJob ¶
type NodeProvisionJob struct {
ID, NodeID, Name, Address, CountryCode, Location, Provider string
SSHHost, HostFingerprint string
SSHPort uint16
Secret []byte
State, Phase, ErrorCode, CreatedBy string
CreatedAt, UpdatedAt time.Time
}
NodeProvisionJob is durable metadata for one owner-requested SSH installation. Secret is ciphertext produced by vault.Vault and is never returned by RPC methods.
type NodeRow ¶
type NodeRow struct {
ID, Name, Address, CountryCode, Location, Provider, Notes string
DNSResolvers []string
LivenessTimeoutS, ApplyTimeoutS, DialTimeoutS int
State string // pending | active | retired
CertSerial string
AgentVersion string
APIVersion int
BootAt, LastSeenAt, LastConnectedAt, LastDisconnectedAt time.Time // zero = never
AgentInstanceID string
LastSeq uint64
DesiredRevision uint64
DesiredHash string
AppliedRevision uint64
AppliedHash string
CreatedAt time.Time
RetiredAt time.Time
// From the last Hello: Hello.built, Hello.capabilities and Hello.last_update as JSON
// ("" = never reported; see LastUpdateRow).
AgentBuilt int64
AgentCaps []string
LastUpdateJSON string
// AwgBackend is the node setting "auto" | "kernel" | "userspace" (migration 00014), sent to agents that list awg/1.
AwgBackend string
// AwgPrepareJSON is the state of the automatic kernel-module build (migration 00019, see AwgPrepareRow); "" = never asked.
AwgPrepareJSON string
}
NodeRow is one node row.
func (NodeRow) AwgPrepare ¶
func (n NodeRow) AwgPrepare() AwgPrepareRow
AwgPrepare is the node's preparation state.
func (NodeRow) LastUpdate ¶
func (n NodeRow) LastUpdate() (LastUpdateRow, bool)
LastUpdate is what the node reported about its last self-update; false when it never did.
type NodeServerAccess ¶
type NodeServerAccess struct {
NodeID, NodeName, SSHHost, SSHUser, HostFingerprint string
SSHPort uint16
Password, PendingPassword []byte
ConfiguredAt time.Time
}
NodeServerAccess contains public connection metadata and vault ciphertext. Callers must never return Password or PendingPassword from an API response.
type PanelBackupSettings ¶
type PanelBackupSettings struct {
AccountID, Jurisdiction, Bucket, AccessKeyID, AgeRecipient string
SecretAccessKey []byte
Enabled bool
IntervalHours, RetentionDays int
LastSuccess time.Time
LastErrorCode string
UpdatedAt time.Time
}
PanelBackupSettings contains the saved R2 configuration. SecretAccessKey is vault ciphertext and must never be returned by an admin RPC.
type Passkey ¶
type Passkey struct {
ID string
AdminID string
CredentialID []byte
PublicKey []byte
AttestationType string
SignCount uint32
AAGUID []byte
Transports []string
Flags byte // raw authenticator data flags
Name string
CreatedAt time.Time
LastUsedAt time.Time // zero if never used to sign in
}
Passkey is a stored WebAuthn credential.
type PasswordCred ¶
type PasswordCred struct {
AdminID string
Login string // lower case
Hash string // argon2id PHC string
TOTPSecret []byte // sealed by the caller (vault); the store never sees the plain secret
TOTPStep int64 // last accepted 30 s step
}
PasswordCred is an admin's password + authenticator-code credential.
type PlanStateError ¶
type PlanStateError struct{ Status string }
PlanStateError is ErrPlanState with the status that was found. A plan past its expires_at reports "expired" even before the sweep has marked it.
func (*PlanStateError) Error ¶
func (e *PlanStateError) Error() string
func (*PlanStateError) Is ¶
func (e *PlanStateError) Is(target error) bool
type 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 inside the write transaction: no database access of its own.
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 RolloutRow ¶
type RolloutRow struct {
ID, Status, ToVersion string
ToBuilt int64
Manifest, Signature []byte
BatchSize int
PauseKey string
PauseParams map[string]string
CreatedBy string
CreatedAt, FinishedAt time.Time // FinishedAt zero while active
}
RolloutRow is one rollout of a signed bundle.
type Session ¶
type Session struct {
TokenHash []byte
AdminID string
CreatedAt time.Time
LastSeenAt time.Time
ExpiresAt time.Time
IP string
UserAgent string
StepUpAt time.Time // last proof of a sign-in factor in this session (signing in counts)
}
Session is a signed-in browser session. Only the SHA-256 of the cookie token is stored.
type StepRow ¶
type StepRow struct {
RolloutID, NodeID, NodeName string
Stage int
State string
FromVersion string
FromBuilt int64
PreFailed []string // inbound ids that were FAILED before the update
SentAt, AckedAt time.Time
ReconnectedAt, FinishedAt time.Time
ErrorKey string
Params map[string]string
}
StepRow is one node's turn in a rollout.
type Store ¶
Store wraps the two connection pools. All writes go through W (one connection, so writers queue instead of hitting SQLITE_BUSY); reads use R.
func Open ¶
Open opens (creating if needed) the database at path and applies migrations. The database file is created with mode 0600 (SQLite gives the -wal and -shm files the same mode); an existing file with wider permissions is tightened.
func (*Store) APITokenBySecretHash ¶
APITokenBySecretHash finds the token for SHA-256 of a presented secret (revoked and expired ones too: the caller says why it refuses). ErrNotFound if there is none.
func (*Store) AcceptDoctor ¶
AcceptDoctor stores (or renews) an acceptance, in one statement and only while the stored result of the check is still a WARN (2) with that detail code; false when it is not (a newer report changed it, and DropStaleAccepts may have run).
func (*Store) ActiveAlerts ¶
func (s *Store) ActiveAlerts(ctx context.Context) ([]HealthAlert, error)
ActiveAlerts returns every unresolved alert.
func (*Store) ActiveRollout ¶
func (s *Store) ActiveRollout(ctx context.Context) (RolloutRow, error)
ActiveRollout is the RUNNING or PAUSED rollout, ErrNotFound when there is none.
func (*Store) AddPasskey ¶
AddPasskey stores another passkey for an existing admin.
func (*Store) AddPassword ¶
AddPassword gives an admin who has none a password login (c.Login lower case, c.Hash and the sealed c.TOTPSecret). ErrLoginTaken when another admin has the login, ErrAccessExists when this admin already has a password login, ErrNotFound for an unknown admin.
func (*Store) AdminCount ¶
AdminCount returns the number of admins.
func (*Store) AdminHasPassword ¶
AdminHasPassword reports whether the admin can sign in with a password.
func (*Store) AdminLogins ¶
func (s *Store) AdminLogins(ctx context.Context) ([]AdminLogin, error)
AdminLogins lists every admin, oldest first, with its password login and how many passkeys it has.
func (*Store) AdvanceTOTPStep ¶
AdvanceTOTPStep records step as used. It returns false if step is not newer than the last accepted one, which is how a code is made single-use (also across racing requests).
func (*Store) AlertCounts ¶
AlertCounts counts the active alerts that feed the badge: not muted, severity warning or critical.
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) Audit ¶
Audit appends a row to the audit log. An entry without a Source takes the one of WithAuditSource, else AuditPanel.
func (*Store) AwgPrepareFinish ¶
func (s *Store) AwgPrepareFinish(ctx context.Context, nodeID string, ok bool, at int64, code, reason string) (switched bool, err error)
AwgPrepareFinish records the end of a build. When it succeeded and the admin still wants the module (Want) the node's awg_backend becomes "kernel" in the same transaction (switched = true): this is the only place the panel switches a node to the kernel module by itself, and only after the node said the module is built, loaded and verified. A failure changes nothing but the record.
func (*Store) AwgPrepareStarted ¶
AwgPrepareStarted records that a build is running (the node said so, or the admin asked and the node accepted). A build that is already recorded as running keeps its start time.
func (*Store) BeginApply ¶
func (s *Store) BeginApply(ctx context.Context, id, tokenID, tool string, paramsHash, confirmHash []byte, now time.Time) (MCPPlan, error)
BeginApply is the compare-and-swap planned|approved -> applying that lets exactly one caller run a plan. It needs the plan to belong to tokenID, to be for tool, to carry the given confirm hash and params hash (both are also checked against SHA-256 of the stored params_json, so a tampered row is refused) and to be unexpired. A plan that is not there for this token and tool is ErrNotFound: one answer, no oracle. A plan in another state is a *PlanStateError (ErrPlanState) with the status found. applied_at is set to now (the start).
func (*Store) CertStatus ¶
CertStatus looks up an issued certificate by serial for the TLS handshake, per-RPC checks and the periodic check of a running stream. ErrNotFound if the panel never issued it.
func (*Store) CheckSetupToken ¶
CheckSetupToken returns ErrSetupClosed unless hash is an unused, unexpired setup token and no admin exists yet. It does not consume the token.
func (*Store) ClaimNodeProvisionJob ¶
func (s *Store) ClaimNodeProvisionJob(ctx context.Context, now time.Time) (NodeProvisionJob, bool, error)
ClaimNodeProvisionJob atomically claims the oldest queued job for the single panel worker.
func (*Store) ClearLoginFailures ¶
ClearLoginFailures forgets the failures of login after a successful sign-in.
func (*Store) ClearPendingNodeServerPassword ¶
ClearPendingNodeServerPassword discards a replacement that could not be applied while the old login still works.
func (*Store) CommitPendingNodeServerPassword ¶
func (s *Store) CommitPendingNodeServerPassword(ctx context.Context, nodeID string, encryptedCurrent []byte, now time.Time) error
CommitPendingNodeServerPassword promotes the verified node-bound ciphertext and removes its recovery copy.
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) 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 and the insert are one transaction on the single writer connection. t.CreatedAt is "now" for the cap.
func (*Store) CreateEnrollment ¶
func (s *Store) CreateEnrollment(ctx context.Context, n *NodeRow, nodeID string, tokenHash []byte, createdBy string, now, expires time.Time) (NodeRow, error)
CreateEnrollment issues an enrollment token. With n != nil it also creates the (pending) node in the same transaction (ErrConflict when the name is taken); otherwise nodeID must be an existing, non-retired node (re-enrollment). Older unused tokens of the node stop working. The returned node is the current row.
func (*Store) CreateFirstAdmin ¶
func (s *Store) CreateFirstAdmin(ctx context.Context, tokenHash []byte, now time.Time, a Admin, p Passkey) error
CreateFirstAdmin atomically consumes the setup token and inserts the first admin and its passkey. It returns ErrSetupClosed if the token is not valid any more or an admin already exists, so a token can never create two admins.
func (*Store) CreateFirstAdminPassword ¶
func (s *Store) CreateFirstAdminPassword(ctx context.Context, tokenHash []byte, now time.Time, a Admin, c PasswordCred) error
CreateFirstAdminPassword is CreateFirstAdmin for an admin whose first credential is a password + authenticator code instead of a passkey. A login name that is taken (it cannot be, before the first admin exists) is reported like any other insert error.
func (*Store) CreateMCPPlan ¶
func (s *Store) CreateMCPPlan(ctx context.Context, p MCPPlan, maxOpenPerToken, maxAwaiting int) error
CreateMCPPlan stores a new plan. Status must be planned (a safe tool) or awaiting (needs_approval). ID, ParamsHash (SHA-256 of ParamsJSON) and the expiry (CreatedAt + PlanTTL) are filled in when empty; ConfirmHash is required. A token may hold maxOpenPerToken open plans, and a new awaiting plan counts against maxAwaiting awaiting ones in the whole panel (ErrTooManyPlans). A revoked token cannot make plans (*PlanStateError cancelled).
func (*Store) CreateNodeProvisionJob ¶
func (s *Store) CreateNodeProvisionJob(ctx context.Context, job NodeProvisionJob) error
CreateNodeProvisionJob persists an owner-confirmed SSH installation request.
func (*Store) CreatePasswordSession ¶
func (s *Store) CreatePasswordSession(ctx context.Context, sess Session, checked PasswordCred) error
CreatePasswordSession is CreateSession for a password + code sign-in: the row goes in only while the admin's password and authenticator secret are still the ones the sign-in checked, else ErrNotFound. A reset or re-bind that lands between the check and this insert (and ends every session) then cannot be outlived by a session of the old credentials.
func (*Store) CreateRollout ¶
CreateRollout stores a rollout and its steps in one transaction. ErrConflict when another rollout is active (the unique index 00013 allows one RUNNING or PAUSED rollout).
func (*Store) CreateSession ¶
CreateSession inserts a session. Signing in is itself a proof of a factor, so StepUpAt starts at CreatedAt.
func (*Store) CreateWarpAccount ¶
func (s *Store) CreateWarpAccount(ctx context.Context, a WarpAccountRow) error
CreateWarpAccount stores a new account. ErrConflict when the node already has one (one per node: delete first), ErrNotFound when there is no such node.
func (*Store) DailyRows ¶
DailyRows returns the aggregates of an inbound (all when inboundID is empty), oldest day first.
func (*Store) DecideMCPPlan ¶
func (s *Store) DecideMCPPlan(ctx context.Context, id, adminID string, approve bool, now time.Time) (MCPPlan, error)
DecideMCPPlan is the owner's answer to a plan awaiting approval: a compare-and-swap awaiting -> approved or rejected that also needs the plan unexpired and its token unrevoked. ErrNotFound for an unknown id, *PlanStateError (ErrPlanState) with the status found when the plan is not awaiting any more.
func (*Store) DeleteAdminSession ¶
func (s *Store) DeleteAdminSession(ctx context.Context, adminID string, tokenHash []byte) (bool, error)
DeleteAdminSession ends one of the admin's sessions; it reports whether there was one.
func (*Store) DeleteOtherSessions ¶
DeleteOtherSessions ends every session of the admin except keep, returning how many.
func (*Store) DeletePasskey ¶
DeletePasskey removes one of the admin's passkeys. It returns ErrNotFound if the admin has no such passkey and ErrLastMethod if it is the only way the admin can sign in.
func (*Store) DeleteSession ¶
DeleteSession removes a session (logout or expiry).
func (*Store) DeleteWarpAccount ¶
DeleteWarpAccount removes the account. ErrNotFound when the node has none.
func (*Store) DoctorAccepts ¶
DoctorAccepts lists the acceptances of one node, or of every node for "".
func (*Store) DoctorResults ¶
DoctorResults returns the stored results of one node, or of every node for "" (ordered by node, check).
func (*Store) 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) 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 (called inside the transaction, only for a first use). Errors: ErrEnrollToken, ErrNodeRetired. A repeat with the same token and key within 10 minutes of first use returns the stored certificate. Every other certificate of the node is revoked (re-enrollment).
func (*Store) Events ¶
func (s *Store) Events(ctx context.Context, f EventFilter) (out []EventRow, hasMore bool, err error)
Events returns events newest first, names resolved from the node/user rows (a missing row leaves the name empty). hasMore reports that more rows exist beyond Limit.
func (*Store) ExpireMCPPlans ¶
ExpireMCPPlans is the once-a-minute sweep: unapplied plans past their expiry become expired; plans stuck in applying for ApplyStuckAfter (the panel restarted mid-call: the outcome is unknown and an apply is never resumed) become failed; finished plans older than PlanKeep are deleted. It returns how many rows it touched.
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). *PlanStateError if the plan is not applying (the sweep may have given up on it).
func (*Store) FinishCancelledNodeProvisionJob ¶
func (s *Store) FinishCancelledNodeProvisionJob(ctx context.Context, id string, now time.Time) (bool, error)
FinishCancelledNodeProvisionJob clears credentials after an active worker stops. The remote host may already have received some installation commands.
func (*Store) FleetDeviceModels ¶
FleetDeviceModels resolves device ids to "platform model" labels.
func (*Store) FleetEnabledInbounds ¶
FleetEnabledInbounds returns the enabled inbounds of every node with the name of the profile each deploys: node id -> inbound id -> profile name. One query for the whole fleet: the Overview and the node list ask on every poll, and the status of a node needs them (no profiles at all, which profile failed, how many there are).
func (*Store) FleetHours ¶
FleetHours returns the hourly rollup since the given hour (Overview, node cards).
func (*Store) FleetInbound ¶
FleetInbound returns one inbound by id, or ErrNotFound.
func (*Store) FleetInbounds ¶
func (s *Store) FleetInbounds(ctx context.Context, nodeID string, onlyEnabled bool) ([]FleetInboundRow, error)
FleetInbounds returns the inbounds of a node ordered by id.
func (*Store) FleetNodeProtocols ¶
FleetNodeProtocols returns the distinct protocols of the enabled inbounds per node.
func (*Store) FleetTopUsers ¶
func (s *Store) FleetTopUsers(ctx context.Context, nodeID string, sinceHour int64, limit int) ([]FleetTop, error)
FleetTopUsers returns the top users of a node by bytes since the given hour ("top today").
func (*Store) FleetUserNames ¶
FleetUserNames resolves user ids to names (missing ids are absent from the result).
func (*Store) 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) GetMCPPlan ¶
GetMCPPlan returns one plan with its stored status. ErrNotFound if there is none.
func (*Store) HealthAlert ¶
HealthAlert returns one alert or ErrNotFound.
func (*Store) 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 transaction. dup reports that the seq was already committed.
func (*Store) IngestStats ¶
func (s *Store) IngestStats(ctx context.Context, in FleetStatsIn) (FleetStatsOut, error)
IngestStats commits one StatsBatch in ONE transaction together with node.last_seq (agent.proto "RELIABLE MESSAGES"): traffic_bucket, node_traffic_hour (+peaks), user.used_bytes, and user.used_bytes (status rules belong to the access module). seq == 0 (not a reliable message) skips the dedup and the counter update.
func (*Store) InsertEvent ¶
InsertEvent appends an event (for panel and admin events; other modules may use it too).
func (*Store) InsertProbeCred ¶
InsertProbeCred stores a credential unless the inbound already has one (two callers racing: the first wins, both then read the same row back with ProbeCred). ErrNotFound when the inbound does not exist.
func (*Store) InsertProbeCredIdx ¶
func (s *Store) InsertProbeCredIdx(ctx context.Context, inboundID, profileID string, maxIdx int, now time.Time, issue ProbeCredIssue) error
InsertProbeCredIdx stores the credential of an inbound whose credential holds a tunnel address (AWG): the peer index comes from the profile's allocator, the same one the devices use (the index and the row are made in one transaction, 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) LastAuditByNode ¶
LastAuditByNode returns, per params.node_id, the time of the newest audit row of an action.
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) 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) ListAPITokens ¶
ListAPITokens returns every token, newest first, revoked and expired ones included.
func (*Store) ListApprovals ¶
func (s *Store) ListApprovals(ctx context.Context, now time.Time, awaitingOnly bool, historyLimit int) (rows []MCPPlan, awaiting int, err error)
ListApprovals returns the plans that need the owner (needs_approval = 1): those awaiting a decision first (oldest first), then up to historyLimit others, newest first (0 = 50, at most 200), unless awaitingOnly. The status of a plan past its expiry is reported as expired whether or not the sweep ran. awaiting counts the plans still awaiting at now.
func (*Store) ListAudit ¶
func (s *Store) ListAudit(ctx context.Context, source string, beforeID int64, limit int) ([]AuditRow, error)
ListAudit returns up to limit rows, newest first, with id < beforeID (0 = from the newest), optionally only those of one source ("" = all).
func (*Store) ListAuditQuery ¶
ListAuditQuery returns the rows of q.
func (*Store) LoginFailures ¶
func (s *Store) LoginFailures(ctx context.Context, login string, now time.Time, window time.Duration) (LoginFailure, error)
LoginFailures returns the lockout state of login (zero value if it has none).
func (*Store) MCPPlanByConfirm ¶
func (s *Store) MCPPlanByConfirm(ctx context.Context, tokenID string, confirmHash []byte) (MCPPlan, error)
MCPPlanByConfirm finds the plan of a token by SHA-256 of its confirm token. The status is the stored one: compare ExpiresAt with the clock. ErrNotFound if the token has no such plan.
func (*Store) MuteAlert ¶
MuteAlert sets (or, with a zero until, clears) the mute of an active alert and returns it. ErrNotFound when the alert does not exist, ErrConflict when it is already resolved.
func (*Store) NodeApplied ¶
func (s *Store) NodeApplied(ctx context.Context, id string, 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) NodeDesired ¶
NodeDesired stores the desired revision and hash (kept across panel restarts so revisions stay monotonic).
func (*Store) NodeDisconnected ¶
NodeDisconnected records the end of a stream.
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, 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) 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) 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.
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); otherwise a row is inserted. The unique index on active rows makes a concurrent double open fail instead of duplicating.
func (*Store) PanelBackupSettings ¶
func (s *Store) PanelBackupSettings(ctx context.Context) (PanelBackupSettings, error)
func (*Store) PasskeyByCredentialID ¶
PasskeyByCredentialID returns the passkey with the given WebAuthn credential id.
func (*Store) PasskeysByAdmin ¶
PasskeysByAdmin lists an admin's passkeys.
func (*Store) PasswordByAdmin ¶
PasswordByAdmin returns the password credential of an admin, or ErrNotFound.
func (*Store) PasswordByLogin ¶
PasswordByLogin returns the credential for a (lower-case) login name, or ErrNotFound.
func (*Store) PendingEnrollmentExpiry ¶
func (s *Store) PendingEnrollmentExpiry(ctx context.Context, nodeID string, now time.Time) (time.Time, error)
PendingEnrollmentExpiry returns when the newest usable enrollment token of the node expires; the zero time if there is none.
func (*Store) PruneEvents ¶
func (s *Store) PruneEvents(ctx context.Context, now time.Time, info, other time.Duration, batch int) (int64, error)
PruneEvents deletes events older than info (severity 1) and older than other (severity 2 and 3), in batches so the single writer is never held for long. It returns the number of rows removed.
func (*Store) PruneHealth ¶
func (s *Store) PruneHealth(ctx context.Context, now time.Time, samples, daily, alerts time.Duration) (int64, error)
PruneHealth deletes check rounds older than samples, aggregates older than daily and alerts resolved longer ago than alerts. It returns the number of rows removed.
func (*Store) 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) PurgeSessions ¶
PurgeSessions deletes sessions past their absolute expiry or idle for longer than idle.
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) PutSetupToken ¶
PutSetupToken stores a new one-time setup token hash and drops older unused ones, so only the latest printed link works.
func (*Store) RecentSamples ¶
RecentSamples returns the newest n rounds of an inbound, newest first (to rebuild the fail streak after a restart).
func (*Store) RecordLoginFailure ¶
func (s *Store) RecordLoginFailure(ctx context.Context, login string, now time.Time, maxFailures int, window, lock time.Duration) (LoginFailure, error)
RecordLoginFailure counts one failed sign-in for login. Reaching maxFailures failures within window locks the login for lock. It also drops stale rows, so the table cannot grow without bound from names an attacker makes up.
func (*Store) RecordPanelBackupRun ¶
func (*Store) RenewCert ¶
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.
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 transaction (a re-registration: the old account must survive a failure to store the new one). ErrNotFound when the node has no account.
func (*Store) RequestCancelNodeProvisionJob ¶
func (s *Store) RequestCancelNodeProvisionJob(ctx context.Context, id string, now time.Time) (state string, changed bool, err error)
RequestCancelNodeProvisionJob atomically stops queued work or requests cancellation of the active worker. The returned state is either cancelled or cancel_requested.
func (*Store) RequeueNodeProvisionJobs ¶
RequeueNodeProvisionJobs restores interrupted work after a panel restart.
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 transaction: c becomes the admin's password login (a new password and authenticator secret for its existing login, or a new login when create is set), the lockouts named in clearLocks are lifted, every session of the admin ends, and the audit row is written. The last accepted authenticator step of an existing login never goes back. It returns how many sessions ended.
func (*Store) ResolveAlert ¶
func (s *Store) ResolveAlert(ctx context.Context, id, resolution string, now time.Time) (bool, error)
ResolveAlert ends an active alert. It reports false when the alert was not active any more.
func (*Store) RetireNode ¶
RetireNode marks the node retired, revokes every certificate and kills unused enrollment tokens. The row, its traffic and its events stay. ErrNotFound / ErrNodeRetired as appropriate.
func (*Store) RevokeAPIToken ¶
RevokeAPIToken revokes a token and cancels its open plans in one transaction. It is idempotent: a second call changes nothing (the first revoker and time stay) and returns the token. ErrNotFound for an unknown id. The partial unique index on the name is freed by the revocation.
func (*Store) RolloutSteps ¶
RolloutSteps lists the steps of a rollout by stage, then node name.
func (*Store) RollupDaily ¶
RollupDaily aggregates the stored rounds of every UTC day that has ended before now into health_check_daily. A day that already has a row is left alone, so it runs safely every hour. The raw rounds live 25 h, which covers a whole finished day for an hour after midnight. A panel that was down for more than an hour after midnight loses that day's aggregate for the hours already pruned (it is computed from what is left); nothing reads the aggregates yet.
func (*Store) SamplesSince ¶
SamplesSince returns every stored round at or after since, oldest first, per inbound.
func (*Store) SavePanelBackupSettings ¶
func (s *Store) SavePanelBackupSettings(ctx context.Context, v PanelBackupSettings, now time.Time) error
SavePanelBackupSettings replaces owner-editable settings while retaining the last successful run and status.
func (*Store) SaveStep ¶
SaveStep overwrites the mutable fields of a step (the worker owns its rows).
func (*Store) SessionStepUp ¶
SessionStepUp records that the session proved a sign-in factor at now.
func (*Store) SessionWithAdmin ¶
SessionWithAdmin returns the session for a token hash together with its admin.
func (*Store) SessionsByAdmin ¶
SessionsByAdmin lists an admin's sessions, most recently used first. Expired ones are included until PurgeSessions removes them; callers filter by the clock they trust.
func (*Store) SetAwgPrepare ¶
SetAwgPrepare replaces the state (the zero value clears it).
func (*Store) 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) 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, now time.Time) error
SetPendingNodeServerPassword journals an encrypted replacement before it is sent to the server.
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) SetSettings ¶
SetSettings upserts several settings in one transaction.
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) 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) 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) TouchAPIToken ¶
TouchAPIToken records a use of the token: when, from which address and over which channel ("api" or "mcp").
func (*Store) TouchAlert ¶
TouchAlert records that the condition of an active alert still holds and refreshes what may change with the diagnosis (severity, texts, params). A mute ends when the severity rises: it was muted at the milder level.
func (*Store) TouchPasskey ¶
func (s *Store) TouchPasskey(ctx context.Context, credID []byte, signCount uint32, flags byte, now time.Time) error
TouchPasskey records a successful sign-in: new signature counter, flags (backup state may change) and last-used time.
func (*Store) TouchSession ¶
TouchSession bumps last_seen_at.
func (*Store) UnacceptDoctor ¶
UnacceptDoctor removes an acceptance; false when there was none.
func (*Store) UpdateNode ¶
UpdateNode applies the patch and returns the new row. ErrConflict on a name clash.
func (*Store) UpdateNodeProvisionJob ¶
func (s *Store) UpdateNodeProvisionJob(ctx context.Context, id, state, phase, errorCode string, secret []byte, now time.Time) error
UpdateNodeProvisionJob changes a job without adding a journal entry.
func (*Store) UpdateNodeProvisionJobWithEvent ¶
func (s *Store) UpdateNodeProvisionJobWithEvent(ctx context.Context, id, state, phase, errorCode string, secret []byte, eventCode string, now time.Time) error
UpdateNodeProvisionJobWithEvent changes the job and appends its journal event atomically.
func (*Store) UpdateRunningNodeProvisionJob ¶
func (s *Store) UpdateRunningNodeProvisionJob(ctx context.Context, id, state, phase, errorCode string, secret []byte, now time.Time) error
UpdateRunningNodeProvisionJob only changes a job that is still running, so it cannot undo a concurrent owner cancellation or overwrite a terminal result.
func (*Store) UpdateRunningNodeProvisionJobWithEvent ¶
func (s *Store) UpdateRunningNodeProvisionJobWithEvent(ctx context.Context, id, state, phase, errorCode string, secret []byte, eventCode string, now time.Time) error
UpdateRunningNodeProvisionJobWithEvent updates an active job and its redacted journal atomically, without reverting a cancel_requested state.
func (*Store) UpdateWarpRefresh ¶
func (s *Store) UpdateWarpRefresh(ctx context.Context, nodeID string, r WarpRefresh, now time.Time) error
UpdateWarpRefresh replaces the connection facts of the account and clears "needs attention". ErrNotFound when the node has no account.
func (*Store) 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 WarpAccountRow ¶
type WarpAccountRow struct {
NodeID, Source string
SecretEnc []byte
PeerPublicKey string
EndpointV4, EndpointV6 string // IP literals, no port
Ports []uint16
AddressV4, AddressV6 string
MTU int
ClientID string // base64; its first three bytes are the "reserved" bytes
UseReserved bool
AccountType string
Enabled bool
TOSURL, TOSAcceptedBy string
TOSAcceptedAt time.Time // zero for an import
RegisteredWith string
Attention string // reason code while the owner has to decide; "" = fine
HealthJSON string // last agent.v1.WarpHealth (protojson); "" = never reported
HealthAt time.Time
CreatedAt, UpdatedAt time.Time
}
WarpAccountRow is one warp_account row.