models

package
v0.13.5 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 11 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

Index

Constants

View Source
const (
	SettingLoginCaptchaEnabled  = "login_captcha_enabled"
	SettingLoginCaptchaAPIKeyID = "login_captcha_api_key_id"
	SettingMCPEnabled           = "mcp_enabled"
)
View Source
const DefaultHISThreshold = 0.8

DefaultHISThreshold mirrors his.BotSuspectThreshold. It is restated here rather than imported so that models keeps no dependency on the scoring package; his_test asserts the two stay equal.

View Source
const MCPTokenPrefix = "gm_"

MCPTokenPrefix marks a token as an MCP admin credential, keeping it visually distinct from the gk_ site API keys.

View Source
const StatsTokenMaxDays = 90

StatsTokenMaxDays bounds the window a stats token can read.

View Source
const StatsTokenPrefix = "gs_"

StatsTokenPrefix marks a read-only per-key stats credential, distinct from the public gk_ key ID (which ships in every page's HTML and so cannot guard anything) and from the gm_ MCP admin tokens.

Variables

View Source
var ErrMCPTokenNotFound = errors.New("mcp token not found")

ErrMCPTokenNotFound is returned when no enabled token matches a secret.

View Source
var ErrStatsTokenNotFound = errors.New("stats token not found")

ErrStatsTokenNotFound is returned when no key holds the presented token.

Functions

func All

func All() []any

All returns every persisted model, in dependency order, for migration.

The list lived in three places (the binary, the SQLite test helper and the MySQL test helper) and had already drifted: the MySQL helper was missing DailyCountryStat and HISSample, so those integration tests ran against an incomplete schema. Adding a model here now reaches every caller at once.

func CleanupExpired

func CleanupExpired(db *gorm.DB) (int64, error)

func CreateHISSample

func CreateHISSample(db *gorm.DB, s *HISSample) error

CreateHISSample persists one raw HIS observation.

func DeleteAPIKey

func DeleteAPIKey(db *gorm.DB, id int64) error

func DeleteMCPToken

func DeleteMCPToken(db *gorm.DB, id int64) (bool, error)

DeleteMCPToken revokes a token. It reports whether a row was removed, so a repeated revoke can be told apart from one that never existed.

func GenerateHMACSecret

func GenerateHMACSecret() (string, error)

func GenerateKeyID

func GenerateKeyID() (string, error)

func GenerateMCPToken

func GenerateMCPToken() (string, error)

GenerateMCPToken returns a new token secret with 128 bits of entropy.

func GetAllKeysStatsSummary

func GetAllKeysStatsSummary(db *gorm.DB) (map[int64]KeyStatsSummary, error)

GetAllKeysStatsSummary returns all-time totals grouped by API key ID.

func GetLoginCaptchaEnabled

func GetLoginCaptchaEnabled(db *gorm.DB) (bool, error)

GetLoginCaptchaEnabled returns whether the login CAPTCHA is enabled.

func GetMCPEnabled

func GetMCPEnabled(db *gorm.DB) (bool, error)

GetMCPEnabled returns whether the MCP endpoint is served. It defaults to false: the endpoint is a second authentication path to full admin capability, so an operator has to turn it on deliberately.

func GetSetting

func GetSetting(db *gorm.DB, key string) (string, error)

GetSetting retrieves a single setting value by key. Returns ("", nil) if the key does not exist.

func HashMCPToken

func HashMCPToken(secret string) string

HashMCPToken returns the storage digest for a token secret.

func IncrementChallengesIssued

func IncrementChallengesIssued(db *gorm.DB, apiKeyID int64) error

func IncrementCountryVerification

func IncrementCountryVerification(db *gorm.DB, apiKeyID int64, country string, ok bool) error

IncrementCountryVerification records one verification outcome for the key/day/country, atomically bumping the matching counter via UPSERT. country may be empty (unknown source); it is stored as-is so totals reconcile.

func IncrementHISObservation

func IncrementHISObservation(db *gorm.DB, apiKeyID int64, botSuspected bool) error

IncrementHISObservation records one HIS Monitor sample for the key/day: it always bumps the observation count and additionally bumps the bot-suspected count when the sample was flagged. It never affects verification outcomes.

func IncrementVerificationsFail

func IncrementVerificationsFail(db *gorm.DB, apiKeyID int64) error

func IncrementVerificationsOK

func IncrementVerificationsOK(db *gorm.DB, apiKeyID int64) error

func IsConsumed

func IsConsumed(db *gorm.DB, challenge string) (bool, error)

func IssueStatsToken

func IssueStatsToken(db *gorm.DB, id int64) (string, error)

IssueStatsToken generates a new stats token for the key, replacing any previous one, and returns the secret. It is shown once and unrecoverable afterwards. The digest is the same SHA-256 the MCP tokens use, for the same reason: 128 bits of CSPRNG output need no slow hash.

func MarkConsumed

func MarkConsumed(db *gorm.DB, challenge string, apiKeyID int64, expiresAt time.Time) error

func PruneHISSamples

func PruneHISSamples(db *gorm.DB, cutoff time.Time) (int64, error)

PruneHISSamples deletes samples recorded before cutoff, returning the count removed. Called periodically by the cleanup worker to bound storage.

func RevokeStatsToken

func RevokeStatsToken(db *gorm.DB, id int64) error

RevokeStatsToken removes the key's stats token, if any. Existence is checked apart from the update: MySQL reports a write that changes nothing (a key that had no token) as zero rows affected, which is not a missing key.

func RotateHMACSecret

func RotateHMACSecret(db *gorm.DB, id int64) (string, error)

func SetAPIKeyEnabled

func SetAPIKeyEnabled(db *gorm.DB, id int64, enabled bool) error

SetAPIKeyEnabled flips only the enabled flag, so enabling or disabling a key can never clobber a concurrent edit to its settings.

func SetSetting

func SetSetting(db *gorm.DB, key, value string) error

SetSetting upserts a setting value.

func TouchMCPToken

func TouchMCPToken(db *gorm.DB, id int64) error

TouchMCPToken records that a token was just used.

func UpdateAPIKey

func UpdateAPIKey(db *gorm.DB, id int64, params UpdateAPIKeyParams) error

func UpdateAPIKeyFields

func UpdateAPIKeyFields(db *gorm.DB, id int64, fields map[string]any) error

UpdateAPIKeyFields writes only the named columns, leaving every other one alone.

UpdateAPIKey writes the whole row, which forces callers into a read-modify-write and makes concurrent edits lose updates: a rename that read Enabled=true before a disable committed would write the key back to enabled. Restricting the write to the fields that actually changed removes the race rather than serialising around it. An empty map is a no-op, not an error.

Types

type APIKey

type APIKey struct {
	ID            int64  `gorm:"primaryKey;autoIncrement" json:"id"`
	KeyID         string `gorm:"not null;uniqueIndex;size:32" json:"key_id"`
	HMACSecret    string `gorm:"not null" json:"hmac_secret,omitempty"`
	Name          string `gorm:"not null;default:''" json:"name"`
	Domain        string `gorm:"not null;default:''" json:"domain"`
	MaxNumber     int64  `gorm:"not null;default:100000" json:"max_number"`
	ExpireSeconds int    `gorm:"not null;default:300" json:"expire_seconds"`
	Algorithm     string `gorm:"not null;default:'SHA-256'" json:"algorithm"`
	// RateLimitPerMin caps how many /api/v1 requests this key accepts per minute,
	// aggregated across all clients. 0 means unlimited (only the global per-IP
	// limiter applies).
	RateLimitPerMin int `gorm:"not null;default:0" json:"rate_limit_per_min"`
	// AdaptiveDifficulty, when set, raises the proof-of-work MaxNumber above this
	// key's configured base for clients (by IP) that request challenges at an
	// abusive rate, capped server-side. MaxNumber stays the floor.
	AdaptiveDifficulty bool `gorm:"not null;default:false" json:"adaptive_difficulty"`
	// HISSampling, when set, persists each scored HIS observation for this key
	// (raw aggregates + score) so enforcement thresholds can be calibrated on
	// real traffic. Samples are pruned after the configured retention window.
	HISSampling bool `gorm:"not null;default:false" json:"his_sampling"`
	// HISEnforce, when set, rejects a verification whose HIS score reaches
	// HISThreshold, instead of merely reporting it. Off by default: HIS ships
	// in Monitor mode and blocking is a decision the operator makes after
	// reading their own calibration histogram, never one inherited from us.
	// It can only ever act on a request that actually carried `his_signals`;
	// a client shipping no collector sends nothing, is scored not at all, and
	// passes untouched whatever this says.
	HISEnforce bool `gorm:"not null;default:false" json:"his_enforce"`
	// HISThreshold is the score at or above which this key treats a sample as
	// automation: it drives the reported `his_bot_suspected`, the Monitor
	// counters, the calibration histogram's marker and, when HISEnforce is on,
	// the rejection. One number, one meaning.
	//
	// The default is deliberately his.BotSuspectThreshold rather than anything
	// lower. A sample whose collector ran and observed nothing at all scores
	// exactly 0.70, and that shape is produced both by automation and by a
	// keyboard-only or assistive-technology visitor. Operators who have read
	// their own histogram can and do lower this; operators who have not should
	// not inherit a number that rejects their accessible traffic.
	HISThreshold float64 `gorm:"not null;default:0.8" json:"his_threshold"`
	// StatsTokenHash is the SHA-256 of the key's read-only stats token (gs_),
	// which lets a site's backend read this key's statistics without admin
	// access. Nil when no token was issued: NULLs never collide in the unique
	// index, an empty string would. Never serialised.
	StatsTokenHash *string `gorm:"uniqueIndex;size:64" json:"-"`
	// StatsTokenDisplay holds the token's leading characters so the dashboard
	// can show which token is live after the secret itself is gone.
	StatsTokenDisplay string    `gorm:"not null;default:''" json:"stats_token_display"`
	Enabled           bool      `gorm:"not null;default:true" json:"enabled"`
	CreatedAt         time.Time `json:"created_at"`
	UpdatedAt         time.Time `json:"updated_at"`
}

APIKey represents a site-specific API key used to generate and verify ALTCHA challenges.

func CreateAPIKey

func CreateAPIKey(db *gorm.DB, name, domain string, maxNumber int64, expireSeconds int, algorithm string) (*APIKey, error)

func EnsureLoginCaptchaAPIKey

func EnsureLoginCaptchaAPIKey(db *gorm.DB) (*APIKey, error)

EnsureLoginCaptchaAPIKey returns the existing login CAPTCHA API key, or creates a dedicated one if none exists yet.

func GetAPIKeyByID

func GetAPIKeyByID(db *gorm.DB, id int64) (*APIKey, error)

func GetAPIKeyByKeyID

func GetAPIKeyByKeyID(db *gorm.DB, keyID string) (*APIKey, error)

func GetAPIKeyByStatsToken

func GetAPIKeyByStatsToken(db *gorm.DB, secret string) (*APIKey, error)

GetAPIKeyByStatsToken returns the key a stats token belongs to. A disabled key still resolves: its owner may want to read why traffic stopped.

func ListAPIKeys

func ListAPIKeys(db *gorm.DB) ([]APIKey, error)

ListAPIKeys returns every key without its HMAC secret. The listing feeds the dashboard table, which never needs the secret; callers that do (key detail, creation, rotation) go through GetAPIKeyByID or RotateHMACSecret instead. Omitting the column keeps the whole secret set out of the response rather than relying on the caller to strip it.

func (*APIKey) AfterFind

func (k *APIKey) AfterFind(*gorm.DB) error

AfterFind normalises the stored threshold on every read path, so no caller ever sees an out-of-range value: not the scorer, not the admin API, and not the edit form, which would otherwise display a 0 that its own validation then refuses to save back. GORM runs this for Find, First and Scan alike.

func (*APIKey) SuspectThreshold

func (k *APIKey) SuspectThreshold() float64

SuspectThreshold is the score at or above which this key counts a sample as automation. Out-of-range values (a column added before this field existed, or a bad write) fall back to the default rather than silently meaning "reject everything", which is what a stored 0 would otherwise do.

type AdminUser

type AdminUser struct {
	ID           int64     `gorm:"primaryKey;autoIncrement" json:"id"`
	Username     string    `gorm:"not null;uniqueIndex;size:64;default:admin" json:"username"`
	PasswordHash string    `gorm:"not null" json:"-"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
}

AdminUser represents a dashboard admin account.

type ConsumedChallenge

type ConsumedChallenge struct {
	ID         int64     `gorm:"primaryKey;autoIncrement"`
	Challenge  string    `gorm:"not null;uniqueIndex;size:256"`
	APIKeyID   int64     `gorm:"not null;index"`
	ExpiresAt  time.Time `gorm:"not null"`
	ConsumedAt time.Time `gorm:"not null;autoCreateTime"`
}

ConsumedChallenge tracks used challenge tokens to prevent replay attacks.

type CountryStat

type CountryStat struct {
	Country           string `json:"country"`
	VerificationsOK   int    `json:"verifications_ok"`
	VerificationsFail int    `json:"verifications_fail"`
	Total             int    `json:"total"`
}

CountryStat is an aggregated per-country row for the dashboard.

func GetCountryStats

func GetCountryStats(db *gorm.DB, apiKeyID *int64, days, limit int) ([]CountryStat, error)

GetCountryStats returns per-country verification totals over the last `days`, ordered by total descending and capped at `limit`. When apiKeyID is nil the totals span every key; otherwise they are scoped to that one key.

type DailyCountryStat

type DailyCountryStat struct {
	ID                int64  `gorm:"primaryKey;autoIncrement" json:"-"`
	APIKeyID          int64  `gorm:"not null;uniqueIndex:idx_key_date_country" json:"api_key_id"`
	Date              string `gorm:"not null;uniqueIndex:idx_key_date_country;size:10" json:"date"`
	Country           string `gorm:"uniqueIndex:idx_key_date_country;size:2" json:"country"`
	VerificationsOK   int    `gorm:"not null;default:0" json:"verifications_ok"`
	VerificationsFail int    `gorm:"not null;default:0" json:"verifications_fail"`
}

DailyCountryStat holds per-key, per-day, per-country verification counters. Country is an ISO 3166-1 alpha-2 code resolved from the client IP at request time; the raw IP is never stored (privacy-first). An empty Country means the source could not be geolocated (private/loopback/unknown) and is bucketed as "unknown" so per-country totals reconcile with the overall verification ones.

type DailyStat

type DailyStat struct {
	ID                int64  `gorm:"primaryKey;autoIncrement" json:"-"`
	APIKeyID          int64  `gorm:"not null;uniqueIndex:idx_key_date" json:"api_key_id"`
	Date              string `gorm:"not null;uniqueIndex:idx_key_date;size:10" json:"date"`
	ChallengesIssued  int    `gorm:"not null;default:0" json:"challenges_issued"`
	VerificationsOK   int    `gorm:"not null;default:0" json:"verifications_ok"`
	VerificationsFail int    `gorm:"not null;default:0" json:"verifications_fail"`
	// HIS (Human Interaction Signature) Monitor counters: every scored sample
	// increments HISObservations; samples at/above the suspect threshold also
	// increment HISBotSuspected. Monitor mode only records — it never blocks.
	HISObservations int `gorm:"not null;default:0" json:"his_observations"`
	HISBotSuspected int `gorm:"not null;default:0" json:"his_bot_suspected"`
}

DailyStat holds per-key per-day counters.

func GetAllKeysDailyStats

func GetAllKeysDailyStats(db *gorm.DB, days int) ([]DailyStat, error)

GetAllKeysDailyStats returns every key's daily rows for the last days days in one query, ordered by key then date, so the dashboard can draw a series per key without one request per key.

func GetKeyStats

func GetKeyStats(db *gorm.DB, apiKeyID int64, days int) ([]DailyStat, error)

type HISCalibration

type HISCalibration struct {
	Samples        int              `json:"samples"`
	Suspected      int              `json:"suspected"`
	Threshold      float64          `json:"threshold"`
	ScoreHistogram []HISScoreBucket `json:"score_histogram"`
	AvgDurationMs  float64          `json:"avg_duration_ms"`
	AvgPointer     float64          `json:"avg_pointer_events"`
	NoMotionPct    float64          `json:"no_motion_pct"`
}

HISCalibration summarizes stored samples to help tune the scoring heuristic and pick an enforcement threshold. The histogram shows how scores distribute relative to the current suspect threshold; the signal averages explain what is driving them.

func GetHISCalibration

func GetHISCalibration(db *gorm.DB, apiKeyID *int64, days int, threshold float64) (*HISCalibration, error)

GetHISCalibration aggregates stored samples over the last `days`. When apiKeyID is nil it spans every key; otherwise it is scoped to that key.

type HISSample

type HISSample struct {
	ID           int64     `gorm:"primaryKey;autoIncrement" json:"id"`
	APIKeyID     int64     `gorm:"not null;index:idx_his_sample_key_created" json:"api_key_id"`
	CreatedAt    time.Time `gorm:"index:idx_his_sample_key_created" json:"created_at"`
	Score        float64   `gorm:"not null" json:"score"`
	BotSuspected bool      `gorm:"not null" json:"bot_suspected"`

	DurationMs         int     `json:"duration_ms"`
	TimeToFirstMs      int     `json:"time_to_first_ms"`
	PointerEvents      int     `json:"pointer_events"`
	PointerDistance    float64 `json:"pointer_distance"`
	Scrolls            int     `json:"scrolls"`
	Touches            int     `json:"touches"`
	Keydowns           int     `json:"keydowns"`
	KeyIntervalStdevMs float64 `json:"key_interval_stdev_ms"`
}

HISSample is a single stored Human Interaction Signature observation: the raw privacy-preserving aggregates produced by the client collector together with the score the heuristic assigned. Samples are only written for keys that opt in (APIKey.HISSampling) and are pruned after a configurable retention window. They exist so HIS enforcement thresholds can be calibrated against real traffic before any blocking is enabled.

Like the rest of HIS, this stores no coordinates, timestamps, key contents or IP — only counts, distances, durations and timing variance.

type HISScoreBucket

type HISScoreBucket struct {
	Lo    float64 `json:"lo"`
	Hi    float64 `json:"hi"`
	Count int     `json:"count"`
}

HISScoreBucket is one column of the score histogram: scores in [lo, hi).

type KeyStatsReport

type KeyStatsReport struct {
	Days      int           `json:"days"`
	Totals    StatsTotals   `json:"totals"`
	Daily     []StatsDay    `json:"daily"`
	Countries []CountryStat `json:"countries"`
}

KeyStatsReport is what a stats token can read: one key's counters over a window, with every day present (zero-filled) so a client can draw a series without knowing which days had traffic.

func GetKeyStatsReport

func GetKeyStatsReport(db *gorm.DB, apiKeyID int64, days int) (*KeyStatsReport, error)

GetKeyStatsReport builds the report for one key over the last days days, today included, oldest first.

type KeyStatsSummary

type KeyStatsSummary struct {
	APIKeyID          int64  `json:"api_key_id"`
	ChallengesIssued  int    `json:"challenges_issued"`
	VerificationsOK   int    `json:"verifications_ok"`
	VerificationsFail int    `json:"verifications_fail"`
	HISObservations   int    `json:"his_observations"`
	HISBotSuspected   int    `json:"his_bot_suspected"`
	LastUsedAt        string `json:"last_used_at"`
}

KeyStatsSummary holds all-time totals for a single API key.

type MCPToken

type MCPToken struct {
	ID   int64  `gorm:"primaryKey;autoIncrement" json:"id"`
	Name string `gorm:"not null;default:''" json:"name"`
	// TokenHash is the hex-encoded SHA-256 of the secret. Never serialised.
	TokenHash string `gorm:"not null;uniqueIndex;size:64" json:"-"`
	// Display holds the token's leading characters so the dashboard can show
	// which token a row refers to after the secret itself is gone.
	Display string `gorm:"not null;default:''" json:"display"`
	// ReadOnly restricts the token to the read-only MCP tools.
	ReadOnly bool `gorm:"not null;default:false" json:"read_only"`
	// LastUsedAt surfaces dormant tokens that should be revoked. Nil until the
	// token authenticates for the first time.
	LastUsedAt *time.Time `json:"last_used_at"`
	CreatedAt  time.Time  `json:"created_at"`
}

MCPToken is a long-lived credential for the MCP endpoint, issued per person rather than shared, so it can be revoked without disturbing anyone else.

The secret is stored as a SHA-256 digest, deliberately not bcrypt. Bcrypt is slow by design to defend low-entropy human-chosen passwords; these tokens are 128 bits of CSPRNG output, so there is nothing to slow down, and bcrypt would add its work factor to every single MCP request for no gain.

func AuthenticateMCPToken

func AuthenticateMCPToken(db *gorm.DB, secret string) (*MCPToken, error)

AuthenticateMCPToken resolves a presented secret to its token record.

The lookup is by digest, so the database never sees the secret and an attacker cannot probe for a prefix. The constant-time comparison that follows guards the row we did find; the indexed lookup itself is not a useful timing oracle because the attacker cannot steer SHA-256 output.

func CreateMCPToken

func CreateMCPToken(db *gorm.DB, name string, readOnly bool) (*MCPToken, string, error)

CreateMCPToken issues a token and returns it alongside the stored record. The secret is returned only here; it is unrecoverable afterwards.

func ListMCPTokens

func ListMCPTokens(db *gorm.DB) ([]MCPToken, error)

ListMCPTokens returns every token, newest first. Digests are never loaded.

type Setting

type Setting struct {
	Key       string    `gorm:"primaryKey;size:64" json:"key"`
	Value     string    `gorm:"not null;default:''" json:"value"`
	UpdatedAt time.Time `json:"updated_at"`
}

Setting holds a key-value configuration entry.

type StatsDay

type StatsDay struct {
	Date              string `json:"date"`
	ChallengesIssued  int    `json:"challenges_issued"`
	VerificationsOK   int    `json:"verifications_ok"`
	VerificationsFail int    `json:"verifications_fail"`
	HISBotSuspected   int    `json:"his_bot_suspected"`
}

StatsDay is one day of a stats report.

type StatsOverview

type StatsOverview struct {
	TotalChallenges        int           `json:"total_challenges"`
	TotalVerificationsOK   int           `json:"total_verifications_ok"`
	TotalVerificationsFail int           `json:"total_verifications_fail"`
	TotalHISObservations   int           `json:"total_his_observations"`
	TotalHISBotSuspected   int           `json:"total_his_bot_suspected"`
	ActiveKeys             int           `json:"active_keys"`
	Daily                  []DailyStat   `json:"daily"`
	Countries              []CountryStat `json:"countries"`
}

StatsOverview holds aggregated statistics for the dashboard.

func GetStatsOverview

func GetStatsOverview(db *gorm.DB, days int) (*StatsOverview, error)

type StatsTotals

type StatsTotals struct {
	ChallengesIssued  int `json:"challenges_issued"`
	VerificationsOK   int `json:"verifications_ok"`
	VerificationsFail int `json:"verifications_fail"`
	HISObservations   int `json:"his_observations"`
	HISBotSuspected   int `json:"his_bot_suspected"`
}

StatsTotals sums a stats report's window.

type UpdateAPIKeyParams

type UpdateAPIKeyParams struct {
	Name               string
	Domain             string
	MaxNumber          int64
	ExpireSeconds      int
	Algorithm          string
	RateLimitPerMin    int
	AdaptiveDifficulty bool
	HISSampling        bool
	HISEnforce         bool
	HISThreshold       float64
	Enabled            bool
}

UpdateAPIKeyParams holds the fields for updating an API key.

Jump to

Keyboard shortcuts

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