admin

package
v0.0.0-...-95891f2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 37 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package admin — database_health.go defines the admin-local contracts the Database page's Health and Backups tabs render. Concrete implementations live in the app layer (over the boot health-check config and the backup/restore plugin services), so the admin package depends on neither — same pattern as DatabaseExplorer.

Package admin — database_service.go implements schema introspection and migration status for the admin database explorer page. Queries MariaDB information_schema for table/column/FK metadata and uses the plugin migration system to show pending migrations.

Package admin provides site-wide administration functionality. Admin routes require the site admin flag (users.is_admin) and provide user management, campaign oversight, and SMTP configuration access.

Index

Constants

View Source
const (
	AreaPeople    = "people"
	AreaCampaigns = "campaigns"
	AreaPackages  = "game-systems"
	AreaFeatures  = "features"
	AreaSecurity  = "security"
	AreaSite      = "site"
	AreaOther     = "other"
)

Activity areas mirror the admin menu so a filter reads like the sidebar.

View Source
const (
	WhenToday = "today"
	When7Days = "7d"
	When30    = "30d"
	WhenAll   = "all"
)

Time windows for the "when" filter.

View Source
const (
	DatabaseTabMigrations = "migrations"
	DatabaseTabHealth     = "health"
	DatabaseTabSchema     = "schema"
)

Tabs of the Database page. They appear as entries of the shared Health & diagnostics strip (components.AdminTabsHealth), whose hrefs must match databaseTabHref.

View Source
const (
	EventLoginSuccess           = "login.success"
	EventLoginFailed            = "login.failed"
	EventLogout                 = "logout"
	EventPasswordResetInitiated = "password.reset_initiated"
	EventPasswordResetCompleted = "password.reset_completed"
	EventAdminPrivilegeChanged  = "admin.privilege_changed"
	EventUserDisabled           = "admin.user_disabled"
	EventUserEnabled            = "admin.user_enabled"
	EventSessionTerminated      = "admin.session_terminated"
	EventForceLogout            = "admin.force_logout"
	EventDiagnosticsBatchRun    = "admin.diagnostics_batch_run"
	EventMediaUploaded          = "media.uploaded"
	EventMediaDeleted           = "media.deleted"
	EventMediaQuotaExceeded     = "media.quota_exceeded"
	EventAccountDeleted         = "account.deleted"
	EventTwoFactorEnabled       = "two_factor.enabled"
	EventTwoFactorDisabled      = "two_factor.disabled"
	EventTwoFactorCodesReplaced = "two_factor.codes_replaced"
	EventTwoFactorFailed        = "login.two_factor_failed"
	EventTwoFactorAdminOff      = "admin.two_factor_disabled"
	EventProviderSaved          = "admin.sign_in_provider_saved"
	EventVisitorAddressSaved    = "admin.visitor_address_saved"
	EventSignInLinked           = "sign_in.linked"
	EventSignInUnlinked         = "sign_in.unlinked"
	EventGuestJoined            = "guest.joined"
	EventGuestKept              = "guest.kept"
	EventGuestMerged            = "guest.merged"
	EventSessionSignedOut       = "account.session_signed_out"
	EventSignedOutEverywhere    = "account.signed_out_everywhere"
	EventAppDisconnected        = "account.app_disconnected"
)

Security event type constants follow the "resource.verb" pattern for consistent filtering and display grouping in the admin security dashboard.

View Source
const (
	SecurityTabOverview  = "overview"
	SecurityTabSessions  = "sessions"
	SecurityTabLog       = "log"
	SecurityTabSignup    = "signup"
	SecurityTabProvider  = "provider"
	SecurityTabAddresses = "addresses"
)

Tabs of the Sign-ins & sessions page. Each is a real link (?tab=…) so the page works without JavaScript and under hx-boost.

View Source
const MaxAdminNavPins = 6

MaxAdminNavPins bounds the pins: the sidebar block is a short list.

Variables

View Source
var ErrCheckupBusy = errors.New("a backup is already running")

ErrCheckupBusy is what a CheckupBackup returns when a backup is already running; the check-up then tries again on its next tick.

Functions

func ActivityAreaOf

func ActivityAreaOf(action string) string

ActivityAreaOf names the area an action belongs to; unknown actions are Other so a recorder added later still shows up under "All areas".

func EventTypeIcon

func EventTypeIcon(eventType string) string

EventTypeIcon returns a Font Awesome icon class for a security event type.

func EventTypeLabel

func EventTypeLabel(eventType string) string

EventTypeLabel returns a human-readable label for a security event type.

func IsReleaseVersion

func IsReleaseVersion(v string) bool

IsReleaseVersion reports whether v names a release rather than a commit, "unknown" or nothing. Only a release server is told about new releases.

func IsStableVersion

func IsStableVersion(v string) bool

IsStableVersion reports whether v is a plain release number such as "1.0.1" or "v1.0.1", with no pre-release suffix.

func NormalizeAdminNavPins

func NormalizeAdminNavPins(pins []string, allowed map[string]bool) ([]string, error)

NormalizeAdminNavPins checks pins against the admin pages that may be pinned (allowed holds item links, never Home) and returns them in order without repeats. An unknown link or more than MaxAdminNavPins distinct pins is refused rather than trimmed, so a caller never believes a pin was kept that was not.

func RegisterRoutes

func RegisterRoutes(e *echo.Echo, h *Handler, authService auth.AuthService, smtpHandler *smtp.Handler) *echo.Group

RegisterRoutes sets up all admin routes on the given Echo instance. Creates a /admin group with auth + site admin middleware, then registers sub-routes for dashboard, users, campaigns, and SMTP settings. Returns the admin group so other plugins can register additional admin routes.

Types

type APIAlertCounter

type APIAlertCounter interface {
	CountUnresolvedAPIAlerts(ctx context.Context) (int, error)
}

APIAlertCounter reports unresolved API security alerts for the Home page. A one-method interface so admin needs nothing from the sync API plugin.

type ActivityActor

type ActivityActor struct {
	ID   string
	Name string
}

ActivityActor is one person who has made a logged change, for the "who" menu.

type ActivityEntry

type ActivityEntry struct {
	ID          int64          `json:"id"`
	ActorUserID string         `json:"actorUserId,omitempty"`
	Action      string         `json:"action"` // "resource.verb", e.g. "user.admin_granted".
	TargetType  string         `json:"targetType,omitempty"`
	TargetID    string         `json:"targetId,omitempty"`
	TargetLabel string         `json:"targetLabel,omitempty"` // Name at the time, so the log survives deletes.
	Detail      map[string]any `json:"detail,omitempty"`
	CreatedAt   time.Time      `json:"createdAt"`

	// ActorName is joined from users for display; empty when the account is gone.
	ActorName string `json:"actorName,omitempty"`
}

ActivityEntry is one row of the site-wide admin change log. Unlike SecurityEvent (sign-in and session security) it records what an admin changed, so the Home page can answer "who changed what".

func (ActivityEntry) Area

func (e ActivityEntry) Area() string

Area is this entry's area key.

func (ActivityEntry) AreaMeta

func (e ActivityEntry) AreaMeta() activityArea

AreaMeta is this entry's area label and icon.

func (ActivityEntry) Sentence

func (e ActivityEntry) Sentence() string

Sentence renders "Mara made Theo an admin". An unknown action still reads acceptably so a recorder added later never shows a blank row.

type ActivityFilter

type ActivityFilter struct {
	ActorID string
	Area    string
	// Since is an inclusive lower bound on created_at; zero means no bound.
	Since time.Time
}

ActivityFilter narrows the change log. The zero value means everything.

func ResolveActivityFilter

func ResolveActivityFilter(q ActivityQuery, now time.Time) ActivityFilter

ResolveActivityFilter turns a query into a filter. "Today" is since UTC midnight because created_at is stored in UTC.

type ActivityQuery

type ActivityQuery struct {
	Actor, Area, When string
}

ActivityQuery is the raw, untrusted filter from the query string.

func (ActivityQuery) Normalize

func (q ActivityQuery) Normalize() ActivityQuery

Normalize drops unknown values to their defaults so a hand-edited URL never reaches the repository as an unexpected filter.

type ActivityRecorder

type ActivityRecorder interface {
	RecordActivity(ctx context.Context, actorUserID, action, targetType, targetID, targetLabel string)
}

ActivityRecorder is the write side of the admin change log. Handlers (and, through their own one-method copies of this interface, other plugins) depend on it rather than on the service, and it has no error return: a failed log write must never fail the admin action that already succeeded.

type ActivityRepository

type ActivityRepository interface {
	// Insert stores one entry; a zero CreatedAt is stamped with the current time.
	Insert(ctx context.Context, e *ActivityEntry) error

	// List returns entries matching the filter, newest first, with the actor's
	// display name joined in, plus the matching row count for pagination.
	List(ctx context.Context, f ActivityFilter, limit, offset int) ([]ActivityEntry, int, error)

	// Actors lists everyone with at least one logged change, by name.
	Actors(ctx context.Context) ([]ActivityActor, error)
}

ActivityRepository is the data-access contract for the admin change log.

func NewActivityRepository

func NewActivityRepository(db *sql.DB) ActivityRepository

NewActivityRepository creates the MariaDB-backed activity repository.

type ActivityService

type ActivityService interface {
	ActivityRecorder

	// Record validates and stores an entry, returning the storage error so
	// callers that care (tests, tools) can see it.
	Record(ctx context.Context, entry ActivityEntry) error

	// List returns one page (1-based) of entries matching the filter, newest
	// first, and the matching total.
	List(ctx context.Context, f ActivityFilter, page, perPage int) ([]ActivityEntry, int, error)

	// Actors lists the people who appear in the log, for the "who" menu.
	Actors(ctx context.Context) ([]ActivityActor, error)
}

ActivityService records and lists admin changes.

func NewActivityService

func NewActivityService(repo ActivityRepository) ActivityService

NewActivityService creates the activity service.

type AddonCounter

type AddonCounter interface {
	CountAddons(ctx context.Context) (int, error)
	CountFeatures(ctx context.Context) (int, error)
}

AddonCounter provides a count of registered addons for the admin dashboard. CountFeatures excludes module-category addons (game systems) which are shown on the Content Packs page instead.

type AddonUsageCounter

type AddonUsageCounter interface {
	CountCampaignsUsingAddon(ctx context.Context, addonSlug string) (int, error)
}

AddonUsageCounter provides campaign usage counts for addon slugs. Used by the system diagnostics page to show how many campaigns use each system.

type AdminNavPinRepository

type AdminNavPinRepository interface {
	// GetAdminNavPins returns the stored links in pin order; nil when none.
	GetAdminNavPins(ctx context.Context, userID string) ([]string, error)
	// SetAdminNavPins replaces the stored links; an empty list clears them.
	SetAdminNavPins(ctx context.Context, userID string, pins []string) error
}

AdminNavPinRepository stores each admin's pinned pages.

func NewAdminNavPinRepository

func NewAdminNavPinRepository(db *sql.DB) AdminNavPinRepository

NewAdminNavPinRepository builds the SQL-backed repository.

type AdminNavPinService

type AdminNavPinService interface {
	// Pins returns the admin's pins, with links that are no longer admin pages dropped.
	Pins(ctx context.Context, userID string) ([]string, error)
	// UpdatePins replaces the admin's pins with the full ordered list and
	// returns what was stored.
	UpdatePins(ctx context.Context, userID string, pins []string) ([]string, error)
}

AdminNavPinService owns the rules for an admin's pinned pages.

func NewAdminNavPinService

func NewAdminNavPinService(repo AdminNavPinRepository, pinnable []string) AdminNavPinService

NewAdminNavPinService builds the service. pinnable lists the admin page links that may be pinned; the sidebar's own data supplies it so this package does not keep a second copy that could drift from the menu.

type BackupArtifact

type BackupArtifact struct {
	Name       string
	SizeBytes  int64
	ModTime    time.Time
	Kind       string // "db", "media", "redis", "manifest", "pre-migrate", "other"
	PreMigrate bool   // automatic pre-migration backup (vs operator-triggered)
}

BackupArtifact is one file in the backup directory, surfaced on the Backups tab.

type BackupCheckResult

type BackupCheckResult struct {
	OK       bool      `json:"ok"`
	MadeNow  bool      `json:"madeNow,omitempty"`
	BackupAt time.Time `json:"backupAt,omitempty"`
	Problem  string    `json:"problem,omitempty"`
}

BackupCheckResult is the weekly read-back of a backup, as the backup plugin reports it through the CheckupBackup adapter.

type BackupInfo

type BackupInfo struct {
	Enabled        bool              // BackupDir configured
	Artifacts      []BackupArtifact  // recent files, newest-first
	Manifests      []RestoreManifest // restorable snapshots, newest-first
	LastPreMigrate *BackupArtifact   // most recent automatic pre-migration backup
	// LastRunFailed is whether the most recent backup run, by the button or
	// the daily schedule, did not finish. A failed run leaves no manifest, so
	// the files alone can't say this.
	LastRunFailed bool
	// ScheduleKnown is false when the daily schedule could not be read;
	// ScheduleOn is whether the daily backup is switched on.
	ScheduleKnown, ScheduleOn bool
}

BackupInfo aggregates everything the Backups tab needs.

type BackupLister

type BackupLister interface {
	BackupInfo(ctx context.Context) (BackupInfo, error)
}

BackupLister provides the Backups tab its data.

type CheckItem

type CheckItem struct {
	Key      string
	Title    string
	Detail   string
	State    CheckState
	FixLabel string
	FixHref  string
	FixPost  string
	FixVals  string
	// FixExternal opens FixHref in a new tab (a page outside the site).
	FixExternal bool
	KeepLabel   string
	KeepVals    string
}

CheckItem is one row of the check-up sheet. A row offers at most one fix: a link (FixHref) or, for a one-click change, a form post (FixPost with FixVals as hx-vals JSON). A row the host may rightly leave as it is also offers a quiet word (KeepLabel) that posts KeepVals to FixPost.

type CheckState

type CheckState string

CheckState is one check-up item's verdict.

const (
	CheckOK   CheckState = "ok"
	CheckWarn CheckState = "warn"
	CheckBad  CheckState = "bad"
)

Check-up verdicts. Bad is reserved for a backup that failed: it is the one thing that turns the shield red and puts the strip up at once.

type Checkup

type Checkup struct {
	Items     []CheckItem
	CheckedAt time.Time // zero when no full run has happened yet
	NextAt    time.Time
	Running   bool
	Now       time.Time
}

Checkup is the built check-up, ready to render.

func (Checkup) Open

func (c Checkup) Open() []CheckItem

Open returns the rows that are not ok.

func (Checkup) StripText

func (c Checkup) StripText() string

StripText is the reminder strip's sentence for open rows.

func (Checkup) Subtitle

func (c Checkup) Subtitle() string

Subtitle says when the check-up last ran and, when all is well, when it runs next.

func (Checkup) Title

func (c Checkup) Title() string

Title is the sheet's heading.

func (Checkup) Worst

func (c Checkup) Worst() CheckState

Worst is the shield's colour: bad beats warn beats ok.

type CheckupBackup

type CheckupBackup interface {
	CheckBackup(ctx context.Context) (BackupCheckResult, error)
}

CheckupBackup reads the newest backup back to prove it restorable, making one first when none is recent. Wired from the backup plugin in internal/app.

type CheckupDeps

type CheckupDeps struct {
	Store     CheckupStore
	Backup    CheckupBackup
	Chronicle ChronicleVersionChecker // nil: Chronicle's version is not checked
	// ChronicleCheckOn is the admin's switch for asking GitHub about
	// Chronicle's version; nil counts as on.
	ChronicleCheckOn func(ctx context.Context) bool
	Packages         PackageUpdateSource // nil: game systems are not checked
	Backups          BackupLister
	Registration     func(ctx context.Context) (string, error)
	EmailReady       func(ctx context.Context) bool
}

CheckupDeps is what the check-up reads. Registration and EmailReady come from the settings and SMTP services the admin handler already holds.

type CheckupRecord

type CheckupRecord struct {
	At        time.Time           `json:"at"`
	Backup    *BackupCheckResult  `json:"backup,omitempty"`
	Chronicle *VersionCheckResult `json:"chronicle,omitempty"`
}

CheckupRecord is the stored outcome of the last full check-up run.

type CheckupService

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

CheckupService runs the check-up and decides when it nags. "Remind me tomorrow" is the only snooze, and it never hides the shield's count.

func NewCheckupService

func NewCheckupService(deps CheckupDeps) *CheckupService

NewCheckupService builds the service.

func (*CheckupService) LastRecord

func (s *CheckupService) LastRecord(ctx context.Context) *CheckupRecord

LastRecord returns the stored last run, or nil when there is none.

func (*CheckupService) RunScheduler

func (s *CheckupService) RunScheduler(ctx context.Context)

RunScheduler starts the weekly check-up when it is due. Call it in its own goroutine; it returns when ctx ends.

func (*CheckupService) Running

func (s *CheckupService) Running() bool

Running reports whether a full check-up is in progress.

func (*CheckupService) SetSignupKeptOpen

func (s *CheckupService) SetSignupKeptOpen(ctx context.Context, kept bool) error

SetSignupKeptOpen records whether open sign-up is the host's choice. An admin saving "open" makes it one; saving any other mode clears it, so reopening later asks again.

func (*CheckupService) Snooze

func (s *CheckupService) Snooze(ctx context.Context, userID string) error

Snooze hides the peek and the strip from userID until this time tomorrow.

func (*CheckupService) Start

func (s *CheckupService) Start(ctx context.Context) bool

Start begins a full check-up in the background and reports whether it started (false: one is already running). The run outlives the request that asked for it; ctx should be the server's lifetime context.

func (*CheckupService) View

func (s *CheckupService) View(ctx context.Context, userID string, signedInAt time.Time, noPeek bool) CheckupView

View builds the check-up for userID, whose session began at signedInAt. A peek is recorded as it is handed out, so it happens once per sign-in whichever page it lands on. noPeek is for the shield's own refreshes.

type CheckupStore

type CheckupStore interface {
	Get(ctx context.Context, key string) (string, error)
	Set(ctx context.Context, key, value string) error
}

CheckupStore is the site settings key/value store. Get returns an apperror NotFound for a key never set.

type CheckupView

type CheckupView struct {
	Checkup
	// Peek opens the sheet by itself for a few seconds: once per sign-in.
	Peek bool
	// Strip puts the reminder strip under the top bar: at once for a failed
	// backup, or once rows have been open for a week.
	Strip bool
}

CheckupView is the check-up for one admin on one page load, with the decisions about nagging already made.

type ChronicleRelease

type ChronicleRelease struct {
	// Version is the release number without a leading "v", e.g. "1.0.1".
	Version string `json:"version"`
	// Tag is the git tag as published, e.g. "v1.0.1"; it builds the notes link.
	Tag string `json:"tag"`
	// Notes are the first lines of the release notes.
	Notes []string `json:"notes,omitempty"`
	// Security is true when the notes have a heading naming security fixes.
	Security bool `json:"security"`
}

ChronicleRelease is the newest published (non-draft, non-prerelease) Chronicle release, as the daily check found it.

type ChronicleReleaseSource

type ChronicleReleaseSource interface {
	LatestChronicleRelease(ctx context.Context) (*ChronicleRelease, error)
}

ChronicleReleaseSource looks up the newest published Chronicle release. It answers nil, nil when none is published. Wired from internal/app.

type ChronicleVersionChecker

type ChronicleVersionChecker interface {
	CheckChronicle(ctx context.Context) VersionCheckResult
}

ChronicleVersionChecker finds out whether a newer Chronicle is published.

type ColumnInfo

type ColumnInfo struct {
	Name     string  `json:"name"`
	Type     string  `json:"type"`
	Nullable bool    `json:"nullable"`
	Default  *string `json:"default"`
	Key      string  `json:"key"` // PRI, MUL, UNI, or ""
}

ColumnInfo describes a single table column.

type ConnectionRevoker

type ConnectionRevoker interface {
	RevokeUserEverywhere(userID string)
}

ConnectionRevoker is the narrow hub view this plugin needs: force-disconnect a user's sockets everywhere when their account is disabled — unlike other plugins, there's no single campaign to scope to.

type CoreMigrationStatus

type CoreMigrationStatus struct {
	Version  uint `json:"version"`  // current schema_migrations version (0 = fresh)
	Dirty    bool `json:"dirty"`    // a migration failed partway
	Highest  uint `json:"highest"`  // highest migration this build ships
	Expected uint `json:"expected"` // the startup health-check floor
	Pending  int  `json:"pending"`  // Highest - Version when behind, else 0
	Ahead    bool `json:"ahead"`    // DB version > Highest (downgrade/rollback)
}

CoreMigrationStatus describes the core (db/migrations) schema_migrations state relative to what this build ships. Surfaced on the admin Database page and the /admin/database/status JSON endpoint so an admin sees migration state without reading boot logs.

type DataHygieneData

type DataHygieneData struct {
	Stats           *DiskUsageStats
	OrphanedMedia   []OrphanedMediaItem
	OrphanedAPIKeys []OrphanedAPIKey
	StaleFiles      []StaleFile
	CSRFToken       string
	// ScanFailed is set when any scan errored, so an empty list is not read as
	// "nothing found".
	ScanFailed bool
}

DataHygieneData bundles all data for the hygiene dashboard page.

type DataHygieneScanner

type DataHygieneScanner interface {
	ScanOrphanedMedia(ctx context.Context) ([]OrphanedMediaItem, error)
	ScanOrphanedAPIKeys(ctx context.Context) ([]OrphanedAPIKey, error)
	ScanStaleFiles(ctx context.Context) ([]StaleFile, error)
	GetDiskUsageStats(ctx context.Context) (*DiskUsageStats, error)
	PurgeOrphanedAPIKeys(ctx context.Context) (int, error)
	PurgeStaleFiles(ctx context.Context) (int, error)
}

DataHygieneScanner detects and cleans up orphaned data across the system.

func NewHygieneService

func NewHygieneService(db *sql.DB, mediaRepo media.MediaRepository, mediaService media.MediaService, mediaPath string, secRepo SecurityEventRepository) DataHygieneScanner

NewHygieneService creates a data hygiene service.

type DatabaseExplorer

type DatabaseExplorer interface {
	// GetSchema returns all tables, columns, and foreign key relationships.
	GetSchema(ctx context.Context) (*DatabaseSchema, error)

	// GetMigrationStatus returns the migration status for each plugin.
	GetMigrationStatus(ctx context.Context) ([]PluginMigrationStatus, error)

	// GetCoreMigrationStatus returns the core schema_migrations state relative to
	// what this build ships (current version, dirty flag, pending count, and
	// whether the DB is AHEAD of the build — a downgrade/rollback).
	GetCoreMigrationStatus(ctx context.Context) (CoreMigrationStatus, error)

	// ApplyPendingMigrations runs all pending plugin migrations and returns results.
	ApplyPendingMigrations(ctx context.Context) ([]database.PluginMigrationResult, error)
}

DatabaseExplorer provides schema introspection and migration status for the admin database explorer page.

func NewDatabaseExplorer

func NewDatabaseExplorer(db *sql.DB, pluginHealth *database.PluginHealthRegistry, pluginSchemas []database.PluginSchema) DatabaseExplorer

NewDatabaseExplorer creates a new database explorer service.

type DatabaseSchema

type DatabaseSchema struct {
	Tables      []TableInfo      `json:"tables"`
	ForeignKeys []ForeignKeyInfo `json:"foreignKeys"`
}

DatabaseSchema holds the full schema graph for visualization.

type DiskUsageStats

type DiskUsageStats struct {
	TotalDiskBytes   int64
	TrackedDBBytes   int64
	OrphanMediaCount int
	OrphanMediaBytes int64
	OrphanAPIKeys    int
	StaleFileCount   int
	StaleFileBytes   int64
}

DiskUsageStats holds aggregate data hygiene statistics.

type EmptyResult

type EmptyResult struct {
	Campaigns int
	Batches   int
	// Failed counts items that could not be finished this run; they stay in
	// the Trash and the next run tries again.
	Failed int
}

EmptyResult says what a purge removed.

type ForeignKeyInfo

type ForeignKeyInfo struct {
	FromTable  string `json:"fromTable"`
	FromColumn string `json:"fromColumn"`
	ToTable    string `json:"toTable"`
	ToColumn   string `json:"toColumn"`
}

ForeignKeyInfo describes a foreign key relationship between two tables.

type Handler

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

Handler handles admin dashboard HTTP requests. Depends on other plugins' services via interfaces -- no direct repo access.

func NewHandler

func NewHandler(authRepo auth.UserRepository, campaignService campaigns.CampaignService, smtpService smtp.SMTPService) *Handler

NewHandler creates a new admin handler.

func (*Handler) Activity

func (h *Handler) Activity(c *echo.Context) error

Activity renders the filterable admin change log (GET /admin/activity).

func (*Handler) ApplyMigrationsAPI

func (h *Handler) ApplyMigrationsAPI(c *echo.Context) error

ApplyMigrationsAPI runs all pending plugin migrations (POST /admin/database/migrations/apply).

func (*Handler) Campaigns

func (h *Handler) Campaigns(c *echo.Context) error

Campaigns renders the campaign management page (GET /admin/campaigns).

func (*Handler) CheckupShield

func (h *Handler) CheckupShield(c *echo.Context) error

CheckupShield handles GET /admin/checkup: the top bar's shield and sheet, plus the reminder strip swapped in out of band. It may peek; the answers to Check now and Remind me tomorrow never do.

func (*Handler) Dashboard

func (h *Handler) Dashboard(c *echo.Context) error

Dashboard renders the admin overview page (GET /admin).

func (*Handler) DataHygiene

func (h *Handler) DataHygiene(c *echo.Context) error

DataHygiene renders the data hygiene dashboard (GET /admin/data-hygiene).

func (*Handler) Database

func (h *Handler) Database(c *echo.Context) error

Database renders the admin database explorer page (GET /admin/database).

func (*Handler) DatabaseSchemaAPI

func (h *Handler) DatabaseSchemaAPI(c *echo.Context) error

DatabaseSchemaAPI returns the full schema as JSON (GET /admin/database/schema). The D3 widget fetches this to render the interactive diagram.

func (*Handler) DatabaseStatusAPI

func (h *Handler) DatabaseStatusAPI(c *echo.Context) error

DatabaseStatusAPI returns core + plugin migration status as JSON (GET /admin/database/status). Usable by external monitoring/alerting as well as the admin page.

func (*Handler) DeleteCampaign

func (h *Handler) DeleteCampaign(c *echo.Context) error

DeleteCampaign moves a campaign to the Trash (DELETE /admin/campaigns/:id). Nothing is removed: the campaign vanishes for everyone and can be brought back from the Trash page until the retention is up.

func (*Handler) DeleteMedia

func (h *Handler) DeleteMedia(c *echo.Context) error

DeleteMedia deletes a media file (DELETE /admin/media/:fileID).

func (*Handler) DiagnosticsWorkspace

func (h *Handler) DiagnosticsWorkspace(c *echo.Context) error

DiagnosticsWorkspace renders the in-app operator AI workspace: the everyday questions, the checks in folds for picking by hand, and the hand-off to an outside AI. Read-only.

func (*Handler) DiagnosticsWorkspaceCompose

func (h *Handler) DiagnosticsWorkspaceCompose(c *echo.Context) error

DiagnosticsWorkspaceCompose turns the checks picked on the page into the same batch request an AI would paste, and shows the same review step for it. POST /admin/diagnostics/workspace/compose.

func (*Handler) DiagnosticsWorkspaceParse

func (h *Handler) DiagnosticsWorkspaceParse(c *echo.Context) error

DiagnosticsWorkspaceParse validates a pasted batch request against the diagnostic catalog and returns the review fragment (the human-approval gate). A malformed request is not an error response — it renders an inline message so the operator can fix the paste. POST /admin/diagnostics/workspace/parse.

func (*Handler) DiagnosticsWorkspaceRun

func (h *Handler) DiagnosticsWorkspaceRun(c *echo.Context) error

DiagnosticsWorkspaceRun re-parses the approved request (never trusting a client-built plan), executes the runnable read-only diagnostics, and returns the compact, secret-redacted result fragment. POST /admin/diagnostics/workspace/run.

func (*Handler) DisableTwoFactor

func (h *Handler) DisableTwoFactor(c *echo.Context) error

DisableTwoFactor switches two-factor off for a user who is locked out of it (PUT /admin/security/users/:id/two-factor/off).

func (*Handler) DisableUser

func (h *Handler) DisableUser(c *echo.Context) error

DisableUser disables a user account (PUT /admin/security/users/:id/disable).

func (*Handler) EmptyTrash

func (h *Handler) EmptyTrash(c *echo.Context) error

EmptyTrash removes everything in the Trash for good (DELETE /admin/trash). The route sits behind the password re-check, like every other admin action that cannot be undone.

func (*Handler) EnableUser

func (h *Handler) EnableUser(c *echo.Context) error

EnableUser re-enables a disabled user account (PUT /admin/security/users/:id/enable).

func (*Handler) ForceLogoutUser

func (h *Handler) ForceLogoutUser(c *echo.Context) error

ForceLogoutUser destroys all sessions for a user (POST /admin/security/users/:id/force-logout).

func (*Handler) HandOver

func (h *Handler) HandOver(c *echo.Context) error

HandOver gives the campaign to the chosen member (POST /admin/campaigns/:id/hand-over). The service re-checks every rule.

func (*Handler) HandoverPage

func (h *Handler) HandoverPage(c *echo.Context) error

HandoverPage shows who could take over a campaign whose owner has been away (GET /admin/campaigns/:id/hand-over). The list's row action asks for it over htmx, so that request is turned into a full page load.

func (*Handler) JoinCampaign

func (h *Handler) JoinCampaign(c *echo.Context) error

JoinCampaign adds the admin to a campaign with the selected role (POST /admin/campaigns/:id/join).

func (*Handler) LeaveCampaign

func (h *Handler) LeaveCampaign(c *echo.Context) error

LeaveCampaign removes the admin from a campaign (DELETE /admin/campaigns/:id/leave).

func (*Handler) PurgeOrphanedAPIKeysAPI

func (h *Handler) PurgeOrphanedAPIKeysAPI(c *echo.Context) error

PurgeOrphanedAPIKeysAPI handles DELETE /admin/data-hygiene/orphaned-api-keys.

func (*Handler) PurgeOrphanedMediaAPI

func (h *Handler) PurgeOrphanedMediaAPI(c *echo.Context) error

PurgeOrphanedMediaAPI handles DELETE /admin/data-hygiene/orphaned-media. The unused uploads move to the Trash as one clean-up that can be undone; the files are only removed when the Trash is emptied.

func (*Handler) PurgeStaleFilesAPI

func (h *Handler) PurgeStaleFilesAPI(c *echo.Context) error

PurgeStaleFilesAPI handles DELETE /admin/data-hygiene/stale-files.

func (*Handler) ReleaseNoticeLater

func (h *Handler) ReleaseNoticeLater(c *echo.Context) error

ReleaseNoticeLater handles POST /admin/release-notice/later: hide this version from the caller until a newer one is out. The empty answer swaps the notice away.

func (*Handler) RunCheckup

func (h *Handler) RunCheckup(c *echo.Context) error

RunCheckup handles POST /admin/checkup/run (Check now). The run goes on in the background; the answer is the shield showing it in progress.

func (*Handler) SaveLongTermTrash

func (h *Handler) SaveLongTermTrash(c *echo.Context) error

SaveLongTermTrash saves how long removed pages and players' old values stay packed (POST /admin/trash/long-term). Each pack keeps the date it was given, so no choice removes anything early and no password re-check is needed.

func (*Handler) SaveSignInProvider

func (h *Handler) SaveSignInProvider(c *echo.Context) error

SaveSignInProvider stores the provider setting (POST /admin/security/sign-in-provider). Reauth-gated.

func (*Handler) SaveSiteLook

func (h *Handler) SaveSiteLook(c *echo.Context) error

SaveSiteLook handles POST /admin/site-look: the whole form in one request, uploads included, so nothing is saved by half.

func (*Handler) SaveTrashRetention

func (h *Handler) SaveTrashRetention(c *echo.Context) error

SaveTrashRetention saves how long deleted things are kept (POST /admin/trash/retention).

func (*Handler) SaveUpdateCheck

func (h *Handler) SaveUpdateCheck(c *echo.Context) error

SaveUpdateCheck handles POST /admin/security/update-check: turn the calls to GitHub about Chronicle's own version on or off. Reauth-gated like the rest of the Security page, since turning it off silences news of security fixes.

func (*Handler) SaveVisitorAddresses

func (h *Handler) SaveVisitorAddresses(c *echo.Context) error

SaveVisitorAddresses stores which header Chronicle believes for the visitor's address (POST /admin/security/visitor-addresses). Reauth-gated: it decides what every per-address rate limit and audit row records. The change applies to this running server at once.

func (*Handler) Security

func (h *Handler) Security(c *echo.Context) error

Security renders the security dashboard page (GET /admin/security).

func (*Handler) SetAPIAlertCounter

func (h *Handler) SetAPIAlertCounter(counter APIAlertCounter)

SetAPIAlertCounter wires the unresolved API alert count for the Home list.

func (*Handler) SetActivityService

func (h *Handler) SetActivityService(svc ActivityService)

SetActivityService wires the admin change log.

func (*Handler) SetAddonCounter

func (h *Handler) SetAddonCounter(counter AddonCounter)

SetAddonCounter sets the addon counter for the dashboard extension count.

func (*Handler) SetAddonUsageCounter

func (h *Handler) SetAddonUsageCounter(counter AddonUsageCounter)

SetAddonUsageCounter wires the addon usage counter for system diagnostics.

func (*Handler) SetBackupLister

func (h *Handler) SetBackupLister(lister BackupLister)

SetBackupLister injects the backup/restore data source for the Database > Backups tab. Optional — when nil the Backups tab shows "unavailable".

func (*Handler) SetBaseURL

func (h *Handler) SetBaseURL(url string)

SetBaseURL sets the public-facing base URL for the Foundry module admin page.

func (*Handler) SetCheckupService

func (h *Handler) SetCheckupService(svc *CheckupService, runCtx context.Context)

SetCheckupService wires the site check-up. runCtx is the server's lifetime context: a run started by Check now outlives the request that asked.

func (*Handler) SetDatabaseExplorer

func (h *Handler) SetDatabaseExplorer(explorer DatabaseExplorer)

SetDatabaseExplorer wires the database explorer for the schema visualization page.

func (*Handler) SetHealthChecker

func (h *Handler) SetHealthChecker(checker HealthChecker)

SetHealthChecker injects the on-demand health-check runner for the Database > Health tab. Optional — when nil the Health tab shows "unavailable".

func (*Handler) SetHygieneScanner

func (h *Handler) SetHygieneScanner(scanner DataHygieneScanner)

SetHygieneScanner wires the data hygiene scanner for the hygiene dashboard.

func (*Handler) SetLongTermTrashSizer

func (h *Handler) SetLongTermTrashSizer(s LongTermTrashSizer)

SetLongTermTrashSizer wires the estimate; without it the setting shows no sizes.

func (*Handler) SetMediaDeps

func (h *Handler) SetMediaDeps(repo media.MediaRepository, svc media.MediaService, resolveMaxUploadSize func() int64)

SetMediaDeps sets the media dependencies for the storage admin page. Called after media plugin is wired to avoid constructor bloat.

resolveMaxUploadSize is a function so the storage page reflects the LIVE limit configured by the admin (matching what the body-limit middleware actually enforces) rather than the value frozen at startup. Reports surface the resolver's result; if nil, the page falls back to the legacy maxUploadSize field.

func (*Handler) SetNavPinService

func (h *Handler) SetNavPinService(svc AdminNavPinService)

SetNavPinService wires the admin's own sidebar pins.

func (*Handler) SetPendingCounter

func (h *Handler) SetPendingCounter(counter PendingCounter)

SetPendingCounter wires the pending submission counter for the dashboard.

func (*Handler) SetReleaseNoticeService

func (h *Handler) SetReleaseNoticeService(svc *ReleaseNoticeService)

SetReleaseNoticeService wires the new-version notice. Left unset, Home shows no notice and the Security page no switch.

func (*Handler) SetSecurityService

func (h *Handler) SetSecurityService(svc SecurityService)

SetSecurityService wires the security service for the security dashboard.

func (*Handler) SetSettingsDeps

func (h *Handler) SetSettingsDeps(svc settings.SettingsService)

SetSettingsDeps sets the settings service for the combined storage page.

func (*Handler) SetSiteLookService

func (h *Handler) SetSiteLookService(svc SiteLookService)

SetSiteLookService wires the Site look service. Called after the settings and media services exist.

func (*Handler) SetTrashService

func (h *Handler) SetTrashService(svc TrashService)

SetTrashService wires the site Trash.

func (*Handler) SetUpdateHealth

func (h *Handler) SetUpdateHealth(r UpdateHealthReporter)

SetUpdateHealth wires update health into Site admin Home.

func (*Handler) SiteLook

func (h *Handler) SiteLook(c *echo.Context) error

SiteLook handles GET /admin/site-look.

func (*Handler) SnoozeCheckup

func (h *Handler) SnoozeCheckup(c *echo.Context) error

SnoozeCheckup handles POST /admin/checkup/snooze (Remind me tomorrow).

func (*Handler) Status

func (h *Handler) Status(c *echo.Context) error

Status renders the status strip's figures (GET /admin/status), loaded by every admin page after it is shown.

func (*Handler) Storage

func (h *Handler) Storage(c *echo.Context) error

Storage renders the combined storage management page (GET /admin/storage). Loads storage stats, files, global settings, overrides, and user/campaign lists for the dropdown selectors.

func (*Handler) Systems

func (h *Handler) Systems(c *echo.Context) error

Systems renders the system diagnostics page (GET /admin/systems).

func (*Handler) TerminateSession

func (h *Handler) TerminateSession(c *echo.Context) error

TerminateSession destroys a specific session by its token hash (DELETE /admin/security/sessions/:hash). Uses hash-based lookup to avoid exposing raw session tokens in admin HTML.

func (*Handler) TestSignInProvider

func (h *Handler) TestSignInProvider(c *echo.Context) error

TestSignInProvider sends the admin through a sign-in that only reports back (POST /admin/security/sign-in-provider/test). Reauth-gated.

func (*Handler) ToggleAdmin

func (h *Handler) ToggleAdmin(c *echo.Context) error

ToggleAdmin toggles a user's is_admin flag (PUT /admin/users/:id/admin).

func (*Handler) Trash

func (h *Handler) Trash(c *echo.Context) error

Trash renders the Trash page (GET /admin/trash).

func (*Handler) UndoTrashedBatch

func (h *Handler) UndoTrashedBatch(c *echo.Context) error

UndoTrashedBatch brings a file clean-up back (POST /admin/trash/batches/:id/undo).

func (*Handler) UndoTrashedCampaign

func (h *Handler) UndoTrashedCampaign(c *echo.Context) error

UndoTrashedCampaign brings a deleted campaign back (POST /admin/trash/campaigns/:id/undo).

func (*Handler) UpdateNavPins

func (h *Handler) UpdateNavPins(c *echo.Context) error

UpdateNavPins replaces the signed-in admin's pinned pages with the full ordered list in the body ({"pins": ["/admin/users"]}) and answers with the re-rendered admin nav block, so the page can swap it in. The client reads the current list from the page before it sends.

func (*Handler) UpdateRegistrationMode

func (h *Handler) UpdateRegistrationMode(c *echo.Context) error

UpdateRegistrationMode persists the site registration gate (POST /admin/security/registration). Reauth-gated as a security-sensitive change.

func (*Handler) Users

func (h *Handler) Users(c *echo.Context) error

Users renders the user management page (GET /admin/users).

type HealthChecker

type HealthChecker interface {
	RunChecks() *HealthResult
}

HealthChecker runs the startup health checks on demand for the Health tab.

type HealthResult

type HealthResult = database.HealthCheckResult

HealthResult is the structured health-check result the Health tab renders. Aliased so the handler + templates use a package-local name (no direct dependency on the database package from those files).

type HomeGroup

type HomeGroup struct {
	Label string
	Tiles []HomeTile
}

HomeGroup is one labelled row of tiles, in menu order.

type HomeTile

type HomeTile struct {
	Big       string
	Label     string
	Line      string
	Href      string
	Attention bool
}

HomeTile is one Admin Home tile. Every tile has the same shape so the page scans: a big figure or status word, the menu label, one plain line, and a dot when something needs a look.

type LongTermTrashSizer

type LongTermTrashSizer interface {
	MonthlyBytes(ctx context.Context) (bytes int64, known bool, err error)
}

LongTermTrashSizer says about how much one month of packed player changes takes on this site, for the Long-term trash setting's estimate. known is false when nothing has been recorded yet.

type MigrationHistory

type MigrationHistory struct {
	Version   int    `json:"version"`
	AppliedAt string `json:"appliedAt"` // RFC3339
}

MigrationHistory records when a specific migration version was applied.

type NeedsItem

type NeedsItem struct {
	Text   string
	Count  int
	Href   string
	Button string
	// Detail is an optional second line in small mono type, such as the
	// last error of a changed feature that fails.
	Detail string
	// contains filtered or unexported fields
}

NeedsItem is one row of the Home "Needs you" list: a plain sentence, how many things it covers, and the single page that fixes it.

func (NeedsItem) Urgent

func (it NeedsItem) Urgent() bool

Urgent is whether the item is a fault (something failed, the database is behind, a security alert) rather than a chore; Home shows faults in red, ahead of the amber chores.

type OrphanedAPIKey

type OrphanedAPIKey struct {
	ID         int
	KeyPrefix  string
	Name       string
	CampaignID string
	CreatedAt  time.Time
}

OrphanedAPIKey represents an API key whose campaign no longer exists.

type OrphanedMediaItem

type OrphanedMediaItem struct {
	ID        string
	Filename  string
	MimeType  string
	FileSize  int64
	CreatedAt time.Time
	// Referenced indicates whether any entity still references this file
	// via image_path or entry_html. Referenced files cannot be purged.
	Referenced bool
}

OrphanedMediaItem represents a media file with no campaign association that is not an avatar or backdrop.

type PackageUpdateSource

type PackageUpdateSource interface {
	CheckAllForUpdates(ctx context.Context) error
	CountUpdatesReady(ctx context.Context) (int, error)
}

PackageUpdateSource refreshes the game systems' release lists and counts the updates ready to install. Wired from the packages plugin.

type PendingCounter

type PendingCounter interface {
	CountPendingSubmissions(ctx context.Context) (int, error)
}

PendingCounter provides a count of pending package submissions for the dashboard.

type PluginMigrationStatus

type PluginMigrationStatus struct {
	Slug           string             `json:"slug"`
	CurrentVersion int                `json:"currentVersion"`
	LatestVersion  int                `json:"latestVersion"`
	Pending        int                `json:"pending"`
	Healthy        bool               `json:"healthy"`
	Error          string             `json:"error,omitempty"`
	History        []MigrationHistory `json:"history,omitempty"`
}

PluginMigrationStatus describes the migration state of a single plugin.

type ReleaseNotice

type ReleaseNotice struct {
	Version  string // the newer release, e.g. "1.0.1"
	Running  string // what this server runs, e.g. "1.0.0"
	Security bool
	WhatsNew string // "" when the notes had nothing to quote
	NotesURL string
	GuideURL string
}

ReleaseNotice is the notice as the dashboard renders it.

type ReleaseNoticeService

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

ReleaseNoticeService runs the daily release check and builds the notice.

func NewReleaseNoticeService

func NewReleaseNoticeService(store CheckupStore, source ChronicleReleaseSource, running func() string) *ReleaseNoticeService

NewReleaseNoticeService builds the service. running reports this server's version (hostinfo.Version); source may be nil, which never checks.

func (*ReleaseNoticeService) CheckOn

func (s *ReleaseNoticeService) CheckOn(ctx context.Context) bool

CheckOn reports whether Chronicle may ask GitHub about its own newer versions. It is on unless an admin turned it off.

func (*ReleaseNoticeService) Later

func (s *ReleaseNoticeService) Later(ctx context.Context, userID, version string) error

Later hides version, and anything older, from userID until a newer release is out. Only a plain release number is stored.

func (*ReleaseNoticeService) Notice

func (s *ReleaseNoticeService) Notice(ctx context.Context, userID string) *ReleaseNotice

Notice is what userID sees on the dashboard, or nil. It never calls GitHub and never fails a page: anything it can't read means no notice.

func (*ReleaseNoticeService) RunScheduler

func (s *ReleaseNoticeService) RunScheduler(ctx context.Context)

RunScheduler checks once a day. Call it in its own goroutine; it returns when ctx ends. The first check waits for the first tick, so a restart loop can't turn into a burst of calls to GitHub.

func (*ReleaseNoticeService) SetCheckOn

func (s *ReleaseNoticeService) SetCheckOn(ctx context.Context, on bool) error

SetCheckOn turns the check on or off. Turning it on checks at the next tick, since the last result may be days old.

type RestoreManifest

type RestoreManifest struct {
	Name             string
	ChronicleVersion string
	MigrationVersion string
	ModTime          time.Time
	ParseError       string
	// PreUpdate marks the automatic capture taken before an update changed
	// the database, rather than a backup someone or the schedule ran.
	PreUpdate bool
}

RestoreManifest is one restorable snapshot manifest, surfaced on the Backups tab.

type SecurityEvent

type SecurityEvent struct {
	ID        int64          `json:"id"`
	EventType string         `json:"eventType"`
	UserID    string         `json:"userId,omitempty"`
	ActorID   string         `json:"actorId,omitempty"` // Admin who performed the action.
	IPAddress string         `json:"ipAddress"`
	UserAgent string         `json:"userAgent,omitempty"`
	Details   map[string]any `json:"details,omitempty"`
	CreatedAt time.Time      `json:"createdAt"`

	// Joined fields for display (not stored in security_events table).
	UserName  string `json:"userName,omitempty"`
	ActorName string `json:"actorName,omitempty"`
}

SecurityEvent represents a single site-wide security event. Unlike campaign audit entries, these track authentication and admin security actions across the entire Chronicle instance.

type SecurityEventRepository

type SecurityEventRepository interface {
	// Log inserts a new security event into the database.
	Log(ctx context.Context, event *SecurityEvent) error

	// List returns paginated security events, most recent first. Optional
	// eventType filter narrows results to a specific event type.
	List(ctx context.Context, eventType string, limit, offset int) ([]SecurityEvent, int, error)

	// GetStats returns aggregate security statistics for the dashboard.
	GetStats(ctx context.Context) (*SecurityStats, error)

	// CountRecentByIP returns the number of events from a specific IP in
	// the given duration. Useful for detecting brute-force attacks.
	CountRecentByIP(ctx context.Context, ip string, eventType string, since time.Duration) (int, error)
}

SecurityEventRepository defines the data access contract for security events.

func NewSecurityEventRepository

func NewSecurityEventRepository(db *sql.DB) SecurityEventRepository

NewSecurityEventRepository creates a new repository backed by the given DB.

type SecurityPageData

type SecurityPageData struct {
	// Tab is the open tab, already whitelisted (see normalizeSecurityTab).
	Tab string
	// WatchItems feeds the overview's "Worth a look" list.
	WatchItems  []WatchItem
	Stats       *SecurityStats
	Events      []SecurityEvent
	TotalEvents int
	EventFilter string
	Page        int
	PerPage     int
	Sessions    []auth.SessionInfo
	CSRFToken   string
	// RegistrationMode is the current site registration gate ("open", "invite",
	// "closed"). Rendered as a select on the security page (B-R4).
	RegistrationMode string
	// Addresses is the Visitor addresses check, read only on its tab.
	Addresses VisitorAddressesData
	// Provider is the sign-in provider setting, read only on its tab.
	Provider       auth.OIDCSettings
	ProviderFailed bool
	// StatsFailed, EventsFailed and SessionsFailed mark sections whose read
	// errored, so the page says so instead of rendering an empty state.
	StatsFailed    bool
	EventsFailed   bool
	SessionsFailed bool
	// UpdateCheckShown shows the new-version check switch; UpdateCheckOn is
	// its state.
	UpdateCheckShown, UpdateCheckOn bool
}

SecurityPageData holds all data needed for the security dashboard page.

type SecurityService

type SecurityService interface {
	// LogEvent records a security event. Fire-and-forget friendly.
	LogEvent(ctx context.Context, eventType, userID, actorID, ip, userAgent string, details map[string]any) error

	// ListEvents returns paginated security events, optionally filtered by type.
	ListEvents(ctx context.Context, eventType string, page int) ([]SecurityEvent, int, error)

	// GetStats returns aggregate security statistics for the dashboard.
	GetStats(ctx context.Context) (*SecurityStats, error)

	// GetActiveSessions returns all active sessions from the session store.
	GetActiveSessions(ctx context.Context) ([]auth.SessionInfo, error)

	// TerminateSessionByHash destroys a specific session identified by the
	// SHA-256 hash of its token. Avoids exposing raw tokens in admin UI.
	TerminateSessionByHash(ctx context.Context, tokenHash string) error

	// ForceLogoutUser destroys all sessions for a user.
	ForceLogoutUser(ctx context.Context, userID string) (int, error)

	// DisableUser disables a user account and destroys all their sessions.
	DisableUser(ctx context.Context, userID string) error

	// EnableUser re-enables a previously disabled user account.
	EnableUser(ctx context.Context, userID string) error

	// DisableTwoFactor switches two-factor off for someone locked out of it.
	DisableTwoFactor(ctx context.Context, userID string) error

	// Sign-in provider: read, save, and start a test sign-in as the admin.
	SignInProvider(ctx context.Context) (auth.OIDCSettings, error)
	SaveSignInProvider(ctx context.Context, in auth.OIDCSettingsInput) error
	BeginProviderTest(ctx context.Context, adminID string) (authURL, state string, err error)

	// SetConnectionRevoker injects the hub's revocation surface, used by
	// DisableUser. Late-bound and nil-safe: a disabled account is already
	// logged out and refused on its next login regardless.
	SetConnectionRevoker(cr ConnectionRevoker)
}

SecurityService handles security event management for the admin dashboard. It provides logging, querying, session management, and user account actions.

func NewSecurityService

func NewSecurityService(repo SecurityEventRepository, authRepo auth.UserRepository, authService auth.AuthService) SecurityService

NewSecurityService creates a new security service.

type SecurityStats

type SecurityStats struct {
	TotalEvents         int `json:"totalEvents"`
	FailedLogins24h     int `json:"failedLogins24h"`
	SuccessfulLogins24h int `json:"successfulLogins24h"`
	ActiveSessions      int `json:"activeSessions"`
	DisabledUsers       int `json:"disabledUsers"`
	UniqueIPs24h        int `json:"uniqueIps24h"`
}

SecurityStats holds aggregate statistics for the admin security dashboard.

type SiteLookPageData

type SiteLookPageData struct {
	Saved     sitelook.Settings
	Draft     sitelook.Settings
	Error     string
	Notice    string
	CSRFToken string
}

SiteLookPageData is everything the Site look page renders. Draft is what the form shows (the saved look, or the rejected submission with its error); Saved is what the site currently uses.

type SiteLookService

type SiteLookService interface {
	// Get returns the saved site look.
	Get(ctx context.Context) (sitelook.Settings, error)
	// Save applies a submission: validates and stores new pictures, saves the
	// look, and tidies pictures the save replaced. It returns what was stored.
	Save(ctx context.Context, userID string, sub SiteLookSubmission) (sitelook.Settings, error)
}

SiteLookService owns the rules of the Site look page.

func NewSiteLookService

func NewSiteLookService(settings SiteLookSettings, media SiteMedia) SiteLookService

NewSiteLookService builds the service. media may be nil, in which case uploads are refused but the text settings still save.

type SiteLookSettings

type SiteLookSettings interface {
	GetSiteLook(ctx context.Context) (sitelook.Settings, error)
	UpdateSiteLook(ctx context.Context, in sitelook.Settings) (sitelook.Settings, error)
}

SiteLookSettings is the slice of the settings service the Site look page needs. The admin plugin reaches site_settings only through this interface.

type SiteLookSubmission

type SiteLookSubmission struct {
	Draft         sitelook.Settings // Name, Look, Background, Welcome, LogoAsFavicon.
	Picture       *SiteLookUpload
	RemovePicture bool
}

SiteLookSubmission is one Save of the Site look page: the text choices, and for each picture either a new upload, a removal, or neither (keep what is saved). Picture names are never taken from the request, only from uploads this service stored, so a request cannot point the site at someone else's file.

type SiteLookUpload

type SiteLookUpload struct {
	Name string
	Data []byte
}

SiteLookUpload is one file from the form.

type SiteMedia

type SiteMedia interface {
	// StoreSitePicture saves an already-validated image and returns its
	// stored filename.
	StoreSitePicture(ctx context.Context, userID string, data []byte, originalName, mimeType string) (string, error)
	// OwnsSitePicture reports whether filename is a site picture stored by
	// StoreSitePicture, as opposed to any other media file.
	OwnsSitePicture(ctx context.Context, filename string) (bool, error)
	// DeleteSitePicture removes filename only if it is a site picture; any
	// other file is left alone and is not an error.
	DeleteSitePicture(ctx context.Context, filename string) error
}

SiteMedia stores the site's logo and sign-in picture. The files belong to no campaign and are public (the sign-in page is shown to visitors), so the implementation stamps them in a way no campaign or avatar file can match.

type StaleFile

type StaleFile struct {
	Path    string
	Size    int64
	ModTime time.Time
}

StaleFile represents a file on disk that has no corresponding DB record.

type StatusFigures

type StatusFigures struct {
	Sessions                   int
	BackupKnown, BackupEnabled bool
	BackupFailed               bool   // the last backup run did not finish
	BackupAge                  string // "" when there is no backup yet
}

StatusFigures are the live figures on the Site admin status strip. Sessions is -1 when it could not be read.

type StoragePageData

type StoragePageData struct {
	Stats          *media.StorageStats
	Files          []media.AdminMediaFile
	TotalFiles     int
	Page           int
	PerPage        int
	MaxUploadSize  int64
	Global         *settings.GlobalStorageLimits
	UserLimits     []settings.UserStorageLimitWithName
	CampaignLimits []settings.CampaignStorageLimitWithName
	Users          []auth.User
	Campaigns      []campaigns.Campaign
	CSRFToken      string
	// LimitsTab selects the limits view (?tab=limits) instead of the file list.
	LimitsTab bool
	// TrashRetentionDays is how long deleted world pages stay in a Trash.
	TrashRetentionDays int
}

StoragePageData holds all data needed for the combined storage management page.

type TableInfo

type TableInfo struct {
	Name        string       `json:"name"`
	RowCount    int64        `json:"rowCount"`
	DataSizeKB  int64        `json:"dataSizeKB"`
	ColumnCount int          `json:"columnCount"`
	Columns     []ColumnInfo `json:"columns"`
	Plugin      string       `json:"plugin"`
}

TableInfo describes a single database table.

type TrashActor

type TrashActor struct {
	UserID string
	Name   string
}

TrashActor is who did the deleting, for the "deleted by" copy. Empty for a system action.

type TrashBatch

type TrashBatch struct {
	ID    string
	Kind  string
	Label string // what the files are, e.g. "pictures" or "files"
	Items int
	Bytes int64
	State string
	// DeletedBy / DeletedByName are who ran the clean-up; the name is a copy
	// so the Trash still reads right after the account is gone.
	DeletedBy     string
	DeletedByName string
	CreatedAt     time.Time
}

TrashBatch is one file clean-up waiting in the Trash.

type TrashBatchRepository

type TrashBatchRepository interface {
	Create(ctx context.Context, b *TrashBatch) error
	SetTotals(ctx context.Context, id string, items int, bytes int64) error
	Get(ctx context.Context, id string) (*TrashBatch, error)
	List(ctx context.Context) ([]TrashBatch, error)
	// Claim moves a batch from one state to another and reports whether this
	// call made the move. A non-zero olderThan adds created_at < olderThan to
	// the same statement, so a purge run's age check cannot go stale between
	// listing and claiming.
	Claim(ctx context.Context, id, from, to string, olderThan time.Time) (bool, error)
	Delete(ctx context.Context, id string) error
}

TrashBatchRepository owns the trash_batches table. The files themselves are marked and restored through the media service, not here.

func NewTrashBatchRepository

func NewTrashBatchRepository(db *sql.DB) TrashBatchRepository

NewTrashBatchRepository creates the MariaDB trash batch repository.

type TrashEntry

type TrashEntry struct {
	Kind TrashKind
	ID   string
	// Title is the row's heading, e.g. "Campaign: Shattered Coast" or
	// "Files clean-up: 42 unused pictures, 180 MB".
	Title string
	// Who is "deleted by alex" for a campaign; empty for a clean-up.
	Who string
	// When is "3 days ago"; Empties is "empties in 27 days".
	When    string
	Empties string
	// Emptying is true while the final delete is under way; Undo is hidden.
	Emptying  bool
	DeletedAt time.Time
}

TrashEntry is one row of the Trash page, already phrased for display.

type TrashKind

type TrashKind string

TrashKind says what a Trash row holds.

const (
	TrashCampaign TrashKind = "campaign"
	TrashFiles    TrashKind = "files"
)

type TrashOverview

type TrashOverview struct {
	Entries       []TrashEntry
	RetentionDays int
}

TrashOverview is everything the Trash page shows.

type TrashRetention

type TrashRetention interface {
	SiteTrashRetentionDays(ctx context.Context) (int, error)
}

TrashRetention reads the retention setting.

type TrashService

type TrashService interface {
	// Overview lists what is waiting, newest first, with phrased dates.
	Overview(ctx context.Context) (*TrashOverview, error)
	// TrashUnusedUploads moves every unused, campaignless upload into one
	// Trash batch. It returns nil when there was nothing to move.
	TrashUnusedUploads(ctx context.Context, actor TrashActor) (*TrashBatch, error)
	// UndoCampaign and UndoBatch bring one item back. They fail with Not
	// Found when the item is gone or its final delete has begun.
	UndoCampaign(ctx context.Context, campaignID string) (name string, err error)
	UndoBatch(ctx context.Context, batchID string) (*TrashBatch, error)
	// EmptyNow removes everything in the Trash for good, whatever its age.
	EmptyNow(ctx context.Context) (EmptyResult, error)
	// PurgeDue removes only what has waited out the retention, and finishes
	// anything a previous run left half done.
	PurgeDue(ctx context.Context) (EmptyResult, error)
	// RetentionDays is the setting the purger obeys.
	// It fails when the setting cannot be read, so nothing is removed on a guess.
	RetentionDays(ctx context.Context) (int, error)
	// StartPurger runs PurgeDue now and then every hour until ctx ends.
	StartPurger(ctx context.Context)
}

TrashService runs the site Trash.

func NewTrashService

NewTrashService wires the Trash. retention may be nil, which means the default period.

type TrashedCampaigns

type TrashedCampaigns interface {
	ListTrashed(ctx context.Context) ([]campaigns.TrashedCampaign, error)
	RestoreFromTrash(ctx context.Context, campaignID string) error
	ListPurgeDue(ctx context.Context, cutoff time.Time, all bool) ([]string, error)
	PurgeTrashed(ctx context.Context, campaignID string, olderThan time.Time) (bool, error)
}

TrashedCampaigns is the part of the campaigns service the Trash needs.

type TrashedFiles

type TrashedFiles interface {
	TrashFiles(ctx context.Context, batchID string, ids []string) (count int, bytes int64, err error)
	RestoreTrashedFiles(ctx context.Context, batchID string) (int, error)
	ListTrashedFileIDs(ctx context.Context, batchID string) ([]string, error)
	PurgeTrashedFile(ctx context.Context, batchID, fileID string) error
}

TrashedFiles is the part of the media service the Trash needs.

type UnusedUploadFinder

type UnusedUploadFinder interface {
	ScanOrphanedMedia(ctx context.Context) ([]OrphanedMediaItem, error)
}

UnusedUploadFinder lists the uploads a clean-up would move; the data hygiene scanner is the one place that knows what counts as unused.

type UpdateHealthReporter

type UpdateHealthReporter interface {
	Report(ctx context.Context) ([]updatehealth.Status, error)
}

UpdateHealthReporter reports where each feature the running release changed stands: failing, not used yet, still counting or passed.

type UpdateHealthView

type UpdateHealthView struct {
	Passed   []updatehealth.Status
	Counting int
}

UpdateHealthView is what Home shows under Needs you about the changed features that need nobody: the ones that passed, and how many are still being counted.

func (UpdateHealthView) Line

func (v UpdateHealthView) Line() string

Line is the quiet sentence for the view.

type VersionCheckResult

type VersionCheckResult struct {
	Known      bool   `json:"known"`
	Behind     int    `json:"behind,omitempty"`
	CompareURL string `json:"compareUrl,omitempty"`
	Problem    string `json:"problem,omitempty"`
}

VersionCheckResult says how far the running Chronicle is behind the newest published one. Known is false when that could not be found out; Problem then says why, and the check-up treats it as a shrug, not a fault.

type VisitorAddressesData

type VisitorAddressesData struct {
	Diagnosis middleware.ClientIPDiagnosis
	Trusted   []string
	Warnings  []string
}

VisitorAddressesData feeds the Visitor addresses section of the Security page: the setting, the trusted proxies in use, and how this very request was read, so an admin can see whether their proxy is set up as chosen.

type WatchItem

type WatchItem struct {
	Title  string
	Detail string
}

WatchItem is one line of the overview's "Worth a look" list.

Jump to

Keyboard shortcuts

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