admin

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2026 License: Apache-2.0, BSD-3-Clause, MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateStateToken

func GenerateStateToken() string

GenerateStateToken generates a secure state token for OIDC

func GetClientIP

func GetClientIP(r *http.Request) string

GetClientIP extracts the client IP from the request

func GetClientIPFromString

func GetClientIPFromString(remoteAddr string, headers http.Header) string

GetClientIPFromString extracts client IP from request with proper handling

func HashPassword

func HashPassword(password string) string

HashPassword exports the hash function for use in config

func VerifyPassword

func VerifyPassword(password, hash string) bool

VerifyPassword checks if a password matches an Argon2id hash

Types

type APIToken

type APIToken struct {
	Token       string
	Name        string
	Description string
	Permissions []string
	CreatedAt   time.Time
	ExpiresAt   time.Time
	LastUsed    time.Time
}

APIToken represents a bearer token for API access

type ActivityItem

type ActivityItem struct {
	Time    string
	Message string
	Type    string // info, success, warning, error
}

ActivityItem represents a recent activity log entry

type Admin

type Admin struct {
	ID          int64
	Username    string
	Email       string
	IsPrimary   bool
	Source      string
	ExternalID  string
	TOTPEnabled bool
	CreatedAt   time.Time
	UpdatedAt   time.Time
	LastLoginAt *time.Time
}

Admin represents a server admin account

type AdminInvite

type AdminInvite struct {
	ID        string
	Username  string
	CreatedBy int64
	ExpiresAt time.Time
	UsedAt    *time.Time
	UsedBy    *int64
	CreatedAt time.Time
}

AdminInvite represents an admin invite token

type AdminPageData

type AdminPageData struct {
	Title            string
	Description      string
	Page             string
	Config           *config.Config
	Stats            *DashboardStats
	Tokens           []*APIToken
	Error            string
	Success          string
	NewToken         string
	SchedulerTasks   map[string]*SchedulerTaskInfo
	SchedulerRunning bool // Per AI.md PART 19: Scheduler is ALWAYS RUNNING
	Extra            map[string]interface{}
	CSRFToken        string // Per AI.md PART 20: CSRF protection on all forms
	AdminPath        string // Per AI.md PART 17: Configurable admin path (default: "admin")
}

AdminPageData holds data for admin templates

type AdminService

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

AdminService handles server admin management per AI.md PART 31

func NewAdminService

func NewAdminService(db *database.DB) *AdminService

NewAdminService creates a new admin service

func (*AdminService) AcceptInvite

func (s *AdminService) AcceptInvite(ctx context.Context, token, username, email, password string) (*Admin, error)

AcceptInvite completes the admin invite flow

func (*AdminService) AuthenticateAdmin

func (s *AdminService) AuthenticateAdmin(ctx context.Context, identifier, password string) (*Admin, error)

AuthenticateAdmin authenticates an admin by username/email and password

func (*AdminService) CanAdminModifyAdmin

func (s *AdminService) CanAdminModifyAdmin(ctx context.Context, modifierID, targetID int64) (bool, error)

CanAdminModifyAdmin checks if one admin can modify another Per AI.md: Primary admin cannot be deleted except via --maintenance setup

func (*AdminService) CanAdminViewAdmin

func (s *AdminService) CanAdminViewAdmin(ctx context.Context, viewerID, targetID int64) (bool, error)

CanAdminViewAdmin checks if one admin can view another's details Per AI.md PART 31: admins cannot see other admin accounts

func (*AdminService) CreateAdmin

func (s *AdminService) CreateAdmin(ctx context.Context, username, email, password string, isPrimary bool) (*Admin, error)

CreateAdmin creates a new admin account

func (*AdminService) CreateInvite

func (s *AdminService) CreateInvite(ctx context.Context, createdBy int64, username string, expiresIn time.Duration) (string, error)

CreateInvite creates an admin invite token per AI.md PART 31

func (*AdminService) CreateSetupToken

func (s *AdminService) CreateSetupToken(ctx context.Context) (string, error)

CreateSetupToken creates a one-time setup token for --maintenance setup

func (*AdminService) DeleteAdmin

func (s *AdminService) DeleteAdmin(ctx context.Context, adminID, requestingAdminID int64) error

DeleteAdmin deletes a non-primary admin

func (*AdminService) GenerateAPIToken

func (s *AdminService) GenerateAPIToken(ctx context.Context, adminID int64) (string, error)

GenerateAPIToken generates a new API token for an admin

func (*AdminService) GetAdminByEmail

func (s *AdminService) GetAdminByEmail(ctx context.Context, email string) (*Admin, error)

GetAdminByEmail retrieves an admin by email

func (*AdminService) GetAdminByID

func (s *AdminService) GetAdminByID(ctx context.Context, id int64) (*Admin, error)

GetAdminByID retrieves an admin by ID

func (*AdminService) GetAdminByUsername

func (s *AdminService) GetAdminByUsername(ctx context.Context, username string) (*Admin, error)

GetAdminByUsername retrieves an admin by username

func (*AdminService) GetAdminsForAdmin

func (s *AdminService) GetAdminsForAdmin(ctx context.Context, requestingAdminID int64) ([]*Admin, error)

GetAdminsForAdmin returns admins visible to the requesting admin Per AI.md PART 31: Non-primary admins can only see their own account

func (*AdminService) GetAuditLogs

func (s *AdminService) GetAuditLogs(ctx context.Context, limit, offset int) ([]*AuditLogEntry, error)

GetAuditLogs retrieves audit log entries

func (*AdminService) GetOnlineAdmins

func (s *AdminService) GetOnlineAdmins(ctx context.Context) ([]string, error)

GetOnlineAdmins returns usernames of currently logged-in admins Per AI.md: admins can see WHO is logged in (username only)

func (*AdminService) GetPrimaryAdmin

func (s *AdminService) GetPrimaryAdmin(ctx context.Context) (*Admin, error)

GetPrimaryAdmin returns the primary admin account

func (*AdminService) GetTotalAdminCount

func (s *AdminService) GetTotalAdminCount(ctx context.Context) (int, error)

GetTotalAdminCount returns total number of admins (visible to all admins)

func (*AdminService) HasAnyAdmin

func (s *AdminService) HasAnyAdmin(ctx context.Context) (bool, error)

HasAnyAdmin checks if any admin account exists

func (*AdminService) ResetPrimaryAdminCredentials

func (s *AdminService) ResetPrimaryAdminCredentials(ctx context.Context) error

ResetPrimaryAdminCredentials resets the primary admin's password/token for --maintenance setup

func (*AdminService) UseSetupToken

func (s *AdminService) UseSetupToken(ctx context.Context, token string) error

UseSetupToken marks a setup token as used

func (*AdminService) ValidateAPIToken

func (s *AdminService) ValidateAPIToken(ctx context.Context, token string) (*Admin, error)

ValidateAPIToken validates an admin API token

func (*AdminService) ValidateInvite

func (s *AdminService) ValidateInvite(ctx context.Context, token string) (*AdminInvite, error)

ValidateInvite validates an invite token and returns the invite details

func (*AdminService) ValidateSetupToken

func (s *AdminService) ValidateSetupToken(ctx context.Context, token string) (bool, error)

ValidateSetupToken validates a setup token

type AdminSession

type AdminSession struct {
	ID        string
	UserID    string
	Username  string
	CreatedAt time.Time
	ExpiresAt time.Time
	IP        string
	UserAgent string
}

AdminSession represents an authenticated admin session

type AlertItem

type AlertItem struct {
	Message string
	Type    string // info, warning, error
}

AlertItem represents an alert or warning

type AuditLogEntry

type AuditLogEntry struct {
	ID        int64
	Timestamp time.Time
	UserID    *int64
	Action    string
	Resource  string
	Details   string
	IPAddress string
	UserAgent string
}

AuditLogEntry represents an audit log entry for display

type AuthManager

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

AuthManager handles admin authentication Per AI.md PART 17: Admin sessions stored in admin_sessions table (server.db)

func NewAuthManager

func NewAuthManager(cfg *config.Config) *AuthManager

NewAuthManager creates a new auth manager

func (*AuthManager) Authenticate

func (am *AuthManager) Authenticate(username, password string) bool

Authenticate validates username and password

func (*AuthManager) ClearSessionCookie

func (am *AuthManager) ClearSessionCookie(w http.ResponseWriter)

ClearSessionCookie removes the admin session cookie

func (*AuthManager) CreateAPIToken

func (am *AuthManager) CreateAPIToken(name, description string, permissions []string, validDays int) *APIToken

CreateAPIToken creates a new API bearer token

func (*AuthManager) CreateSession

func (am *AuthManager) CreateSession(username, ip, userAgent string) *AdminSession

CreateSession creates a new admin session Per AI.md PART 17: Sessions stored in admin_sessions table when db is available

func (*AuthManager) DeleteSession

func (am *AuthManager) DeleteSession(sessionID string)

DeleteSession removes a session Per AI.md PART 17: Remove from both memory and database

func (*AuthManager) GetSession

func (am *AuthManager) GetSession(sessionID string) (*AdminSession, bool)

GetSession retrieves a session by ID Per AI.md PART 17: Check database for session if not in memory (supports restart persistence)

func (*AuthManager) GetSessionFromRequest

func (am *AuthManager) GetSessionFromRequest(r *http.Request) (*AdminSession, bool)

GetSessionFromRequest extracts session from request cookie

func (*AuthManager) GetTokenFromRequest

func (am *AuthManager) GetTokenFromRequest(r *http.Request) string

GetTokenFromRequest extracts bearer token from Authorization header

func (*AuthManager) ListAPITokens

func (am *AuthManager) ListAPITokens() []*APIToken

ListAPITokens returns all active API tokens (without the actual token values)

func (*AuthManager) RefreshSession

func (am *AuthManager) RefreshSession(sessionID string) bool

RefreshSession extends a session's expiration Per AI.md PART 17: Update expiration in both memory and database

func (*AuthManager) RevokeAPIToken

func (am *AuthManager) RevokeAPIToken(token string) bool

RevokeAPIToken revokes an API token

func (*AuthManager) SetDatabase

func (am *AuthManager) SetDatabase(db *database.DB)

SetDatabase sets the database for session persistence Per AI.md PART 17: Admin sessions stored in admin_sessions table (server.db)

func (*AuthManager) SetSessionCookie

func (am *AuthManager) SetSessionCookie(w http.ResponseWriter, session *AdminSession)

SetSessionCookie sets the admin session cookie

func (*AuthManager) ValidateAPIToken

func (am *AuthManager) ValidateAPIToken(token string) (*APIToken, bool)

ValidateAPIToken validates a bearer token and returns permissions

type ClusterManager

type ClusterManager interface {
	Mode() string
	IsClusterMode() bool
	IsPrimary() bool
	NodeID() string
	Hostname() string
	GetNodes(ctx context.Context) ([]ClusterNode, error)
	GenerateJoinToken(ctx context.Context) (string, error)
	LeaveCluster(ctx context.Context) error
}

ClusterManager interface for cluster operations

type ClusterNode

type ClusterNode struct {
	ID        string
	Hostname  string
	Address   string
	Port      int
	Version   string
	IsPrimary bool
	Status    string
	LastSeen  time.Time
	JoinedAt  time.Time
}

ClusterNode represents a cluster node

type DashboardStats

type DashboardStats struct {
	// Status
	Status  string // Online, Maintenance, Error
	Uptime  string
	Version string

	// Request stats (24h)
	Requests24h int64
	Errors24h   int64

	// System resources
	CPUPercent  float64
	MemPercent  float64
	DiskPercent float64
	MemAlloc    string
	MemTotal    string

	// Runtime info
	GoVersion     string
	NumGoroutines int
	NumCPU        int
	ServerMode    string

	// Feature status
	TorEnabled     bool
	SSLEnabled     bool
	EnginesEnabled int

	// Recent activity (last 5 items)
	RecentActivity []ActivityItem

	// Scheduled tasks (next 5 tasks)
	ScheduledTasks []ScheduledTask

	// Alerts/Warnings
	Alerts []AlertItem
}

DashboardStats holds dashboard statistics

type EngineRegistry

type EngineRegistry interface {
	Count() int
	GetEnabled() []interface{}
	GetAll() []interface{}
}

EngineRegistry interface for engine management

type ExternalAdmin

type ExternalAdmin struct {
	ID           int64
	ProviderType string
	ProviderID   string
	ExternalID   string
	Username     string
	Email        string
	Groups       []string
	IsAdmin      bool
	CachedAt     time.Time
	LastLoginAt  *time.Time
}

ExternalAdmin represents an externally authenticated admin

type ExternalAuthService

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

ExternalAuthService handles OIDC/LDAP authentication per AI.md PART 31

func NewExternalAuthService

func NewExternalAuthService(db *database.DB, cfg *config.Config) *ExternalAuthService

NewExternalAuthService creates a new external auth service

func (*ExternalAuthService) CheckAdminGroupMembership

func (s *ExternalAuthService) CheckAdminGroupMembership(providerType, providerID string, groups []string) bool

CheckAdminGroupMembership checks if the user is in any admin group

func (*ExternalAuthService) ExchangeOIDCCode

func (s *ExternalAuthService) ExchangeOIDCCode(ctx context.Context, providerID, code string) (*OIDCTokenResponse, error)

ExchangeOIDCCode exchanges an authorization code for tokens

func (*ExternalAuthService) GetCachedExternalAdmin

func (s *ExternalAuthService) GetCachedExternalAdmin(ctx context.Context, providerType, providerID, externalID string) (*ExternalAdmin, error)

GetCachedExternalAdmin retrieves a cached external admin (for offline fallback)

func (*ExternalAuthService) GetEnabledLDAPProviders

func (s *ExternalAuthService) GetEnabledLDAPProviders() []config.LDAPConfig

GetEnabledLDAPProviders returns all enabled LDAP providers

func (*ExternalAuthService) GetEnabledOIDCProviders

func (s *ExternalAuthService) GetEnabledOIDCProviders() []config.OIDCProviderConfig

GetEnabledOIDCProviders returns all enabled OIDC providers

func (*ExternalAuthService) GetExternalAdmin

func (s *ExternalAuthService) GetExternalAdmin(ctx context.Context, providerType, providerID, externalID string) (*ExternalAdmin, error)

GetExternalAdmin retrieves a cached external admin

func (*ExternalAuthService) GetOIDCAuthURL

func (s *ExternalAuthService) GetOIDCAuthURL(providerID, state string) (string, error)

GetOIDCAuthURL returns the authorization URL for an OIDC provider

func (*ExternalAuthService) GetOIDCUserInfo

func (s *ExternalAuthService) GetOIDCUserInfo(ctx context.Context, providerID, accessToken string) (*OIDCUserInfo, error)

GetOIDCUserInfo fetches user info from the OIDC provider

func (*ExternalAuthService) SyncExternalAdmin

func (s *ExternalAuthService) SyncExternalAdmin(ctx context.Context, providerType, providerID string, userInfo *OIDCUserInfo) (*ExternalAdmin, error)

SyncExternalAdmin syncs an external user as admin if they are in admin groups

type Handler

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

Handler wraps admin HTTP handlers

func NewHandler

func NewHandler(cfg *config.Config, renderer Renderer) *Handler

NewHandler creates a new admin handler

func (*Handler) AuthManager

func (h *Handler) AuthManager() *AuthManager

AuthManager returns the admin authentication manager Per AI.md PART 11: Used by server auth.go for scoped login redirect

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(mux *http.ServeMux)

RegisterRoutes registers admin routes on the given mux Per AI.md PART 17: Admin Route Hierarchy (NON-NEGOTIABLE) - /{adminpath}/ = Dashboard ONLY - /{adminpath}/profile = Admin's own profile - /{adminpath}/preferences = Admin's own preferences - /{adminpath}/server/* = ALL server management

func (*Handler) SetAdminService

func (h *Handler) SetAdminService(svc *AdminService)

SetAdminService sets the admin service for multi-admin support

func (*Handler) SetClusterManager

func (h *Handler) SetClusterManager(cm ClusterManager)

SetClusterManager sets the cluster manager for node management

func (*Handler) SetConfigPath

func (h *Handler) SetConfigPath(path string)

SetConfigPath sets the path to the config file

func (*Handler) SetConfigSync

func (h *Handler) SetConfigSync(cs *config.ConfigSync)

SetConfigSync sets the config sync manager for cluster mode Per AI.md PART 5 lines 5212-5310: Configuration Source of Truth (NON-NEGOTIABLE)

func (*Handler) SetDatabase

func (h *Handler) SetDatabase(db *database.DB)

SetDatabase sets the database for session persistence per AI.md PART 17

func (*Handler) SetRegistry

func (h *Handler) SetRegistry(registry EngineRegistry)

SetRegistry sets the engine registry for admin reporting

func (*Handler) SetReloadCallback

func (h *Handler) SetReloadCallback(cb ReloadCallback)

SetReloadCallback sets the callback for config reload

func (*Handler) SetScheduler

func (h *Handler) SetScheduler(sm SchedulerManager)

SetScheduler sets the scheduler manager per AI.md PART 19 Required for admin panel to show actual scheduler runtime state

func (*Handler) SetTorManager

func (h *Handler) SetTorManager(tm TorManager)

SetTorManager sets the Tor service manager per AI.md PART 32

type OIDCTokenResponse

type OIDCTokenResponse struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
	IDToken      string `json:"id_token"`
}

OIDCTokenResponse represents the token endpoint response

type OIDCUserInfo

type OIDCUserInfo struct {
	Sub           string   `json:"sub"`
	Name          string   `json:"name"`
	Email         string   `json:"email"`
	EmailVerified bool     `json:"email_verified"`
	Groups        []string `json:"groups"`
}

OIDCUserInfo represents the userinfo endpoint response

type ReloadCallback

type ReloadCallback func() error

ReloadCallback is called when config reload is triggered

type Renderer

type Renderer interface {
	Render(w io.Writer, name string, data interface{}) error
}

Renderer interface for template rendering

type ScheduledTask

type ScheduledTask struct {
	Name    string
	NextRun string
}

ScheduledTask represents an upcoming scheduled task

type SchedulerManager

type SchedulerManager interface {
	IsRunning() bool
	GetTasks() []*SchedulerTaskInfo
	GetTask(id string) (*SchedulerTaskInfo, error)
	Enable(id string) error
	Disable(id string) error
	RunNow(id string) error
}

SchedulerManager interface for scheduler operations Per AI.md PART 19: Admin panel must show actual scheduler runtime state

type SchedulerTaskInfo

type SchedulerTaskInfo struct {
	ID          string    `json:"id"`
	Name        string    `json:"name"`
	Description string    `json:"description"`
	Schedule    string    `json:"schedule"`
	TaskType    string    `json:"task_type"`
	LastRun     time.Time `json:"last_run"`
	LastStatus  string    `json:"last_status"`
	LastError   string    `json:"last_error,omitempty"`
	NextRun     time.Time `json:"next_run"`
	RunCount    int64     `json:"run_count"`
	FailCount   int64     `json:"fail_count"`
	Enabled     bool      `json:"enabled"`
	Skippable   bool      `json:"skippable"`

	// Retry state per AI.md PART 19
	RetryCount int       `json:"retry_count"`
	NextRetry  time.Time `json:"next_retry,omitempty"`
	MaxRetries int       `json:"max_retries"`
}

SchedulerTaskInfo represents task information for admin panel Per AI.md PART 19: Task state shown in admin UI

type TorManager

type TorManager interface {
	IsRunning() bool
	GetOnionAddress() string
	GetTorStatus() map[string]interface{}
	Start() error
	Stop() error
	Restart() error
	RegenerateAddress() (string, error)
	GenerateVanity(prefix string) error
	CancelVanity()
	GetVanityProgress() *VanityProgress
	ExportKeys() ([]byte, error)
	ImportKeys(privateKey []byte) (string, error)
}

TorManager interface for Tor operations per AI.md PART 32

type VanityProgress

type VanityProgress struct {
	Prefix    string
	Attempts  int64
	StartTime time.Time
	Running   bool
	Found     bool
	Address   string
	Error     string
}

VanityProgress represents vanity address generation progress

Jump to

Keyboard shortcuts

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