handlers

package
v0.0.0-...-faf1238 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 76 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 handlers provides HTTP request handlers for the API.

Package handlers provides HTTP handlers used by the Charon backend API.

It exposes Gin-based handler implementations for resources such as certificates, proxy hosts, users, notifications, backups, and system configuration. This package wires services to HTTP endpoints and performs request validation, response formatting, and basic error handling.

Index

Constants

View Source
const (
	// EmergencyTokenEnvVar is the environment variable name for the emergency token
	EmergencyTokenEnvVar = "CHARON_EMERGENCY_TOKEN"

	// EmergencyTokenHeader is the HTTP header name for the emergency token
	EmergencyTokenHeader = "X-Emergency-Token"

	// MinTokenLength is the minimum required length for the emergency token
	MinTokenLength = 32
)
View Source
const EmergencyResetReplyBudget = 2*proxyApplyTimeout + 15*time.Second

EmergencyResetReplyBudget bounds how long an emergency reset may take to answer: the wait for an apply lock held by another apply, the reset's own apply, its throttle wait and the writes. The reset extends its write deadline by this budget so the reply is not cut off by the Tier 2 server's write timeout.

Variables

This section is empty.

Functions

func CheckMountedImport

func CheckMountedImport(db *gorm.DB, mountPath, caddyBinary, importDir string) error

CheckMountedImport checks for mounted Caddyfile on startup.

func GetTemplateDB

func GetTemplateDB() (*gorm.DB, error)

GetTemplateDB returns the pre-migrated template database. Tests can use this to copy the schema instead of running AutoMigrate each time.

func HealthHandler

func HealthHandler(c *gin.Context)

HealthHandler responds with basic service metadata for uptime checks.

func LimitSmallJSONBody

func LimitSmallJSONBody() gin.HandlerFunc

LimitSmallJSONBody caps the request body of a small JSON route at maxSmallJSONBodyBytes. Routes outside this package use it.

func MaskPassword

func MaskPassword(password string) string

MaskPassword masks the password for display.

func MaskPasswordForTest

func MaskPasswordForTest(password string) string

MaskPasswordForTest is an alias for testing.

func OpenTestDB

func OpenTestDB(t *testing.T) *gorm.DB

Opens a SQLite in-memory DB unique per test and applies a busy timeout and WAL journal mode to reduce SQLITE locking during parallel tests.

func OpenTestDBWithMigrations

func OpenTestDBWithMigrations(t *testing.T) *gorm.DB

OpenTestDBWithMigrations creates a SQLite in-memory DB and runs AutoMigrate for all commonly used models. This is faster than individual test migrations because it uses the template database schema when available.

Types

type AcceptInviteRequest

type AcceptInviteRequest struct {
	Token    string `json:"token" binding:"required"`
	Name     string `json:"name" binding:"required"`
	Password string `json:"password" binding:"required,min=8"`
}

AcceptInviteRequest represents the request body for accepting an invite.

type AccessListHandler

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

AccessListHandler handles access list API requests.

func NewAccessListHandler

func NewAccessListHandler(db *gorm.DB) *AccessListHandler

NewAccessListHandler creates a new AccessListHandler without proxy apply, for callers that only manage lists.

func NewAccessListHandlerWithDeps

func NewAccessListHandlerWithDeps(db *gorm.DB, caddyManager CaddyConfigManager) *AccessListHandler

NewAccessListHandlerWithDeps creates an AccessListHandler that re-applies the proxy config when an edit reaches a list that hosts use.

func (*AccessListHandler) Create

func (h *AccessListHandler) Create(c *gin.Context)

Create handles POST /api/v1/access-lists

func (*AccessListHandler) Delete

func (h *AccessListHandler) Delete(c *gin.Context)

Delete handles DELETE /api/v1/access-lists/:id

func (*AccessListHandler) Get

func (h *AccessListHandler) Get(c *gin.Context)

Get handles GET /api/v1/access-lists/:id

func (*AccessListHandler) GetTemplates

func (h *AccessListHandler) GetTemplates(c *gin.Context)

GetTemplates handles GET /api/v1/access-lists/templates

func (*AccessListHandler) List

func (h *AccessListHandler) List(c *gin.Context)

List handles GET /api/v1/access-lists

func (*AccessListHandler) SelfCheck

func (h *AccessListHandler) SelfCheck(c *gin.Context)

SelfCheck handles POST /api/v1/access-lists/self-check. It evaluates the posted draft for the address the caller connects from, using the same evaluation as the tester and the proxy. Nothing is saved. Admin only.

func (*AccessListHandler) SetGeoIPService

func (h *AccessListHandler) SetGeoIPService(geoipSvc *services.GeoIPService)

SetGeoIPService sets the GeoIP service for geo-based ACL lookups.

func (*AccessListHandler) TestIP

func (h *AccessListHandler) TestIP(c *gin.Context)

TestIP handles POST /api/v1/access-lists/:id/test

func (*AccessListHandler) Update

func (h *AccessListHandler) Update(c *gin.Context)

Update handles PUT /api/v1/access-lists/:id

func (*AccessListHandler) WithACLMode

func (h *AccessListHandler) WithACLMode(mode string) *AccessListHandler

WithACLMode sets the static access-control mode the management lock-out guard reads when no runtime switch is stored.

type AccessListSelfCheckResponse

type AccessListSelfCheckResponse struct {
	IPAddress      string `json:"ip_address"`
	CountryCode    string `json:"country_code"`
	Allowed        bool   `json:"allowed"`
	AdminExempt    bool   `json:"admin_exempt"`
	GeoIPAvailable bool   `json:"geoip_available"`
	Reason         string `json:"reason"`
}

AccessListSelfCheckResponse is the decision the proxy would make for the caller's current address under an unsaved access list draft. reason is one of the services.Reason* identifiers.

type AckRequest

type AckRequest struct {
	Action string `json:"action" binding:"required,oneof=dismiss_temporary dismiss_permanent"`
	OptOut bool   `json:"opt_out"`
}

AckRequest is the body of POST /changelog/ack.

type AlertsHandler

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

AlertsHandler serves the active alerts shown by the notification bell.

func NewAlertsHandler

func NewAlertsHandler(svc *alerts.Service) *AlertsHandler

NewAlertsHandler returns a handler that lists the active alerts of svc.

func (*AlertsHandler) List

func (h *AlertsHandler) List(c *gin.Context)

List returns the active alerts computed at request time. It always answers 200.

type AssetConfig

type AssetConfig struct {
	FormField      string // multipart field name, e.g. "logo" or "banner"
	URLSettingKey  string // e.g. "ui.logo_url" or "ui.banner_url"
	TypeSettingKey string // e.g. "ui.logo_type" or "ui.banner_type"
	FileBaseName   string // e.g. "logo" or "banner" (extension appended at runtime)
}

AssetConfig parameterizes a specific image asset type.

type AuditLogHandler

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

AuditLogHandler handles audit log API requests.

func NewAuditLogHandler

func NewAuditLogHandler(securityService *services.SecurityService) *AuditLogHandler

NewAuditLogHandler creates a new audit log handler.

func (*AuditLogHandler) Get

func (h *AuditLogHandler) Get(c *gin.Context)

Get handles GET /api/v1/audit-logs/:uuid Returns a single audit log entry.

func (*AuditLogHandler) List

func (h *AuditLogHandler) List(c *gin.Context)

List handles GET /api/v1/audit-logs Returns audit logs with pagination and filtering.

func (*AuditLogHandler) ListByProvider

func (h *AuditLogHandler) ListByProvider(c *gin.Context)

ListByProvider handles GET /api/v1/dns-providers/:id/audit-logs Returns audit logs for a specific DNS provider.

type AuthHandler

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

func NewAuthHandler

func NewAuthHandler(authService *services.AuthService, trustedProxies []string) *AuthHandler

func NewAuthHandlerWithDB

func NewAuthHandlerWithDB(authService *services.AuthService, db *gorm.DB, trustedProxies []string) *AuthHandler

NewAuthHandlerWithDB creates an AuthHandler with database access for forward auth.

func (*AuthHandler) ChangePassword

func (h *AuthHandler) ChangePassword(c *gin.Context)

func (*AuthHandler) CheckHostAccess

func (h *AuthHandler) CheckHostAccess(c *gin.Context)

CheckHostAccess checks if the current user can access a specific host.

func (*AuthHandler) GetAccessibleHosts

func (h *AuthHandler) GetAccessibleHosts(c *gin.Context)

GetAccessibleHosts returns the list of proxy hosts the authenticated user can access.

func (*AuthHandler) Login

func (h *AuthHandler) Login(c *gin.Context)

func (*AuthHandler) Logout

func (h *AuthHandler) Logout(c *gin.Context)

func (*AuthHandler) Me

func (h *AuthHandler) Me(c *gin.Context)

func (*AuthHandler) Refresh

func (h *AuthHandler) Refresh(c *gin.Context)

Refresh creates a new token for the authenticated user. Must be called with a valid existing token. Supports long-running test sessions by allowing token refresh before expiry.

func (*AuthHandler) Verify

func (h *AuthHandler) Verify(c *gin.Context)

Verify is the forward auth endpoint for Caddy. It validates the user's session and checks access permissions for the requested host. Used by Caddy's forward_auth directive.

Expected headers from Caddy:

  • X-Forwarded-Host: The original host being accessed
  • X-Forwarded-Uri: The original URI being accessed

Response headers on success (200):

  • X-Forwarded-User: The user's email
  • X-Forwarded-Groups: The user's role (for future RBAC)

Response on failure:

  • 401: Not authenticated (redirect to login)
  • 403: Authenticated but not authorized for this host

func (*AuthHandler) VerifyStatus

func (h *AuthHandler) VerifyStatus(c *gin.Context)

VerifyStatus returns the current auth status without triggering a redirect. Useful for frontend to check if user is logged in.

type BackupHandler

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

func NewBackupHandler

func NewBackupHandler(service *services.BackupService) *BackupHandler

func NewBackupHandlerWithDeps

func NewBackupHandlerWithDeps(service *services.BackupService, securityService *services.SecurityService, db *gorm.DB) *BackupHandler

func (*BackupHandler) Create

func (h *BackupHandler) Create(c *gin.Context)

Create handles POST /api/v1/backups (admin). Body is optional (spec §3.3.1); when encrypt is requested without a passphrase, both settings defaults and an explicit 400 are reasonable — we require the caller to supply one explicitly rather than silently falling back to a stored scheduled passphrase, since manual encryption is a per-request secret (spec §3.6).

Async job contract (docs/plans/current_spec.md — Async Backup/Restore Jobs, §3.2.1/§3.5): the archive-creation pipeline now runs in a tracked background goroutine (services.BackupService.StartCreateBackupJob) so this handler returns as soon as the job row exists — 202 Accepted with {job_id, type, status} — instead of blocking for the full duration and risking the client's 30s axios timeout aborting the request client-side (NS_BINDING_ABORTED) on a large data directory. Poll GET /api/v1/backups/jobs/:job_id (GetJob) for progress/completion.

func (*BackupHandler) Delete

func (h *BackupHandler) Delete(c *gin.Context)

Delete handles DELETE /api/v1/backups/:filename (admin). Also removes the BackupRecord and any BackupRemoteCopy rows (best-effort, logged only).

func (*BackupHandler) Download

func (h *BackupHandler) Download(c *gin.Context)

Download handles GET /api/v1/backups/:filename/download. Admin-gated (changed from management in v1 — a backup contains the full database including password hashes and cert private keys, spec §3.9).

func (*BackupHandler) GetJob

func (h *BackupHandler) GetJob(c *gin.Context)

GetJob handles GET /api/v1/backups/jobs/:job_id (admin, spec §3.2.3) — polled by the frontend while a create/restore job started by Create/ Restore is pending/running.

func (*BackupHandler) GetSettings

func (h *BackupHandler) GetSettings(c *gin.Context)

GetSettings handles GET /api/v1/backups/settings (management, spec §3.3.2).

func (*BackupHandler) List

func (h *BackupHandler) List(c *gin.Context)

List returns the backup history, reconciling the filesystem scan with any persisted BackupRecord (spec §3.3.1). Files on disk without a record (pre-upgrade backups) are listed as legacy manual/v1 entries; records whose file has disappeared are marked Status "deleted" so a future list no longer references them.

func (*BackupHandler) Restore

func (h *BackupHandler) Restore(c *gin.Context)

Restore handles POST /api/v1/backups/:filename/restore (admin), starting the full V->S->A->R->F safe-restore pipeline as a tracked background job (spec §3.2.2/§3.5 — same async-job contract as Create; see its doc comment above). Returns 202 Accepted with {job_id, type, status}; a nonexistent/typo'd filename still gets a synchronous 404, unchanged from before this plan (services.ErrBackupNotFound, spec §3.3.1).

func (*BackupHandler) UpdateSettings

func (h *BackupHandler) UpdateSettings(c *gin.Context)

UpdateSettings handles PUT /api/v1/backups/settings (admin, spec §3.3.2). Every field is optional (partial update); validation and the reschedule side effect are entirely owned by services.BackupService.UpdateSettings.

func (*BackupHandler) Upload

func (h *BackupHandler) Upload(c *gin.Context)

Upload handles POST /api/v1/backups/upload (admin, multipart) — accepts a v2 (.zip/.zip.age), legacy v1 (.zip), or raw v0 SQLite (.db) file, validates it, and persists it under a server-generated filename (spec §3.3.2, §3.10). Client-supplied filenames are discarded entirely.

func (*BackupHandler) Validate

func (h *BackupHandler) Validate(c *gin.Context)

Validate handles POST /api/v1/backups/:filename/validate (admin) — a dry-run of the V1-V6 validation steps (spec §3.3.2, §3.5). Nothing is mutated.

type BackupRemoteHandler

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

BackupRemoteHandler exposes remote storage target CRUD and connection testing (spec §3.3.2). Every route is admin-gated (see the auth policy table in spec §3.3): hostnames/usernames/bucket names are sensitive even with secrets omitted, so this is not management-level like plain backup listing.

func NewBackupRemoteHandler

func NewBackupRemoteHandler(service *services.BackupRemoteService) *BackupRemoteHandler

func (*BackupRemoteHandler) Create

func (h *BackupRemoteHandler) Create(c *gin.Context)

Create handles POST /api/v1/backups/remote-targets (admin).

func (*BackupRemoteHandler) Delete

func (h *BackupRemoteHandler) Delete(c *gin.Context)

Delete handles DELETE /api/v1/backups/remote-targets/:uuid (admin).

func (*BackupRemoteHandler) List

func (h *BackupRemoteHandler) List(c *gin.Context)

List handles GET /api/v1/backups/remote-targets (admin).

func (*BackupRemoteHandler) OAuthCallback

func (h *BackupRemoteHandler) OAuthCallback(c *gin.Context)

OAuthCallback handles GET /api/v1/backups/remote-targets/oauth/:provider/callback.

SECURITY: this route is deliberately registered OUTSIDE RequireManagementAccess (see routes.go) — the browser arrives here directly from Dropbox/Google with no Charon session at all, so a session/JWT check here cannot succeed and is not the actual control. Its entire security rests on the single-use, time-bound `state` CSRF token issued by OAuthStart and consumed below (spec §3.8, R3) — never add an auth check to this handler; it is unreachable in the flow this route exists to serve.

func (*BackupRemoteHandler) OAuthDisconnect

func (h *BackupRemoteHandler) OAuthDisconnect(c *gin.Context)

OAuthDisconnect handles POST /api/v1/backups/remote-targets/:uuid/oauth/disconnect (admin).

func (*BackupRemoteHandler) OAuthStart

func (h *BackupRemoteHandler) OAuthStart(c *gin.Context)

OAuthStart handles POST /api/v1/backups/remote-targets/:uuid/oauth/start (admin). Issues a fresh CSRF state token and returns the provider's authorize URL (spec §3.3/R3).

func (*BackupRemoteHandler) Test

func (h *BackupRemoteHandler) Test(c *gin.Context)

Test handles POST /api/v1/backups/remote-targets/:uuid/test (admin).

func (*BackupRemoteHandler) TestDraft

func (h *BackupRemoteHandler) TestDraft(c *gin.Context)

TestDraft handles POST /api/v1/backups/remote-targets/test-draft (admin). It is the stateless counterpart of Test: unlike Test, it never looks up a persisted RemoteStorageTarget, so it can run SFTP host-key discovery against a draft config the user hasn't saved yet (spec §3.7). Only type "sftp" is supported — S3 has no host-key-pinning discovery step, so draft-testing an S3 config already works via the create/update SSRF validation and needs no stateless endpoint.

remotestorage.DiscoverSFTPHostKey never attempts authentication (it aborts the SSH handshake as soon as the host key is offered) and applies the same SSRF policy as every other remote-target entry point before dialing — see TestBackupRemoteHandler_TestDraft_NeverAuthenticates and TestBackupRemoteHandler_TestDraft_SSRFRejected.

func (*BackupRemoteHandler) Update

func (h *BackupRemoteHandler) Update(c *gin.Context)

Update handles PUT /api/v1/backups/remote-targets/:uuid (admin). Secret fields left empty in the request mean "keep existing" (spec §3.3.2).

type BackupServiceInterface

type BackupServiceInterface interface {
	CreateAutomaticBackup(kind string) (*models.BackupRecord, error)
	ListBackups() ([]services.BackupFile, error)
	DeleteBackup(filename string) error
	GetBackupPath(filename string) (string, error)
	RestoreBackup(filename string) error
	GetAvailableSpace() (int64, error)
}

BackupServiceInterface defines the contract for backup service operations

type BanIPRequest

type BanIPRequest struct {
	IP       string `json:"ip"`
	Duration string `json:"duration"`
	Reason   string `json:"reason"`
}

BanIPRequest represents the request body for banning an IP or a range

type BannerHandler

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

BannerHandler wraps ImageUploadHandler for the banner asset.

func NewBannerHandler

func NewBannerHandler(db *gorm.DB, dataDir string) *BannerHandler

NewBannerHandler creates a new BannerHandler.

func (*BannerHandler) DeleteBanner

func (h *BannerHandler) DeleteBanner(c *gin.Context)

DeleteBanner handles DELETE /api/v1/settings/banner. Clears banner settings from DB and removes the uploaded file.

func (*BannerHandler) UploadBanner

func (h *BannerHandler) UploadBanner(c *gin.Context)

UploadBanner handles POST /api/v1/settings/banner. Accepts multipart form with field "banner" (image/png, image/jpeg, image/webp only). SVG uploads are explicitly rejected — too many XSS vectors to sanitize inline. Validates MIME via server-side byte sniffing (does NOT trust multipart Content-Type). Max size 2MB enforced via MaxBytesReader before any bytes are read.

type BouncerInfo

type BouncerInfo struct {
	Name       string `json:"name"`
	KeyPreview string `json:"key_preview"` // First 4 + last 3 chars
	KeySource  string `json:"key_source"`  // "env_var" | "file" | "memory" | "none"
	FilePath   string `json:"file_path"`
	Registered bool   `json:"registered"`
	// Registration is "registered", "not_registered" or "unknown"; Registered is true only for "registered".
	Registration registrationState `json:"registration"`
}

BouncerInfo represents the bouncer key information for UI display.

type BrowserOriginRefresher

type BrowserOriginRefresher interface {
	Refresh() error
}

BrowserOriginRefresher rebuilds the cross-origin check after the public address setting changes.

type BulkUpdateSecurityHeadersRequest

type BulkUpdateSecurityHeadersRequest struct {
	HostUUIDs               []string `json:"host_uuids" binding:"required"`
	SecurityHeaderProfileID *uint    `json:"security_header_profile_id"` // nil means remove profile
}

BulkUpdateSecurityHeadersRequest represents the request body for bulk security header updates.

type CacheInvalidator

type CacheInvalidator interface {
	InvalidateCache()
}

CacheInvalidator interface for invalidating security settings cache

type CaddyConfigManager

type CaddyConfigManager interface {
	ApplyConfig(ctx context.Context) error
}

CaddyConfigManager interface for triggering Caddy config reload

type CerberusLogsHandler

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

CerberusLogsHandler handles WebSocket connections for streaming security logs.

func NewCerberusLogsHandler

func NewCerberusLogsHandler(watcher *services.LogWatcher, tracker *services.WebSocketTracker) *CerberusLogsHandler

NewCerberusLogsHandler creates a new handler for Cerberus security log streaming.

func (*CerberusLogsHandler) LiveLogs

func (h *CerberusLogsHandler) LiveLogs(c *gin.Context)

LiveLogs handles WebSocket connections for Cerberus security log streaming. It upgrades the HTTP connection to WebSocket, subscribes to the LogWatcher, and streams SecurityLogEntry as JSON to connected clients.

Query parameters for filtering:

  • source: filter by source (waf, crowdsec, ratelimit, acl, normal)
  • blocked_only: only show blocked requests (true/false)
  • level: filter by log level (info, warn, error)
  • ip: filter by client IP (partial match)
  • host: filter by host (partial match)

func (*CerberusLogsHandler) WithOriginPolicy

WithOriginPolicy wires the configured public origin and the trusted-proxy list into the WebSocket origin check.

func (*CerberusLogsHandler) WithStreamQuota

WithStreamQuota caps the live streams this handler admits per user and in total.

type CertificateHandler

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

func (*CertificateHandler) BulkDelete

func (h *CertificateHandler) BulkDelete(c *gin.Context)

BulkDelete removes several certificates by UUID. One backup covers the whole batch and is taken before any deletion. Per-certificate failures are reported in the response and do not stop the remaining deletions.

func (*CertificateHandler) Delete

func (h *CertificateHandler) Delete(c *gin.Context)

func (*CertificateHandler) Export

func (h *CertificateHandler) Export(c *gin.Context)

func (*CertificateHandler) Get

func (h *CertificateHandler) Get(c *gin.Context)

func (*CertificateHandler) List

func (h *CertificateHandler) List(c *gin.Context)

func (*CertificateHandler) SetDB

func (h *CertificateHandler) SetDB(db *gorm.DB)

SetDB sets the database connection for user lookups (export re-auth).

func (*CertificateHandler) SetPasswordAttemptGuard

func (h *CertificateHandler) SetPasswordAttemptGuard(g PasswordAttemptGuard)

SetPasswordAttemptGuard charges private-key export password checks to the sign-in budget.

func (*CertificateHandler) Update

func (h *CertificateHandler) Update(c *gin.Context)

func (*CertificateHandler) Upload

func (h *CertificateHandler) Upload(c *gin.Context)

func (*CertificateHandler) Validate

func (h *CertificateHandler) Validate(c *gin.Context)

type ChangePasswordRequest

type ChangePasswordRequest struct {
	OldPassword string `json:"old_password" binding:"required"`
	NewPassword string `json:"new_password" binding:"required,min=8"`
}

type ChangelogHandler

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

ChangelogHandler serves the "What's New" changelog: the per-user unseen-entries status check, the full browsable history, and the two self-service dismiss/opt-in mutations. All four routes are self-service-on-your-own-user-row, registered under the `protected` group (see routes.go) — RolePassthrough users are rejected explicitly via rejectPassthrough, matching GetProfile/UpdateProfile/RegenerateAPIKey.

func NewChangelogHandler

func NewChangelogHandler(db *gorm.DB, svc *changelog.Service) *ChangelogHandler

NewChangelogHandler constructs a ChangelogHandler.

func (*ChangelogHandler) Ack

func (h *ChangelogHandler) Ack(c *gin.Context)

Ack records the user's response to the changelog modal. dismiss_permanent advances LastSeenVersion to the bare SemVer form of the running version so the modal won't reappear for these entries. It never moves LastSeenVersion backwards, and an unversioned build writes nothing. dismiss_temporary leaves it untouched so the modal reappears next login. Either action may also set ChangelogOptOut via opt_out.

func (*ChangelogHandler) All

func (h *ChangelogHandler) All(c *gin.Context)

All returns the full changelog history, independent of the caller's last-seen version — used by the Settings "revisit" browse mode.

func (*ChangelogHandler) OptIn

func (h *ChangelogHandler) OptIn(c *gin.Context)

OptIn re-enables changelog notifications for the current user (clears ChangelogOptOut). Used by the Appearance Settings toggle.

func (*ChangelogHandler) Status

func (h *ChangelogHandler) Status(c *gin.Context)

Status returns whether the current user has unseen changelog entries, and the entries themselves. Always show_changelog=false for dev builds, opted-out users, and when there are zero unseen entries — the modal must never render empty.

type CharonAccessList

type CharonAccessList struct {
	UUID             string `json:"uuid"`
	Name             string `json:"name"`
	Description      string `json:"description"`
	Type             string `json:"type"`
	IPRules          string `json:"ip_rules"`
	CountryCodes     string `json:"country_codes"`
	LocalNetworkOnly bool   `json:"local_network_only"`
	Enabled          bool   `json:"enabled"`
}

CharonAccessList represents an access list in Charon export format.

type CharonDNSRecord

type CharonDNSRecord struct {
	UUID       string `json:"uuid"`
	Name       string `json:"name"`
	Type       string `json:"type"`
	Value      string `json:"value"`
	TTL        int    `json:"ttl"`
	ProviderID uint   `json:"provider_id"`
}

CharonDNSRecord represents a DNS record in Charon export format.

type CharonExport

type CharonExport struct {
	Version     string             `json:"version"`
	ExportedAt  time.Time          `json:"exported_at"`
	ProxyHosts  []CharonProxyHost  `json:"proxy_hosts"`
	AccessLists []CharonAccessList `json:"access_lists"`
	DNSRecords  []CharonDNSRecord  `json:"dns_records"`
}

CharonExport represents the top-level structure of a Charon export file.

type CharonProxyHost

type CharonProxyHost struct {
	UUID             string `json:"uuid"`
	Name             string `json:"name"`
	DomainNames      string `json:"domain_names"`
	ForwardScheme    string `json:"forward_scheme"`
	ForwardHost      string `json:"forward_host"`
	ForwardPort      int    `json:"forward_port"`
	SSLForced        bool   `json:"ssl_forced"`
	HTTP2Support     bool   `json:"http2_support"`
	HSTSEnabled      bool   `json:"hsts_enabled"`
	HSTSSubdomains   bool   `json:"hsts_subdomains"`
	BlockExploits    bool   `json:"block_exploits"`
	WebsocketSupport bool   `json:"websocket_support"`
	Application      string `json:"application"`
	Enabled          bool   `json:"enabled"`
	AdvancedConfig   string `json:"advanced_config"`
	WAFDisabled      bool   `json:"waf_disabled"`
	UseDNSChallenge  bool   `json:"use_dns_challenge"`
}

CharonProxyHost represents a proxy host in Charon export format.

type CommandExecutor

type CommandExecutor interface {
	Execute(ctx context.Context, name string, args ...string) ([]byte, error)
}

CommandExecutor abstracts command execution for testing.

type ConfigArchiveValidator

type ConfigArchiveValidator struct {
	MaxSize             int64    // Maximum compressed size (50MB default)
	MaxUncompressed     int64    // Maximum uncompressed size (500MB default)
	MaxCompressionRatio float64  // Maximum compression ratio (100x default)
	RequiredFiles       []string // Required files (config.yaml minimum)
}

ConfigArchiveValidator validates CrowdSec configuration archives.

func (*ConfigArchiveValidator) Validate

func (v *ConfigArchiveValidator) Validate(path string) error

Validate performs comprehensive validation of the archive.

type CreateChallengeRequest

type CreateChallengeRequest struct {
	FQDN  string `json:"fqdn" binding:"required"`
	Token string `json:"token"`
	Value string `json:"value" binding:"required"`
}

CreateChallengeRequest represents the request to create a manual challenge.

type CreateDecisionRequest

type CreateDecisionRequest struct {
	IP      string `json:"ip" binding:"required"`
	Action  string `json:"action" binding:"required"`
	Host    string `json:"host,omitempty"`
	RuleID  string `json:"rule_id,omitempty"`
	Details string `json:"details,omitempty"`
}

CreateDecisionRequest is the client-facing DTO for manual decision creation. Enrichment fields (Scenario, Country, ExpiresAt) are system-populated and deliberately excluded to prevent clients from injecting arbitrary values.

type CreateMonitorRequest

type CreateMonitorRequest struct {
	Name       string `json:"name" binding:"required"`
	URL        string `json:"url" binding:"required"`
	Type       string `json:"type" binding:"required,oneof=http tcp https"`
	Interval   int    `json:"interval"`
	MaxRetries int    `json:"max_retries"`
}

CreateMonitorRequest represents the JSON payload for creating a new monitor

type CreateUserRequest

type CreateUserRequest struct {
	Email          string `json:"email" binding:"required,email"`
	Name           string `json:"name" binding:"required"`
	Password       string `json:"password" binding:"required,min=8"`
	Role           string `json:"role"`
	PermissionMode string `json:"permission_mode"`
	PermittedHosts []uint `json:"permitted_hosts"`
}

CreateUserRequest represents the request body for creating a user.

type CredentialHandler

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

CredentialHandler handles HTTP requests for DNS provider credentials.

func NewCredentialHandler

func NewCredentialHandler(credentialService services.CredentialService, dnsProviderService services.DNSProviderService) *CredentialHandler

NewCredentialHandler creates a new credential handler.

func (*CredentialHandler) Create

func (h *CredentialHandler) Create(c *gin.Context)

Create handles POST /api/v1/dns-providers/:id/credentials

func (*CredentialHandler) Delete

func (h *CredentialHandler) Delete(c *gin.Context)

Delete handles DELETE /api/v1/dns-providers/:id/credentials/:cred_id

func (*CredentialHandler) EnableMultiCredentials

func (h *CredentialHandler) EnableMultiCredentials(c *gin.Context)

EnableMultiCredentials handles POST /api/v1/dns-providers/:id/enable-multi-credentials

func (*CredentialHandler) Get

func (h *CredentialHandler) Get(c *gin.Context)

Get handles GET /api/v1/dns-providers/:id/credentials/:cred_id

func (*CredentialHandler) List

func (h *CredentialHandler) List(c *gin.Context)

List handles GET /api/v1/dns-providers/:id/credentials

func (*CredentialHandler) Test

func (h *CredentialHandler) Test(c *gin.Context)

Test handles POST /api/v1/dns-providers/:id/credentials/:cred_id/test

func (*CredentialHandler) Update

func (h *CredentialHandler) Update(c *gin.Context)

Update handles PUT /api/v1/dns-providers/:id/credentials/:cred_id

type CrowdSecDecision

type CrowdSecDecision struct {
	ID        int64     `json:"id"`
	Origin    string    `json:"origin"`
	Type      string    `json:"type"`
	Scope     string    `json:"scope"`
	Value     string    `json:"value"`
	Duration  string    `json:"duration"`
	Scenario  string    `json:"scenario"`
	CreatedAt time.Time `json:"created_at"`
	Until     string    `json:"until,omitempty"`
}

CrowdSecDecision represents a ban decision from CrowdSec

type CrowdsecBusyError

type CrowdsecBusyError struct {
	JobID string
}

CrowdsecBusyError reports that a Start or Stop was refused because another change holds the engine. JobID names the background install when one is the cause; it is empty for every other holder, and for a second Start or Stop.

func (*CrowdsecBusyError) Error

func (e *CrowdsecBusyError) Error() string

type CrowdsecExecutor

type CrowdsecExecutor interface {
	Start(ctx context.Context, binPath, configDir string) (int, error)
	Stop(ctx context.Context, configDir string) error
	Status(ctx context.Context, configDir string) (running bool, pid int, err error)
}

CrowdsecExecutor abstracts starting/stopping CrowdSec so tests can mock it.

type CrowdsecHandler

type CrowdsecHandler struct {
	DB           *gorm.DB
	Executor     CrowdsecExecutor
	CmdExec      CommandExecutor
	BinPath      string
	DataDir      string
	Hub          *crowdsec.HubService
	Console      *crowdsec.ConsoleEnrollmentService
	Security     *services.SecurityService
	WhitelistSvc *services.CrowdSecWhitelistService

	LAPIMaxWait      time.Duration // For testing; 0 means 60s default
	LAPIPollInterval time.Duration // For testing; 0 means 500ms default
	// contains filtered or unexported fields
}

CrowdsecHandler manages CrowdSec process and config imports.

func NewCrowdsecHandler

func NewCrowdsecHandler(db *gorm.DB, executor CrowdsecExecutor, binPath, dataDir string, caddyMgr CaddyConfigManager) *CrowdsecHandler

NewCrowdsecHandler builds the CrowdSec handler. caddyMgr re-applies the proxy configuration after Start; a nil manager (including a typed nil pointer) leaves the handler unwired.

func (*CrowdsecHandler) AddWhitelist

func (h *CrowdsecHandler) AddWhitelist(c *gin.Context)

AddWhitelist adds a new IP or CIDR to the CrowdSec whitelist.

func (*CrowdsecHandler) ApplyJobs

func (h *CrowdsecHandler) ApplyJobs() *crowdsec.ApplyJobManager

ApplyJobs returns the background install manager: its busy flag, and the holds that requests take while they change DataDir (holdUnlessBusy).

func (*CrowdsecHandler) ApplyPreset

func (h *CrowdsecHandler) ApplyPreset(c *gin.Context)

ApplyPreset installs a pulled preset: a curated preset through cscli, a hub preset by installing the pulled item with cscli and verifying the result.

With "async": true a hub preset is installed as a background job (202 with the job, see crowdsec_apply_jobs_handler.go); curated presets are quick and always apply synchronously. The synchronous path is bounded by the 120 s apply timeout and is deprecated for large hub presets, which can take minutes.

func (*CrowdsecHandler) BanIP

func (h *CrowdsecHandler) BanIP(c *gin.Context)

BanIP adds a manual ban for an address or a CIDR range. The request is validated before cscli runs.

func (*CrowdsecHandler) CancelApplyJob

func (h *CrowdsecHandler) CancelApplyJob(c *gin.Context)

CancelApplyJob asks an active install job to stop; the job rolls back and ends cancelled. A finished job answers 409 job_not_active.

func (*CrowdsecHandler) CheckLAPIHealth

func (h *CrowdsecHandler) CheckLAPIHealth(c *gin.Context)

CheckLAPIHealth verifies that CrowdSec LAPI is responding.

func (*CrowdsecHandler) ConsoleEnroll

func (h *CrowdsecHandler) ConsoleEnroll(c *gin.Context)

ConsoleEnroll enrolls the local engine with CrowdSec console.

func (*CrowdsecHandler) ConsoleHeartbeat

func (h *CrowdsecHandler) ConsoleHeartbeat(c *gin.Context)

ConsoleHeartbeat returns the current heartbeat status for console. GET /api/v1/admin/crowdsec/console/heartbeat

func (*CrowdsecHandler) ConsoleStatus

func (h *CrowdsecHandler) ConsoleStatus(c *gin.Context)

ConsoleStatus returns the current console enrollment status without secrets.

func (*CrowdsecHandler) DashboardScenarios

func (h *CrowdsecHandler) DashboardScenarios(c *gin.Context)

DashboardScenarios returns scenario breakdown with counts and percentages.

func (*CrowdsecHandler) DashboardSummary

func (h *CrowdsecHandler) DashboardSummary(c *gin.Context)

DashboardSummary returns aggregate counts for the dashboard summary cards.

func (*CrowdsecHandler) DashboardTimeline

func (h *CrowdsecHandler) DashboardTimeline(c *gin.Context)

DashboardTimeline returns time-bucketed decision counts for the timeline chart.

func (*CrowdsecHandler) DashboardTopIPs

func (h *CrowdsecHandler) DashboardTopIPs(c *gin.Context)

DashboardTopIPs returns top attacking IPs ranked by decision count.

func (*CrowdsecHandler) DeleteConsoleEnrollment

func (h *CrowdsecHandler) DeleteConsoleEnrollment(c *gin.Context)

DeleteConsoleEnrollment clears the local enrollment state to allow fresh enrollment. DELETE /api/v1/admin/crowdsec/console/enrollment Note: This does NOT unenroll from crowdsec.net - that must be done manually on the console.

func (*CrowdsecHandler) DeleteWhitelist

func (h *CrowdsecHandler) DeleteWhitelist(c *gin.Context)

DeleteWhitelist removes a whitelist entry by UUID.

func (*CrowdsecHandler) DiagnosticsConfig

func (h *CrowdsecHandler) DiagnosticsConfig(c *gin.Context)

DiagnosticsConfig validates CrowdSec configuration files. GET /api/v1/admin/crowdsec/diagnostics/config

func (*CrowdsecHandler) DiagnosticsConnectivity

func (h *CrowdsecHandler) DiagnosticsConnectivity(c *gin.Context)

DiagnosticsConnectivity verifies connectivity to all CrowdSec components. GET /api/v1/admin/crowdsec/diagnostics/connectivity

func (*CrowdsecHandler) ExportConfig

func (h *CrowdsecHandler) ExportConfig(c *gin.Context)

ExportConfig builds a tar.gz archive of the CrowdSec data directory in a temporary file and then sends it. Every failure is reported before the first byte of the download, so a client never receives a truncated archive with a success status.

Exports stay available while a background preset install runs (no busy refusal, by design): an archive taken during an install can contain a partly installed hub tree.

func (*CrowdsecHandler) ExportDecisions

func (h *CrowdsecHandler) ExportDecisions(c *gin.Context)

ExportDecisions exports decisions as downloadable CSV or JSON.

func (*CrowdsecHandler) GetAcquisitionConfig

func (h *CrowdsecHandler) GetAcquisitionConfig(c *gin.Context)

GetAcquisitionConfig returns the current CrowdSec acquisition configuration. GET /api/v1/admin/crowdsec/acquisition

func (*CrowdsecHandler) GetApplyJob

func (h *CrowdsecHandler) GetApplyJob(c *gin.Context)

GetApplyJob answers one install job by id.

func (*CrowdsecHandler) GetBouncerInfo

func (h *CrowdsecHandler) GetBouncerInfo(c *gin.Context)

GetBouncerInfo returns information about the current bouncer key. GET /api/v1/admin/crowdsec/bouncer

func (*CrowdsecHandler) GetBouncerKey

func (h *CrowdsecHandler) GetBouncerKey(c *gin.Context)

GetBouncerKey returns the full bouncer key (for copy to clipboard). GET /api/v1/admin/crowdsec/bouncer/key

func (*CrowdsecHandler) GetCachedPreset

func (h *CrowdsecHandler) GetCachedPreset(c *gin.Context)

GetCachedPreset returns cached preview for a slug when available.

func (*CrowdsecHandler) GetCurrentApplyJob

func (h *CrowdsecHandler) GetCurrentApplyJob(c *gin.Context)

GetCurrentApplyJob answers the active install job, or the newest finished one from the last 30 minutes, or {"job": null}. The UI calls it on page load to resume the progress row.

func (*CrowdsecHandler) GetKeyStatus

func (h *CrowdsecHandler) GetKeyStatus(c *gin.Context)

GetKeyStatus returns the current CrowdSec bouncer key status and any rejection information. This endpoint provides UX feedback when env var keys are rejected by LAPI. @Summary Get CrowdSec API key status @Description Returns current key source, validity, the LAPI key check and rejection status if env key was invalid @Tags crowdsec @Produce json @Success 200 {object} KeyStatusResponse @Router /admin/crowdsec/key-status [get]

func (*CrowdsecHandler) GetLAPIDecisions

func (h *CrowdsecHandler) GetLAPIDecisions(c *gin.Context)

GetLAPIDecisions queries CrowdSec LAPI directly for current decisions. This is an alternative to ListDecisions which uses cscli. Query params:

  • ip: filter by specific IP address
  • scope: filter by scope (e.g., "ip", "range")
  • type: filter by decision type (e.g., "ban", "captcha")

func (*CrowdsecHandler) HasProxyApplier

func (h *CrowdsecHandler) HasProxyApplier() bool

HasProxyApplier reports whether the handler was built with a Caddy manager.

func (*CrowdsecHandler) ImportConfig

func (h *CrowdsecHandler) ImportConfig(c *gin.Context)

ImportConfig accepts a tar.gz upload and replaces the CrowdSec configuration in DataDir. The previous configuration is snapshotted first and restored on failure; server-local state (live db, data/, hub_cache/, installed hub items) is never replaced and DataDir itself is never renamed.

func (*CrowdsecHandler) ListAlerts

func (h *CrowdsecHandler) ListAlerts(c *gin.Context)

ListAlerts lists CrowdSec alerts through cscli (the local API needs a machine login for alerts, not a bouncer key).

func (*CrowdsecHandler) ListApplyJobs

func (h *CrowdsecHandler) ListApplyJobs(c *gin.Context)

ListApplyJobs answers the most recent install jobs, newest first (default 20, at most 50).

func (*CrowdsecHandler) ListDecisions

func (h *CrowdsecHandler) ListDecisions(c *gin.Context)

ListDecisions calls cscli to get current decisions (banned IPs)

func (*CrowdsecHandler) ListFiles

func (h *CrowdsecHandler) ListFiles(c *gin.Context)

ListFiles returns a flat list of the readable files under the CrowdSec DataDir.

func (*CrowdsecHandler) ListPresets

func (h *CrowdsecHandler) ListPresets(c *gin.Context)

ListPresets returns the curated preset catalog when Cerberus is enabled.

func (*CrowdsecHandler) ListWhitelists

func (h *CrowdsecHandler) ListWhitelists(c *gin.Context)

ListWhitelists returns all CrowdSec IP/CIDR whitelist entries.

func (*CrowdsecHandler) PullPreset

func (h *CrowdsecHandler) PullPreset(c *gin.Context)

PullPreset downloads and caches a hub preset while returning a preview.

func (*CrowdsecHandler) ReadFile

func (h *CrowdsecHandler) ReadFile(c *gin.Context)

ReadFile returns the contents of a specific file under DataDir. Query param 'path' required.

func (*CrowdsecHandler) RegisterBouncer

func (h *CrowdsecHandler) RegisterBouncer(c *gin.Context)

RegisterBouncer checks the saved bouncer key against the local engine and registers a new bouncer only when CrowdSec definitively rejects that key, so a working key is never replaced. It uses the key decision Start uses (ensureBouncerRegistrationWait), so the key file, the proxy and the response agree with the engine.

Answers: 200 "registered" when a key is in use; 200 "unverified" when no key could be checked (LAPI down), which changes nothing; 500 when the registration failed; 504 when it ran out of time. A running Start or Stop or an install job answers 409 crowdsec_busy, and a request after shutdown began answers 503 shutting_down. The proxy configuration is applied after every decision. The work runs on the operation context, so a client that leaves does not cut it in half. POST /api/v1/admin/crowdsec/bouncer/register

func (*CrowdsecHandler) RegisterRoutes

func (h *CrowdsecHandler) RegisterRoutes(rg *gin.RouterGroup)

RegisterRoutes registers crowdsec admin routes under protected group

func (*CrowdsecHandler) ResetCrowdSecState

func (h *CrowdsecHandler) ResetCrowdSecState(write func() error) error

ResetCrowdSecState implements CrowdsecLifecycle. The reset's writes run under stateMu. Inside that critical section the pending stop is counted before the generation moves, so a Start that loads the new generation also sees the stop, and a Start that loaded the old one is caught by its checkpoints.

func (*CrowdsecHandler) RestoreHubItems

func (h *CrowdsecHandler) RestoreHubItems(c *gin.Context)

RestoreHubItems installs the requested hub items that are not installed yet: POST /admin/crowdsec/hub-items/restore. Every hub write takes dataMu for exactly one cscli section, so an import, export, file save or preset apply waits for at most one bounded call and never overlaps an install.

func (*CrowdsecHandler) ShutdownApplyJobs

func (h *CrowdsecHandler) ShutdownApplyJobs()

ShutdownApplyJobs cancels the running install job, which rolls back from its snapshot, and waits for it to end. Call it from the graceful shutdown path; startup recovery is the backstop when the grace period ends first.

func (*CrowdsecHandler) Start

func (h *CrowdsecHandler) Start(c *gin.Context)

Start is the HTTP switch that starts CrowdSec and waits for LAPI. The engine logic is in StartCrowdSec.

func (*CrowdsecHandler) StartCrowdSec

func (h *CrowdsecHandler) StartCrowdSec(reqCtx context.Context) (CrowdsecStartResult, error)

StartCrowdSec starts the CrowdSec engine and waits for LAPI to be ready. It is the request-independent core of the Start switch. It refuses with *CrowdsecBusyError while another Start or Stop runs, while a background change holds the manager, or while an emergency reset's engine stop is still pending. Every outcome that changes or confirms the CrowdSec state re-applies the proxy configuration exactly once. When an emergency reset turns CrowdSec off while the Start runs, the Start stops the engine, keeps the reset's values and answers errCrowdsecStateChanged.

Before the engine starts, Charon's whitelist file is rewritten from the database under dataMu, so the engine never reads an out-of-date list. Start sends no reload signal: whitelist changes reload the engine themselves (see reloadCrowdSec), and a running engine picks up the rewritten file at its next reload (see syncWhitelistFile).

func (*CrowdsecHandler) Status

func (h *CrowdsecHandler) Status(c *gin.Context)

Status returns running state including LAPI availability check.

func (*CrowdsecHandler) Stop

func (h *CrowdsecHandler) Stop(c *gin.Context)

Stop is the HTTP switch that stops CrowdSec. The engine logic is in StopCrowdSec.

func (*CrowdsecHandler) StopAfterReset

func (h *CrowdsecHandler) StopAfterReset(resetErr error)

StopAfterReset implements CrowdsecLifecycle. It returns at once: the stop runs in a goroutine that holds no handler lock, so neither the reply nor a Start waits for a slow engine stop beyond resetStopTimeout.

func (*CrowdsecHandler) StopCrowdSec

func (h *CrowdsecHandler) StopCrowdSec(reqCtx context.Context) (CrowdsecStopResult, error)

StopCrowdSec stops the CrowdSec engine and turns its state off. It is the request-independent core of the Stop switch, and it refuses with *CrowdsecBusyError under the same rules as StartCrowdSec.

func (*CrowdsecHandler) UnbanIP

func (h *CrowdsecHandler) UnbanIP(c *gin.Context)

UnbanIP removes the decisions that match an address or a CIDR range exactly: cscli compares the scope, so a covering range does not remove the single addresses inside it. The route is a catch-all so that a range written as 10.0.0.0/24 or 10.0.0.0%2F24 reaches the handler; the value arrives with a leading slash.

func (*CrowdsecHandler) UpdateAcquisitionConfig

func (h *CrowdsecHandler) UpdateAcquisitionConfig(c *gin.Context)

UpdateAcquisitionConfig updates the CrowdSec acquisition configuration. PUT /api/v1/admin/crowdsec/acquisition

func (*CrowdsecHandler) WaitRegistrations

func (h *CrowdsecHandler) WaitRegistrations(ctx context.Context) error

WaitRegistrations closes the registration gate, so no new bouncer swap can start, and waits until the swaps in flight have finished or ctx ends. It is called once, at shutdown. The swaps run on a context that the shutdown cancel does not end, so this wait is what lets them finish before the process exits.

func (*CrowdsecHandler) WaitResetStops

func (h *CrowdsecHandler) WaitResetStops(ctx context.Context) error

WaitResetStops waits until no emergency reset's engine stop is pending, or until ctx ends. The shutdown path and the tests use it.

func (*CrowdsecHandler) WithAppContext

func (h *CrowdsecHandler) WithAppContext(ctx context.Context) *CrowdsecHandler

WithAppContext sets the application context that ends the Start and Stop operations at shutdown.

func (*CrowdsecHandler) WriteFile

func (h *CrowdsecHandler) WriteFile(c *gin.Context)

WriteFile saves content to an allowed file under DataDir, first copying only the replaced file into the file-backup namespace. DataDir itself is never renamed or emptied. JSON body: { "path": "relative/path.conf", "content": "..." }

type CrowdsecLifecycle

type CrowdsecLifecycle interface {
	StartCrowdSec(reqCtx context.Context) (CrowdsecStartResult, error)
	StopCrowdSec(reqCtx context.Context) (CrowdsecStopResult, error)
	// ResetCrowdSecState runs an emergency reset's writes under stateMu. Before the writes, in the same critical
	// section, it counts one pending engine stop and moves the state generation, so a Start in flight stops at its
	// next checkpoint and a later Start waits for the counted stop. Every call must be followed by exactly one
	// StopAfterReset, whether the writes succeed, fail or panic.
	ResetCrowdSecState(write func() error) error
	// StopAfterReset consumes the stop counted by ResetCrowdSecState. resetErr is the reset's result, or an error
	// when the writes did not complete. The stop runs in a tracked goroutine, so the caller never waits for it.
	StopAfterReset(resetErr error)
	// WaitRegistrations closes the bouncer registration gate and waits for the swaps in flight, or for ctx. Shutdown
	// calls it once, after the app context is cancelled.
	WaitRegistrations(ctx context.Context) error
}

CrowdsecLifecycle is the one owner of the CrowdSec engine state. The engine process, the default row's crowd_sec_mode, the security.crowdsec.enabled setting and the proxy configuration change together, and only through it. The HTTP switches and the settings and emergency handlers call it; none of them drives the engine on its own. The request context passed in only supplies values: an operation does not stop when it is cancelled (see operationContext).

func LifecycleOrNil

func LifecycleOrNil(l CrowdsecLifecycle) CrowdsecLifecycle

LifecycleOrNil returns nil for a nil interface or for a nil *CrowdsecHandler stored in one, so a handler that was never built is detectable as not wired. It is a type switch rather than reflection, so no kind can panic.

type CrowdsecStartResult

type CrowdsecStartResult struct {
	Status       string // "started" or "already_running"
	PID          int
	LAPIReady    bool
	Warning      string // set when the engine started but LAPI was not ready in time
	ProxyApplied bool   // the real outcome of the one proxy apply
}

CrowdsecStartResult is the outcome of a Start that did not fail.

type CrowdsecStopResult

type CrowdsecStopResult struct {
	ProxyApplied bool
}

CrowdsecStopResult is the outcome of a Stop that did not fail.

type CustomThemeHandler

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

CustomThemeHandler handles CRUD for user-created named themes.

func NewCustomThemeHandler

func NewCustomThemeHandler(db *gorm.DB) *CustomThemeHandler

NewCustomThemeHandler creates a new CustomThemeHandler.

func (*CustomThemeHandler) CreateTheme

func (h *CustomThemeHandler) CreateTheme(c *gin.Context)

CreateTheme handles POST /api/v1/themes. Body: { "name": string, "colors": string (JSON) } Returns: 201 with the created CustomTheme record.

func (*CustomThemeHandler) DeleteTheme

func (h *CustomThemeHandler) DeleteTheme(c *gin.Context)

DeleteTheme handles DELETE /api/v1/themes/:id. Returns: 200 { "message": "theme deleted" }

func (*CustomThemeHandler) ListThemes

func (h *CustomThemeHandler) ListThemes(c *gin.Context)

ListThemes handles GET /api/v1/themes. Returns all user-created themes ordered by created_at ASC. Always returns a JSON array (never null) — empty array when no themes exist.

func (*CustomThemeHandler) UpdateTheme

func (h *CustomThemeHandler) UpdateTheme(c *gin.Context)

UpdateTheme handles PUT /api/v1/themes/:id. Body: { "name"?: string, "colors"?: string (JSON) } Returns: 200 with the updated record.

type DBHealthHandler

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

DBHealthHandler provides database health check endpoints.

func NewDBHealthHandler

func NewDBHealthHandler(db *gorm.DB, backupService *services.BackupService, dbPath string) *DBHealthHandler

NewDBHealthHandler creates a new DBHealthHandler. dbPath is the on-disk path to the main SQLite database file (spec §2.5d/§3.9) — Check uses it to run the integrity scan on a dedicated connection rather than the shared db pool.

func (*DBHealthHandler) Check

func (h *DBHealthHandler) Check(c *gin.Context)

Check performs a database health check. GET /api/v1/health/db Returns 200 if healthy, 503 if corrupted.

type DBHealthResponse

type DBHealthResponse struct {
	Status          string     `json:"status"`
	IntegrityOK     bool       `json:"integrity_ok"`
	IntegrityResult string     `json:"integrity_result"`
	WALMode         bool       `json:"wal_mode"`
	JournalMode     string     `json:"journal_mode"`
	LastBackup      *time.Time `json:"last_backup"`
	CheckedAt       time.Time  `json:"checked_at"`
}

DBHealthResponse represents the database health check response.

type DNSDetectionHandler

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

DNSDetectionHandler handles DNS provider auto-detection API requests.

func NewDNSDetectionHandler

func NewDNSDetectionHandler(service services.DNSDetectionService) *DNSDetectionHandler

NewDNSDetectionHandler creates a new DNS detection handler.

func (*DNSDetectionHandler) Detect

func (h *DNSDetectionHandler) Detect(c *gin.Context)

Detect handles POST /api/v1/dns-providers/detect Performs DNS provider auto-detection for a given domain.

func (*DNSDetectionHandler) GetPatterns

func (h *DNSDetectionHandler) GetPatterns(c *gin.Context)

GetPatterns handles GET /api/v1/dns-providers/detection-patterns Returns the current nameserver pattern database.

type DNSProviderHandler

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

DNSProviderHandler handles DNS provider API requests.

func NewDNSProviderHandler

func NewDNSProviderHandler(service services.DNSProviderService) *DNSProviderHandler

NewDNSProviderHandler creates a new DNS provider handler.

func (*DNSProviderHandler) Create

func (h *DNSProviderHandler) Create(c *gin.Context)

Create handles POST /api/v1/dns-providers Creates a new DNS provider with encrypted credentials.

func (*DNSProviderHandler) Delete

func (h *DNSProviderHandler) Delete(c *gin.Context)

Delete handles DELETE /api/v1/dns-providers/:id Deletes a DNS provider. Accepts either numeric ID or UUID for flexibility.

func (*DNSProviderHandler) Get

func (h *DNSProviderHandler) Get(c *gin.Context)

Get handles GET /api/v1/dns-providers/:id Returns a single DNS provider without exposing credentials. Accepts either numeric ID or UUID for flexibility.

func (*DNSProviderHandler) GetTypes

func (h *DNSProviderHandler) GetTypes(c *gin.Context)

GetTypes handles GET /api/v1/dns-providers/types Returns the list of supported DNS provider types with their required fields. Types are sourced from the provider registry (built-in, custom, and external plugins).

func (*DNSProviderHandler) List

func (h *DNSProviderHandler) List(c *gin.Context)

List handles GET /api/v1/dns-providers Returns all DNS providers without exposing credentials.

func (*DNSProviderHandler) Test

func (h *DNSProviderHandler) Test(c *gin.Context)

Test handles POST /api/v1/dns-providers/:id/test Tests a saved DNS provider's credentials. Accepts either numeric ID or UUID for flexibility.

func (*DNSProviderHandler) TestCredentials

func (h *DNSProviderHandler) TestCredentials(c *gin.Context)

TestCredentials handles POST /api/v1/dns-providers/test Tests DNS provider credentials without saving them.

func (*DNSProviderHandler) Update

func (h *DNSProviderHandler) Update(c *gin.Context)

Update handles PUT /api/v1/dns-providers/:id Updates an existing DNS provider. Accepts either numeric ID or UUID for flexibility.

type DNSProviderServiceInterface

type DNSProviderServiceInterface interface {
	Get(ctx context.Context, id uint) (*models.DNSProvider, error)
	// ResolveID resolves the :id path param — accepting either a legacy
	// numeric ID (back-compat) or the DNS provider's UUID, since
	// DNSProviderResponse never exposes the internal numeric ID to clients
	// — to the provider's internal numeric ID. See
	// services.DNSProviderService.ResolveID for the full contract.
	ResolveID(ctx context.Context, idOrUUID string) (uint, error)
}

DNSProviderServiceInterface defines the subset of DNSProviderService needed by ManualChallengeHandler.

type DatabaseMaintenanceHandler

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

DatabaseMaintenanceHandler serves the admin-only database page: file size, what could be reclaimed, the notice that applies right now and the "reclaim space on next restart" request.

func NewDatabaseMaintenanceHandler

func NewDatabaseMaintenanceHandler(db *sql.DB, dbPath, envMode string) *DatabaseMaintenanceHandler

NewDatabaseMaintenanceHandler builds the handler for the database at dbPath. envMode is the CHARON_DB_COMPACT_ON_START value (config.DBCompactAuto or config.DBCompactOff).

func (*DatabaseMaintenanceHandler) CancelOptimize

func (h *DatabaseMaintenanceHandler) CancelOptimize(c *gin.Context)

CancelOptimize clears the flag. It is idempotent. DELETE /api/v1/system/database/optimize-on-restart

func (*DatabaseMaintenanceHandler) GetStatus

func (h *DatabaseMaintenanceHandler) GetStatus(c *gin.Context)

GetStatus returns the card data. The notice is computed fresh on every call from a cheap Inspect, never from a boot snapshot: the pruner frees pages without a restart. GET /api/v1/system/database

func (*DatabaseMaintenanceHandler) RequestOptimize

func (h *DatabaseMaintenanceHandler) RequestOptimize(c *gin.Context)

RequestOptimize sets the "reclaim space on next restart" flag. A repeated request while the flag is set is a 200 before any other check (it only resets an exhausted failure counter). A request that could never do anything is a 409 whose body names the actual cause. POST /api/v1/system/database/optimize-on-restart

type DefaultCrowdsecExecutor

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

DefaultCrowdsecExecutor implements CrowdsecExecutor using OS processes.

func NewDefaultCrowdsecExecutor

func NewDefaultCrowdsecExecutor() *DefaultCrowdsecExecutor

func (*DefaultCrowdsecExecutor) EngineAge

func (e *DefaultCrowdsecExecutor) EngineAge(pid int) (age time.Duration, known bool)

EngineAge reports how long the engine with pid has been running. An engine this executor spawned is measured on the monotonic clock from its spawn. An adopted engine (one it did not start, e.g. after a Charon restart) is read from /proc. known is false when the age cannot be determined.

func (*DefaultCrowdsecExecutor) Start

func (e *DefaultCrowdsecExecutor) Start(ctx context.Context, binPath, configDir string) (int, error)

Start launches the CrowdSec engine, or returns the pid of the one already running for this config directory. The check and the spawn happen under one lock, so concurrent calls never start two engines.

func (*DefaultCrowdsecExecutor) Status

func (e *DefaultCrowdsecExecutor) Status(ctx context.Context, configDir string) (running bool, pid int, err error)

Status reports whether CrowdSec is running, falling back to a process-table scan when the pid file does not point at a live CrowdSec process. When no engine is running it returns the (possibly stale) pid recorded in the file.

func (*DefaultCrowdsecExecutor) Stop

func (e *DefaultCrowdsecExecutor) Stop(ctx context.Context, configDir string) error

Stop stops the CrowdSec process: SIGTERM, then SIGKILL if it has not exited within the stop timeout. It is idempotent - stopping an already-stopped service or one that was never started will succeed without error. A pid file pointing at a recycled, non-CrowdSec process is removed without signalling anything. If ctx is cancelled while waiting, Stop gives up with the context error instead of escalating to SIGKILL; if the process survives SIGKILL, Stop returns an error and keeps the pid file.

type DetectRequest

type DetectRequest struct {
	Domain string `json:"domain" binding:"required"`
}

DetectRequest represents the request body for DNS provider detection.

type DockerHandler

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

func NewDockerHandler

func NewDockerHandler(dockerService dockerAPI, remoteServerService remoteServerGetter) *DockerHandler

func (*DockerHandler) ListContainers

func (h *DockerHandler) ListContainers(c *gin.Context)

func (*DockerHandler) LocalStatus

func (h *DockerHandler) LocalStatus(c *gin.Context)

LocalStatus reports whether the local Docker socket is usable. Unavailable Docker is a normal 200 answer; the payload never exposes path or uid details.

func (*DockerHandler) RegisterRoutes

func (h *DockerHandler) RegisterRoutes(r *gin.RouterGroup)

func (*DockerHandler) SetOrthrusResolver

func (h *DockerHandler) SetOrthrusResolver(r orthrusProxyResolver)

type DomainHandler

type DomainHandler struct {
	DB *gorm.DB
	// contains filtered or unexported fields
}

func NewDomainHandler

func NewDomainHandler(db *gorm.DB, ns *services.NotificationService) *DomainHandler

func (*DomainHandler) Create

func (h *DomainHandler) Create(c *gin.Context)

func (*DomainHandler) Delete

func (h *DomainHandler) Delete(c *gin.Context)

func (*DomainHandler) List

func (h *DomainHandler) List(c *gin.Context)

type EmergencyHandler

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

EmergencyHandler handles emergency security reset operations

func NewEmergencyHandler

func NewEmergencyHandler(db *gorm.DB) *EmergencyHandler

NewEmergencyHandler creates a new EmergencyHandler

func NewEmergencyHandlerWithDeps

func NewEmergencyHandlerWithDeps(db *gorm.DB, caddyManager CaddyConfigManager, cerberus CacheInvalidator) *EmergencyHandler

NewEmergencyHandlerWithDeps creates a new EmergencyHandler with optional cache invalidation and config reload.

func NewEmergencyTokenHandler

func NewEmergencyTokenHandler(tokenService *services.EmergencyTokenService) *EmergencyHandler

NewEmergencyTokenHandler creates a handler for emergency token management endpoints This is an alias for NewEmergencyHandler, provided for semantic clarity in route registration

func (*EmergencyHandler) Close

func (h *EmergencyHandler) Close()

Close shuts down the handler's resources (e.g., SecurityService).

func (*EmergencyHandler) GenerateToken

func (h *EmergencyHandler) GenerateToken(c *gin.Context)

GenerateToken generates a new emergency token with expiration policy POST /api/v1/emergency/token/generate Requires admin authentication

func (*EmergencyHandler) GetTokenStatus

func (h *EmergencyHandler) GetTokenStatus(c *gin.Context)

GetTokenStatus returns token metadata (not the token itself) GET /api/v1/emergency/token/status Requires admin authentication

func (*EmergencyHandler) RevokeToken

func (h *EmergencyHandler) RevokeToken(c *gin.Context)

RevokeToken revokes the current emergency token DELETE /api/v1/emergency/token Requires admin authentication

func (*EmergencyHandler) SecurityReset

func (h *EmergencyHandler) SecurityReset(c *gin.Context)

SecurityReset disables all security modules for emergency lockout recovery. This endpoint works in conjunction with the EmergencyBypass middleware which validates the token and IP restrictions, then sets the emergency_bypass flag.

Security measures: - EmergencyBypass middleware validates token and IP (timing-safe comparison) - All attempts (success and failure) are logged to audit trail with timestamp and IP

func (*EmergencyHandler) UpdateTokenExpiration

func (h *EmergencyHandler) UpdateTokenExpiration(c *gin.Context)

UpdateTokenExpiration updates the expiration policy for the current token PATCH /api/v1/emergency/token/expiration Requires admin authentication

func (*EmergencyHandler) WithCrowdsecLifecycle

func (h *EmergencyHandler) WithCrowdsecLifecycle(l CrowdsecLifecycle) *EmergencyHandler

WithCrowdsecLifecycle wires the CrowdSec lifecycle that the emergency reset drives. A typed-nil handler is not wired.

func (*EmergencyHandler) WithManagementCIDRs

func (h *EmergencyHandler) WithManagementCIDRs(cidrs []string) *EmergencyHandler

WithManagementCIDRs sets the networks allowed to use the direct reset path. An empty list selects the default private and loopback ranges. An invalid entry limits the networks to loopback; the error is reported once by middleware.EmergencyBypass at startup, so it is not logged again here.

type EncryptionHandler

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

EncryptionHandler manages encryption key operations and rotation.

func NewEncryptionHandler

func NewEncryptionHandler(rotationService *crypto.RotationService, securityService *services.SecurityService) *EncryptionHandler

NewEncryptionHandler creates a new encryption handler.

func (*EncryptionHandler) GetHistory

func (h *EncryptionHandler) GetHistory(c *gin.Context)

GetHistory returns audit logs related to encryption key operations. GET /api/v1/admin/encryption/history

func (*EncryptionHandler) GetStatus

func (h *EncryptionHandler) GetStatus(c *gin.Context)

GetStatus returns the current encryption key status, verified by decryption. GET /api/v1/admin/encryption/status

func (*EncryptionHandler) Rotate

func (h *EncryptionHandler) Rotate(c *gin.Context)

Rotate re-encrypts every stored secret to the rotation target. POST /api/v1/admin/encryption/rotate

func (*EncryptionHandler) Validate

func (h *EncryptionHandler) Validate(c *gin.Context)

Validate checks every configured encryption key. POST /api/v1/admin/encryption/validate

type ErrorResponse

type ErrorResponse struct {
	Success bool `json:"success"`
	Error   struct {
		Code    string                 `json:"code"`
		Message string                 `json:"message"`
		Details map[string]interface{} `json:"details,omitempty"`
	} `json:"error"`
}

ErrorResponse represents an error response with a code.

type FeatureFlagsHandler

type FeatureFlagsHandler struct {
	DB *gorm.DB
	// contains filtered or unexported fields
}

FeatureFlagsHandler exposes simple DB-backed feature flags with env fallback. The Cerberus flag is a security switch and is written through the same switch writer as the settings API.

func NewFeatureFlagsHandler

func NewFeatureFlagsHandler(db *gorm.DB, caddyMgr CaddyConfigManager, cerberus CacheInvalidator) *FeatureFlagsHandler

NewFeatureFlagsHandler returns the handler. caddyMgr and cerberus are the proxy apply and the Cerberus cache that a Cerberus flag write uses; either may be nil.

func (*FeatureFlagsHandler) GetFlags

func (h *FeatureFlagsHandler) GetFlags(c *gin.Context)

GetFlags returns a map of feature flag -> bool. DB setting takes precedence and falls back to environment variables if present.

func (*FeatureFlagsHandler) UpdateFlags

func (h *FeatureFlagsHandler) UpdateFlags(c *gin.Context)

UpdateFlags accepts a JSON object map[string]bool and upserts settings. The batch is atomic. When it includes the Cerberus flag, the flag goes through the switch writer together with the other flags, in one write-locked transaction, so a failed flag write rolls the switch back and a refused proxy apply restores every key in the batch.

type HecateHandler

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

HecateHandler handles REST requests for tunnel configuration and provider data.

func NewHecateHandler

func NewHecateHandler(svc *services.HecateService) *HecateHandler

NewHecateHandler creates a HecateHandler backed by the given service.

func (*HecateHandler) Create

func (h *HecateHandler) Create(c *gin.Context)

Create persists a new TunnelConfig.

func (*HecateHandler) Delete

func (h *HecateHandler) Delete(c *gin.Context)

Delete stops and removes a TunnelConfig.

func (*HecateHandler) Get

func (h *HecateHandler) Get(c *gin.Context)

Get retrieves a single TunnelConfig by UUID.

func (*HecateHandler) GetCloudflaredConfig

func (h *HecateHandler) GetCloudflaredConfig(c *gin.Context)

GetCloudflaredConfig returns a cloudflared YAML configuration template for a tunnel.

func (*HecateHandler) GetStatus

func (h *HecateHandler) GetStatus(c *gin.Context)

GetStatus returns the runtime status of all managed tunnels.

func (*HecateHandler) List

func (h *HecateHandler) List(c *gin.Context)

List returns all TunnelConfig records.

func (*HecateHandler) ListCloudflareTunnels

func (h *HecateHandler) ListCloudflareTunnels(c *gin.Context)

ListCloudflareTunnels proxies a ListTunnels call to the active Cloudflare provider.

func (*HecateHandler) ListNetBirdPeers

func (h *HecateHandler) ListNetBirdPeers(c *gin.Context)

ListNetBirdPeers proxies a ListPeers call to the active NetBird provider.

func (*HecateHandler) ListTailscaleDevices

func (h *HecateHandler) ListTailscaleDevices(c *gin.Context)

ListTailscaleDevices proxies a ListDevices call to the active Tailscale provider.

func (*HecateHandler) ListZeroTierMembers

func (h *HecateHandler) ListZeroTierMembers(c *gin.Context)

ListZeroTierMembers proxies a ListMembers call to the active ZeroTier provider.

func (*HecateHandler) ListZeroTierNetworks

func (h *HecateHandler) ListZeroTierNetworks(c *gin.Context)

ListZeroTierNetworks proxies a ListNetworks call to the active ZeroTier provider.

func (*HecateHandler) RegisterRoutes

func (h *HecateHandler) RegisterRoutes(read, admin *gin.RouterGroup)

RegisterRoutes wires the Hecate endpoints. Read-only status/list endpoints that back role=user-reachable screens (the Dashboard hecate widget and the proxy-host create/edit flow) are registered on read; everything that mutates tunnels or exposes tunnel-provider credentials / network topology is registered on admin (deny-by-default for role=user). Callers that do not need the split may pass the same group for both.

func (*HecateHandler) RotateCredentials

func (h *HecateHandler) RotateCredentials(c *gin.Context)

RotateCredentials replaces the credentials for a running tunnel.

func (*HecateHandler) Start

func (h *HecateHandler) Start(c *gin.Context)

Start activates the tunnel for a given TunnelConfig UUID.

func (*HecateHandler) Stop

func (h *HecateHandler) Stop(c *gin.Context)

Stop deactivates the tunnel for a given TunnelConfig UUID.

func (*HecateHandler) SyncNetBird

func (h *HecateHandler) SyncNetBird(c *gin.Context)

SyncNetBird forces a cache refresh of the NetBird peer list.

func (*HecateHandler) SyncTailscale

func (h *HecateHandler) SyncTailscale(c *gin.Context)

SyncTailscale forces a cache refresh of the Tailscale device list.

func (*HecateHandler) Update

func (h *HecateHandler) Update(c *gin.Context)

Update applies changes to an existing TunnelConfig.

type HecateWSHandler

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

HecateWSHandler streams tunnel log entries over WebSocket.

func NewHecateWSHandler

func NewHecateWSHandler(svc *services.HecateService, tracker *services.WebSocketTracker) *HecateWSHandler

NewHecateWSHandler creates a HecateWSHandler.

func (*HecateWSHandler) StreamLogs

func (h *HecateWSHandler) StreamLogs(c *gin.Context)

StreamLogs upgrades the request to WebSocket and streams log lines from the tunnel's ring buffer. It replays buffered lines first, then delivers new lines as they arrive. The connection is kept alive with pings.

func (*HecateWSHandler) WithOriginPolicy

WithOriginPolicy wires the configured public origin and the trusted-proxy list into the WebSocket origin check.

func (*HecateWSHandler) WithStreamQuota

func (h *HecateWSHandler) WithStreamQuota(q *services.StreamQuota) *HecateWSHandler

WithStreamQuota caps the live streams this handler admits per user and in total.

type ImageUploadHandler

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

ImageUploadHandler handles generic image asset upload and deletion. Both UploadAsset and DeleteAsset enforce requireAuthenticatedAdmin internally.

func NewImageUploadHandler

func NewImageUploadHandler(db *gorm.DB, dataDir string, cfg AssetConfig) *ImageUploadHandler

NewImageUploadHandler creates a new ImageUploadHandler.

func (*ImageUploadHandler) DeleteAsset

func (h *ImageUploadHandler) DeleteAsset(c *gin.Context)

DeleteAsset handles DELETE for any image asset type. Calls requireAuthenticatedAdmin(c) at the top — returns 401/403 and aborts if not satisfied.

func (*ImageUploadHandler) UploadAsset

func (h *ImageUploadHandler) UploadAsset(c *gin.Context)

UploadAsset handles POST for any image asset type. Calls requireAuthenticatedAdmin(c) at the top — returns 401/403 and aborts if not satisfied.

type ImportHandler

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

ImportHandler handles Caddyfile import operations.

func NewImportHandler

func NewImportHandler(db *gorm.DB, caddyBinary, importDir, mountPath string) *ImportHandler

NewImportHandler creates a new import handler.

func NewImportHandlerWithDeps

func NewImportHandlerWithDeps(db *gorm.DB, caddyBinary, importDir, mountPath string, securityService *services.SecurityService) *ImportHandler

func NewImportHandlerWithService

func NewImportHandlerWithService(db *gorm.DB, proxyHostSvc ProxyHostServiceInterface, caddyBinary, importDir, mountPath string, securityService *services.SecurityService) *ImportHandler

NewImportHandlerWithService creates an import handler with a custom ProxyHostService. This is primarily used for testing with mock services.

func (*ImportHandler) Cancel

func (h *ImportHandler) Cancel(c *gin.Context)

Cancel discards a pending import session.

func (*ImportHandler) Commit

func (h *ImportHandler) Commit(c *gin.Context)

Commit finalizes the import with user's conflict resolutions.

func (*ImportHandler) DetectImports

func (h *ImportHandler) DetectImports(c *gin.Context)

DetectImports analyzes Caddyfile content and returns detected import directives.

func (*ImportHandler) GetPreview

func (h *ImportHandler) GetPreview(c *gin.Context)

GetPreview returns parsed hosts and conflicts for review.

func (*ImportHandler) GetStatus

func (h *ImportHandler) GetStatus(c *gin.Context)

GetStatus returns current import session status.

func (*ImportHandler) RegisterRoutes

func (h *ImportHandler) RegisterRoutes(router *gin.RouterGroup)

RegisterRoutes registers import-related routes.

func (*ImportHandler) SweepUploads

func (h *ImportHandler) SweepUploads() error

SweepUploads applies the upload retention rules once; the server calls it at start-up.

func (*ImportHandler) Upload

func (h *ImportHandler) Upload(c *gin.Context)

Upload handles manual Caddyfile upload or paste.

func (*ImportHandler) UploadMulti

func (h *ImportHandler) UploadMulti(c *gin.Context)

UploadMulti handles upload of main Caddyfile + multiple site files.

type ImporterService

type ImporterService interface {
	NormalizeCaddyfile(content string) (string, error)
	ParseCaddyfile(path string) ([]byte, error)
	ImportFile(path string) (*caddy.ImportResult, error)
	ExtractHosts(caddyJSON []byte) (*caddy.ImportResult, error)
	ValidateCaddyBinary() error
}

ImporterService defines the interface for Caddyfile import operations

type InviteUserRequest

type InviteUserRequest struct {
	Email          string `json:"email" binding:"required,email"`
	Role           string `json:"role"`
	PermissionMode string `json:"permission_mode"`
	PermittedHosts []uint `json:"permitted_hosts"`
}

InviteUserRequest represents the request body for inviting a user.

type JSONImportHandler

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

JSONImportHandler handles JSON configuration imports (both Charon and NPM formats).

func NewJSONImportHandler

func NewJSONImportHandler(db *gorm.DB) *JSONImportHandler

NewJSONImportHandler creates a new JSON import handler.

func (*JSONImportHandler) Cancel

func (h *JSONImportHandler) Cancel(c *gin.Context)

Cancel cancels a JSON import session and cleans up resources.

func (*JSONImportHandler) Commit

func (h *JSONImportHandler) Commit(c *gin.Context)

Commit finalizes the JSON import with user's conflict resolutions.

func (*JSONImportHandler) RegisterRoutes

func (h *JSONImportHandler) RegisterRoutes(router *gin.RouterGroup)

RegisterRoutes registers JSON import routes.

func (*JSONImportHandler) Upload

func (h *JSONImportHandler) Upload(c *gin.Context)

Upload parses a JSON export (Charon or NPM format) and returns a preview.

type KeyStatusResponse

type KeyStatusResponse struct {
	// KeySource indicates where the current key came from
	// Values: "env" (from environment variable), "file" (from bouncer_key file), "memory" (held in memory after a failed save), "auto-generated" (newly generated)
	KeySource string `json:"key_source"`

	// EnvKeyRejected is true if an environment variable key was set but rejected by LAPI
	EnvKeyRejected bool `json:"env_key_rejected"`

	// CurrentKeyPreview shows a masked preview of the current valid key (first 4 + last 4 chars)
	CurrentKeyPreview string `json:"current_key_preview,omitempty"`

	// RejectedKeyPreview shows a masked preview of the rejected env key (if applicable)
	RejectedKeyPreview string `json:"rejected_key_preview,omitempty"`

	// FullKey is the unmasked valid key, only returned when EnvKeyRejected is true
	// so the user can copy it to fix their docker-compose.yml
	FullKey string `json:"full_key,omitempty"`

	// Message provides user-friendly guidance
	Message string `json:"message,omitempty"`

	// KeyCheck is the LAPI check of the current key: "accepted", "rejected" (403 only), "unknown" (LAPI could not
	// answer) or "none" (no key). Valid is true only for "accepted".
	KeyCheck string `json:"key_check"`

	// Valid indicates whether the current key is valid (authenticated successfully with LAPI)
	Valid bool `json:"valid"`

	// BouncerName is the name of the registered bouncer
	BouncerName string `json:"bouncer_name"`

	// KeyFilePath is the path where the valid key is stored
	KeyFilePath string `json:"key_file_path"`
}

KeyStatusResponse represents the API response for the key-status endpoint. This endpoint provides UX feedback when env var keys are rejected by LAPI.

type LogEntry

type LogEntry struct {
	Level     string         `json:"level"`
	Message   string         `json:"message"`
	Timestamp string         `json:"timestamp"`
	Source    string         `json:"source"`
	Fields    map[string]any `json:"fields"`
}

LogEntry represents a structured log entry sent over WebSocket.

type LoginProtectionHandler

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

LoginProtectionHandler serves the admin-only login-protection status.

func NewLoginProtectionHandler

func NewLoginProtectionHandler(src LoginProtectionStatusSource) *LoginProtectionHandler

NewLoginProtectionHandler returns a handler reading status from src.

func (*LoginProtectionHandler) Get

func (h *LoginProtectionHandler) Get(c *gin.Context)

Get handles GET /api/v1/security/login-protection. It also reports how Charon sees the caller's own address, so admins can spot deployments where every visitor shares one address.

type LoginProtectionStatusSource

type LoginProtectionStatusSource interface {
	Status() middleware.AuthRateLimitStatus
}

LoginProtectionStatusSource supplies the sign-in throttle's admin status.

type LoginRequest

type LoginRequest struct {
	Email    string `json:"email" binding:"required,email"`
	Password string `json:"password" binding:"required"`
}

type LogoHandler

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

LogoHandler wraps ImageUploadHandler for the logo asset.

func NewLogoHandler

func NewLogoHandler(db *gorm.DB, dataDir string) *LogoHandler

NewLogoHandler creates a new LogoHandler.

func (h *LogoHandler) DeleteLogo(c *gin.Context)

DeleteLogo handles DELETE /api/v1/settings/logo. Clears logo settings from DB and removes the uploaded file.

func (h *LogoHandler) UploadLogo(c *gin.Context)

UploadLogo handles POST /api/v1/settings/logo. Accepts multipart form with field "logo" (image/png, image/jpeg, image/webp only). SVG uploads are explicitly rejected — too many XSS vectors to sanitize inline. Validates MIME via server-side byte sniffing (does NOT trust multipart Content-Type). Max size 2MB enforced via MaxBytesReader before any bytes are read.

type LogsHandler

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

func NewLogsHandler

func NewLogsHandler(service *services.LogService) *LogsHandler

func (*LogsHandler) Download

func (h *LogsHandler) Download(c *gin.Context)

func (*LogsHandler) List

func (h *LogsHandler) List(c *gin.Context)

func (*LogsHandler) Read

func (h *LogsHandler) Read(c *gin.Context)

type LogsWSHandler

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

LogsWSHandler handles WebSocket connections for live log streaming.

func NewLogsWSHandler

func NewLogsWSHandler(tracker *services.WebSocketTracker) *LogsWSHandler

NewLogsWSHandler creates a new handler for log streaming.

func (*LogsWSHandler) HandleWebSocket

func (h *LogsWSHandler) HandleWebSocket(c *gin.Context)

HandleWebSocket handles WebSocket connections for live log streaming.

func (*LogsWSHandler) WithOriginPolicy

WithOriginPolicy wires the configured public origin and the trusted-proxy list into the WebSocket origin check.

func (*LogsWSHandler) WithStreamQuota

func (h *LogsWSHandler) WithStreamQuota(q *services.StreamQuota) *LogsWSHandler

WithStreamQuota caps the live streams this handler admits per user and in total.

type ManagementAccessHandler

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

ManagementAccessHandler serves the access lists that protect Charon's own interface.

func NewManagementAccessHandler

func NewManagementAccessHandler(db *gorm.DB, aclMode string, cerb CacheInvalidator) *ManagementAccessHandler

NewManagementAccessHandler creates the handler. cerb may be nil.

func (*ManagementAccessHandler) Get

func (h *ManagementAccessHandler) Get(c *gin.Context)

Get returns the chosen lists. A chosen list that no longer exists is omitted.

func (*ManagementAccessHandler) Put

func (h *ManagementAccessHandler) Put(c *gin.Context)

Put replaces the chosen lists. A choice that would refuse the caller is refused before the write.

type ManualChallengeHandler

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

ManualChallengeHandler handles manual DNS challenge API requests.

func NewManualChallengeHandler

func NewManualChallengeHandler(challengeService ManualChallengeServiceInterface, providerService DNSProviderServiceInterface) *ManualChallengeHandler

NewManualChallengeHandler creates a new manual challenge handler.

func (*ManualChallengeHandler) CreateChallenge

func (h *ManualChallengeHandler) CreateChallenge(c *gin.Context)

CreateChallenge handles POST /api/v1/dns-providers/:id/manual-challenges Creates a new manual DNS challenge.

func (*ManualChallengeHandler) DeleteChallenge

func (h *ManualChallengeHandler) DeleteChallenge(c *gin.Context)

DeleteChallenge handles DELETE /api/v1/dns-providers/:id/manual-challenge/:challengeId Cancels/deletes a challenge.

func (*ManualChallengeHandler) GetChallenge

func (h *ManualChallengeHandler) GetChallenge(c *gin.Context)

GetChallenge handles GET /api/v1/dns-providers/:id/manual-challenge/:challengeId Returns the status and details of a manual DNS challenge.

func (*ManualChallengeHandler) ListChallenges

func (h *ManualChallengeHandler) ListChallenges(c *gin.Context)

ListChallenges handles GET /api/v1/dns-providers/:id/manual-challenges Returns all challenges for a provider.

func (*ManualChallengeHandler) PollChallenge

func (h *ManualChallengeHandler) PollChallenge(c *gin.Context)

PollChallenge handles GET /api/v1/dns-providers/:id/manual-challenge/:challengeId/poll Returns the current status for polling.

func (*ManualChallengeHandler) RegisterRoutes

func (h *ManualChallengeHandler) RegisterRoutes(rg *gin.RouterGroup)

RegisterRoutes registers all manual challenge routes.

func (*ManualChallengeHandler) VerifyChallenge

func (h *ManualChallengeHandler) VerifyChallenge(c *gin.Context)

VerifyChallenge handles POST /api/v1/dns-providers/:id/manual-challenge/:challengeId/verify Triggers DNS verification for a challenge.

type ManualChallengeResponse

type ManualChallengeResponse struct {
	ID                   string `json:"id"`
	ProviderID           uint   `json:"provider_id"`
	FQDN                 string `json:"fqdn"`
	Value                string `json:"value"`
	Status               string `json:"status"`
	DNSPropagated        bool   `json:"dns_propagated"`
	CreatedAt            string `json:"created_at"`
	ExpiresAt            string `json:"expires_at"`
	LastCheckAt          string `json:"last_check_at,omitempty"`
	TimeRemainingSeconds int    `json:"time_remaining_seconds"`
	ErrorMessage         string `json:"error_message,omitempty"`
}

ManualChallengeResponse represents the API response for a manual challenge.

type ManualChallengeServiceInterface

type ManualChallengeServiceInterface interface {
	CreateChallenge(ctx context.Context, req services.CreateChallengeRequest) (*models.ManualChallenge, error)
	GetChallengeForUser(ctx context.Context, challengeID string, userID uint) (*models.ManualChallenge, error)
	ListChallengesForProvider(ctx context.Context, providerID, userID uint) ([]models.ManualChallenge, error)
	VerifyChallenge(ctx context.Context, challengeID string, userID uint) (*services.VerifyResult, error)
	PollChallengeStatus(ctx context.Context, challengeID string, userID uint) (*services.ChallengeStatusResponse, error)
	DeleteChallenge(ctx context.Context, challengeID string, userID uint) error
}

ManualChallengeServiceInterface defines the interface for manual challenge operations. This allows for easier testing by enabling mock implementations.

type MyIPResponse

type MyIPResponse struct {
	IP     string `json:"ip"`
	Source string `json:"source"`
}

type NPMAccessItem

type NPMAccessItem struct {
	ID           int    `json:"id"`
	AccessListID int    `json:"access_list_id"`
	Address      string `json:"address"`
	Directive    string `json:"directive"`
	CreatedOn    string `json:"created_on"`
	ModifiedOn   string `json:"modified_on"`
}

NPMAccessItem represents an item in an NPM access list.

type NPMAccessList

type NPMAccessList struct {
	ID                  int             `json:"id"`
	Name                string          `json:"name"`
	PassAuth            int             `json:"pass_auth"`
	SatisfyAny          int             `json:"satisfy_any"`
	OwnerUserID         int             `json:"owner_user_id"`
	Items               []NPMAccessItem `json:"items"`
	Clients             []NPMAccessItem `json:"clients"`
	ProxyHostsCount     int             `json:"proxy_host_count"`
	CreatedOn           string          `json:"created_on"`
	ModifiedOn          string          `json:"modified_on"`
	AuthorizationHeader any             `json:"authorization_header"`
}

NPMAccessList represents an access list from NPM export.

type NPMCertificate

type NPMCertificate struct {
	ID             int      `json:"id"`
	Provider       string   `json:"provider"`
	NiceName       string   `json:"nice_name"`
	DomainNames    []string `json:"domain_names"`
	ExpiresOn      string   `json:"expires_on"`
	CreatedOn      string   `json:"created_on"`
	ModifiedOn     string   `json:"modified_on"`
	IsDNSChallenge bool     `json:"is_dns_challenge"`
	Meta           any      `json:"meta"`
}

NPMCertificate represents a certificate from NPM export.

type NPMExport

type NPMExport struct {
	ProxyHosts   []NPMProxyHost   `json:"proxy_hosts"`
	AccessLists  []NPMAccessList  `json:"access_lists"`
	Certificates []NPMCertificate `json:"certificates"`
}

NPMExport represents the top-level structure of an NPM export file.

type NPMImportHandler

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

NPMImportHandler handles NPM configuration imports.

func NewNPMImportHandler

func NewNPMImportHandler(db *gorm.DB) *NPMImportHandler

NewNPMImportHandler creates a new NPM import handler.

func (*NPMImportHandler) Cancel

func (h *NPMImportHandler) Cancel(c *gin.Context)

Cancel cancels an NPM import session and cleans up resources.

func (*NPMImportHandler) Commit

func (h *NPMImportHandler) Commit(c *gin.Context)

Commit finalizes the NPM import with user's conflict resolutions.

func (*NPMImportHandler) RegisterRoutes

func (h *NPMImportHandler) RegisterRoutes(router *gin.RouterGroup)

RegisterRoutes registers NPM import routes.

func (*NPMImportHandler) Upload

func (h *NPMImportHandler) Upload(c *gin.Context)

Upload parses an NPM export JSON and returns a preview with conflict detection.

type NPMProxyHost

type NPMProxyHost struct {
	ID                       int      `json:"id"`
	DomainNames              []string `json:"domain_names"`
	ForwardScheme            string   `json:"forward_scheme"`
	ForwardHost              string   `json:"forward_host"`
	ForwardPort              int      `json:"forward_port"`
	CertificateID            *int     `json:"certificate_id"`
	SSLForced                bool     `json:"ssl_forced"`
	CachingEnabled           bool     `json:"caching_enabled"`
	BlockExploits            bool     `json:"block_exploits"`
	AdvancedConfig           string   `json:"advanced_config"`
	Meta                     any      `json:"meta"`
	AllowWebsocketUpgrade    bool     `json:"allow_websocket_upgrade"`
	HTTP2Support             bool     `json:"http2_support"`
	HSTSEnabled              bool     `json:"hsts_enabled"`
	HSTSSubdomains           bool     `json:"hsts_subdomains"`
	AccessListID             *int     `json:"access_list_id"`
	Enabled                  bool     `json:"enabled"`
	Locations                []any    `json:"locations"`
	CustomLocations          []any    `json:"custom_locations"`
	OwnerUserID              int      `json:"owner_user_id"`
	UseDefaultLocation       bool     `json:"use_default_location"`
	IPV6                     bool     `json:"ipv6"`
	CreatedOn                string   `json:"created_on"`
	ModifiedOn               string   `json:"modified_on"`
	ForwardDomainName        string   `json:"forward_domain_name"`
	ForwardDomainNameEnabled bool     `json:"forward_domain_name_enabled"`
}

NPMProxyHost represents a proxy host from NPM export.

type NotificationHandler

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

func NewNotificationHandler

func NewNotificationHandler(service *services.NotificationService) *NotificationHandler

func (*NotificationHandler) List

func (h *NotificationHandler) List(c *gin.Context)

func (*NotificationHandler) MarkAllAsRead

func (h *NotificationHandler) MarkAllAsRead(c *gin.Context)

func (*NotificationHandler) MarkAsRead

func (h *NotificationHandler) MarkAsRead(c *gin.Context)

type NotificationProviderHandler

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

func NewNotificationProviderHandler

func NewNotificationProviderHandler(service *services.NotificationService) *NotificationProviderHandler

func NewNotificationProviderHandlerWithDeps

func NewNotificationProviderHandlerWithDeps(service *services.NotificationService, securityService *services.SecurityService, dataRoot string) *NotificationProviderHandler

func (*NotificationProviderHandler) Create

func (h *NotificationProviderHandler) Create(c *gin.Context)

func (*NotificationProviderHandler) Delete

func (h *NotificationProviderHandler) Delete(c *gin.Context)

func (*NotificationProviderHandler) List

func (*NotificationProviderHandler) Preview

func (h *NotificationProviderHandler) Preview(c *gin.Context)

Preview renders the template for a provider and returns the resulting JSON object or an error.

func (*NotificationProviderHandler) Templates

func (h *NotificationProviderHandler) Templates(c *gin.Context)

Templates returns a list of built-in templates a provider can use.

func (*NotificationProviderHandler) Test

func (*NotificationProviderHandler) Update

func (h *NotificationProviderHandler) Update(c *gin.Context)

type NotificationTemplateHandler

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

func NewNotificationTemplateHandlerWithDeps

func NewNotificationTemplateHandlerWithDeps(s *services.NotificationService, securityService *services.SecurityService, dataRoot string) *NotificationTemplateHandler

func (*NotificationTemplateHandler) Create

func (h *NotificationTemplateHandler) Create(c *gin.Context)

func (*NotificationTemplateHandler) Delete

func (h *NotificationTemplateHandler) Delete(c *gin.Context)

func (*NotificationTemplateHandler) List

func (*NotificationTemplateHandler) Preview

func (h *NotificationTemplateHandler) Preview(c *gin.Context)

Preview allows rendering an arbitrary template (provided in request) or a stored template by id.

func (*NotificationTemplateHandler) Update

func (h *NotificationTemplateHandler) Update(c *gin.Context)

type OSChecker

type OSChecker struct{}

func (OSChecker) Check

func (OSChecker) Check(path, required string) util.PermissionCheck

type OrthrusHandler

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

func NewOrthrusHandler

func NewOrthrusHandler(orthrsuSvc *services.OrthrusService, securityService *services.SecurityService) *OrthrusHandler

NewOrthrusHandler creates an OrthrusHandler backed by the given service. securityService is used to emit an audit entry whenever an operator toggles an agent's write-mode flag (see Patch) — a separate, handler-level concern from the per-request write-path audit entries Muzzle emits directly via the AuditLogger interface (see muzzle.go), following this codebase's existing convention of logging admin-initiated audit events at the handler layer rather than inside the service (compare security_handler.go, crowdsec_handler.go).

func (*OrthrusHandler) Delete

func (h *OrthrusHandler) Delete(c *gin.Context)

Delete removes an Orthrus agent from the database.

func (*OrthrusHandler) Get

func (h *OrthrusHandler) Get(c *gin.Context)

Get retrieves a single Orthrus agent by UUID.

func (*OrthrusHandler) GetInstallSnippets

func (h *OrthrusHandler) GetInstallSnippets(c *gin.Context)

GetInstallSnippets returns platform install templates for an agent. The real auth key is never present in snippets; the placeholder <AUTH_KEY> must be replaced by the user with the value returned at Provision time.

func (*OrthrusHandler) GetProxyStatus

func (h *OrthrusHandler) GetProxyStatus(c *gin.Context)

GetProxyStatus returns the runtime external Docker proxy state for an agent. 404 when the agent is not found in the database. When the agent exists but is not currently connected, agent_online is false and live fields are zero.

func (*OrthrusHandler) List

func (h *OrthrusHandler) List(c *gin.Context)

List returns all registered Orthrus agents.

func (*OrthrusHandler) LocalNetworks

func (h *OrthrusHandler) LocalNetworks(c *gin.Context)

LocalNetworks lists the host networks the external proxy can listen on, with the address the automatic setting would choose.

func (*OrthrusHandler) Patch

func (h *OrthrusHandler) Patch(c *gin.Context)

Patch applies a partial update to an Orthrus agent. If WriteEnabled is present in the request, this is the one field on this endpoint whose change is itself security-relevant enough to warrant its own audit entry (distinct from, and in addition to, the per-write-request audit entries Muzzle emits directly for actual proxied traffic — see muzzle.go).

func (*OrthrusHandler) Provision

func (h *OrthrusHandler) Provision(c *gin.Context)

Provision creates a new Orthrus agent and returns the auth key exactly once.

func (*OrthrusHandler) RegisterRoutes

func (h *OrthrusHandler) RegisterRoutes(read, admin *gin.RouterGroup)

RegisterRoutes wires the Orthrus agent endpoints. The agent list/summary reads that back the role=user-reachable proxy-host create/edit flow are registered on read; agent provisioning, mutation, revocation and the detail endpoints (install snippets embed a bootstrap token; proxy-status exposes agent internals) are registered on admin (deny-by-default for role=user). Callers that do not need the split may pass the same group for both.

func (*OrthrusHandler) Revoke

func (h *OrthrusHandler) Revoke(c *gin.Context)

Revoke invalidates the auth key for an agent and disconnects its active session.

func (*OrthrusHandler) RotateKey

func (h *OrthrusHandler) RotateKey(c *gin.Context)

RotateKey replaces an agent's auth key and returns the new key exactly once. The response is never cached. A security audit entry records the rotation without the key.

func (*OrthrusHandler) SetConfigApplier

func (h *OrthrusHandler) SetConfigApplier(a proxyConfigApplier)

SetConfigApplier sets the applier that re-evaluates proxy hosts after an external proxy change. A nil applier skips the re-evaluation.

func (*OrthrusHandler) SetProxyResolver

func (h *OrthrusHandler) SetProxyResolver(r orthrusProxyStatusResolver)

SetProxyResolver wires a live OrthrusServer so that GetProxyStatus can return real-time external proxy state for connected agents.

type PasswordAttemptGuard

type PasswordAttemptGuard interface {
	AllowPasswordAttempt(c *gin.Context) bool
}

PasswordAttemptGuard charges one account-password verification against the caller's sign-in budget. It returns false after writing the 429 response. Implemented by *middleware.AuthRateLimiter.

type PermissionChecker

type PermissionChecker interface {
	Check(path, required string) util.PermissionCheck
}

type PluginHandler

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

PluginHandler handles plugin-related API endpoints.

func NewPluginHandler

func NewPluginHandler(db *gorm.DB, pluginLoader *services.PluginLoaderService) *PluginHandler

NewPluginHandler creates a new plugin handler.

func (*PluginHandler) DisablePlugin

func (h *PluginHandler) DisablePlugin(c *gin.Context)

DisablePlugin disables an active plugin. @Summary Disable a plugin @Tags Plugins @Param id path int true "Plugin ID" @Success 200 {object} gin.H @Router /admin/plugins/{id}/disable [post]

func (*PluginHandler) EnablePlugin

func (h *PluginHandler) EnablePlugin(c *gin.Context)

EnablePlugin enables a disabled plugin. @Summary Enable a plugin @Tags Plugins @Param id path int true "Plugin ID" @Success 200 {object} gin.H @Router /admin/plugins/{id}/enable [post]

func (*PluginHandler) GetPlugin

func (h *PluginHandler) GetPlugin(c *gin.Context)

GetPlugin returns details for a specific plugin. @Summary Get plugin details @Tags Plugins @Produce json @Param id path int true "Plugin ID" @Success 200 {object} PluginInfo @Router /admin/plugins/{id} [get]

func (*PluginHandler) ListPlugins

func (h *PluginHandler) ListPlugins(c *gin.Context)

ListPlugins returns all plugins (built-in and external). @Summary List all DNS provider plugins @Tags Plugins @Produce json @Success 200 {array} PluginInfo @Router /admin/plugins [get]

func (*PluginHandler) ReloadPlugins

func (h *PluginHandler) ReloadPlugins(c *gin.Context)

ReloadPlugins reloads all plugins from the plugin directory. @Summary Reload all plugins @Tags Plugins @Success 200 {object} gin.H @Router /admin/plugins/reload [post]

type PluginInfo

type PluginInfo struct {
	ID               uint    `json:"id"`
	UUID             string  `json:"uuid"`
	Name             string  `json:"name"`
	Type             string  `json:"type"`
	Enabled          bool    `json:"enabled"`
	Status           string  `json:"status"`
	Error            string  `json:"error,omitempty"`
	Version          string  `json:"version,omitempty"`
	Author           string  `json:"author,omitempty"`
	IsBuiltIn        bool    `json:"is_built_in"`
	Description      string  `json:"description,omitempty"`
	DocumentationURL string  `json:"documentation_url,omitempty"`
	LoadedAt         *string `json:"loaded_at,omitempty"`
	CreatedAt        string  `json:"created_at"`
	UpdatedAt        string  `json:"updated_at"`
}

PluginInfo represents plugin information for API responses.

type PreviewInviteURLRequest

type PreviewInviteURLRequest struct {
	Email string `json:"email" binding:"required,email"`
}

PreviewInviteURLRequest represents the request for previewing an invite URL.

type ProxyGroupHandler

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

ProxyGroupHandler handles CRUD operations for proxy groups.

func NewProxyGroupHandler

func NewProxyGroupHandler(db *gorm.DB) *ProxyGroupHandler

NewProxyGroupHandler creates a new ProxyGroupHandler.

func (*ProxyGroupHandler) Create

func (h *ProxyGroupHandler) Create(c *gin.Context)

Create creates a new proxy group.

func (*ProxyGroupHandler) Delete

func (h *ProxyGroupHandler) Delete(c *gin.Context)

Delete removes a proxy group by UUID, clearing host assignments.

func (*ProxyGroupHandler) Get

func (h *ProxyGroupHandler) Get(c *gin.Context)

Get returns a single proxy group by UUID, including host count.

func (*ProxyGroupHandler) List

func (h *ProxyGroupHandler) List(c *gin.Context)

List returns all proxy groups ordered by name.

func (*ProxyGroupHandler) RegisterRoutes

func (h *ProxyGroupHandler) RegisterRoutes(router *gin.RouterGroup)

RegisterRoutes registers proxy group routes on the given router group.

func (*ProxyGroupHandler) Update

func (h *ProxyGroupHandler) Update(c *gin.Context)

Update updates an existing proxy group by UUID.

type ProxyHostHandler

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

ProxyHostHandler handles CRUD operations for proxy hosts.

func NewProxyHostHandler

func NewProxyHostHandler(db *gorm.DB, caddyManager *caddy.Manager, ns *services.NotificationService, uptimeService *services.UptimeService) *ProxyHostHandler

NewProxyHostHandler creates a new proxy host handler.

func (*ProxyHostHandler) BulkUpdateACL

func (h *ProxyHostHandler) BulkUpdateACL(c *gin.Context)

BulkUpdateACL applies or removes an access list to multiple proxy hosts.

func (*ProxyHostHandler) BulkUpdateGroup

func (h *ProxyHostHandler) BulkUpdateGroup(c *gin.Context)

BulkUpdateGroup assigns or removes a proxy group from multiple proxy hosts. PUT /proxy-hosts/bulk-update-group

func (*ProxyHostHandler) BulkUpdateSecurityHeaders

func (h *ProxyHostHandler) BulkUpdateSecurityHeaders(c *gin.Context)

BulkUpdateSecurityHeaders applies or removes a security header profile to multiple proxy hosts.

func (*ProxyHostHandler) Create

func (h *ProxyHostHandler) Create(c *gin.Context)

Create creates a new proxy host.

func (*ProxyHostHandler) Delete

func (h *ProxyHostHandler) Delete(c *gin.Context)

Delete removes a proxy host.

func (*ProxyHostHandler) Get

func (h *ProxyHostHandler) Get(c *gin.Context)

Get retrieves a proxy host by UUID.

func (*ProxyHostHandler) List

func (h *ProxyHostHandler) List(c *gin.Context)

List retrieves all proxy hosts.

func (*ProxyHostHandler) RegisterRoutes

func (h *ProxyHostHandler) RegisterRoutes(router *gin.RouterGroup)

RegisterRoutes registers proxy host routes.

func (*ProxyHostHandler) SetCertificateService

func (h *ProxyHostHandler) SetCertificateService(certService services.CertificateCacheInvalidator)

SetCertificateService wires an optional certificate cache invalidator into the underlying proxy host service, so that creating, updating, or deleting a proxy host immediately refreshes the certificates list's "in_use" status instead of waiting out CertificateService's scan TTL. Safe to leave unset in tests/import flows that don't need this.

func (*ProxyHostHandler) SetConnectionTestLimiter

func (g *ProxyHostHandler) SetConnectionTestLimiter(l *ratelimit.KeyedLimiter)

SetConnectionTestLimiter replaces the limiter of this handler. Tests use it to set a small or fake limit; production code keeps the default.

func (*ProxyHostHandler) TestConnection

func (h *ProxyHostHandler) TestConnection(c *gin.Context)

TestConnection checks if the proxy host is reachable.

func (*ProxyHostHandler) Update

func (h *ProxyHostHandler) Update(c *gin.Context)

Update updates an existing proxy host.

type ProxyHostResponse

type ProxyHostResponse struct {
	UUID                    string                        `json:"uuid"`
	Name                    string                        `json:"name"`
	DomainNames             string                        `json:"domain_names"`
	ForwardScheme           string                        `json:"forward_scheme"`
	ForwardHost             string                        `json:"forward_host"`
	ForwardPort             int                           `json:"forward_port"`
	SSLForced               bool                          `json:"ssl_forced"`
	HTTP2Support            bool                          `json:"http2_support"`
	HSTSEnabled             bool                          `json:"hsts_enabled"`
	HSTSSubdomains          bool                          `json:"hsts_subdomains"`
	BlockExploits           bool                          `json:"block_exploits"`
	WebsocketSupport        bool                          `json:"websocket_support"`
	Application             string                        `json:"application"`
	Enabled                 bool                          `json:"enabled"`
	CertificateID           *uint                         `json:"certificate_id"`
	Certificate             *models.SSLCertificate        `json:"certificate,omitempty"`
	AccessListID            *uint                         `json:"access_list_id"`
	AccessList              *models.AccessList            `json:"access_list,omitempty"`
	Locations               []models.Location             `json:"locations"`
	AdvancedConfig          string                        `json:"advanced_config"`
	AdvancedConfigBackup    string                        `json:"advanced_config_backup"`
	ForwardAuthEnabled      bool                          `json:"forward_auth_enabled"`
	WAFDisabled             bool                          `json:"waf_disabled"`
	SecurityHeaderProfileID *uint                         `json:"security_header_profile_id"`
	SecurityHeaderProfile   *models.SecurityHeaderProfile `json:"security_header_profile,omitempty"`
	SecurityHeadersEnabled  bool                          `json:"security_headers_enabled"`
	SecurityHeadersCustom   string                        `json:"security_headers_custom"`
	EnableStandardHeaders   *bool                         `json:"enable_standard_headers,omitempty"`
	DNSProviderID           *uint                         `json:"dns_provider_id,omitempty"`
	DNSProvider             *models.DNSProvider           `json:"dns_provider,omitempty"`
	UseDNSChallenge         bool                          `json:"use_dns_challenge"`
	ProxyGroupID            *uint                         `json:"-"`
	ProxyGroup              *models.ProxyGroup            `json:"proxy_group,omitempty"`
	CreatedAt               time.Time                     `json:"created_at"`
	UpdatedAt               time.Time                     `json:"updated_at"`
	Warnings                []ProxyHostWarning            `json:"warnings,omitempty"`
}

ProxyHostResponse wraps a proxy host with optional advisory warnings. Uses explicit fields to avoid exposing internal database IDs.

func NewProxyHostResponse

func NewProxyHostResponse(host *models.ProxyHost, warnings []ProxyHostWarning) ProxyHostResponse

NewProxyHostResponse creates a ProxyHostResponse from a ProxyHost model.

type ProxyHostServiceInterface

type ProxyHostServiceInterface interface {
	Create(host *models.ProxyHost) error
	Update(host *models.ProxyHost) error
	CreateImported(budget *services.ImportNameBudget, host *models.ProxyHost) error
	UpdateImported(budget *services.ImportNameBudget, host *models.ProxyHost) error
	List() ([]models.ProxyHost, error)
}

ProxyHostServiceInterface defines the subset of ProxyHostService needed by ImportHandler. This allows for easier testing by enabling mock implementations.

type ProxyHostWarning

type ProxyHostWarning struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

ProxyHostWarning represents an advisory warning about proxy host configuration.

type PublicOriginSource

type PublicOriginSource interface {
	TrustedOrigin() string
}

PublicOriginSource yields the configured public origin ("scheme://host[:port]"), or "" when none is set. The browser origin guard implements it from its last rebuild, so a WebSocket handshake never reads the database.

type RealCommandExecutor

type RealCommandExecutor struct{}

RealCommandExecutor executes commands using os/exec.

func (*RealCommandExecutor) Execute

func (r *RealCommandExecutor) Execute(ctx context.Context, name string, args ...string) ([]byte, error)

Execute runs a command and returns its combined output (stdout/stderr)

type RedirectionHostHandler

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

RedirectionHostHandler handles CRUD operations for redirection hosts, following ProxyHostHandler's conventions (structured gin.H{"error": ...} errors, server-generated UUIDs, partial-update-via-map[string]any on Update) — see docs/plans/archive/2026-09-23_redirection-hosts-1367_spec.md §4.4.

func NewRedirectionHostHandler

func NewRedirectionHostHandler(db *gorm.DB, caddyManager *caddy.Manager) *RedirectionHostHandler

NewRedirectionHostHandler creates a new RedirectionHostHandler.

func (*RedirectionHostHandler) Create

func (h *RedirectionHostHandler) Create(c *gin.Context)

Create creates a new redirection host.

func (*RedirectionHostHandler) Delete

func (h *RedirectionHostHandler) Delete(c *gin.Context)

Delete removes a redirection host by UUID.

func (*RedirectionHostHandler) Get

func (h *RedirectionHostHandler) Get(c *gin.Context)

Get retrieves a redirection host by UUID.

func (*RedirectionHostHandler) List

func (h *RedirectionHostHandler) List(c *gin.Context)

List retrieves all redirection hosts.

func (*RedirectionHostHandler) RegisterRoutes

func (h *RedirectionHostHandler) RegisterRoutes(router *gin.RouterGroup)

RegisterRoutes registers redirection host routes on the given router group.

func (*RedirectionHostHandler) Update

func (h *RedirectionHostHandler) Update(c *gin.Context)

Update partially updates an existing redirection host by UUID.

type RemoteServerHandler

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

RemoteServerHandler handles HTTP requests for remote server management.

func NewRemoteServerHandler

func NewRemoteServerHandler(service *services.RemoteServerService, ns *services.NotificationService) *RemoteServerHandler

NewRemoteServerHandler creates a new remote server handler.

func (*RemoteServerHandler) Create

func (h *RemoteServerHandler) Create(c *gin.Context)

Create creates a new remote server.

func (*RemoteServerHandler) Delete

func (h *RemoteServerHandler) Delete(c *gin.Context)

Delete removes a remote server.

func (*RemoteServerHandler) Get

func (h *RemoteServerHandler) Get(c *gin.Context)

Get retrieves a remote server by UUID.

func (*RemoteServerHandler) List

func (h *RemoteServerHandler) List(c *gin.Context)

List retrieves all remote servers.

func (*RemoteServerHandler) RegisterRoutes

func (h *RemoteServerHandler) RegisterRoutes(read, admin *gin.RouterGroup)

RegisterRoutes wires the remote-server endpoints. The list/detail reads that back the role=user-reachable proxy-host create/edit flow and the Remote Servers page are registered on read; create/update/delete and the SSH connection-test endpoints (they act on stored SSH targets and credentials) are registered on admin (deny-by-default for role=user). Callers that do not need the split may pass the same group for both.

func (*RemoteServerHandler) SetConnectionTestLimiter

func (g *RemoteServerHandler) SetConnectionTestLimiter(l *ratelimit.KeyedLimiter)

SetConnectionTestLimiter replaces the limiter of this handler. Tests use it to set a small or fake limit; production code keeps the default.

func (*RemoteServerHandler) SetUptimeService

func (h *RemoteServerHandler) SetUptimeService(u *services.UptimeService)

SetUptimeService wires the uptime service so remote-server CRUD drives an immediate targeted monitor sync (spec §3.1.3, user decision #4). Mirrors ProxyHostHandler.SetCertificateService — a setter rather than a constructor arg keeps the ~20 existing NewRemoteServerHandler call sites unchanged.

func (*RemoteServerHandler) TestConnection

func (h *RemoteServerHandler) TestConnection(c *gin.Context)

TestConnection tests the TCP connection to a remote server.

func (*RemoteServerHandler) TestConnectionCustom

func (h *RemoteServerHandler) TestConnectionCustom(c *gin.Context)

TestConnectionCustom tests connectivity to a host/port provided in the body

func (*RemoteServerHandler) Update

func (h *RemoteServerHandler) Update(c *gin.Context)

Update updates an existing remote server.

type SMTPConfigRequest

type SMTPConfigRequest struct {
	Host        string `json:"host" binding:"required"`
	Port        int    `json:"port" binding:"required,min=1,max=65535"`
	Username    string `json:"username"`
	Password    string `json:"password"`
	FromAddress string `json:"from_address" binding:"required,email"`
	Encryption  string `json:"encryption" binding:"required,oneof=none ssl starttls"`
}

SMTPConfigRequest represents the request body for SMTP configuration.

type SecurityHandler

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

SecurityHandler handles security-related API requests.

func NewSecurityHandler

func NewSecurityHandler(cfg config.SecurityConfig, db *gorm.DB, caddyManager CaddyConfigManager) *SecurityHandler

NewSecurityHandler creates a new SecurityHandler.

func NewSecurityHandlerWithDeps

func NewSecurityHandlerWithDeps(cfg config.SecurityConfig, db *gorm.DB, caddyManager CaddyConfigManager, cerberus CacheInvalidator) *SecurityHandler

NewSecurityHandlerWithDeps creates a new SecurityHandler with optional cache invalidation.

func (*SecurityHandler) AddWAFExclusion

func (h *SecurityHandler) AddWAFExclusion(c *gin.Context)

AddWAFExclusion adds a rule exclusion to the WAF configuration. The duplicate check and the write share one write lock. A refused proxy apply restores the stored exclusions.

func (*SecurityHandler) Close

func (h *SecurityHandler) Close()

Close stops the background audit goroutine. Required for test cleanup.

func (*SecurityHandler) CreateDecision

func (h *SecurityHandler) CreateDecision(c *gin.Context)

CreateDecision creates a manual decision (override) - for now no checks besides payload

func (*SecurityHandler) DeleteRuleSet

func (h *SecurityHandler) DeleteRuleSet(c *gin.Context)

DeleteRuleSet removes a ruleset by id

func (*SecurityHandler) DeleteWAFExclusion

func (h *SecurityHandler) DeleteWAFExclusion(c *gin.Context)

DeleteWAFExclusion removes a rule exclusion by rule_id. The lookup and the write share one write lock. A refused proxy apply restores the stored exclusions.

func (*SecurityHandler) Disable

func (h *SecurityHandler) Disable(c *gin.Context)

Disable toggles Cerberus off; requires break-glass token or localhost request

func (*SecurityHandler) DisableACL

func (h *SecurityHandler) DisableACL(c *gin.Context)

DisableACL disables the Access Control List security module POST /api/v1/security/acl/disable

func (*SecurityHandler) DisableCerberus

func (h *SecurityHandler) DisableCerberus(c *gin.Context)

DisableCerberus disables the Cerberus security monitoring module POST /api/v1/security/cerberus/disable

func (*SecurityHandler) DisableCrowdSec

func (h *SecurityHandler) DisableCrowdSec(c *gin.Context)

DisableCrowdSec stops the CrowdSec engine through the lifecycle, which also turns the CrowdSec setting off. POST /api/v1/security/crowdsec/disable

func (*SecurityHandler) DisableRateLimit

func (h *SecurityHandler) DisableRateLimit(c *gin.Context)

DisableRateLimit disables the Rate Limiting security module POST /api/v1/security/rate-limit/disable

func (*SecurityHandler) DisableWAF

func (h *SecurityHandler) DisableWAF(c *gin.Context)

DisableWAF disables the Web Application Firewall security module POST /api/v1/security/waf/disable

func (*SecurityHandler) Enable

func (h *SecurityHandler) Enable(c *gin.Context)

Enable turns Cerberus on. The allow-list or break-glass check runs against the row read under the write lock, and the enable is written in that same lock. A refused proxy apply restores the row.

func (*SecurityHandler) EnableACL

func (h *SecurityHandler) EnableACL(c *gin.Context)

EnableACL enables the Access Control List security module POST /api/v1/security/acl/enable

func (*SecurityHandler) EnableCerberus

func (h *SecurityHandler) EnableCerberus(c *gin.Context)

EnableCerberus enables the Cerberus security monitoring module POST /api/v1/security/cerberus/enable

func (*SecurityHandler) EnableCrowdSec

func (h *SecurityHandler) EnableCrowdSec(c *gin.Context)

EnableCrowdSec starts the CrowdSec engine through the lifecycle, which also turns the CrowdSec setting on. POST /api/v1/security/crowdsec/enable

func (*SecurityHandler) EnableRateLimit

func (h *SecurityHandler) EnableRateLimit(c *gin.Context)

EnableRateLimit enables the Rate Limiting security module POST /api/v1/security/rate-limit/enable

func (*SecurityHandler) EnableWAF

func (h *SecurityHandler) EnableWAF(c *gin.Context)

EnableWAF enables the Web Application Firewall security module POST /api/v1/security/waf/enable

func (*SecurityHandler) GenerateBreakGlass

func (h *SecurityHandler) GenerateBreakGlass(c *gin.Context)

GenerateBreakGlass generates a break-glass token and returns the plaintext token once

func (*SecurityHandler) GeoIPAlertSource

func (h *SecurityHandler) GeoIPAlertSource() alerts.Source

GeoIPAlertSource returns the notification bell alert for country lists that are not enforced because no GeoIP database is usable. It is active while countryListsNotEnforced names a list, so it follows the last applied config and goes away once a later apply succeeds with a usable database. DatabaseAvailable tells the bell whether a reload can help.

func (*SecurityHandler) GeoIPManagementAlertSource

func (h *SecurityHandler) GeoIPManagementAlertSource() alerts.Source

GeoIPManagementAlertSource returns the bell alert for country lists that protect Charon's own interface and are not enforced because no GeoIP database is usable. It carries the "management" scope, so it is kept apart from the proxy-host alert with the same key.

func (*SecurityHandler) GetConfig

func (h *SecurityHandler) GetConfig(c *gin.Context)

GetConfig returns the site security configuration from DB or default

func (*SecurityHandler) GetGeoIPStatus

func (h *SecurityHandler) GetGeoIPStatus(c *gin.Context)

GetGeoIPStatus returns the current status of the GeoIP service and the database card.

func (*SecurityHandler) GetRateLimitPresets

func (h *SecurityHandler) GetRateLimitPresets(c *gin.Context)

GetRateLimitPresets returns predefined rate limit configurations

func (*SecurityHandler) GetStatus

func (h *SecurityHandler) GetStatus(c *gin.Context)

GetStatus returns the current status of all security services. Priority chain: 1. Settings table (highest - runtime overrides) 2. SecurityConfig DB record (middle - user configuration) 3. Static config (lowest - defaults)

func (*SecurityHandler) GetWAFExclusions

func (h *SecurityHandler) GetWAFExclusions(c *gin.Context)

GetWAFExclusions returns current WAF rule exclusions from SecurityConfig

func (*SecurityHandler) ListDecisions

func (h *SecurityHandler) ListDecisions(c *gin.Context)

ListDecisions returns recent security decisions

func (*SecurityHandler) ListRuleSets

func (h *SecurityHandler) ListRuleSets(c *gin.Context)

ListRuleSets returns the list of known rulesets

func (*SecurityHandler) LookupGeoIP

func (h *SecurityHandler) LookupGeoIP(c *gin.Context)

LookupGeoIP performs a GeoIP lookup for a given IP address.

func (*SecurityHandler) PatchACL

func (h *SecurityHandler) PatchACL(c *gin.Context)

PatchACL handles PATCH requests to enable/disable ACL based on JSON body PATCH /api/v1/security/acl Expects: {"enabled": true/false}

func (*SecurityHandler) PatchCrowdSec

func (h *SecurityHandler) PatchCrowdSec(c *gin.Context)

PatchCrowdSec starts or stops the CrowdSec engine through the lifecycle, based on the JSON body. PATCH /api/v1/security/crowdsec Expects: {"enabled": true/false}

func (*SecurityHandler) PatchRateLimit

func (h *SecurityHandler) PatchRateLimit(c *gin.Context)

PatchRateLimit handles PATCH requests to enable/disable Rate Limiting based on JSON body PATCH /api/v1/security/rate-limit Expects: {"enabled": true/false}

func (*SecurityHandler) PatchWAF

func (h *SecurityHandler) PatchWAF(c *gin.Context)

PatchWAF handles PATCH requests to enable/disable WAF based on JSON body PATCH /api/v1/security/waf Expects: {"enabled": true/false}

func (*SecurityHandler) ReloadGeoIP

func (h *SecurityHandler) ReloadGeoIP(c *gin.Context)

ReloadGeoIP reloads the GeoIP database from disk.

func (*SecurityHandler) RemoveGeoIPDatabase

func (h *SecurityHandler) RemoveGeoIPDatabase(c *gin.Context)

RemoveGeoIPDatabase deletes the data-folder copy so the image's bundled copy is used again.

func (*SecurityHandler) ReplaceGeoIPDatabase

func (h *SecurityHandler) ReplaceGeoIPDatabase(c *gin.Context)

ReplaceGeoIPDatabase installs an uploaded country database as the data-folder copy. The request is one multipart part named file. The client's file name and content type are ignored and never stored.

func (*SecurityHandler) SetGeoIPService

func (h *SecurityHandler) SetGeoIPService(geoipSvc *services.GeoIPService)

SetGeoIPService sets the GeoIP service for the handler and builds the database store over it. The store applies the proxy config after a change when the handler has a caddy manager.

func (*SecurityHandler) UpdateConfig

func (h *SecurityHandler) UpdateConfig(c *gin.Context)

UpdateConfig creates or updates the SecurityConfig in DB

func (*SecurityHandler) UpsertRuleSet

func (h *SecurityHandler) UpsertRuleSet(c *gin.Context)

UpsertRuleSet uploads or updates a ruleset

func (*SecurityHandler) WithCrowdsecLifecycle

func (h *SecurityHandler) WithCrowdsecLifecycle(l CrowdsecLifecycle) *SecurityHandler

WithCrowdsecLifecycle wires the CrowdSec lifecycle that the security switches drive. A typed-nil handler is not wired.

type SecurityHeadersHandler

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

SecurityHeadersHandler manages security header profiles

func NewSecurityHeadersHandler

func NewSecurityHeadersHandler(db *gorm.DB, caddyManager *caddy.Manager) *SecurityHeadersHandler

NewSecurityHeadersHandler creates a new handler

func (*SecurityHeadersHandler) ApplyPreset

func (h *SecurityHeadersHandler) ApplyPreset(c *gin.Context)

ApplyPreset applies a preset to create/update a profile POST /api/v1/security/headers/presets/apply

func (*SecurityHeadersHandler) BuildCSP

func (h *SecurityHeadersHandler) BuildCSP(c *gin.Context)

BuildCSP builds a CSP string from directives POST /api/v1/security/headers/csp/build

func (*SecurityHeadersHandler) CalculateScore

func (h *SecurityHeadersHandler) CalculateScore(c *gin.Context)

CalculateScore calculates security score for given settings POST /api/v1/security/headers/score

func (*SecurityHeadersHandler) CreateProfile

func (h *SecurityHeadersHandler) CreateProfile(c *gin.Context)

CreateProfile creates a new security header profile. The fields the client sends are stored as sent, so an option switched off on create stays off. The client cannot mark a profile as a preset. POST /api/v1/security/headers/profiles

func (*SecurityHeadersHandler) DeleteProfile

func (h *SecurityHeadersHandler) DeleteProfile(c *gin.Context)

DeleteProfile deletes a profile (not presets) DELETE /api/v1/security/headers/profiles/:id

func (*SecurityHeadersHandler) GetPresets

func (h *SecurityHeadersHandler) GetPresets(c *gin.Context)

GetPresets returns the list of built-in presets GET /api/v1/security/headers/presets

func (*SecurityHeadersHandler) GetProfile

func (h *SecurityHeadersHandler) GetProfile(c *gin.Context)

GetProfile returns a single profile by ID or UUID GET /api/v1/security/headers/profiles/:id

func (*SecurityHeadersHandler) ListProfiles

func (h *SecurityHeadersHandler) ListProfiles(c *gin.Context)

ListProfiles returns all security header profiles GET /api/v1/security/headers/profiles

func (*SecurityHeadersHandler) UpdateProfile

func (h *SecurityHeadersHandler) UpdateProfile(c *gin.Context)

UpdateProfile updates an existing profile PUT /api/v1/security/headers/profiles/:id

func (*SecurityHeadersHandler) ValidateCSP

func (h *SecurityHeadersHandler) ValidateCSP(c *gin.Context)

ValidateCSP validates a CSP string POST /api/v1/security/headers/csp/validate

type SecurityNotificationHandler

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

SecurityNotificationHandler handles notification settings endpoints.

func NewSecurityNotificationHandler

func NewSecurityNotificationHandler(service SecurityNotificationServiceInterface) *SecurityNotificationHandler

NewSecurityNotificationHandler creates a new handler instance.

func NewSecurityNotificationHandlerWithDeps

func NewSecurityNotificationHandlerWithDeps(
	service SecurityNotificationServiceInterface,
	securityService *services.SecurityService,
	dataRoot string,
	notificationService *services.NotificationService,
	managementCIDRs []string,
) *SecurityNotificationHandler

func (*SecurityNotificationHandler) DeprecatedGetSettings

func (h *SecurityNotificationHandler) DeprecatedGetSettings(c *gin.Context)

func (*SecurityNotificationHandler) DeprecatedUpdateSettings

func (h *SecurityNotificationHandler) DeprecatedUpdateSettings(c *gin.Context)

func (*SecurityNotificationHandler) GetSettings

func (h *SecurityNotificationHandler) GetSettings(c *gin.Context)

GetSettings retrieves the current notification settings.

func (*SecurityNotificationHandler) HandleSecurityEvent

func (h *SecurityNotificationHandler) HandleSecurityEvent(c *gin.Context)

HandleSecurityEvent receives runtime security events from Caddy/Cerberus (Blocker 1: Production dispatch path). This endpoint is called by Caddy bouncer/middleware when security events occur (WAF blocks, CrowdSec decisions, etc.).

func (*SecurityNotificationHandler) UpdateSettings

func (h *SecurityNotificationHandler) UpdateSettings(c *gin.Context)

UpdateSettings is deprecated and returns 410 Gone (R6). Security settings must now be managed via provider Notification Events.

type SecurityNotificationServiceInterface

type SecurityNotificationServiceInterface interface {
	GetSettings() (*models.NotificationConfig, error)
	UpdateSettings(*models.NotificationConfig) error
	SendViaProviders(ctx context.Context, event models.SecurityEvent) error
}

SecurityNotificationServiceInterface defines the interface for security notification service.

type SettingsHandler

type SettingsHandler struct {
	DB           *gorm.DB
	MailService  *services.MailService
	CaddyManager CaddyConfigManager // For triggering config reload on security settings change
	Cerberus     CacheInvalidator   // For invalidating cache on security settings change
	SecuritySvc  *services.SecurityService

	DataRoot string
	// contains filtered or unexported fields
}

func NewSettingsHandler

func NewSettingsHandler(db *gorm.DB) *SettingsHandler

func NewSettingsHandlerWithDeps

func NewSettingsHandlerWithDeps(db *gorm.DB, caddyMgr CaddyConfigManager, cerberus CacheInvalidator, securitySvc *services.SecurityService, dataRoot string) *SettingsHandler

NewSettingsHandlerWithDeps creates a SettingsHandler with all dependencies for config reload

func (*SettingsHandler) GetSMTPConfig

func (h *SettingsHandler) GetSMTPConfig(c *gin.Context)

GetSMTPConfig returns the current SMTP configuration.

func (*SettingsHandler) GetSettings

func (h *SettingsHandler) GetSettings(c *gin.Context)

GetSettings returns all settings. The admin-only keys are answered to administrators only.

func (*SettingsHandler) PatchConfig

func (h *SettingsHandler) PatchConfig(c *gin.Context)

PatchConfig updates multiple configuration settings at once PATCH /api/v1/config Requires admin authentication

func (*SettingsHandler) SendTestEmail

func (h *SettingsHandler) SendTestEmail(c *gin.Context)

SendTestEmail sends a test email to verify the SMTP configuration.

func (*SettingsHandler) TestPublicURL

func (h *SettingsHandler) TestPublicURL(c *gin.Context)

TestPublicURL performs a server-side connectivity test with comprehensive SSRF protection. This endpoint implements defense-in-depth security: 1. Format validation: Ensures valid HTTP/HTTPS URLs without path components 2. SSRF validation: Pre-validates DNS resolution and blocks private/reserved IPs 3. Runtime protection: ssrfSafeDialer validates IPs again at connection time This multi-layer approach satisfies both static analysis (CodeQL) and runtime security.

func (*SettingsHandler) TestSMTPConfig

func (h *SettingsHandler) TestSMTPConfig(c *gin.Context)

TestSMTPConfig tests the SMTP connection.

func (*SettingsHandler) UpdateSMTPConfig

func (h *SettingsHandler) UpdateSMTPConfig(c *gin.Context)

UpdateSMTPConfig updates the SMTP configuration.

func (*SettingsHandler) UpdateSetting

func (h *SettingsHandler) UpdateSetting(c *gin.Context)

UpdateSetting updates or creates a setting.

func (*SettingsHandler) ValidatePublicURL

func (h *SettingsHandler) ValidatePublicURL(c *gin.Context)

ValidatePublicURL validates a URL is properly formatted for use as the application URL.

func (*SettingsHandler) WithACLMode

func (h *SettingsHandler) WithACLMode(mode string) *SettingsHandler

WithACLMode sets the static access-control mode the management lock-out guard reads when no runtime switch is stored.

func (*SettingsHandler) WithBrowserOriginRefresher

func (h *SettingsHandler) WithBrowserOriginRefresher(r BrowserOriginRefresher) *SettingsHandler

WithBrowserOriginRefresher wires the guard that trusts the configured public address. Saving that setting refreshes it.

func (*SettingsHandler) WithCrowdsecLifecycle

func (h *SettingsHandler) WithCrowdsecLifecycle(l CrowdsecLifecycle) *SettingsHandler

WithCrowdsecLifecycle wires the CrowdSec lifecycle that the settings API drives. A typed-nil handler is not wired.

type SetupRequest

type SetupRequest struct {
	Name     string `json:"name" binding:"required"`
	Email    string `json:"email" binding:"required,email"`
	Password string `json:"password" binding:"required,min=8"`
	// SetupCode is the first-run setup code printed to the log at startup or preset
	// through CHARON_SETUP_TOKEN.
	SetupCode string `json:"setup_code,omitempty"`
}

type StatsHandler

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

StatsHandler handles REST endpoints for the enhanced dashboard statistics API.

func NewStatsHandler

func NewStatsHandler(svc *services.StatsService) *StatsHandler

NewStatsHandler creates a StatsHandler without an ingester or hub reference.

func NewStatsHandlerFull

func NewStatsHandlerFull(svc *services.StatsService, ingester *services.StatsIngester, hub *StatsWSHub) *StatsHandler

NewStatsHandlerFull creates a fully wired StatsHandler with ingester and hub.

func NewStatsHandlerWithIngester

func NewStatsHandlerWithIngester(svc *services.StatsService, ingester *services.StatsIngester) *StatsHandler

NewStatsHandlerWithIngester creates a StatsHandler that can also serve the health endpoint.

func (*StatsHandler) GetCertExpiry

func (h *StatsHandler) GetCertExpiry(c *gin.Context)

GetCertExpiry returns certificates expiring within the given number of days. GET /api/stats/cert-expiry?within_days=30

func (*StatsHandler) GetRequests

func (h *StatsHandler) GetRequests(c *gin.Context)

GetRequests is an alias for GetTrafficVolume returning per-bucket request counts. GET /api/stats/requests?bucket=1h

func (*StatsHandler) GetStatsHealth

func (h *StatsHandler) GetStatsHealth(c *gin.Context)

GetStatsHealth returns the ingester health including the number of dropped log entries. GET /api/stats/health

func (*StatsHandler) GetStatsSummary

func (h *StatsHandler) GetStatsSummary(c *gin.Context)

GetStatsSummary returns request counts for the last 24h, 7d, and 30d. GET /api/stats/summary

func (*StatsHandler) GetStatusDistribution

func (h *StatsHandler) GetStatusDistribution(c *gin.Context)

GetStatusDistribution returns HTTP status code counts over the given period. GET /api/stats/status-distribution?period=24h

func (*StatsHandler) GetTopHosts

func (h *StatsHandler) GetTopHosts(c *gin.Context)

GetTopHosts returns the top N hosts by request count over the given period. GET /api/stats/top-hosts?period=24h&limit=10

func (*StatsHandler) GetTrafficVolume

func (h *StatsHandler) GetTrafficVolume(c *gin.Context)

GetTrafficVolume returns bytes sent bucketed by time interval. GET /api/stats/traffic-volume?bucket=1h

func (*StatsHandler) StatsWS

func (h *StatsHandler) StatsWS(c *gin.Context)

StatsWS upgrades the connection to WebSocket and streams stats push messages. GET /api/stats/ws

func (*StatsHandler) WithOriginPolicy

func (h *StatsHandler) WithOriginPolicy(s PublicOriginSource, trusted security.TrustedProxyMatcher) *StatsHandler

WithOriginPolicy wires the configured public origin and the trusted-proxy list into the WebSocket origin check.

func (*StatsHandler) WithStreamQuota

func (h *StatsHandler) WithStreamQuota(q *services.StreamQuota) *StatsHandler

WithStreamQuota caps the live streams this handler admits per user and in total.

type StatsWSHub

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

StatsWSHub manages WebSocket clients for real-time stats push messages. It implements services.BroadcastHub.

func NewStatsWSHub

func NewStatsWSHub() *StatsWSHub

NewStatsWSHub creates a new StatsWSHub ready to Run.

func (*StatsWSHub) Broadcast

func (h *StatsWSHub) Broadcast(msg services.StatsPushMessage)

Broadcast implements services.BroadcastHub. It is safe to call from any goroutine; the message is queued non-blocking.

func (*StatsWSHub) Run

func (h *StatsWSHub) Run(ctx context.Context)

Run processes registrations and broadcasts until ctx is cancelled. Start as a goroutine: go hub.Run(ctx)

func (*StatsWSHub) ServeClient

func (h *StatsWSHub) ServeClient(c *statsWSClient)

ServeClient registers an upgraded client with the hub. It blocks until the client disconnects. Call from a Gin handler.

type SystemHandler

type SystemHandler struct{}

func NewSystemHandler

func NewSystemHandler() *SystemHandler

func (*SystemHandler) GetMyIP

func (h *SystemHandler) GetMyIP(c *gin.Context)

GetMyIP returns the client's IP address as resolved by the server. Forwarded-address headers are honored only through the engine's trusted-proxy configuration (c.ClientIP), never read directly from the request.

type SystemPermissionsHandler

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

func NewSystemPermissionsHandler

func NewSystemPermissionsHandler(cfg config.Config, securityService *services.SecurityService, checker PermissionChecker) *SystemPermissionsHandler

func (*SystemPermissionsHandler) GetPermissions

func (h *SystemPermissionsHandler) GetPermissions(c *gin.Context)

func (*SystemPermissionsHandler) RepairPermissions

func (h *SystemPermissionsHandler) RepairPermissions(c *gin.Context)

type TrustedProxyHandler

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

TrustedProxyHandler serves the proxy-layer trust list on the Security page. The list decides which peers may vouch for the visitor's address at the proxy.

func NewTrustedProxyHandler

func NewTrustedProxyHandler(db *gorm.DB, caddy CaddyConfigManager, apiLayer []string, aclMode string) *TrustedProxyHandler

NewTrustedProxyHandler creates the trusted-proxy handler. caddy may be nil, in which case a saved list is stored without a proxy apply.

func (*TrustedProxyHandler) Delete

func (h *TrustedProxyHandler) Delete(c *gin.Context)

Delete removes the saved trust list, so the environment list or the loopback default applies again.

func (*TrustedProxyHandler) Get

func (h *TrustedProxyHandler) Get(c *gin.Context)

Get returns the trust list in force. Non-administrators learn only whether any proxies are configured.

func (*TrustedProxyHandler) Put

func (h *TrustedProxyHandler) Put(c *gin.Context)

Put replaces the saved trust list. An empty list trusts loopback only.

type UpdateHandler

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

func NewUpdateHandler

func NewUpdateHandler(service *services.UpdateService) *UpdateHandler

func (*UpdateHandler) Check

func (h *UpdateHandler) Check(c *gin.Context)

type UpdateProfileRequest

type UpdateProfileRequest struct {
	Name            string `json:"name" binding:"required"`
	Email           string `json:"email" binding:"required,email"`
	CurrentPassword string `json:"current_password"`
}

type UpdateSettingRequest

type UpdateSettingRequest struct {
	Key      string `json:"key" binding:"required"`
	Value    string `json:"value"`
	Category string `json:"category"`
	Type     string `json:"type"`
}

type UpdateUserPermissionsRequest

type UpdateUserPermissionsRequest struct {
	PermissionMode string `json:"permission_mode" binding:"required,oneof=allow_all deny_all"`
	PermittedHosts []uint `json:"permitted_hosts"`
}

UpdateUserPermissionsRequest represents the request body for updating user permissions.

type UpdateUserRequest

type UpdateUserRequest struct {
	Name     string  `json:"name"`
	Email    string  `json:"email"`
	Password *string `json:"password" binding:"omitempty,min=8"`
	// CurrentPassword must accompany a password change on the caller's own account.
	CurrentPassword string `json:"current_password"`
	Role            string `json:"role"`
	Enabled         *bool  `json:"enabled"`
}

UpdateUserRequest represents the request body for updating a user.

type UptimeHandler

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

func NewUptimeHandler

func NewUptimeHandler(service *services.UptimeService) *UptimeHandler

func (*UptimeHandler) CheckMonitor

func (h *UptimeHandler) CheckMonitor(c *gin.Context)

CheckMonitor triggers an immediate check for a specific monitor. With a live worker pool it enqueues the job with a short block, returning 503 if the queue stays full (spec §3.1.2 / N5); without a pool it falls back to a background inline check.

func (*UptimeHandler) Create

func (h *UptimeHandler) Create(c *gin.Context)

Create creates a new uptime monitor

func (*UptimeHandler) Delete

func (h *UptimeHandler) Delete(c *gin.Context)

Delete removes a monitor and its associated data

func (*UptimeHandler) GetHistory

func (h *UptimeHandler) GetHistory(c *gin.Context)

func (*UptimeHandler) Health

func (h *UptimeHandler) Health(c *gin.Context)

Health exposes the uptime write/execution pipeline back-pressure counters (spec §3.5.5). Safe to call before the pool/ingester Run loops start, and in unit-test construction where either may be nil -> the field reports 0. GET /api/v1/uptime/health

func (*UptimeHandler) List

func (h *UptimeHandler) List(c *gin.Context)

func (*UptimeHandler) Summary

func (h *UptimeHandler) Summary(c *gin.Context)

Summary returns the batch per-monitor dashboard payload (status, latency, last check, 24h uptime %, and a recent-beat sparkline) for every monitor in one response, from three cached windowed queries (spec §3.5). GET /api/v1/uptime/monitors/summary?beats=<1..60>

func (*UptimeHandler) Sync

func (h *UptimeHandler) Sync(c *gin.Context)

func (*UptimeHandler) Update

func (h *UptimeHandler) Update(c *gin.Context)

type UserHandler

type UserHandler struct {
	DB          *gorm.DB
	AuthService *services.AuthService
	MailService *services.MailService
	// contains filtered or unexported fields
}

func NewUserHandler

func NewUserHandler(db *gorm.DB, authService *services.AuthService) *UserHandler

func (*UserHandler) AcceptInvite

func (h *UserHandler) AcceptInvite(c *gin.Context)

AcceptInvite accepts an invitation and sets the user's password (public endpoint).

func (*UserHandler) CreateUser

func (h *UserHandler) CreateUser(c *gin.Context)

CreateUser creates a new user with a password (admin only).

func (*UserHandler) DeleteUser

func (h *UserHandler) DeleteUser(c *gin.Context)

DeleteUser deletes a user (admin only).

func (*UserHandler) GetProfile

func (h *UserHandler) GetProfile(c *gin.Context)

GetProfile returns the current user's profile including API key.

func (*UserHandler) GetSetupStatus

func (h *UserHandler) GetSetupStatus(c *gin.Context)

GetSetupStatus checks if the application needs initial setup (i.e., no users exist).

func (*UserHandler) GetUser

func (h *UserHandler) GetUser(c *gin.Context)

GetUser returns a single user by ID (admin only).

func (*UserHandler) InviteUser

func (h *UserHandler) InviteUser(c *gin.Context)

InviteUser creates a new user with an invite token and sends an email (admin only).

func (*UserHandler) ListUsers

func (h *UserHandler) ListUsers(c *gin.Context)

ListUsers returns all users (admin only).

func (*UserHandler) PreviewInviteURL

func (h *UserHandler) PreviewInviteURL(c *gin.Context)

PreviewInviteURL returns what the invite URL would look like with current settings.

func (*UserHandler) RegenerateAPIKey

func (h *UserHandler) RegenerateAPIKey(c *gin.Context)

RegenerateAPIKey generates a new API key for the authenticated user.

func (*UserHandler) RegisterRoutes

func (h *UserHandler) RegisterRoutes(r *gin.RouterGroup)

func (*UserHandler) ResendInvite

func (h *UserHandler) ResendInvite(c *gin.Context)

ResendInvite regenerates and resends an invitation to a pending user (admin only).

func (*UserHandler) SetPasswordAttemptGuard

func (h *UserHandler) SetPasswordAttemptGuard(g PasswordAttemptGuard)

SetPasswordAttemptGuard charges email-change password checks to the sign-in budget.

func (*UserHandler) SetSetupCodeGuard

func (h *UserHandler) SetSetupCodeGuard(g *services.SetupCodeGuard)

SetSetupCodeGuard installs the first-run setup code that Setup accepts.

func (*UserHandler) Setup

func (h *UserHandler) Setup(c *gin.Context)

Setup creates the initial admin user and configures the ACME email.

func (*UserHandler) UpdateProfile

func (h *UserHandler) UpdateProfile(c *gin.Context)

UpdateProfile updates the authenticated user's profile.

func (*UserHandler) UpdateUser

func (h *UserHandler) UpdateUser(c *gin.Context)

UpdateUser updates an existing user (admin only for management fields, self-service for name/password).

func (*UserHandler) UpdateUserPermissions

func (h *UserHandler) UpdateUserPermissions(c *gin.Context)

UpdateUserPermissions updates a user's permission mode and host exceptions (admin only).

func (*UserHandler) ValidateInvite

func (h *UserHandler) ValidateInvite(c *gin.Context)

ValidateInvite validates an invite token (public endpoint).

type WAFExclusion

type WAFExclusion struct {
	RuleID      int    `json:"rule_id"`
	Target      string `json:"target,omitempty"`
	Description string `json:"description,omitempty"`
}

WAFExclusion represents a stored rule exclusion

type WAFExclusionRequest

type WAFExclusionRequest struct {
	RuleID      int    `json:"rule_id" binding:"required"`
	Target      string `json:"target,omitempty"`      // e.g., "ARGS:password"
	Description string `json:"description,omitempty"` // Human-readable reason
}

WAFExclusionRequest represents a rule exclusion for false positives

type WebPushHandler

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

WebPushHandler exposes the Web Push provisioning and subscription lifecycle endpoints (docs/plans/current_spec.md §3.4). All routes are mounted on the existing authenticated `management` route group; the Provision route is additionally gated admin-only at the route registration layer (routes.go), mirroring the Test/Preview precedent — see §3.4.0 for the full authorization-model writeup.

func NewWebPushHandler

func NewWebPushHandler(service *services.NotificationService) *WebPushHandler

func (*WebPushHandler) ListSubscriptions

func (h *WebPushHandler) ListSubscriptions(c *gin.Context)

ListSubscriptions returns the caller's own subscriptions only (§3.4.4).

func (*WebPushHandler) Provision

func (h *WebPushHandler) Provision(c *gin.Context)

Provision generates a new VAPID identity and creates the singleton webpush NotificationProvider row (§3.4.1). Admin-only — enforced by middleware.RequireRole(models.RoleAdmin) at the route registration layer (routes.go), matching the Test/Preview admin-only precedent on this same route group; no additional in-handler check is needed.

func (*WebPushHandler) Subscribe

func (h *WebPushHandler) Subscribe(c *gin.Context)

Subscribe registers (or idempotently re-registers) the caller's browser PushSubscription (§3.4.3).

func (*WebPushHandler) Unsubscribe

func (h *WebPushHandler) Unsubscribe(c *gin.Context)

Unsubscribe removes a subscription owned by the caller (§3.4.5). Returns 404 — never 403 — for a subscription that doesn't exist or isn't owned by the caller, to avoid confirming existence of another user's row.

func (*WebPushHandler) VAPIDPublicKey

func (h *WebPushHandler) VAPIDPublicKey(c *gin.Context)

VAPIDPublicKey serves the current VAPID public key for PushManager.subscribe (§3.4.2). Available to any authenticated management-access user, not just admins — a non-admin user's browser can still subscribe to receive alerts.

type WebSocketStatusHandler

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

WebSocketStatusHandler provides endpoints for WebSocket connection monitoring.

func NewWebSocketStatusHandler

func NewWebSocketStatusHandler(tracker *services.WebSocketTracker) *WebSocketStatusHandler

NewWebSocketStatusHandler creates a new handler for WebSocket status monitoring.

func (*WebSocketStatusHandler) GetConnections

func (h *WebSocketStatusHandler) GetConnections(c *gin.Context)

GetConnections returns a list of all active WebSocket connections.

func (*WebSocketStatusHandler) GetStats

func (h *WebSocketStatusHandler) GetStats(c *gin.Context)

GetStats returns aggregate statistics about WebSocket connections.

Source Files

Jump to

Keyboard shortcuts

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