Files
Havline/internal/settings/settings.go
T
mrleeandDevin 9d75fb1d3e
CI / verify (push) Canceled after 0s
fix: 收敛正确性缺口并补齐质量门禁
备份、隧道生命周期、日志、会话与设置项存在一批「静默失效」问题,本次一并收敛。

正确性:
- 备份归档补上 session_secret 与 frp 配置。缺密钥时换机恢复后库里所有凭据都解不开,
  界面表现为「配置都在、一执行就报解密失败」;同时支持口令加密(scrypt + AES-256-GCM)。
- 修复「立即备份」必失败:tar 头用的是遍历时的文件尺寸,而 logs、frpc 配置在打包期间
  还在增长,读出的字节多于声明值导致 archive/tar 报错、整份备份作废。改为打开后重新
  取尺寸并用 LimitReader 兜住,被截短时补零保持条目结构完整。
- 数据库改用 VACUUM INTO 生成一致性快照。直接打包正在写入的 SQLite 文件可能得到
  结构完整但内容自相矛盾的副本,恢复后才暴露。
- Cloudflare 启动改用 StartAuto,Shutdown 显式 StopAll,子进程绑定应用 ctx。此前
  重启会把用户手动停掉的隧道重新拉起,退出也可能留下孤儿进程。
- Nginx 访问/错误日志加轮转(200MB 阈值、gzip 归档、USR1 重开),读取改为从文件尾
  分块倒读,并跨当日归档统计。此前日志只增不减,读接口每次全量扫描。
- 过期会话改由日任务清理;删除反代规则时同步清掉流量累计,避免同名规则重建继承旧读数。
- 启动加就绪门:Nginx bootstrap 完成后再放行 FRP 对账、Agent 隧道与 Cloudflare 自启。

设置项:
- 新增设置项注册表(internal/settings/registry.go),白名单与默认值从它派生,
  并记录每个键的消费者,防止再出现「界面能改、后端没人读」的黑洞设置。
- 接上三个此前不生效的设置项:timezone(启动与保存时应用到 time.Local)、
  theme(后端为权威源,挂载时覆盖本地偏好、顶栏切换回写)、log_retention_days
  (控制日志归档保留天数)。

工程质量:
- gofmt 全量格式化 23 个历史文件,CI 增加格式化门禁。
- 前端引入 ESLint(flat config)与 lint 脚本,CI 增加 lint 步骤;顺带修掉
  logDisplay 的 let→const 与 LogsView 模板内直接改 prop 两处问题。
- 删除无引用的 pnpm-lock.yaml,prototype/ 加入忽略列表。
- 打包版本对齐:Docker manifest 同步到 2.0.0,CI 校验 VERSION 与 package.json 一致。

验证:gofmt 0 文件、go vet、go test ./...、npm run lint/typecheck/test/build 全绿。

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-24 16:30:00 +08:00

206 lines
7.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package settings
import (
"context"
"database/sql"
"strconv"
"strings"
)
const (
KeyTheme = "theme"
KeyTimezone = "timezone"
KeyLogRetentionDays = "log_retention_days"
KeyDDNSCheckInterval = "ddns_check_interval_minutes"
KeyCertRenewThreshold = "cert_renew_threshold_days"
KeyRootDomain = "root_domain"
KeyACMEEmail = "acme_email"
KeyACMECA = "acme_ca"
KeyZeroSSLAPIKey = "zerossl_api_key"
// KeyACMEDNSResolvers DNS-01 传播检查用的递归解析器(逗号分隔;system = 用系统解析器)
KeyACMEDNSResolvers = "acme_dns_resolvers"
// LiteSSL 强制 EAB:kid 与 hmac 在 FreeSSL 的「证书自动化 → EAB 管理」创建
KeyLiteSSLEABKid = "litessl_eab_kid"
KeyLiteSSLEABHMAC = "litessl_eab_hmac"
KeyNotifyWebhookURL = "notify_webhook_url"
KeyNotifyType = "notify_type"
KeyNotifyEmailJSON = "notify_email_json"
KeyNotifySMTPPassword = "notify_smtp_password"
KeyNotifyWebhookJSON = "notify_webhook_json"
KeyNotifyWebhookSecret = "notify_webhook_secret"
KeyNotifyTelegramJSON = "notify_telegram_json"
KeyNotifyTelegramToken = "notify_telegram_token"
KeyNotifyOnDDNSError = "notify_on_ddns_error" // legacy, migrated to KeyNotifyOnDDNSFailure
KeyNotifyOnCertError = "notify_on_cert_error" // legacy, migrated to KeyNotifyOnCertExpiry
KeyNotifyOnNginxError = "notify_on_nginx_error" // legacy, ignored
KeyNotifyOnDDNSIPChange = "notify_on_ddns_ip_change"
KeyNotifyOnDDNSFailure = "notify_on_ddns_failure"
KeyNotifyOnCertExpiry = "notify_on_cert_expiry"
KeyNotifyOnCertRenewSuccess = "notify_on_cert_renew_success"
KeyNotifyOnIPFrequentAccess = "notify_on_ip_frequent_access"
KeyNotifyOnCertRenewFailure = "notify_on_cert_renew_failure"
KeyNotifyOnLoginFailure = "notify_on_login_failure"
KeyNotifyOnNginxReloadFailure = "notify_on_nginx_reload_failure"
KeyNotifyIPFrequentThreshold = "notify_ip_frequent_threshold"
KeyNotifyIPFrequentWindowSec = "notify_ip_frequent_window_sec"
KeyNotifyLoginFailureThreshold = "notify_login_failure_threshold"
KeyNotifyLoginFailureWindowSec = "notify_login_failure_window_sec"
KeyNotifyOnResourceThreshold = "notify_on_resource_threshold"
KeyNotifyOnTunnelDown = "notify_on_tunnel_down"
KeyNotifyCPUThreshold = "notify_cpu_threshold"
KeyNotifyMemoryThreshold = "notify_memory_threshold"
KeyNotifyDiskThreshold = "notify_disk_threshold"
KeyNotifyTunnelFailThreshold = "notify_tunnel_fail_threshold"
KeyNotifyOnFrpsDown = "notify_on_frps_down"
KeyNotifyOnAgentUnreachable = "notify_on_agent_unreachable"
KeyNotifyOnRouteDrift = "notify_on_route_drift"
KeyNotifyFrpsFailThreshold = "notify_frps_fail_threshold"
KeyNotifyAgentFailThreshold = "notify_agent_fail_threshold"
KeyNotifyDriftCooldownHours = "notify_drift_cooldown_hours"
KeyBackupAutoEnabled = "backup_auto_enabled"
KeyBackupKeepCount = "backup_keep_count"
KeyRouteHealthEnabled = "route_health_enabled"
KeyStatusPageEnabled = "status_page_enabled"
KeyMetricsHistoryEnabled = "metrics_history_enabled"
// KeyStatusPageCodeHash 存访问码的 SHA-256;明文只在保存请求里出现一次
KeyStatusPageCodeHash = "status_page_code_hash"
// KeyStatusPageCode 只是「保存请求」里用的字段名,不会被直接写库
KeyStatusPageCode = "status_page_code"
KeyNotifyOnBackupFailure = "notify_on_backup_failure"
KeyTrustedProxy = "trusted_proxy_json"
KeyGlobalIPBlacklist = "global_ip_blacklist"
KeyGlobalIPWhitelist = "global_ip_whitelist"
KeyChinaCIDRUpdateHours = "china_cidr_update_interval_hours"
KeyChinaCIDRSourceV4 = "china_cidr_source_url_v4"
KeyChinaCIDRSourceV6 = "china_cidr_source_url_v6"
KeyChinaCIDRUpdatedAt = "china_cidr_updated_at"
KeyChinaCIDRCountV4 = "china_cidr_count_v4"
KeyChinaCIDRCountV6 = "china_cidr_count_v6"
KeyChinaCIDRLastError = "china_cidr_last_error"
KeyFRPEnabled = "frp_enabled"
KeyFRPServerAddr = "frp_server_addr"
KeyFRPServerPort = "frp_server_port"
KeyFRPAuthToken = "frp_auth_token"
KeyFRPTLSEnabled = "frp_tls_enabled"
KeyFRPCustomDomains = "frp_custom_domains"
KeyFRPLastError = "frp_last_error"
KeyFRPStartedAt = "frp_started_at"
KeyNginxGlobalMode = "nginx_global_mode"
// KeyTerminalEnabled 内置 SSH 终端总开关:默认关闭,shell 入口必须显式打开
KeyTerminalEnabled = "terminal_enabled"
// KeyTerminalRecording 会话录制开关:默认关闭,开启后把终端输出写入 logs/terminal
KeyTerminalRecording = "terminal_recording_enabled"
// KeyFrpResumeOnStart 记录「上次 frpc 是否处于运行状态」:应用被停用再启用后,
// 用它决定要不要自动把 frpc 拉起来(否则用户会发现应用起来了但 frpc 没起)。
// 该键由程序内部维护,不在设置页暴露。
KeyFrpResumeOnStart = "frp_resume_on_start"
)
type Store struct {
db *sql.DB
}
func NewStore(db *sql.DB) *Store {
return &Store{db: db}
}
func (s *Store) Get(ctx context.Context, key string) (string, error) {
var value string
err := s.db.QueryRowContext(ctx, `SELECT value FROM settings WHERE key = ?`, key).Scan(&value)
if err == sql.ErrNoRows {
if def, ok := Defaults[key]; ok {
return def, nil
}
return "", nil
}
return value, err
}
func (s *Store) Set(ctx context.Context, key, value string) error {
_, err := s.db.ExecContext(ctx, `
INSERT INTO settings(key, value) VALUES (?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value
`, key, value)
return err
}
func (s *Store) GetBool(ctx context.Context, key string) (bool, error) {
raw, err := s.Get(ctx, key)
if err != nil {
return false, err
}
switch strings.ToLower(strings.TrimSpace(raw)) {
case "1", "true", "yes", "on":
return true, nil
default:
return false, nil
}
}
func (s *Store) SetBool(ctx context.Context, key string, value bool) error {
if value {
return s.Set(ctx, key, "true")
}
return s.Set(ctx, key, "false")
}
func (s *Store) SetInt(ctx context.Context, key string, value int) error {
return s.Set(ctx, key, strconv.Itoa(value))
}
func (s *Store) GetInt(ctx context.Context, key string) (int, error) {
raw, err := s.Get(ctx, key)
if err != nil {
return 0, err
}
if raw == "" {
if def, ok := Defaults[key]; ok {
raw = def
}
}
n, err := strconv.Atoi(raw)
if err != nil {
return 0, err
}
return n, nil
}
func (s *Store) List(ctx context.Context) (map[string]string, error) {
rows, err := s.db.QueryContext(ctx, `SELECT key, value FROM settings`)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]string{}
for k, v := range Defaults {
out[k] = v
}
for rows.Next() {
var key, value string
if err := rows.Scan(&key, &value); err != nil {
return nil, err
}
out[key] = value
}
return out, rows.Err()
}
func (s *Store) SetMany(ctx context.Context, values map[string]string) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
for key, value := range values {
if _, err := tx.ExecContext(ctx, `
INSERT INTO settings(key, value) VALUES (?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value
`, key, value); err != nil {
return err
}
}
return tx.Commit()
}