server

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: 63 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ThemeDark  = "dark"
	ThemeLight = "light"
	ThemeAuto  = "auto"
)

Theme constants Per AI.md PART 16: Themes (NON-NEGOTIABLE - PROJECT-WIDE)

View Source
const DefaultTheme = ThemeDark

DefaultTheme is the default theme when no preference is set Per AI.md PART 16: Dark theme is the default

Variables

View Source
var EmbeddedFS embed.FS
View Source
var ErrInvalidToken = fmt.Errorf("invalid token format")

ErrInvalidToken is returned for malformed tokens

View Source
var ErrNoAccess = fmt.Errorf("no access to requested resource")

ErrNoAccess is returned when token lacks access to requested context

Functions

func Chain

func Chain(h http.Handler, middlewares ...func(http.Handler) http.Handler) http.Handler

Chain chains multiple middleware handlers together

func CheckPIDFile

func CheckPIDFile(pidPath string) (bool, int, error)

CheckPIDFile checks if PID file exists and if the process is still running Returns: (isRunning bool, pid int, err error) Per AI.md PART 8: Stale PID detection is REQUIRED

func GetStaticFile

func GetStaticFile(path string) ([]byte, error)

GetStaticFile returns the content of a static file

func GetTheme

func GetTheme(r *http.Request) string

GetTheme gets the current theme from cookie or defaults to dark Per AI.md PART 16: Themes (NON-NEGOTIABLE - PROJECT-WIDE) Theme system applies to: - Web interface (HTML pages) - Admin panel - Swagger UI - GraphiQL interface - All interactive elements

func GetThemeClass

func GetThemeClass(theme string) string

GetThemeClass returns the CSS class for the current theme Per AI.md PART 16: Apply theme class to <html> element

func GetTokenFromContext

func GetTokenFromContext(r *http.Request) string

GetTokenFromContext retrieves the token string from request context

func IsValidTheme

func IsValidTheme(theme string) bool

IsValidTheme checks if a theme string is valid

func PathSecurityMiddleware

func PathSecurityMiddleware(next http.Handler) http.Handler

PathSecurityMiddleware normalizes paths and blocks traversal attempts Per AI.md PART 5: This middleware MUST be after URLNormalizeMiddleware

func PrintBanner

func PrintBanner(info *BannerInfo)

PrintBanner prints a responsive startup banner per AI.md spec Uses box drawing characters and emojis for visual appeal

func SetTheme

func SetTheme(w http.ResponseWriter, theme string)

SetTheme sets the theme cookie Per AI.md PART 16: User preference persisted in cookie

func StaticFileServer

func StaticFileServer() http.Handler

StaticFileServer returns an http.Handler for serving static files

func URLNormalizeMiddleware

func URLNormalizeMiddleware(next http.Handler) http.Handler

URLNormalizeMiddleware normalizes URLs for consistent routing Per AI.md PART 16: Removes trailing slashes (except for root "/"), redirects to canonical URL This middleware MUST be FIRST in the chain - before PathSecurityMiddleware

Types

type Announcement

type Announcement struct {
	ID          string
	Type        string
	Title       string
	Message     string
	Dismissible bool
}

Announcement represents a site announcement (local type for templates)

type AuthPageData

type AuthPageData struct {
	PageData
	Error        string
	Success      string
	Username     string
	Email        string
	SSOProviders []SSOProvider
	RequireEmail bool
}

AuthPageData represents data for auth pages

type BannerInfo

type BannerInfo struct {
	AppName    string
	Version    string
	Mode       string
	Debug      bool
	HTTPPort   int
	HTTPSPort  int
	HTTPAddr   string
	HTTPSAddr  string
	TorAddr    string
	I2PAddr    string
	ListenAddr string
	IsHTTPS    bool
}

BannerInfo holds information for the startup banner

func BuildBannerInfo

func BuildBannerInfo(cfg *config.Config, torAddr string) *BannerInfo

BuildBannerInfo creates banner info from server configuration

type BuildInfo

type BuildInfo struct {
	Commit string `json:"commit"`
	Date   string `json:"date"`
}

BuildInfo represents build information per AI.md PART 13 Note: Fields are "commit" and "date" per spec, not "commit_id" and "build_date"

type CSRFMiddleware

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

CSRF middleware handles Cross-Site Request Forgery protection

func NewCSRFMiddleware

func NewCSRFMiddleware(cfg *config.Config) *CSRFMiddleware

NewCSRFMiddleware creates a new CSRF middleware

func (*CSRFMiddleware) GenerateToken

func (c *CSRFMiddleware) GenerateToken() string

GenerateToken generates a new CSRF token

func (*CSRFMiddleware) Protect

func (c *CSRFMiddleware) Protect(next http.Handler) http.Handler

Protect applies CSRF protection to handlers

func (*CSRFMiddleware) SetLogManager

func (c *CSRFMiddleware) SetLogManager(logMgr *logging.Manager)

SetLogManager sets the logging manager for security events

func (*CSRFMiddleware) ValidateToken

func (c *CSRFMiddleware) ValidateToken(r *http.Request) bool

ValidateToken validates a CSRF token from the request

type ClusterInfo

type ClusterInfo struct {
	Enabled   bool     `json:"enabled"`
	Status    string   `json:"status,omitempty"`     // "connected", "disconnected"
	Primary   string   `json:"primary,omitempty"`    // primary node public URL
	Nodes     []string `json:"nodes,omitempty"`      // all node public URLs
	NodeCount int      `json:"node_count,omitempty"` // total nodes
	Role      string   `json:"role,omitempty"`       // "primary" or "member"
}

ClusterInfo represents cluster status per AI.md PART 13

type ContactPageData

type ContactPageData struct {
	PageData
	ContactSent  bool
	ContactError string
	CaptchaA     int
	CaptchaB     int
	CaptchaID    string
}

ContactPageData extends PageData with contact form fields

type CookieConsentData

type CookieConsentData struct {
	Enabled   bool
	Message   string
	PolicyURL string
}

CookieConsentData represents cookie consent popup data

type DirectAnswerPageData

type DirectAnswerPageData struct {
	PageData
	Answer *direct.Answer
}

DirectAnswerPageData contains data for rendering a direct answer page

type ErrorPageData

type ErrorPageData struct {
	PageData
	ErrorCode    int
	ErrorTitle   string
	ErrorMessage string
	ErrorDetails string
}

ErrorPageData extends PageData with error-specific fields

type FlashMessage

type FlashMessage struct {
	Type    string
	Message string
}

FlashMessage represents a flash message

type HealthFeatures

type HealthFeatures struct {
	MultiUser     bool        `json:"multi_user"`
	Organizations bool        `json:"organizations"`
	Tor           *TorFeature `json:"tor"`
	GeoIP         bool        `json:"geoip"`
	Metrics       bool        `json:"metrics"`
}

HealthFeatures represents feature status per AI.md PART 13

type HealthInfo

type HealthInfo struct {
	Project        *ProjectInfo      `json:"project,omitempty"`
	Status         string            `json:"status"`
	Version        string            `json:"version"`
	GoVersion      string            `json:"go_version"`
	Mode           string            `json:"mode"`
	Uptime         string            `json:"uptime"`
	Timestamp      string            `json:"timestamp"`
	Build          *BuildInfo        `json:"build,omitempty"`
	Node           *NodeInfo         `json:"node,omitempty"`
	Cluster        *ClusterInfo      `json:"cluster,omitempty"`
	Features       *HealthFeatures   `json:"features,omitempty"`
	Checks         map[string]string `json:"checks"`
	Stats          *HealthStats      `json:"stats,omitempty"`
	System         *SystemInfo       `json:"system,omitempty"`
	PendingRestart bool              `json:"pending_restart,omitempty"`
	RestartReason  []string          `json:"restart_reason,omitempty"`
	Maintenance    *MaintenanceInfo  `json:"maintenance,omitempty"`
}

HealthInfo represents health check information per AI.md PART 13

type HealthPageData

type HealthPageData struct {
	PageData
	Health *HealthInfo
}

HealthPageData extends PageData with health-specific fields

type HealthStats

type HealthStats struct {
	RequestsTotal     int64 `json:"requests_total"`
	Requests24h       int64 `json:"requests_24h"`
	ActiveConnections int   `json:"active_connections"`
}

HealthStats represents health statistics per AI.md PART 13

type LogEntry

type LogEntry struct {
	Timestamp time.Time              `json:"timestamp"`
	Level     string                 `json:"level"`
	Message   string                 `json:"message"`
	Fields    map[string]interface{} `json:"fields,omitempty"`
	File      string                 `json:"file,omitempty"`
	Line      int                    `json:"line,omitempty"`
}

LogEntry represents a single log entry

type LogLevel

type LogLevel int

LogLevel represents logging levels

const (
	LevelDebug LogLevel = iota
	LevelInfo
	LevelWarn
	LevelError
	LevelFatal
)

func ParseLogLevel

func ParseLogLevel(s string) LogLevel

ParseLogLevel parses a log level string

func (LogLevel) String

func (l LogLevel) String() string

String returns the string representation of a log level

type Logger

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

Logger provides structured logging

func NewLogger

func NewLogger(cfg *config.Config) *Logger

NewLogger creates a new logger

func (*Logger) Close

func (l *Logger) Close() error

Close closes the logger

func (*Logger) Debug

func (l *Logger) Debug(msg string, args ...interface{})

Debug logs a debug message

func (*Logger) Error

func (l *Logger) Error(msg string, args ...interface{})

Error logs an error message

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, args ...interface{})

Fatal logs a fatal message and exits

func (*Logger) Info

func (l *Logger) Info(msg string, args ...interface{})

Info logs an info message

func (*Logger) RequestLogger

func (l *Logger) RequestLogger(method, path, ip string, status int, latency time.Duration)

RequestLogger returns a logger for HTTP requests

func (*Logger) Rotate

func (l *Logger) Rotate() error

Rotate rotates the log file

func (*Logger) SetLevel

func (l *Logger) SetLevel(level LogLevel)

SetLevel sets the log level

func (*Logger) Warn

func (l *Logger) Warn(msg string, args ...interface{})

Warn logs a warning message

func (*Logger) WithField

func (l *Logger) WithField(key string, value interface{}) *Logger

WithField returns a logger with an additional field

func (*Logger) WithFields

func (l *Logger) WithFields(fields map[string]interface{}) *Logger

WithFields returns a logger with additional fields

type MaintenanceHandler

type MaintenanceHandler interface {
	IsInMaintenance() bool
	GetMode() int
	GetMessage() string
}

MaintenanceHandler is a function that checks maintenance mode

type MaintenanceInfo

type MaintenanceInfo struct {
	Reason  string `json:"reason,omitempty"`
	Message string `json:"message,omitempty"`
	Since   string `json:"since,omitempty"`
}

MaintenanceInfo represents maintenance mode status

type Metrics

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

Metrics collects server metrics using Prometheus client library Per AI.md PART 29: MUST use github.com/prometheus/client_golang

func NewMetrics

func NewMetrics(cfg *config.Config) *Metrics

NewMetrics creates a new Prometheus metrics collector Per AI.md PART 29: Use github.com/prometheus/client_golang with promauto

func (*Metrics) AuthenticatedHandler

func (m *Metrics) AuthenticatedHandler() http.HandlerFunc

AuthenticatedHandler returns an HTTP handler with optional Bearer token authentication

func (*Metrics) GetActiveConnections

func (m *Metrics) GetActiveConnections() int64

GetActiveConnections returns current active connections for health endpoint Per AI.md PART 13: stats.active_connections must return actual count

func (*Metrics) GetTotalRequests

func (m *Metrics) GetTotalRequests() int64

GetTotalRequests returns total requests for health endpoint Per AI.md PART 13: stats.requests_total must return actual count

func (*Metrics) Handler

func (m *Metrics) Handler() http.Handler

Handler returns an HTTP handler for Prometheus metrics Per AI.md PART 29: Uses promhttp.Handler()

func (*Metrics) MetricsMiddleware

func (m *Metrics) MetricsMiddleware(next http.Handler) http.Handler

MetricsMiddleware creates middleware for recording request metrics Per AI.md PART 13: Tracks active connections for health endpoint stats

func (*Metrics) RecordAuthAttempt

func (m *Metrics) RecordAuthAttempt(method, status string)

RecordAuthAttempt records an authentication attempt

func (*Metrics) RecordCacheHit

func (m *Metrics) RecordCacheHit(cache string)

RecordCacheHit records a cache hit

func (*Metrics) RecordCacheMiss

func (m *Metrics) RecordCacheMiss(cache string)

RecordCacheMiss records a cache miss

func (*Metrics) RecordDBError

func (m *Metrics) RecordDBError(operation, errorType string)

RecordDBError records a database error

func (*Metrics) RecordDBQuery

func (m *Metrics) RecordDBQuery(operation, table string, duration time.Duration)

RecordDBQuery records a database query

func (*Metrics) RecordEngineError

func (m *Metrics) RecordEngineError(engine string)

RecordEngineError records an error from a search engine

func (*Metrics) RecordEngineRequest

func (m *Metrics) RecordEngineRequest(engine string)

RecordEngineRequest records a request to a search engine

func (*Metrics) RecordRequest

func (m *Metrics) RecordRequest(method, path string, statusCode int, duration time.Duration, reqSize, respSize int64)

RecordRequest records an HTTP request Per AI.md PART 13: Also increments atomic counter for health endpoint stats

func (*Metrics) RecordSchedulerTask

func (m *Metrics) RecordSchedulerTask(task, status string, duration time.Duration)

RecordSchedulerTask records a scheduler task execution

func (*Metrics) RecordSearch

func (m *Metrics) RecordSearch(category string, duration time.Duration)

RecordSearch records a search operation

func (*Metrics) SetActiveRequests

func (m *Metrics) SetActiveRequests(n int)

SetActiveRequests sets the current number of active requests

func (*Metrics) SetActiveSessions

func (m *Metrics) SetActiveSessions(n int)

SetActiveSessions sets the current number of active sessions

func (*Metrics) SetCacheStats

func (m *Metrics) SetCacheStats(cache string, size int, bytes int64)

SetCacheStats sets cache statistics

func (*Metrics) SetDBConnections

func (m *Metrics) SetDBConnections(open, inUse int)

SetDBConnections sets the current database connection counts

func (*Metrics) SetUserCounts

func (m *Metrics) SetUserCounts(total, active int)

SetUserCounts sets the user count metrics

type Middleware

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

Middleware wraps an http.Handler to add common functionality

func NewMiddleware

func NewMiddleware(cfg *config.Config, logMgr *logging.Manager) *Middleware

NewMiddleware creates a new middleware instance

func (*Middleware) CORS

func (m *Middleware) CORS(next http.Handler) http.Handler

CORS handles Cross-Origin Resource Sharing

func (*Middleware) Compress

func (m *Middleware) Compress(next http.Handler) http.Handler

Compress middleware adds gzip compression for text-based responses

func (*Middleware) ContextMiddleware

func (m *Middleware) ContextMiddleware(adminPath string) func(http.Handler) http.Handler

ContextMiddleware extracts context from URL path and validates token access Per AI.md PART 11: Routes are always URL-scoped. Context is determined from URL path.

func (*Middleware) DegradedMode

func (m *Middleware) DegradedMode(handler MaintenanceHandler) func(http.Handler) http.Handler

DegradedMode middleware handles degraded mode per AI.md PART 6 Shows warnings to users when system is in degraded state

func (*Middleware) GeoBlock

func (m *Middleware) GeoBlock(lookup *geoip.Lookup) func(http.Handler) http.Handler

GeoBlock middleware blocks requests based on GeoIP location

func (*Middleware) Logger

func (m *Middleware) Logger(next http.Handler) http.Handler

Logger middleware logs all requests

func (*Middleware) MaintenanceMode

func (m *Middleware) MaintenanceMode(handler MaintenanceHandler) func(http.Handler) http.Handler

MaintenanceMode middleware handles maintenance mode per AI.md PART 6 - Allows admin routes even during maintenance - Shows maintenance page to regular users - Allows health checks for monitoring

func (*Middleware) RateLimit

func (m *Middleware) RateLimit(limiter *RateLimiter) func(http.Handler) http.Handler

RateLimit middleware applies rate limiting

func (*Middleware) Recovery

func (m *Middleware) Recovery(next http.Handler) http.Handler

Recovery middleware recovers from panics Per AI.md PART 9: All panics must be safely recovered and logged with context

func (*Middleware) RequestID

func (m *Middleware) RequestID(next http.Handler) http.Handler

RequestID middleware adds a unique request ID (UUID v4 per AI.md)

func (*Middleware) SecurityHeaders

func (m *Middleware) SecurityHeaders(next http.Handler) http.Handler

SecurityHeaders adds security headers to all responses

func (*Middleware) TokenValidationMiddleware

func (m *Middleware) TokenValidationMiddleware(adminPath string) func(http.Handler) http.Handler

TokenValidationMiddleware validates API tokens and checks access per URL context Per AI.md PART 11 lines 11282-11311: Server request handling

type NodeInfo

type NodeInfo struct {
	ID       string `json:"id"`
	Hostname string `json:"hostname"`
}

NodeInfo represents node information for cluster mode

type OpenSearchDescription

type OpenSearchDescription struct {
	XMLName        xml.Name         `xml:"OpenSearchDescription"`
	XMLNS          string           `xml:"xmlns,attr"`
	ShortName      string           `xml:"ShortName"`
	Description    string           `xml:"Description"`
	Tags           string           `xml:"Tags,omitempty"`
	Contact        string           `xml:"Contact,omitempty"`
	LongName       string           `xml:"LongName,omitempty"`
	Image          *OpenSearchImage `xml:"Image,omitempty"`
	URLs           []OpenSearchURL  `xml:"Url"`
	InputEncoding  string           `xml:"InputEncoding"`
	OutputEncoding string           `xml:"OutputEncoding"`
}

OpenSearchDescription represents the OpenSearch XML format

type OpenSearchImage

type OpenSearchImage struct {
	Width  int    `xml:"width,attr"`
	Height int    `xml:"height,attr"`
	Type   string `xml:"type,attr"`
	URL    string `xml:",chardata"`
}

OpenSearchImage represents the search engine icon

type OpenSearchURL

type OpenSearchURL struct {
	Type     string `xml:"type,attr"`
	Method   string `xml:"method,attr,omitempty"`
	Template string `xml:"template,attr"`
	Rel      string `xml:"rel,attr,omitempty"`
}

OpenSearchURL represents a search URL template

type PageData

type PageData struct {
	Title          string
	Description    string
	Page           string
	Theme          string
	Lang           string // Language code for html lang attribute (default: "en")
	Dir            string // Text direction for html dir attribute (default: "ltr")
	Config         *config.Config
	User           interface{}
	CSRF           string
	CSRFToken      string
	Flash          *FlashMessage
	Data           interface{}
	Query          string
	Category       string
	BuildDate      string
	Announcements  []Announcement // Active announcements
	TorEnabled     bool           // Tor hidden service enabled (binary found)
	TorStatus      string         // Tor status: "connected", "connecting", "disabled"
	TorAddress     string         // .onion address (when connected)
	WidgetsEnabled bool
	DefaultWidgets string // JSON array of default widget types
	CookieConsent  *CookieConsentData
	Extra          map[string]interface{}
	AdminPath      string // Per AI.md PART 17: Configurable admin path (default: "admin")
}

PageData represents common data passed to all page templates

func NewPageData

func NewPageData(cfg *config.Config, title, page string) *PageData

NewPageData creates a new PageData with defaults

type Pagination

type Pagination struct {
	CurrentPage int
	TotalPages  int
	HasPrev     bool
	HasNext     bool
}

Pagination represents pagination information

type ProjectInfo

type ProjectInfo struct {
	Name        string `json:"name"`        // branding.app_name or server.title
	Tagline     string `json:"tagline"`     // branding.tagline (short slogan)
	Description string `json:"description"` // server.description (longer)
}

ProjectInfo represents project information for healthz per AI.md PART 13

type RateLimiter

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

RateLimiter implements token bucket rate limiting

func NewRateLimiter

func NewRateLimiter(cfg *config.RateLimitConfig) *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(ip string) bool

Allow checks if a request is allowed

type RequestContext

type RequestContext struct {
	Type TargetType
	Name string // Username or org slug when applicable
}

RequestContext holds context extracted from URL path Per AI.md PART 11: Context is determined from URL path, NOT headers

func GetRequestContext

func GetRequestContext(r *http.Request) *RequestContext

GetRequestContext retrieves the request context from the request

type SSLManager

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

SSLManager handles SSL/TLS configuration

func NewSSLManager

func NewSSLManager(cfg *config.Config) *SSLManager

NewSSLManager creates a new SSL manager

func (*SSLManager) GetCertificatePaths

func (m *SSLManager) GetCertificatePaths() (certFile, keyFile string)

GetCertificatePaths returns the paths for SSL certificates

func (*SSLManager) GetTLSConfig

func (m *SSLManager) GetTLSConfig() (*tls.Config, error)

GetTLSConfig returns a TLS configuration based on settings

func (*SSLManager) HasValidCertificate

func (m *SSLManager) HasValidCertificate() bool

HasValidCertificate checks if valid SSL certificates exist

func (*SSLManager) LogSSLStatus

func (m *SSLManager) LogSSLStatus()

LogSSLStatus logs the current SSL status

type SSOProvider

type SSOProvider struct {
	Name    string
	ID      string
	IconURL string
	URL     string
}

SSOProvider represents a single sign-on provider

type SearchPageData

type SearchPageData struct {
	PageData
	Query         string
	Category      string
	Results       interface{}
	TotalResults  int
	SearchTime    float64
	Pagination    *Pagination
	Error         string
	InstantAnswer interface{} // Instant answer result (if any)
}

SearchPageData extends PageData with search-specific fields

type Server

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

Server represents the HTTP server

func New

func New(cfg *config.Config) *Server

New creates a new server instance

func (*Server) GetSchedulerTasks

func (s *Server) GetSchedulerTasks() []*scheduler.TaskInfo

GetSchedulerTasks returns all scheduler tasks for API/UI

func (*Server) RunSchedulerTask

func (s *Server) RunSchedulerTask(taskID string) error

RunSchedulerTask runs a scheduler task immediately

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server with a context

func (*Server) Start

func (s *Server) Start() error

Start starts the HTTP server

func (*Server) UpdateConfig

func (s *Server) UpdateConfig(cfg *config.Config)

UpdateConfig updates the server configuration

type Session

type Session struct {
	ID        string
	Data      map[string]interface{}
	UserID    string
	IP        string
	UserAgent string
	CreatedAt time.Time
	ExpiresAt time.Time
	LastSeen  time.Time
}

Session represents a user session

type SessionDisplay

type SessionDisplay struct {
	ID         int64
	DeviceName string
	IPAddress  string
	CreatedAt  string
	LastUsed   string
	IsCurrent  bool
}

SessionDisplay represents session info for display

type SessionManager

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

SessionManager manages user sessions

func NewSessionManager

func NewSessionManager(cfg *config.Config) *SessionManager

NewSessionManager creates a new session manager

func (*SessionManager) ClearCookie

func (sm *SessionManager) ClearCookie(w http.ResponseWriter)

ClearCookie removes the session cookie

func (*SessionManager) Count

func (sm *SessionManager) Count() int

Count returns the number of active sessions

func (*SessionManager) Create

func (sm *SessionManager) Create(userID, ip, userAgent string) *Session

Create creates a new session

func (*SessionManager) Destroy

func (sm *SessionManager) Destroy(id string)

Destroy removes a session

func (*SessionManager) Get

func (sm *SessionManager) Get(id string) (*Session, bool)

Get retrieves a session by ID

func (*SessionManager) GetFromRequest

func (sm *SessionManager) GetFromRequest(r *http.Request) (*Session, bool)

GetFromRequest retrieves session from request cookie

func (*SessionManager) Refresh

func (sm *SessionManager) Refresh(id string) bool

Refresh extends a session's expiration

func (*SessionManager) SetCookie

func (sm *SessionManager) SetCookie(w http.ResponseWriter, session *Session)

SetCookie sets the session cookie on the response

type SystemInfo

type SystemInfo struct {
	GoVersion    string `json:"go_version"`
	NumCPU       int    `json:"num_cpu"`
	NumGoroutine int    `json:"num_goroutine"`
	MemAlloc     string `json:"mem_alloc"`
}

SystemInfo represents system information

type TargetType

type TargetType int

TargetType represents the context type extracted from URL path Per AI.md PART 11: Server-Side Context from URL (NON-NEGOTIABLE)

const (
	TargetUnknown     TargetType = iota // Unknown/invalid target
	TargetPublic                        // Public routes (/, /api/v1/, project-specific like /search)
	TargetServerPages                   // Server pages - about, help, contact, privacy (/server/*)
	TargetAuth                          // Auth flows (/auth/*)
	TargetCurrentUser                   // Current user from token (/users/*)
	TargetUser                          // Specific user (/users/{username}/*)
	TargetOrg                           // Organization (/orgs/{slug}/*)
	TargetAdmin                         // Server admin panel (/admin/*)
	TargetAdminServer                   // Server settings within admin (/admin/server/*)
)

func (TargetType) String

func (t TargetType) String() string

String returns the string representation of TargetType

type TaskNotFoundError

type TaskNotFoundError struct {
	Name string
}

TaskNotFoundError is returned when a task is not found

func (*TaskNotFoundError) Error

func (e *TaskNotFoundError) Error() string

type TemplateNotFoundError

type TemplateNotFoundError struct {
	Name string
}

TemplateNotFoundError is returned when a template is not found

func (*TemplateNotFoundError) Error

func (e *TemplateNotFoundError) Error() string

type TemplateRenderer

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

TemplateRenderer handles template rendering

func NewTemplateRenderer

func NewTemplateRenderer(cfg *config.Config, i18nFuncs template.FuncMap) *TemplateRenderer

NewTemplateRenderer creates a new template renderer i18nFuncs provides translation functions (t, lang, isRTL, dir, languages) If nil, a fallback t function that returns the key is used

func (*TemplateRenderer) Render

func (tr *TemplateRenderer) Render(w io.Writer, name string, data interface{}) error

Render renders a template with the given data

type ThemeInfo

type ThemeInfo struct {
	Current   string // Current theme (light, dark, auto)
	ClassName string // CSS class name (theme-light, theme-dark, theme-auto)
	IsDark    bool   // True if effective theme is dark
	IsLight   bool   // True if effective theme is light
	IsAuto    bool   // True if auto mode
}

ThemeInfo holds theme metadata for template rendering

func GetThemeInfo

func GetThemeInfo(r *http.Request) ThemeInfo

GetThemeInfo returns complete theme information for template rendering

type TokenDisplay

type TokenDisplay struct {
	ID          int64
	Name        string
	Prefix      string
	Permissions []string
	LastUsed    string
	ExpiresAt   string
	Expired     bool
}

TokenDisplay represents token info for display

type TokenInfo

type TokenInfo struct {
	Type     TokenType
	OwnerID  int64  // admin.id, user.id, or org.id
	Prefix   string // First 8 chars for display
	Scope    string // global, read-write, read
	Username string // For user tokens, the associated username
	OrgSlug  string // For org tokens, the specific org slug
}

TokenInfo holds validated token information Per AI.md PART 11: Token validation

type TokenType

type TokenType int

TokenType represents the type of API token Per AI.md PART 11: Token prefixes (NON-NEGOTIABLE)

const (
	TokenTypeUnknown  TokenType = iota
	TokenTypeAdmin              // adm_ prefix
	TokenTypeUser               // usr_ prefix
	TokenTypeOrg                // org_ prefix
	TokenTypeAdminAgt           // adm_agt_ prefix (admin agent)
	TokenTypeUserAgt            // usr_agt_ prefix (user agent)
	TokenTypeOrgAgt             // org_agt_ prefix (org agent)
)

func GetTokenTypeFromContext

func GetTokenTypeFromContext(r *http.Request) TokenType

GetTokenTypeFromContext retrieves the token type from request context

type TorFeature

type TorFeature struct {
	Enabled  bool   `json:"enabled"`
	Running  bool   `json:"running"`
	Status   string `json:"status"`
	Hostname string `json:"hostname"`
}

TorFeature represents Tor status per AI.md PART 13

type TwoFactorPageData

type TwoFactorPageData struct {
	PageData
	Error          string
	SessionID      string
	RemainingKeys  int
	UseRecoveryKey bool
}

TwoFactorPageData represents data for 2FA pages

type UserPageData

type UserPageData struct {
	PageData
	User           *userpkg.User
	Error          string
	Success        string
	Sessions       []SessionDisplay
	Tokens         []TokenDisplay
	TwoFAEnabled   bool
	TwoFASetup     *userpkg.TOTPSetupResponse
	RecoveryKeys   []string
	RecoveryStats  *userpkg.RecoveryKeyStats
	CurrentSession int64
}

UserPageData represents data for user pages

Jump to

Keyboard shortcuts

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