Compare commits

115 Commits
Author SHA1 Message Date
mrlee b9d43538b5 refactor: simplify public proxy traffic table
CI / verify (push) Canceled after 0s
2026-10-24 20:31:27 +08:00
mrlee 56f04ae12b feat: refresh dashboard layout and navigation
CI / verify (push) Canceled after 0s
2026-10-24 20:06:42 +08:00
mrleeandDevin 9d75fb1d3e fix: 收敛正确性缺口并补齐质量门禁
CI / verify (push) Canceled after 0s
备份、隧道生命周期、日志、会话与设置项存在一批「静默失效」问题,本次一并收敛。

正确性:
- 备份归档补上 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
mrlee 6dd2136dd2 禁用暂不可用的穿透类型
CI / verify (push) Canceled after 0s
2026-10-24 09:29:52 +08:00
mrlee e4edbdcef0 tcp新增端口校验逻辑
CI / verify (push) Canceled after 0s
2026-10-19 15:53:59 +08:00
mrlee 5b9773b74a 修复列表错位
CI / verify (push) Canceled after 0s
2026-10-19 15:49:22 +08:00
mrlee 2c1cf1260b 修正frpc重启按钮的工作流程
CI / verify (push) Canceled after 0s
2026-10-19 13:50:05 +08:00
mrlee 211d8e66e0 添加自定义404页面
CI / verify (push) Canceled after 0s
2026-10-17 20:22:27 +08:00
mrlee 6b8ff0e5a3 WebSocket 把 proxy_http_version 1.1 + Upgrade/Connection 移进 location / 内部
CI / verify (push) Canceled after 0s
2026-10-17 11:58:43 +08:00
mrlee c1bcdd0b86 公网反代默认转发 WebSocket 升级头
CI / verify (push) Canceled after 0s
2026-10-17 10:21:24 +08:00
mrlee 302248a907 chore(release): 发布 v2.0.0
CI / verify (push) Canceled after 0s
- 内置 SSH 终端(/terminal):复用已保存的 SSH 密码/私钥与独立 known_hosts 校验
- 终端二次认证、会话审计(/terminal/audits)、录像审计与常用命令
- DDNS 服务商名称与自定义 IP,新增迁移 037/038/039
- CHANGELOG 与 VERSION 更新至 2.0.0
2026-10-16 20:18:04 +08:00
mrlee a0cc553d2d fix(native): updater Token 不再拖垮非 root 启动(飞牛原生版无法启用)
CI / verify (push) Canceled after 0s
原生版以非 root 的 havline 用户运行,而 app.New 会无条件调用 updater.EnsureToken,
去写默认的 /run/havline-updater/updater.token:MkdirAll 因权限不足失败 →
app.New 返回错误 → main 里 log.Fatalf → 进程秒退,飞牛应用中心报「本地应用启动失败」。
该逻辑由 v1.9.2 引入,v1.9.1 及之前不受影响。

- 新增 updater.EnsureTokenIfEnabled:updater 未启用(socket 为空)时直接返回,
  完全不触碰 Token 文件
- app.New 改用该函数,只有真正启用一键升级 sidecar 时才准备共享 Token
- 补充回归测试:socket 为空不创建文件、socket 非空照旧创建
2026-10-11 15:59:03 +08:00
mrlee 2856040883 chore(release): 发布 v1.9.3
CI / verify (push) Canceled after 0s
Docker Release / build-and-push (amd64, linux/amd64) (push) Canceled after 0s
Docker Release / build-and-push (arm64, linux/arm64) (push) Canceled after 0s
GitHub Release / release (push) Canceled after 0s
Docker Release / create-manifest (push) Canceled after 0s
- VERSION 与 web/package.json、package-lock 提升到 1.9.3
- README 版本徽章与飞牛安装包名同步到 1.9.3
- CHANGELOG 的 [Unreleased] 段落转为 [v1.9.3] - 2026-10-11
2026-10-11 15:18:32 +08:00
mrlee 0f68101503 feat(frp): frps vhost 回源端口支持 80/443,公网反代在该配置下不再适用
- 服务端表单不再硬性拒绝 vhostHTTPPort=80 / vhostHTTPSPort=443,改为保存时弹窗二次确认;
  确认后请求携带 allow_privileged_vhost_ports 提交并由后端校验放行,未携带标记的请求(含直接调 API)仍被拒绝
- frps.toml 生成改为写入风险注释、不再报错;各规则的公网反代回源地址随 80/443 自动跟随
- 「公网反代」页检测到 80/443 后显示说明卡片并隐藏统计/Nginx/规则台账/漂移区块,
  同时跳过 agent 的路由、漂移与健康请求
- 后端 DeployAgentRoute 与 RedeployAllRoutes(含漂移一键修复)拒绝下发,自动下发路径 syncAgentRoute 跳过
- 新增 internal/frp/vhost_port_test.go:校验、二次确认、frps.toml 生成、反代回源跟随与守卫对照
2026-10-11 15:18:32 +08:00
mrlee 50b8cc1351 Update README.md 2026-10-11 13:58:57 +08:00
mrlee d1c498a286 chore: 停止跟踪 docs/ 并移除 README 中的文档链接
CI / verify (push) Canceled after 0s
- docs/ 只保留在本地,加入 .gitignore(85 个文件移出版本库,工作区文件不受影响)
- README 删除截图画廊与 docs/user-guide.md 引用,并从项目结构表中移除 docs 行
2026-10-11 13:51:35 +08:00
mrlee 9c77d23078 Delete docs directory 2026-10-11 13:32:37 +08:00
mrlee fb57b2aef8 chore: 同步版本号到 1.9.2、整理 CHANGELOG 并移除误提交的 exe
- README 版本徽章与飞牛安装包名对齐到 1.9.2
- web/package-lock.json 根版本与 web/package.json 保持一致(原为 1.9.0)
- CHANGELOG 合并整理 1.1.0 起的相近补丁版本并重新编排版本号
- 取消跟踪 Windows 构建产物 havline-agent.exe,并加入 .gitignore
2026-10-11 13:23:56 +08:00
mrlee 2a0740a60f chore(release): 发布 v1.9.2
CI / verify (push) Canceled after 0s
Docker Release / build-and-push (amd64, linux/amd64) (push) Canceled after 0s
Docker Release / build-and-push (arm64, linux/arm64) (push) Canceled after 0s
GitHub Release / release (push) Canceled after 0s
Docker Release / create-manifest (push) Canceled after 0s
- 「公网服务端」新增 Nginx 启停控制(Agent 0.15.2,停止带二次确认)
- frps 启动失败不再误报成功,并增强启动诊断
- frps vhost 端口禁止 80/443,避免与 VPS 上 Nginx 冲突
- 旧服务端配置的 tcp_mux / login_fail_exit 默认值补齐
- 新增安全审查、页面布局方案与场景操作文档
2026-10-07 19:26:02 +08:00
mrlee a7d71752e3 feat(updater): generate shared token without init container 2026-10-05 19:11:05 +08:00
mrlee 9aaefa3b77 fix: surface frps startup failures and avoid nginx port conflicts 2026-10-05 13:07:56 +08:00
mrlee 7d8a327533 docs: add dialog screenshots and step-by-step operations
CI / verify (push) Canceled after 0s
2026-10-02 17:07:23 +08:00
mrlee 5a36ae243c docs: add illustrated user guide for all Havline pages
CI / verify (push) Canceled after 0s
2026-10-02 16:54:21 +08:00
mrlee a7e47e950a Revert "feat: add native fnOS gateway socket and base path support"
CI / verify (push) Canceled after 0s
This reverts commit 419c205103.
2026-10-02 15:17:05 +08:00
mrlee 419c205103 feat: add native fnOS gateway socket and base path support
CI / verify (push) Canceled after 0s
2026-10-02 14:59:57 +08:00
mrlee c5502b0f95 docs: add fnOS native application plan
CI / verify (push) Canceled after 0s
2026-10-02 14:47:26 +08:00
mrlee a14d92ccbb docs: add fnOS unified gateway plan
CI / verify (push) Canceled after 0s
2026-10-02 14:38:00 +08:00
mrlee 9ca5da4523 docs: document Gitea registry OAuth fix and add manual OCI pusher
CI / verify (push) Canceled after 0s
2026-10-02 13:26:27 +08:00
mrlee 244297f96c fix: update repository URL to jayhub.top
CI / verify (push) Canceled after 0s
2026-10-02 13:01:03 +08:00
mrlee ea5fd1b934 refactor(fnos): move packaging workspace outside main repository
CI / verify (push) Canceled after 0s
2026-10-01 18:58:28 +08:00
mrlee ac56394dce feat(fnos): scaffold Havline fnOS application package
CI / verify (push) Canceled after 0s
2026-10-01 18:49:08 +08:00
mrlee 1f33c7d9a7 docs: add official fnOS packaging research
CI / verify (push) Canceled after 0s
2026-10-01 18:36:08 +08:00
mrlee 90b7a9af6e docs: rewrite README for Havline project
CI / verify (push) Canceled after 0s
2026-10-01 18:06:15 +08:00
mrlee 31a5abe539 feat(web): enrich about page project story and layout
CI / verify (push) Canceled after 0s
2026-10-01 17:28:35 +08:00
mrlee fafde0f709 feat(web): replace example page with about project page
CI / verify (push) Canceled after 0s
2026-10-01 17:20:06 +08:00
mrlee c6f96ffc0f fix: link repository footer to upstream Fonu project
CI / verify (push) Canceled after 0s
2026-10-01 17:14:02 +08:00
mrlee 8fa5d922ac feat: rename project from Fonu to Havline
CI / verify (push) Canceled after 0s
2026-10-01 16:54:35 +08:00
mrlee c377405696 chore(release): 发布 v1.9.0 并更新 Cloudflare 文档 2026-10-01 13:12:37 +08:00
mrlee 83cc9d504b feat(cloudflare): 完成隧道接入、运维与 P0 体验优化 2026-10-01 11:32:54 +08:00
mrlee 36d8b1e464 docs: 按 Fonu 定位输出 Cloudflare 隧道适配版功能计划 2026-09-30 13:16:35 +08:00
mrlee dd40008be8 docs: 基于官方文档与参考项目输出 Cloudflare 隧道全功能规划 2026-09-30 12:04:07 +08:00
mrlee 2d0f63517b feat(cloudflare): 新增全局托管开关并发布 v1.8.0 2026-09-30 11:56:56 +08:00
mrlee 1434cfd72b feat(cloudflare): 自动创建隧道 DNS 记录并发布 v1.7.0 2026-09-28 18:47:37 +08:00
mrlee af07ebd462 fix(cloudflare): 测试连接使用当前输入的 Account ID 并发布 v1.6.9 2026-09-28 18:30:34 +08:00
mrlee 8f78aad19b feat(cloudflare): 改用 Account ID + API Token 创建管理隧道并发布 v1.6.8 2026-09-28 18:23:38 +08:00
mrlee 7acf13583b feat(cloudflare): 支持 API Token 连接验证并发布 v1.6.7 2026-09-28 17:53:45 +08:00
mrlee 26dd84abaa fix(cloudflare): Token 解码兼容 URL-safe base64 并发布 v1.6.6 2026-09-28 17:48:09 +08:00
mrlee 3caff9fd8e feat(cloudflare): Token 配置新增测试连接与获取入口并发布 v1.6.5 2026-09-28 17:32:06 +08:00
mrlee be35fbf546 fix(cloudflare): 隧道弹窗去除与应用配置重复字段并发布 v1.6.4 2026-09-28 17:27:15 +08:00
mrlee 5e995dee28 feat(cloudflare): 应用配置支持程序安装与默认 Token 并发布 v1.6.3 2026-09-28 16:59:30 +08:00
mrlee 0d7af99a78 fix(cloudflare): 统一隧道弹窗宽度并发布 v1.6.2 2026-09-28 16:44:39 +08:00
mrlee aefa2a5b20 feat(cloudflare): 完善隧道页面弹窗并发布 v1.6.1 2026-09-28 16:41:15 +08:00
mrlee a8a33e87d2 feat(cloudflare): 新增 Cloudflare 隧道独立模块并发布 v1.6.0 2026-09-28 16:36:05 +08:00
mrlee 66081e93d5 docs: 结合 Tunnel-Cloudflared-Manager 1.0.1 优化 Cloudflare Tunnel 方案 2026-09-28 16:16:10 +08:00
mrlee 8481bc3ac8 refactor(web): 统一前端轮询组合式函数并发布 v1.5.4 2026-09-28 16:06:52 +08:00
mrlee 21efc10536 test: 补路由鉴权、配置回滚与 Agent 版本兼容测试并发布 v1.5.3 2026-09-28 15:53:36 +08:00
mrlee 0feb6132d6 fix(agent): 升级 Agent 保持 HTTPS 直连并清理残留反代并发布 v1.5.2 2026-09-28 15:42:16 +08:00
mrlee 1ada58af02 refactor(nginx): 抽取共享 Nginx 模板包并发布 v1.5.1 2026-09-28 15:37:14 +08:00
mrlee faf43293e5 feat(agent): 完成 HTTPS 自动端口、证书轮换与防火墙辅助并发布 v1.5.0 2026-09-28 15:19:51 +08:00
mrlee dfce843b50 fix(agent): HTTPS 自检证书指纹并定位端口占用并发布 v1.4.6 2026-09-28 14:57:11 +08:00
mrlee 87c072f5d4 fix(agent): 探测阶段自愈 nginx 版本目录并发布 v1.4.5 2026-09-28 14:43:59 +08:00
mrlee c92d06642f fix(agent): 修复 nginx 版本目录被误加载并发布 v1.4.4 2026-09-28 14:37:15 +08:00
mrlee 8c07e64e87 fix(agent): 自愈 HTTPS 直连地址并发布 v1.4.3 2026-09-28 14:30:35 +08:00
mrlee 4a29bcb249 fix(agent): 同步更新 transport URL 并发布 v1.4.2 2026-09-28 14:24:37 +08:00
mrlee fac9234e4d feat(agent): 增加 HTTPS pin 模式并修复隧道端口竞态 2026-09-28 14:13:57 +08:00
mrlee 1bec91cc5e feat(agent): 默认回环监听并自动建立 SSH 隧道并发布 v1.4.0 2026-09-28 13:42:21 +08:00
mrlee 49d4af27ca fix(updater): 忽略容器路径并优先使用 Compose 配置目录 2026-09-28 12:01:39 +08:00
mrlee 63538ec5b7 fix(agent): 限流状态损坏时拒绝覆盖并发布 v1.3.9 2026-09-28 11:53:58 +08:00
mrlee 454371368c feat(web): 更新示例页验证内容并发布 v1.3.8 2026-09-28 11:32:33 +08:00
mrlee 4e948f65d1 fix(updater): 复用原 Compose 项目名并保护非 Compose 部署 2026-09-28 11:24:51 +08:00
mrlee f63c28e10e feat(web): 添加示例页升级验证区块并发布 v1.3.7 2026-09-28 11:15:16 +08:00
mrlee d154aef807 fix(updater): 自动定位宿主机 Compose 目录并发布 v1.3.6 2026-09-28 11:10:14 +08:00
mrlee 3f23610e59 feat(web): 更新示例页验证内容并发布 v1.3.5 2026-09-28 10:58:06 +08:00
mrlee bed1e223cc fix(updater): 修复 Compose 文件挂载并发布 v1.3.4 2026-09-28 10:30:50 +08:00
mrlee da054517c0 feat(web): 更新示例页升级验证标识并发布 v1.3.3 2026-09-27 19:25:49 +08:00
mrlee fa9cdf913f fix(updater): 通过 raw 接口读取远端版本并发布 v1.3.2 2026-09-27 19:18:54 +08:00
mrlee 6074cfceca feat(web): 添加在线升级验证示例页并发布 v1.3.1 2026-09-27 18:58:26 +08:00
mrlee 163df0c5b0 feat(update): 支持 Docker Compose 页面一键升级并发布 v1.3.0 2026-09-27 18:43:34 +08:00
mrlee 32dfe3b6de fix(agent): Bearer Token 改为常量时间比较并发布 v1.2.21 2026-09-27 18:27:23 +08:00
mrlee d39f8a7201 chore(release): 发布 v1.2.20 2026-09-27 18:16:40 +08:00
mrlee 4c49f6a3b5 fix(web): DDNS 页改用 FRP 多服务端状态接口 2026-09-27 18:14:47 +08:00
mrlee 8d932a50f3 docs: 添加项目详细分析与 P0-P3 改进路线实施方案 2026-09-27 18:14:42 +08:00
mrlee 70b891c2af feat(scripts): 新增 upgrade-hub.sh,仅编排文件的部署可一条命令升级
- 自动从仓库取 VERSION 作为镜像 tag(没装 git 则退回时间戳 tag,同样唯一可回滚)→ docker compose up -d --build(构建上下文是 Git 地址,自动拉最新分支)→ 轮询 /api/version 确认 → 打印当前版本与回滚命令

- .gitignore 白名单补 scripts/upgrade-hub.sh;bash -n 校验通过
2026-09-27 15:40:38 +08:00
mrlee 8f1114753d docs: 补充仅编排文件(hub 变体)部署时的升级与回滚方式
- 构建上下文是 Git 地址时,每次 --build 会重新解析仓库分支,无需 git pull;给出带 FONU_VERSION 的升级/回滚命令,并说明 scripts/upgrade.sh 需要本地源码目录、不适用于只有编排文件的部署目录

- 补充升级前后两件小事:整目录备份与启动日志确认
2026-09-27 15:34:00 +08:00
mrlee ac5d98330e feat(docker,docs): 数据目录可通过 FONU_DATA_PATH 指定(默认仍为命名卷),新增容器部署与数据指南(v1.2.19)
- 三个 compose 的挂载改为 \:/data:默认命名卷不变(老用户升级不受影响),在同层 .env 写 FONU_DATA_PATH=/vol1/docker/fonu-data 即可落到指定宿主机目录

- 新增 docs/container-deploy-and-data.md:编排文件选择、干净机器部署、数据目录与迁移(含从命名卷拷到宿主机目录)、备份三条注意(务必带上 session_secret)、升级与回滚、环境变量速查、常见问题排查

- 本轮不涉及 Go 代码,安装包未重出(dist 里 1.2.17 仍可用)
2026-09-27 15:31:26 +08:00
mrlee a954bf09a2 fix(docker): 去掉 # syntax 行(国内加速器 401 Unauthorized)并为 hub 编排加 pull_policy: build(v1.2.18)
- Dockerfile 顶部原来显式写 # syntax=docker/dockerfile:1,会让 BuildKit 额外拉 docker/dockerfile 镜像,在国内加速器(飞牛的 docker.fnnas.com)上被拦成 401,构建直接失败;该行已移除——RUN --mount=type=cache 由内建 BuildKit frontend 已支持,缓存挂载保持不变

- docker-compose.hub.yml 增加 pull_policy: build,跳过日志里那条 fonu Pulling(国内直连 Docker Hub 的超时告警)

- 本轮只改 Dockerfile 与 compose,不涉及 Go 代码:安装包未重出,dist 里 1.2.17 的包仍可用
2026-09-27 15:15:39 +08:00
mrlee 1309cfef5b feat(config,docker): 会话密钥未配置时自动生成并持久化,compose 改为留空即自动(v1.2.17)
- internal/config 新增 ResolveSessionSecret:显式配置优先;未配置则读 <数据目录>/session_secret,不存在或内容损坏就生成 32 字节随机密钥(64 字符,0600,先写临时文件再改名、写后显式 Chmod)

- FONU_SESSION_SECRET 默认值由 change-me-in-production 改为空(空 = 未配置 → 自动生成);启动日志打印密钥来源。注意该密钥同时是 secret.NewBox 的加密密钥,因此不替换已配置的值(含历史默认值,只提示)——替换会让库里已加密的凭据无法解密

- 三个 compose 统一 \;docker-compose.hub.yml 单文件部署不再需要 .env,直接 docker compose up -d --build

- .gitignore 补 .env 与 .env.local;测试 4 例(生成复用/权限/显式优先/历史默认值保留/损坏重生成),go build/vet/test 全绿
2026-09-27 15:08:28 +08:00
mrlee 84842e9359 feat(docker): docker-compose.hub.yml 改为从仓库拉取源码构建的单文件部署(v1.2.16)
- build.context 改用 Git 地址(http://45.207.223.190:10082/mrlee/-Fonu.git#main),由 BuildKit 自己克隆后构建:干净机器只需这一个 compose 文件 + 一个 .env,不必先 git clone;升级即回目录重跑 docker compose up -d --build

- FONU_SESSION_SECRET 改为必填(\),没给值直接拒绝启动并给出生成命令,避免用 change-me-in-production 跑在公网

- 文件头补齐完整用法与前提(需要 BuildKit、匿名可读则无需凭据、80/443 被占用改用 host 那份)
2026-09-27 14:58:47 +08:00
mrlee e0202a872f feat(web,docker): 仪表盘实时流量支持本机/公网来源切换,容器升级改为部署机直接构建(v1.2.15)
- 仪表盘「实时流量」新增数据源切换:本机读本地 Nginx 访问日志,公网读 frps 逐规则的 today_traffic_in/out 与 cur_conns(速率由后端两次采样算出,口径与公网反代页一致);两源归一成同一形状供汇总/Top/曲线共用,切换时清空 5 分钟曲线避免混采样,无穿透规则时公网按钮禁用

- Docker 交付(方案 1):Dockerfile 加 docker/dockerfile:1 语法与四处 RUN --mount=type=cache(npm/go 模块/编译缓存复用);三个 compose 统一 name: fonu(防止改目录名后 fonu-data 变新空卷)与 image: fonu:\(tag 随版本走便于回滚),.host.yml 补上缺失的 image

- 新增 scripts/upgrade.sh:一条命令完成拉代码→构建→重建→健康检查,支持 --no-pull / --rollback <tag>(不重建) / COMPOSE_FILE=(host 网络那份)

- 验证:bash -n 与 --help 实跑通过;容器构建与 compose 配置解析本机无 docker,需在 NAS 上执行一次确认
2026-09-27 14:38:27 +08:00
mrlee fc16fb2dc2 fix(agent,acme,cert,web): 修 frps 安装 404 与 nginx 探测两处,证书颁发机构用 LiteSSL 替换 Buypass(v1.2.14)
- frps 安装/升级一直 404:frp 官方校验文件名始终是 frp_sha256_checksums.txt(不带版本号),代码却拼 frp_<版本>_sha256sums.txt;现按候选名依次尝试并在失败时列出尝试项。同一条 bug 也存在于本机下载 frpc 的路径,一并修复(SHA-256 校验逻辑未改)

- nginx 探测(agent):nginxPath() 不再回落到配置里的裸名字 nginx(否则「未安装」被误报为配置校验失败,且一键安装入口永不出现);vhost 目录探测不再要求被加载文件带 .conf 后缀(Debian 的 sites-enabled/default 不带,导致只剩主配置目录可试,报「均无法放置完整 server 配置」),失败信息补上具体原因

- 证书 CA:LiteSSL(亚数 TrustAsia,90 天,支持单域名/通配符/多域名)替换 Buypass。LiteSSL 目录 meta.externalAccountRequired=true,强制 EAB——在 FreeSSL 创建后填 Kid/HMAC 即可,HMAC 只回掩码;Buypass 保留常量与展示元数据但不再可选

- 前端申请证书弹窗的颁发机构卡片改为前端可控清单(原先后端 /api/certs/options 的结果不参与渲染,后端改了弹窗不变)

- 测试:internal/frp 校验文件候选名与 sha256sum 解析;internal/acme LiteSSL 目录/别名/通配符/Buypass 停用提示。gofmt / go build / go vet / go test / vue-tsc / vite build 全绿

- AgentVersion 0.12.4 → 0.12.7,双架构二进制已重编:VPS 上需点「升级 Agent」
2026-09-27 13:44:03 +08:00
mrlee dda0eb876e feat(cert,scripts,docs): Linux 原生安装包与证书申请三处修复(DNS 解析器 / Buypass 下线 / ZeroSSL 报错与密钥脱敏)(v1.2.13)
- Linux 安装包:scripts/build-linux.ps1 交叉编译出 fonu-<版本>-linux-{amd64,arm64}.tar.gz(二进制 + migrations + systemd 安装脚本 + 运行时资源 + sha256),scripts/fonu-install.sh 负责装机(/opt/fonu、/var/lib/fonu、/etc/fonu/fonu.env 首次生成随机会话密钥)并新增 --reset-admin;装完直接打印初始管理员口令

- 证书 DNS-01:lego 默认读系统 resolv.conf(容器里是 Docker 的 127.0.0.11,不返回权威 NS)导致 could not determine authoritative nameservers;现显式传 AddRecursiveNameservers,默认 223.5.5.5/1.1.1.1/8.8.8.8,设置项 acme_dns_resolvers 可覆盖(system = 回到系统解析器)

- Buypass 已停止签发(2025-10-15)并终止服务(2026-04-15):从可选 CA 移除,历史记录仍可展示,直接提交会被拦下并给出中文原因

- ZeroSSL:422 时带出 error.type/error.code(非 JSON 退回截断正文);同时修掉网络错误把含 access_key 的完整 URL 写进任务日志与 app.log 的密钥泄露

- 测试:解析器列表解析 3 例 + ZeroSSL EAB 4 例(含不泄露密钥断言);gofmt / go build / go vet / go test 全绿
2026-09-27 10:10:15 +08:00
mrlee 2236259a52 fix(web,agent,frp): frps 配置预览脱敏、日志界面倒序与来源中文化,agent 0.12.4 重写日志日期格式(v1.2.12)
- frps.toml 同源配置预览泄露明文密钥:FRPSServerConfig(对外预览入口)改为走 maskFRPSSecrets,auth.token / auth.oidc.clientSecret 的值换成 ********(键名与结构保留、注释行不动);下发路径 PushFRPSConfigToAgent 与安装流程仍用未脱敏内容。弹窗补说明,「复制」改「复制(已脱敏)」

- agent 0.12.4:frps 日志 6 行 → 最近 20 行、最新在最上面;日期由 short-iso 的 2026-09-22T18:43:34+08:00 RainYun-XXX 重写为 2026-09-22 18:43:34 进程: 消息(去掉 T 分隔、时区偏移与每行重复的主机名),frps/action 失败日志一并统一

- 日志界面:FRP 日志「来源」列由 Go 源码文件名(client/control.go:174)改为中文模块名;规则详情「日志」页签倒序;「公网服务端」弹窗改为显示 VPS 上的 frps 服务日志

- 测试:maskFRPSSecrets 脱敏(明文不出现、非敏感行不误伤)与注释行不改写;gofmt / go build / go vet / go test / vue-tsc / vite build 全绿

- AgentVersion 0.12.2 → 0.12.4,双架构内嵌二进制已重编:需在 VPS 上点一次「升级 Agent」才生效
2026-09-25 13:56:07 +08:00
mrlee 74d731d0ac feat: 自动备份与保留策略、健康持续化与状态页、指标历史与趋势图,并修隧道判定误报与仪表盘布局(v1.2.11)
- 自动备份:每日一份(按最新备份是否在 24h 内判定,重启不重复)、保留份数可配、列表/下载/恢复/删除,恢复前先校验归档;顺手修 writeArchive 逐个检查 tar/gzip/文件 Close()(审查报告 §二)

- 健康持续化:只存状态变更(up/down/unknown)并推导可用率与不可用区间;公开状态页默认关闭、访问码存 SHA-256、按 IP 限流、只暴露域名与可用率

- 隧道判定修复:RouteHealthCandidate 新增 tunnel_known,frps 管理接口不可用时不再把「判不出来」当成「不通」(此前会误报「隧道连续不通」);汇总与徽标同样区分「无法判定」

- 指标历史:metrics_samples 纵向点表(本机 CPU/内存/磁盘 + 每规则上下行,30 天保留、查询按桶平均、不做降采样表);仪表盘趋势卡支持 1h/24h/7d

- 仪表盘布局:运行状态并入顶部统计区(运行时长补进「服务」卡);性能并入系统资源那一行,整行 4 列

- 测试:backup/metrics/frp/api/app 新增用例;gofmt、go build/vet/test、vue-tsc、vite build 全绿

- agent 无改动,AgentVersion 保持 0.12.2
2026-09-25 13:05:58 +08:00
mrlee c8264bf280 feat(notify): 告警补服务端掉线/Agent 不可达/配置漂移,巡检改 Source 接口(v1.2.10)
- 三个新事件(默认关闭):公网服务端掉线、公网 agent 不可达、配置漂移;连续失败阈值与漂移提醒间隔均可配,达标与恢复各报一次

- 避免误报:只在「用户要服务端运行」时判定掉线;ConnectionState=unknown 按健康处理;没配 agent 的服务端不参与可达性判定

- internal/monitor 改 Source 接口(Routes/Servers/Agents/Drift),frp 适配在 internal/app/monitor_source.go;「连续 N 次」抽成共用 failureTransition,通知一律在锁外调用

- 通知图标分类补齐;通知方式标签改「Webhook / IM 机器人」;新增 6 个设置项;补 serverDown/serverLabel/stateOr 测试

- agent 无改动,AgentVersion 保持 0.12.2
2026-09-25 09:54:48 +08:00
mrlee 862442e77f feat: 配置版本历史/对比/回滚、国内 IM 通知渠道、阈值告警与 API Token(v1.2.9)
- 配置版本:fsutil 版本化备份(内容相同自动去重),主 nginx.conf 与 VPS vhost 的版本列表/逐行差异/一键回滚,回滚先校验语法与 nginx -t 再写回

- agent 0.12.2:写 vhost 前留版本;nginx -t 校验失败改为恢复上一个可用版本(此前直接删文件),新增域名 vhost 版本端点,双架构二进制已重编

- 通知:补企业微信 / 钉钉 / 飞书机器人,切换预设时服务地址跟随该预设默认值

- 阈值告警:新增 internal/monitor 巡检(CPU/内存/磁盘持续超阈值、隧道连续 N 次未注册),默认关闭,带静默期与恢复通知

- API Token:api_tokens 表 + Authorization Bearer 认证,只读/读写两种范围;令牌管理与改密/退出仅限登录会话
2026-09-24 20:50:17 +08:00
mrlee 8f75e99339 fix(web,agent): P1 正确性与鉴权加固,P2 抽 fsutil 并补测试(v1.2.8) 2026-09-24 19:03:05 +08:00
mrlee 6abedbbe42 fix(security): P0 修复——备份恢复路径与权限、frps 安装白名单与 SHA-256、SSH 主机密钥 TOFU、三处凭据掩码,另修状态徽标与仪表盘文案(v1.2.7) 2026-09-24 17:06:34 +08:00
mrlee 0fce234ef3 feat(web): 公网服务端页并入服务端列表并改左列表右详情,内网穿透页改左服务端右规则(v1.2.6) 2026-09-24 15:27:26 +08:00
mrlee 828be2ea66 feat(agent): agent 0.11.0 新增证书清单与 Nginx 重载,公网 Agent 页并排展示 VPS 资源与证书(v1.2.5)
agent 0.11.0:新增 GET /api/v1/certs(遍历证书目录、crypto/x509 解析 fullchain.pem 到期时间、按剩余天数排序、解析失败记 warnings)与 POST /api/v1/nginx/reload(回传 nginx -t 与 reload 的失败原因,成功后失效可用性探测缓存)

应用侧:AgentClient.Certs / NginxReload + service / handler / router;agent 版本要求提到 ≥ 0.11.0(旧版本仍按 404/405 降级为升级提示)

前端:公网 Agent 页新增「VPS 证书」卡(域名/剩余天数/Fonu 证书库/到期时间,与 Fonu 证书库交叉核对);Nginx 卡新增「重载 Nginx」并显示失败原因;VPS 资源与 VPS 证书改为并排各占半行(dep-grid 6 列 + span 分配,窄屏复位)

二进制:内嵌 fonu-agent-linux-amd64 / arm64 重编;VERSION → 1.2.5
2026-09-24 10:49:28 +08:00
mrlee 2f59f5adc4 feat(agent): agent 0.10.0 新增资源/日志/配置回读端点,前端接入 VPS 资源与公网 Nginx 日志(v1.2.4)
agent 0.10.0:新增 GET /api/v1/metrics(资源采集,复用 internal/sysinfo;CPU 两次采样差值 + 1 秒内复用上次结果)、GET /api/v1/logs/nginx(日志尾部,路径白名单来自 nginx -T / 环境变量 / 默认目录,32KB 块倒读、单行 4KB 截断、上限 2000 行)、GET /api/v1/frps/config(frps.toml 回读,256KB 上限)

internal/sysinfo:补 LoadAvg 与 UptimeSeconds(Linux /proc/loadavg 与 /proc/uptime、Windows GetTickCount64、其它平台空值)

应用侧:AgentClient 三个只读方法;request 错误改为带状态码的 statusError,新增 ErrAgentEndpointMissing,把 404/405 统一转成「agent 版本过低需 ≥ 0.10.0」提示;补 service/handler/router

前端:公网 Agent 页「VPS 资源」横排带(占满环境与依赖整行);日志中心「公网 Nginx」页签;frps 同源配置弹窗「比对 VPS 实际文件」

二进制:内嵌 fonu-agent-linux-amd64 / arm64 用新代码重编;VERSION → 1.2.4
2026-09-24 10:15:11 +08:00
mrlee f75e672a45 feat: 公网反代部署漂移与全量重部署,仪表盘补公网穿透/系统资源/中国 IP 段/通知通道(v1.2.3)
仪表盘:新增「公网穿透」卡与运行状态「公网反代」行(新增 GET /api/frpmulti/routes/summary 逐台聚合);「性能」面板(今日异常/平均响应)与「流量 Top 5」;新增一行三卡「系统资源 / 中国 IP 段 / 通知通道」,系统资源来自新增跨平台采集 internal/sysinfo

仪表盘:「服务」卡不再写死「正常」,按 Fonu/Nginx/DDNS/证书四项实际状态聚合;/api/status 每 15 秒刷新并按页面可见性暂停轮询;删除死样式

公网反代:部署漂移清单(未部署/孤儿配置/未生效/内容不一致)+ 重新部署全部(逐条下发、单条失败不中断)

公网 Agent:端口矩阵补端口含义;frps 启动一致性核对;证书徽标补证书来源

FRP:frpc 版本探测失败时回落按二进制目录名推导,并逐台服务端探测

文档:新增 docs/agent-capability-plan.md(agent 能力扩展方案);VERSION 提升到 1.2.3
2026-09-24 09:20:07 +08:00
mrlee 8f6fac802f feat(web): 仪表盘补系统资源/中国 IP 段/通知通道与公网穿透卡,修复 frpc 版本读取
仪表盘:修「服务」卡写死的「正常」——改为按 Fonu/Nginx/DDNS/证书四项实际状态聚合,异常时点名并降级徽标

仪表盘:新增「性能」面板(今日异常/平均响应,/api/status 早已返回但从未展示)与「流量 Top 5」(复用已有逐规则流量轮询);/api/status 每 15 秒刷新并在页面隐藏时暂停(连同流量轮询)

仪表盘:新增「公网穿透」统计卡;运行状态面板增加公网反代行,数据来自新增的 GET /api/frpmulti/routes/summary(逐台服务端聚合,单台失败不中断)

仪表盘:新增一行三卡「系统资源 / 中国 IP 段 / 通知通道」;系统资源为新增跨平台采集 internal/sysinfo(Linux /proc、Windows kernel32,无新依赖)

FRP:修复 frpc 版本读不出来——RuntimeStatus.Version 带 omitempty,--version 探测失败时字段被省略,前端只能显示未检测;现回落按 <FrpDir>/bin/<版本>/ 目录名推导(与「FRP 应用配置」弹窗的 active_version 同源),并逐台服务端探测版本

清理:删除 DashboardView 死样式(.dashboard/.stat-highlight/.proxy-metric*)
2026-09-23 19:10:43 +08:00
mrlee 1b30be45a0 fix(web): FRP 日志页签解析、级别筛选与呈现对齐系统日志
解析:容忍行首 [组件] 前缀(真实行为 [web] …),来源取 [文件:行号]、缺失时回落组件名,级别统一大写

筛选:级别选项值 INFO/WARN/ERROR 与 frpc 单字母级别对齐(原先与中文标签比较永不相等,选中即过滤为空),并补筛选变化重置页码

呈现:级别/来源改小号标签、消息单行省略带 tooltip、时间走 logTimeCell,与「系统日志」页签一致;空态按筛选结果判定,区分「暂无日志」与「没有匹配的日志」
2026-09-23 18:08:31 +08:00
mrlee fd1661622e feat: 上游 1.0.3-1.0.5 同步第 1-8 项(v1.2.2)
剪贴板:新增 web/src/utils/clipboard.ts,5 处调用点支持非 HTTPS 环境(对齐 1.0.4)

日志中心:新增「FRP 日志」Tab,解析 frpc 日志为 时间/级别/来源/消息(对齐 1.0.3)

通知:单通道密文解密失败不再拖垮整份配置(对齐 1.0.5);容器补 TZ + tzdata(对齐 1.0.4);Telegram 代理自动补 http:// 并校验 scheme(对齐 1.0.3)

反向代理:复制不再追加「-复制」(对齐 1.0.5);监听占用校验合并表单规则与手动 Nginx 配置两张表(迁移 024 + endpoints 解析器),冲突提示写明占用规则;改端口的并发冲突改为可读提示

FRP:frps 弹窗补「VPS 防火墙放行 TCP 远程端口」提示(对齐 1.0.3);反代配置弹窗补齐内容区内边距与来源说明

文档:新增 docs/upstream-sync-plan.md(逐版本对照 + 第 5 项详细整理);VERSION 与 CHANGELOG 记 v1.2.2
2026-09-23 17:46:21 +08:00
mrlee 1e915fe7c1 chore: 忽略本地压缩包与导出产物(页面 UI 调整收尾)
本次页面 UI 调整分三笔完成:
- ca309db 公网反代页:协议列按启用 HTTPS 自动识别(StatusBadge 绿/灰 + 悬停说明)
- 70796e5 FRP 穿透页:状态卡统一标准统计区;修「运行中」状态颜色(statusKind 当 value 传被判为 unknown);公网服务端列表改 n-data-table;4 个弹窗统一外壳 + 详情弹窗排版对齐;补 :deep() 修好失效的单元格样式;13 处硬编码色值换令牌、内联样式清零、删死样式 15 条
- 本笔收尾:.gitignore 忽略 *.rar/*.zip/*.7z/*.tar.gz/*.log,本地压缩包(如 web/src.rar)不入库
2026-09-23 15:50:25 +08:00
mrlee 70796e5379 style(web): FRP 穿透页整体样式对齐标准页
- 状态卡改为标准 .stats-row/.stat-card(4 张:客户端状态/启用规则/frpc 版本/最近应用)
- 修 运行中 状态颜色:statusKind 返回合法 StatusKind 且改用 :kind(原先当 value 传导致被判为 unknown 灰色),详情弹窗同 bug 一并修
- 公网服务端列表改为 n-data-table(8 列,操作列含启动/停止/查看/日志/测速/校验/Agent 管理/编辑/删除)
- 4 个弹窗统一 .frp-card-modal 外壳(运行日志/导出配置/frps 同源配置/FRP 应用配置),服务端详情用 .frp-detail-card 对齐排版
- 单元格样式补 :deep()(render 创建的节点不带 scoped 属性),修好 table-muted/type-chip/mono 此前失效的问题
- 硬编码色值 13 处换令牌、内联样式清零、删死样式 15 条
2026-09-23 15:44:46 +08:00
mrlee ca309dbf42 feat(web): 公网反代页协议列按启用 HTTPS 自动识别
- 新增 protocolOf():从规则 options 的 https_disabled 反推入口协议(规则 type 恒为 http,不能代表入口协议)
- 协议列改用 StatusBadge:HTTPS 绿色 / HTTP 灰色,悬停说明 443 终结 TLS 与是否强制 301 跳转
- 列宽 80→90,scroll-x 1780→1790
2026-09-23 15:44:45 +08:00
mrlee 356dae2312 chore: 整理 .dockerignore 并刷新内嵌 agent 二进制
- .dockerignore: scripts 目录说明补正、去掉 docs 行的前导空格、补充 *.log/*.rar/*.zip/*.tar.gz/.breezell 排除
- agentbin: 重编后仅内嵌 git 版本戳变化,功能等价
2026-09-23 15:22:43 +08:00
mrlee 5b5091e1ed feat(web): 公网反代页重构(部署台账 + 弹窗对齐本地页)
- 台账改用 n-data-table:规则/域名(含复制与打开)、协议、上游/回源、健康、连接、当前上传、当前下载、总上传、总下载、更新时间、操作
- 单元格样式走 :deep():render 函数创建的节点不带 scoped 的 data-v 属性
- 修复 loadErrorMsg 从不渲染、按动作粒度 loading、切换服务端重置、轮询静默与可见性保护、移除反代二次确认
- 部署设置弹窗对齐本地反代页:900px、三段式、页脚分隔线、开关行底色,并新增右侧配置说明栏
- 新增统计区(可部署规则/已生效/健康通过/当前连接)与环境与 Nginx 卡(4 列)
- 文档:docs/proxy-remote-design.md
2026-09-23 15:22:43 +08:00
mrlee 8a98d8e4f0 feat(web): 公网 Agent 页按设计 v2 重构(功能清单驱动)
- 重写 AgentView.vue:运行状态 / 环境与依赖 / frps 控制 / Agent 生命周期 / 输出与日志 五段分区
- 补齐 5 处「数据已返回但页面未展示」:Agent 凭据状态、8080 端口、反代路由数、最后检查时间、Nginx 可用性
- 状态机:busy 按动作粒度 loading、轮询静默、切换服务端重置状态、三态区分(未加载/加载中/失败)
- 交互:卸载(含数据)二次确认;管理面板与安装 frps 常显但按条件禁用;输出改为带来源与时间的时间线
- 新增「配置查看」按钮 + 只读弹窗(getFrpFRPSConfig)
- 无障碍与响应式:section[aria-label]、aria-live、aria-hidden、320px、≤760px 触控目标、prefers-reduced-motion
- 文档:docs/agent-view-design-v2.md(设计规格)、docs/agent-view-design.md、docs/agent-view-refactor-plan.md
2026-09-23 13:54:42 +08:00
mrlee a3c31c626b 更新 README.md 2026-09-23 11:41:35 +08:00
mrlee 166449871f feat(agent): Basic Auth 改为纯 Go apr1 并去掉 VPS openssl 依赖
- 新增 internal/agent/apr1.go(Apache apr_md5_encode 移植)+ 参考向量单元测试(与 openssl 输出逐字节一致)
- ensureBasicAuthSecret / writeBasicAuthSecret 不再调用 openssl passwd -apr1
- 安装脚本 token 改用 /dev/urandom(内嵌副本与 scripts/agent-install.sh 同步)
- AgentVersion 0.9.2;重编 amd64/arm64 内嵌二进制
- CHANGELOG v1.2.0 补记该改动
2026-09-23 11:22:11 +08:00
mrlee 69d1bc0733 docs(changelog): 新增 v1.2.0 变更记录并将版本号提升到 1.2.0
- CHANGELOG: 新增 v1.2.0(公网反代全链路、五段健康检查、部署设置三梯队、frps 双版本兼容、Nginx 状态与一键安装、流量列)
- VERSION: 1.1.0 -> 1.2.0
2026-09-23 10:08:50 +08:00
mrlee 2fa82c4b31 chore(scripts): 纳入 agent 安装脚本并固定 shell 脚本行尾
- .gitignore: scripts/ 改为 scripts/* 并例外 agent-install.sh
- 新增 .gitattributes: *.sh text eol=lf
2026-09-23 09:48:40 +08:00
mrlee 278f8267b7 chore: 初始提交 Fonu 1.0.2
- 公网反代:Nginx 状态卡片(版本 / 运行状态 / 配置校验 / 端口监听)
- 部署设置第一、二梯队(HTTPS 开关、安全头、限流、连接数、仅中国大陆 IP)
- 隧道检测兼容 frps v0.68 / v0.71(V2 与旧版端点)
- 恢复被清空的 internal/frp/store.go、internal/api/ddns_handler.go、web/src/views/DdnsView.vue
2026-09-23 09:40:59 +08:00
489 changed files with 89785 additions and 227 deletions
+16
View File
@@ -0,0 +1,16 @@
.git
web/node_modules
web/dist
bin
*.db
/data
# 本地运行数据与归档,不进镜像(防止把真实数据库/证书/日志带入构建上下文)
.data
# 文档与本地杂项
docs
# 本地导出/打包产物与日志(预防性:不进入构建上下文)
*.log
*.rar
*.zip
*.tar.gz
.breezell
+2
View File
@@ -0,0 +1,2 @@
# shell 脚本一律以 LF 入库与检出,避免在 Windows 上被 CRLF 破坏(Linux 端会报 bad interpreter)
*.sh text eol=lf
+85
View File
@@ -0,0 +1,85 @@
name: CI
on:
push:
branches: ['**']
pull_request:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
verify:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
# 版本号是构建的唯一事实来源(VERSION 文件):前端 package.json 与它不一致时,
# 界面上显示的版本和二进制里的版本会对不上,所以在构建前先卡住。
- name: Check version consistency
run: |
version="$(tr -d ' \t\r\n' < VERSION)"
pkg="$(node -p "require('./web/package.json').version")"
echo "VERSION=$version package.json=$pkg"
if [ "$version" != "$pkg" ]; then
echo "::error::版本不一致:VERSION=$version,web/package.json=$pkg。请把两者改成同一个版本号。"
exit 1
fi
# 顺序不能颠倒:cmd/havline/main.go 用 //go:embed all:web/dist 嵌入前端,
# 干净检出时该目录不存在,go vet / go build 会直接失败。
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
cache-dependency-path: web/package-lock.json
- name: Install web dependencies
working-directory: web
run: npm ci
- name: Lint web
working-directory: web
run: npm run lint
- name: Type-check and build web
working-directory: web
run: npm run build
- name: Run web unit tests
working-directory: web
run: npm test
- name: Sync web dist into embed directory
run: |
rm -rf cmd/havline/web/dist
cp -r web/dist cmd/havline/web/dist
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache: true
# 格式化门禁:历史文件已在 M2 一次性 gofmt -w 过,从这里开始保持零容忍,
# 避免再退回「改动时顺手格式化一大片、review 看不出真实差异」的状态。
- name: gofmt
run: |
unformatted="$(gofmt -l internal cmd)"
if [ -n "$unformatted" ]; then
echo "::error::以下文件未格式化,请运行 gofmt -w internal cmd"
echo "$unformatted"
exit 1
fi
- name: go vet
run: go vet ./...
- name: go test
run: go test ./... -count=1
- name: go build
run: go build ./...
+105
View File
@@ -0,0 +1,105 @@
name: Docker Release
on:
push:
tags:
- 'v*'
workflow_dispatch:
inputs:
tag:
description: 'Release tag (e.g. v0.1.0)'
required: true
default: v0.1.0
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
concurrency:
group: docker-release-${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref }}-${{ matrix.arch }}
cancel-in-progress: false
strategy:
fail-fast: false
matrix:
include:
- platform: linux/amd64
arch: amd64
- platform: linux/arm64
arch: arm64
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref }}
- name: Resolve version
id: version
env:
REF_NAME: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref_name }}
run: echo "version=${REF_NAME#v}" >> "$GITHUB_OUTPUT"
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Set up QEMU
if: matrix.arch == 'arm64'
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push arch image
uses: docker/build-push-action@v6
with:
context: .
platforms: ${{ matrix.platform }}
push: true
build-args: |
VERSION=${{ steps.version.outputs.version }}
tags: ${{ secrets.DOCKERHUB_USERNAME }}/havline:${{ steps.version.outputs.version }}-${{ matrix.arch }}
labels: |
org.opencontainers.image.source=${{ github.repositoryUrl }}
org.opencontainers.image.version=${{ steps.version.outputs.version }}
org.opencontainers.image.revision=${{ github.sha }}
cache-from: type=gha,scope=${{ matrix.arch }}
cache-to: type=gha,mode=max,scope=${{ matrix.arch }}
create-manifest:
needs: build-and-push
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Resolve version
id: version
env:
REF_NAME: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref_name }}
run: echo "version=${REF_NAME#v}" >> "$GITHUB_OUTPUT"
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Create multi-arch manifest
env:
IMAGE: ${{ secrets.DOCKERHUB_USERNAME }}/havline
VERSION: ${{ steps.version.outputs.version }}
run: |
if [ -z "${IMAGE}" ]; then
echo "DOCKERHUB_USERNAME secret is not set" >&2
exit 1
fi
docker buildx imagetools create \
-t "${IMAGE}:${VERSION}" \
-t "${IMAGE}:latest" \
"${IMAGE}:${VERSION}-amd64" \
"${IMAGE}:${VERSION}-arm64"
+51
View File
@@ -0,0 +1,51 @@
name: GitHub Release
on:
push:
tags:
- 'v*'
workflow_dispatch:
inputs:
tag:
description: 'Release tag (e.g. v0.1.0)'
required: true
concurrency:
group: github-release-${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref }}
cancel-in-progress: true
jobs:
release:
runs-on: ubuntu-latest
permissions:
contents: write
env:
VERSION: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref_name }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ env.VERSION }}
- name: Extract release notes from CHANGELOG
id: notes
run: |
if awk -v ver="$VERSION" '
$0 ~ "^## \\[" ver "\\]" { found = 1; next }
found && /^## \[v/ { exit }
found { print }
' CHANGELOG.md > release-body.md && [ -s release-body.md ]; then
echo "use_changelog=true" >> "$GITHUB_OUTPUT"
else
echo "use_changelog=false" >> "$GITHUB_OUTPUT"
fi
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ env.VERSION }}
name: ${{ env.VERSION }}
body_path: ${{ steps.notes.outputs.use_changelog == 'true' && 'release-body.md' || '' }}
generate_release_notes: ${{ steps.notes.outputs.use_changelog != 'true' }}
draft: false
prerelease: false
+41
View File
@@ -0,0 +1,41 @@
bin/
.data/
web/node_modules/
web/dist/
cmd/havline/web/dist/
dist/
*.db
/data/
# 会话密钥等本地环境变量(.env.example 这类模板可以照常入库)
.env
.env.local
.DS_Store
.cursor/
.playwright-cli/
output/
# Windows 本地构建产物不入库(历史上误提交过 havline-agent.exe,10MB 级二进制)
*.exe
# 项目文档(方案 / 手册 / 截图)只保留在本地,不入版本库、不推送
# 例外:随仓库分发的示例可在取消忽略后单独跟踪
/docs/
web/public/111favicon.png
web/src/assets/brand/logo00.png
# scripts/ 下的本地辅助脚本不入库,但随仓库分发的 agent 安装脚本需要跟踪
scripts/*
!scripts/agent-install.sh
!scripts/build-linux.ps1
!scripts/havline-install.sh
!scripts/upgrade.sh
!scripts/upgrade-hub.sh
!scripts/push-oci-manual.ps1
# 本地压缩包与导出产物不入库(如 web/src.rar)
*.rar
*.zip
*.7z
*.tar.gz
*.log
# 前端 UI 原型(HTML 草稿与截图,约 2.8MB):只作设计参考,不是构建输入
/prototype/
# 只保留 npm 一份 lockfile:仓库里曾同时存在 pnpm-lock.yaml,
# 两份锁文件各自记录不同版本,装出哪个依赖取决于用哪个包管理器,容易排查不清
web/pnpm-lock.yaml
+1075
View File
File diff suppressed because it is too large Load Diff
+89
View File
@@ -0,0 +1,89 @@
# 不写 `# syntax=docker/dockerfile:1`:显式指定会让 BuildKit 额外去拉 docker/dockerfile 镜像,
# 在国内加速器(如飞牛的 docker.fnnas.com)上可能直接 401 Unauthorized;
# 而下面用到的 RUN --mount=type=cache 由 Docker 内建的 BuildKit frontend 已支持,无需显式指定。
ARG TARGETARCH
# 版本单一来源:根目录 VERSION 文件,本地改版本号只需改此文件
ARG VERSION_FILE=VERSION
# 本地项目:基础镜像默认走国内镜像源(fnOS 等环境直连 Docker Hub 会被加速器拦截 401)。
# 海外/可直连环境可用 --build-arg 或 .env 覆盖回官方名:NODE_IMAGE=node:22-alpine 等
ARG NODE_IMAGE=docker.m.daocloud.io/library/node:22-alpine
ARG GO_IMAGE=docker.m.daocloud.io/library/golang:1.23-bookworm
ARG RUNTIME_IMAGE=docker.m.daocloud.io/library/debian:bookworm-slim
ARG UPDATER_IMAGE=docker.m.daocloud.io/library/docker:27-cli
# Go 依赖代理:国内默认 goproxy.cn(官方 proxy.golang.org 国内不可达),海外可覆盖回 direct
ARG GOPROXY=https://goproxy.cn,direct
# 版本注入 stage:把根目录 VERSION 文件载入构建图,供前后端构建 stage 读取
FROM ${NODE_IMAGE} AS version
ARG VERSION_FILE
COPY ${VERSION_FILE} /VERSION
FROM --platform=$BUILDPLATFORM ${NODE_IMAGE} AS web-builder
WORKDIR /src/web
COPY web/package.json web/package-lock.json* ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY web/ ./
COPY --from=version /VERSION /src/web/.version
RUN VITE_APP_VERSION=$(tr -d ' \t\n\r' < /src/web/.version) npm run build
FROM --platform=$BUILDPLATFORM ${GO_IMAGE} AS go-builder
ARG TARGETARCH
ARG GOPROXY
ENV GOPROXY=${GOPROXY}
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
COPY --from=version /VERSION ./VERSION
# 先交叉编译 havline-agent 到 embed 目录(替换仓库中的占位文件),主程序构建时自动内嵌
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -o internal/frp/agentbin/havline-agent-linux-amd64 ./cmd/havline-agent \
&& CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -o internal/frp/agentbin/havline-agent-linux-arm64 ./cmd/havline-agent
COPY --from=web-builder /src/web/dist ./cmd/havline/web/dist
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build \
-ldflags "-X github.com/havline/havline/internal/version.Version=$(cat /src/VERSION | tr -d ' \t\n\r')" \
-o /havline ./cmd/havline
# 一键升级 sidecar:独立容器持有 Docker Socket,主程序只通过共享 Unix Socket 调用它
FROM --platform=$BUILDPLATFORM ${GO_IMAGE} AS updater-builder
ARG TARGETARCH
ARG GOPROXY
ENV GOPROXY=${GOPROXY}
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY cmd ./cmd
COPY internal ./internal
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build -trimpath -o /havline-updater ./cmd/havline-updater
# updater 运行时:Docker CLI / Compose 与 Git 只在 sidecar 内可用
FROM ${UPDATER_IMAGE} AS updater
RUN apk add --no-cache git docker-cli-compose docker-cli-buildx ca-certificates
COPY --from=updater-builder /havline-updater /usr/local/bin/havline-updater
ENTRYPOINT ["/usr/local/bin/havline-updater"]
# 运行时 stage
FROM ${RUNTIME_IMAGE}
ARG TARGETARCH
# frpc 不预装:需要内网穿透时在「应用配置」弹窗内按需下载(存入数据目录)
RUN apt-get update \
&& apt-get install -y --no-install-recommends nginx ca-certificates tzdata \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=go-builder /havline /app/havline
COPY --from=go-builder /src/web/assets/image /app/web/assets/image
COPY migrations /app/migrations
# 时区:Go 的 time.Local 取决于 TZ 环境变量,且需要镜像内存在 zoneinfo(故装上 tzdata)
ENV TZ=Asia/Shanghai \
HAVLINE_DATA_DIR=/data \
HAVLINE_LISTEN=:6893 \
HAVLINE_NGINX_MIME_TYPES=/etc/nginx/mime.types
EXPOSE 6893 80 443
VOLUME ["/data"]
CMD ["/app/havline"]
+667 -225
View File
@@ -1,232 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
Havline
Copyright (C) 2026 mrlee
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Havline Copyright (C) 2026 mrlee
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+337 -2
View File
@@ -1,3 +1,338 @@
# Havline
<p align="center">
<img src="web/src/assets/brand/havline-logo.svg" alt="Havline Logo" width="96" />
</p>
Havline
<h1 align="center">Havline</h1>
<p align="center"><strong>让 NAS 访问更简单</strong></p>
<p align="center">
面向 <strong>飞牛 fnOS</strong> 的轻量公网访问管理工具<br />
反向代理 · DDNS · HTTPS 证书 · 内网穿透 · Cloudflare Tunnel · 一站式 Web 管理
</p>
<p align="center">
<a href="https://github.com/mrlee233/havline/releases"><img src="https://img.shields.io/badge/version-2.0.0-22c55e?style=flat-square" alt="发布版本" /></a>
<img src="https://img.shields.io/badge/目标平台-飞牛_fnOS-22c55e?style=flat-square" alt="飞牛 fnOS" />
<img src="https://img.shields.io/badge/其他环境-未测试-94a3b8?style=flat-square" alt="其他环境未测试" />
<img src="https://img.shields.io/badge/Go-1.23-00ADD8?style=flat-square&logo=go&logoColor=white" alt="Go" />
<img src="https://img.shields.io/badge/Vue-3-4FC08D?style=flat-square&logo=vuedotjs&logoColor=white" alt="Vue 3" />
<img src="https://img.shields.io/badge/Nginx-内置-009639?style=flat-square&logo=nginx&logoColor=white" alt="Nginx" />
<a href="https://www.gnu.org/licenses/gpl-3.0.html"><img src="https://img.shields.io/badge/license-GPL--3.0-blue?style=flat-square" alt="GPL-3.0" /></a>
</p>
---
## 简介
**Havline** 是一款主要为 **飞牛 fnOS** 编写的反代与管理工具,帮助你在 NAS 上快速搭建稳定的公网访问能力:通过 Web 界面管理 Nginx 反向代理、自动同步 DDNS、申请与续期 Let's Encrypt 证书,并在一个仪表盘里查看服务状态、访问日志与流量统计。
无需手写 Nginx 配置,也无需在多个工具之间切换。当前开发与测试环境以飞牛 fnOS 为主,**群晖、威联通、自建 Linux 等其他环境尚未充分测试**,部署前请自行验证。
Havline 基于开源项目 [O96u/Fonu](https://github.com/O96u/Fonu) **1.0.2** 继续开发,保留上游在反向代理、DDNS、证书和内网穿透上的基础能力,并继续扩展公网 Agent、Cloudflare Tunnel、一键升级和飞牛应用交付。
## 功能特性
| 模块 | 说明 |
| -------------- | ---------------------------------------------------------------------------------------------- |
| **反向代理** | 多域名、多端口、HTTP/HTTPS、自动重定向;实时访问日志、流量统计、当前连接 IP |
| **DDNS** | 支持 Cloudflare、DNSPod、阿里云、腾讯云、火山引擎 DNS;单任务多根域名,自动同步公网 IP |
| **HTTPS 证书** | ACME 自动申请与续期;证书/私钥/ZIP 下载;申请进度实时日志 |
| **仪表盘** | 公网 IP、域名、证书、服务状态一览;请求趋势与运行健康度 |
| **日志中心** | 系统日志、Nginx 访问日志、Nginx 错误日志;分页筛选与自动刷新 |
| **内网穿透** | FRP 多服务端管理,支持 TCP/UDP/HTTP/HTTPS 等代理类型;客户端按需下载、配置与运行诊断 |
| **公网 Agent** | 通过 SSH 安装和维护 VPS Agent,远程管理 frps、Nginx、证书和路由 |
| **Cloudflare Tunnel** | cloudflared 按需下载、隧道与路由管理、DNS 同步、健康检查和漂移修复 |
| **一键升级** | 含 updater 的 Compose 部署支持镜像构建、主服务重建和版本健康检查 |
| **系统设置** | 常规 / 通知 / 安全 / 高级分栏;邮件/Webhook/Telegram 告警、备份与恢复 |
| **其他** | 深色模式、配置导出/导入、版本更新提示 |
## 相比上游 Fonu 的主要增量
| 方向 | Havline 增量 |
| --- | --- |
| **公网服务端** | 通过 SSH 安装、升级和维护 VPS 上的 `havline-agent`,远程管理 frps、Nginx、证书和公网反代 |
| **FRP 管理** | 多服务端管理、FRP 客户端按需下载、代理规则校验、运行诊断、路由健康与漂移检测 |
| **Cloudflare Tunnel** | cloudflared 按需下载、Account/API Token 预检、隧道与路由管理、DNS 同步、健康巡检和漂移修复 |
| **一键升级** | Compose + updater sidecar,支持构建/重建/健康检查,并在部分失败场景下尝试回滚 |
| **飞牛交付** | 提供 Docker 离线镜像包与 Native 应用两种形态,支持统一网关 `/app/havline` 接入 |
## 技术栈
| 层级 | 技术 |
| ------------ | ---------------------------------------------------------------------- |
| **后端** | Go 1.23、标准库 HTTP、SQLite(modernc.org/sqlite) |
| **反向代理** | 内置 Nginx(动态生成配置、热重载) |
| **证书** | go-acme/lego(ACME DNS-01) |
| **DDNS** | Cloudflare / DNSPod / 阿里云 / 腾讯云 / 火山引擎 DNS API |
| **内网穿透** | FRP 客户端按需下载;多服务端和代理规则管理,支持公网 Agent |
| **隧道** | Cloudflare Tunnel / cloudflared |
| **前端** | Vue 3、TypeScript、Vite、Naive UI、ECharts |
| **部署** | Docker 多架构镜像(amd64 / arm64)、GitHub Actions CI |
## 项目结构
| 路径 | 说明 |
| --- | --- |
| `cmd/havline` | 主程序入口,提供 Web 管理后台、API、调度和内置 Nginx/FRP 管理 |
| `cmd/havline-agent` | 公网 VPS 上的 Agent,接收主程序下发并管理 frps、Nginx、证书和路由 |
| `cmd/havline-updater` | 一键升级 sidecar,仅它挂载 Docker Socket,并通过 Unix Socket 与主程序通信 |
| `internal/api` | HTTP 路由、鉴权中间件、请求处理器和 API 响应封装 |
| `internal/app` | 应用启动、服务装配、统一网关和运行生命周期 |
| `internal/nginx`、`internal/nginxtmpl` | Nginx 配置生成、共享模板、安全/限流/geo/TLS 片段和热重载 |
| `internal/proxy`、`internal/service` | 反向代理规则、证书绑定、访问策略和 Nginx 配置编排 |
| `internal/frp` | FRP 多服务端、规则、运行进程、Agent 安装、诊断、健康和漂移检测 |
| `internal/cloudflared` | Cloudflare Tunnel 设置、隧道、路由、DNS、健康事件和漂移修复 |
| `internal/agent` | Agent 服务端实现,包括鉴权、监听策略、防火墙提示、Nginx/frps 操作 |
| `internal/updater` | updater 服务端、客户端、执行器和远端版本读取 |
| `internal/ddns`、`internal/certificate`、`internal/acme` | DDNS 服务商、证书存储、导入和 ACME 申请续期 |
| `internal/backup`、`internal/notify`、`internal/monitor`、`internal/metrics` | 备份恢复、通知渠道、监控采集和指标导出 |
| `web/src` | Vue 3 前端,包含 API 客户端、组合式函数、组件、路由、样式和页面视图 |
| `migrations` | SQLite 数据库迁移 |
| `docker-compose*.yml` | Host、Bridge 和单文件 Git 构建部署编排 |
## 部署
源码仓库:[https://github.com/mrlee233/havline](https://github.com/mrlee233/havline) · [发布版本](https://github.com/mrlee233/havline/releases)
以下方式均从源码构建,不使用上游 Docker 镜像。
| 场景 | 推荐方式 | 说明 |
| --- | --- | --- |
| 飞牛 fnOS 常规安装 | Host 模式 Compose | 避开系统已占用的 `80/443`,默认使用 `6893/18080/9443` |
| 非 host 网络或自定义端口映射 | Bridge 模式 Compose | 主服务和 updater 通过端口映射访问,适合测试或自建 Linux |
| 只拿一个 Compose 文件部署 | 单文件 Git 构建 | updater 从远端仓库读取版本并构建,本地不需要完整源码 |
| 飞牛应用商店安装 | Docker 离线包或 Native FPK | 见下方「飞牛 fnOS 应用」章节 |
### 快速部署(推荐 · 飞牛 fnOS · Host 模式)
飞牛系统已占用 **80/443**,使用 **host 网络** + **高位反代端口**,避免与系统 Nginx 冲突。
```bash
git clone --branch main https://github.com/mrlee233/havline.git
cd havline
docker compose -f docker-compose.host.yml up -d --build
```
| 入口 | 地址 |
| ------------------ | ----------------------- |
| 管理后台 | `http://<NAS-IP>:6893` |
| HTTP 反代(默认) | `http://<NAS-IP>:18080` |
| HTTPS 反代(默认) | `https://<NAS-IP>:9443` |
- 默认命名卷挂载到 `/data`,存放数据库、Nginx 配置、证书与日志;可通过 `HAVLINE_DATA_PATH` 选择绑定目录,已有数据须先迁移
- Host 编排设置反代默认端口为 `18080`、`9443`,可通过环境变量修改;该编排不包含 updater
### 其他部署方式
<details>
<summary>本地源码 + Bridge 网络</summary>
在已克隆的源码目录中执行:
```bash
docker compose -f docker-compose.yml up -d --build
```
默认映射 `6893:6893`、`18080:80`、`9443:443`。主程序首次启动时会在共享卷中自动生成 updater Token,updater 等待并读取同一文件,不会创建额外的初始化容器;只有 updater 挂载 Docker Socket。
</details>
<details>
<summary>单文件 Git 构建(不需要本地源码)</summary>
```bash
mkdir -p /opt/havline && cd /opt/havline
curl -fsSLo docker-compose.hub.yml \
https://github.com/mrlee233/havline/raw/branch/main/docker-compose.hub.yml
docker compose -f docker-compose.hub.yml up -d --build
```
BuildKit 从当前仓库 `main` 分支构建,默认使用 Bridge 端口映射。Token 由主程序自动生成,`HAVLINE_VERSION` 只控制镜像标签,不锁定源码提交。
</details>
<details>
<summary>手动构建镜像</summary>
```bash
docker build -t havline:local .
```
在源码根目录执行;构建镜像不会自动启动容器,部署时仍需选择合适的 Compose 编排。
</details>
### 首次登录
1. 启动后查看容器/运行日志,获取自动生成的 **admin 初始密码**
2. 访问 `http://<NAS-IP>:6893/login` 登录
3. 在 **设置** 中立即修改管理员密码
### FRP 内网穿透(无公网 IP)
适用于无法端口映射、无公网 IPv4 的场景。Havline 在 **内网穿透** 页面统一管理多个服务端与代理规则,**frpc 按需下载**:
- **Web 网关**:外网 HTTP/HTTPS 经 VPS 上的 frps 中转至本地 Havline Nginx(默认 `18080` / `9443`),域名分流、证书、访问控制、日志仍由 Nginx 处理
- **端口转发(TCP/UDP)**:将 VPS 远程端口映射到内网服务(如 SSH、数据库、DNS/游戏等 UDP);可与 Web 网关同时启用,纯端口穿透可不配置 Web 域名
- **服务端设置**:填写 frps 地址、端口、认证和 TLS 选项;保存后添加代理规则,校验配置再启动
**Web 流量路径**:用户 → DNS(解析到 VPS)→ frps → frpc → Havline Nginx → 内网服务
**端口转发流量路径**:用户 → VPS 公网 IP:远程端口 → frps → frpc → 内网 `IP:端口`(TCP 或 UDP)
#### 1. VPS 部署 frps
在具有公网 IP 的 VPS 上安装 [frp](https://github.com/fatedier/frp),选择与本地 frpc 兼容的版本。在服务端详情中查看生成的 `frps.toml` 参考,也可通过公网 Agent 管理 frps。
典型 Web 网关示例:
```toml
bindAddr = "0.0.0.0"
bindPort = 7000
auth.method = "token"
auth.token = "your-secret-token"
vhostHTTPPort = 80
vhostHTTPSPort = 443
```
启动:`frps -c frps.toml`。安全组/防火墙需放行 **7000**(控制连接)、**80/443**(Web 虚拟主机),以及 **隧道远程端口**(在 Havline 添加规则后按提示放行;UDP 隧道需在防火墙同时放行对应端口的 UDP)。
#### 2. Havline 配置 frpc
在侧栏 **内网穿透** 页面:
1. 添加服务端,填写服务器地址、端口、认证信息和 TLS 选项,与 VPS 上 frps 保持一致。
2. 添加 HTTP / HTTPS 代理时填写域名和本机 Nginx 目标端口;Host 编排默认使用 `18080` / `9443`,Bridge 容器内通常为 `80` / `443`,以实际规则为准。
3. 添加 TCP / UDP 代理时填写 VPS 远程端口及内网目标地址;开放对应安全组和防火墙端口。
4. 在应用配置中下载或激活 FRP 客户端,校验配置后启动,通过服务端诊断和日志检查运行状态。
控制连接成功不等于业务已连通,还需检查代理端口、内网目标、DNS 和 Nginx 路由。
#### 3. DNS 与证书
- **DDNS**:FRP 访问域名应解析到 **VPS 公网 IP**,而非 NAS IP;按需使用自定义 IP 或在 DNS 服务商处配置
- **HTTPS 证书**:Web 网关推荐继续使用 **DNS-01** 验证(Cloudflare、阿里云、腾讯云、DNSPod、火山引擎等已支持);证书仍在 NAS 侧 Nginx 终结
- **纯端口穿透**:无需为 TCP/UDP 隧道单独配置域名证书
### 公网 Agent 与 Cloudflare Tunnel
- **公网 Agent**:在公网 Agent 页面配置 VPS 信息,按需通过 SSH 安装并测试连接,再管理 frps、Nginx 和证书;需要公网反代时部署对应路由。限制 Agent 管理通道访问,不要仅凭业务端口可用判断管理通道安全。
- **Cloudflare Tunnel**:配置 Account ID 和 API Token,预检授权并按需下载 cloudflared;创建隧道后,在反向代理规则中选择 Cloudflare 出口和目标隧道,检查路由、DNS 与连接状态。托管模式从本地规则派生 ingress,修复漂移前先确认本地配置。
## 飞牛 fnOS 应用
Havline 提供两种飞牛应用形态,均支持统一网关入口 `/app/havline`。
### Docker 应用(离线镜像包)
- 独立仓库:<https://github.com/mrlee233/havline>
- 安装包:`havline-2.0.0.fpk`
- 包内包含 amd64 / arm64 离线镜像,安装时执行 `docker load`
- Compose 使用本地镜像并设置 `pull_policy: never`,不依赖外部 Registry
- 管理界面通过统一网关 `/app/havline` 访问
## 环境变量
| 变量 | 默认值 | 说明 |
| ----------------------- | ------------------------- | ------------------------------------------ |
| `HAVLINE_LISTEN` | `:6893` | 管理后台监听地址 |
| `HAVLINE_DATA_DIR` | `/data` | 数据目录(数据库、Nginx 配置、证书、日志) |
| `HAVLINE_SESSION_SECRET` | 空,自动生成 | 会话与凭据加密密钥,保存在数据目录;已有数据后不要更换 |
| `HAVLINE_INITIAL_ADMIN_PASSWORD` | 空,自动生成 | 首次初始化管理员时使用的密码;不设置时会生成随机密码并输出到首次启动日志 |
| `HAVLINE_UPDATER_TOKEN` | 空,自动生成 | 可选覆盖值;未设置时读取共享 Token 文件 |
| `HAVLINE_UPDATER_TOKEN_FILE` | `/run/havline-updater/updater.token` | 主程序与 updater sidecar 共享的 Token 文件 |
| `HAVLINE_UPDATER_SOCKET` | `/run/havline-updater/updater.sock` | 主程序与 updater sidecar 通信的 Unix Socket |
| `HAVLINE_DATA_PATH` | `havline-data` | Compose 挂载来源,可配置宿主机目录 |
| `HAVLINE_NGINX_HTTP_PORT` | `80` | 新建 HTTP 反代规则的默认监听端口 |
| `HAVLINE_NGINX_HTTPS_PORT` | `443` | 新建 HTTPS 反代规则的默认监听端口 |
| `HAVLINE_NGINX_BIN` | `nginx` | Nginx 可执行文件路径(本地开发可指定) |
| `HAVLINE_FRPC_BIN` | `frpc` | frpc 可执行文件路径(运行时可按需下载) |
| `HAVLINE_FRP_PID` | `{DATA_DIR}/frp/frpc.pid` | frpc 进程 PID 文件路径 |
| `HAVLINE_GATEWAY_SOCKET` | 空 | 飞牛统一网关接入时使用的 Unix Socket |
| `HAVLINE_GATEWAY_PREFIX` | 空 | 统一网关访问前缀,例如 `/app/havline` |
| `HAVLINE_AGENT_LISTEN` | `127.0.0.1:7700` | Agent 默认监听地址 |
| `HAVLINE_AGENT_ALLOW_REMOTE` | `0` | 是否允许 Agent 监听非回环地址;启用前应确认防火墙和 HTTPS/隧道策略 |
| `HAVLINE_AGENT_TOKEN` | 安装时生成 | Agent Bearer Token |
| `HAVLINE_UPDATE_PROJECT_DIR` | `/workspace` | updater 容器内 Compose 项目目录 |
| `HAVLINE_UPDATE_COMPOSE_FILE` | `docker-compose.yml` | updater 允许操作的 Compose 文件 |
| `HAVLINE_UPDATE_MODE` | `local` | 升级模式,支持 `local` 或 `git` |
| `HAVLINE_UPDATE_REPO` | 无 | `git` 模式下的远端仓库地址 |
| `HAVLINE_UPDATE_BRANCH` | `main` | `git` 模式下的分支 |
| `HAVLINE_UPDATE_HOST_DIR` | 自动发现 | 宿主机 Compose 文件目录;自动发现失败时必须显式设置 |
### 数据目录速查
| 路径 | 内容 |
| --- | --- |
| `/data/havline.db` | 管理员、会话、代理、DDNS、FRP、Cloudflare、健康事件等 SQLite 数据 |
| `/data/session_secret` | 会话签名与敏感凭据加密主密钥;已有数据后不可随意更换 |
| `/data/nginx/` | 生成的 Nginx 配置、日志和相关运行文件 |
| `/data/certs/` | ACME 证书与私钥 |
| `/data/frp/` | frpc 配置、二进制、PID 和运行状态 |
## 注意事项
1. **密钥持久化**:会话密钥未显式配置时自动生成并写入数据目录;已有数据不要更换密钥。含 updater 的编排会由主程序在共享卷中自动生成 Token,旧部署仍可用 `HAVLINE_UPDATER_TOKEN` 覆盖。
2. **端口冲突**:宿主机已有 Nginx(如飞牛系统)占用 80/443 时,不要让 Havline 反代规则监听 80/443;使用 `18080/9443` 或 host 模式 + 环境变量。
3. **已有反代规则**:修改 `HAVLINE_NGINX_HTTP_PORT` / `HAVLINE_NGINX_HTTPS_PORT` 后,**不会自动更新**数据库中已有规则的端口,需在反代页手动修改并保存。
4. **访问日志**:仅统计经 Havline Nginx 反代的域名流量,不包含管理后台 `:6893` 的请求。
5. **证书与 DNS**:DNS-01 申请不要求域名指向 NAS,但需确保 DNS 凭证能写入对应根域的验证记录,并等待传播。业务访问仍需正确解析、端口和路由。
6. **数据持久化**:Docker 部署请挂载 volume 到 `HAVLINE_DATA_DIR`,避免容器重建后配置丢失。
7. **备份**:可通过设置页导出数据;文件级备份前停止服务,保留整个数据目录(数据库、密钥、证书私钥和运行配置);显式环境密钥需另行安全保留。
8. **升级**:含 updater 的 Compose 实例可使用一键升级;仅重建后版本健康检查失败时尝试镜像回滚,构建失败和数据库迁移回退需人工处理。升级前保留备份和旧镜像。
## 常见问题
| 现象 | 优先检查 |
| --- | --- |
| 无法登录或忘记初始密码 | 首次启动日志中的 `admin` 密码;若日志已丢失,停止服务后从备份恢复,或按部署文档处理数据库 |
| 启动后提示端口被占用 | 飞牛系统通常占用 `80/443`;Host 模式请使用 `6893/18080/9443`,Bridge 模式检查端口映射 |
| 修改反代端口后旧规则不生效 | `HAVLINE_NGINX_HTTP_PORT` / `HAVLINE_NGINX_HTTPS_PORT` 只影响新规则,已有规则需在反代页手动修改 |
| 证书申请失败 | 检查 DNS 服务商凭证、根域权限、ACME 邮箱、DNS 传播和 CA 限制;泛域名必须使用 DNS-01 |
| DDNS 没有更新 | 检查 DNS API 权限、记录是否存在、公网 IP 探测结果;FRP 场景域名应解析到 VPS 公网 IP |
| FRP 客户端启动失败 | 确认 frps 地址/端口/Token/TLS 一致,VPS 安全组已放行控制端口和远程端口 |
| Cloudflare DNS 未自动创建 | 确认根域名在同一个 Account ID 下,API Token 至少具备 Zone:Read 和 DNS:Edit |
| Cloudflare 隧道 502 或 Token 错误 | 使用 API Token 预检;Tunnel Token 与 Account API Token 不是同一种凭据 |
| 升级时找不到 Compose 文件 | 设置 `HAVLINE_UPDATE_HOST_DIR` 指向宿主机 Compose 所在目录,并确认容器名和 Compose 项目标签来自同一部署 |
| 升级后数据异常 | 恢复升级前备份,确认 `HAVLINE_DATA_DIR`、`session_secret` 和数据库迁移状态未变化 |
| Agent 直连失败 | 确认 Agent 监听地址、端口、防火墙和 Token;默认策略应优先使用 SSH 隧道或 HTTPS,不建议直接暴露管理端口 |
| 公网访问失败 | 按 DNS → 端口/隧道 → Nginx 路由 → 内网服务逐段排查,不要只看 FRP 或 Tunnel 是否在线 |
## 本地开发
```powershell
# 构建前端并准备嵌入目录
cd web
npm ci
npm run build
cd ..
New-Item -ItemType Directory -Force cmd/havline/web/dist | Out-Null
Copy-Item web/dist/* cmd/havline/web/dist -Recurse -Force
# 运行后端(需要可用 Nginx)
go run ./cmd/havline
```
前端热更新在另一终端执行 `cd web`、`npm run dev`。测试命令:
```powershell
go test ./...
go vet ./...
cd web
npm run typecheck
npm test
```
版本来源为根目录 `VERSION`;Docker 构建注入前后端,本地 `go run` 未注入时显示 `dev`。
## 开源协议
本项目采用 [GPL-3.0](https://www.gnu.org/licenses/gpl-3.0.html) 开源。
Havline 基于 [O96u/Fonu](https://github.com/O96u/Fonu) **1.0.2** 版本继续开发,感谢上游作者及贡献者。保留原作者版权、来源与 GPL-3.0 下适用的源代码提供义务。
问题反馈:[Havline Issues](https://github.com/mrlee233/havline/issues)。请提供版本、部署方式、复现步骤和脱敏日志,不上传密码、Token、私钥或完整备份。
+1
View File
@@ -0,0 +1 @@
2.0.0
+62
View File
@@ -0,0 +1,62 @@
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"os/signal"
"strings"
"syscall"
"github.com/havline/havline/internal/agent"
)
func main() {
listen := flag.String("listen", envOr("HAVLINE_AGENT_LISTEN", "127.0.0.1:7700"), "agent listen address")
allowRemote := flag.Bool("allow-remote", envBool("HAVLINE_AGENT_ALLOW_REMOTE"), "allow non-loopback listen address")
token := flag.String("token", os.Getenv("HAVLINE_AGENT_TOKEN"), "agent bearer token")
nginxDir := flag.String("nginx-conf-dir", envOr("HAVLINE_AGENT_NGINX_CONF_DIR", ""), "managed nginx config directory(留空自动探测 Nginx 实际加载的 vhost 目录)")
certsDir := flag.String("certs-dir", envOr("HAVLINE_AGENT_CERTS_DIR", "/var/lib/havline-agent/certs"), "certificate directory")
frpsConfig := flag.String("frps-config", envOr("HAVLINE_AGENT_FRPS_CONFIG", "/etc/frp/frps.toml"), "frps config path")
frpsBin := flag.String("frps-bin", envOr("HAVLINE_AGENT_FRPS_BIN", "frps"), "frps binary")
dataDir := flag.String("data-dir", envOr("HAVLINE_AGENT_DATA_DIR", "/var/lib/havline-agent"), "agent data directory")
showVersion := flag.Bool("version", false, "print agent version and exit")
flag.Parse()
if *showVersion {
fmt.Println("havline-agent", agent.AgentVersion)
return
}
if *token == "" {
log.Fatal("HAVLINE_AGENT_TOKEN or -token is required")
}
server, err := agent.NewServer(agent.Config{
ListenAddr: *listen, AllowRemote: *allowRemote, Token: *token, NginxConfDir: *nginxDir,
CertsDir: *certsDir, FrpsConfigPath: *frpsConfig, FrpsBinary: *frpsBin, DataDir: *dataDir,
})
if err != nil {
log.Fatal(err)
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
if err := server.ListenAndServe(ctx); err != nil && ctx.Err() == nil {
log.Fatal(err)
}
}
func envOr(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
func envBool(key string) bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv(key))) {
case "1", "true", "yes", "on":
return true
default:
return false
}
}
+59
View File
@@ -0,0 +1,59 @@
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/havline/havline/internal/updater"
)
func main() {
token, tokenSource, err := updater.WaitForToken(
envOr("HAVLINE_UPDATER_TOKEN", ""),
envOr("HAVLINE_UPDATER_TOKEN_FILE", updater.DefaultTokenPath),
2*time.Minute,
)
if err != nil {
log.Fatal(err)
}
if token == "" {
log.Fatal("HAVLINE_UPDATER_TOKEN 或 HAVLINE_UPDATER_TOKEN_FILE 未配置")
}
log.Printf("updater Token 已就绪:%s", tokenSource)
server, err := updater.NewServer(updater.Config{
SocketPath: envOr("HAVLINE_UPDATER_SOCKET", "/run/havline-updater/updater.sock"),
ProjectDir: envOr("HAVLINE_UPDATE_PROJECT_DIR", "/workspace"),
ComposeFile: envOr("HAVLINE_UPDATE_COMPOSE_FILE", "docker-compose.yml"),
Service: envOr("HAVLINE_UPDATE_SERVICE", "havline"),
Mode: envOr("HAVLINE_UPDATE_MODE", "local"),
RepoURL: envOr("HAVLINE_UPDATE_REPO", ""),
Branch: envOr("HAVLINE_UPDATE_BRANCH", "main"),
AppURL: envOr("HAVLINE_UPDATE_APP_URL", "http://havline:6893"),
HostProjectDir: envOr("HAVLINE_UPDATE_HOST_DIR", ""),
ProjectName: envOr("HAVLINE_UPDATE_PROJECT_NAME", ""),
SelfImage: envOr("HAVLINE_UPDATE_SELF_IMAGE", ""),
DockerSocket: envOr("HAVLINE_UPDATE_DOCKER_SOCK", "/var/run/docker.sock"),
Token: token,
}, nil)
if err != nil {
log.Fatal(err)
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
if err := server.Serve(ctx); err != nil && ctx.Err() == nil {
log.Fatal(err)
}
}
func envOr(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
+54
View File
@@ -0,0 +1,54 @@
package main
import (
"context"
"embed"
"errors"
"io/fs"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/havline/havline/internal/app"
"github.com/havline/havline/internal/config"
)
//go:embed all:web/dist
var webDist embed.FS
func main() {
cfg := config.Load()
migrationsDir, err := app.ResolveMigrationsDir()
if err != nil {
log.Fatalf("resolve migrations: %v", err)
}
staticFS, err := fs.Sub(webDist, "web/dist")
if err != nil {
log.Fatalf("load static files: %v", err)
}
application, err := app.New(cfg, staticFS, migrationsDir)
if err != nil {
log.Fatalf("start application: %v", err)
}
go func() {
if err := application.Run(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("server error: %v", err)
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
<-stop
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := application.Shutdown(ctx); err != nil {
log.Printf("shutdown error: %v", err)
}
}
+15
View File
@@ -0,0 +1,15 @@
types {
text/html html htm shtml;
text/css css;
text/javascript js;
application/json json;
image/gif gif;
image/jpeg jpeg jpg;
application/javascript js;
application/octet-stream bin exe dll;
image/png png;
image/svg+xml svg svgz;
image/webp webp;
font/woff woff;
font/woff2 woff2;
}
+37
View File
@@ -0,0 +1,37 @@
# 源码仓库:https://github.com/mrlee233/havline.git(main 分支)
# 飞牛 NAS 等已占用 80/443 的环境:使用 host 网络 + 高位默认反代端口
# 本地项目:直接用源码构建镜像,不从 Docker Hub 拉取
name: havline
services:
havline:
build:
context: .
args:
NODE_IMAGE: ${NODE_IMAGE:-docker.m.daocloud.io/library/node:22-alpine}
GO_IMAGE: ${GO_IMAGE:-docker.m.daocloud.io/library/golang:1.23-bookworm}
RUNTIME_IMAGE: ${RUNTIME_IMAGE:-docker.m.daocloud.io/library/debian:bookworm-slim}
GOPROXY: ${GOPROXY:-https://goproxy.cn,direct}
image: havline:${HAVLINE_VERSION:-local}
# 本地源码部署直接构建,跳过无意义的 Docker Hub 拉取和超时警告。
pull_policy: build
container_name: havline
restart: unless-stopped
network_mode: host
volumes:
# 数据目录:默认用命名卷 havline-data(由 Docker 管理,位置随 Docker 数据根)。
# 想落到指定目录就在同层 .env 里设 HAVLINE_DATA_PATH=/vol1/docker/havline-data ——
# 以 / 或 . 开头的写法会被 compose 当成 bind mount,其余字符串仍是命名卷。
- ${HAVLINE_DATA_PATH:-havline-data}:/data
environment:
HAVLINE_DATA_DIR: /data
HAVLINE_LISTEN: :6893
# 留空即自动:应用会在数据目录里生成并持久化 <DataDir>/session_secret(0600)
# 想自己指定就设这个变量;注意它同时是凭据加密密钥,已有数据后不要随意更换
HAVLINE_SESSION_SECRET: ${HAVLINE_SESSION_SECRET:-}
# 时区:通知消息时间按此显示(默认东八区)
TZ: ${TZ:-Asia/Shanghai}
HAVLINE_NGINX_HTTP_PORT: ${HAVLINE_NGINX_HTTP_PORT:-18080}
HAVLINE_NGINX_HTTPS_PORT: ${HAVLINE_NGINX_HTTPS_PORT:-9443}
volumes:
havline-data:
+97
View File
@@ -0,0 +1,97 @@
# 从仓库拉源码构建并启动(适合干净机器:只要这一个文件)
#
# 用法:
# mkdir -p /opt/havline && cd /opt/havline
# # 取本文件(按你仓库页面上的「原始文件」链接下载,或 git clone 后复制过来):
# # curl -fsSLo docker-compose.hub.yml https://raw.githubusercontent.com/mrlee233/havline/main/docker-compose.hub.yml
# docker compose up -d --build # 会话密钥由应用首次启动自动生成并持久化在数据卷里
#
# 想自己指定会话密钥(可选项):在 compose 文件同层建 .env 写入
# HAVLINE_SESSION_SECRET=<一串随机字符,openssl rand -hex 32 可生成>
# 注意:它同时是凭据加密密钥,数据卷里已经有数据后不要随意更换,否则已存的凭据无法解密。
#
# 构建上下文用的是 Git 地址:BuildKit 会自己把仓库克隆下来,不需要先 git clone 到本地;
# 仓库匿名可读时无需凭据。需要认证时改用 https://<用户名>:<令牌>@<主机>/<路径>.git,
# 或先 git clone 后用 docker-compose.yml(本地上下文那份)。
#
# 首次构建要拉前端与 Go 依赖,比较慢;之后靠 Dockerfile 里的 cache mount 复用缓存。
# 80/443 已被占用(如飞牛 NAS)请改用 docker-compose.host.yml。
name: havline
services:
havline:
build:
context: https://github.com/mrlee233/havline.git#main
args:
NODE_IMAGE: ${NODE_IMAGE:-docker.m.daocloud.io/library/node:22-alpine}
GO_IMAGE: ${GO_IMAGE:-docker.m.daocloud.io/library/golang:1.23-bookworm}
RUNTIME_IMAGE: ${RUNTIME_IMAGE:-docker.m.daocloud.io/library/debian:bookworm-slim}
UPDATER_IMAGE: ${UPDATER_IMAGE:-docker.m.daocloud.io/library/docker:27-cli}
GOPROXY: ${GOPROXY:-https://goproxy.cn,direct}
image: havline:${HAVLINE_VERSION:-local}
# 有 build 段时 compose 默认会先尝试拉同名镜像(日志里那条 "havline Pulling" 就是),
# 国内直连 Docker Hub 会超时报警;强制走构建,跳过这一步。
pull_policy: build
container_name: havline
restart: unless-stopped
depends_on:
- updater
ports:
- "6893:6893"
- "18080:80"
- "9443:443"
volumes:
# 数据目录:默认用命名卷 havline-data(由 Docker 管理,位置随 Docker 数据根)。
# 想落到指定目录就在同层 .env 里设 HAVLINE_DATA_PATH=/vol1/docker/havline-data ——
# 以 / 或 . 开头的写法会被 compose 当成 bind mount,其余字符串仍是命名卷。
- ${HAVLINE_DATA_PATH:-havline-data}:/data
- havline-updater-sock:/run/havline-updater
environment:
HAVLINE_DATA_DIR: /data
HAVLINE_LISTEN: :6893
HAVLINE_UPDATER_SOCKET: /run/havline-updater/updater.sock
# 主程序首次启动时生成共享 Token;旧部署仍可用环境变量覆盖
HAVLINE_UPDATER_TOKEN: ${HAVLINE_UPDATER_TOKEN:-}
HAVLINE_UPDATER_TOKEN_FILE: /run/havline-updater/updater.token
# 留空即自动:应用会在数据目录里生成并持久化 <DataDir>/session_secret(0600)
# 想自己指定就在同层 .env 里设这个变量;注意它同时是凭据加密密钥,已有数据后不要更换
HAVLINE_SESSION_SECRET: ${HAVLINE_SESSION_SECRET:-}
# 时区:通知消息时间按此显示(默认东八区)
TZ: ${TZ:-Asia/Shanghai}
# 受限升级 sidecar:只有它持有 Docker Socket,主程序通过共享 Unix Socket 触发
updater:
build:
context: https://github.com/mrlee233/havline.git#main
target: updater
args:
GO_IMAGE: ${GO_IMAGE:-docker.m.daocloud.io/library/golang:1.23-bookworm}
UPDATER_IMAGE: ${UPDATER_IMAGE:-docker.m.daocloud.io/library/docker:27-cli}
GOPROXY: ${GOPROXY:-https://goproxy.cn,direct}
image: havline-updater:${HAVLINE_VERSION:-local}
pull_policy: build
container_name: havline-updater
restart: unless-stopped
volumes:
- ${DOCKER_SOCK:-/var/run/docker.sock}:/var/run/docker.sock
- ${HAVLINE_UPDATE_HOST_DIR:-.}:/workspace
- havline-updater-sock:/run/havline-updater
environment:
HAVLINE_UPDATER_SOCKET: /run/havline-updater/updater.sock
HAVLINE_UPDATER_TOKEN: ${HAVLINE_UPDATER_TOKEN:-}
HAVLINE_UPDATER_TOKEN_FILE: /run/havline-updater/updater.token
HAVLINE_UPDATE_PROJECT_DIR: /workspace
HAVLINE_UPDATE_COMPOSE_FILE: docker-compose.hub.yml
HAVLINE_UPDATE_SERVICE: havline
HAVLINE_UPDATE_MODE: git
HAVLINE_UPDATE_REPO: https://github.com/mrlee233/havline.git
HAVLINE_UPDATE_BRANCH: main
HAVLINE_UPDATE_APP_URL: http://havline:6893
HAVLINE_UPDATE_HOST_DIR: ${HAVLINE_UPDATE_HOST_DIR:-}
HAVLINE_UPDATE_PROJECT_NAME: ${HAVLINE_UPDATE_PROJECT_NAME:-havline}
HAVLINE_UPDATE_SELF_IMAGE: havline-updater:${HAVLINE_VERSION:-local}
HAVLINE_UPDATE_DOCKER_SOCK: ${DOCKER_SOCK:-/var/run/docker.sock}
TZ: ${TZ:-Asia/Shanghai}
volumes:
havline-data:
havline-updater-sock:
+83
View File
@@ -0,0 +1,83 @@
# 源码仓库:https://github.com/mrlee233/havline.git(main 分支)
# 固定项目名:不改的话,改了目录名/项目名后 compose 会把它当成新项目,
# havline-data 会变成新空卷(看起来像「数据丢了」)。
name: havline
# 本地项目:用源码构建镜像(镜像名随 VERSION 变,便于回滚;也便于导出 / 备份)
# 升级:docker compose up -d --build(或在部署机跑 scripts/upgrade.sh)
# 回滚:HAVLINE_VERSION=上一个版本号 docker compose up -d(镜像 tag 还在本地)
services:
havline:
build:
context: .
args:
NODE_IMAGE: ${NODE_IMAGE:-docker.m.daocloud.io/library/node:22-alpine}
GO_IMAGE: ${GO_IMAGE:-docker.m.daocloud.io/library/golang:1.23-bookworm}
RUNTIME_IMAGE: ${RUNTIME_IMAGE:-docker.m.daocloud.io/library/debian:bookworm-slim}
UPDATER_IMAGE: ${UPDATER_IMAGE:-docker.m.daocloud.io/library/docker:27-cli}
GOPROXY: ${GOPROXY:-https://goproxy.cn,direct}
image: havline:${HAVLINE_VERSION:-local}
# 本地源码部署直接构建,跳过无意义的 Docker Hub 拉取和超时警告。
pull_policy: build
container_name: havline
restart: unless-stopped
depends_on:
- updater
ports:
- "6893:6893"
- "18080:80"
- "9443:443"
volumes:
# 数据目录:默认用命名卷 havline-data(由 Docker 管理,位置随 Docker 数据根)。
# 想落到指定目录就在同层 .env 里设 HAVLINE_DATA_PATH=/vol1/docker/havline-data ——
# 以 / 或 . 开头的写法会被 compose 当成 bind mount,其余字符串仍是命名卷。
- ${HAVLINE_DATA_PATH:-havline-data}:/data
- havline-updater-sock:/run/havline-updater
environment:
HAVLINE_DATA_DIR: /data
HAVLINE_LISTEN: :6893
HAVLINE_UPDATER_SOCKET: /run/havline-updater/updater.sock
# 主程序首次启动时生成共享 Token;旧部署仍可用环境变量覆盖
HAVLINE_UPDATER_TOKEN: ${HAVLINE_UPDATER_TOKEN:-}
HAVLINE_UPDATER_TOKEN_FILE: /run/havline-updater/updater.token
# 留空即自动:应用会在数据目录里生成并持久化 <DataDir>/session_secret(0600)
# 想自己指定就设这个变量;注意它同时是凭据加密密钥,已有数据后不要随意更换
HAVLINE_SESSION_SECRET: ${HAVLINE_SESSION_SECRET:-}
# 时区:通知消息时间按此显示(默认东八区)
TZ: ${TZ:-Asia/Shanghai}
# 受限升级 sidecar:只有它持有 Docker Socket,主程序通过共享 Unix Socket 触发
updater:
build:
context: .
target: updater
args:
GO_IMAGE: ${GO_IMAGE:-docker.m.daocloud.io/library/golang:1.23-bookworm}
UPDATER_IMAGE: ${UPDATER_IMAGE:-docker.m.daocloud.io/library/docker:27-cli}
GOPROXY: ${GOPROXY:-https://goproxy.cn,direct}
image: havline-updater:${HAVLINE_VERSION:-local}
pull_policy: build
container_name: havline-updater
restart: unless-stopped
volumes:
- ${DOCKER_SOCK:-/var/run/docker.sock}:/var/run/docker.sock
- ${HAVLINE_UPDATE_HOST_DIR:-.}:/workspace
- havline-updater-sock:/run/havline-updater
environment:
HAVLINE_UPDATER_SOCKET: /run/havline-updater/updater.sock
HAVLINE_UPDATER_TOKEN: ${HAVLINE_UPDATER_TOKEN:-}
HAVLINE_UPDATER_TOKEN_FILE: /run/havline-updater/updater.token
HAVLINE_UPDATE_PROJECT_DIR: /workspace
HAVLINE_UPDATE_COMPOSE_FILE: docker-compose.yml
HAVLINE_UPDATE_SERVICE: havline
HAVLINE_UPDATE_MODE: local
HAVLINE_UPDATE_APP_URL: http://havline:6893
HAVLINE_UPDATE_HOST_DIR: ${HAVLINE_UPDATE_HOST_DIR:-}
HAVLINE_UPDATE_PROJECT_NAME: ${HAVLINE_UPDATE_PROJECT_NAME:-havline}
HAVLINE_UPDATE_SELF_IMAGE: havline-updater:${HAVLINE_VERSION:-local}
HAVLINE_UPDATE_DOCKER_SOCK: ${DOCKER_SOCK:-/var/run/docker.sock}
TZ: ${TZ:-Asia/Shanghai}
volumes:
havline-data:
havline-updater-sock:
+52
View File
@@ -0,0 +1,52 @@
module github.com/havline/havline
go 1.23.0
require (
github.com/go-acme/lego/v4 v4.23.1
github.com/gorilla/websocket v1.5.3
github.com/nrdcg/dnspod-go v0.4.0
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.1128
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/dnspod v1.0.1128
github.com/volcengine/volcengine-go-sdk v1.2.53
golang.org/x/crypto v0.36.0
golang.org/x/sys v0.31.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
modernc.org/sqlite v1.34.4
)
require (
github.com/aliyun/alibaba-cloud-sdk-go v1.63.100 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cloudflare/cloudflare-go v0.115.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-jose/go-jose/v4 v4.0.5 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/miekg/dns v1.1.64 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/volcengine/volc-sdk-golang v1.0.199 // indirect
golang.org/x/mod v0.23.0 // indirect
golang.org/x/net v0.37.0 // indirect
golang.org/x/sync v0.12.0 // indirect
golang.org/x/text v0.23.0 // indirect
golang.org/x/time v0.11.0 // indirect
golang.org/x/tools v0.30.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
modernc.org/libc v1.55.3 // indirect
modernc.org/mathutil v1.6.0 // indirect
modernc.org/memory v1.8.0 // indirect
modernc.org/strutil v1.2.0 // indirect
modernc.org/token v1.1.0 // indirect
)
+910
View File
@@ -0,0 +1,910 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU=
cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU=
cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY=
cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc=
cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0=
cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To=
cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4=
cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M=
cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc=
cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk=
cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs=
cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc=
cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY=
cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=
cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE=
cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc=
cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg=
cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc=
cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ=
cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE=
cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk=
cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I=
cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw=
cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA=
cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU=
cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw=
cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos=
cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk=
cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs=
cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
github.com/HdrHistogram/hdrhistogram-go v1.1.0/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo=
github.com/HdrHistogram/hdrhistogram-go v1.1.2/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo=
github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo=
github.com/Shopify/sarama v1.30.1/go.mod h1:hGgx05L/DiW8XYBXeJdKIN6V2QUy2H6JqME5VT1NLRw=
github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI=
github.com/Shopify/toxiproxy/v2 v2.1.6-0.20210914104332-15ea381dcdae/go.mod h1:/cvHQkZ1fst0EmZnA5dFtiQdWCNCFYzb+uE2vqVgvx0=
github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g=
github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c=
github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
github.com/aliyun/alibaba-cloud-sdk-go v1.63.100 h1:yUkCbrSM1cWtgBfRVKMQtdt22KhDvKY7g4V+92eG9wA=
github.com/aliyun/alibaba-cloud-sdk-go v1.63.100/go.mod h1:SOSDHfe1kX91v3W5QiBsWSLqeLxImobbMX1mxrFHsVQ=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
github.com/armon/go-metrics v0.3.9/go.mod h1:4O98XIr/9W0sxpJ8UaYkvjk10Iff7SnFrb4QAOwNTFc=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/avast/retry-go v3.0.0+incompatible/go.mod h1:XtSnn+n/sHqQIpZ10K1qAevBhOOCWBLXXy3hyiqqBrY=
github.com/aws/aws-sdk-go v1.40.45/go.mod h1:585smgzpB/KqRA+K3y/NL/oYRqQvpNJYvLm+LY1U59Q=
github.com/aws/aws-sdk-go-v2 v1.9.1/go.mod h1:cK/D0BBs0b/oWPIcX/Z/obahJK1TT7IPVjy53i/mX/4=
github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.8.1/go.mod h1:CM+19rL1+4dFWnOQKwDc7H1KwXTz+h61oUSHyhV0b3o=
github.com/aws/smithy-go v1.8.0/go.mod h1:SObp3lf9smib00L/v3U2eAKG8FyQ7iLrJnQiAmR5n+E=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
github.com/casbin/casbin/v2 v2.37.0/go.mod h1:vByNa/Fchek0KZUgG5wEsl7iFsiviAYKRtgrQfcJqHg=
github.com/cenkalti/backoff/v4 v4.1.1/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw=
github.com/cenkalti/backoff/v4 v4.1.2/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6Dob7S7YxXgwXpfOuvO54S+tGdZdw9fuRZt25Ag=
github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp5jckzBHf4XRpQvBOLI+I=
github.com/clbanning/mxj v1.8.4/go.mod h1:BVjHeAH+rl9rs6f+QIpeRl0tfu10SXn1pUSa5PVGJng=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cloudflare/cloudflare-go v0.115.0 h1:84/dxeeXweCc0PN5Cto44iTA8AkG1fyT11yPO5ZB7sM=
github.com/cloudflare/cloudflare-go v0.115.0/go.mod h1:Ds6urDwn/TF2uIU24mu7H91xkKP8gSAHxQ44DSZgVmU=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs=
github.com/eapache/go-resiliency v1.2.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs=
github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU=
github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I=
github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
github.com/fatih/color v1.12.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM=
github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k=
github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g=
github.com/franela/goblin v0.0.0-20210519012713-85d372ac71e2/go.mod h1:VzmDKDJVZI3aJmnRI9VjAn9nJ8qPPsN1fqzr9dqInIo=
github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20=
github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM0I9ntUbOk+k=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-acme/lego/v4 v4.23.1 h1:lZ5fGtGESA2L9FB8dNTvrQUq3/X4QOb8ExkKyY7LSV4=
github.com/go-acme/lego/v4 v4.23.1/go.mod h1:7UMVR7oQbIYw6V7mTgGwi4Er7B6Ww0c+c8feiBM0EgI=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-jose/go-jose/v4 v4.0.5 h1:M6T8+mKZl/+fNNuFHvGIzDz7BTLQPIounk/b9dw3AaE=
github.com/go-jose/go-jose/v4 v4.0.5/go.mod h1:s3P1lRrkT8igV8D9OjyL4WRyHvjB6a4JSllnOrmmBOA=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-kit/kit v0.12.0/go.mod h1:lHd+EkCZPIwYItmGDDRdhinkzX2A1sj+M9biaEaizzs=
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
github.com/go-kit/log v0.2.0/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
github.com/go-zookeeper/zk v1.0.2/go.mod h1:nOB03cncLtlp4t+UAkGSV+9beXP/akpekBwL+UX1Qcw=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A=
github.com/golang-jwt/jwt/v4 v4.0.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
github.com/hashicorp/consul/api v1.10.1/go.mod h1:XjsvQN+RJGWI2TWy1/kqaE16HrR2J/FWgkYjdZQsX9M=
github.com/hashicorp/consul/sdk v0.8.0/go.mod h1:GBvyrGALthsZObzUGsfgHZQDXjg4lOjagTIwIR1vPms=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=
github.com/hashicorp/go-hclog v0.12.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ=
github.com/hashicorp/go-hclog v0.16.2/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ=
github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA=
github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs=
github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8=
github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU=
github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4=
github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=
github.com/hashicorp/mdns v1.0.1/go.mod h1:4gW7WsVCke5TE7EPeYliwHlRUyBtfCwuFwuMg2DmyNY=
github.com/hashicorp/memberlist v0.2.2/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE=
github.com/hashicorp/serf v0.9.5/go.mod h1:UWDWwZeL5cuWDJdl0C6wrvrUwEqtQ4ZKBKKENpqIUyk=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/hudl/fargo v1.4.0/go.mod h1:9Ai6uvFy5fQNq6VPKtg+Ceq1+eTY4nKUlR2JElEOcDo=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/influxdata/influxdb1-client v0.0.0-20200827194710-b269163b24ab/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo=
github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs=
github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM=
github.com/jcmturner/gofork v1.0.0/go.mod h1:MK8+TM0La+2rjBD4jE12Kj1pCCxK7d2LK/UM3ncEo0o=
github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg=
github.com/jcmturner/gokrb5/v8 v8.4.2/go.mod h1:sb+Xq/fTY5yktf/VxLsE3wlfPqQjp0aWNYyvBVK62bc=
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8=
github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.13.4/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg=
github.com/klauspost/compress v1.13.5/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso=
github.com/miekg/dns v1.1.43/go.mod h1:+evo5L0630/F6ca/Z9+GAqzhjGyn8/c+TBaOyfEl0V4=
github.com/miekg/dns v1.1.64 h1:wuZgD9wwCE6XMT05UU/mlSko71eRSXEAm2EbjQXLKnQ=
github.com/miekg/dns v1.1.64/go.mod h1:Dzw9769uoKVaLuODMDZz9M6ynFU6Em65csPuoi8G0ck=
github.com/minio/highwayhash v1.0.1/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY=
github.com/minio/highwayhash v1.0.2/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY=
github.com/mitchellh/cli v1.1.0/go.mod h1:xcISNoH86gajksDmfB23e/pu+B+GeFRMYmoHXxx3xhI=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.4.2/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/nats-io/jwt v1.2.2/go.mod h1:/xX356yQA6LuXI9xWW7mZNpxgF2mBmGecH+Fj34sP5Q=
github.com/nats-io/jwt/v2 v2.0.3/go.mod h1:VRP+deawSXyhNjXmxPCHskrR6Mq50BqpEI5SEcNiGlY=
github.com/nats-io/nats-server/v2 v2.5.0/go.mod h1:Kj86UtrXAL6LwYRA6H4RqzkHhK0Vcv2ZnKD5WbQ1t3g=
github.com/nats-io/nats.go v1.12.1/go.mod h1:BPko4oXsySz4aSWeFgOHLZs3G4Jq4ZAyE6/zMCxRT6w=
github.com/nats-io/nkeys v0.2.0/go.mod h1:XdZpAbhgyyODYqjTawOnIOI7VlbKSarI9Gfy1tqEu/s=
github.com/nats-io/nkeys v0.3.0/go.mod h1:gvUNGjVcM2IPr5rCsRsC6Wb3Hr2CQAm08dsxtV6A5y4=
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/nrdcg/dnspod-go v0.4.0 h1:c/jn1mLZNKF3/osJ6mz3QPxTudvPArXTjpkmYj0uK6U=
github.com/nrdcg/dnspod-go v0.4.0/go.mod h1:vZSoFSFeQVm2gWLMkyX61LZ8HI3BaqtHZWgPTGKr6KQ=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.16.2/go.mod h1:CObGmKUOKaSC0RjmoAK7tKyn4Azo5P2IWuoMnvwxz1E=
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.13.0/go.mod h1:lRk9szgn8TxENtWd0Tp4c3wjlRfMTMH27I+3Je41yGY=
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk=
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b h1:FfH+VrHHk6Lxt9HdVS0PXzSXFyS2NbZKXv33FYPol0A=
github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b/go.mod h1:AC62GU6hc0BrNm+9RK9VSiwa/EUe1bkIeFORAMcHvJU=
github.com/openzipkin/zipkin-go v0.2.5/go.mod h1:KpXfKdgRDnnhsxw4pNIH9Md5lyFqKUa4YDFlwRYAMyE=
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/performancecopilot/speed/v4 v4.0.0/go.mod h1:qxrSyuDGrTOWfV+uKRFhfxw6h/4HXRGUiZiufxo49BM=
github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc=
github.com/pierrec/lz4 v2.6.1+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU=
github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4=
github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo=
github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc=
github.com/prometheus/common v0.30.0/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls=
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A=
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg=
github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
github.com/streadway/amqp v1.0.0/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
github.com/streadway/handy v0.0.0-20200128134331-0f66f006fb2e/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.1128 h1:NGnqDc8FQL0YdiCHgTO4Wkso6ToD8rE3JW9VOzoPBNA=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.1128/go.mod h1:r5r4xbfxSaeR04b166HGsBa/R4U3SueirEUpXGuw+Q0=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/dnspod v1.0.1128 h1:mrJ5Fbkd7sZIJ5F6oRfh5zebPQaudPH9Y0+GUmFytYU=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/dnspod v1.0.1128/go.mod h1:zbsYIBT+VTX4z4ocjTAdLBIWyNYj3z0BRqd0iPdnjsk=
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
github.com/uber/jaeger-client-go v2.30.0+incompatible h1:D6wyKGCecFaSRUpo8lCVbaOOb6ThwMmTEbhRwtKR97o=
github.com/uber/jaeger-client-go v2.30.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk=
github.com/uber/jaeger-lib v2.4.1+incompatible h1:td4jdvLcExb4cBISKIpHuGoVXh+dVKhn2Um6rjCsSsg=
github.com/uber/jaeger-lib v2.4.1+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U=
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
github.com/volcengine/volc-sdk-golang v1.0.23/go.mod h1:AfG/PZRUkHJ9inETvbjNifTDgut25Wbkm2QoYBTbvyU=
github.com/volcengine/volc-sdk-golang v1.0.199 h1:zv9QOqTl/IsLwtfC37GlJtcz6vMAHi+pjq8ILWjLYUc=
github.com/volcengine/volc-sdk-golang v1.0.199/go.mod h1:stZX+EPgv1vF4nZwOlEe8iGcriUPRBKX8zA19gXycOQ=
github.com/volcengine/volcengine-go-sdk v1.2.53 h1:aWooc5D8+Tx+R+Z7VsIp8aJCbWgfGdb687tq8G5b2JI=
github.com/volcengine/volcengine-go-sdk v1.2.53/go.mod h1:DURKPVQ8Rsi4OQu4/NPjUyjla3MeHPgXT/qV+400fAw=
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs=
github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs=
go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g=
go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ=
go.etcd.io/etcd/client/v3 v3.5.0/go.mod h1:AIKXXVX/DQXtfTEqBryiLTUXwON+GuvO6Z7lLS/oTh0=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E=
go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/multierr v1.7.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak=
go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo=
go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200323165209-0ec3e9974c59/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201112155050-0c6587e931a9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20210915214749-c084706c2272/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20210920023735-84f357641f63/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio=
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190125153040-c74c464bbbf2/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek=
golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY=
golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs=
golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.23.0 h1:Zb7khfcRGKk+kqfxFaP5tZqCnDZMjC5VtUBs87Hr6QM=
golang.org/x/mod v0.23.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210917221730-978cfadd31cf/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA=
golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c=
golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190130150945-aca44879d564/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190922100055-0a153f010e69/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210303074136-134d130e1a04/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210917161153-d61c044b1678/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20190907020128-2ca718005c18/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw=
golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw=
golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8=
golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.30.0 h1:BgcpHewrV5AUp2G9MebG4XPFI1E2W41zU1SaqVA9vJY=
golang.org/x/tools v0.30.0/go.mod h1:c347cR/OJfw5TI+GfX7RUPNMdDRRbjvYTS0jPyvsVtY=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo=
gonum.org/v1/gonum v0.8.2/go.mod h1:oe/vMfY3deqTw+1EZJhuvEW2iwGF1bW9wwu7XCu0+v0=
gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw=
gonum.org/v1/plot v0.0.0-20190515093506-e2840ee46a6b/go.mod h1:Wt8AAjI+ypCyYX3nZBvf6cAIx93T+c/OS2HFAYskSZc=
google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M=
google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE=
google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE=
google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM=
google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8=
google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA=
google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA=
google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0=
google.golang.org/genproto v0.0.0-20210917145530-b395a37504d4/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60=
google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk=
google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0=
google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc=
google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU=
google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM=
google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4=
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=
modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s=
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw=
modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU=
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI=
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4=
modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U=
modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w=
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E=
modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU=
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc=
modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss=
modernc.org/sqlite v1.34.4 h1:sjdARozcL5KJBvYQvLlZEmctRgW9xqIZc2ncN7PU0P8=
modernc.org/sqlite v1.34.4/go.mod h1:3QQFCG2SEMtc2nv+Wq4cQCH7Hjcg+p/RMlS1XK+zwbk=
modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc=
+111
View File
@@ -0,0 +1,111 @@
package acme
import (
"fmt"
"strings"
"github.com/go-acme/lego/v4/lego"
)
const (
CALetsEncrypt = "letsencrypt"
CALetsEncryptStaging = "letsencrypt-staging"
CAZeroSSL = "zerossl"
CABuypass = "buypass"
// CALiteSSL 亚数 TrustAsia 的公益免费证书(90 天,支持单域名/通配符/多域名,强制 EAB)
CALiteSSL = "litessl"
)
// caRetired 记录已停止签发的 CA:仍然认识这些值(历史证书记录里可能存着,用于展示与清理),
// 但不允许再用来申请——否则用户只会看到一个难懂的 ACME 报错而不是「这家 CA 不干了」。
var caRetired = map[string]string{
CABuypass: "Buypass 已于 2025-10-15 停止签发证书(ACME 服务 2026-04-15 终止),请改用 Let's Encrypt、LiteSSL 或 ZeroSSL",
}
// CAUnavailableReason 返回该 CA 已停用的原因;可用的 CA 返回空字符串。
func CAUnavailableReason(ca string) string {
return caRetired[NormalizeCA(ca)]
}
const (
zeroSSLDirectoryURL = "https://acme.zerossl.com/v2/DV90"
buypassDirectoryURL = "https://api.buypass.com/acme/directory"
// liteSSLDirectoryURL 实测 2026-09-27 可访问,目录里 meta.externalAccountRequired = true
liteSSLDirectoryURL = "https://acme.litessl.com/acme/v2/directory"
)
func NormalizeCA(ca string) string {
switch ca {
case "", CALetsEncrypt, "production":
return CALetsEncrypt
case CALetsEncryptStaging, "staging", "letsencrypt-test":
return CALetsEncryptStaging
case CAZeroSSL:
return CAZeroSSL
case CABuypass, "buypass-go":
return CABuypass
case CALiteSSL, "trustasia":
return CALiteSSL
default:
return ca
}
}
func DirectoryURL(ca string) (string, error) {
switch NormalizeCA(ca) {
case CALetsEncrypt:
return lego.LEDirectoryProduction, nil
case CALetsEncryptStaging:
return lego.LEDirectoryStaging, nil
case CAZeroSSL:
return zeroSSLDirectoryURL, nil
case CABuypass:
return buypassDirectoryURL, nil
case CALiteSSL:
return liteSSLDirectoryURL, nil
default:
return "", fmt.Errorf("不支持的颁发机构:%s", ca)
}
}
func CALabel(ca string) string {
switch NormalizeCA(ca) {
case CALetsEncrypt:
return "Let's Encrypt"
case CALetsEncryptStaging:
return "Let's Encrypt 测试"
case CAZeroSSL:
return "ZeroSSL"
case CABuypass:
return "Buypass"
case CALiteSSL:
return "LiteSSL"
default:
if ca == "" {
return "手动导入"
}
return ca
}
}
func ValidateCA(ca string) error {
_, err := DirectoryURL(ca)
return err
}
// ValidateCADomains 校验各 CA 自己的限制。
// LiteSSL 官方支持单域名 / 通配符 / 多域名,因此这里不额外限制。
func ValidateCADomains(ca string, domains []string) error {
switch NormalizeCA(ca) {
case CABuypass:
if len(domains) > 5 {
return fmt.Errorf("Buypass 单张证书最多支持 5 个域名")
}
for _, domain := range domains {
if strings.HasPrefix(domain, "*.") {
return fmt.Errorf("Buypass 不支持通配符证书")
}
}
}
return nil
}
+37
View File
@@ -0,0 +1,37 @@
package acme
import "testing"
func TestDirectoryURL(t *testing.T) {
url, err := DirectoryURL(CALetsEncrypt)
if err != nil || url == "" {
t.Fatalf("production: %v", err)
}
url, err = DirectoryURL(CALetsEncryptStaging)
if err != nil || url == "" {
t.Fatalf("staging: %v", err)
}
url, err = DirectoryURL(CAZeroSSL)
if err != nil || url == "" {
t.Fatalf("zerossl: %v", err)
}
url, err = DirectoryURL(CABuypass)
if err != nil || url == "" {
t.Fatalf("buypass: %v", err)
}
if err := ValidateCA("unknown"); err == nil {
t.Fatal("expected error for unknown ca")
}
}
func TestValidateCADomainsBuypass(t *testing.T) {
if err := ValidateCADomains(CABuypass, []string{"*.example.com"}); err == nil {
t.Fatal("expected wildcard error")
}
if err := ValidateCADomains(CABuypass, []string{"a.com", "b.com", "c.com", "d.com", "e.com", "f.com"}); err == nil {
t.Fatal("expected domain limit error")
}
if err := ValidateCADomains(CALetsEncrypt, []string{"*.example.com"}); err != nil {
t.Fatalf("letsencrypt wildcard should be allowed: %v", err)
}
}
+98
View File
@@ -0,0 +1,98 @@
package acme
import (
"fmt"
"strings"
"github.com/go-acme/lego/v4/challenge"
"github.com/go-acme/lego/v4/providers/dns/alidns"
"github.com/go-acme/lego/v4/providers/dns/cloudflare"
"github.com/go-acme/lego/v4/providers/dns/dnspod"
"github.com/go-acme/lego/v4/providers/dns/tencentcloud"
"github.com/havline/havline/internal/ddns"
)
func newDNS01Provider(provider string, cred ddns.Credentials) (challenge.Provider, error) {
switch provider {
case "dnspod":
cfg := dnspod.NewDefaultConfig()
cfg.LoginToken = cred.LoginToken()
return dnspod.NewDNSProviderConfig(cfg)
case "alidns":
cfg := alidns.NewDefaultConfig()
cfg.APIKey = cred.Token
cfg.SecretKey = cred.Secret
return alidns.NewDNSProviderConfig(cfg)
case "tencentcloud":
cfg := tencentcloud.NewDefaultConfig()
cfg.SecretID = cred.Token
cfg.SecretKey = cred.Secret
return tencentcloud.NewDNSProviderConfig(cfg)
case "volcengine":
return newVolcengineDNSProvider(cred)
default:
cfg := cloudflare.NewDefaultConfig()
cfg.AuthToken = cred.Token
return cloudflare.NewDNSProviderConfig(cfg)
}
}
func dnsProviderName(provider string) string {
switch provider {
case "dnspod", "alidns", "tencentcloud", "volcengine":
return provider
default:
return "cloudflare"
}
}
type loggingDNSProvider struct {
inner challenge.Provider
job *Job
}
func wrapDNSProvider(inner challenge.Provider, job *Job) challenge.Provider {
if job == nil {
return inner
}
return &loggingDNSProvider{inner: inner, job: job}
}
func (p *loggingDNSProvider) Present(domain, token, keyAuth string) error {
record := strings.TrimSuffix(domain, ".")
p.job.Info(fmt.Sprintf("添加 DNS TXT 记录: _acme-challenge.%s", record))
if err := p.inner.Present(domain, token, keyAuth); err != nil {
p.job.Error(fmt.Sprintf("添加 DNS TXT 记录失败: %v", err))
return err
}
p.job.Info("DNS TXT 记录已添加,等待 DNS 传播…")
return nil
}
func (p *loggingDNSProvider) CleanUp(domain, token, keyAuth string) error {
p.job.Info("清理 DNS TXT 验证记录…")
return p.inner.CleanUp(domain, token, keyAuth)
}
func validateDNSCredentials(provider string, cred ddns.Credentials) error {
if err := cred.Validate(dnsProviderName(provider)); err != nil {
return err
}
if provider == "dnspod" && cred.TokenID == "" {
return fmt.Errorf("请先在 DDNS 页面配置 DNSPod ID 和 Token")
}
if provider == "alidns" && cred.Secret == "" {
return fmt.Errorf("请先在 DDNS 页面配置阿里云 AccessKey")
}
if provider == "tencentcloud" && cred.Secret == "" {
return fmt.Errorf("请先在 DDNS 页面配置腾讯云 SecretKey")
}
if provider == "volcengine" && cred.Secret == "" {
return fmt.Errorf("请先在 DDNS 页面配置火山引擎 Secret Access Key")
}
if provider != "dnspod" && provider != "alidns" && provider != "tencentcloud" && provider != "volcengine" && cred.Token == "" {
return fmt.Errorf("请先在 DDNS 页面配置 Cloudflare API Token")
}
return nil
}
+23
View File
@@ -0,0 +1,23 @@
package acme
import (
"testing"
"github.com/havline/havline/internal/ddns"
)
func TestValidateDNSCredentialsVolcengine(t *testing.T) {
if err := validateDNSCredentials("volcengine", ddns.Credentials{Token: "ak", Secret: "sk"}); err != nil {
t.Fatalf("expected volcengine credentials to pass: %v", err)
}
}
func TestNewVolcengineDNSProvider(t *testing.T) {
p, err := newVolcengineDNSProvider(ddns.Credentials{Token: "ak", Secret: "sk"})
if err != nil {
t.Fatal(err)
}
if p == nil {
t.Fatal("expected provider")
}
}
+166
View File
@@ -0,0 +1,166 @@
package acme
import (
"encoding/json"
"fmt"
"strings"
"github.com/havline/havline/internal/validate"
)
func NormalizeCertDomains(raw []string) ([]string, error) {
if len(raw) == 0 {
return nil, fmt.Errorf("请填写至少一个域名")
}
if len(raw) > 100 {
return nil, fmt.Errorf("域名数量不能超过 100 个")
}
seen := map[string]bool{}
out := make([]string, 0, len(raw))
for _, item := range raw {
for _, part := range splitDomainInput(item) {
domain, err := normalizeCertDomain(part)
if err != nil {
return nil, err
}
if seen[domain] {
continue
}
seen[domain] = true
out = append(out, domain)
}
}
if len(out) == 0 {
return nil, fmt.Errorf("请填写至少一个域名")
}
return out, nil
}
func splitDomainInput(input string) []string {
input = strings.ReplaceAll(input, "\r\n", "\n")
input = strings.ReplaceAll(input, ",", "\n")
parts := strings.Split(input, "\n")
out := make([]string, 0, len(parts))
for _, part := range parts {
part = strings.TrimSpace(part)
if part != "" {
out = append(out, part)
}
}
return out
}
func normalizeCertDomain(domain string) (string, error) {
domain = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(domain)), ".")
if domain == "" {
return "", fmt.Errorf("域名不能为空")
}
wildcard := strings.HasPrefix(domain, "*.")
base := strings.TrimPrefix(domain, "*.")
if err := validate.Domain(base); err != nil {
return "", err
}
if wildcard {
return "*." + base, nil
}
return base, nil
}
func DomainsUnderZone(domains []string, zone string) error {
return DomainsUnderZones(domains, []string{zone})
}
func DomainsUnderZones(domains []string, zones []string) error {
normalized := normalizeManagedZones(zones)
if len(normalized) == 0 {
return fmt.Errorf("请选择 DNS 凭证")
}
for _, domain := range domains {
base := strings.TrimPrefix(domain, "*.")
if !domainUnderAnyZone(base, normalized) {
return fmt.Errorf("域名 %s 不在所选 DNS 凭证的管理范围内(%s)", domain, strings.Join(normalized, "、"))
}
}
return nil
}
func normalizeManagedZones(zones []string) []string {
seen := map[string]bool{}
out := make([]string, 0, len(zones))
for _, zone := range zones {
zone = strings.ToLower(strings.TrimSpace(strings.TrimPrefix(zone, "*.")))
if zone == "" || seen[zone] {
continue
}
seen[zone] = true
out = append(out, zone)
}
return out
}
func domainUnderAnyZone(domain string, zones []string) bool {
for _, zone := range zones {
if domain == zone || strings.HasSuffix(domain, "."+zone) {
return true
}
}
return false
}
func PrimaryCertDomain(domains []string) string {
for _, domain := range domains {
if !strings.HasPrefix(domain, "*.") {
return domain
}
}
if len(domains) > 0 {
return strings.TrimPrefix(domains[0], "*.")
}
return ""
}
func HasWildcardDomain(domains []string) bool {
for _, domain := range domains {
if strings.HasPrefix(domain, "*.") {
return true
}
}
return false
}
func LegacyCertDomains(domain string, wildcard bool) []string {
domain = strings.ToLower(strings.TrimSpace(domain))
if domain == "" {
return nil
}
if wildcard {
return []string{domain, "*." + domain}
}
return []string{domain}
}
func EncodeCertDomains(domains []string) string {
if len(domains) == 0 {
return ""
}
b, err := json.Marshal(domains)
if err != nil {
return ""
}
return string(b)
}
func DecodeCertDomains(raw string, domain string, wildcard bool) []string {
raw = strings.TrimSpace(raw)
if raw != "" {
var domains []string
if err := json.Unmarshal([]byte(raw), &domains); err == nil && len(domains) > 0 {
normalized, err := NormalizeCertDomains(domains)
if err == nil {
return normalized
}
}
}
return LegacyCertDomains(domain, wildcard)
}
+43
View File
@@ -0,0 +1,43 @@
package acme
import "testing"
func TestNormalizeCertDomains(t *testing.T) {
domains, err := NormalizeCertDomains([]string{"example.com", "*.example.com", "nas.example.com"})
if err != nil {
t.Fatal(err)
}
if len(domains) != 3 {
t.Fatalf("expected 3 domains, got %d", len(domains))
}
if domains[1] != "*.example.com" {
t.Fatalf("unexpected wildcard: %s", domains[1])
}
}
func TestDomainsUnderZone(t *testing.T) {
domains := []string{"example.com", "*.example.com", "nas.example.com"}
if err := DomainsUnderZone(domains, "example.com"); err != nil {
t.Fatal(err)
}
if err := DomainsUnderZone([]string{"other.com"}, "example.com"); err == nil {
t.Fatal("expected zone mismatch error")
}
}
func TestDomainsUnderZonesMultiRoot(t *testing.T) {
zones := []string{"roven.cc", "chiak.cc"}
if err := DomainsUnderZones([]string{"chiak.cc", "*.chiak.cc"}, zones); err != nil {
t.Fatal(err)
}
if err := DomainsUnderZones([]string{"other.com"}, zones); err == nil {
t.Fatal("expected zone mismatch error")
}
}
func TestDecodeCertDomainsLegacy(t *testing.T) {
got := DecodeCertDomains("", "example.com", true)
if len(got) != 2 || got[1] != "*.example.com" {
t.Fatalf("unexpected legacy domains: %v", got)
}
}
+117
View File
@@ -0,0 +1,117 @@
package acme
import (
"archive/zip"
"bytes"
"context"
"fmt"
"os"
"path/filepath"
"strings"
certstore "github.com/havline/havline/internal/certificate"
)
type DownloadPart string
const (
DownloadZIP DownloadPart = "zip"
DownloadCert DownloadPart = "cert"
DownloadKey DownloadPart = "key"
)
func (s *Service) Download(ctx context.Context, domain string, part string) (filename string, contentType string, data []byte, err error) {
domain = strings.ToLower(strings.TrimSpace(domain))
if domain == "" {
return "", "", nil, fmt.Errorf("域名不能为空")
}
rec, err := s.store.GetByDomain(ctx, domain)
if err != nil {
return "", "", nil, err
}
if rec.CertPath == "" || rec.KeyPath == "" {
return "", "", nil, fmt.Errorf("证书文件不存在,可能尚未申请成功")
}
if err := validateCertFilePath(s.cfg.CertsDir(), rec.CertPath); err != nil {
return "", "", nil, err
}
if err := validateCertFilePath(s.cfg.CertsDir(), rec.KeyPath); err != nil {
return "", "", nil, err
}
certPEM, err := os.ReadFile(rec.CertPath)
if err != nil {
return "", "", nil, fmt.Errorf("读取证书失败")
}
keyPEM, err := os.ReadFile(rec.KeyPath)
if err != nil {
return "", "", nil, fmt.Errorf("读取私钥失败")
}
base := downloadBaseName(rec)
switch DownloadPart(strings.ToLower(strings.TrimSpace(part))) {
case "", DownloadZIP:
data, err = zipCertBundle(base, certPEM, keyPEM)
if err != nil {
return "", "", nil, err
}
return base + ".zip", "application/zip", data, nil
case DownloadCert:
return base + "-fullchain.pem", "application/x-pem-file", certPEM, nil
case DownloadKey:
return base + "-privatekey.pem", "application/x-pem-file", keyPEM, nil
default:
return "", "", nil, fmt.Errorf("不支持的下载类型")
}
}
func downloadBaseName(rec certstore.Record) string {
name := strings.TrimPrefix(rec.Domain, "*.")
name = strings.ReplaceAll(name, "*", "wildcard")
name = strings.ReplaceAll(name, "/", "_")
if name == "" {
name = "certificate"
}
return name
}
func validateCertFilePath(certsDir, path string) error {
absCerts, err := filepath.Abs(certsDir)
if err != nil {
return fmt.Errorf("证书目录无效")
}
absPath, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("证书路径无效")
}
rel, err := filepath.Rel(absCerts, absPath)
if err != nil || strings.HasPrefix(rel, "..") {
return fmt.Errorf("证书路径无效")
}
return nil
}
func zipCertBundle(base string, certPEM, keyPEM []byte) ([]byte, error) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
if err := writeZipEntry(zw, "fullchain.pem", certPEM); err != nil {
return nil, err
}
if err := writeZipEntry(zw, "privatekey.pem", keyPEM); err != nil {
return nil, err
}
if err := zw.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func writeZipEntry(zw *zip.Writer, name string, data []byte) error {
w, err := zw.Create(name)
if err != nil {
return err
}
_, err = w.Write(data)
return err
}
+26
View File
@@ -0,0 +1,26 @@
package acme
import (
"path/filepath"
"testing"
)
func TestValidateCertFilePath(t *testing.T) {
certsDir := filepath.Clean("/data/certs")
if err := validateCertFilePath(certsDir, "/data/certs/example.com/fullchain.pem"); err != nil {
t.Fatalf("expected valid path: %v", err)
}
if err := validateCertFilePath(certsDir, "/etc/passwd"); err == nil {
t.Fatal("expected invalid path")
}
}
func TestZipCertBundle(t *testing.T) {
data, err := zipCertBundle("example.com", []byte("cert"), []byte("key"))
if err != nil {
t.Fatal(err)
}
if len(data) == 0 {
t.Fatal("empty zip")
}
}
+183
View File
@@ -0,0 +1,183 @@
package acme
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"path/filepath"
"sync"
"time"
certstore "github.com/havline/havline/internal/certificate"
)
type JobEvent struct {
Type string `json:"type"`
Level string `json:"level,omitempty"`
Message string `json:"message,omitempty"`
Result *JobDonePayload `json:"result,omitempty"`
}
type JobDonePayload struct {
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
Domain string `json:"domain,omitempty"`
CertPath string `json:"cert_path,omitempty"`
KeyPath string `json:"key_path,omitempty"`
CertDir string `json:"cert_dir,omitempty"`
ExpiresAt string `json:"expires_at,omitempty"`
}
type Job struct {
id string
mu sync.Mutex
events []JobEvent
done bool
waiters map[chan JobEvent]struct{}
}
type JobManager struct {
mu sync.Mutex
jobs map[string]*Job
}
func NewJobManager() *JobManager {
return &JobManager{jobs: map[string]*Job{}}
}
func (m *JobManager) Create() *Job {
job := &Job{
id: fmt.Sprintf("%d", time.Now().UnixNano()),
waiters: map[chan JobEvent]struct{}{},
}
m.mu.Lock()
m.jobs[job.id] = job
m.mu.Unlock()
return job
}
func (m *JobManager) Get(id string) *Job {
m.mu.Lock()
job := m.jobs[id]
m.mu.Unlock()
return job
}
func (j *Job) ID() string {
return j.id
}
func (j *Job) Append(level, message string) {
j.emit(JobEvent{Type: "log", Level: level, Message: message})
}
func (j *Job) Info(message string) { j.Append("info", message) }
func (j *Job) Warn(message string) { j.Append("warn", message) }
func (j *Job) Error(message string) { j.Append("error", message) }
func (j *Job) Finish(result JobDonePayload) {
j.emit(JobEvent{Type: "done", Result: &result})
}
func (j *Job) emit(ev JobEvent) {
j.mu.Lock()
j.events = append(j.events, ev)
if ev.Type == "done" {
j.done = true
}
for ch := range j.waiters {
ch <- ev
}
j.mu.Unlock()
}
func (j *Job) Snapshot() []JobEvent {
j.mu.Lock()
out := append([]JobEvent(nil), j.events...)
j.mu.Unlock()
return out
}
func (j *Job) Subscribe() chan JobEvent {
ch := make(chan JobEvent, 32)
j.mu.Lock()
j.waiters[ch] = struct{}{}
j.mu.Unlock()
return ch
}
func (j *Job) Unsubscribe(ch chan JobEvent) {
j.mu.Lock()
delete(j.waiters, ch)
j.mu.Unlock()
close(ch)
}
func (m *JobManager) Stream(ctx context.Context, w http.ResponseWriter, id string, flush func() error) error {
job := m.Get(id)
if job == nil {
return fmt.Errorf("任务不存在或已过期")
}
ch := job.Subscribe()
defer job.Unsubscribe(ch)
for _, ev := range job.Snapshot() {
if err := writeJobSSE(w, ev); err != nil {
return err
}
if err := flush(); err != nil {
return err
}
if ev.Type == "done" {
return nil
}
}
for {
select {
case <-ctx.Done():
return ctx.Err()
case ev := <-ch:
if err := writeJobSSE(w, ev); err != nil {
return err
}
if err := flush(); err != nil {
return err
}
if ev.Type == "done" {
return nil
}
}
}
}
func writeJobSSE(w io.Writer, ev JobEvent) error {
data, err := json.Marshal(ev)
if err != nil {
return err
}
_, err = fmt.Fprintf(w, "event: %s\ndata: %s\n\n", ev.Type, data)
return err
}
func jobDoneFromRecord(rec certstore.Record, err error) JobDonePayload {
if err != nil {
return JobDonePayload{OK: false, Error: err.Error()}
}
payload := JobDonePayload{
OK: true,
Domain: rec.Domain,
CertPath: rec.CertPath,
KeyPath: rec.KeyPath,
}
if rec.CertPath != "" {
payload.CertDir = filepath.Dir(rec.CertPath)
}
if rec.ExpiresAt != nil {
payload.ExpiresAt = rec.ExpiresAt.UTC().Format(time.RFC3339)
}
return payload
}
+50
View File
@@ -0,0 +1,50 @@
package acme
import (
"strings"
"testing"
)
// LiteSSL 接替 Buypass 的位置:目录地址实测可用,且强制 EAB。
func TestLiteSSLDirectoryAndLabel(t *testing.T) {
url, err := DirectoryURL(CALiteSSL)
if err != nil {
t.Fatalf("LiteSSL 目录地址解析失败:%v", err)
}
if url != "https://acme.litessl.com/acme/v2/directory" {
t.Fatalf("LiteSSL 目录地址不对:%q", url)
}
if label := CALabel(CALiteSSL); label != "LiteSSL" {
t.Fatalf("LiteSSL 展示名不对:%q", label)
}
// 别名与归一化
if got := NormalizeCA("trustasia"); got != CALiteSSL {
t.Fatalf("别名 trustasia 应归一化为 %s,实际 %q", CALiteSSL, got)
}
if reason := CAUnavailableReason(CALiteSSL); reason != "" {
t.Fatalf("LiteSSL 是可用的 CA,不该有停用原因:%q", reason)
}
}
// LiteSSL 支持通配符与多域名,因此 ValidateCADomains 不应拦它。
func TestValidateCADomainsLiteSSLAllowsWildcard(t *testing.T) {
domains := []string{"*.36800.cc", "a.com", "b.com", "c.com", "d.com", "e.com", "f.com"}
if err := ValidateCADomains(CALiteSSL, domains); err != nil {
t.Fatalf("LiteSSL 应允许通配符与多域名:%v", err)
}
}
// Buypass 保留在停用表里(历史记录要能展示),但提示里应给出可用的替代。
func TestBuypassIsRetiredWithAlternatives(t *testing.T) {
reason := CAUnavailableReason(CABuypass)
if reason == "" {
t.Fatal("Buypass 应仍被标记为已停用")
}
if !strings.Contains(reason, "LiteSSL") {
t.Fatalf("停用提示里应包含 LiteSSL 这个替代项:%q", reason)
}
// 旧记录仍能正常取到目录地址(不报「不支持的颁发机构」)
if _, err := DirectoryURL(CABuypass); err != nil {
t.Fatalf("历史 Buypass 记录的目录地址仍应可解析:%v", err)
}
}
+46
View File
@@ -0,0 +1,46 @@
package acme
import "testing"
func TestParseResolverList(t *testing.T) {
cases := []struct {
name string
raw string
want []string
}{
{"带端口", "223.5.5.5:53, 1.1.1.1:53", []string{"223.5.5.5:53", "1.1.1.1:53"}},
{"缺端口补 53", "8.8.8.8\n9.9.9.9", []string{"8.8.8.8:53", "9.9.9.9:53"}},
{"分号与空格", "223.5.5.5;8.8.4.4 1.0.0.1", []string{"223.5.5.5:53", "8.8.4.4:53", "1.0.0.1:53"}},
{"空值", " ", nil},
{"只留空白项", " , ; \n", nil},
}
for _, item := range cases {
got := parseResolverList(item.raw)
if len(got) != len(item.want) {
t.Fatalf("%s: 期望 %v,实际 %v", item.name, item.want, got)
}
for i := range got {
if got[i] != item.want[i] {
t.Fatalf("%s: 期望 %v,实际 %v", item.name, item.want, got)
}
}
}
}
func TestParseResolverListCapsEntries(t *testing.T) {
raw := "1.1.1.1,1.1.1.2,1.1.1.3,1.1.1.4,1.1.1.5,1.1.1.6,1.1.1.7,1.1.1.8,1.1.1.9,1.1.1.10"
if got := parseResolverList(raw); len(got) != 8 {
t.Fatalf("最多取前 8 条,实际 %d:%v", len(got), got)
}
}
// 内置的默认值必须是 lego 能直接用的 host:port 形式
func TestDefaultResolversAreUsable(t *testing.T) {
got := parseResolverList(defaultACMEDNSResolvers)
if len(got) == 0 {
t.Fatalf("默认解析器解析为空:%q", defaultACMEDNSResolvers)
}
if got[0] != "223.5.5.5:53" {
t.Fatalf("默认解析器首项应带端口,实际 %q", got[0])
}
}
+701
View File
@@ -0,0 +1,701 @@
package acme
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"log/slog"
"net/http"
"net/mail"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/go-acme/lego/v4/certcrypto"
legocert "github.com/go-acme/lego/v4/certificate"
"github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/lego"
"github.com/go-acme/lego/v4/registration"
certstore "github.com/havline/havline/internal/certificate"
"github.com/havline/havline/internal/config"
"github.com/havline/havline/internal/ddns"
"github.com/havline/havline/internal/notify"
"github.com/havline/havline/internal/service"
"github.com/havline/havline/internal/settings"
)
type Service struct {
cfg config.Config
store *certstore.Store
ddnsSvc *ddns.Service
settings *settings.Store
proxySvc *service.ProxyService
logger *slog.Logger
notify *notify.Service
jobs *JobManager
expiryAlertMu sync.Mutex
expiryAlerted map[string]string
}
func NewService(cfg config.Config, store *certstore.Store, ddnsSvc *ddns.Service, settings *settings.Store, proxySvc *service.ProxyService, logger *slog.Logger, notifySvc *notify.Service) *Service {
return &Service{
cfg: cfg,
store: store,
ddnsSvc: ddnsSvc,
settings: settings,
proxySvc: proxySvc,
logger: logger.With("module", "ACME"),
notify: notifySvc,
jobs: NewJobManager(),
expiryAlerted: map[string]string{},
}
}
func (s *Service) List(ctx context.Context) ([]certstore.Record, error) {
return s.store.List(ctx)
}
func (s *Service) StartApply(ctx context.Context, domains []string, ca, email string, ddnsConfigID int64) (string, error) {
if ddnsConfigID <= 0 {
return "", fmt.Errorf("请选择 DNS 任务")
}
domains, ca, email, primary, dnsZone, provider, cred, err := s.prepareApplyWithConfig(ctx, domains, ca, email, ddnsConfigID)
if err != nil {
return "", err
}
job := s.jobs.Create()
go s.runApplyJob(job, dnsZone, domains, ca, email, primary, provider, cred)
return job.ID(), nil
}
func (s *Service) StreamJob(ctx context.Context, w http.ResponseWriter, jobID string, flush func() error) error {
return s.jobs.Stream(ctx, w, jobID, flush)
}
func (s *Service) prepareApplyWithConfig(ctx context.Context, domains []string, ca, email string, ddnsConfigID int64) ([]string, string, string, string, string, string, ddns.Credentials, error) {
domains, err := NormalizeCertDomains(domains)
if err != nil {
return nil, "", "", "", "", "", ddns.Credentials{}, err
}
primary := PrimaryCertDomain(domains)
if primary == "" {
return nil, "", "", "", "", "", ddns.Credentials{}, fmt.Errorf("请填写至少一个域名")
}
email, err = s.resolveACMEEmail(ctx, email)
if err != nil {
return nil, "", "", "", "", "", ddns.Credentials{}, err
}
ca, err = s.resolveCA(ctx, ca)
if err != nil {
return nil, "", "", "", "", "", ddns.Credentials{}, err
}
if err := ValidateCADomains(ca, domains); err != nil {
return nil, "", "", "", "", "", ddns.Credentials{}, err
}
cfg, provider, cred, err := s.ddnsSvc.CredentialsForConfigID(ctx, ddnsConfigID)
if err != nil {
return nil, "", "", "", "", "", ddns.Credentials{}, err
}
if err := validateDNSCredentials(provider, cred); err != nil {
return nil, "", "", "", "", "", ddns.Credentials{}, err
}
dnsZone := cfg.RootDomain
zones := cfg.ManagedDNSZones()
if len(zones) > 0 {
dnsZone = zones[0]
}
return domains, ca, email, primary, dnsZone, provider, cred, nil
}
func (s *Service) prepareApplyByZone(ctx context.Context, dnsZone string, domains []string, ca, email string) ([]string, string, string, string, string, string, ddns.Credentials, error) {
domains, err := NormalizeCertDomains(domains)
if err != nil {
return nil, "", "", "", "", "", ddns.Credentials{}, err
}
dnsZone = strings.ToLower(strings.TrimSpace(dnsZone))
ddnsCfg, err := s.ddnsSvc.ConfigForDNSZone(ctx, dnsZone)
if err != nil {
return nil, "", "", "", "", "", ddns.Credentials{}, err
}
if err := DomainsUnderZones(domains, ddnsCfg.ManagedDNSZones()); err != nil {
return nil, "", "", "", "", "", ddns.Credentials{}, err
}
primary := PrimaryCertDomain(domains)
if primary == "" {
return nil, "", "", "", "", "", ddns.Credentials{}, fmt.Errorf("请填写至少一个域名")
}
email, err = s.resolveACMEEmail(ctx, email)
if err != nil {
return nil, "", "", "", "", "", ddns.Credentials{}, err
}
ca, err = s.resolveCA(ctx, ca)
if err != nil {
return nil, "", "", "", "", "", ddns.Credentials{}, err
}
if err := ValidateCADomains(ca, domains); err != nil {
return nil, "", "", "", "", "", ddns.Credentials{}, err
}
provider, cred, err := s.dnsCredentialsForDomain(ctx, dnsZone)
if err != nil {
return nil, "", "", "", "", "", ddns.Credentials{}, err
}
return domains, ca, email, primary, dnsZone, provider, cred, nil
}
func (s *Service) runApplyJob(job *Job, dnsZone string, domains []string, ca, email, primary, provider string, cred ddns.Credentials) {
ctx := context.Background()
job.Info("开始申请证书…")
job.Info(fmt.Sprintf("主域名: %s", primary))
job.Info(fmt.Sprintf("覆盖域名: %s", strings.Join(domains, ", ")))
job.Info(fmt.Sprintf("DNS 凭证: %s (%s)", dnsZone, provider))
rec, err := s.obtain(ctx, job, ca, email, provider, cred, primary, domains)
if err != nil {
s.markCertError(ctx, primary, domains, ca, err)
job.Error(err.Error())
job.Finish(JobDonePayload{OK: false, Error: err.Error(), Domain: primary})
return
}
if err := s.settings.Set(ctx, settings.KeyACMECA, ca); err != nil {
job.Warn("保存 ACME 颁发机构设置失败: " + err.Error())
}
if err := s.proxySvc.ReloadAll(ctx); err != nil {
job.Warn("Nginx 重载失败: " + err.Error())
} else {
job.Info("Nginx 已重载")
}
job.Info("证书申请完成")
job.Finish(jobDoneFromRecord(rec, nil))
}
func (s *Service) Apply(ctx context.Context, dnsZone string, domains []string, ca, email string) ([]certstore.Record, error) {
domains, ca, email, primary, _, provider, cred, err := s.prepareApplyByZone(ctx, dnsZone, domains, ca, email)
if err != nil {
return nil, err
}
rec, err := s.obtain(ctx, nil, ca, email, provider, cred, primary, domains)
if err != nil {
s.markCertError(ctx, primary, domains, ca, err)
return nil, err
}
if err := s.settings.Set(ctx, settings.KeyACMECA, ca); err != nil {
s.logger.Warn("save acme ca setting failed", "error", err.Error())
}
if err := s.proxySvc.ReloadAll(ctx); err != nil {
s.logger.Error("nginx reload after cert apply failed", "error", err.Error())
}
_ = rec
return s.store.List(ctx)
}
func (s *Service) Import(ctx context.Context, certPEM, keyPEM, certFile, keyFile string) (certstore.Record, error) {
certBytes, err := certstore.ResolvePEMSource(certPEM, certFile)
if err != nil {
return certstore.Record{}, fmt.Errorf("证书:%w", err)
}
keyBytes, err := certstore.ResolvePEMSource(keyPEM, keyFile)
if err != nil {
return certstore.Record{}, fmt.Errorf("私钥:%w", err)
}
info, err := certstore.InspectImport(certBytes, keyBytes)
if err != nil {
return certstore.Record{}, err
}
certPath, keyPath, err := writeCertFiles(s.cfg.CertsDir(), info.Domains, certBytes, keyBytes)
if err != nil {
return certstore.Record{}, err
}
status := "ok"
if time.Now().After(info.ExpiresAt) {
status = "expired"
}
domainsJSON := EncodeCertDomains(info.Domains)
record, err := s.store.Upsert(ctx, info.Primary, info.Wildcard, domainsJSON, "imported", certPath, keyPath, info.ExpiresAt, status, "")
if err != nil {
return certstore.Record{}, err
}
if err := s.proxySvc.ReloadAll(ctx); err != nil {
s.logger.Warn("nginx reload after cert import failed", "error", err.Error())
}
s.logger.Info("certificate imported", "domain", info.Primary, "domains", info.Domains, "expires_at", info.ExpiresAt.Format(time.RFC3339))
return record, nil
}
func (s *Service) Delete(ctx context.Context, domain string) error {
domain = strings.ToLower(strings.TrimSpace(domain))
if domain == "" {
return fmt.Errorf("域名不能为空")
}
existing, err := s.store.GetByDomain(ctx, domain)
if err != nil {
return err
}
if err := removeCertFiles(s.cfg.CertsDir(), existing); err != nil {
s.logger.Warn("remove cert files failed", "domain", domain, "error", err.Error())
}
if err := s.store.Delete(ctx, domain); err != nil {
return err
}
if err := s.proxySvc.ReloadAll(ctx); err != nil {
s.logger.Warn("nginx reload after cert delete failed", "error", err.Error())
}
s.logger.Info("certificate deleted", "domain", domain)
return nil
}
func (s *Service) Renew(ctx context.Context, domain string, ca string) (certstore.Record, error) {
rootDomain := strings.ToLower(strings.TrimSpace(strings.TrimPrefix(domain, "*.")))
if rootDomain == "" {
return certstore.Record{}, fmt.Errorf("请选择要续签的证书域名")
}
existing, err := s.store.GetByDomain(ctx, rootDomain)
if err != nil {
return certstore.Record{}, err
}
if existing.ACMECA == "imported" {
return certstore.Record{}, fmt.Errorf("手动导入的证书请重新导入,无法自动续签")
}
if ca == "" {
ca = existing.ACMECA
}
ca, err = s.resolveCA(ctx, ca)
if err != nil {
return certstore.Record{}, err
}
email, err := s.resolveACMEEmail(ctx, "")
if err != nil {
return certstore.Record{}, err
}
domains := existing.Domains
if len(domains) == 0 {
domains = LegacyCertDomains(existing.Domain, existing.Wildcard)
}
dnsZone, err := s.resolveDNSZone(ctx, domains)
if err != nil {
return certstore.Record{}, err
}
provider, cred, err := s.dnsCredentialsForDomain(ctx, dnsZone)
if err != nil {
return certstore.Record{}, err
}
if _, err := s.obtain(ctx, nil, ca, email, provider, cred, existing.Domain, domains); err != nil {
s.markCertError(ctx, rootDomain, domains, ca, err)
return certstore.Record{}, err
}
if err := s.proxySvc.ReloadAll(ctx); err != nil {
s.logger.Error("nginx reload after cert renew failed", "error", err.Error())
}
rec, err := s.store.GetByDomain(ctx, rootDomain)
if err != nil {
return certstore.Record{}, err
}
if s.notify != nil {
expires := "未知"
if rec.ExpiresAt != nil {
expires = rec.ExpiresAt.Local().Format("2006-01-02")
}
s.notify.Alert(ctx, notify.EventCertRenewSuccess, "证书续签成功",
fmt.Sprintf("%s 已续签,到期 %s", rootDomain, expires))
}
return rec, nil
}
func (s *Service) Tick(ctx context.Context) {
records, err := s.store.List(ctx)
if err != nil {
return
}
threshold, err := s.settings.GetInt(ctx, settings.KeyCertRenewThreshold)
if err != nil || threshold <= 0 {
threshold = 30
}
for _, rec := range records {
if rec.ExpiresAt == nil {
continue
}
if rec.ACMECA != "imported" && rec.DaysLeft <= threshold {
s.maybeAlertCertExpiry(ctx, rec.Domain, rec.DaysLeft)
}
if rec.DaysLeft <= threshold {
if rec.ACMECA == "imported" {
continue
}
if _, err := s.Renew(ctx, rec.Domain, rec.ACMECA); err != nil {
s.logger.Error("certificate renew failed", "domain", rec.Domain, "error", err.Error())
if s.notify != nil {
s.notify.Alert(ctx, notify.EventCertRenewFailure, "证书续签失败",
fmt.Sprintf("%s: %s", rec.Domain, err.Error()))
}
}
}
}
}
func (s *Service) maybeAlertCertExpiry(ctx context.Context, domain string, daysLeft int) {
if s.notify == nil {
return
}
today := time.Now().Format("2006-01-02")
s.expiryAlertMu.Lock()
if s.expiryAlerted[domain] == today {
s.expiryAlertMu.Unlock()
return
}
s.expiryAlerted[domain] = today
s.expiryAlertMu.Unlock()
msg := fmt.Sprintf("%s 剩余 %d 天到期", domain, daysLeft)
if daysLeft <= 0 {
msg = fmt.Sprintf("%s 已到期或即将失效", domain)
}
s.notify.Alert(ctx, notify.EventCertExpiry, "证书即将到期", msg)
}
func (s *Service) markCertError(ctx context.Context, primary string, domains []string, ca string, err error) {
if err == nil {
return
}
errMsg := err.Error()
s.logger.Error("certificate operation failed", "domain", primary, "error", errMsg)
_, upsertErr := s.store.Upsert(ctx, primary, HasWildcardDomain(domains), EncodeCertDomains(domains), ca, "", "", time.Time{}, "error", errMsg)
if upsertErr != nil {
s.logger.Error("save cert error status failed", "domain", primary, "error", upsertErr.Error())
}
}
func (s *Service) resolveCA(ctx context.Context, ca string) (string, error) {
if strings.TrimSpace(ca) == "" {
ca, err := s.settings.Get(ctx, settings.KeyACMECA)
if err != nil || strings.TrimSpace(ca) == "" {
ca = CALetsEncrypt
}
}
ca = NormalizeCA(ca)
if err := ValidateCA(ca); err != nil {
return "", err
}
if reason := CAUnavailableReason(ca); reason != "" {
return "", fmt.Errorf("%s", reason)
}
return ca, nil
}
func (s *Service) registerACMEAccount(ctx context.Context, client *lego.Client, ca string, logStep func(string)) (*registration.Resource, error) {
reg, err := client.Registration.ResolveAccountByKey()
if err == nil {
return reg, nil
}
logStep("注册 ACME 账户…")
switch NormalizeCA(ca) {
case CAZeroSSL:
apiKey, err := s.settings.Get(ctx, settings.KeyZeroSSLAPIKey)
if err != nil {
return nil, err
}
kid, hmac, err := zerosslEABCredentials(ctx, apiKey)
if err != nil {
return nil, err
}
return client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
TermsOfServiceAgreed: true,
Kid: kid,
HmacEncoded: hmac,
})
case CALiteSSL:
// LiteSSL 的目录里 meta.externalAccountRequired = true:必须带 EAB。
// 与 ZeroSSL 不同,不经过厂商 API 换取,而是用户在 FreeSSL 平台自建 EAB 后直接填 kid/hmac。
kid, err := s.settings.Get(ctx, settings.KeyLiteSSLEABKid)
if err != nil {
return nil, err
}
hmac, err := s.settings.Get(ctx, settings.KeyLiteSSLEABHMAC)
if err != nil {
return nil, err
}
kid = strings.TrimSpace(kid)
hmac = strings.TrimSpace(hmac)
if kid == "" || hmac == "" {
return nil, fmt.Errorf("LiteSSL 要求 EAB 凭据:请在设置里填写 EAB Kid 与 EAB HMAC(在 FreeSSL 的「证书自动化 → EAB 管理」创建后原样粘贴)")
}
return client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
TermsOfServiceAgreed: true,
Kid: kid,
HmacEncoded: hmac,
})
default:
return client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
}
}
func (s *Service) obtain(ctx context.Context, job *Job, ca, email, provider string, cred ddns.Credentials, rootDomain string, domains []string) (certstore.Record, error) {
logStep := func(msg string) {
if job != nil {
job.Info(msg)
}
}
caDir, err := DirectoryURL(ca)
if err != nil {
return certstore.Record{}, err
}
logStep(fmt.Sprintf("连接 ACME 服务器 (%s)", CALabel(ca)))
user, err := newUser(email)
if err != nil {
return certstore.Record{}, err
}
config := lego.NewConfig(user)
config.CADirURL = caDir
config.Certificate.KeyType = certcrypto.EC256
client, err := lego.NewClient(config)
if err != nil {
return certstore.Record{}, err
}
dnsProvider, err := newDNS01Provider(provider, cred)
if err != nil {
return certstore.Record{}, fmt.Errorf("初始化 DNS Provider 失败:%w", err)
}
dnsProvider = wrapDNSProvider(dnsProvider, job)
// DNS-01 的传播检查由 lego 自己做,它默认读系统 /etc/resolv.conf;
// 容器里那通常是 Docker 的 127.0.0.11,它不返回权威 NS,于是报
// 「[zone=example.com.] could not determine authoritative nameservers」。
// 所以显式指定可靠递归解析器(设置项可改;设为 system 则显式回到系统解析器)。
resolvers, err := s.acmeDNSResolvers(ctx)
if err != nil {
return certstore.Record{}, err
}
var challengeOpts []dns01.ChallengeOption
if len(resolvers) > 0 {
challengeOpts = append(challengeOpts, dns01.AddRecursiveNameservers(resolvers))
}
if err := client.Challenge.SetDNS01Provider(dnsProvider, challengeOpts...); err != nil {
return certstore.Record{}, err
}
logStep("检查 ACME 账户…")
reg, err := s.registerACMEAccount(ctx, client, ca, logStep)
if err != nil {
return certstore.Record{}, fmt.Errorf("ACME 注册失败:%w", err)
}
user.registration = reg
logStep("开始 DNS-01 验证并申请证书(可能需要 1~3 分钟)…")
request := legocert.ObtainRequest{
Domains: domains,
Bundle: true,
}
cert, err := client.Certificate.Obtain(request)
if err != nil {
return certstore.Record{}, fmt.Errorf("证书申请失败:%w", err)
}
certPath, keyPath, err := writeCertFiles(s.cfg.CertsDir(), domains, cert.Certificate, cert.PrivateKey)
if err != nil {
return certstore.Record{}, err
}
logStep(fmt.Sprintf("证书已保存: %s", certPath))
logStep(fmt.Sprintf("私钥已保存: %s", keyPath))
expiresAt, err := parseCertExpiry(cert.Certificate)
if err != nil {
expiresAt = time.Now().Add(90 * 24 * time.Hour)
}
logStep(fmt.Sprintf("到期时间: %s", expiresAt.Local().Format("2006-01-02 15:04:ss")))
rec, err := s.store.Upsert(ctx, rootDomain, HasWildcardDomain(domains), EncodeCertDomains(domains), ca, certPath, keyPath, expiresAt, "ok", "")
if err != nil {
return certstore.Record{}, err
}
s.logger.Info("certificate obtained", "domain", rootDomain, "ca", ca, "expires_at", expiresAt.Format(time.RFC3339))
return rec, nil
}
func (s *Service) resolveACMEEmail(ctx context.Context, email string) (string, error) {
email = strings.TrimSpace(email)
if email == "" {
stored, err := s.settings.Get(ctx, settings.KeyACMEEmail)
if err != nil || strings.TrimSpace(stored) == "" {
return "", fmt.Errorf("请先填写 ACME 邮箱,用于注册 ACME 账户(首次申请必填)")
}
email = strings.TrimSpace(stored)
}
if err := validateACMEEmail(email); err != nil {
return "", err
}
if err := s.settings.Set(ctx, settings.KeyACMEEmail, email); err != nil {
s.logger.Warn("save acme email failed", "error", err.Error())
}
return email, nil
}
// defaultACMEDNSResolvers 默认递归解析器(阿里/Cloudflare/Google)。
// 容器里的系统解析器常只指向 127.0.0.11,无法用于 DNS-01 的权威 NS 查询;
// 设置项写 system 则回到系统解析器,写其它值则按逗号/空格分隔逐条使用。
const defaultACMEDNSResolvers = "223.5.5.5:53,1.1.1.1:53,8.8.8.8:53"
// acmeDNSResolvers 返回本次申请要用的解析器;空 slice 表示交给 lego 读系统解析器。
func (s *Service) acmeDNSResolvers(ctx context.Context) ([]string, error) {
raw, err := s.settings.Get(ctx, settings.KeyACMEDNSResolvers)
if err != nil || strings.TrimSpace(raw) == "" {
raw = defaultACMEDNSResolvers
}
if strings.EqualFold(strings.TrimSpace(raw), "system") {
return nil, nil
}
resolvers := parseResolverList(raw)
if len(resolvers) == 0 {
return nil, fmt.Errorf("DNS 解析器配置无效(%q):请填 host 或 host:port,多个用逗号分隔;留空用默认值,填 system 用系统解析器", raw)
}
return resolvers, nil
}
// parseResolverList 解析解析器列表:逗号/空格/换行分隔,未写端口时补 53,最多取前 8 个。
func parseResolverList(raw string) []string {
fields := strings.FieldsFunc(raw, func(r rune) bool {
return r == ',' || r == ' ' || r == '\t' || r == '\n' || r == ';'
})
out := make([]string, 0, len(fields))
for _, item := range fields {
item = strings.TrimSpace(item)
if item == "" {
continue
}
if !strings.Contains(item, ":") {
item += ":53"
}
out = append(out, item)
if len(out) >= 8 {
break
}
}
return out
}
func validateACMEEmail(email string) error {
addr, err := mail.ParseAddress(email)
if err != nil || addr.Address != email {
return fmt.Errorf("ACME 邮箱格式不正确,请填写类似 admin@example.com 的地址")
}
return nil
}
func (s *Service) resolveDNSZone(ctx context.Context, domains []string) (string, error) {
for _, domain := range domains {
cfg, err := s.ddnsSvc.ConfigForAnyDomain(ctx, domain)
if err == nil {
return cfg.RootDomain, nil
}
}
return "", fmt.Errorf("请先在 DDNS 页面配置对应域名的 DNS 凭证")
}
func (s *Service) dnsCredentialsForDomain(ctx context.Context, rootDomain string) (string, ddns.Credentials, error) {
provider, cred, err := s.ddnsSvc.CredentialsForDomain(ctx, rootDomain)
if err != nil {
return "", ddns.Credentials{}, fmt.Errorf("请先在 DDNS 页面为 %s 配置 DNS 凭证", rootDomain)
}
if err := validateDNSCredentials(provider, cred); err != nil {
return "", ddns.Credentials{}, err
}
return provider, cred, nil
}
func writeCertFiles(certsDir string, domains []string, certPEM, keyPEM []byte) (string, string, error) {
names := certStorageNames(domains)
if len(names) == 0 {
return "", "", fmt.Errorf("证书域名不能为空")
}
var certPath, keyPath string
for _, name := range names {
dir := filepath.Join(certsDir, name)
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", "", err
}
cp := filepath.Join(dir, "fullchain.pem")
kp := filepath.Join(dir, "privatekey.pem")
if err := os.WriteFile(cp, certPEM, 0o600); err != nil {
return "", "", err
}
if err := os.WriteFile(kp, keyPEM, 0o600); err != nil {
return "", "", err
}
certPath, keyPath = cp, kp
}
return certPath, keyPath, nil
}
func removeCertFiles(certsDir string, record certstore.Record) error {
domains := record.Domains
if len(domains) == 0 {
domains = LegacyCertDomains(record.Domain, record.Wildcard)
}
var firstErr error
for _, name := range certStorageNames(domains) {
dir := filepath.Join(certsDir, name)
if err := os.RemoveAll(dir); err != nil && firstErr == nil {
firstErr = err
}
}
return firstErr
}
func certStorageNames(domains []string) []string {
seen := map[string]bool{}
var names []string
for _, domain := range domains {
name := domain
if strings.HasPrefix(domain, "*.") {
name = "wildcard." + strings.TrimPrefix(domain, "*.")
}
if seen[name] {
continue
}
seen[name] = true
names = append(names, name)
}
return names
}
func parseCertExpiry(pemBytes []byte) (time.Time, error) {
block, _ := pem.Decode(pemBytes)
if block == nil {
return time.Time{}, fmt.Errorf("invalid pem")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return time.Time{}, err
}
return cert.NotAfter, nil
}
type acmeUser struct {
email string
registration *registration.Resource
key crypto.PrivateKey
}
func (u *acmeUser) GetEmail() string { return u.email }
func (u *acmeUser) GetRegistration() *registration.Resource { return u.registration }
func (u *acmeUser) GetPrivateKey() crypto.PrivateKey { return u.key }
func newUser(email string) (*acmeUser, error) {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, err
}
return &acmeUser{email: email, key: privateKey}, nil
}
+37
View File
@@ -0,0 +1,37 @@
package acme
import (
"context"
"github.com/go-acme/lego/v4/challenge"
"github.com/go-acme/lego/v4/challenge/dns01"
"github.com/havline/havline/internal/ddns"
)
type volcengineDNS struct {
provider *ddns.Volcengine
cred ddns.Credentials
}
func newVolcengineDNSProvider(cred ddns.Credentials) (challenge.Provider, error) {
if err := cred.Validate("volcengine"); err != nil {
return nil, err
}
return &volcengineDNS{
provider: ddns.NewVolcengine(),
cred: cred,
}, nil
}
func (p *volcengineDNS) Present(domain, token, keyAuth string) error {
info := dns01.GetChallengeInfo(domain, keyAuth)
fqdn := dns01.UnFqdn(info.EffectiveFQDN)
return p.provider.UpsertTXTRecord(context.Background(), p.cred, fqdn, info.Value)
}
func (p *volcengineDNS) CleanUp(domain, token, keyAuth string) error {
info := dns01.GetChallengeInfo(domain, keyAuth)
fqdn := dns01.UnFqdn(info.EffectiveFQDN)
return p.provider.DeleteTXTRecord(context.Background(), p.cred, fqdn, info.Value)
}
+94
View File
@@ -0,0 +1,94 @@
package acme
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
type zeroSSLEABResponse struct {
Success int `json:"success"`
EABKid string `json:"eab_kid"`
EABHmacKey string `json:"eab_hmac_key"`
Error struct {
Code int `json:"code"`
Type string `json:"type"`
} `json:"error"`
}
// zeroSSLEABEndpoint 单独成变量,测试可以替换成本地 httptest 服务。
var zeroSSLEABEndpoint = "https://api.zerossl.com/acme/eab-credentials"
func zerosslEABCredentials(ctx context.Context, apiKey string) (kid, hmac string, err error) {
apiKey = strings.TrimSpace(apiKey)
if apiKey == "" {
return "", "", fmt.Errorf("请在设置中配置 ZeroSSL API Key")
}
endpoint := zeroSSLEABEndpoint + "?access_key=" + url.QueryEscape(apiKey)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return "", "", err
}
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
// 不能把 url.Error 整个包进错误:它的字符串里是带 access_key 的完整 URL,
// 而这条错误会进任务日志与 <数据目录>/logs/app.log,等于把密钥写进日志。
return "", "", fmt.Errorf("请求 ZeroSSL API 失败:%s", redactURLError(err))
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return "", "", err
}
var payload zeroSSLEABResponse
parseErr := json.Unmarshal(body, &payload)
if resp.StatusCode != http.StatusOK {
// 422 基本都是 access_key 无效(也可能是账号/权限问题)。ZeroSSL 会在
// error.type 与 error.code 里写清原因,所以带上它,而不是只回状态码让用户猜。
if parseErr == nil && payload.Error.Type != "" {
return "", "", fmt.Errorf("ZeroSSL API 返回 %d:%s(错误码 %d)", resp.StatusCode, payload.Error.Type, payload.Error.Code)
}
return "", "", fmt.Errorf("ZeroSSL API 返回 %d:%s", resp.StatusCode, snippet(body))
}
if parseErr != nil {
return "", "", fmt.Errorf("解析 ZeroSSL 响应失败:%w", parseErr)
}
if payload.Success != 1 || payload.EABKid == "" || payload.EABHmacKey == "" {
if payload.Error.Type != "" {
return "", "", fmt.Errorf("ZeroSSL API 错误:%s(错误码 %d)", payload.Error.Type, payload.Error.Code)
}
return "", "", fmt.Errorf("ZeroSSL API 未返回有效的 EAB 凭据")
}
return payload.EABKid, payload.EABHmacKey, nil
}
// redactURLError 只保留底层错误原因,避免把带 access_key 的 URL 写进日志。
func redactURLError(err error) string {
var urlErr *url.Error
if errors.As(err, &urlErr) && urlErr.Err != nil {
return urlErr.Err.Error()
}
return err.Error()
}
// snippet 压平并截断响应正文:既不把整页 HTML 灌进日志,也不让换行破坏排版。
func snippet(body []byte) string {
text := strings.Join(strings.Fields(string(body)), " ")
if text == "" {
return "(响应体为空)"
}
if len(text) > 200 {
text = text[:200] + "…"
}
return text
}
+86
View File
@@ -0,0 +1,86 @@
package acme
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// withEndpoint 把 ZeroSSL 端点指向本地测试服务(用完恢复)。
func withEndpoint(t *testing.T, handler http.HandlerFunc) {
t.Helper()
server := httptest.NewServer(handler)
previous := zeroSSLEABEndpoint
zeroSSLEABEndpoint = server.URL
t.Cleanup(func() {
zeroSSLEABEndpoint = previous
server.Close()
})
}
func TestZeroSSLEABCredentialsSuccess(t *testing.T) {
withEndpoint(t, func(w http.ResponseWriter, r *http.Request) {
if got := r.URL.Query().Get("access_key"); got != "good-key" {
t.Fatalf("access_key 应原样传出,实际 %q", got)
}
_, _ = w.Write([]byte(`{"success":1,"eab_kid":"kid-1","eab_hmac_key":"hmac-1"}`))
})
kid, hmac, err := zerosslEABCredentials(context.Background(), "good-key")
if err != nil {
t.Fatalf("不应报错:%v", err)
}
if kid != "kid-1" || hmac != "hmac-1" {
t.Fatalf("凭据解析错误:kid=%q hmac=%q", kid, hmac)
}
}
// 422 时要把 ZeroSSL 给的错误类型带出来,而不是只回一个状态码让用户猜
func TestZeroSSLEABCredentialsSurfacesErrorType(t *testing.T) {
withEndpoint(t, func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnprocessableEntity)
_, _ = w.Write([]byte(`{"success":false,"error":{"code":2902,"type":"invalid_api_key"}}`))
})
_, _, err := zerosslEABCredentials(context.Background(), "bad-key")
if err == nil {
t.Fatal("期望报错")
}
if !strings.Contains(err.Error(), "422") || !strings.Contains(err.Error(), "invalid_api_key") {
t.Fatalf("错误里应含状态码与错误类型,实际:%v", err)
}
}
// 非 JSON 的失败响应:退回截断正文,便于定位(例如网关返回的 HTML)
func TestZeroSSLEABCredentialsFallsBackToBodySnippet(t *testing.T) {
withEndpoint(t, func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusBadGateway)
_, _ = w.Write([]byte("<html><body>\n 502 Bad Gateway\n</body></html>"))
})
_, _, err := zerosslEABCredentials(context.Background(), "any")
if err == nil || !strings.Contains(err.Error(), "502 Bad Gateway") {
t.Fatalf("应带上响应正文摘要,实际:%v", err)
}
}
// 网络错误必须脱敏:url.Error 的字符串里带 access_key,泄漏进日志等于泄密
func TestZeroSSLEABCredentialsDoesNotLeakKey(t *testing.T) {
const key = "SUPERSECRETACCESSKEY"
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
server.Close() // 立刻关掉,制造连接失败
previous := zeroSSLEABEndpoint
zeroSSLEABEndpoint = server.URL
t.Cleanup(func() { zeroSSLEABEndpoint = previous })
_, _, err := zerosslEABCredentials(context.Background(), key)
if err == nil {
t.Fatal("期望请求失败")
}
if strings.Contains(err.Error(), key) {
t.Fatalf("错误信息里泄露了 API Key:%v", err)
}
}
+101
View File
@@ -0,0 +1,101 @@
package agent
import (
"crypto/md5"
"crypto/rand"
"fmt"
"strings"
)
// apr1Itoa64 是 apr1(Apache MD5 crypt)使用的自定义 base64 字母表,同时用作随机盐字符集。
const apr1Itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
// apr1Crypt 生成 apr1 哈希,与 `openssl passwd -apr1` 等价(纯 Go,无外部命令依赖)。
// 选 apr1 而非 bcrypt:Nginx 对 $apr1$ 是自带实现,跨发行版稳定;bcrypt 依赖系统 crypt(3),
// 在 CentOS 7 这类老 glibc 上无法校验。
func apr1Crypt(password string) (string, error) {
salt, err := apr1RandomSalt(8)
if err != nil {
return "", err
}
return apr1CryptWithSalt(password, salt), nil
}
// apr1RandomSalt 生成指定长度的随机盐(字符取自 itoa64,与 openssl 行为一致)。
func apr1RandomSalt(n int) (string, error) {
buf := make([]byte, n)
if _, err := rand.Read(buf); err != nil {
return "", fmt.Errorf("生成随机盐失败: %w", err)
}
var b strings.Builder
for _, v := range buf {
b.WriteByte(apr1Itoa64[int(v)%len(apr1Itoa64)])
}
return b.String(), nil
}
// apr1CryptWithSalt 是 apr1 的确定性实现(salt 取前 8 字符),供单元测试用参考向量比对。
// 算法来自 Apache apr_md5_encode:MD5 三轮 + 1000 次迭代 + 自定义字节序 base64。
func apr1CryptWithSalt(password, salt string) string {
if len(salt) > 8 {
salt = salt[:8]
}
ctx := md5.New()
ctx.Write([]byte(password))
ctx.Write([]byte("$apr1$"))
ctx.Write([]byte(salt))
alt := md5.Sum([]byte(password + salt + password))
for i := len(password); i > 0; i -= 16 {
n := i
if n > 16 {
n = 16
}
ctx.Write(alt[:n])
}
for i := len(password); i > 0; i >>= 1 {
if i&1 != 0 {
ctx.Write([]byte{0})
} else {
ctx.Write([]byte(password[0:1]))
}
}
final := ctx.Sum(nil)
for i := 0; i < 1000; i++ {
round := md5.New()
if i&1 != 0 {
round.Write([]byte(password))
} else {
round.Write(final)
}
if i%3 != 0 {
round.Write([]byte(salt))
}
if i%7 != 0 {
round.Write([]byte(password))
}
if i&1 != 0 {
round.Write(final)
} else {
round.Write([]byte(password))
}
final = round.Sum(nil)
}
var out strings.Builder
to64 := func(v uint32, n int) {
for ; n > 0; n-- {
out.WriteByte(apr1Itoa64[v&0x3f])
v >>= 6
}
}
to64(uint32(final[0])<<16|uint32(final[6])<<8|uint32(final[12]), 4)
to64(uint32(final[1])<<16|uint32(final[7])<<8|uint32(final[13]), 4)
to64(uint32(final[2])<<16|uint32(final[8])<<8|uint32(final[14]), 4)
to64(uint32(final[3])<<16|uint32(final[9])<<8|uint32(final[15]), 4)
to64(uint32(final[4])<<16|uint32(final[10])<<8|uint32(final[5]), 4)
to64(uint32(final[11]), 2)
return "$apr1$" + salt + "$" + out.String()
}
+58
View File
@@ -0,0 +1,58 @@
package agent
import "testing"
// 参考向量由本机 OpenSSL 3.5.4 生成:
//
// openssl passwd -apr1 -salt <salt> <password>
//
// 自研哈希必须与 openssl 完全一致,否则 Nginx Basic Auth 会永远认证失败。
func TestApr1CryptMatchesOpenSSLVectors(t *testing.T) {
cases := []struct {
password string
salt string
want string
}{
{"password", "xxxxxxxx", "$apr1$xxxxxxxx$dxHfLAsjHkDRmG83UXe8K0"},
{"hello", "01234567", "$apr1$01234567$JGzOENmOOkvGYFfJQyG9X/"},
{"P@ssw0rd!", "abcdefgh", "$apr1$abcdefgh$T9Ta7XuM2Yltpi/4uviFw0"},
}
for _, c := range cases {
if got := apr1CryptWithSalt(c.password, c.salt); got != c.want {
t.Errorf("apr1CryptWithSalt(%q, %q)\n got: %s\nwant: %s", c.password, c.salt, got, c.want)
}
}
}
func TestApr1CryptSaltHandling(t *testing.T) {
// 超过 8 字符的盐只取前 8 位(与 openssl / apr 行为一致)
long := apr1CryptWithSalt("password", "xxxxxxxxyyyy")
short := apr1CryptWithSalt("password", "xxxxxxxx")
if long != short {
t.Errorf("盐应截断到 8 字符: %s vs %s", long, short)
}
}
func TestApr1CryptRandomSalt(t *testing.T) {
first, err := apr1Crypt("password")
if err != nil {
t.Fatalf("apr1Crypt 失败: %v", err)
}
second, err := apr1Crypt("password")
if err != nil {
t.Fatalf("apr1Crypt 失败: %v", err)
}
if first == second {
t.Error("随机盐应产生不同哈希")
}
// 结构:$apr1$<8 位盐>$<22 位编码> = 37 字符
if len(first) != 37 {
t.Errorf("哈希长度应为 37,实际 %d: %s", len(first), first)
}
if first[:6] != "$apr1$" || first[14] != '$' {
t.Errorf("哈希结构异常: %s", first)
}
if same := apr1CryptWithSalt("password", first[6:14]); same != first {
t.Errorf("从哈希中取出的盐应能复现同一哈希: %s vs %s", same, first)
}
}
+54
View File
@@ -0,0 +1,54 @@
package agent
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestServerAuthToken(t *testing.T) {
server := &Server{cfg: Config{Token: "secret-token"}}
handler := server.auth(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
cases := []struct {
name string
header string
status int
}{
{name: "正确 Token", header: "Bearer secret-token", status: http.StatusNoContent},
{name: "Bearer 大小写不敏感", header: "bearer secret-token", status: http.StatusNoContent},
{name: "多余空白可容忍", header: " Bearer secret-token ", status: http.StatusNoContent},
{name: "错误 Token", header: "Bearer wrong-token", status: http.StatusUnauthorized},
{name: "长度不同的 Token", header: "Bearer secret-token-longer", status: http.StatusUnauthorized},
{name: "缺少 Authorization", status: http.StatusUnauthorized},
{name: "认证方案错误", header: "Token secret-token", status: http.StatusUnauthorized},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/v1/ping", nil)
if tc.header != "" {
req.Header.Set("Authorization", tc.header)
}
recorder := httptest.NewRecorder()
handler(recorder, req)
if recorder.Code != tc.status {
t.Fatalf("期望状态 %d,实际 %d", tc.status, recorder.Code)
}
})
}
}
func TestSecureTokenEqual(t *testing.T) {
if !secureTokenEqual("same-token", "same-token") {
t.Fatal("相同 Token 应通过")
}
if secureTokenEqual("short", "longer-token") {
t.Fatal("不同 Token 不应通过")
}
if secureTokenEqual("", "non-empty") {
t.Fatal("空 Token 不应通过")
}
}
+127
View File
@@ -0,0 +1,127 @@
package agent
import (
"encoding/json"
"errors"
"net/http"
"os/exec"
"strconv"
"strings"
)
type firewallStatus struct {
Tool string `json:"tool"`
Active bool `json:"active"`
PortOpen bool `json:"port_open"`
Message string `json:"message,omitempty"`
}
// firewallStatus 只检测主机防火墙,不修改规则;云安全组无法从 VPS 内部感知。
func (s *Server) firewallStatus(w http.ResponseWriter, r *http.Request) {
port := 7443
if raw := strings.TrimSpace(r.URL.Query().Get("port")); raw != "" {
if parsed, err := strconv.Atoi(raw); err == nil && parsed > 0 && parsed <= 65535 {
port = parsed
}
}
writeJSON(w, http.StatusOK, detectFirewall(port))
}
// firewallAllow 仅在用户显式确认后调用;只自动处理 ufw 与 firewalld。
func (s *Server) firewallAllow(w http.ResponseWriter, r *http.Request) {
var req struct {
Port int `json:"port"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
if req.Port <= 0 || req.Port > 65535 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "端口无效"})
return
}
output, err := allowFirewallPort(req.Port)
if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()})
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "output": output, "status": detectFirewall(req.Port)})
}
func detectFirewall(port int) firewallStatus {
if path, err := exec.LookPath("ufw"); err == nil {
if out, err := exec.Command(path, "status").Output(); err == nil {
active, open := parseUFWStatus(string(out), port)
if active {
return firewallStatus{Tool: "ufw", Active: true, PortOpen: open}
}
}
}
if path, err := exec.LookPath("firewall-cmd"); err == nil {
if out, err := exec.Command(path, "--state").Output(); err == nil && strings.TrimSpace(string(out)) == "running" {
return firewallStatus{Tool: "firewalld", Active: true, PortOpen: firewalldPortOpen(path, port)}
}
}
if _, err := exec.LookPath("nft"); err == nil {
return firewallStatus{Tool: "nftables", Active: true, Message: "nftables 需要手工放行,Agent 不会自动修改规则"}
}
if _, err := exec.LookPath("iptables"); err == nil {
return firewallStatus{Tool: "iptables", Active: true, Message: "iptables 需要手工放行,Agent 不会自动修改规则"}
}
return firewallStatus{Tool: "none", Message: "未检测到主机防火墙"}
}
// parseUFWStatus 纯解析 ufw status 输出:是否启用、目标端口是否已放行。
func parseUFWStatus(output string, port int) (bool, bool) {
active := false
open := false
needle := strconv.Itoa(port)
for _, line := range strings.Split(output, "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "Status:") {
active = strings.EqualFold(strings.TrimSpace(strings.TrimPrefix(line, "Status:")), "active")
continue
}
if !strings.Contains(line, needle) || !strings.Contains(line, "ALLOW") {
continue
}
fields := strings.Fields(line)
if len(fields) > 0 && (fields[0] == needle || strings.HasPrefix(fields[0], needle+"/")) {
open = true
}
}
return active, open
}
func firewalldPortOpen(path string, port int) bool {
out, err := exec.Command(path, "--list-ports").Output()
if err != nil {
return false
}
for _, item := range strings.Fields(string(out)) {
if strings.HasPrefix(item, strconv.Itoa(port)+"/") {
return true
}
}
return false
}
func allowFirewallPort(port int) (string, error) {
status := detectFirewall(port)
switch status.Tool {
case "ufw":
out, err := exec.Command("ufw", "allow", strconv.Itoa(port)+"/tcp").CombinedOutput()
return strings.TrimSpace(string(out)), err
case "firewalld":
first, err := exec.Command("firewall-cmd", "--permanent", "--add-port="+strconv.Itoa(port)+"/tcp").CombinedOutput()
if err != nil {
return strings.TrimSpace(string(first)), err
}
second, err := exec.Command("firewall-cmd", "--reload").CombinedOutput()
return strings.TrimSpace(string(first) + "\n" + string(second)), err
case "nftables", "iptables":
return "", errors.New("当前防火墙需要手工放行,Agent 不会自动修改 nftables / iptables 规则")
default:
return "", errors.New("未检测到可自动放行的主机防火墙(仅支持 ufw / firewalld)")
}
}
+38
View File
@@ -0,0 +1,38 @@
package agent
import "testing"
func TestParseUFWStatus(t *testing.T) {
output := `Status: active
To Action From
-- ------ ----
22/tcp ALLOW Anywhere
7443/tcp ALLOW Anywhere
`
active, open := parseUFWStatus(output, 7443)
if !active || !open {
t.Fatalf("应识别出 ufw 已启用且 7443 已放行:active=%v open=%v", active, open)
}
_, open = parseUFWStatus(output, 9443)
if open {
t.Fatal("未放行的端口不应判定为已放行")
}
}
func TestParseUFWStatusInactive(t *testing.T) {
active, open := parseUFWStatus("Status: inactive\n", 7443)
if active || open {
t.Fatalf("inactive 时不应判定为启用:active=%v open=%v", active, open)
}
}
func TestCandidateHTTPSPorts(t *testing.T) {
if got := candidateHTTPSPorts(9443); len(got) != 1 || got[0] != 9443 {
t.Fatalf("显式端口应只返回该端口:%v", got)
}
got := candidateHTTPSPorts(0)
if len(got) != 3 || got[0] != 7443 || got[1] != 8443 || got[2] != 9443 {
t.Fatalf("自动模式应返回 7443/8443/9443:%v", got)
}
}
+80
View File
@@ -0,0 +1,80 @@
package agent
import (
"encoding/json"
"errors"
"net/http"
"os"
"path/filepath"
"strings"
)
// frps 的 custom404Page 只认 VPS 上的文件路径,所以「自定义 404 页面内容」必须先把内容
// 落到 VPS 上。这里给 Havline 一个受控的写文件入口:只写绝对路径、只写 .html,避免变成
// 任意文件写入。
type frpsPageRequest struct {
Path string `json:"path"`
Content string `json:"content"`
}
func (s *Server) putFRPS404Page(w http.ResponseWriter, r *http.Request) {
var req frpsPageRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
path, err := validatePagePath(req.Path)
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
return
}
if strings.TrimSpace(req.Content) == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "页面内容为空"})
return
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()})
return
}
s.mu.Lock()
defer s.mu.Unlock()
if err := atomicWrite(path, []byte(req.Content), 0o644); err != nil {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()})
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "path": path, "bytes": len(req.Content)})
}
func (s *Server) deleteFRPS404Page(w http.ResponseWriter, r *http.Request) {
path, err := validatePagePath(r.URL.Query().Get("path"))
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
return
}
s.mu.Lock()
defer s.mu.Unlock()
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()})
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
// validatePagePath 只接受绝对路径 + .html/.htm 结尾,防止这个接口被当成任意文件写入。
func validatePagePath(raw string) (string, error) {
path := strings.TrimSpace(raw)
// agent 只跑在 Linux 上,这里按 POSIX 绝对路径判断(用 filepath.IsAbs 会在别的平台判错)
if path == "" || !strings.HasPrefix(path, "/") {
return "", errors.New("页面路径必须是绝对路径")
}
if strings.Contains(path, "..") {
return "", errors.New("页面路径不允许包含 ..")
}
switch strings.ToLower(filepath.Ext(path)) {
case ".html", ".htm":
return filepath.Clean(path), nil
default:
return "", errors.New("页面文件必须以 .html 或 .htm 结尾")
}
}
+19
View File
@@ -0,0 +1,19 @@
package agent
import "testing"
// 404 页面写入接口只接受绝对路径 + .html/.htm,避免被当成任意文件写入。
func TestValidatePagePath(t *testing.T) {
ok := []string{"/etc/frp/havline-404.html", "/var/www/404.htm"}
for _, path := range ok {
if _, err := validatePagePath(path); err != nil {
t.Errorf("%s 应当通过:%v", path, err)
}
}
bad := []string{"", "etc/frp/404.html", "/etc/frp/404.txt", "/etc/../etc/passwd.html"}
for _, path := range bad {
if _, err := validatePagePath(path); err == nil {
t.Errorf("%s 应当被拒绝", path)
}
}
}
+423
View File
@@ -0,0 +1,423 @@
package agent
import (
"bytes"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"math"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/havline/havline/internal/sysinfo"
)
const (
// metricsInterval 两次 CPU 采样的最小间隔:间隔内重复调用直接返回上次结果,避免数值抖动
metricsInterval = time.Second
// maxLogLineBytes 单行日志截断长度,避免一行超长把响应撑大
maxLogLineBytes = 4 << 10
// maxLogLines 日志尾部行数上限
maxLogLines = 2000
// maxFRPSConfigBytes frps.toml 回读上限
maxFRPSConfigBytes = 256 << 10
)
// metrics 采集 VPS 主机资源(CPU / 内存 / 磁盘 / 负载 / 运行时长)。
// 复用 internal/sysinfo:agent 跑在 VPS 上,采到的天然是 VPS 自身数值。
func (s *Server) metrics(w http.ResponseWriter, _ *http.Request) {
s.metricsMu.Lock()
defer s.metricsMu.Unlock()
now := time.Now()
if s.metricsCached != nil && now.Sub(s.metricsAt) < metricsInterval {
writeJSON(w, http.StatusOK, s.metricsCached)
return
}
stats, sample := sysinfo.Read(s.metricsSample)
s.metricsSample = sample
payload := map[string]any{
"cpu_percent": math.Round(stats.CPUPercent*10) / 10,
"mem_used_bytes": stats.MemUsedBytes,
"mem_total_bytes": stats.MemTotalBytes,
"disk_used_bytes": stats.DiskUsedBytes,
"disk_total_bytes": stats.DiskTotalBytes,
// 当前只统计根文件系统(与 internal/sysinfo 的 Linux 实现一致)
"disk_path": "/",
"checked_at": now.UTC().Format(time.RFC3339),
}
if load := sysinfo.LoadAvg(); len(load) == 3 {
payload["load_avg"] = load
}
if uptime := sysinfo.UptimeSeconds(); uptime > 0 {
payload["uptime_seconds"] = uptime
}
s.metricsAt = now
s.metricsCached = payload
writeJSON(w, http.StatusOK, payload)
}
// nginxLogs 读取 VPS 上 Nginx 的 access / error 日志尾部。
// 路径不接受请求参数:只从 `nginx -T` 的实际生效配置、默认目录或环境变量目录里取,避免变成任意文件读取。
func (s *Server) nginxLogs(w http.ResponseWriter, r *http.Request) {
kind := strings.TrimSpace(r.URL.Query().Get("type"))
if kind != "access" && kind != "error" {
kind = "access"
}
lines := maxLogLines
if raw := strings.TrimSpace(r.URL.Query().Get("lines")); raw != "" {
if parsed, err := strconv.Atoi(raw); err == nil {
lines = parsed
}
}
if lines <= 0 || lines > maxLogLines {
lines = maxLogLines
}
path := s.nginxLogPath(kind)
if path == "" {
writeJSON(w, http.StatusOK, map[string]any{
"type": kind, "path": "", "lines": []string{}, "truncated": false,
"checked_at": time.Now().UTC().Format(time.RFC3339),
})
return
}
content, truncated, err := tailFile(path, lines, maxLogLineBytes)
if err != nil {
if os.IsNotExist(err) {
// 文件不存在不是错误:返回空列表 + 路径,由前端提示「未找到日志文件」
writeJSON(w, http.StatusOK, map[string]any{
"type": kind, "path": path, "lines": []string{}, "truncated": false,
"checked_at": time.Now().UTC().Format(time.RFC3339),
})
return
}
status := http.StatusInternalServerError
if os.IsPermission(err) {
status = http.StatusForbidden
}
writeJSON(w, status, map[string]any{"error": fmt.Sprintf("读取日志失败:%v", err), "path": path})
return
}
writeJSON(w, http.StatusOK, map[string]any{
"type": kind, "path": path, "lines": content, "truncated": truncated,
"checked_at": time.Now().UTC().Format(time.RFC3339),
})
}
// nginxLogPath 解析日志文件路径:优先 `nginx -T` 实际生效配置里的指令,其次环境变量目录,最后默认目录
func (s *Server) nginxLogPath(kind string) string {
directive := "access_log"
if kind == "error" {
directive = "error_log"
}
if nginx := s.nginxPath(); nginx != "" {
if out, err := exec.Command(nginx, "-T").CombinedOutput(); err == nil {
if path := logPathFromDump(string(out), directive); path != "" {
return path
}
}
}
dir := strings.TrimSpace(os.Getenv("HAVLINE_AGENT_NGINX_LOG_DIR"))
if dir == "" {
dir = "/var/log/nginx"
}
return filepath.Join(dir, kind+".log")
}
// logPathFromDump 从 `nginx -T` 输出里取第一条绝对路径的日志指令(跳过 off / stderr / 含变量的写法)
func logPathFromDump(dump, directive string) string {
pattern := regexp.MustCompile(`(?m)^\s*` + directive + `\s+([^;\s]+)`)
for _, match := range pattern.FindAllStringSubmatch(dump, -1) {
candidate := strings.TrimSpace(match[1])
if candidate == "" || candidate == "off" || candidate == "stderr" || strings.Contains(candidate, "$") {
continue
}
// 只接受绝对路径:agent 只跑在 Linux 上,用前导斜杠判定(filepath.IsAbs 在 Windows 上对 /var/... 返回 false)
if strings.HasPrefix(candidate, "/") {
return candidate
}
}
return ""
}
// tailFile 从文件末尾倒读最多 lines 行:按块回溯,避免把整个日志读进内存;单行超长时截断
func tailFile(path string, lines int, maxLine int) ([]string, bool, error) {
file, err := os.Open(path)
if err != nil {
return nil, false, err
}
defer file.Close()
info, err := file.Stat()
if err != nil {
return nil, false, err
}
const chunkSize = 32 * 1024
var (
offset int64 = info.Size()
buffer []byte
)
for offset > 0 && bytes.Count(buffer, []byte("\n")) <= lines {
readSize := int64(chunkSize)
if offset < readSize {
readSize = offset
}
offset -= readSize
block := make([]byte, readSize)
if _, err := file.ReadAt(block, offset); err != nil && err != io.EOF {
return nil, false, err
}
buffer = append(block, buffer...)
}
rows := strings.Split(strings.TrimRight(string(buffer), "\n"), "\n")
truncated := false
if len(rows) > lines {
rows = rows[len(rows)-lines:]
truncated = true
}
out := make([]string, 0, len(rows))
for _, row := range rows {
if len(row) > maxLine {
row = row[:maxLine] + "…"
}
out = append(out, row)
}
return out, truncated, nil
}
// vpsCertificate VPS 证书目录里的一张证书
// 注意:证书按 <CertsDir>/<域名>/fullchain.pem + privkey.pem 存放(与 putCertificate 一致)。
type vpsCertificate struct {
Domain string `json:"domain"`
CertPath string `json:"cert_path"`
KeyPath string `json:"key_path"`
NotAfter string `json:"not_after,omitempty"`
DaysLeft int `json:"days_left"`
}
// certs 列出 VPS 证书目录下的域名与到期时间:用于与 Havline 证书库交叉核对,也能看到宝塔自行申请的证书
func (s *Server) certs(w http.ResponseWriter, _ *http.Request) {
dir := strings.TrimSpace(s.cfg.CertsDir)
payload := map[string]any{
"certs": []vpsCertificate{}, "warnings": []string{}, "dir": dir,
"checked_at": time.Now().UTC().Format(time.RFC3339),
}
if dir == "" {
writeJSON(w, http.StatusOK, payload)
return
}
entries, err := os.ReadDir(dir)
if err != nil {
if os.IsNotExist(err) {
writeJSON(w, http.StatusOK, payload)
return
}
status := http.StatusInternalServerError
if os.IsPermission(err) {
status = http.StatusForbidden
}
writeJSON(w, status, map[string]string{"error": fmt.Sprintf("读取证书目录失败:%v", err)})
return
}
now := time.Now()
certs := make([]vpsCertificate, 0, len(entries))
warnings := make([]string, 0)
for _, entry := range entries {
if !entry.IsDir() {
continue
}
domain := entry.Name()
item := vpsCertificate{
Domain: domain,
CertPath: filepath.Join(dir, domain, "fullchain.pem"),
KeyPath: filepath.Join(dir, domain, "privkey.pem"),
}
notAfter, err := readCertificateNotAfter(item.CertPath)
if err != nil {
warnings = append(warnings, fmt.Sprintf("%s:%v", domain, err))
} else {
item.NotAfter = notAfter.UTC().Format(time.RFC3339)
item.DaysLeft = int(notAfter.Sub(now).Hours() / 24)
}
certs = append(certs, item)
}
// 到期最快的排在前面,便于直接看出哪张该续了
sort.Slice(certs, func(i, j int) bool { return certs[i].DaysLeft < certs[j].DaysLeft })
payload["certs"] = certs
payload["warnings"] = warnings
writeJSON(w, http.StatusOK, payload)
}
// readCertificateNotAfter 解析 PEM 证书的到期时间
func readCertificateNotAfter(path string) (time.Time, error) {
data, err := os.ReadFile(path)
if err != nil {
return time.Time{}, err
}
block, _ := pem.Decode(data)
if block == nil {
return time.Time{}, fmt.Errorf("不是有效的 PEM 证书")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return time.Time{}, err
}
return cert.NotAfter, nil
}
// nginxReload 显式校验并重载 Nginx,把校验/重载失败的原因回传。
// 这里不加 s.mu:validateNginx / reloadNginx 的调用方约定(见 writeRoute 注释)是外部持锁,
// 而本端点是用户显式触发的排查动作,不加锁可避免与路由写入相互阻塞。
func (s *Server) nginxReload(w http.ResponseWriter, _ *http.Request) {
payload := map[string]any{"checked_at": time.Now().UTC().Format(time.RFC3339)}
if err := s.validateNginx(); err != nil {
payload["ok"] = false
payload["test_ok"] = false
payload["test_error"] = err.Error()
writeJSON(w, http.StatusOK, payload)
return
}
payload["test_ok"] = true
if err := s.reloadNginx(); err != nil {
payload["ok"] = false
payload["reload_ok"] = false
payload["reload_error"] = err.Error()
writeJSON(w, http.StatusOK, payload)
return
}
// 重载成功后让 Nginx 可用性探测的缓存失效,避免页面继续显示旧结论
s.invalidateNginxProbe()
payload["ok"] = true
payload["reload_ok"] = true
writeJSON(w, http.StatusOK, payload)
}
// nginxAction 启动 / 停止 / 重启 VPS 上的 Nginx。
//
// 不走 systemctl:宝塔、源码编译等安装方式没有 systemd unit,
// 统一用 nginx 自身信号控制,与 reloadNginx 走同一条路径,行为一致可预期。
func (s *Server) nginxAction(w http.ResponseWriter, r *http.Request) {
var req struct {
Action string `json:"action"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<10)).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
if req.Action != "start" && req.Action != "stop" && req.Action != "restart" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "action 需为 start/stop/restart"})
return
}
nginx := s.nginxPath()
if nginx == "" {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "未找到 nginx 可执行文件:请先安装 Nginx,或用 HAVLINE_AGENT_NGINX_BIN 指定路径"})
return
}
s.mu.Lock()
defer s.mu.Unlock()
if err := runNginxAction(nginx, req.Action); err != nil {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()})
return
}
// 启停异步生效,留出短暂窗口再重新探测,避免页面读到旧状态
time.Sleep(600 * time.Millisecond)
s.invalidateNginxProbe()
probe := s.probeNginx()
writeJSON(w, http.StatusOK, map[string]any{
"ok": true,
"action": req.Action,
"nginx_running": probe.Running,
"nginx_ok": probe.OK,
"nginx_error": probe.Error,
})
}
// runNginxAction 执行一次启停;已经是目标状态时按幂等处理,不报错。
func runNginxAction(nginx, action string) error {
running := nginxRunning()
switch action {
case "start":
if running {
return nil
}
return startNginx(nginx)
case "stop":
if !running {
return nil
}
return stopNginx(nginx)
default: // restart
if running {
_ = stopNginx(nginx)
time.Sleep(500 * time.Millisecond)
}
return startNginx(nginx)
}
}
func startNginx(nginx string) error {
if out, err := exec.Command(nginx).CombinedOutput(); err != nil {
return fmt.Errorf("启动 Nginx 失败:%s", strings.TrimSpace(string(out)))
}
return nil
}
func stopNginx(nginx string) error {
if out, err := exec.Command(nginx, "-s", "stop").CombinedOutput(); err != nil {
return fmt.Errorf("停止 Nginx 失败:%s", strings.TrimSpace(string(out)))
}
return nil
}
// frpsConfig 回读 VPS 上的 frps.toml,供应用侧与「即将下发的内容」比对,检出被手工修改的情况
func (s *Server) frpsConfig(w http.ResponseWriter, _ *http.Request) {
path := strings.TrimSpace(s.cfg.FrpsConfigPath)
payload := map[string]any{
"path": path, "exists": false, "content": "", "truncated": false,
"checked_at": time.Now().UTC().Format(time.RFC3339),
}
if path == "" {
writeJSON(w, http.StatusOK, payload)
return
}
info, err := os.Stat(path)
if err != nil {
writeJSON(w, http.StatusOK, payload)
return
}
data, err := os.ReadFile(path)
if err != nil {
status := http.StatusInternalServerError
if os.IsPermission(err) {
status = http.StatusForbidden
}
writeJSON(w, status, map[string]any{"error": fmt.Sprintf("读取 frps 配置失败:%v", err), "path": path})
return
}
if len(data) > maxFRPSConfigBytes {
data = data[:maxFRPSConfigBytes]
payload["truncated"] = true
}
payload["exists"] = true
payload["content"] = string(data)
payload["mod_time"] = info.ModTime().UTC().Format(time.RFC3339)
writeJSON(w, http.StatusOK, payload)
}
+67
View File
@@ -0,0 +1,67 @@
package agent
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestTailFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "access.log")
if err := os.WriteFile(path, []byte("line1\nline2\nline3\nline4\n"), 0o644); err != nil {
t.Fatalf("write: %v", err)
}
rows, truncated, err := tailFile(path, 2, maxLogLineBytes)
if err != nil {
t.Fatalf("tailFile: %v", err)
}
// 文件里还有更早的行没返回,因此应当标记为截断
if !truncated {
t.Fatal("只取两行时应标记为截断(还有更早的日志未返回)")
}
if len(rows) != 2 || rows[0] != "line3" || rows[1] != "line4" {
t.Fatalf("unexpected rows: %#v", rows)
}
// 请求行数超过文件内容:返回全部且不标记截断
rows, truncated, err = tailFile(path, 100, maxLogLineBytes)
if err != nil || truncated || len(rows) != 4 {
t.Fatalf("unexpected full read: rows=%d truncated=%v err=%v", len(rows), truncated, err)
}
// 单行超长时截断
long := strings.Repeat("x", maxLogLineBytes+10)
if err := os.WriteFile(path, []byte(long+"\n"), 0o644); err != nil {
t.Fatalf("write: %v", err)
}
rows, _, err = tailFile(path, 5, maxLogLineBytes)
if err != nil {
t.Fatalf("tailFile: %v", err)
}
if len(rows) != 1 || !strings.HasSuffix(rows[0], "…") || len(rows[0]) > maxLogLineBytes+3 {
t.Fatalf("超长行未被截断:len=%d", len(rows[0]))
}
// 文件不存在返回错误,由调用方转成「200 + 空列表」
if _, _, err := tailFile(filepath.Join(t.TempDir(), "missing.log"), 10, maxLogLineBytes); err == nil {
t.Fatal("文件不存在应返回错误")
}
}
func TestLogPathFromDump(t *testing.T) {
dump := "# configuration file /etc/nginx/nginx.conf:\naccess_log /var/log/nginx/access.log main;\nerror_log /var/log/nginx/error.log warn;\n"
if got := logPathFromDump(dump, "access_log"); got != "/var/log/nginx/access.log" {
t.Fatalf("unexpected access log: %q", got)
}
if got := logPathFromDump(dump, "error_log"); got != "/var/log/nginx/error.log" {
t.Fatalf("unexpected error log: %q", got)
}
// off / stderr / 相对路径 / 含变量 都不采用
skip := "access_log off;\naccess_log stderr;\naccess_log logs/access.log;\naccess_log /var/log/nginx/$host.log;\n"
if got := logPathFromDump(skip, "access_log"); got != "" {
t.Fatalf("expected empty, got %q", got)
}
}
+65
View File
@@ -0,0 +1,65 @@
package agent
import (
"os"
"path/filepath"
"testing"
)
func TestReadLimitStateFile(t *testing.T) {
dir := t.TempDir()
missing, err := readLimitStateFile(filepath.Join(dir, "missing.json"))
if err != nil {
t.Fatalf("文件不存在应返回空状态: %v", err)
}
if len(missing) != 0 {
t.Fatalf("文件不存在应返回空 map,实际 %#v", missing)
}
validPath := filepath.Join(dir, "valid.json")
valid := []byte(`{"a.example.com":{"rate":10,"burst":20,"conn":5}}`)
if err := os.WriteFile(validPath, valid, 0o600); err != nil {
t.Fatal(err)
}
state, err := readLimitStateFile(validPath)
if err != nil {
t.Fatal(err)
}
got := state["a.example.com"]
if got.Rate != 10 || got.Burst != 20 || got.Conn != 5 {
t.Fatalf("解析结果不正确: %#v", got)
}
brokenPath := filepath.Join(dir, "broken.json")
broken := []byte(`{"a.example.com":`)
if err := os.WriteFile(brokenPath, broken, 0o600); err != nil {
t.Fatal(err)
}
if _, err := readLimitStateFile(brokenPath); err == nil {
t.Fatal("损坏 JSON 应返回错误")
}
after, err := os.ReadFile(brokenPath)
if err != nil {
t.Fatal(err)
}
if string(after) != string(broken) {
t.Fatalf("读取失败不应修改原文件: %q", after)
}
emptyPath := filepath.Join(dir, "empty.json")
if err := os.WriteFile(emptyPath, nil, 0o600); err != nil {
t.Fatal(err)
}
if _, err := readLimitStateFile(emptyPath); err == nil {
t.Fatal("空文件应返回错误")
}
nullPath := filepath.Join(dir, "null.json")
if err := os.WriteFile(nullPath, []byte("null\n"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := readLimitStateFile(nullPath); err == nil {
t.Fatal("null 内容应返回错误")
}
}
+35
View File
@@ -0,0 +1,35 @@
package agent
import "testing"
func TestValidateListenAddr(t *testing.T) {
cases := []struct {
addr string
allowRemote bool
loopback bool
wantErr bool
}{
{"127.0.0.1:7700", false, true, false},
{"localhost:7700", false, true, false},
{"[::1]:7700", false, true, false},
{":7700", false, false, true},
{"0.0.0.0:7700", false, false, true},
{"0.0.0.0:7700", true, false, false},
{"bad-address", false, false, true},
}
for _, tc := range cases {
loopback, err := validateListenAddr(tc.addr, tc.allowRemote)
if tc.wantErr {
if err == nil {
t.Fatalf("%s 应拒绝", tc.addr)
}
continue
}
if err != nil {
t.Fatalf("%s 不应报错: %v", tc.addr, err)
}
if loopback != tc.loopback {
t.Fatalf("%s loopback=%v, want %v", tc.addr, loopback, tc.loopback)
}
}
}
+88
View File
@@ -0,0 +1,88 @@
package agent
import (
"net"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
)
// 用临时参数跑探测,避免单测真的等满默认的 1.5 秒间隔
func stubProbeRetry(t *testing.T, attempts int) {
t.Helper()
oldAttempts, oldInterval := routeProbeAttempts, routeProbeInterval
routeProbeAttempts, routeProbeInterval = attempts, time.Millisecond
t.Cleanup(func() { routeProbeAttempts, routeProbeInterval = oldAttempts, oldInterval })
}
func probePort(t *testing.T, server *httptest.Server) int {
t.Helper()
addr, ok := server.Listener.Addr().(*net.TCPAddr)
if !ok {
t.Fatalf("无法取到测试服务端口:%v", server.Listener.Addr())
}
return addr.Port
}
// TestProbeVhostReadyWaitsForRegistration:前两次 404(隧道尚未注册)后应继续重试并拿到 200,
// 这正是「部署后立刻探测误报失败、刷新又正常」的场景。
func TestProbeVhostReadyWaitsForRegistration(t *testing.T) {
stubProbeRetry(t, 4)
var hits int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
if atomic.AddInt32(&hits, 1) <= 2 {
w.WriteHeader(http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
code, _ := (&Server{}).probeVhostReady(probePort(t, server), "a.example.com")
if code != http.StatusOK {
t.Fatalf("期望重试后拿到 200,实际 %d", code)
}
if hits != 3 {
t.Fatalf("期望探测 3 次后成功,实际 %d 次", hits)
}
}
// TestProbeVhostReadyStopsOnSuccess:非 404 立即返回,不做多余重试。
func TestProbeVhostReadyStopsOnSuccess(t *testing.T) {
stubProbeRetry(t, 4)
var hits int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
atomic.AddInt32(&hits, 1)
w.WriteHeader(http.StatusBadGateway)
}))
defer server.Close()
code, _ := (&Server{}).probeVhostReady(probePort(t, server), "a.example.com")
if code != http.StatusBadGateway {
t.Fatalf("期望原样返回 502,实际 %d", code)
}
if hits != 1 {
t.Fatalf("502 不应重试,实际探测 %d 次", hits)
}
}
// TestProbeVhostReadyGivesUpAfterAttempts:一直 404 时用尽重试次数并返回最后一次结果。
func TestProbeVhostReadyGivesUpAfterAttempts(t *testing.T) {
stubProbeRetry(t, 3)
var hits int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
atomic.AddInt32(&hits, 1)
w.WriteHeader(http.StatusNotFound)
}))
defer server.Close()
code, _ := (&Server{}).probeVhostReady(probePort(t, server), "a.example.com")
if code != http.StatusNotFound {
t.Fatalf("期望最终仍为 404,实际 %d", code)
}
if hits != 3 {
t.Fatalf("期望探测 3 次后放弃,实际 %d 次", hits)
}
}
+115
View File
@@ -0,0 +1,115 @@
package agent
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestValidateRoute(t *testing.T) {
cases := []struct {
name string
req routeRequest
ok bool
}{
{"正常", routeRequest{Domain: "a.example.com", Upstream: "127.0.0.1:8080"}, true},
{"非法域名", routeRequest{Domain: "bad domain", Upstream: "127.0.0.1:8080"}, false},
{"空上游", routeRequest{Domain: "a.example.com"}, false},
{"上游带分号", routeRequest{Domain: "a.example.com", Upstream: "127.0.0.1:80; rm -rf /"}, false},
{"相对证书目录", routeRequest{Domain: "a.example.com", Upstream: "127.0.0.1:80", TLS: true, CertDir: "certs"}, false},
}
for _, c := range cases {
err := validateRoute(c.req)
if c.ok && err != nil {
t.Errorf("%s:期望通过,实际 %v", c.name, err)
}
if !c.ok && err == nil {
t.Errorf("%s:期望报错", c.name)
}
}
}
// TestNginxRouteRendersUpstream:vhost 模板的关键行(标记、server_name、proxy_pass)。
// 不构造 Basic Auth 场景——那条路径会往 /var/lib/havline-agent 写 htpasswd,不适合在单测里触发。
func TestNginxRouteRendersUpstream(t *testing.T) {
out := nginxRoute(routeRequest{Domain: "a.example.com", Upstream: "127.0.0.1:8080"}, "")
if !strings.HasPrefix(out, "# Managed by havline-agent.") {
t.Errorf("缺少托管标记,其它工具无法识别该文件归属:\n%s", out)
}
if !strings.Contains(out, "server_name a.example.com;") {
t.Errorf("缺少 server_name:\n%s", out)
}
if !strings.Contains(out, "proxy_pass http://127.0.0.1:8080;") {
t.Errorf("缺少 proxy_pass 回源:\n%s", out)
}
if strings.Contains(out, "listen 443") {
t.Errorf("未启用 TLS 时不应监听 443:\n%s", out)
}
}
// TestNginxRouteSharedTemplateSemantics 锁定共享模板迁出后的关键语义与顺序。
func TestNginxRouteSharedTemplateSemantics(t *testing.T) {
out := nginxRoute(routeRequest{
Domain: "a.example.com",
Upstream: "127.0.0.1:8080",
TLS: true,
RedirectTLS: true,
SecurityHeaders: true,
WebSocket: true,
AllowIPs: []string{"192.168.1.0/24"},
DenyIPs: []string{"8.8.8.8"},
RateLimitRate: 10,
RateLimitBurst: 20,
ConnLimitMax: 5,
ChinaOnly: true,
}, "/etc/havline-agent/certs/a.example.com")
for _, want := range []string{
"ssl_protocols TLSv1.2 TLSv1.3;",
`add_header Referrer-Policy "strict-origin-when-cross-origin" always;`,
"deny 8.8.8.8;",
"if ($havline_china_client = 0) { return 403; }",
"allow 192.168.1.0/24;",
"deny all;",
"limit_conn havline_a_example_com_conn 5;",
"limit_req zone=havline_a_example_com_req burst=20 nodelay;",
"proxy_set_header Upgrade $http_upgrade;",
`proxy_set_header Connection "upgrade";`,
} {
if !strings.Contains(out, want) {
t.Fatalf("缺少 %q:\n%s", want, out)
}
}
denyIdx := strings.Index(out, "deny 8.8.8.8;")
// WebSocket 头必须落在 location 内部:location 自定义 proxy_set_header 后,
// server 级的那组不会被继承,写在 server 块里等于没生效(升级请求会一直挂起)
locationIdx := strings.Index(out, "location / {")
upgradeIdx := strings.Index(out, "proxy_set_header Upgrade $http_upgrade;")
if locationIdx < 0 || upgradeIdx < 0 || upgradeIdx < locationIdx {
t.Fatalf("Upgrade 头必须写在 location 内:\n%s", out)
}
if !strings.Contains(out, "proxy_read_timeout 3600s;") {
t.Fatalf("WebSocket 未配读超时时应给长连接默认超时:\n%s", out)
}
allowIdx := strings.Index(out, "allow 192.168.1.0/24;")
denyAllIdx := strings.Index(out, "deny all;")
if denyIdx < 0 || allowIdx < 0 || denyAllIdx < 0 || !(denyIdx < allowIdx && allowIdx < denyAllIdx) {
t.Fatalf("allow / deny 顺序不正确:\n%s", out)
}
}
// TestFileSHA256 覆盖 frps 安装包的校验路径。
func TestFileSHA256(t *testing.T) {
path := filepath.Join(t.TempDir(), "payload.txt")
if err := os.WriteFile(path, []byte("hello"), 0o600); err != nil {
t.Fatal(err)
}
got, err := fileSHA256(path)
if err != nil {
t.Fatal(err)
}
const want = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
if got != want {
t.Fatalf("sha256 不符:got %s", got)
}
}
+29
View File
@@ -0,0 +1,29 @@
package agent
import (
"net/http"
"net/http/httptest"
"regexp"
"testing"
)
var agentRouteParamPattern = regexp.MustCompile(`\{[^}]+\}`)
// TestAgentRoutesRequireToken 遍历全部 Agent API:匿名请求必须 401,防止新增路由漏挂 auth。
func TestAgentRoutesRequireToken(t *testing.T) {
server := &Server{cfg: Config{Token: "secret-token"}}
routes := agentRoutes(server)
if len(routes) < 20 {
t.Fatalf("Agent 路由覆盖不足:%d 条", len(routes))
}
handler := server.Handler()
for _, route := range routes {
path := agentRouteParamPattern.ReplaceAllString(route.Pattern, "1")
req := httptest.NewRequest(route.Method, path, nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("路由 %s %s 匿名请求应返回 401,实际 %d", route.Method, route.Pattern, rec.Code)
}
}
}
File diff suppressed because it is too large Load Diff
+317
View File
@@ -0,0 +1,317 @@
package agent
import (
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/havline/havline/internal/fsutil"
"github.com/havline/havline/internal/nginxtmpl"
)
const (
httpsProxyConfigName = "havlineagent-https.conf"
httpsProxyCertPath = "/etc/havline-agent/tls/agent.crt"
httpsProxyKeyPath = "/etc/havline-agent/tls/agent.key"
)
type httpsProxyRequest struct {
CertPEM string `json:"cert_pem"`
KeyPEM string `json:"key_pem"`
Port int `json:"port"`
}
type httpsProxyState struct {
Port int `json:"port"`
}
func (s *Server) putHTTPSProxy(w http.ResponseWriter, r *http.Request) {
var req httpsProxyRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 2<<20)).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
if req.Port < 0 || req.Port > 65535 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "端口需在 0-65535 之间,0 表示自动选择"})
return
}
if _, err := tls.X509KeyPair([]byte(req.CertPEM), []byte(req.KeyPEM)); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "证书或私钥格式无效"})
return
}
if probe := s.probeNginx(); probe.Missing {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "VPS 未安装 Nginx,无法启用 HTTPS 直连"})
return
}
s.mu.Lock()
defer s.mu.Unlock()
port, err := s.configureHTTPSProxy(req)
if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()})
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "port": port, "self_check": "ok"})
}
func (s *Server) deleteHTTPSProxy(w http.ResponseWriter, _ *http.Request) {
s.mu.Lock()
defer s.mu.Unlock()
if err := s.removeHTTPSProxy(); err != nil {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()})
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
// getHTTPSProxy 返回当前 HTTPS 反代状态与证书到期时间,供中央端同步轮换计划。
func (s *Server) getHTTPSProxy(w http.ResponseWriter, _ *http.Request) {
s.mu.Lock()
defer s.mu.Unlock()
state, enabled := readHTTPSProxyState(s.cfg.DataDir)
notAfter := ""
if t, err := readCertificateNotAfter(httpsProxyCertPath); err == nil {
notAfter = t.UTC().Format(time.RFC3339)
}
writeJSON(w, http.StatusOK, map[string]any{
"enabled": enabled,
"port": state.Port,
"not_after": notAfter,
})
}
// configureHTTPSProxy 按候选端口逐个尝试;请求端口为 0 时自动选择 7443 / 8443 / 9443。
func (s *Server) configureHTTPSProxy(req httpsProxyRequest) (int, error) {
var lastErr error
for _, port := range candidateHTTPSPorts(req.Port) {
if err := s.applyHTTPSProxy(req, port); err != nil {
lastErr = fmt.Errorf("端口 %d 不可用: %w", port, err)
continue
}
return port, nil
}
if lastErr == nil {
lastErr = errors.New("没有可用的 HTTPS 端口")
}
return 0, lastErr
}
func candidateHTTPSPorts(requested int) []int {
if requested > 0 {
return []int{requested}
}
return []int{7443, 8443, 9443}
}
func (s *Server) applyHTTPSProxy(req httpsProxyRequest, port int) error {
dir, err := s.ensureNginxDir()
if err != nil {
return err
}
tlsDir := "/etc/havline-agent/tls"
if err := os.MkdirAll(tlsDir, 0o750); err != nil {
return err
}
if err := atomicWrite(httpsProxyCertPath, []byte(req.CertPEM), 0o640); err != nil {
return err
}
if err := atomicWrite(httpsProxyKeyPath, []byte(req.KeyPEM), 0o600); err != nil {
return err
}
path := filepath.Join(dir, httpsProxyConfigName)
previous, readErr := os.ReadFile(path)
if _, err := fsutil.BackupVersioned(path, 10); err != nil {
return err
}
content := renderHTTPSProxy(port, httpsProxyCertPath, httpsProxyKeyPath)
if err := atomicWrite(path, []byte(content), 0o640); err != nil {
return err
}
if err := s.validateNginx(); err != nil {
s.restoreHTTPSConfig(path, previous, readErr)
return fmt.Errorf("nginx config rejected: %w", err)
}
if err := s.reloadNginx(); err != nil {
s.restoreHTTPSConfig(path, previous, readErr)
return err
}
pin, err := certificatePin(req.CertPEM)
if err != nil {
return err
}
if err := s.verifyHTTPSProxy(port, pin); err != nil {
s.restoreHTTPSConfig(path, previous, readErr)
return err
}
return writeHTTPSProxyState(s.cfg.DataDir, httpsProxyState{Port: port})
}
func (s *Server) removeHTTPSProxy() error {
dir, err := s.ensureNginxDir()
if err != nil {
return err
}
path := filepath.Join(dir, httpsProxyConfigName)
previous, readErr := os.ReadFile(path)
if errors.Is(readErr, os.ErrNotExist) {
_ = os.Remove(httpsProxyStatePath(s.cfg.DataDir))
return nil
}
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
if err := s.validateNginx(); err != nil {
s.restoreHTTPSConfig(path, previous, readErr)
return err
}
if err := s.reloadNginx(); err != nil {
s.restoreHTTPSConfig(path, previous, readErr)
return err
}
_ = os.Remove(httpsProxyStatePath(s.cfg.DataDir))
return nil
}
func (s *Server) restoreHTTPSConfig(path string, previous []byte, readErr error) {
if readErr == nil {
_ = atomicWrite(path, previous, 0o640)
} else {
_ = os.Remove(path)
}
_ = s.reloadNginx()
}
func (s *Server) ensureNginxDir() (string, error) {
dir := strings.TrimSpace(s.cfg.NginxConfDir)
if dir != "" {
return dir, nil
}
dir, err := detectNginxConfDir(s.nginxPath())
if err != nil {
return "", err
}
s.cfg.NginxConfDir = dir
return dir, nil
}
func renderHTTPSProxy(port int, certPath, keyPath string) string {
return fmt.Sprintf(`# Managed by havline-agent. Do not edit.
server {
listen %d ssl default_server;
server_name _;
%s
location /api/v1/ {
proxy_pass http://127.0.0.1:7700;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Authorization $http_authorization;
}
}
`, port, nginxtmpl.SSLDirectives(nginxtmpl.TLSConfig{CertPath: certPath, KeyPath: keyPath}))
}
func certificatePin(certPEM string) (string, error) {
block, _ := pem.Decode([]byte(certPEM))
if block == nil {
return "", errors.New("证书 PEM 解码失败")
}
sum := sha256.Sum256(block.Bytes)
return hex.EncodeToString(sum[:]), nil
}
// verifyHTTPSProxy 在 reload 后从本机回环地址握手,确认 7443 上真正返回的就是刚写入的证书。
// nginx reload 是异步的,这里留出短暂重试窗口,避免旧 worker 造成的瞬时误判。
func (s *Server) verifyHTTPSProxy(port int, want string) error {
deadline := time.Now().Add(5 * time.Second)
var lastErr error
for {
lastErr = probeHTTPSPin(port, want)
if lastErr == nil {
return nil
}
if time.Now().After(deadline) {
return lastErr
}
time.Sleep(500 * time.Millisecond)
}
}
func probeHTTPSPin(port int, want string) error {
addr := net.JoinHostPort("127.0.0.1", strconv.Itoa(port))
dialer := &net.Dialer{Timeout: 3 * time.Second}
conn, err := tls.DialWithDialer(dialer, "tcp", addr, &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS12})
if err != nil {
return fmt.Errorf("本机 https://%s 自检失败:%w;%s", addr, err, portListenerHint(port))
}
defer conn.Close()
certs := conn.ConnectionState().PeerCertificates
if len(certs) == 0 {
return fmt.Errorf("本机 https://%s 未返回证书;%s", addr, portListenerHint(port))
}
sum := sha256.Sum256(certs[0].Raw)
got := hex.EncodeToString(sum[:])
if !strings.EqualFold(got, want) {
return fmt.Errorf("本机 https://%s 证书指纹不匹配:期望 %s,实际 %s;%s", addr, want, got, portListenerHint(port))
}
return nil
}
// portListenerHint 把监听该端口的进程信息带进错误里,便于区分 nginx 未生效与端口被其他服务占用。
func portListenerHint(port int) string {
out, err := exec.Command("ss", "-tlnp").CombinedOutput()
if err != nil {
return "无法读取端口监听信息"
}
suffix := ":" + strconv.Itoa(port)
lines := make([]string, 0, 2)
for _, line := range strings.Split(string(out), "\n") {
if strings.Contains(line, suffix+" ") || strings.HasSuffix(strings.TrimSpace(line), suffix) {
lines = append(lines, strings.TrimSpace(line))
}
}
if len(lines) == 0 {
return "未发现监听 " + suffix + " 的进程"
}
return "监听 " + suffix + ":" + strings.Join(lines, " | ")
}
func httpsProxyStatePath(dataDir string) string {
return filepath.Join(dataDir, "https_transport.json")
}
func writeHTTPSProxyState(dataDir string, state httpsProxyState) error {
if strings.TrimSpace(dataDir) == "" {
return nil
}
data, err := json.Marshal(state)
if err != nil {
return err
}
return atomicWrite(httpsProxyStatePath(dataDir), data, 0o640)
}
func readHTTPSProxyState(dataDir string) (httpsProxyState, bool) {
data, err := os.ReadFile(httpsProxyStatePath(dataDir))
if err != nil {
return httpsProxyState{}, false
}
var state httpsProxyState
if err := json.Unmarshal(data, &state); err != nil || state.Port <= 0 {
return httpsProxyState{}, false
}
return state, true
}
+127
View File
@@ -0,0 +1,127 @@
package agent
import (
"fmt"
"net/http"
"os"
"strings"
"time"
"github.com/havline/havline/internal/fsutil"
)
// maxRouteVersions 每个域名 vhost 保留的版本份数。内容相同的写入会被 fsutil 去重,
// 因此这里对应的是最近 10 次「配置真的变了」的改动。
const maxRouteVersions = 10
type routeVersionInfo struct {
Name string `json:"name"`
Size int64 `json:"size"`
CreatedAt time.Time `json:"created_at"`
}
// routeVersions 返回某域名的当前配置与历史版本,供应用侧把「漂移」与「历史」放在一起看。
func (s *Server) routeVersions(w http.ResponseWriter, r *http.Request) {
domain := strings.ToLower(strings.TrimSpace(r.PathValue("domain")))
if !validDomain(domain) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid domain"})
return
}
s.mu.Lock()
defer s.mu.Unlock()
path := s.routePath(domain)
content, err := os.ReadFile(path)
if err != nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "该域名尚未部署反代"})
return
}
versions, err := fsutil.ListVersions(path)
if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()})
return
}
writeJSON(w, http.StatusOK, map[string]any{
"domain": domain,
"content": string(content),
"versions": mapRouteVersions(versions),
})
}
// routeVersion 返回某个历史版本的内容(前端拿它与当前配置做差异对比)。
func (s *Server) routeVersion(w http.ResponseWriter, r *http.Request) {
domain := strings.ToLower(strings.TrimSpace(r.PathValue("domain")))
if !validDomain(domain) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid domain"})
return
}
name := r.PathValue("name")
s.mu.Lock()
defer s.mu.Unlock()
content, err := fsutil.ReadVersion(s.routePath(domain), name)
if err != nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": err.Error()})
return
}
writeJSON(w, http.StatusOK, map[string]any{"domain": domain, "name": name, "content": string(content)})
}
// rollbackRoute 把某域名的 vhost 回退到指定版本。
func (s *Server) rollbackRoute(w http.ResponseWriter, r *http.Request) {
domain := strings.ToLower(strings.TrimSpace(r.PathValue("domain")))
if !validDomain(domain) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid domain"})
return
}
name := r.PathValue("name")
s.mu.Lock()
defer s.mu.Unlock()
path := s.routePath(domain)
content, err := fsutil.ReadVersion(path, name)
if err != nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": err.Error()})
return
}
if err := s.applyRouteContent(path, content); err != nil {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()})
return
}
if err := s.reloadRouteConfig(); err != nil {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": err.Error()})
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "domain": domain, "name": name})
}
// applyRouteContent 写入 vhost 内容并做 nginx -t 校验。
//
// 写之前先把当前内容留成一个版本;校验失败时恢复回上一个可用版本(此前没有文件才删除)。
// 旧行为是校验失败直接删文件——那等于把已经在跑的站点从磁盘上抹掉,只能靠重新部署救回来。
func (s *Server) applyRouteContent(path string, content []byte) error {
previous, readErr := os.ReadFile(path)
if _, err := fsutil.BackupVersioned(path, maxRouteVersions); err != nil {
return err
}
if err := atomicWrite(path, content, 0o640); err != nil {
return err
}
if err := s.validateRouteConfig(); err != nil {
if readErr == nil {
_ = atomicWrite(path, previous, 0o640)
} else {
_ = os.Remove(path)
}
return fmt.Errorf("nginx config rejected: %w", err)
}
return nil
}
func mapRouteVersions(entries []fsutil.VersionEntry) []routeVersionInfo {
out := make([]routeVersionInfo, 0, len(entries))
for _, entry := range entries {
out = append(out, routeVersionInfo{Name: entry.Name, Size: entry.Size, CreatedAt: entry.CreatedAt})
}
return out
}
+182
View File
@@ -0,0 +1,182 @@
package agent
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"errors"
"math/big"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
"github.com/havline/havline/internal/fsutil"
)
func TestMigrateLegacyVersionDirs(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "havlineagent-https.conf")
legacy := path + ".versions"
if err := os.MkdirAll(legacy, 0o700); err != nil {
t.Fatal(err)
}
name := "20260101T000000.000-abcd.conf"
if err := os.WriteFile(filepath.Join(legacy, name), []byte("old"), 0o600); err != nil {
t.Fatal(err)
}
migrateLegacyVersionDirs(dir)
if _, err := os.Stat(legacy); !os.IsNotExist(err) {
t.Fatalf("旧版本目录应被移出 nginx include 范围:%v", err)
}
entries, err := os.ReadDir(filepath.Join(dir, ".havlineagent-https.conf.versions"))
if err != nil || len(entries) != 1 {
t.Fatalf("隐藏版本目录应保留 1 个版本:%v %v", entries, err)
}
}
func TestMigrateVersionDirsFromNginxOutput(t *testing.T) {
dir := t.TempDir()
legacy := filepath.Join(dir, "havlineagent-https.conf.versions")
if err := os.MkdirAll(legacy, 0o700); err != nil {
t.Fatal(err)
}
output := "2026/09/28 14:38:16 [crit] 6053#6053: pread() \"" + legacy + "\" failed (21: Is a directory)"
if !migrateVersionDirsFromNginxOutput(output) {
t.Fatal("应从 nginx 报错文本中识别并迁移旧版本目录")
}
if _, err := os.Stat(legacy); !os.IsNotExist(err) {
t.Fatalf("旧版本目录应被移出 include 范围:%v", err)
}
}
func TestCertificatePin(t *testing.T) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
template := &x509.Certificate{
SerialNumber: big.NewInt(1),
NotBefore: time.Now().Add(-time.Minute),
NotAfter: time.Now().Add(time.Hour),
}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
block := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
got, err := certificatePin(string(block))
if err != nil {
t.Fatal(err)
}
sum := sha256.Sum256(der)
if want := hex.EncodeToString(sum[:]); got != want {
t.Fatalf("certificatePin() = %s, 期望 %s", got, want)
}
}
func TestApplyRouteContentSavesPreviousVersion(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "havline-a.example.com.conf")
if err := os.WriteFile(path, []byte("old config"), 0o640); err != nil {
t.Fatal(err)
}
server := &Server{cfg: Config{NginxConfDir: dir}, validateNginxFn: func() error { return nil }}
if err := server.applyRouteContent(path, []byte("new config")); err != nil {
t.Fatal(err)
}
current, err := os.ReadFile(path)
if err != nil || string(current) != "new config" {
t.Fatalf("当前配置未更新:%q %v", current, err)
}
versions, err := fsutil.ListVersions(path)
if err != nil || len(versions) != 1 {
t.Fatalf("写 vhost 前应保存上一版本:%v %v", versions, err)
}
previous, err := fsutil.ReadVersion(path, versions[0].Name)
if err != nil || string(previous) != "old config" {
t.Fatalf("历史版本内容不符:%q %v", previous, err)
}
}
func TestApplyRouteContentRestoresOnValidationFailure(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "havline-a.example.com.conf")
if err := os.WriteFile(path, []byte("old config"), 0o640); err != nil {
t.Fatal(err)
}
server := &Server{
cfg: Config{NginxConfDir: dir},
validateNginxFn: func() error { return errors.New("nginx rejected") },
}
if err := server.applyRouteContent(path, []byte("new config")); err == nil {
t.Fatal("校验失败应返回错误")
}
current, err := os.ReadFile(path)
if err != nil || string(current) != "old config" {
t.Fatalf("校验失败后应恢复上一可用版本:%q %v", current, err)
}
}
func TestApplyRouteContentRemovesNewFileOnValidationFailure(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "havline-new.example.com.conf")
server := &Server{
cfg: Config{NginxConfDir: dir},
validateNginxFn: func() error { return errors.New("nginx rejected") },
}
if err := server.applyRouteContent(path, []byte("new config")); err == nil {
t.Fatal("校验失败应返回错误")
}
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatalf("首次部署失败应删除新文件,避免留下坏配置:%v", err)
}
}
func TestRollbackRouteReloadsAfterApply(t *testing.T) {
dir := t.TempDir()
reloaded := false
server := &Server{
cfg: Config{NginxConfDir: dir},
validateNginxFn: func() error { return nil },
reloadNginxFn: func() error { reloaded = true; return nil },
}
path := server.routePath("a.example.com")
if err := os.WriteFile(path, []byte("healthy"), 0o640); err != nil {
t.Fatal(err)
}
if _, err := fsutil.BackupVersioned(path, maxRouteVersions); err != nil {
t.Fatal(err)
}
versions, err := fsutil.ListVersions(path)
if err != nil || len(versions) != 1 {
t.Fatalf("准备版本失败:%v %v", versions, err)
}
if err := os.WriteFile(path, []byte("broken"), 0o640); err != nil {
t.Fatal(err)
}
mux := http.NewServeMux()
mux.HandleFunc("POST /api/v1/routes/{domain}/versions/{name}/rollback", server.rollbackRoute)
req := httptest.NewRequest(http.MethodPost, "/api/v1/routes/a.example.com/versions/"+versions[0].Name+"/rollback", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("回滚应成功:%d %s", rec.Code, rec.Body.String())
}
if !reloaded {
t.Fatal("回滚后应执行 nginx reload")
}
current, err := os.ReadFile(path)
if err != nil || string(current) != "healthy" {
t.Fatalf("回滚后内容不符:%q %v", current, err)
}
}
+214
View File
@@ -0,0 +1,214 @@
package api
import (
"encoding/json"
"errors"
"net"
"net/http"
"strings"
"sync"
"time"
"github.com/havline/havline/internal/auth"
"github.com/havline/havline/internal/notify"
)
type AuthHandler struct {
auth *auth.Service
notify *notify.Service
guard *loginGuard
unlocks *terminalUnlockStore
}
// NewAuthHandler 装配登录处理器;unlocks 是终端二次认证票据,改密后要让当前会话立即失效。
func NewAuthHandler(authSvc *auth.Service, notifySvc *notify.Service, unlocks *terminalUnlockStore) *AuthHandler {
return &AuthHandler{auth: authSvc, notify: notifySvc, guard: newLoginGuard(), unlocks: unlocks}
}
const (
loginFailureLimit = 5
loginLockoutWindow = 5 * time.Minute
)
// loginGuard 是进程内的登录失败退避:同一 IP 在窗口内失败到阈值后直接拒绝,
// 避免明文 HTTP 部署下被无限爆破;与用于通知的失败统计相互独立。
type loginGuard struct {
mu sync.Mutex
failures map[string][]time.Time
}
func newLoginGuard() *loginGuard {
return &loginGuard{failures: make(map[string][]time.Time)}
}
// blocked 返回该 IP 是否仍在锁定窗口内(顺带清理过期记录)。
func (g *loginGuard) blocked(ip string) bool {
g.mu.Lock()
defer g.mu.Unlock()
kept := g.recentLocked(ip)
g.failures[ip] = kept
return len(kept) >= loginFailureLimit
}
func (g *loginGuard) fail(ip string) {
g.mu.Lock()
defer g.mu.Unlock()
if len(g.failures) > 1024 {
for key := range g.failures {
if len(g.recentLocked(key)) == 0 {
delete(g.failures, key)
}
}
}
g.failures[ip] = append(g.recentLocked(ip), time.Now())
}
func (g *loginGuard) reset(ip string) {
g.mu.Lock()
defer g.mu.Unlock()
delete(g.failures, ip)
}
// recentLocked 返回窗口内的失败时间(调用方需持有锁)。
func (g *loginGuard) recentLocked(ip string) []time.Time {
now := time.Now()
kept := make([]time.Time, 0, len(g.failures[ip]))
for _, at := range g.failures[ip] {
if now.Sub(at) < loginLockoutWindow {
kept = append(kept, at)
}
}
return kept
}
type loginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type authStatusResponse struct {
Initialized bool `json:"initialized"`
Authenticated bool `json:"authenticated"`
}
func (h *AuthHandler) Status(w http.ResponseWriter, r *http.Request) {
initialized, err := h.auth.IsInitialized(r.Context())
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取初始化状态失败")
return
}
authenticated := false
if sessionID := sessionIDFromContext(r.Context()); sessionID != "" {
if err := h.auth.ValidateSession(r.Context(), sessionID); err == nil {
authenticated = true
}
}
writeJSON(w, http.StatusOK, authStatusResponse{
Initialized: initialized,
Authenticated: authenticated,
})
}
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
var req loginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
ip := clientIP(r)
if h.guard.blocked(ip) {
writeError(r, w, http.StatusTooManyRequests, "登录失败次数过多,请稍后再试")
return
}
sessionID, err := h.auth.Login(r.Context(), req.Username, req.Password)
if err != nil {
if errors.Is(err, auth.ErrUnauthorized) {
h.guard.fail(ip)
if h.notify != nil {
h.notify.RecordLoginFailure(r.Context(), ip)
}
writeError(r, w, http.StatusUnauthorized, "用户名或密码错误")
return
}
writeError(r, w, http.StatusInternalServerError, "登录失败")
return
}
h.guard.reset(ip)
setSessionCookie(w, r, sessionID)
writeJSON(w, http.StatusOK, map[string]string{"message": "登录成功"})
}
func (h *AuthHandler) ChangePassword(w http.ResponseWriter, r *http.Request) {
var req struct {
OldPassword string `json:"old_password"`
NewPassword string `json:"new_password"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
sessionID := sessionIDFromContext(r.Context())
adminID, err := h.auth.AdminIDForSession(r.Context(), sessionID)
if err != nil {
writeError(r, w, http.StatusUnauthorized, "未登录或会话已过期")
return
}
if err := h.auth.ChangePassword(r.Context(), adminID, req.OldPassword, req.NewPassword, sessionID); err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
// 改密后当前会话的终端解锁票据立即作废:密码都换了,不该还留着已解锁的 shell
if h.unlocks != nil {
h.unlocks.revoke(sessionID)
}
writeJSON(w, http.StatusOK, map[string]string{"message": "密码已更新"})
}
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
if sessionID := sessionIDFromContext(r.Context()); sessionID != "" {
_ = h.auth.Logout(r.Context(), sessionID)
}
clearSessionCookie(w, r)
writeJSON(w, http.StatusOK, map[string]string{"message": "已退出登录"})
}
func setSessionCookie(w http.ResponseWriter, r *http.Request, sessionID string) {
http.SetCookie(w, &http.Cookie{
Name: "havline_session",
Value: sessionID,
Path: "/",
HttpOnly: true,
Secure: requestIsHTTPS(r),
SameSite: http.SameSiteLaxMode,
MaxAge: int((7 * 24 * time.Hour).Seconds()),
})
}
// requestIsHTTPS:直连 TLS 或经反代(X-Forwarded-Proto)时给会话 cookie 加 Secure;
// 默认明文 HTTP 部署下不加,否则浏览器会直接丢弃 cookie 导致登录不了。
func requestIsHTTPS(r *http.Request) bool {
if r.TLS != nil {
return true
}
return strings.EqualFold(strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")), "https")
}
func clientIP(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return strings.TrimSpace(r.RemoteAddr)
}
return host
}
func clearSessionCookie(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
Name: "havline_session",
Value: "",
Path: "/",
HttpOnly: true,
Secure: requestIsHTTPS(r),
SameSite: http.SameSiteLaxMode,
MaxAge: -1,
})
}
+96
View File
@@ -0,0 +1,96 @@
package api
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"github.com/havline/havline/internal/auth"
"github.com/havline/havline/internal/backup"
"github.com/havline/havline/internal/certificate"
"github.com/havline/havline/internal/config"
"github.com/havline/havline/internal/db"
"github.com/havline/havline/internal/discovery"
"github.com/havline/havline/internal/proxy"
"github.com/havline/havline/internal/service"
"github.com/havline/havline/internal/settings"
)
func TestAuthSetupAndLoginFlow(t *testing.T) {
conn, err := db.Open(filepath.Join(t.TempDir(), "havline.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
defer conn.Close()
if err := db.Migrate(context.Background(), conn, filepath.Join("..", "..", "migrations")); err != nil {
t.Fatalf("migrate: %v", err)
}
tmpDir := t.TempDir()
authSvc := auth.New(conn)
proxySvc := service.NewProxyService(config.Config{DataDir: tmpDir, NginxPIDFile: tmpDir + "/nginx.pid"}, conn, proxy.NewStore(conn), certificate.NewStore(conn), settings.NewStore(conn), nil)
handler := NewRouter(Deps{
Config: config.Config{DataDir: tmpDir, NginxPIDFile: tmpDir + "/nginx.pid"},
Auth: authSvc,
Proxy: proxySvc,
Backup: backup.New(tmpDir),
Discovery: discovery.New(),
StartedAt: time.Now().UTC().Format(time.RFC3339),
})
statusReq := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil)
statusRec := httptest.NewRecorder()
handler.ServeHTTP(statusRec, statusReq)
if statusRec.Code != http.StatusOK {
t.Fatalf("status code: %d", statusRec.Code)
}
if err := authSvc.Setup(context.Background(), "admin", "password123"); err != nil {
t.Fatalf("setup admin: %v", err)
}
loginBody, _ := json.Marshal(map[string]string{
"username": "admin",
"password": "password123",
})
loginReq := httptest.NewRequest(http.MethodPost, "/api/auth/login", bytes.NewReader(loginBody))
loginRec := httptest.NewRecorder()
handler.ServeHTTP(loginRec, loginReq)
if loginRec.Code != http.StatusOK {
t.Fatalf("login status: %d body=%s", loginRec.Code, loginRec.Body.String())
}
cookie := loginRec.Result().Cookies()[0]
if cookie.Name != "havline_session" || cookie.HttpOnly == false {
t.Fatal("expected httponly session cookie")
}
authStatusReq := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil)
authStatusReq.AddCookie(cookie)
authStatusRec := httptest.NewRecorder()
handler.ServeHTTP(authStatusRec, authStatusReq)
if authStatusRec.Code != http.StatusOK {
t.Fatalf("auth status code: %d", authStatusRec.Code)
}
var authStatus authStatusResponse
if err := json.Unmarshal(authStatusRec.Body.Bytes(), &authStatus); err != nil {
t.Fatalf("decode auth status: %v", err)
}
if !authStatus.Initialized || !authStatus.Authenticated {
t.Fatalf("expected authenticated status, got %+v", authStatus)
}
proxiesReq := httptest.NewRequest(http.MethodGet, "/api/proxies", nil)
proxiesReq.AddCookie(cookie)
proxiesRec := httptest.NewRecorder()
handler.ServeHTTP(proxiesRec, proxiesReq)
if proxiesRec.Code != http.StatusOK {
t.Fatalf("proxies status: %d", proxiesRec.Code)
}
}
+176
View File
@@ -0,0 +1,176 @@
package api
import (
"io"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/havline/havline/internal/backup"
"github.com/havline/havline/internal/settings"
)
type BackupHandler struct {
svc *backup.Service
settings *settings.Store
}
func NewBackupHandler(svc *backup.Service, settingsStore *settings.Store) *BackupHandler {
return &BackupHandler{svc: svc, settings: settingsStore}
}
// passphraseFromHeader 读取可选的归档口令。
// 放在请求头而不是查询串:查询串会进访问日志,口令不该落盘。
func passphraseFromHeader(r *http.Request) string {
return strings.TrimSpace(r.Header.Get("X-Backup-Passphrase"))
}
func (h *BackupHandler) Export(w http.ResponseWriter, r *http.Request) {
path, err := h.svc.ExportWith(r.Context(), backup.Options{Passphrase: passphraseFromHeader(r)})
if err != nil {
writeError(r, w, http.StatusInternalServerError, "创建备份失败")
return
}
defer os.Remove(path)
file, err := os.Open(path)
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取备份失败")
return
}
defer file.Close()
w.Header().Set("Content-Type", "application/gzip")
w.Header().Set("Content-Disposition", "attachment; filename="+filepath.Base(path))
_, _ = io.Copy(w, file)
}
func (h *BackupHandler) Restore(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(64 << 20); err != nil {
writeError(r, w, http.StatusBadRequest, "上传文件无效")
return
}
file, _, err := r.FormFile("file")
if err != nil {
writeError(r, w, http.StatusBadRequest, "请选择备份文件")
return
}
defer file.Close()
// 上传文件名完全由客户端控制:不能拼进临时路径(../ 可逃出临时目录),交给 CreateTemp 生成
out, err := os.CreateTemp("", "havline-restore-*.tar.gz")
if err != nil {
writeError(r, w, http.StatusInternalServerError, "保存上传文件失败")
return
}
tmpPath := out.Name()
if _, err := io.Copy(out, file); err != nil {
out.Close()
_ = os.Remove(tmpPath)
writeError(r, w, http.StatusInternalServerError, "保存上传文件失败")
return
}
out.Close()
if err := h.svc.RestoreWith(r.Context(), tmpPath, backup.Options{Passphrase: passphraseFromHeader(r)}); err != nil {
_ = os.Remove(tmpPath)
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
_ = os.Remove(tmpPath)
writeJSON(w, http.StatusOK, map[string]string{"message": "备份已恢复,建议重启 Havline"})
}
// ListArchives 列出留在磁盘上的备份(自动备份 + 手动「立即备份」)。
// 与「立即下载」不同:这些文件长期留在 <DataDir>/backups 下。
func (h *BackupHandler) ListArchives(w http.ResponseWriter, r *http.Request) {
archives, err := h.svc.List()
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取备份列表失败", err)
return
}
writeJSON(w, http.StatusOK, map[string]any{
"archives": archives,
"keep": backup.KeepCount(r.Context(), h.settings),
})
}
// CreateArchive 立即备份一份并保留在服务器上,顺带按保留份数剪枝
func (h *BackupHandler) CreateArchive(w http.ResponseWriter, r *http.Request) {
opts := backup.Options{Passphrase: passphraseFromHeader(r)}
path, err := h.svc.ExportWith(r.Context(), opts)
if err != nil {
writeError(r, w, http.StatusInternalServerError, "创建备份失败", err)
return
}
name := filepath.Base(path)
// 写失败的备份不能留在列表里冒充可用备份
if _, err := h.svc.VerifyWith(r.Context(), path, opts); err != nil {
_ = h.svc.Remove(name)
writeError(r, w, http.StatusInternalServerError, "备份校验失败:"+err.Error(), err)
return
}
removed, err := h.svc.Prune(backup.KeepCount(r.Context(), h.settings))
if err != nil {
writeError(r, w, http.StatusInternalServerError, "备份已创建,但清理旧备份失败:"+err.Error(), err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"name": name, "removed": removed})
}
// DownloadArchive 下载指定备份;用 ServeContent 支持断点续传
func (h *BackupHandler) DownloadArchive(w http.ResponseWriter, r *http.Request) {
path, err := h.svc.Path(r.PathValue("name"))
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
file, err := os.Open(path)
if err != nil {
writeError(r, w, http.StatusNotFound, "备份不存在")
return
}
defer file.Close()
info, err := file.Stat()
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取备份失败", err)
return
}
w.Header().Set("Content-Type", "application/gzip")
w.Header().Set("Content-Disposition", "attachment; filename="+filepath.Base(path))
http.ServeContent(w, r, filepath.Base(path), info.ModTime(), file)
}
// RestoreArchive 从指定备份恢复。恢复会覆盖数据库与证书,前端必须二次确认
func (h *BackupHandler) RestoreArchive(w http.ResponseWriter, r *http.Request) {
path, err := h.svc.Path(r.PathValue("name"))
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
opts := backup.Options{Passphrase: passphraseFromHeader(r)}
// 恢复前先校验:半个包不能拿去覆盖现有数据
if _, err := h.svc.VerifyWith(r.Context(), path, opts); err != nil {
writeError(r, w, http.StatusBadRequest, "该备份不可用:"+err.Error(), err)
return
}
if err := h.svc.RestoreWith(r.Context(), path, opts); err != nil {
writeError(r, w, http.StatusBadRequest, err.Error(), err)
return
}
writeJSON(w, http.StatusOK, map[string]string{"message": "备份已恢复,建议重启 Havline"})
}
// DeleteArchive 删除指定备份
func (h *BackupHandler) DeleteArchive(w http.ResponseWriter, r *http.Request) {
if err := h.svc.Remove(r.PathValue("name")); err != nil {
if err.Error() == "备份不存在" {
writeError(r, w, http.StatusNotFound, err.Error())
return
}
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
+159
View File
@@ -0,0 +1,159 @@
package api
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/havline/havline/internal/acme"
)
type CertHandler struct {
svc *acme.Service
}
func NewCertHandler(svc *acme.Service) *CertHandler {
return &CertHandler{svc: svc}
}
func (h *CertHandler) List(w http.ResponseWriter, r *http.Request) {
records, err := h.svc.List(r.Context())
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取证书失败")
return
}
writeJSON(w, http.StatusOK, records)
}
func (h *CertHandler) Options(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, []map[string]string{
{"value": acme.CALetsEncrypt, "label": acme.CALabel(acme.CALetsEncrypt)},
{"value": acme.CAZeroSSL, "label": acme.CALabel(acme.CAZeroSSL)},
// Buypass 已于 2025-10-15 停止签发、2026-04-15 终止 ACME 服务,不再列为可选 CA
// (历史记录仍能展示,直接提交会被 CAUnavailableReason 抦下);LiteSSL 接替其位置。
{"value": acme.CALiteSSL, "label": acme.CALabel(acme.CALiteSSL)},
{"value": acme.CALetsEncryptStaging, "label": acme.CALabel(acme.CALetsEncryptStaging)},
})
}
func (h *CertHandler) Apply(w http.ResponseWriter, r *http.Request) {
var req struct {
Domain string `json:"domain"`
DNSZone string `json:"dns_zone"`
DDNSConfigID int64 `json:"ddns_config_id"`
Domains []string `json:"domains"`
CA string `json:"ca"`
Email string `json:"email"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
domains := req.Domains
if len(domains) == 0 && strings.TrimSpace(req.Domain) != "" {
domains = []string{req.Domain}
}
if req.DDNSConfigID <= 0 {
writeError(r, w, http.StatusBadRequest, "请选择 DNS 任务")
return
}
jobID, err := h.svc.StartApply(r.Context(), domains, req.CA, req.Email, req.DDNSConfigID)
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusAccepted, map[string]string{"job_id": jobID})
}
func (h *CertHandler) ApplyJobStream(w http.ResponseWriter, r *http.Request) {
jobID := strings.TrimSpace(r.PathValue("id"))
if jobID == "" {
writeError(r, w, http.StatusBadRequest, "无效的任务 ID")
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
flusher, ok := w.(http.Flusher)
if !ok {
writeError(r, w, http.StatusInternalServerError, "SSE 不可用")
return
}
if err := h.svc.StreamJob(r.Context(), w, jobID, func() error {
flusher.Flush()
return nil
}); err != nil {
return
}
}
func (h *CertHandler) Import(w http.ResponseWriter, r *http.Request) {
var req struct {
Certificate string `json:"certificate"`
PrivateKey string `json:"private_key"`
CertPath string `json:"cert_path"`
KeyPath string `json:"key_path"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
record, err := h.svc.Import(r.Context(), req.Certificate, req.PrivateKey, req.CertPath, req.KeyPath)
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, record)
}
func (h *CertHandler) Download(w http.ResponseWriter, r *http.Request) {
domain := strings.TrimSpace(r.PathValue("domain"))
if domain == "" {
writeError(r, w, http.StatusBadRequest, "域名不能为空")
return
}
part := r.URL.Query().Get("part")
filename, contentType, data, err := h.svc.Download(r.Context(), domain, part)
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(data)))
w.WriteHeader(http.StatusOK)
_, _ = w.Write(data)
}
func (h *CertHandler) Delete(w http.ResponseWriter, r *http.Request) {
domain := strings.TrimSpace(r.PathValue("domain"))
if domain == "" {
writeError(r, w, http.StatusBadRequest, "域名不能为空")
return
}
if err := h.svc.Delete(r.Context(), domain); err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]string{"message": "证书已删除"})
}
func (h *CertHandler) Renew(w http.ResponseWriter, r *http.Request) {
var req struct {
Domain string `json:"domain"`
CA string `json:"ca"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
record, err := h.svc.Renew(r.Context(), req.Domain, req.CA)
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, record)
}
+29
View File
@@ -0,0 +1,29 @@
package api
import (
"net/http"
"github.com/havline/havline/internal/chinacidr"
)
type ChinaCIDRHandler struct {
svc *chinacidr.Service
}
func NewChinaCIDRHandler(svc *chinacidr.Service) *ChinaCIDRHandler {
return &ChinaCIDRHandler{svc: svc}
}
func (h *ChinaCIDRHandler) Status(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, h.svc.Status(r.Context()))
}
func (h *ChinaCIDRHandler) Refresh(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if err := h.svc.Update(ctx); err != nil {
h.svc.RecordLastError(ctx, err)
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, h.svc.Status(ctx))
}
+404
View File
@@ -0,0 +1,404 @@
package api
import (
"context"
"encoding/json"
"net/http"
"strconv"
"strings"
"github.com/havline/havline/internal/cloudflared"
)
type CloudflareHandler struct {
svc *cloudflared.Service
}
func NewCloudflareHandler(svc *cloudflared.Service) *CloudflareHandler {
return &CloudflareHandler{svc: svc}
}
func (h *CloudflareHandler) List(w http.ResponseWriter, r *http.Request) {
items, err := h.svc.List(r.Context())
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, items)
}
func (h *CloudflareHandler) Get(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "隧道 ID 无效")
return
}
item, err := h.svc.Get(r.Context(), id)
if err != nil {
writeError(r, w, http.StatusNotFound, err.Error())
return
}
writeJSON(w, http.StatusOK, item)
}
func (h *CloudflareHandler) Create(w http.ResponseWriter, r *http.Request) {
var input cloudflared.CreateInput
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&input); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
input.Network = normalizeCloudflareNetwork(input.Network)
item, err := h.svc.Create(r.Context(), input)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, item)
}
func (h *CloudflareHandler) Update(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "隧道 ID 无效")
return
}
var input cloudflared.CreateInput
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&input); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
input.Network = normalizeCloudflareNetwork(input.Network)
item, err := h.svc.Update(r.Context(), id, input)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, item)
}
func (h *CloudflareHandler) Delete(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "隧道 ID 无效")
return
}
if err := h.svc.Delete(r.Context(), id); err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
func (h *CloudflareHandler) Start(w http.ResponseWriter, r *http.Request) {
h.tunnelAction(w, r, h.svc.Start)
}
func (h *CloudflareHandler) Stop(w http.ResponseWriter, r *http.Request) {
h.tunnelAction(w, r, h.svc.Stop)
}
func (h *CloudflareHandler) Restart(w http.ResponseWriter, r *http.Request) {
h.tunnelAction(w, r, h.svc.Restart)
}
func (h *CloudflareHandler) RefreshCredentials(w http.ResponseWriter, r *http.Request) {
h.tunnelAction(w, r, h.svc.RefreshCredentials)
}
func (h *CloudflareHandler) tunnelAction(w http.ResponseWriter, r *http.Request, fn func(context.Context, int64) (cloudflared.Tunnel, error)) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "隧道 ID 无效")
return
}
item, err := fn(r.Context(), id)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, item)
}
func (h *CloudflareHandler) Status(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "隧道 ID 无效")
return
}
status, err := h.svc.RuntimeStatus(r.Context(), id)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, status)
}
func (h *CloudflareHandler) Logs(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "隧道 ID 无效")
return
}
lines, _ := strconv.Atoi(strings.TrimSpace(r.URL.Query().Get("lines")))
output, err := h.svc.Logs(r.Context(), id, lines)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"output": output})
}
func (h *CloudflareHandler) Config(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "隧道 ID 无效")
return
}
content, err := h.svc.PreviewConfig(r.Context(), id)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"content": content})
}
func (h *CloudflareHandler) Routes(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "隧道 ID 无效")
return
}
routes, err := h.svc.Routes(r.Context(), id)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, routes)
}
func (h *CloudflareHandler) ReplaceRoutes(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "隧道 ID 无效")
return
}
var request struct {
Routes []cloudflared.RouteInput `json:"routes"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&request); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
routes, err := h.svc.ReplaceRoutes(r.Context(), id, request.Routes)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, routes)
}
func (h *CloudflareHandler) Drift(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "隧道 ID 无效")
return
}
result, err := h.svc.Drift(r.Context(), id)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, result)
}
func (h *CloudflareHandler) SyncRoutes(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "隧道 ID 无效")
return
}
if err := h.svc.PushTunnel(r.Context(), id); err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
func (h *CloudflareHandler) Diagnostics(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "隧道 ID 无效")
return
}
result, err := h.svc.Diagnostics(r.Context(), id)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, result)
}
func (h *CloudflareHandler) Preflight(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, h.svc.Preflight(r.Context()))
}
func (h *CloudflareHandler) TestRoute(w http.ResponseWriter, r *http.Request) {
var request struct {
Service string `json:"service"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&request); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
result, err := h.svc.TestService(r.Context(), request.Service)
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, result)
}
func (h *CloudflareHandler) BinaryInfo(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"version": h.svc.BinaryVersion(),
"mirrors": cloudflared.DefaultMirrors(),
})
}
func (h *CloudflareHandler) AppSettings(w http.ResponseWriter, r *http.Request) {
settings, err := h.svc.AppSettings(r.Context())
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, settings)
}
func (h *CloudflareHandler) SaveAppSettings(w http.ResponseWriter, r *http.Request) {
var input cloudflared.AppSettingsInput
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&input); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
input.Network = normalizeCloudflareNetwork(input.Network)
settings, err := h.svc.SaveAppSettings(r.Context(), input)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, settings)
}
func (h *CloudflareHandler) TestToken(w http.ResponseWriter, r *http.Request) {
var request struct {
AccountID string `json:"account_id"`
Token string `json:"token"`
Kind string `json:"kind"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&request); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
message, err := h.svc.TestToken(r.Context(), request.AccountID, request.Token, request.Kind)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": message})
}
func (h *CloudflareHandler) SetEnabled(w http.ResponseWriter, r *http.Request) {
var request struct {
Enabled bool `json:"enabled"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
settings, err := h.svc.SetEnabled(r.Context(), request.Enabled)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, settings)
}
func (h *CloudflareHandler) DownloadBinary(w http.ResponseWriter, r *http.Request) {
var request struct {
Mirror string `json:"mirror"`
Version string `json:"version"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
version, err := h.svc.DownloadBinaryVersion(r.Context(), request.Mirror, request.Version)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "version": version})
}
func (h *CloudflareHandler) LatestBinary(w http.ResponseWriter, r *http.Request) {
version, err := h.svc.LatestBinaryVersion(r.Context())
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"version": version})
}
func (h *CloudflareHandler) RollbackBinary(w http.ResponseWriter, r *http.Request) {
version, err := h.svc.RollbackBinary()
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "version": version})
}
func (h *CloudflareHandler) IngressCandidates(w http.ResponseWriter, r *http.Request) {
hosts, err := h.svc.IngressCandidates(r.Context())
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"hostnames": hosts})
}
func (h *CloudflareHandler) Zones(w http.ResponseWriter, r *http.Request) {
zones, err := h.svc.Zones(r.Context())
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"zones": zones})
}
func (h *CloudflareHandler) AccessStatus(w http.ResponseWriter, r *http.Request) {
hostname := strings.TrimSpace(r.URL.Query().Get("hostname"))
enabled, name, err := h.svc.AccessStatus(r.Context(), hostname)
if err != nil {
writeError(r, w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"enabled": enabled, "name": name})
}
func normalizeCloudflareNetwork(network cloudflared.NetworkSettings) cloudflared.NetworkSettings {
defaults := cloudflared.DefaultNetworkSettings()
if strings.TrimSpace(network.TransportProtocol) == "" {
network.TransportProtocol = defaults.TransportProtocol
}
if strings.TrimSpace(network.EdgeIPVersion) == "" {
network.EdgeIPVersion = defaults.EdgeIPVersion
}
if network.HAConnections <= 0 {
network.HAConnections = defaults.HAConnections
}
if strings.TrimSpace(network.ProxyMode) == "" {
network.ProxyMode = defaults.ProxyMode
}
return network
}
+162
View File
@@ -0,0 +1,162 @@
package api
import (
"encoding/json"
"net/http"
"strconv"
"github.com/havline/havline/internal/ddns"
)
type DDNSHandler struct {
svc *ddns.Service
}
func NewDDNSHandler(svc *ddns.Service) *DDNSHandler {
return &DDNSHandler{svc: svc}
}
type ddnsRequest struct {
Provider string `json:"provider"`
Name string `json:"name"`
RootDomain string `json:"root_domain"`
RecordName string `json:"record_name"`
RecordNames []string `json:"record_names"`
Domains []string `json:"domains"`
IPv4Enabled *bool `json:"ipv4_enabled"`
IPv6Enabled *bool `json:"ipv6_enabled"`
Enabled *bool `json:"enabled"`
CustomIPv4 string `json:"custom_ipv4"`
CustomIPv6 string `json:"custom_ipv6"`
APIToken string `json:"api_token"`
APITokenID string `json:"api_token_id"`
APISecret string `json:"api_secret"`
}
func (h *DDNSHandler) toInput(req ddnsRequest) ddns.SaveInput {
return ddns.SaveInput{
Provider: req.Provider,
Name: req.Name,
RootDomain: req.RootDomain,
RecordName: req.RecordName,
RecordNames: req.RecordNames,
Domains: req.Domains,
IPv4Enabled: boolDefault(req.IPv4Enabled, true),
IPv6Enabled: boolDefault(req.IPv6Enabled, false),
Enabled: boolDefault(req.Enabled, true),
CustomIPv4: req.CustomIPv4,
CustomIPv6: req.CustomIPv6,
APIToken: req.APIToken,
APITokenID: req.APITokenID,
APISecret: req.APISecret,
}
}
func (h *DDNSHandler) List(w http.ResponseWriter, r *http.Request) {
var configs []ddns.Config
var err error
if r.URL.Query().Get("lite") == "1" {
configs, err = h.svc.ListLite(r.Context())
} else {
configs, err = h.svc.List(r.Context())
}
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取 DDNS 配置失败")
return
}
writeJSON(w, http.StatusOK, configs)
}
func (h *DDNSHandler) Create(w http.ResponseWriter, r *http.Request) {
var req ddnsRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
cfg, err := h.svc.Create(r.Context(), h.toInput(req))
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, cfg)
}
func (h *DDNSHandler) Update(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
writeError(r, w, http.StatusBadRequest, "无效的配置 ID")
return
}
var req ddnsRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
cfg, err := h.svc.Update(r.Context(), id, h.toInput(req))
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, cfg)
}
func (h *DDNSHandler) Delete(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
writeError(r, w, http.StatusBadRequest, "无效的配置 ID")
return
}
if err := h.svc.Delete(r.Context(), id); err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *DDNSHandler) Test(w http.ResponseWriter, r *http.Request) {
var req struct {
ConfigID int64 `json:"config_id"`
Provider string `json:"provider"`
APIToken string `json:"api_token"`
APITokenID string `json:"api_token_id"`
APISecret string `json:"api_secret"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
if err := h.svc.Test(r.Context(), ddns.TestInput{
ConfigID: req.ConfigID,
Provider: req.Provider,
APIToken: req.APIToken,
APITokenID: req.APITokenID,
APISecret: req.APISecret,
}); err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]string{"message": "连接成功"})
}
func (h *DDNSHandler) UpdateOne(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
writeError(r, w, http.StatusBadRequest, "无效的配置 ID")
return
}
cfg, err := h.svc.UpdateNow(r.Context(), id)
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, cfg)
}
func (h *DDNSHandler) UpdateAll(w http.ResponseWriter, r *http.Request) {
configs, err := h.svc.UpdateAll(r.Context())
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, configs)
}
+52
View File
@@ -0,0 +1,52 @@
package api
import (
"io/fs"
"log/slog"
"github.com/havline/havline/internal/acme"
"github.com/havline/havline/internal/auth"
"github.com/havline/havline/internal/backup"
"github.com/havline/havline/internal/chinacidr"
"github.com/havline/havline/internal/cloudflared"
"github.com/havline/havline/internal/config"
"github.com/havline/havline/internal/ddns"
"github.com/havline/havline/internal/discovery"
"github.com/havline/havline/internal/frp"
"github.com/havline/havline/internal/metrics"
"github.com/havline/havline/internal/notify"
"github.com/havline/havline/internal/service"
"github.com/havline/havline/internal/settings"
"github.com/havline/havline/internal/terminal"
"github.com/havline/havline/internal/traffic"
"github.com/havline/havline/internal/updater"
)
type Deps struct {
Config config.Config
Logger *slog.Logger
Auth *auth.Service
Proxy *service.ProxyService
DDNS *ddns.Service
ACME *acme.Service
Settings *settings.Store
ChinaCIDR *chinacidr.Service
Backup *backup.Service
Metrics *metrics.Store
Discovery *discovery.Service
FRPMulti *frp.Service
Cloudflare *cloudflared.Service
Traffic *traffic.Collector
Notify *notify.Service
Updater *updater.Client
StaticFS fs.FS
StartedAt string
// Terminal 是内置 SSH 终端的会话管理器;为 nil 时相关接口不注册
Terminal *terminal.Manager
// TerminalAudits 是终端会话审计存储;为 nil 时不注册审计接口
TerminalAudits *terminal.AuditStore
// TerminalCommands 是终端常用命令存储;为 nil 时常用命令接口返回空
TerminalCommands *terminal.CommandStore
// TerminalRecordings 是会话录制存储;为 nil 时录制接口返回空
TerminalRecordings *terminal.RecordingStore
}
+20
View File
@@ -0,0 +1,20 @@
package api
import (
"net/http"
"github.com/havline/havline/internal/discovery"
)
type DiscoveryHandler struct {
svc *discovery.Service
}
func NewDiscoveryHandler(svc *discovery.Service) *DiscoveryHandler {
return &DiscoveryHandler{svc: svc}
}
func (h *DiscoveryHandler) Scan(w http.ResponseWriter, r *http.Request) {
host := r.URL.Query().Get("host")
writeJSON(w, http.StatusOK, h.svc.Scan(r.Context(), host))
}
File diff suppressed because it is too large Load Diff
+128
View File
@@ -0,0 +1,128 @@
package api
import (
"net/http"
"path/filepath"
"strconv"
"github.com/havline/havline/internal/config"
"github.com/havline/havline/internal/logstore"
)
type LogsHandler struct {
cfg config.Config
}
func NewLogsHandler(cfg config.Config) *LogsHandler {
return &LogsHandler{cfg: cfg}
}
func (h *LogsHandler) Access(w http.ResponseWriter, r *http.Request) {
limit := queryInt(r, "limit", 100)
keyword := r.URL.Query().Get("keyword")
status := queryInt(r, "status", 0)
entries, err := logstore.ReadAccess(filepath.Join(h.cfg.LogsDir(), "access.log"), limit, keyword, status)
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取访问日志失败")
return
}
writeJSON(w, http.StatusOK, entries)
}
func (h *LogsHandler) Error(w http.ResponseWriter, r *http.Request) {
limit := queryInt(r, "limit", 100)
keyword := r.URL.Query().Get("keyword")
lines, err := logstore.ReadError(filepath.Join(h.cfg.LogsDir(), "error.log"), limit, keyword)
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取错误日志失败")
return
}
writeJSON(w, http.StatusOK, lines)
}
func (h *LogsHandler) System(w http.ResponseWriter, r *http.Request) {
limit := queryInt(r, "limit", 100)
level := r.URL.Query().Get("level")
keyword := r.URL.Query().Get("keyword")
entries, err := logstore.ReadSystem(filepath.Join(h.cfg.LogsDir(), "app.log"), limit, level, keyword)
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取系统日志失败")
return
}
writeJSON(w, http.StatusOK, entries)
}
func (h *LogsHandler) Stream(w http.ResponseWriter, r *http.Request) {
kind := r.URL.Query().Get("type")
if kind == "" {
kind = "error"
}
var path string
switch kind {
case "access":
path = filepath.Join(h.cfg.LogsDir(), "access.log")
case "error":
path = filepath.Join(h.cfg.LogsDir(), "error.log")
default:
writeError(r, w, http.StatusBadRequest, "实时日志仅支持 Nginx 访问/错误日志")
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
flusher, ok := w.(http.Flusher)
if !ok {
writeError(r, w, http.StatusInternalServerError, "SSE 不可用")
return
}
tail := queryInt(r, "tail", 100)
var filter logstore.LineFilter
if kind == "access" {
filter = logstore.AccessHostFilter(r.URL.Query()["host"])
}
_ = logstore.StreamFile(r.Context(), path, w, func() error {
flusher.Flush()
return nil
}, tail, filter)
}
func (h *LogsHandler) StreamAccessForHosts(w http.ResponseWriter, r *http.Request, hosts []string) {
endpoints := make([]logstore.AccessEndpoint, 0, len(hosts))
for _, host := range hosts {
endpoints = append(endpoints, logstore.AccessEndpoint{Host: host})
}
h.StreamAccessForEndpoints(w, r, endpoints)
}
func (h *LogsHandler) StreamAccessForEndpoints(w http.ResponseWriter, r *http.Request, endpoints []logstore.AccessEndpoint) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
flusher, ok := w.(http.Flusher)
if !ok {
writeError(r, w, http.StatusInternalServerError, "SSE 不可用")
return
}
path := filepath.Join(h.cfg.LogsDir(), "access.log")
tail := queryInt(r, "tail", 100)
filter := logstore.AccessEndpointFilter(endpoints)
_ = logstore.StreamFile(r.Context(), path, w, func() error {
flusher.Flush()
return nil
}, tail, filter)
}
func queryInt(r *http.Request, key string, fallback int) int {
raw := r.URL.Query().Get(key)
if raw == "" {
return fallback
}
n, err := strconv.Atoi(raw)
if err != nil {
return fallback
}
return n
}
+65
View File
@@ -0,0 +1,65 @@
package api
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"github.com/havline/havline/internal/auth"
"github.com/havline/havline/internal/backup"
"github.com/havline/havline/internal/certificate"
"github.com/havline/havline/internal/config"
"github.com/havline/havline/internal/db"
"github.com/havline/havline/internal/discovery"
"github.com/havline/havline/internal/proxy"
"github.com/havline/havline/internal/service"
"github.com/havline/havline/internal/settings"
)
func TestLogsAccessRoute(t *testing.T) {
dir := t.TempDir()
conn, err := db.Open(filepath.Join(dir, "havline.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
defer conn.Close()
if err := db.Migrate(context.Background(), conn, filepath.Join("..", "..", "migrations")); err != nil {
t.Fatalf("migrate: %v", err)
}
authSvc := auth.New(conn)
if err := authSvc.Setup(context.Background(), "admin", "password123"); err != nil {
t.Fatalf("setup: %v", err)
}
sessionID, err := authSvc.Login(context.Background(), "admin", "password123")
if err != nil {
t.Fatalf("login: %v", err)
}
handler := NewRouter(Deps{
Config: config.Config{DataDir: dir, NginxPIDFile: filepath.Join(dir, "nginx.pid")},
Auth: authSvc,
Proxy: service.NewProxyService(config.Config{DataDir: dir, NginxPIDFile: filepath.Join(dir, "nginx.pid")}, conn, proxy.NewStore(conn), certificate.NewStore(conn), settings.NewStore(conn), nil),
Backup: backup.New(dir),
Discovery: discovery.New(),
StartedAt: time.Now().UTC().Format(time.RFC3339),
})
req := httptest.NewRequest(http.MethodGet, "/api/logs/access?limit=100", nil)
req.AddCookie(&http.Cookie{Name: "havline_session", Value: sessionID})
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", rec.Code, rec.Body.String())
}
var body []map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("invalid json: %v", err)
}
}
+47
View File
@@ -0,0 +1,47 @@
package api
import (
"net/http"
"strconv"
"time"
"github.com/havline/havline/internal/metrics"
)
type MetricsHandler struct {
store *metrics.Store
}
func NewMetricsHandler(store *metrics.Store) *MetricsHandler {
return &MetricsHandler{store: store}
}
// History 返回指标历史:窗口内的序列已按桶取平均,前端拿到就能直接画。
// hours 最多 30 天(=保留期),buckets 最多 metrics.MaxBuckets。
func (h *MetricsHandler) History(w http.ResponseWriter, r *http.Request) {
hours := 24
if raw := r.URL.Query().Get("hours"); raw != "" {
if parsed, err := strconv.Atoi(raw); err == nil && parsed > 0 && parsed <= 24*30 {
hours = parsed
}
}
buckets := 48
if raw := r.URL.Query().Get("buckets"); raw != "" {
if parsed, err := strconv.Atoi(raw); err == nil && parsed > 0 {
buckets = parsed
}
}
if buckets > metrics.MaxBuckets {
buckets = metrics.MaxBuckets
}
series, err := h.store.Query(r.Context(), time.Duration(hours)*time.Hour, buckets)
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取指标历史失败", err)
return
}
writeJSON(w, http.StatusOK, map[string]any{
"hours": hours,
"buckets": buckets,
"series": series,
})
}
+88
View File
@@ -0,0 +1,88 @@
package api
import (
"context"
"net/http"
"strings"
"github.com/havline/havline/internal/auth"
)
type contextKey string
const sessionContextKey contextKey = "session_id"
func SessionMiddleware(authSvc *auth.Service) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("havline_session")
if err == nil && cookie.Value != "" {
ctx := context.WithValue(r.Context(), sessionContextKey, cookie.Value)
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
})
}
}
// RequireAuth 接受两种凭据:浏览器的会话 cookie,以及 Authorization: Bearer <api token>。
// 令牌分读写两种范围:read 只允许 GET/HEAD,write 与会话同权。
func RequireAuth(authSvc *auth.Service) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if token := bearerToken(r); token != "" {
scope, err := authSvc.ValidateAPIToken(r.Context(), token)
if err != nil {
writeError(r, w, http.StatusUnauthorized, "API Token 无效或已过期")
return
}
// 账号与令牌管理只允许浏览器会话:否则一个 write 令牌可以自己给自己提权
if tokenDeniedPath(r.URL.Path) {
writeError(r, w, http.StatusForbidden, "该操作需要使用登录会话")
return
}
if scope != auth.TokenScopeWrite && r.Method != http.MethodGet && r.Method != http.MethodHead {
writeError(r, w, http.StatusForbidden, "该 Token 只读,不能执行写操作")
return
}
next.ServeHTTP(w, r)
return
}
sessionID, _ := r.Context().Value(sessionContextKey).(string)
if err := authSvc.ValidateSession(r.Context(), sessionID); err != nil {
writeError(r, w, http.StatusUnauthorized, "未登录或会话已过期")
return
}
next.ServeHTTP(w, r)
})
}
}
// bearerToken 取出 Authorization: Bearer 里的明文令牌;没有或格式不对返回空串。
func bearerToken(r *http.Request) string {
header := strings.TrimSpace(r.Header.Get("Authorization"))
const prefix = "Bearer "
if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) {
return ""
}
return strings.TrimSpace(header[len(prefix):])
}
// tokenDeniedPath 是只允许浏览器会话的路径(账号与令牌管理,以及需要二次认证的终端)。
func tokenDeniedPath(path string) bool {
if path == "/api/auth/password" || path == "/api/auth/logout" {
return true
}
// 终端是 root shell 入口:API Token 不能绕过二次认证,一律要求浏览器会话
if strings.HasPrefix(path, "/api/terminal") {
return true
}
return strings.HasPrefix(path, "/api/settings/tokens") ||
strings.HasPrefix(path, "/api/system/update")
}
func sessionIDFromContext(ctx context.Context) string {
v, _ := ctx.Value(sessionContextKey).(string)
return v
}
+130
View File
@@ -0,0 +1,130 @@
package api
import (
"context"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"github.com/havline/havline/internal/auth"
"github.com/havline/havline/internal/db"
)
func newTokenTestAuth(t *testing.T, scope string) (*auth.Service, string) {
t.Helper()
conn, err := db.Open(filepath.Join(t.TempDir(), "havline.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
t.Cleanup(func() { _ = conn.Close() })
if err := db.Migrate(context.Background(), conn, filepath.Join("..", "..", "migrations")); err != nil {
t.Fatalf("migrate: %v", err)
}
svc := auth.New(conn)
created, err := svc.CreateAPIToken(context.Background(), "test", scope, time.Time{})
if err != nil {
t.Fatalf("create token: %v", err)
}
return svc, created.Token
}
func okTokenHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }
}
func TestRequireAuthAcceptsReadTokenForGet(t *testing.T) {
svc, plain := newTokenTestAuth(t, auth.TokenScopeRead)
handler := RequireAuth(svc)(okTokenHandler())
req := httptest.NewRequest(http.MethodGet, "/api/status", nil)
req.Header.Set("Authorization", "Bearer "+plain)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("只读令牌应能读,实际 %d", rec.Code)
}
}
func TestRequireAuthBlocksWriteForReadToken(t *testing.T) {
svc, plain := newTokenTestAuth(t, auth.TokenScopeRead)
handler := RequireAuth(svc)(okTokenHandler())
req := httptest.NewRequest(http.MethodDelete, "/api/proxies/1", nil)
req.Header.Set("Authorization", "Bearer "+plain)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("只读令牌不应能写,实际 %d", rec.Code)
}
}
func TestRequireAuthAllowsWriteForWriteToken(t *testing.T) {
svc, plain := newTokenTestAuth(t, auth.TokenScopeWrite)
handler := RequireAuth(svc)(okTokenHandler())
req := httptest.NewRequest(http.MethodPost, "/api/proxies", nil)
req.Header.Set("Authorization", "Bearer "+plain)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("写令牌应能写,实际 %d", rec.Code)
}
}
func TestRequireAuthTokenCannotManageTokens(t *testing.T) {
// 写令牌也不能管理令牌:否则等于拿令牌给自己提权或无限续期
svc, plain := newTokenTestAuth(t, auth.TokenScopeWrite)
handler := RequireAuth(svc)(okTokenHandler())
req := httptest.NewRequest(http.MethodGet, "/api/settings/tokens", nil)
req.Header.Set("Authorization", "Bearer "+plain)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("令牌管理应只允许登录会话,实际 %d", rec.Code)
}
}
func TestRequireAuthRejectsBadCredentials(t *testing.T) {
svc, _ := newTokenTestAuth(t, auth.TokenScopeRead)
handler := RequireAuth(svc)(okTokenHandler())
cases := map[string]string{
"未知令牌": "Bearer deadbeef",
"错误前缀": "Token abc",
"没有凭据": "",
}
for name, header := range cases {
req := httptest.NewRequest(http.MethodGet, "/api/status", nil)
if header != "" {
req.Header.Set("Authorization", header)
}
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("%s 应返回 401,实际 %d", name, rec.Code)
}
}
}
func TestBearerTokenParsing(t *testing.T) {
cases := map[string]string{
"Bearer abc": "abc",
"bearer abc": "abc",
"Bearer abc": "abc",
"Basic abc": "",
"Bearer ": "",
"": "",
}
for header, want := range cases {
req := httptest.NewRequest(http.MethodGet, "/", nil)
if header != "" {
req.Header.Set("Authorization", header)
}
if got := bearerToken(req); got != want {
t.Fatalf("Authorization %q 解析为 %q,期望 %q", header, got, want)
}
}
}
+163
View File
@@ -0,0 +1,163 @@
package api
import (
"encoding/json"
"net/http"
"github.com/havline/havline/internal/service"
)
type NginxHandler struct {
proxy *service.ProxyService
}
func NewNginxHandler(proxy *service.ProxyService) *NginxHandler {
return &NginxHandler{proxy: proxy}
}
type saveRuleNginxRequest struct {
Mode string `json:"mode"`
Content *string `json:"content"`
}
type rollbackNginxRequest struct {
Backup string `json:"backup"`
}
func (h *NginxHandler) GetRule(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "无效的规则 ID")
return
}
view, err := h.proxy.GetRuleNginx(r.Context(), id)
if err != nil {
writeServiceError(r, w, err)
return
}
writeJSON(w, http.StatusOK, view)
}
func (h *NginxHandler) PutRule(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "无效的规则 ID")
return
}
var req saveRuleNginxRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
view, err := h.proxy.SaveRuleNginx(r.Context(), id, service.SaveRuleNginxInput{
Mode: req.Mode,
Content: req.Content,
})
if err != nil {
writeServiceError(r, w, err)
return
}
writeJSON(w, http.StatusOK, view)
}
func (h *NginxHandler) RollbackRule(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "无效的规则 ID")
return
}
var req rollbackNginxRequest
if r.Body != nil && r.ContentLength != 0 {
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
}
view, err := h.proxy.RollbackRuleNginx(r.Context(), id, req.Backup)
if err != nil {
writeServiceError(r, w, err)
return
}
writeJSON(w, http.StatusOK, view)
}
func (h *NginxHandler) GetGlobal(w http.ResponseWriter, r *http.Request) {
view, err := h.proxy.GetGlobalNginx(r.Context())
if err != nil {
writeServiceError(r, w, err)
return
}
writeJSON(w, http.StatusOK, view)
}
func (h *NginxHandler) PutGlobal(w http.ResponseWriter, r *http.Request) {
var req saveRuleNginxRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
view, err := h.proxy.SaveGlobalNginx(r.Context(), service.SaveGlobalNginxInput{
Mode: req.Mode,
Content: req.Content,
})
if err != nil {
writeServiceError(r, w, err)
return
}
writeJSON(w, http.StatusOK, view)
}
func (h *NginxHandler) RollbackGlobal(w http.ResponseWriter, r *http.Request) {
var req rollbackNginxRequest
if r.Body != nil && r.ContentLength != 0 {
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
}
view, err := h.proxy.RollbackGlobalNginx(r.Context(), req.Backup)
if err != nil {
writeServiceError(r, w, err)
return
}
writeJSON(w, http.StatusOK, view)
}
func (h *NginxHandler) GetConfigVersions(w http.ResponseWriter, r *http.Request) {
view, err := h.proxy.GetNginxConfigVersions()
if err != nil {
writeServiceError(r, w, err)
return
}
writeJSON(w, http.StatusOK, view)
}
func (h *NginxHandler) GetConfigVersion(w http.ResponseWriter, r *http.Request) {
view, err := h.proxy.ReadNginxConfigVersion(r.PathValue("name"))
if err != nil {
writeServiceError(r, w, err)
return
}
writeJSON(w, http.StatusOK, view)
}
func (h *NginxHandler) RollbackConfigVersion(w http.ResponseWriter, r *http.Request) {
view, err := h.proxy.RollbackNginxConfigVersion(r.Context(), r.PathValue("name"))
if err != nil {
writeServiceError(r, w, err)
return
}
writeJSON(w, http.StatusOK, view)
}
func writeServiceError(r *http.Request, w http.ResponseWriter, err error) {
if err == nil {
return
}
msg := err.Error()
if msg == "规则不存在" {
writeError(r, w, http.StatusNotFound, msg, err)
return
}
writeError(r, w, http.StatusBadRequest, msg, err)
}
+33
View File
@@ -0,0 +1,33 @@
package api
import (
"encoding/json"
"net/http"
"github.com/havline/havline/internal/notify"
)
type NotifyHandler struct {
notify *notify.Service
}
func NewNotifyHandler(notifySvc *notify.Service) *NotifyHandler {
return &NotifyHandler{notify: notifySvc}
}
func (h *NotifyHandler) Test(w http.ResponseWriter, r *http.Request) {
if h.notify == nil {
writeError(r, w, http.StatusInternalServerError, "通知服务未初始化")
return
}
var req notify.TestInput
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
if err := h.notify.SendTest(r.Context(), req); err != nil {
writeError(r, w, http.StatusBadRequest, err.Error(), err)
return
}
writeJSON(w, http.StatusOK, map[string]string{"message": "测试通知已发送"})
}
+277
View File
@@ -0,0 +1,277 @@
package api
import (
"encoding/json"
"net/http"
"strconv"
"github.com/havline/havline/internal/config"
"github.com/havline/havline/internal/logstore"
"github.com/havline/havline/internal/proxy"
"github.com/havline/havline/internal/service"
"github.com/havline/havline/internal/traffic"
)
type ProxyHandler struct {
cfg config.Config
svc *service.ProxyService
logs *LogsHandler
traffic *traffic.Collector
}
func NewProxyHandler(cfg config.Config, svc *service.ProxyService, logs *LogsHandler, collector *traffic.Collector) *ProxyHandler {
return &ProxyHandler{cfg: cfg, svc: svc, logs: logs, traffic: collector}
}
type proxyRequest struct {
Domain string `json:"domain"`
Upstream string `json:"upstream"`
ListenPort *int `json:"listen_port"`
ListenIPv4 *bool `json:"listen_ipv4"`
ListenIPv6 *bool `json:"listen_ipv6"`
Hosts []string `json:"hosts"`
HTTPSEnabled *bool `json:"https_enabled"`
HTTPRedirect *bool `json:"http_redirect"`
Enabled *bool `json:"enabled"`
Name *string `json:"name"`
Remark *string `json:"remark"` // deprecated alias for name
Security *securityRequest `json:"security,omitempty"`
Exits []string `json:"exits"`
CFTunnelID *int64 `json:"cf_tunnel_id"`
}
type proxyReorderRequest struct {
IDs []int64 `json:"ids"`
}
func (h *ProxyHandler) List(w http.ResponseWriter, r *http.Request) {
rules, err := h.svc.List(r.Context())
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取反向代理规则失败")
return
}
writeJSON(w, http.StatusOK, proxy.RulesForAPI(rules))
}
func (h *ProxyHandler) Create(w http.ResponseWriter, r *http.Request) {
var req proxyRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
hosts := req.hosts()
if len(hosts) == 0 {
writeError(r, w, http.StatusBadRequest, "至少需要一个前端域名")
return
}
listenPort := intDefault(req.ListenPort, h.cfg.DefaultListenPort(boolDefault(req.HTTPSEnabled, true)))
name := ""
if resolved := req.resolveName(); resolved != nil {
name = *resolved
}
in := proxy.CreateInput{
Upstream: req.Upstream,
ListenPort: listenPort,
ListenIPv4: boolDefault(req.ListenIPv4, true),
ListenIPv6: boolDefault(req.ListenIPv6, false),
Hosts: hosts,
HTTPSEnabled: boolDefault(req.HTTPSEnabled, true),
HTTPRedirect: boolDefault(req.HTTPRedirect, true),
Enabled: boolDefault(req.Enabled, true),
Name: name,
Security: req.securityInput(),
Exits: req.Exits,
CFTunnelID: int64Default(req.CFTunnelID, 0),
}
rule, err := h.svc.Create(r.Context(), in)
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusCreated, proxy.RuleForAPI(rule))
}
func (h *ProxyHandler) Update(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "无效的规则 ID")
return
}
var req proxyRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
in := proxy.UpdateInput{}
if req.Upstream != "" {
in.Upstream = &req.Upstream
}
if req.ListenPort != nil {
in.ListenPort = req.ListenPort
}
if req.ListenIPv4 != nil {
in.ListenIPv4 = req.ListenIPv4
}
if req.ListenIPv6 != nil {
in.ListenIPv6 = req.ListenIPv6
}
if hosts := req.hosts(); len(hosts) > 0 {
in.Hosts = &hosts
}
if req.HTTPSEnabled != nil {
in.HTTPSEnabled = req.HTTPSEnabled
}
if req.HTTPRedirect != nil {
in.HTTPRedirect = req.HTTPRedirect
}
if req.Enabled != nil {
in.Enabled = req.Enabled
}
if resolved := req.resolveName(); resolved != nil {
in.Name = resolved
}
if req.Security != nil {
sec := req.securityInput()
in.Security = &sec
}
if req.Exits != nil {
in.Exits = &req.Exits
}
if req.CFTunnelID != nil {
in.CFTunnelID = req.CFTunnelID
}
rule, err := h.svc.Update(r.Context(), id, in)
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, proxy.RuleForAPI(rule))
}
func (h *ProxyHandler) Traffic(w http.ResponseWriter, r *http.Request) {
if h.traffic == nil {
writeJSON(w, http.StatusOK, []traffic.RuleTraffic{})
return
}
rules, err := h.svc.List(r.Context())
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取反向代理规则失败")
return
}
writeJSON(w, http.StatusOK, h.traffic.SnapshotForRules(rules))
}
func (h *ProxyHandler) Clients(w http.ResponseWriter, r *http.Request) {
if h.traffic == nil {
writeJSON(w, http.StatusOK, []traffic.ClientConn{})
return
}
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "无效的规则 ID")
return
}
rule, err := h.svc.Get(r.Context(), id)
if err != nil {
writeError(r, w, http.StatusBadRequest, "规则不存在")
return
}
writeJSON(w, http.StatusOK, h.traffic.ClientsForRule(rule))
}
func (h *ProxyHandler) StreamLogs(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "无效的规则 ID")
return
}
rule, err := h.svc.Get(r.Context(), id)
if err != nil {
writeError(r, w, http.StatusBadRequest, "规则不存在")
return
}
endpoints := rule.Endpoints()
if len(endpoints) == 0 {
writeError(r, w, http.StatusBadRequest, "该规则没有前端域名")
return
}
matches := make([]logstore.AccessEndpoint, 0, len(endpoints))
for _, ep := range endpoints {
matches = append(matches, logstore.AccessEndpoint{Host: ep.Hostname, Port: ep.Port})
}
h.logs.StreamAccessForEndpoints(w, r, matches)
}
func (h *ProxyHandler) Reorder(w http.ResponseWriter, r *http.Request) {
var req proxyReorderRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
if err := h.svc.Reorder(r.Context(), req.IDs); err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *ProxyHandler) Delete(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "无效的规则 ID")
return
}
if err := h.svc.Delete(r.Context(), id); err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
w.WriteHeader(http.StatusNoContent)
}
func (req proxyRequest) resolveName() *string {
if req.Name != nil {
return req.Name
}
return req.Remark
}
func (req proxyRequest) hosts() []string {
if len(req.Hosts) > 0 {
return req.Hosts
}
if req.Domain != "" {
return []string{req.Domain}
}
return nil
}
func intDefault(v *int, fallback int) int {
if v == nil {
return fallback
}
return *v
}
func parseID(raw string) (int64, error) {
return strconv.ParseInt(raw, 10, 64)
}
func boolDefault(v *bool, fallback bool) bool {
if v == nil {
return fallback
}
return *v
}
func int64Default(v *int64, fallback int64) int64 {
if v == nil {
return fallback
}
return *v
}
+60
View File
@@ -0,0 +1,60 @@
package api
import (
"github.com/havline/havline/internal/proxy"
)
type securityRequest struct {
IPBlacklist []string `json:"ip_blacklist,omitempty"`
IPWhitelist []string `json:"ip_whitelist,omitempty"`
IPWhitelistMode *bool `json:"ip_whitelist_mode,omitempty"`
IPBlacklistText *string `json:"ip_blacklist_text,omitempty"`
IPWhitelistText *string `json:"ip_whitelist_text,omitempty"`
ChinaOnly *bool `json:"china_only,omitempty"`
BasicAuth *basicAuthRequest `json:"basic_auth,omitempty"`
RateLimit *proxy.RateLimitConfig `json:"rate_limit,omitempty"`
ConnLimit *proxy.ConnLimitConfig `json:"conn_limit,omitempty"`
ProxySSLVerifyOff *bool `json:"proxy_ssl_verify_off,omitempty"`
ProxyHostUpstream *bool `json:"proxy_host_upstream,omitempty"`
TLSMin13Only *bool `json:"tls_min_13_only,omitempty"`
SecurityHeaders *bool `json:"security_headers,omitempty"`
}
type basicAuthRequest struct {
Enabled *bool `json:"enabled,omitempty"`
Username *string `json:"username,omitempty"`
Password *string `json:"password,omitempty"`
}
func (req *proxyRequest) securityInput() proxy.SecurityInput {
if req.Security == nil {
return proxy.SecurityInput{}
}
s := req.Security
in := proxy.SecurityInput{
IPBlacklist: s.IPBlacklist,
IPWhitelist: s.IPWhitelist,
IPWhitelistMode: s.IPWhitelistMode,
ChinaOnly: s.ChinaOnly,
RateLimit: s.RateLimit,
ConnLimit: s.ConnLimit,
ProxySSLVerifyOff: s.ProxySSLVerifyOff,
ProxyHostUpstream: s.ProxyHostUpstream,
TLSMin13Only: s.TLSMin13Only,
SecurityHeaders: s.SecurityHeaders,
}
if s.IPBlacklistText != nil {
in.IPBlacklist = proxy.ParseIPListText(*s.IPBlacklistText)
}
if s.IPWhitelistText != nil {
in.IPWhitelist = proxy.ParseIPListText(*s.IPWhitelistText)
}
if s.BasicAuth != nil {
in.BasicAuth = &proxy.BasicAuthInput{
Enabled: s.BasicAuth.Enabled,
Username: s.BasicAuth.Username,
Password: s.BasicAuth.Password,
}
}
return in
}
+72
View File
@@ -0,0 +1,72 @@
package api
import (
"encoding/json"
"log/slog"
"net/http"
"reflect"
)
type ErrorBody struct {
Error string `json:"error"`
// Code 是给前端分支用的稳定标识(例如 terminal_locked),文案可能改,code 不改
Code string `json:"code,omitempty"`
}
func writeJSON(w http.ResponseWriter, status int, payload any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
if payload == nil {
_, _ = w.Write([]byte("null"))
return
}
// Go nil slices/maps encode as JSON null; clients expect [] / {}.
v := reflect.ValueOf(payload)
switch v.Kind() {
case reflect.Slice:
if v.IsNil() {
_, _ = w.Write([]byte("[]"))
return
}
case reflect.Map:
if v.IsNil() {
_, _ = w.Write([]byte("{}"))
return
}
}
_ = json.NewEncoder(w).Encode(payload)
}
func writeError(r *http.Request, w http.ResponseWriter, status int, message string, cause ...error) {
logAPIError(r, status, message, cause)
writeJSON(w, status, ErrorBody{Error: message})
}
// writeErrorCode 与 writeError 相同,但多带一个稳定错误码,供前端区分分支。
func writeErrorCode(r *http.Request, w http.ResponseWriter, status int, code, message string, cause ...error) {
logAPIError(r, status, message, cause)
writeJSON(w, status, ErrorBody{Error: message, Code: code})
}
func logAPIError(r *http.Request, status int, message string, cause []error) {
if status < 400 {
return
}
attrs := []any{
"module", "API",
"status", status,
"message", message,
}
if r != nil {
attrs = append(attrs, "method", r.Method, "path", r.URL.Path)
}
if len(cause) > 0 && cause[0] != nil {
attrs = append(attrs, "error", cause[0].Error())
}
switch {
case status >= 500:
slog.Error("request failed", attrs...)
default:
slog.Warn("request rejected", attrs...)
}
}
+64
View File
@@ -0,0 +1,64 @@
package api
import (
"bytes"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
)
func TestWriteJSONNilSlice(t *testing.T) {
var items []string
rec := httptest.NewRecorder()
writeJSON(rec, http.StatusOK, items)
if rec.Body.String() != "[]" {
t.Fatalf("expected [], got %q", rec.Body.String())
}
}
func TestWriteJSONNilMap(t *testing.T) {
var values map[string]string
rec := httptest.NewRecorder()
writeJSON(rec, http.StatusOK, values)
if rec.Body.String() != "{}" {
t.Fatalf("expected {}, got %q", rec.Body.String())
}
}
func TestWriteJSONSlice(t *testing.T) {
rec := httptest.NewRecorder()
writeJSON(rec, http.StatusOK, []int{1, 2})
var out []int
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatal(err)
}
if len(out) != 2 {
t.Fatalf("expected 2 items, got %v", out)
}
}
func TestWriteErrorLogsClientError(t *testing.T) {
var buf bytes.Buffer
prev := slog.Default()
slog.SetDefault(slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn})))
defer slog.SetDefault(prev)
req := httptest.NewRequest(http.MethodPost, "/api/settings/notify/test", nil)
rec := httptest.NewRecorder()
writeError(req, rec, http.StatusBadRequest, "请填写 SMTP 主机")
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", rec.Code)
}
if !bytes.Contains(buf.Bytes(), []byte("请填写 SMTP 主机")) {
t.Fatalf("expected log message, got %s", buf.String())
}
if !bytes.Contains(buf.Bytes(), []byte("/api/settings/notify/test")) {
t.Fatalf("expected log path, got %s", buf.String())
}
}
+378
View File
@@ -0,0 +1,378 @@
package api
import (
"bufio"
"fmt"
"io/fs"
"log/slog"
"net"
"net/http"
"strings"
"time"
"github.com/havline/havline/internal/auth"
)
// routeSpec 是一条 API 路由的注册信息;测试据此遍历全部路由验证鉴权覆盖。
type routeSpec struct {
Pattern string
Handler http.HandlerFunc
Public bool
}
func NewRouter(deps Deps) http.Handler {
handler, _ := newRouterWithSpecs(deps)
return handler
}
func newRouterWithSpecs(deps Deps) (http.Handler, []routeSpec) {
logsHandler := NewLogsHandler(deps.Config)
// 终端二次认证票据:登录处理器与终端处理器共用一份,改密即可让当前会话失效
terminalUnlocks := newTerminalUnlockStore()
r := &Router{
authHandler: NewAuthHandler(deps.Auth, deps.Notify, terminalUnlocks),
proxyHandler: NewProxyHandler(deps.Config, deps.Proxy, logsHandler, deps.Traffic),
nginxHandler: NewNginxHandler(deps.Proxy),
statusHandler: NewStatusHandler(deps.Config, deps.Proxy, deps.DDNS, deps.ACME, deps.Cloudflare, deps.StartedAt, deps.Config.NginxPIDFile),
ddnsHandler: NewDDNSHandler(deps.DDNS),
certHandler: NewCertHandler(deps.ACME),
settingsHandler: NewSettingsHandler(deps.Settings, deps.Proxy, deps.Notify),
chinaCIDRHandler: NewChinaCIDRHandler(deps.ChinaCIDR),
logsHandler: logsHandler,
backupHandler: NewBackupHandler(deps.Backup, deps.Settings),
statusPageHandler: NewStatusPageHandler(deps.Settings, deps.FRPMulti, deps.Cloudflare),
metricsHandler: NewMetricsHandler(deps.Metrics),
discoveryHandler: NewDiscoveryHandler(deps.Discovery),
frpmultiHandler: NewFRPMultiHandler(deps.FRPMulti, deps.Auth),
cloudflareHandler: NewCloudflareHandler(deps.Cloudflare),
updateHandler: NewUpdateHandler(deps.Updater),
terminalHandler: NewTerminalHandler(TerminalHandlerOptions{
FRP: deps.FRPMulti,
Settings: deps.Settings,
Auth: deps.Auth,
Manager: deps.Terminal,
Audits: deps.TerminalAudits,
Commands: deps.TerminalCommands,
Recordings: deps.TerminalRecordings,
Unlocks: terminalUnlocks,
Logger: deps.Logger,
}),
authSvc: deps.Auth,
staticFS: deps.StaticFS,
}
mux := http.NewServeMux()
var specs []routeSpec
public := func(pattern string, handler http.HandlerFunc) {
specs = append(specs, routeSpec{Pattern: pattern, Handler: handler, Public: true})
}
protected := func(pattern string, handler http.HandlerFunc) {
specs = append(specs, routeSpec{Pattern: pattern, Handler: handler})
}
public("GET /api/version", Version(deps.Config))
// 唯一一个匿名只读接口:默认关闭、可设访问码、按 IP 限流
public("GET /api/status-page", r.statusPageHandler.Get)
public("GET /api/auth/status", r.authHandler.Status)
public("POST /api/auth/login", r.authHandler.Login)
public("POST /api/auth/logout", r.authHandler.Logout)
protect := protected
protect("POST /api/auth/password", r.authHandler.ChangePassword)
protect("GET /api/settings/tokens", r.authHandler.ListTokens)
protect("POST /api/settings/tokens", r.authHandler.CreateToken)
protect("DELETE /api/settings/tokens/{id}", r.authHandler.DeleteToken)
protect("GET /api/status", r.statusHandler.Get)
protect("GET /api/proxies", r.proxyHandler.List)
protect("GET /api/proxies/traffic", r.proxyHandler.Traffic)
protect("POST /api/proxies", r.proxyHandler.Create)
protect("PUT /api/proxies/reorder", r.proxyHandler.Reorder)
protect("PUT /api/proxies/{id}", r.proxyHandler.Update)
protect("DELETE /api/proxies/{id}", r.proxyHandler.Delete)
protect("GET /api/proxies/{id}/logs/stream", r.proxyHandler.StreamLogs)
protect("GET /api/proxies/{id}/clients", r.proxyHandler.Clients)
protect("GET /api/proxies/{id}/nginx", r.nginxHandler.GetRule)
protect("PUT /api/proxies/{id}/nginx", r.nginxHandler.PutRule)
protect("POST /api/proxies/{id}/nginx/rollback", r.nginxHandler.RollbackRule)
protect("GET /api/settings/nginx/global", r.nginxHandler.GetGlobal)
protect("PUT /api/settings/nginx/global", r.nginxHandler.PutGlobal)
protect("POST /api/settings/nginx/global/rollback", r.nginxHandler.RollbackGlobal)
protect("GET /api/settings/nginx/config/versions", r.nginxHandler.GetConfigVersions)
protect("GET /api/settings/nginx/config/versions/{name}", r.nginxHandler.GetConfigVersion)
protect("POST /api/settings/nginx/config/versions/{name}/rollback", r.nginxHandler.RollbackConfigVersion)
protect("GET /api/ddns", r.ddnsHandler.List)
protect("POST /api/ddns", r.ddnsHandler.Create)
protect("PUT /api/ddns/{id}", r.ddnsHandler.Update)
protect("DELETE /api/ddns/{id}", r.ddnsHandler.Delete)
protect("POST /api/ddns/test", r.ddnsHandler.Test)
protect("POST /api/ddns/update", r.ddnsHandler.UpdateAll)
protect("POST /api/ddns/{id}/update", r.ddnsHandler.UpdateOne)
protect("GET /api/certificates", r.certHandler.List)
protect("GET /api/certificates/ca-options", r.certHandler.Options)
protect("POST /api/certificates/apply", r.certHandler.Apply)
protect("GET /api/certificates/jobs/{id}/stream", r.certHandler.ApplyJobStream)
protect("POST /api/certificates/import", r.certHandler.Import)
protect("POST /api/certificates/renew", r.certHandler.Renew)
protect("GET /api/certificates/{domain}/download", r.certHandler.Download)
protect("DELETE /api/certificates/{domain}", r.certHandler.Delete)
notifyHandler := NewNotifyHandler(deps.Notify)
protect("GET /api/settings", r.settingsHandler.Get)
protect("PUT /api/settings", r.settingsHandler.Put)
protect("POST /api/settings/notify/test", notifyHandler.Test)
if deps.ChinaCIDR != nil {
protect("GET /api/settings/china-cidr", r.chinaCIDRHandler.Status)
protect("POST /api/settings/china-cidr/refresh", r.chinaCIDRHandler.Refresh)
}
protect("GET /api/logs/access", r.logsHandler.Access)
protect("GET /api/logs/error", r.logsHandler.Error)
protect("GET /api/logs/system", r.logsHandler.System)
protect("GET /api/metrics/history", r.metricsHandler.History)
protect("GET /api/logs/stream", r.logsHandler.Stream)
protect("GET /api/system/update/status", r.updateHandler.Status)
protect("POST /api/system/update/apply", r.updateHandler.Apply)
protect("GET /api/backup/export", r.backupHandler.Export)
protect("POST /api/backup/restore", r.backupHandler.Restore)
protect("GET /api/backup/archives", r.backupHandler.ListArchives)
protect("POST /api/backup/archives", r.backupHandler.CreateArchive)
protect("GET /api/backup/archives/{name}", r.backupHandler.DownloadArchive)
protect("POST /api/backup/archives/{name}/restore", r.backupHandler.RestoreArchive)
protect("DELETE /api/backup/archives/{name}", r.backupHandler.DeleteArchive)
protect("GET /api/discovery/scan", r.discoveryHandler.Scan)
if deps.FRPMulti != nil {
frpHandler := r.frpmultiHandler
protect("GET /api/frpmulti/status", frpHandler.Status)
protect("GET /api/frpmulti/runtime", frpHandler.Runtime)
protect("PUT /api/frpmulti/runtime/download-proxy", frpHandler.SetDownloadProxy)
protect("GET /api/frpmulti/releases", frpHandler.Releases)
protect("GET /api/frpmulti/binaries", frpHandler.Binaries)
protect("GET /api/frpmulti/download", frpHandler.DownloadStatus)
protect("POST /api/frpmulti/releases/{version}/download", frpHandler.DownloadRelease)
protect("POST /api/frpmulti/binaries/{version}/activate", frpHandler.ActivateBinary)
protect("DELETE /api/frpmulti/binaries/{version}", frpHandler.DeleteBinary)
protect("GET /api/frpmulti/servers", frpHandler.ListServers)
protect("GET /api/frpmulti/servers/{id}/detail", frpHandler.ServerDetail)
protect("GET /api/frpmulti/servers/{id}/diagnostics", frpHandler.ServerDiagnostics)
protect("GET /api/frpmulti/servers/{id}/frps-config", frpHandler.FRPSServerConfig)
protect("POST /api/frpmulti/servers/{id}/start", frpHandler.StartServer)
protect("POST /api/frpmulti/servers/{id}/stop", frpHandler.StopServer)
protect("POST /api/frpmulti/servers", frpHandler.CreateServer)
protect("PUT /api/frpmulti/servers/{id}", frpHandler.UpdateServer)
protect("DELETE /api/frpmulti/servers/{id}", frpHandler.DeleteServer)
protect("POST /api/frpmulti/servers/{id}/test", frpHandler.TestServer)
protect("POST /api/frpmulti/servers/{id}/agent/probe", frpHandler.AgentProbe)
protect("POST /api/frpmulti/servers/{id}/agent/install", frpHandler.AgentInstall)
protect("POST /api/frpmulti/servers/{id}/agent/uninstall", frpHandler.AgentUninstall)
protect("POST /api/frpmulti/servers/{id}/agent/ssh-diagnose", frpHandler.AgentSSHDiagnose)
protect("POST /api/frpmulti/servers/{id}/agent/test", frpHandler.AgentTest)
protect("POST /api/frpmulti/servers/{id}/agent/tunnel/restart", frpHandler.AgentTunnelRestart)
protect("POST /api/frpmulti/servers/{id}/agent/transport", frpHandler.SetAgentTransport)
protect("GET /api/frpmulti/servers/{id}/agent/transport", frpHandler.AgentTransportStatus)
protect("POST /api/frpmulti/servers/{id}/agent/transport/rotate", frpHandler.AgentTransportRotateCert)
protect("GET /api/frpmulti/servers/{id}/agent/firewall", frpHandler.AgentFirewallStatus)
protect("POST /api/frpmulti/servers/{id}/agent/firewall/allow", frpHandler.AgentFirewallAllow)
protect("GET /api/frpmulti/servers/{id}/agent/status", frpHandler.AgentStatus)
protect("GET /api/frpmulti/servers/{id}/agent/routes", frpHandler.AgentRoutes)
protect("GET /api/frpmulti/servers/{id}/agent/routes/health", frpHandler.AgentRouteHealth)
protect("GET /api/frpmulti/routes/summary", frpHandler.AgentRouteHealthSummary)
protect("GET /api/frpmulti/routes/uptime", frpHandler.RouteUptime)
protect("GET /api/frpmulti/servers/{id}/agent/routes/drift", frpHandler.AgentRouteDrift)
protect("POST /api/frpmulti/servers/{id}/agent/routes/redeploy", frpHandler.AgentRedeployRoutes)
protect("GET /api/frpmulti/servers/{id}/agent/metrics", frpHandler.AgentMetrics)
protect("GET /api/frpmulti/servers/{id}/agent/logs/nginx", frpHandler.AgentNginxLogs)
protect("GET /api/frpmulti/servers/{id}/agent/frps-config", frpHandler.AgentFRPSConfig)
protect("GET /api/frpmulti/servers/{id}/agent/certs", frpHandler.AgentCerts)
protect("POST /api/frpmulti/servers/{id}/agent/nginx/reload", frpHandler.AgentNginxReload)
protect("POST /api/frpmulti/servers/{id}/agent/nginx/install", frpHandler.AgentInstallNginx)
protect("POST /api/frpmulti/servers/{id}/agent/nginx/action", frpHandler.AgentNginxAction)
protect("GET /api/frpmulti/servers/{id}/agent/routes/{proxyID}/conf", frpHandler.AgentRouteConf)
protect("GET /api/frpmulti/servers/{id}/agent/routes/{proxyID}/versions", frpHandler.AgentRouteVersions)
protect("GET /api/frpmulti/servers/{id}/agent/routes/{proxyID}/versions/{name}", frpHandler.AgentRouteVersion)
protect("POST /api/frpmulti/servers/{id}/agent/routes/{proxyID}/versions/{name}/rollback", frpHandler.AgentRollbackRouteVersion)
protect("GET /api/frpmulti/servers/{id}/agent/route-candidates", frpHandler.AgentRouteCandidates)
protect("POST /api/frpmulti/servers/{id}/agent/routes/{proxyID}", frpHandler.DeployAgentRoute)
protect("DELETE /api/frpmulti/servers/{id}/agent/routes/{proxyID}", frpHandler.RemoveAgentRoute)
protect("POST /api/frpmulti/servers/{id}/agent/frps-install", frpHandler.InstallFRPSOnAgent)
protect("POST /api/frpmulti/servers/{id}/agent/frps-action", frpHandler.AgentFRPSAction)
protect("POST /api/frpmulti/servers/{id}/agent/frps-config", frpHandler.PushFRPSConfigToAgent)
protect("GET /api/frpmulti/proxies", frpHandler.ListProxies)
protect("GET /api/frpmulti/proxies/traffic", frpHandler.ListProxiesTraffic)
protect("POST /api/frpmulti/proxies", frpHandler.CreateProxy)
protect("PUT /api/frpmulti/proxies/{id}", frpHandler.UpdateProxy)
protect("DELETE /api/frpmulti/proxies/{id}", frpHandler.DeleteProxy)
protect("GET /api/frpmulti/proxies/{id}/logs", frpHandler.ProxyLogs)
protect("POST /api/frpmulti/start", frpHandler.Start)
protect("POST /api/frpmulti/stop", frpHandler.Stop)
protect("POST /api/frpmulti/restart", frpHandler.Restart)
protect("POST /api/frpmulti/reload", frpHandler.Reload)
protect("GET /api/frpmulti/logs", frpHandler.Logs)
protect("GET /api/frpmulti/config/export", frpHandler.ExportConfig)
}
if deps.Cloudflare != nil {
cf := r.cloudflareHandler
protect("GET /api/cloudflare/tunnels", cf.List)
protect("POST /api/cloudflare/tunnels", cf.Create)
protect("GET /api/cloudflare/tunnels/{id}", cf.Get)
protect("PUT /api/cloudflare/tunnels/{id}", cf.Update)
protect("DELETE /api/cloudflare/tunnels/{id}", cf.Delete)
protect("POST /api/cloudflare/tunnels/{id}/start", cf.Start)
protect("POST /api/cloudflare/tunnels/{id}/stop", cf.Stop)
protect("POST /api/cloudflare/tunnels/{id}/restart", cf.Restart)
protect("POST /api/cloudflare/tunnels/{id}/credentials/refresh", cf.RefreshCredentials)
protect("GET /api/cloudflare/tunnels/{id}/status", cf.Status)
protect("GET /api/cloudflare/tunnels/{id}/logs", cf.Logs)
protect("GET /api/cloudflare/tunnels/{id}/config", cf.Config)
protect("GET /api/cloudflare/tunnels/{id}/routes", cf.Routes)
protect("PUT /api/cloudflare/tunnels/{id}/routes", cf.ReplaceRoutes)
protect("GET /api/cloudflare/tunnels/{id}/drift", cf.Drift)
protect("POST /api/cloudflare/tunnels/{id}/sync", cf.SyncRoutes)
protect("GET /api/cloudflare/tunnels/{id}/diagnostics", cf.Diagnostics)
protect("GET /api/cloudflare/binary", cf.BinaryInfo)
protect("POST /api/cloudflare/binary/download", cf.DownloadBinary)
protect("GET /api/cloudflare/binary/latest", cf.LatestBinary)
protect("POST /api/cloudflare/binary/rollback", cf.RollbackBinary)
protect("GET /api/cloudflare/settings", cf.AppSettings)
protect("PUT /api/cloudflare/settings", cf.SaveAppSettings)
protect("POST /api/cloudflare/settings/test", cf.TestToken)
protect("POST /api/cloudflare/enabled", cf.SetEnabled)
protect("GET /api/cloudflare/ingress-candidates", cf.IngressCandidates)
protect("GET /api/cloudflare/zones", cf.Zones)
protect("GET /api/cloudflare/access-status", cf.AccessStatus)
protect("GET /api/cloudflare/preflight", cf.Preflight)
protect("POST /api/cloudflare/routes/test", cf.TestRoute)
}
if deps.Terminal != nil {
term := r.terminalHandler
protect("GET /api/terminal/targets", term.ListTargets)
protect("GET /api/terminal/unlock", term.UnlockStatus)
protect("POST /api/terminal/unlock", term.Unlock)
protect("DELETE /api/terminal/unlock", term.Lock)
protect("GET /api/terminal/commands", term.ListCommands)
protect("POST /api/terminal/commands", term.CreateCommand)
protect("DELETE /api/terminal/commands/{id}", term.DeleteCommand)
protect("GET /api/terminal/recordings", term.ListRecordings)
protect("GET /api/terminal/recordings/{id}", term.GetRecording)
protect("GET /api/terminal/sessions", term.ListSessions)
protect("POST /api/terminal/sessions", term.CreateSession)
protect("GET /api/terminal/sessions/{id}/ws", term.Stream)
protect("DELETE /api/terminal/sessions/{id}", term.CloseSession)
}
// 审计不依赖终端开关:功能关掉后,历史记录仍然应该查得到
if deps.TerminalAudits != nil {
protect("GET /api/terminal/audits", r.terminalHandler.ListAudits)
}
if deps.StaticFS != nil {
mux.Handle("/", r.spaHandler())
}
for _, spec := range specs {
if spec.Public {
mux.HandleFunc(spec.Pattern, spec.Handler)
continue
}
mux.Handle(spec.Pattern, SessionMiddleware(deps.Auth)(RequireAuth(deps.Auth)(spec.Handler)))
}
logger := deps.Logger
if logger == nil {
logger = slog.Default()
}
return loggingMiddleware(logger, SessionMiddleware(deps.Auth)(mux)), specs
}
type Router struct {
authHandler *AuthHandler
proxyHandler *ProxyHandler
nginxHandler *NginxHandler
statusHandler *StatusHandler
ddnsHandler *DDNSHandler
certHandler *CertHandler
settingsHandler *SettingsHandler
chinaCIDRHandler *ChinaCIDRHandler
logsHandler *LogsHandler
backupHandler *BackupHandler
statusPageHandler *StatusPageHandler
metricsHandler *MetricsHandler
discoveryHandler *DiscoveryHandler
frpmultiHandler *FRPMultiHandler
cloudflareHandler *CloudflareHandler
updateHandler *UpdateHandler
terminalHandler *TerminalHandler
authSvc *auth.Service
staticFS fs.FS
}
func (r *Router) spaHandler() http.Handler {
fileServer := http.FileServer(http.FS(r.staticFS))
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if strings.HasPrefix(req.URL.Path, "/api/") {
http.NotFound(w, req)
return
}
path := strings.TrimPrefix(req.URL.Path, "/")
if path == "" {
path = "index.html"
}
if _, err := fs.Stat(r.staticFS, path); err != nil {
// SPA fallback: unknown routes serve index.html
req.URL.Path = "/index.html"
}
fileServer.ServeHTTP(w, req)
})
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (w *statusRecorder) WriteHeader(code int) {
w.status = code
w.ResponseWriter.WriteHeader(code)
}
func (w *statusRecorder) Flush() {
if f, ok := w.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
// Hijack 转发给底层 ResponseWriter:WebSocket 升级(内置 SSH 终端)需要拿到原始连接。
func (w *statusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker, ok := w.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, fmt.Errorf("底层 ResponseWriter 不支持 Hijack")
}
return hijacker.Hijack()
}
func loggingMiddleware(logger *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
if strings.HasPrefix(r.URL.Path, "/api/") &&
!strings.Contains(r.URL.Path, "/logs/stream") &&
!strings.Contains(r.URL.Path, "/certificates/jobs/") &&
rec.status >= 400 {
level := slog.LevelWarn
msg := "api request completed with client error"
if rec.status >= 500 {
level = slog.LevelError
msg = "api request failed"
}
logger.Log(r.Context(), level, msg,
"module", "HTTP",
"method", r.Method,
"path", r.URL.Path,
"status", rec.status,
"duration_ms", time.Since(start).Milliseconds(),
)
}
})
}
+101
View File
@@ -0,0 +1,101 @@
package api
import (
"context"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"path/filepath"
"regexp"
"strings"
"testing"
"github.com/havline/havline/internal/auth"
"github.com/havline/havline/internal/certificate"
"github.com/havline/havline/internal/cloudflared"
"github.com/havline/havline/internal/config"
"github.com/havline/havline/internal/db"
"github.com/havline/havline/internal/frp"
"github.com/havline/havline/internal/secret"
"github.com/havline/havline/internal/settings"
)
var routeParamPattern = regexp.MustCompile(`\{[^}]+\}`)
// TestProtectedRoutesRequireAuth 遍历路由表:受保护路由匿名必须 401,公开路由不能被鉴权误拦。
func TestProtectedRoutesRequireAuth(t *testing.T) {
dir := t.TempDir()
conn, err := db.Open(filepath.Join(dir, "havline.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
defer conn.Close()
if err := db.Migrate(context.Background(), conn, filepath.Join("..", "..", "migrations")); err != nil {
t.Fatalf("migrate: %v", err)
}
authSvc := auth.New(conn)
box, err := secret.NewBox("router-auth-test-key")
if err != nil {
t.Fatal(err)
}
cfg := config.Config{DataDir: dir, NginxPIDFile: filepath.Join(dir, "nginx.pid")}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
frpSvc := frp.NewService(cfg, frp.NewStore(conn), box, logger, certificate.NewStore(conn))
cfSvc := cloudflared.NewService(cfg, cloudflared.NewStore(conn), box, logger, nil)
handler, specs := newRouterWithSpecs(Deps{
Config: cfg,
Auth: authSvc,
FRPMulti: frpSvc,
Cloudflare: cfSvc,
Settings: settings.NewStore(conn),
Logger: logger,
})
protected, public := 0, 0
for _, spec := range specs {
req := httptest.NewRequest(routeMethod(spec.Pattern), sampleRoutePath(spec.Pattern), nil)
code := callRouteSafely(handler, req)
if spec.Public {
public++
if code == http.StatusUnauthorized {
t.Fatalf("公开路由 %s 不应被鉴权拦截", spec.Pattern)
}
continue
}
protected++
if code != http.StatusUnauthorized {
t.Fatalf("受保护路由 %s 匿名请求应返回 401,实际 %d", spec.Pattern, code)
}
}
if protected < 100 {
t.Fatalf("受保护路由覆盖不足:%d 条", protected)
}
if public < 4 {
t.Fatalf("公开路由覆盖不足:%d 条", public)
}
}
func routeMethod(pattern string) string {
method, _, _ := strings.Cut(pattern, " ")
return method
}
func sampleRoutePath(pattern string) string {
_, path, _ := strings.Cut(pattern, " ")
return routeParamPattern.ReplaceAllString(path, "1")
}
// callRouteSafely 在依赖缺失导致 handler panic 时返回 0,避免公开路由的构造依赖影响鉴权断言。
func callRouteSafely(handler http.Handler, req *http.Request) (code int) {
defer func() {
if recover() != nil {
code = 0
}
}()
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
return rec.Code
}
+242
View File
@@ -0,0 +1,242 @@
package api
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/havline/havline/internal/notify"
"github.com/havline/havline/internal/service"
"github.com/havline/havline/internal/settings"
"github.com/havline/havline/internal/validate"
)
type SettingsHandler struct {
store *settings.Store
proxy *service.ProxyService
notify *notify.Service
}
func NewSettingsHandler(store *settings.Store, proxySvc *service.ProxyService, notifySvc *notify.Service) *SettingsHandler {
return &SettingsHandler{store: store, proxy: proxySvc, notify: notifySvc}
}
func (h *SettingsHandler) Get(w http.ResponseWriter, r *http.Request) {
values, err := h.store.List(r.Context())
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取设置失败", err)
return
}
notify.SanitizeSettings(values)
// 状态页访问码只回掩码:既不下发明文也不下发哈希
if values[settings.KeyStatusPageCodeHash] != "" {
values[settings.KeyStatusPageCode] = MaskedStatusPageCode
}
delete(values, settings.KeyStatusPageCodeHash)
writeJSON(w, http.StatusOK, values)
}
func (h *SettingsHandler) Put(w http.ResponseWriter, r *http.Request) {
var req map[string]string
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
// 白名单从设置注册表派生(settings.Specs 里 Writable=true 的键)。
// 之前是手写 map,新增设置项时容易只改前端与常量、忘了加白名单。
allowed := settings.WritableKeys()
filtered := map[string]string{}
for key, value := range req {
if !allowed[key] {
continue
}
if err := h.validateSetting(key, value); err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
filtered[key] = value
}
// 时区在写入前先校验:写进库之后才发现不合法,就得再回滚一次。
if tz, ok := filtered[settings.KeyTimezone]; ok {
if _, err := settings.LoadTimezone(tz); err != nil {
writeError(r, w, http.StatusBadRequest, err.Error(), err)
return
}
}
// 状态页访问码走「掩码往返」:客户端提交明文,这里落 SHA-256;
// 空串 = 清除访问码,掩码值 = 保持不变。哈希字段不接受客户端直接写入。
if code, ok := filtered[settings.KeyStatusPageCode]; ok {
delete(filtered, settings.KeyStatusPageCode)
trimmed := strings.TrimSpace(code)
switch {
case trimmed == MaskedStatusPageCode:
case trimmed == "":
filtered[settings.KeyStatusPageCodeHash] = ""
default:
filtered[settings.KeyStatusPageCodeHash] = hashStatusPageCode(trimmed)
}
}
if h.notify != nil && h.notify.Store() != nil {
if in, ok := notify.ParseSaveInputFromMap(filtered); ok {
if err := h.notify.Store().Save(r.Context(), in); err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
for key := range filtered {
if isNotifySettingKey(key) {
delete(filtered, key)
}
}
}
}
if err := h.store.SetMany(r.Context(), filtered); err != nil {
writeError(r, w, http.StatusInternalServerError, "保存设置失败", err)
return
}
// 时区是进程级状态:保存后立即生效,不必等重启(否则用户改了看不到变化,
// 又会变成「界面能改、实际不生效」的观感)。
if tz, ok := filtered[settings.KeyTimezone]; ok && strings.TrimSpace(tz) != "" {
if _, err := settings.ApplyTimezone(r.Context(), h.store); err != nil {
writeError(r, w, http.StatusBadRequest, err.Error(), err)
return
}
}
if h.proxy != nil && (filtered[settings.KeyTrustedProxy] != "" || filtered[settings.KeyGlobalIPBlacklist] != "" || filtered[settings.KeyGlobalIPWhitelist] != "") {
if err := h.proxy.ReloadAll(r.Context()); err != nil {
writeError(r, w, http.StatusInternalServerError, "设置已保存,但 Nginx 重载失败:"+err.Error(), err)
return
}
}
values, err := h.store.List(r.Context())
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取设置失败", err)
return
}
notify.SanitizeSettings(values)
// 状态页访问码只回掩码:既不下发明文也不下发哈希
if values[settings.KeyStatusPageCodeHash] != "" {
values[settings.KeyStatusPageCode] = MaskedStatusPageCode
}
delete(values, settings.KeyStatusPageCodeHash)
writeJSON(w, http.StatusOK, values)
}
func isNotifySettingKey(key string) bool {
switch key {
case settings.KeyNotifyType,
settings.KeyNotifyEmailJSON,
settings.KeyNotifySMTPPassword,
settings.KeyNotifyWebhookJSON,
settings.KeyNotifyWebhookSecret,
settings.KeyNotifyTelegramJSON,
settings.KeyNotifyTelegramToken,
settings.KeyNotifyOnDDNSIPChange,
settings.KeyNotifyOnDDNSFailure,
settings.KeyNotifyOnCertExpiry,
settings.KeyNotifyOnCertRenewSuccess,
settings.KeyNotifyOnIPFrequentAccess,
settings.KeyNotifyOnCertRenewFailure,
settings.KeyNotifyOnLoginFailure,
settings.KeyNotifyOnNginxReloadFailure,
settings.KeyNotifyIPFrequentThreshold,
settings.KeyNotifyIPFrequentWindowSec,
settings.KeyNotifyLoginFailureThreshold,
settings.KeyNotifyLoginFailureWindowSec,
settings.KeyNotifyOnResourceThreshold,
settings.KeyNotifyOnTunnelDown,
settings.KeyNotifyCPUThreshold,
settings.KeyNotifyMemoryThreshold,
settings.KeyNotifyDiskThreshold,
settings.KeyNotifyTunnelFailThreshold,
settings.KeyNotifyOnFrpsDown,
settings.KeyNotifyOnAgentUnreachable,
settings.KeyNotifyOnRouteDrift,
settings.KeyNotifyFrpsFailThreshold,
settings.KeyNotifyAgentFailThreshold,
settings.KeyNotifyDriftCooldownHours,
settings.KeyNotifyOnBackupFailure,
settings.KeyNotifyWebhookURL:
return true
default:
return false
}
}
func (h *SettingsHandler) validateSetting(key, value string) error {
switch key {
case settings.KeyNotifyEmailJSON, settings.KeyNotifyWebhookJSON, settings.KeyNotifyTelegramJSON:
if value != "" {
var raw map[string]any
if err := json.Unmarshal([]byte(value), &raw); err != nil {
return err
}
}
case settings.KeyNotifyType:
switch value {
case "", "email", "webhook", "telegram":
default:
return fmt.Errorf("无效的通知类型")
}
case settings.KeyNotifyIPFrequentThreshold:
if value != "" {
n, err := strconv.Atoi(value)
if err != nil || n < 10 || n > 10000 {
return fmt.Errorf("频繁访问阈值需在 10–10000 之间")
}
}
case settings.KeyNotifyIPFrequentWindowSec, settings.KeyNotifyLoginFailureWindowSec:
if value != "" {
n, err := strconv.Atoi(value)
if err != nil || n < 10 || n > 3600 {
return fmt.Errorf("统计窗口需在 10–3600 秒之间")
}
}
case settings.KeyBackupKeepCount:
if value != "" {
n, err := strconv.Atoi(value)
if err != nil || n < 1 || n > 60 {
return fmt.Errorf("备份保留份数需在 1–60 之间")
}
}
case settings.KeyNotifyLoginFailureThreshold:
if value != "" {
n, err := strconv.Atoi(value)
if err != nil || n < 3 || n > 100 {
return fmt.Errorf("登录失败阈值需在 3–100 之间")
}
}
case settings.KeyGlobalIPBlacklist, settings.KeyGlobalIPWhitelist:
var list []string
if value != "" && value != "[]" {
if err := json.Unmarshal([]byte(value), &list); err != nil {
return err
}
if err := validate.IPOrCIDRList(list); err != nil {
return err
}
}
case settings.KeyTrustedProxy:
if value != "" && value != "{}" {
var raw map[string]any
if err := json.Unmarshal([]byte(value), &raw); err != nil {
return err
}
}
case settings.KeyTheme:
switch strings.TrimSpace(value) {
case "system", "light", "dark":
default:
return fmt.Errorf("无效的主题:只支持 system / light / dark")
}
case settings.KeyLogRetentionDays:
if value != "" {
n, err := strconv.Atoi(value)
if err != nil || n < 1 || n > 365 {
return fmt.Errorf("日志保留天数需在 1–365 之间")
}
}
}
return nil
}
+231
View File
@@ -0,0 +1,231 @@
package api
import (
"context"
"fmt"
"math"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/havline/havline/internal/acme"
certstore "github.com/havline/havline/internal/certificate"
"github.com/havline/havline/internal/cloudflared"
"github.com/havline/havline/internal/config"
"github.com/havline/havline/internal/ddns"
"github.com/havline/havline/internal/logstore"
"github.com/havline/havline/internal/publicip"
"github.com/havline/havline/internal/service"
"github.com/havline/havline/internal/sysinfo"
)
type StatusHandler struct {
cfg config.Config
proxySvc *service.ProxyService
ddnsSvc *ddns.Service
acmeSvc *acme.Service
cloudflareSvc *cloudflared.Service
startedAt string
nginxPIDFile string
cpuMu sync.Mutex
cpuSample sysinfo.CPUSample
}
func NewStatusHandler(cfg config.Config, proxySvc *service.ProxyService, ddnsSvc *ddns.Service, acmeSvc *acme.Service, cloudflareSvc *cloudflared.Service, startedAt, nginxPIDFile string) *StatusHandler {
// 先采一次 CPU 计数器,使首次请求就能算出占用率(否则只能返回 0)
_, sample := sysinfo.Read(sysinfo.CPUSample{})
return &StatusHandler{
cfg: cfg,
proxySvc: proxySvc,
ddnsSvc: ddnsSvc,
acmeSvc: acmeSvc,
cloudflareSvc: cloudflareSvc,
startedAt: startedAt,
nginxPIDFile: nginxPIDFile,
cpuSample: sample,
}
}
type statusResponse struct {
PublicIPv4 string `json:"public_ipv4"`
PublicIPv6 string `json:"public_ipv6"`
PublicIPSource string `json:"public_ip_source"`
DDNSStatus string `json:"ddns_status"`
DDNSCount int `json:"ddns_count"`
DDNSLastUpdated string `json:"ddns_last_updated,omitempty"`
CertificateStatus string `json:"certificate_status"`
CertificateDays int `json:"certificate_days"`
CertificateCount int `json:"certificate_count"`
CertificateSummary string `json:"certificate_summary,omitempty"`
ProxyCount int `json:"proxy_count"`
NginxStatus string `json:"nginx_status"`
RequestToday int `json:"request_today"`
RequestYesterday int `json:"request_yesterday"`
RequestTrend *int `json:"request_trend,omitempty"`
RequestsHourly []int `json:"requests_hourly"`
RequestsHourlyLabels []string `json:"requests_hourly_labels"`
ErrorToday int `json:"error_today"`
AvgResponseMs float64 `json:"avg_response_ms"`
CPUPercent float64 `json:"cpu_percent"`
MemUsedBytes uint64 `json:"mem_used_bytes"`
MemTotalBytes uint64 `json:"mem_total_bytes"`
DiskUsedBytes uint64 `json:"disk_used_bytes"`
DiskTotalBytes uint64 `json:"disk_total_bytes"`
CloudflareCount int `json:"cloudflare_count"`
CloudflareOnline int `json:"cloudflare_online"`
CloudflareStatus string `json:"cloudflare_status"`
CloudflareMessage string `json:"cloudflare_message,omitempty"`
StartedAt string `json:"started_at"`
UptimeSeconds int64 `json:"uptime_seconds"`
}
func (h *StatusHandler) Get(w http.ResponseWriter, r *http.Request) {
rules, err := h.proxySvc.List(r.Context())
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取状态失败")
return
}
nginxStatus := "unknown"
if _, err := os.Stat(h.nginxPIDFile); err == nil {
nginxStatus = "running"
} else if os.IsNotExist(err) {
nginxStatus = "stopped"
}
ddnsStatus, ddnsLastUpdated, ddnsCount := h.ddnsSvc.Summary(r.Context())
ipv4, ipv6, ipSource := h.resolvePublicIPs(r.Context())
records, _ := h.acmeSvc.List(r.Context())
certStatus, certDays, certCount, certSummary := summarizeCertificates(records)
resources, cpuSample := sysinfo.Read(h.currentCPUSample())
h.setCPUSample(cpuSample)
cfSummary := cloudflared.TunnelSummary{Status: "none", Message: "未创建隧道"}
if h.cloudflareSvc != nil {
cfSummary = h.cloudflareSvc.Summary(r.Context())
}
accessLog := filepath.Join(h.cfg.LogsDir(), "access.log")
total, errors, avgMs := logstore.CountTodayAccess(accessLog)
yesterday, _, _ := logstore.CountAccessForDay(accessLog, time.Now().AddDate(0, 0, -1))
hourly, hourlyLabels := logstore.HourlyAccessCounts(accessLog)
started, _ := time.Parse(time.RFC3339, h.startedAt)
uptime := time.Since(started).Seconds()
writeJSON(w, http.StatusOK, statusResponse{
PublicIPv4: ipv4,
PublicIPv6: ipv6,
PublicIPSource: ipSource,
DDNSStatus: ddnsStatus,
DDNSCount: ddnsCount,
DDNSLastUpdated: ddnsLastUpdated,
CertificateStatus: certStatus,
CertificateDays: certDays,
CertificateCount: certCount,
CertificateSummary: certSummary,
ProxyCount: len(rules),
NginxStatus: nginxStatus,
RequestToday: total,
RequestYesterday: yesterday,
RequestTrend: requestTrendPercent(total, yesterday),
RequestsHourly: hourly,
RequestsHourlyLabels: hourlyLabels,
ErrorToday: errors,
AvgResponseMs: avgMs,
CPUPercent: resources.CPUPercent,
MemUsedBytes: resources.MemUsedBytes,
MemTotalBytes: resources.MemTotalBytes,
DiskUsedBytes: resources.DiskUsedBytes,
DiskTotalBytes: resources.DiskTotalBytes,
CloudflareCount: cfSummary.Count,
CloudflareOnline: cfSummary.Online,
CloudflareStatus: cfSummary.Status,
CloudflareMessage: cfSummary.Message,
StartedAt: h.startedAt,
UptimeSeconds: int64(uptime),
})
}
// currentCPUSample 与 setCPUSample 用锁保护上次采样,/api/status 可能被并发调用
func (h *StatusHandler) currentCPUSample() sysinfo.CPUSample {
h.cpuMu.Lock()
defer h.cpuMu.Unlock()
return h.cpuSample
}
func (h *StatusHandler) setCPUSample(sample sysinfo.CPUSample) {
h.cpuMu.Lock()
defer h.cpuMu.Unlock()
h.cpuSample = sample
}
func (h *StatusHandler) resolvePublicIPs(ctx context.Context) (ipv4, ipv6, source string) {
if ipv4, ipv6, ok := h.ddnsSvc.PublicIPs(ctx); ok {
return ipv4, ipv6, "ddns"
}
if ipv4, ipv6, ok := h.ddnsSvc.LastKnownPublicIPs(ctx); ok {
return ipv4, ipv6, "ddns"
}
detectCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
ipv4, ipv6, err := publicip.Detect(detectCtx)
if err != nil {
return "", ipv6, "none"
}
return ipv4, ipv6, "detect"
}
func summarizeCertificates(records []certstore.Record) (status string, days int, count int, summary string) {
if len(records) == 0 {
return "none", 0, 0, ""
}
count = len(records)
status = "ok"
days = records[0].DaysLeft
for _, rec := range records {
if rec.DaysLeft < days {
days = rec.DaysLeft
}
switch {
case rec.Status == "error" || rec.DaysLeft <= 0:
status = "error"
case rec.DaysLeft <= 30 && status != "error":
status = "warning"
}
}
if count == 1 {
summary = certificateSummaryName(records[0])
} else {
summary = fmt.Sprintf("%d 张证书", count)
}
return status, days, count, summary
}
func requestTrendPercent(today, yesterday int) *int {
if yesterday <= 0 {
if today <= 0 {
return nil
}
v := 100
return &v
}
v := int(math.Round(float64(today-yesterday) / float64(yesterday) * 100))
return &v
}
func certificateSummaryName(rec certstore.Record) string {
for _, domain := range rec.Domains {
if strings.HasPrefix(domain, "*.") {
return domain
}
}
if rec.Wildcard {
return "*." + rec.Domain
}
return rec.Domain
}
+18
View File
@@ -0,0 +1,18 @@
package api
import "testing"
func TestRequestTrendPercent(t *testing.T) {
if got := requestTrendPercent(0, 0); got != nil {
t.Fatalf("expected nil trend, got %v", *got)
}
if got := requestTrendPercent(10, 0); got == nil || *got != 100 {
t.Fatalf("expected 100 for new traffic, got %v", got)
}
if got := requestTrendPercent(150, 100); got == nil || *got != 50 {
t.Fatalf("expected 50, got %v", got)
}
if got := requestTrendPercent(50, 100); got == nil || *got != -50 {
t.Fatalf("expected -50, got %v", got)
}
}
+252
View File
@@ -0,0 +1,252 @@
package api
import (
"context"
"crypto/sha256"
"encoding/hex"
"net"
"net/http"
"strings"
"sync"
"time"
"github.com/havline/havline/internal/cloudflared"
"github.com/havline/havline/internal/frp"
"github.com/havline/havline/internal/notify"
"github.com/havline/havline/internal/settings"
)
// statusPageWindow / statusPageLimit 匿名访问的限流窗口与配额:
// 状态页会被扫描器盯上,这里比登录接口更宽松但仍有限度。
const (
statusPageWindow = time.Minute
statusPageLimit = 60
)
// StatusPageHandler 提供**匿名只读**状态页数据,默认关闭。
//
// 刻意只暴露域名与可用率:不带内网地址、端口、证书路径、服务端地址——
// 状态页是要挂到公网上的东西,泄露拓扑就等于把内网结构摊开给别人看。
type StatusPageHandler struct {
settings *settings.Store
frp *frp.Service
cloudflare *cloudflared.Service
limiter *statusPageLimiter
}
func NewStatusPageHandler(settingsStore *settings.Store, frpSvc *frp.Service, cloudflareSvc *cloudflared.Service) *StatusPageHandler {
return &StatusPageHandler{
settings: settingsStore,
frp: frpSvc,
cloudflare: cloudflareSvc,
limiter: newStatusPageLimiter(),
}
}
type statusPageRoute struct {
Domain string `json:"domain"`
State string `json:"state"`
Source string `json:"source,omitempty"`
Uptime float64 `json:"uptime_pct"`
DownMinutes int `json:"down_minutes"`
UnknownMinutes int `json:"unknown_minutes"`
Incidents []statusPageIncident `json:"incidents"`
}
type statusPageIncident struct {
From string `json:"from"`
To string `json:"to,omitempty"`
Reason string `json:"reason,omitempty"`
Detail string `json:"detail,omitempty"`
Minutes int `json:"minutes"`
}
type statusPagePayload struct {
Title string `json:"title"`
CodeRequired bool `json:"code_required"`
CheckedAt string `json:"checked_at"`
Up int `json:"up"`
Down int `json:"down"`
Unknown int `json:"unknown"`
Routes []statusPageRoute `json:"routes"`
}
// Get 是唯一的匿名入口:关闭时一律 404(与「不存在」不可区分),
// 设了访问码时校验 ?code=,校验失败也回 404。
func (h *StatusPageHandler) Get(w http.ResponseWriter, r *http.Request) {
if h == nil || h.settings == nil {
writeError(r, w, http.StatusNotFound, "状态页未开启")
return
}
if !h.limiter.allow(clientIPForLimit(r)) {
writeError(r, w, http.StatusTooManyRequests, "请求过于频繁")
return
}
enabled, _ := h.settings.GetBool(r.Context(), settings.KeyStatusPageEnabled)
if !enabled || (h.frp == nil && h.cloudflare == nil) {
writeError(r, w, http.StatusNotFound, "状态页未开启")
return
}
codeHash, err := h.settings.Get(r.Context(), settings.KeyStatusPageCodeHash)
if err != nil {
codeHash = ""
}
codeRequired := strings.TrimSpace(codeHash) != ""
if codeRequired && hashStatusPageCode(r.URL.Query().Get("code")) != codeHash {
writeError(r, w, http.StatusNotFound, "状态页未开启")
return
}
payload := statusPagePayload{
Title: "Havline 服务状态",
CodeRequired: codeRequired,
CheckedAt: time.Now().UTC().Format(time.RFC3339),
Routes: make([]statusPageRoute, 0),
}
if err := appendFRPStatus(&payload, h.frp, r.Context()); err != nil {
writeError(r, w, http.StatusInternalServerError, "读取状态失败", err)
return
}
if err := appendCloudflareStatus(&payload, h.cloudflare, r.Context()); err != nil {
writeError(r, w, http.StatusInternalServerError, "读取状态失败", err)
return
}
writeJSON(w, http.StatusOK, payload)
}
func appendFRPStatus(payload *statusPagePayload, svc *frp.Service, ctx context.Context) error {
if svc == nil {
return nil
}
stats, err := svc.RouteUptime(ctx, 24*time.Hour)
if err != nil {
return err
}
for _, stat := range stats {
switch stat.State {
case frp.RouteHealthUp:
payload.Up++
case frp.RouteHealthDown:
payload.Down++
default:
payload.Unknown++
}
payload.Routes = append(payload.Routes, statusPageRoute{
Domain: stat.Domain,
State: stat.State,
Source: "frp",
Uptime: stat.Uptime,
DownMinutes: stat.DownMinutes,
UnknownMinutes: stat.UnknownMinutes,
Incidents: mapFRPIncidents(stat.Incidents),
})
}
return nil
}
func appendCloudflareStatus(payload *statusPagePayload, svc *cloudflared.Service, ctx context.Context) error {
if svc == nil {
return nil
}
stats, err := svc.HealthUptime(ctx, 24*time.Hour)
if err != nil {
return err
}
for _, stat := range stats {
switch stat.State {
case cloudflared.HealthUp:
payload.Up++
case cloudflared.HealthDown:
payload.Down++
default:
payload.Unknown++
}
payload.Routes = append(payload.Routes, statusPageRoute{
Domain: stat.Domain,
State: stat.State,
Source: "cloudflare",
Uptime: stat.Uptime,
DownMinutes: stat.DownMinutes,
UnknownMinutes: stat.UnknownMinutes,
Incidents: mapCloudflareIncidents(stat.Incidents),
})
}
return nil
}
func mapFRPIncidents(items []frp.RouteHealthIncident) []statusPageIncident {
out := make([]statusPageIncident, 0, len(items))
for _, item := range items {
out = append(out, statusPageIncident{
From: item.From, To: item.To, Reason: item.Reason, Detail: item.Detail, Minutes: item.Minutes,
})
}
return out
}
func mapCloudflareIncidents(items []cloudflared.HealthIncident) []statusPageIncident {
out := make([]statusPageIncident, 0, len(items))
for _, item := range items {
out = append(out, statusPageIncident{
From: item.From, To: item.To, Reason: item.Reason, Detail: item.Detail, Minutes: item.Minutes,
})
}
return out
}
func hashStatusPageCode(code string) string {
sum := sha256.Sum256([]byte(strings.TrimSpace(code)))
return hex.EncodeToString(sum[:])
}
// clientIPForLimit 取限流用的客户端 IP
func clientIPForLimit(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
}
// statusPageLimiter 按 IP 的滑动窗口限流;只给匿名状态页用
type statusPageLimiter struct {
mu sync.Mutex
hits map[string][]time.Time
now func() time.Time
}
func newStatusPageLimiter() *statusPageLimiter {
return &statusPageLimiter{hits: map[string][]time.Time{}, now: time.Now}
}
func (l *statusPageLimiter) allow(ip string) bool {
now := l.now()
cutoff := now.Add(-statusPageWindow)
l.mu.Lock()
defer l.mu.Unlock()
kept := make([]time.Time, 0, len(l.hits[ip])+1)
for _, at := range l.hits[ip] {
if at.After(cutoff) {
kept = append(kept, at)
}
}
if len(kept) >= statusPageLimit {
l.hits[ip] = kept
return false
}
l.hits[ip] = append(kept, now)
// 顺手清理长期不活跃的 IP,避免 map 无限增长
if len(l.hits) > 1024 {
for key, times := range l.hits {
if len(times) == 0 {
delete(l.hits, key)
}
}
}
return true
}
// MaskedStatusPageCode 供设置接口回显用(与通知模块的掩码约定一致)
const MaskedStatusPageCode = notify.MaskedSecret
+43
View File
@@ -0,0 +1,43 @@
package api
import (
"testing"
"time"
)
func TestStatusPageLimiterBlocksAfterLimit(t *testing.T) {
limiter := newStatusPageLimiter()
now := time.Date(2026, 9, 25, 10, 0, 0, 0, time.UTC)
limiter.now = func() time.Time { return now }
for i := 0; i < statusPageLimit; i++ {
if !limiter.allow("1.2.3.4") {
t.Fatalf("第 %d 次请求应放行", i+1)
}
}
if limiter.allow("1.2.3.4") {
t.Fatal("超过配额应拒绝")
}
// 限流按 IP 计:别的访客不该被牵连
if !limiter.allow("5.6.7.8") {
t.Fatal("其它 IP 不应被牵连")
}
// 窗口滑过后恢复
now = now.Add(statusPageWindow + time.Second)
if !limiter.allow("1.2.3.4") {
t.Fatal("窗口过后应恢复放行")
}
}
func TestHashStatusPageCodeHidesPlaintext(t *testing.T) {
hash := hashStatusPageCode("my-secret")
if hash == "my-secret" || len(hash) != 64 {
t.Fatalf("访问码应以 SHA-256 存储,实际 %q", hash)
}
if hashStatusPageCode(" my-secret ") != hash {
t.Fatal("前后空白裁剪后应得到同一哈希")
}
if hashStatusPageCode("other") == hash {
t.Fatal("不同访问码不应得到同一哈希")
}
}
+65
View File
@@ -0,0 +1,65 @@
package api
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"github.com/havline/havline/internal/db"
"github.com/havline/havline/internal/terminal"
)
// TestListAuditsHandler:审计接口返回落库记录;未接存储时返回空数组而不是 null。
func TestListAuditsHandler(t *testing.T) {
conn, err := db.Open(filepath.Join(t.TempDir(), "audit.db"))
if err != nil {
t.Fatalf("打开数据库失败:%v", err)
}
defer conn.Close()
if err := db.Migrate(context.Background(), conn, filepath.Join("..", "..", "migrations")); err != nil {
t.Fatalf("迁移失败:%v", err)
}
store := terminal.NewAuditStore(conn)
now := time.Now().UTC()
entry := terminal.AuditEntry{
SessionID: "s1", ServerID: 3, Target: "东京 VPS · root@10.0.0.1",
User: "admin", ClientIP: "192.168.1.9",
StartedAt: now.Format(time.RFC3339), EndedAt: now.Add(time.Second).Format(time.RFC3339),
DurationMS: 1_000, Reason: "用户关闭",
}
if err := store.WriteAudit(context.Background(), entry); err != nil {
t.Fatalf("写入审计失败:%v", err)
}
handler := NewTerminalHandler(TerminalHandlerOptions{Audits: store})
rec := httptest.NewRecorder()
handler.ListAudits(rec, httptest.NewRequest(http.MethodGet, "/api/terminal/audits", nil))
if rec.Code != http.StatusOK {
t.Fatalf("状态码不符:%d %s", rec.Code, rec.Body.String())
}
var body struct {
Entries []terminal.AuditEntry `json:"entries"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("解析响应失败:%v", err)
}
if len(body.Entries) != 1 {
t.Fatalf("期望 1 条审计,实际 %d 条", len(body.Entries))
}
if body.Entries[0].User != "admin" || body.Entries[0].Reason != "用户关闭" {
t.Fatalf("审计字段不符:%+v", body.Entries[0])
}
// 未接存储时也要给前端一个数组,避免前端拿到 null 崩掉
empty := NewTerminalHandler(TerminalHandlerOptions{})
emptyRec := httptest.NewRecorder()
empty.ListAudits(emptyRec, httptest.NewRequest(http.MethodGet, "/api/terminal/audits", nil))
if got := emptyRec.Body.String(); got != "{\"entries\":[]}\n" {
t.Fatalf("空审计响应不符:%s", got)
}
}
+535
View File
@@ -0,0 +1,535 @@
package api
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/havline/havline/internal/auth"
"github.com/havline/havline/internal/frp"
"github.com/havline/havline/internal/settings"
"github.com/havline/havline/internal/terminal"
)
// 终端通道的读超时:前端每 30 秒发一次 ping,这里留 3 倍余量。
const terminalReadTimeout = 90 * time.Second
// TerminalHandlerOptions 是终端处理器的装配参数;Manager 为 nil 时相关接口返回不可用。
type TerminalHandlerOptions struct {
FRP *frp.Service
Settings *settings.Store
Auth *auth.Service
Manager *terminal.Manager
Audits *terminal.AuditStore
// Commands 是「常用命令」存储;为 nil 时相关接口返回空列表
Commands *terminal.CommandStore
// Recordings 是会话录制存储;为 nil 时录制接口返回空
Recordings *terminal.RecordingStore
// Unlocks 与 AuthHandler 共用同一份解锁票据:改密后要让当前会话立即失效
Unlocks *terminalUnlockStore
Logger *slog.Logger
}
// TerminalHandler 提供内置 SSH 终端:目标列表、会话创建、WebSocket 双向通道与关闭。
type TerminalHandler struct {
frp *frp.Service
settings *settings.Store
auth *auth.Service
manager *terminal.Manager
audits *terminal.AuditStore
commands *terminal.CommandStore
recordings *terminal.RecordingStore
unlocks *terminalUnlockStore
guard *loginGuard
logger *slog.Logger
upgrader websocket.Upgrader
}
// NewTerminalHandler 装配终端处理器。
func NewTerminalHandler(opts TerminalHandlerOptions) *TerminalHandler {
logger := opts.Logger
if logger == nil {
logger = slog.Default()
}
unlocks := opts.Unlocks
if unlocks == nil {
unlocks = newTerminalUnlockStore()
}
return &TerminalHandler{
frp: opts.FRP, settings: opts.Settings, auth: opts.Auth, manager: opts.Manager,
audits: opts.Audits, commands: opts.Commands, recordings: opts.Recordings,
unlocks: unlocks, guard: newLoginGuard(), logger: logger,
upgrader: websocket.Upgrader{
ReadBufferSize: 4096,
WriteBufferSize: 4096,
CheckOrigin: allowSameOrigin,
},
}
}
// allowSameOrigin 只允许同源页面建立 WebSocket,避免第三方页面借用已登录会话。
func allowSameOrigin(r *http.Request) bool {
origin := strings.TrimSpace(r.Header.Get("Origin"))
if origin == "" {
return true
}
parsed, err := url.Parse(origin)
if err != nil {
return false
}
return strings.EqualFold(parsed.Host, r.Host)
}
type terminalTarget struct {
Value string `json:"value"`
Label string `json:"label"`
Detail string `json:"detail"`
Ready bool `json:"ready"`
Disabled string `json:"disabled_reason,omitempty"`
}
type terminalCreateRequest struct {
ServerID int64 `json:"server_id"`
Cols int `json:"cols"`
Rows int `json:"rows"`
}
// terminalUnlockRequest 是终端二次认证的请求体。
type terminalUnlockRequest struct {
Password string `json:"password"`
}
// terminalCommandRequest 是新增快捷命令的请求体。
type terminalCommandRequest struct {
Name string `json:"name"`
Command string `json:"command"`
}
type terminalClientMessage struct {
Type string `json:"type"`
Data string `json:"data,omitempty"`
Cols int `json:"cols,omitempty"`
Rows int `json:"rows,omitempty"`
}
type terminalServerMessage struct {
Type string `json:"type"`
Data string `json:"data,omitempty"`
Reason string `json:"reason,omitempty"`
Message string `json:"message,omitempty"`
}
// ListTargets 返回可选目标:只列出已配置 SSH 的服务端,未配置的给出原因。
func (h *TerminalHandler) ListTargets(w http.ResponseWriter, r *http.Request) {
if !h.requireEnabled(r, w) {
return
}
servers, err := h.frp.ListServers(r.Context())
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取服务端列表失败", err)
return
}
targets := make([]terminalTarget, 0, len(servers))
for _, server := range servers {
item := terminalTarget{
Value: strconv.FormatInt(server.ID, 10),
Label: server.Name,
Detail: fmt.Sprintf("%s@%s:%d", server.SSHUser, server.SSHHost, server.SSHPort),
Ready: server.SSHConfigured,
}
if !server.SSHConfigured {
item.Disabled = "未配置 SSH,请到「公网服务端」填写"
}
targets = append(targets, item)
}
writeJSON(w, http.StatusOK, map[string]any{"targets": targets})
}
// ListRecordings 返回磁盘上的会话录制,供「录像审计」列表使用。
func (h *TerminalHandler) ListRecordings(w http.ResponseWriter, r *http.Request) {
if !h.requireEnabled(r, w) {
return
}
if h.recordings == nil {
writeJSON(w, http.StatusOK, map[string]any{"recordings": []terminal.Recording{}})
return
}
items, err := h.recordings.List()
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取录制列表失败", err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"recordings": items})
}
// GetRecording 读取一段录制(asciinema v2 文本),供前端回放。
func (h *TerminalHandler) GetRecording(w http.ResponseWriter, r *http.Request) {
if !h.requireEnabled(r, w) {
return
}
if h.recordings == nil {
writeError(r, w, http.StatusNotFound, "录制不存在或已被清理")
return
}
id := r.PathValue("id")
path, ok := h.recordings.Path(id)
if !ok {
writeError(r, w, http.StatusBadRequest, "录制 ID 不合法")
return
}
file, err := os.Open(path)
if err != nil {
writeError(r, w, http.StatusNotFound, "录制不存在或已被清理")
return
}
defer file.Close()
info, err := file.Stat()
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取录制失败", err)
return
}
// 录制内容按原样返回:前端按 asciinema v2 解析后逐帧回放
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
http.ServeContent(w, r, id+".cast", info.ModTime(), file)
}
// ListCommands 返回已保存的快捷命令(右侧「常用命令」面板)。
func (h *TerminalHandler) ListCommands(w http.ResponseWriter, r *http.Request) {
if !h.requireEnabled(r, w) {
return
}
if h.commands == nil {
writeJSON(w, http.StatusOK, map[string]any{"commands": []terminal.TerminalCommand{}})
return
}
commands, err := h.commands.ListCommands(r.Context())
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取常用命令失败", err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"commands": commands})
}
// CreateCommand 保存一条快捷命令。
func (h *TerminalHandler) CreateCommand(w http.ResponseWriter, r *http.Request) {
if !h.requireEnabled(r, w) {
return
}
if h.commands == nil {
writeError(r, w, http.StatusServiceUnavailable, "常用命令当前不可用")
return
}
var req terminalCommandRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
command, err := h.commands.CreateCommand(r.Context(), req.Name, req.Command)
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error(), err)
return
}
writeJSON(w, http.StatusCreated, command)
}
// DeleteCommand 删除一条快捷命令。
func (h *TerminalHandler) DeleteCommand(w http.ResponseWriter, r *http.Request) {
if !h.requireEnabled(r, w) {
return
}
if h.commands == nil {
writeError(r, w, http.StatusServiceUnavailable, "常用命令当前不可用")
return
}
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil || id <= 0 {
writeError(r, w, http.StatusBadRequest, "命令 ID 无效")
return
}
if err := h.commands.DeleteCommand(r.Context(), id); err != nil {
if errors.Is(err, terminal.ErrCommandNotFound) {
writeError(r, w, http.StatusNotFound, err.Error())
return
}
writeError(r, w, http.StatusInternalServerError, "删除常用命令失败", err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
// UnlockStatus 返回当前登录会话的终端解锁状态,供前端显示剩余时间。
func (h *TerminalHandler) UnlockStatus(w http.ResponseWriter, r *http.Request) {
if !h.requireEnabled(r, w) {
return
}
expires, ok := h.unlocks.expiresAt(sessionIDFromContext(r.Context()))
if !ok {
writeJSON(w, http.StatusOK, map[string]any{"unlocked": false})
return
}
writeJSON(w, http.StatusOK, map[string]any{
"unlocked": true,
"expires_at": expires.UTC().Format(time.RFC3339),
})
}
// Unlock 校验管理员密码,换取终端短时解锁。
// 这是「登录态点一下就能拿到 root shell」与「还需要知道一个密码」之间的那道门。
func (h *TerminalHandler) Unlock(w http.ResponseWriter, r *http.Request) {
if !h.requireEnabled(r, w) {
return
}
sessionID := sessionIDFromContext(r.Context())
if sessionID == "" {
// 终端不接受 API Token,二次认证也必须走浏览器会话
writeErrorCode(r, w, http.StatusForbidden, "terminal_session_required", "终端二次认证需要使用浏览器登录会话")
return
}
ip := clientIP(r)
if h.guard.blocked(ip) {
writeErrorCode(r, w, http.StatusTooManyRequests, "too_many_attempts", "密码错误次数过多,请 5 分钟后再试")
return
}
var req terminalUnlockRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
adminID, err := h.auth.AdminIDForSession(r.Context(), sessionID)
if err != nil {
writeError(r, w, http.StatusUnauthorized, "未登录或会话已过期")
return
}
// 密码原样比对:不做 TrimSpace,避免把首尾空格当作无关字符
if err := h.auth.VerifyPassword(r.Context(), adminID, req.Password); err != nil {
h.guard.fail(ip)
h.logger.Warn("终端二次认证失败", "module", "TERMINAL", "client_ip", ip, "admin_id", adminID)
writeErrorCode(r, w, http.StatusUnauthorized, "bad_password", "管理员密码不正确")
return
}
h.guard.reset(ip)
expires := h.unlocks.grant(sessionID)
h.logger.Info("终端二次认证通过",
"module", "TERMINAL", "client_ip", ip, "admin_id", adminID,
"expires_at", expires.UTC().Format(time.RFC3339))
writeJSON(w, http.StatusOK, map[string]any{"expires_at": expires.UTC().Format(time.RFC3339)})
}
// Lock 主动锁定当前会话的终端解锁,之后新建会话需要重新输入密码。
func (h *TerminalHandler) Lock(w http.ResponseWriter, r *http.Request) {
h.unlocks.revoke(sessionIDFromContext(r.Context()))
h.logger.Info("终端已锁定", "module", "TERMINAL", "client_ip", clientIP(r))
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
// CreateSession 建立一条新的 SSH 终端会话。
func (h *TerminalHandler) CreateSession(w http.ResponseWriter, r *http.Request) {
if !h.requireEnabled(r, w) {
return
}
// 二次认证:没有有效解锁票据(或已过期)就不许建会话
if _, unlocked := h.unlocks.expiresAt(sessionIDFromContext(r.Context())); !unlocked {
writeErrorCode(r, w, http.StatusForbidden, "terminal_locked", "终端需要二次认证:请先输入管理员密码解锁")
return
}
var req terminalCreateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
if req.ServerID <= 0 {
writeError(r, w, http.StatusBadRequest, "请选择要连接的服务端")
return
}
// SSH 认证 + PTY 申请需要时间,单独给 30 秒上限
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
user, clientIP := h.terminalActor(r)
// 录制开关默认关闭:开启后本次会话输出会写入 logs/terminal
record, err := h.settings.GetBool(r.Context(), settings.KeyTerminalRecording)
if err != nil {
record = false
}
session, err := h.manager.Create(ctx, terminal.CreateOptions{
ServerID: req.ServerID,
Cols: req.Cols,
Rows: req.Rows,
User: user,
ClientIP: clientIP,
Record: record,
})
if err != nil {
writeTerminalError(r, w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"session_id": session.ID, "label": session.Label})
}
// ListAudits 返回最近的终端会话审计:谁、何时、连了哪台、多久、为什么断开。
func (h *TerminalHandler) ListAudits(w http.ResponseWriter, r *http.Request) {
if h.audits == nil {
writeJSON(w, http.StatusOK, map[string]any{"entries": []terminal.AuditEntry{}})
return
}
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
entries, err := h.audits.ListAudits(r.Context(), limit)
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取终端审计记录失败", err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"entries": entries})
}
// terminalActor 解析审计需要的调用方身份:登录用户名与来源 IP。
// 用 API Token 调用时没有会话 Cookie,这里如实记成「API Token」而不是伪造用户名。
func (h *TerminalHandler) terminalActor(r *http.Request) (string, string) {
ip := clientIP(r)
if bearerToken(r) != "" {
return "API Token", ip
}
sessionID := sessionIDFromContext(r.Context())
if sessionID == "" || h.auth == nil {
return "未知", ip
}
adminID, err := h.auth.AdminIDForSession(r.Context(), sessionID)
if err != nil {
return "未知", ip
}
username, err := h.auth.AdminUsername(r.Context(), adminID)
if err != nil || strings.TrimSpace(username) == "" {
return "未知", ip
}
return username, ip
}
// ListSessions 返回当前会话快照(前端刷新后清理与排查用)。
func (h *TerminalHandler) ListSessions(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"sessions": h.manager.List()})
}
// CloseSession 主动关闭会话。用户点「关闭」或页面卸载时调用。
func (h *TerminalHandler) CloseSession(w http.ResponseWriter, r *http.Request) {
h.manager.Close(r.PathValue("id"), "用户关闭")
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
// Stream 是终端双向通道:浏览器发送按键/尺寸,服务端推送输出与结束原因。
func (h *TerminalHandler) Stream(w http.ResponseWriter, r *http.Request) {
if !h.requireEnabled(r, w) {
return
}
id := r.PathValue("id")
session, ok := h.manager.Get(id)
if !ok {
writeError(r, w, http.StatusNotFound, "终端会话不存在或已关闭")
return
}
conn, err := h.upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
defer conn.Close()
go h.readClient(conn, session, id)
h.writeClient(conn, session)
}
// writeClient 把会话输出推给浏览器;订阅通道关闭表示会话结束。
func (h *TerminalHandler) writeClient(conn *websocket.Conn, session *terminal.Session) {
chunks, cancel := session.Subscribe()
defer cancel()
for chunk := range chunks {
message := terminalServerMessage{Type: "output", Data: base64.StdEncoding.EncodeToString(chunk)}
if err := writeSocketMessage(conn, message); err != nil {
return
}
}
_ = writeSocketMessage(conn, terminalServerMessage{Type: "exit", Reason: session.Snapshot().Reason})
}
// readClient 处理按键与窗口尺寸;连接断开时立刻回收会话。
func (h *TerminalHandler) readClient(conn *websocket.Conn, session *terminal.Session, id string) {
conn.SetReadLimit(1 << 20)
for {
_ = conn.SetReadDeadline(time.Now().Add(terminalReadTimeout))
_, payload, err := conn.ReadMessage()
if err != nil {
h.manager.Close(id, "前端断开")
return
}
var message terminalClientMessage
if err := json.Unmarshal(payload, &message); err != nil {
continue
}
h.dispatchClientMessage(session, message)
}
}
func (h *TerminalHandler) dispatchClientMessage(session *terminal.Session, message terminalClientMessage) {
switch message.Type {
case "input":
data, err := base64.StdEncoding.DecodeString(message.Data)
if err != nil {
return
}
_ = session.Input(data)
case "resize":
_ = session.Resize(message.Cols, message.Rows)
}
}
func writeSocketMessage(conn *websocket.Conn, message terminalServerMessage) error {
payload, err := json.Marshal(message)
if err != nil {
return err
}
_ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
return conn.WriteMessage(websocket.TextMessage, payload)
}
// terminalEnabled 读设置开关:缺省视为关闭(shell 入口必须显式打开)。
func (h *TerminalHandler) terminalEnabled(r *http.Request) (bool, error) {
// 用 GetBool 而不是只认 "1":设置页写 "1"/"0",但 true/on 这类写法也应被认作开启,
// 否则开关看着是开的、接口却按未启用拒绝,排查起来很费劲
return h.settings.GetBool(r.Context(), settings.KeyTerminalEnabled)
}
// requireEnabled 检查设置开关与运行能力;未通过时直接写出错误并返回 false。
func (h *TerminalHandler) requireEnabled(r *http.Request, w http.ResponseWriter) bool {
enabled, err := h.terminalEnabled(r)
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取设置失败", err)
return false
}
if !enabled {
writeError(r, w, http.StatusForbidden, "SSH 终端未启用:请到「系统设置」打开后再使用")
return false
}
if h.manager == nil || !h.manager.Enabled() {
writeError(r, w, http.StatusServiceUnavailable, "SSH 终端当前不可用")
return false
}
return true
}
func writeTerminalError(r *http.Request, w http.ResponseWriter, err error) {
switch {
case errors.Is(err, terminal.ErrDisabled):
writeError(r, w, http.StatusForbidden, "SSH 终端未启用")
case errors.Is(err, terminal.ErrTooManySessions):
writeError(r, w, http.StatusTooManyRequests, err.Error())
case errors.Is(err, terminal.ErrNotFound):
writeError(r, w, http.StatusNotFound, err.Error())
default:
writeError(r, w, http.StatusBadGateway, err.Error())
}
}
+70
View File
@@ -0,0 +1,70 @@
package api
import (
"sync"
"time"
)
// terminalUnlockTTL 是一次二次认证的有效期:输一次管理员密码,十分钟内新建会话不再重复输入。
const terminalUnlockTTL = 10 * time.Minute
// terminalUnlockStore 记录「哪个登录会话已通过终端二次认证」。
//
// 只放内存、不落盘:进程重启即全部失效,符合「短时解锁」的定位;
// 键是会话 Cookie 的会话 ID 而不是管理员 ID,换个浏览器/会话就要重新解锁。
type terminalUnlockStore struct {
mu sync.Mutex
expires map[string]time.Time
}
func newTerminalUnlockStore() *terminalUnlockStore {
return &terminalUnlockStore{expires: make(map[string]time.Time)}
}
// grant 记下这次解锁并返回到期时间。
func (s *terminalUnlockStore) grant(sessionID string) time.Time {
now := time.Now()
expires := now.Add(terminalUnlockTTL)
s.mu.Lock()
defer s.mu.Unlock()
s.pruneLocked(now)
s.expires[sessionID] = expires
return expires
}
// expiresAt 返回该会话的解锁到期时间;未解锁或已过期返回 false。
func (s *terminalUnlockStore) expiresAt(sessionID string) (time.Time, bool) {
if sessionID == "" {
return time.Time{}, false
}
s.mu.Lock()
defer s.mu.Unlock()
expires, ok := s.expires[sessionID]
if !ok {
return time.Time{}, false
}
if time.Now().After(expires) {
delete(s.expires, sessionID)
return time.Time{}, false
}
return expires, true
}
// revoke 主动锁定:用户点锁定,或改密后让当前会话立即失效。
func (s *terminalUnlockStore) revoke(sessionID string) {
if sessionID == "" {
return
}
s.mu.Lock()
defer s.mu.Unlock()
delete(s.expires, sessionID)
}
// pruneLocked 清理过期条目,避免长期运行后 map 里堆积失效的旧会话(调用方需持锁)。
func (s *terminalUnlockStore) pruneLocked(now time.Time) {
for sessionID, expires := range s.expires {
if now.After(expires) {
delete(s.expires, sessionID)
}
}
}
+273
View File
@@ -0,0 +1,273 @@
package api
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/havline/havline/internal/auth"
"github.com/havline/havline/internal/db"
"github.com/havline/havline/internal/settings"
"github.com/havline/havline/internal/terminal"
)
const (
testAdminPassword = "admin-password-123"
)
// TestTerminalUnlockStore:票据按时失效、可主动撤销,过期条目会被顺带清理。
func TestTerminalUnlockStore(t *testing.T) {
store := newTerminalUnlockStore()
const testSessionID = "session-abc"
if _, ok := store.expiresAt(testSessionID); ok {
t.Fatal("未解锁的会话不应有效")
}
expires := store.grant(testSessionID)
if !expires.After(time.Now()) {
t.Fatalf("解锁到期时间应当在未来:%v", expires)
}
if _, ok := store.expiresAt(testSessionID); !ok {
t.Fatal("解锁后应当有效")
}
store.revoke(testSessionID)
if _, ok := store.expiresAt(testSessionID); ok {
t.Fatal("锁定后应当失效")
}
// 手动塞一条过期记录,grant 时应当被清掉
store.expires["stale"] = time.Now().Add(-time.Minute)
store.grant("other")
if _, ok := store.expires["stale"]; ok {
t.Fatal("过期条目未被清理")
}
}
// TestTerminalUnlockFlow:未解锁不能建会话 → 密码错误被拒并计数 → 解锁后可建会话 → 可主动锁定。
func TestTerminalUnlockFlow(t *testing.T) {
handler, openerCalled, sessionID := newUnlockTestHandler(t)
// 1) 未解锁:建会话被拒,并给出稳定错误码
rec := callTerminal(t, handler.CreateSession, http.MethodPost, `{"server_id":1,"cols":80,"rows":24}`, sessionID)
if rec.Code != http.StatusForbidden {
t.Fatalf("未解锁建会话应当 403,实际 %d %s", rec.Code, rec.Body.String())
}
if code := errorCode(t, rec); code != "terminal_locked" {
t.Fatalf("错误码应当是 terminal_locked,实际 %q", code)
}
if *openerCalled {
t.Fatal("未解锁就触发了后端连接")
}
// 2) 密码错误:401,且不发放票据
rec = callTerminal(t, handler.Unlock, http.MethodPost, `{"password":"wrong-password"}`, sessionID)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("错误密码应当 401,实际 %d %s", rec.Code, rec.Body.String())
}
if code := errorCode(t, rec); code != "bad_password" {
t.Fatalf("错误码应当是 bad_password,实际 %q", code)
}
if _, ok := handler.unlocks.expiresAt(sessionID); ok {
t.Fatal("密码错误却发放了解锁票据")
}
// 3) 密码正确:解锁成功
rec = callTerminal(t, handler.Unlock, http.MethodPost, `{"password":"`+testAdminPassword+`"}`, sessionID)
if rec.Code != http.StatusOK {
t.Fatalf("正确密码应当 200,实际 %d %s", rec.Code, rec.Body.String())
}
var unlocked struct {
ExpiresAt string `json:"expires_at"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &unlocked); err != nil || unlocked.ExpiresAt == "" {
t.Fatalf("解锁响应缺少 expires_at:%s", rec.Body.String())
}
// 状态接口能读到剩余时间
rec = callTerminal(t, handler.UnlockStatus, http.MethodGet, "", sessionID)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"unlocked":true`) {
t.Fatalf("解锁状态不符:%d %s", rec.Code, rec.Body.String())
}
// 4) 已解锁:放行到后端连接(测试用 Opener 固定失败,所以这里是 502 而不是 403)
rec = callTerminal(t, handler.CreateSession, http.MethodPost, `{"server_id":1,"cols":80,"rows":24}`, sessionID)
if rec.Code == http.StatusForbidden {
t.Fatalf("解锁后仍被拦:%s", rec.Body.String())
}
if !*openerCalled {
t.Fatal("解锁后应当尝试连接后端")
}
// 5) 主动锁定
rec = callTerminal(t, handler.Lock, http.MethodDelete, "", sessionID)
if rec.Code != http.StatusOK {
t.Fatalf("锁定失败:%d %s", rec.Code, rec.Body.String())
}
if _, ok := handler.unlocks.expiresAt(sessionID); ok {
t.Fatal("锁定后票据仍有效")
}
}
// TestTerminalUnlockRateLimit:同一 IP 连续失败到阈值后被锁定。
func TestTerminalUnlockRateLimit(t *testing.T) {
handler, _, sessionID := newUnlockTestHandler(t)
for i := 0; i < loginFailureLimit; i++ {
rec := callTerminal(t, handler.Unlock, http.MethodPost, `{"password":"wrong-password"}`, sessionID)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("第 %d 次失败应当 401,实际 %d", i+1, rec.Code)
}
}
rec := callTerminal(t, handler.Unlock, http.MethodPost, `{"password":"wrong-password"}`, sessionID)
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("超过阈值应当 429,实际 %d %s", rec.Code, rec.Body.String())
}
if code := errorCode(t, rec); code != "too_many_attempts" {
t.Fatalf("错误码应当是 too_many_attempts,实际 %q", code)
}
// 锁定期间即使密码正确也不放行
rec = callTerminal(t, handler.Unlock, http.MethodPost, `{"password":"`+testAdminPassword+`"}`, sessionID)
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("锁定期间应当继续 429,实际 %d", rec.Code)
}
}
// TestTerminalCommandsAPI:常用命令的新增、列表与删除。
func TestTerminalCommandsAPI(t *testing.T) {
handler, _, sessionID := newUnlockTestHandler(t)
rec := callTerminal(t, handler.CreateCommand, http.MethodPost, `{"name":"磁盘占用","command":"df -h"}`, sessionID)
if rec.Code != http.StatusCreated {
t.Fatalf("新增命令应当 201,实际 %d %s", rec.Code, rec.Body.String())
}
var created terminal.TerminalCommand
if err := json.Unmarshal(rec.Body.Bytes(), &created); err != nil || created.ID == 0 {
t.Fatalf("新增响应缺少 ID:%s", rec.Body.String())
}
rec = callTerminal(t, handler.ListCommands, http.MethodGet, "", sessionID)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "df -h") {
t.Fatalf("列表未包含新增命令:%d %s", rec.Code, rec.Body.String())
}
// 空名称应当被拒
rec = callTerminal(t, handler.CreateCommand, http.MethodPost, `{"name":" ","command":"ls"}`, sessionID)
if rec.Code != http.StatusBadRequest {
t.Fatalf("空名称应当 400,实际 %d", rec.Code)
}
// 删除要走带路径参数的分支,这里手工塞 PathValue
if code := deleteCommand(t, handler, sessionID, created.ID); code != http.StatusOK {
t.Fatalf("删除应当 200,实际 %d", code)
}
if code := deleteCommand(t, handler, sessionID, created.ID); code != http.StatusNotFound {
t.Fatalf("重复删除应当 404,实际 %d", code)
}
}
// deleteCommand 按路由形态调用删除接口(PathValue 由 ServeMux 注入,测试里手工设置)。
func deleteCommand(t *testing.T, handler *TerminalHandler, sessionID string, id int64) int {
t.Helper()
raw := strconv.FormatInt(id, 10)
req := httptest.NewRequest(http.MethodDelete, "/api/terminal/commands/"+raw, nil)
req.AddCookie(&http.Cookie{Name: "havline_session", Value: sessionID})
req.SetPathValue("id", raw)
rec := httptest.NewRecorder()
SessionMiddleware(nil)(http.HandlerFunc(handler.DeleteCommand)).ServeHTTP(rec, req)
return rec.Code
}
// TestTokenDeniedPathCoversTerminal:终端不接受 API Token,否则二次认证可以被绕过。
func TestTokenDeniedPathCoversTerminal(t *testing.T) {
for _, path := range []string{
"/api/terminal/targets",
"/api/terminal/unlock",
"/api/terminal/sessions",
} {
if !tokenDeniedPath(path) {
t.Fatalf("%s 应当只允许浏览器会话", path)
}
}
if tokenDeniedPath("/api/proxies") {
t.Fatal("普通接口不应被限制")
}
}
// newUnlockTestHandler 造一套「终端已开启 + 已初始化管理员」的处理器,并返回一个真实会话 ID。
func newUnlockTestHandler(t *testing.T) (*TerminalHandler, *bool, string) {
t.Helper()
conn, err := db.Open(filepath.Join(t.TempDir(), "havline.db"))
if err != nil {
t.Fatalf("打开数据库失败:%v", err)
}
t.Cleanup(func() { conn.Close() })
if err := db.Migrate(context.Background(), conn, filepath.Join("..", "..", "migrations")); err != nil {
t.Fatalf("迁移失败:%v", err)
}
ctx := context.Background()
authSvc := auth.New(conn)
if err := authSvc.Setup(ctx, "admin", testAdminPassword); err != nil {
t.Fatalf("初始化管理员失败:%v", err)
}
settingsStore := settings.NewStore(conn)
if err := settingsStore.SetBool(ctx, settings.KeyTerminalEnabled, true); err != nil {
t.Fatalf("打开终端开关失败:%v", err)
}
// 解锁票据绑定真实会话:没有这条会话记录,AdminIDForSession 会先拒绝
sessionID, err := authSvc.Login(ctx, "admin", testAdminPassword)
if err != nil {
t.Fatalf("登录失败:%v", err)
}
openerCalled := false
manager := terminal.NewManager(
slog.New(slog.NewTextHandler(io.Discard, nil)),
func(context.Context, int64, int, int) (terminal.Terminal, string, error) {
openerCalled = true
return nil, "", errors.New("测试环境不建立真实连接")
},
terminal.Options{},
)
handler := NewTerminalHandler(TerminalHandlerOptions{
Auth: authSvc,
Settings: settingsStore,
Manager: manager,
Unlocks: newTerminalUnlockStore(),
Commands: terminal.NewCommandStore(conn),
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
})
return handler, &openerCalled, sessionID
}
// callTerminal 带上会话 Cookie 调用处理器;SessionMiddleware 只读 Cookie,这里复用它注入会话。
func callTerminal(t *testing.T, next http.HandlerFunc, method, body, sessionID string) *httptest.ResponseRecorder {
t.Helper()
var reader io.Reader
if body != "" {
reader = strings.NewReader(body)
}
req := httptest.NewRequest(method, "/api/terminal", reader)
req.AddCookie(&http.Cookie{Name: "havline_session", Value: sessionID})
rec := httptest.NewRecorder()
SessionMiddleware(nil)(next).ServeHTTP(rec, req)
return rec
}
// errorCode 读出响应体里的稳定错误码。
func errorCode(t *testing.T, rec *httptest.ResponseRecorder) string {
t.Helper()
var body ErrorBody
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("解析错误响应失败:%v", err)
}
return body.Code
}
+72
View File
@@ -0,0 +1,72 @@
package api
import (
"encoding/json"
"net/http"
"strings"
"time"
"github.com/havline/havline/internal/auth"
)
// 令牌管理挂在 AuthHandler 上:它已经持有 auth.Service,不必再加一层 handler。
const maxTokenExpiryDays = 3650
type createTokenRequest struct {
Name string `json:"name"`
Scope string `json:"scope"`
ExpiresInDays int `json:"expires_in_days"`
}
func (h *AuthHandler) ListTokens(w http.ResponseWriter, r *http.Request) {
tokens, err := h.auth.ListAPITokens(r.Context())
if err != nil {
writeError(r, w, http.StatusInternalServerError, "读取令牌失败", err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"tokens": tokens})
}
// CreateToken 新建令牌;明文只在这一个响应里返回,之后无法再取回。
func (h *AuthHandler) CreateToken(w http.ResponseWriter, r *http.Request) {
var req createTokenRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(r, w, http.StatusBadRequest, "请求格式无效")
return
}
scope := strings.TrimSpace(req.Scope)
if scope == "" {
scope = auth.TokenScopeRead
}
var expiresAt time.Time
if req.ExpiresInDays > 0 {
if req.ExpiresInDays > maxTokenExpiryDays {
writeError(r, w, http.StatusBadRequest, "有效期最长 3650 天")
return
}
expiresAt = time.Now().AddDate(0, 0, req.ExpiresInDays)
}
token, err := h.auth.CreateAPIToken(r.Context(), req.Name, scope, expiresAt)
if err != nil {
writeError(r, w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusCreated, token)
}
func (h *AuthHandler) DeleteToken(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(r, w, http.StatusBadRequest, "无效的令牌 ID")
return
}
if err := h.auth.DeleteAPIToken(r.Context(), id); err != nil {
if err.Error() == "令牌不存在" {
writeError(r, w, http.StatusNotFound, err.Error())
return
}
writeError(r, w, http.StatusInternalServerError, "删除令牌失败", err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
+45
View File
@@ -0,0 +1,45 @@
package api
import (
"net/http"
"github.com/havline/havline/internal/updater"
)
type UpdateHandler struct {
client *updater.Client
}
func NewUpdateHandler(client *updater.Client) *UpdateHandler {
return &UpdateHandler{client: client}
}
func (h *UpdateHandler) Status(w http.ResponseWriter, r *http.Request) {
if h.client == nil || !h.client.Enabled() {
writeJSON(w, http.StatusOK, updater.Status{
Enabled: false,
Phase: updater.PhaseIdle,
Message: "当前部署未启用一键升级",
})
return
}
status, err := h.client.Status(r.Context())
if err != nil {
writeError(r, w, http.StatusBadGateway, "读取升级状态失败", err)
return
}
writeJSON(w, http.StatusOK, status)
}
func (h *UpdateHandler) Apply(w http.ResponseWriter, r *http.Request) {
if h.client == nil || !h.client.Enabled() {
writeError(r, w, http.StatusServiceUnavailable, "当前部署未启用一键升级")
return
}
status, err := h.client.Apply(r.Context())
if err != nil {
writeError(r, w, http.StatusBadGateway, "启动升级失败", err)
return
}
writeJSON(w, http.StatusAccepted, status)
}
+29
View File
@@ -0,0 +1,29 @@
package api
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestUpdateHandlerDisabled(t *testing.T) {
handler := NewUpdateHandler(nil)
statusRecorder := httptest.NewRecorder()
statusReq := httptest.NewRequest(http.MethodGet, "/api/system/update/status", nil)
handler.Status(statusRecorder, statusReq)
if statusRecorder.Code != http.StatusOK {
t.Fatalf("状态接口期望 200,实际 %d", statusRecorder.Code)
}
if body := statusRecorder.Body.String(); !strings.Contains(body, `"enabled":false`) {
t.Fatalf("未返回 enabled=false: %s", body)
}
applyRecorder := httptest.NewRecorder()
applyReq := httptest.NewRequest(http.MethodPost, "/api/system/update/apply", nil)
handler.Apply(applyRecorder, applyReq)
if applyRecorder.Code != http.StatusServiceUnavailable {
t.Fatalf("升级接口期望 503,实际 %d", applyRecorder.Code)
}
}
+24
View File
@@ -0,0 +1,24 @@
package api
import (
"net/http"
"github.com/havline/havline/internal/config"
"github.com/havline/havline/internal/version"
)
type versionResponse struct {
Version string `json:"version"`
NginxHTTPPort int `json:"nginx_http_port"`
NginxHTTPSPort int `json:"nginx_https_port"`
}
func Version(cfg config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, versionResponse{
Version: version.Version,
NginxHTTPPort: cfg.NginxDefaultHTTPPort,
NginxHTTPSPort: cfg.NginxDefaultHTTPSPort,
})
}
}
+36
View File
@@ -0,0 +1,36 @@
package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/havline/havline/internal/config"
"github.com/havline/havline/internal/version"
)
func TestVersionEndpoint(t *testing.T) {
version.Version = "0.1.6"
cfg := config.Config{NginxDefaultHTTPPort: 18080, NginxDefaultHTTPSPort: 9443}
req := httptest.NewRequest(http.MethodGet, "/api/version", nil)
rec := httptest.NewRecorder()
Version(cfg)(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status %d", rec.Code)
}
var body map[string]interface{}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("decode: %v", err)
}
if body["version"] != "0.1.6" {
t.Fatalf("version %q", body["version"])
}
if body["nginx_http_port"] != float64(18080) {
t.Fatalf("nginx_http_port %v", body["nginx_http_port"])
}
if body["nginx_https_port"] != float64(9443) {
t.Fatalf("nginx_https_port %v", body["nginx_https_port"])
}
}
+478
View File
@@ -0,0 +1,478 @@
package app
import (
"context"
"fmt"
"io"
"io/fs"
"log/slog"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/havline/havline/internal/acme"
"github.com/havline/havline/internal/api"
"github.com/havline/havline/internal/auth"
"github.com/havline/havline/internal/backup"
"github.com/havline/havline/internal/certificate"
"github.com/havline/havline/internal/chinacidr"
"github.com/havline/havline/internal/cloudflared"
"github.com/havline/havline/internal/config"
"github.com/havline/havline/internal/db"
"github.com/havline/havline/internal/ddns"
"github.com/havline/havline/internal/discovery"
"github.com/havline/havline/internal/frp"
"github.com/havline/havline/internal/logstore"
"github.com/havline/havline/internal/metrics"
"github.com/havline/havline/internal/monitor"
"github.com/havline/havline/internal/nginx"
"github.com/havline/havline/internal/notify"
"github.com/havline/havline/internal/proxy"
"github.com/havline/havline/internal/scheduler"
"github.com/havline/havline/internal/secret"
"github.com/havline/havline/internal/service"
"github.com/havline/havline/internal/settings"
"github.com/havline/havline/internal/terminal"
"github.com/havline/havline/internal/traffic"
"github.com/havline/havline/internal/updater"
)
type App struct {
cfg config.Config
logger *slog.Logger
server *http.Server
nginx *nginx.Manager
frpMulti *frp.Service
cloudflare *cloudflared.Service
scheduler *scheduler.Scheduler
shutdownFn context.CancelFunc
db interface{ Close() error }
}
func New(cfg config.Config, staticFS fs.FS, migrationsDir string) (*App, error) {
appLogWriter := logstore.NewAppLogWriter(cfg.LogsDir())
logger := slog.New(slog.NewJSONHandler(io.MultiWriter(os.Stdout, appLogWriter), &slog.HandlerOptions{Level: slog.LevelInfo}))
slog.SetDefault(logger)
for _, dir := range []string{cfg.DataDir, cfg.NginxDir(), cfg.LogsDir(), cfg.CertsDir(), cfg.FrpDir()} {
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, err
}
}
// 会话密钥:显式配置优先;未配置则在数据目录里读/生成并持久化
// (它同时是 secret box 的加密密钥,所以只在未配置时才生成,不替换已配置的值)
secretSource, err := cfg.ResolveSessionSecret()
if err != nil {
return nil, err
}
logger.Info("会话密钥已就绪", "module", "SYSTEM", "source", secretSource)
// updater Token 只给「一键升级」sidecar 用;原生版与飞牛 Docker 版都显式把 socket 置空,
// 此时不能去写 /run/havline-updater:原生版以非 root 运行,权限不足会让应用直接起不来。
updaterToken, updaterTokenSource, err := updater.EnsureTokenIfEnabled(cfg.UpdaterSocket, cfg.UpdaterToken, cfg.UpdaterTokenFile)
if err != nil {
return nil, err
}
if updaterToken != "" {
logger.Info("updater Token 已就绪", "module", "SYSTEM", "source", updaterTokenSource)
}
conn, err := db.Open(cfg.DBPath())
if err != nil {
return nil, err
}
if err := db.Migrate(context.Background(), conn, migrationsDir); err != nil {
conn.Close()
return nil, err
}
secretBox, err := secret.NewBox(cfg.SessionSecret)
if err != nil {
conn.Close()
return nil, err
}
authSvc := auth.New(conn)
if err := authSvc.EnsureDefaultAdmin(context.Background(), logger); err != nil {
conn.Close()
return nil, fmt.Errorf("bootstrap admin: %w", err)
}
proxyStore := proxy.NewStore(conn)
settingsStore := settings.NewStore(conn)
// 时区必须在任何业务开始前生效:通知时间戳、日志时间、调度判断都依赖 time.Local。
// 设置项缺失或写坏时退回 TZ 环境变量,不让应用起不来。
if loc, err := settings.ApplyTimezone(context.Background(), settingsStore); err != nil {
logger.Warn("应用时区设置失败,沿用系统 TZ", "module", "SYSTEM", "error", err.Error())
} else {
logger.Info("时区已应用", "module", "SYSTEM", "timezone", loc.String())
}
ddnsStore := ddns.NewStore(conn)
certStore := certificate.NewStore(conn)
nginxMgr := nginx.NewManager(cfg, logger.With("module", "NGINX"))
if err := nginxMgr.EnsureDirs(); err != nil {
conn.Close()
return nil, err
}
proxySvc := service.NewProxyService(cfg, conn, proxyStore, certStore, settingsStore, nginxMgr)
chinaCIDRSvc := chinacidr.New(cfg, settingsStore, nginxMgr, proxyStore, logger.With("module", "CHINA_CIDR"))
notifySvc := notify.New(settingsStore, secretBox, logger)
proxySvc.SetNotify(notifySvc)
ddnsSvc := ddns.NewService(ddnsStore, settingsStore, secretBox, logger, notifySvc)
acmeSvc := acme.NewService(cfg, certStore, ddnsSvc, settingsStore, proxySvc, logger, notifySvc)
backupSvc := backup.New(cfg.DataDir)
// 注入数据库连接:导出时用 VACUUM INTO 拿一致性快照,而不是直接打包正在写的文件
backupSvc.SetDB(conn)
// 指标历史:与巡检同生命周期,采样跟随巡检轮次
metricsStore := metrics.NewStore(conn)
discoverySvc := discovery.New()
// 新增:多服务端 FRP 模块(接管原网关模式)
frpMultiSvc := frp.NewService(cfg, frp.NewStore(conn), secretBox, logger, certStore)
if err := frpMultiSvc.EnsureDirs(); err != nil {
conn.Close()
return nil, err
}
// 记录/恢复 frpc 运行状态:应用被停用再启用后要能自动回到运行状态
frpMultiSvc.SetSettingsStore(settingsStore)
cloudflareSvc := cloudflared.NewService(cfg, cloudflared.NewStore(conn), secretBox, logger, proxySvc)
if err := cloudflareSvc.EnsureDirs(); err != nil {
conn.Close()
return nil, err
}
proxySvc.SetExitSync(cloudflareSvc)
startedAt := time.Now().UTC().Format(time.RFC3339)
trafficCollector := traffic.NewCollector(conn, filepath.Join(cfg.LogsDir(), "access.log"), notifySvc)
// 删规则时连带清掉它的流量累计,否则同名规则重建会继承上一轮的读数
proxySvc.SetTrafficCleaner(trafficCollector)
updaterClient := updater.NewClient(cfg.UpdaterSocket, updaterToken)
// 内置 SSH 终端:会话管理借用 frp 的 SSH 凭据与 known_hosts;开关默认关闭,见 settings.KeyTerminalEnabled
// 会话审计落 SQLite:谁、何时、连了哪台、多久、为什么断开
terminalAuditStore := terminal.NewAuditStore(conn)
// 常用命令:右侧面板的快捷命令,落库后换浏览器也在
terminalCommandStore := terminal.NewCommandStore(conn)
terminalManager := terminal.NewManager(logger, frpMultiSvc.OpenSSHTerminal, terminal.Options{})
terminalManager.SetAuditSink(terminalAuditStore)
// 会话录制:默认关闭,开启后按 asciinema v2 把输出写进 logs/terminal
terminalRecordingStore := terminal.NewRecordingStore(filepath.Join(cfg.LogsDir(), "terminal"))
if err := terminalRecordingStore.EnsureDir(); err != nil {
logger.Warn("终端录制目录创建失败", "module", "TERMINAL", "error", err.Error())
}
terminalManager.SetRecorderFactory(func(sessionID string, opts terminal.CreateOptions) (terminal.OutputRecorder, error) {
title := fmt.Sprintf("服务端 #%d", opts.ServerID)
return terminal.NewCastRecorder(terminalRecordingStore, sessionID, title, opts.Cols, opts.Rows, time.Now())
})
handler := api.NewRouter(api.Deps{
Config: cfg,
Logger: logger,
Auth: authSvc,
Proxy: proxySvc,
DDNS: ddnsSvc,
ACME: acmeSvc,
Settings: settingsStore,
Notify: notifySvc,
ChinaCIDR: chinaCIDRSvc,
Backup: backupSvc,
Metrics: metricsStore,
Discovery: discoverySvc,
FRPMulti: frpMultiSvc,
Cloudflare: cloudflareSvc,
Traffic: trafficCollector,
Updater: updaterClient,
StaticFS: staticFS,
StartedAt: startedAt,
Terminal: terminalManager,
TerminalAudits: terminalAuditStore,
TerminalCommands: terminalCommandStore,
TerminalRecordings: terminalRecordingStore,
})
if prefix := strings.TrimSpace(cfg.GatewayPrefix); prefix != "" {
handler = stripPrefixIfPresent(prefix, handler)
}
server := &http.Server{
Addr: cfg.ListenAddr,
Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
// 读超时放到 5 分钟:备份恢复要上传最大 64MB;不设 WriteTimeout,否则日志 SSE 会被中途切断
ReadTimeout: 5 * time.Minute,
IdleTimeout: 2 * time.Minute,
}
ctx, cancel := context.WithCancel(context.Background())
// 终端会话回收:空闲超时、超长会话与已结束会话都靠它清理
terminalManager.StartSweeper(ctx, time.Minute)
frpMultiSvc.SetBaseContext(ctx)
// cloudflared 子进程跟随应用 ctx:应用退出时不会留下孤儿进程
cloudflareSvc.SetBaseContext(ctx)
intervalMinutes, _ := settingsStore.GetInt(ctx, settings.KeyDDNSCheckInterval)
if intervalMinutes <= 0 {
intervalMinutes = 5
}
chinaHours, _ := settingsStore.GetInt(ctx, settings.KeyChinaCIDRUpdateHours)
if chinaHours <= 0 {
chinaHours = 24
}
// 巡检间隔比其它任务短:「连续 N 次不通」需要足够采样次数才能判定
monitorChecker := monitor.New(settingsStore, notifySvc, logger, monitorSource{frp: frpMultiSvc, cloudflare: cloudflareSvc, logger: logger, traffic: trafficCollector}, healthRecorder{frp: frpMultiSvc}, metricsStore)
// 自动备份:启动时会先跑一轮,靠「最新备份是否在 24h 内」避免频繁重启重复备份
backupRunner := backup.NewAutoRunner(backupSvc, settingsStore, notifySvc, logger)
sched := scheduler.New(
scheduler.Job{
Name: "ddns",
Interval: time.Duration(intervalMinutes) * time.Minute,
Run: ddnsSvc.Tick,
},
scheduler.Job{
Name: "acme",
Interval: 24 * time.Hour,
Run: acmeSvc.Tick,
},
scheduler.Job{
Name: "china_cidr",
Interval: time.Duration(chinaHours) * time.Hour,
Run: chinaCIDRSvc.Tick,
},
scheduler.Job{
Name: "monitor",
Interval: 2 * time.Minute,
Run: monitorChecker.Run,
},
scheduler.Job{
Name: "backup",
Interval: backup.AutoInterval,
Run: backupRunner.Run,
},
scheduler.Job{
Name: "terminal_audit",
Interval: 24 * time.Hour,
// 审计只留 90 天:清理比会话回收慢得多,单独挂一个日任务即可
Run: func(ctx context.Context) {
deleted, err := terminalAuditStore.PruneAudits(ctx)
if err != nil {
logger.Warn("终端审计清理失败", "module", "TERMINAL", "error", err.Error())
}
if deleted > 0 {
logger.Info("终端审计清理完成", "module", "TERMINAL", "deleted", deleted)
}
removed, err := terminalRecordingStore.Prune(time.Now().Add(-terminal.AuditRetention))
if err != nil {
logger.Warn("终端录制清理失败", "module", "TERMINAL", "error", err.Error())
}
if removed > 0 {
logger.Info("终端录制清理完成", "module", "TERMINAL", "deleted", removed)
}
},
},
scheduler.Job{
Name: "session_prune",
Interval: 24 * time.Hour,
// 过期会话否则只能等自己被访问时删掉自己,长期不登录的设备会一直留在表里
Run: func(ctx context.Context) {
removed, err := authSvc.PruneExpiredSessions(ctx)
if err != nil {
logger.Warn("过期会话清理失败", "module", "AUTH", "error", err.Error())
return
}
if removed > 0 {
logger.Info("过期会话清理完成", "module", "AUTH", "deleted", removed)
}
},
},
scheduler.Job{
Name: "log_rotate",
Interval: time.Hour,
// Nginx 自己不会轮转:不切的话 access.log 会一直长,同时读日志的
// 几个接口(今日统计、小时曲线)会越来越慢。
Run: func(ctx context.Context) {
rotateNginxLogs(ctx, cfg, nginxMgr, settingsStore, logger)
},
},
)
sched.Start(ctx)
trafficCollector.Start(ctx)
app := &App{
cfg: cfg,
logger: logger,
server: server,
nginx: nginxMgr,
frpMulti: frpMultiSvc,
cloudflare: cloudflareSvc,
scheduler: sched,
shutdownFn: cancel,
db: conn,
}
// 就绪门:Nginx 首轮配置应用完之前不放后台任务。
// 否则 Agent 路由下发、Cloudflare ingress 同步会在启动瞬间各触发一次
// Nginx reload,和 bootstrap 抢同一份配置与 pid。
ready := make(chan struct{})
if err := app.bootstrapNginx(context.Background(), proxySvc); err != nil {
cancel()
conn.Close()
return nil, err
}
close(ready)
go waitReady(ctx, ready, func() {
if err := frpMultiSvc.ReconcileRuntime(ctx); err != nil {
logger.Warn("initial frp runtime reconcile skipped", "module", "FRP", "error", err.Error())
}
if err := frpMultiSvc.AutoStart(ctx); err != nil {
logger.Warn("initial frp autostart skipped", "module", "FRP", "error", err.Error())
}
cloudflareSvc.StartAuto(ctx)
})
go waitReady(ctx, ready, func() { frpMultiSvc.StartAgentTunnels(ctx) })
go waitReady(ctx, ready, func() { frpMultiSvc.StartAgentCertificateRenewal(ctx) })
listen := strings.TrimSpace(cfg.ListenAddr)
if listen == "" {
listen = strings.TrimSpace(cfg.GatewaySocket)
}
logger.Info("application started", "module", "SYSTEM", "listen", listen)
return app, nil
}
// waitReady 等到 ready 关闭(或 ctx 取消)后再执行 fn。
func waitReady(ctx context.Context, ready <-chan struct{}, fn func()) {
select {
case <-ready:
case <-ctx.Done():
return
}
if ctx.Err() != nil {
return
}
fn()
}
// rotateNginxLogs 轮转 access.log 与 error.log。
// 保留天数接「设置 → 常规 → 日志保留天数」,份数用 logstore 默认值兜底。
func rotateNginxLogs(ctx context.Context, cfg config.Config, nginxMgr *nginx.Manager, store *settings.Store, logger *slog.Logger) {
retentionDays, err := store.GetInt(ctx, settings.KeyLogRetentionDays)
if err != nil || retentionDays <= 0 {
retentionDays = 30
}
logsDir := cfg.LogsDir()
for _, name := range []string{"access.log", "error.log"} {
rotator := logstore.NewRotator(filepath.Join(logsDir, name), retentionDays, func() error {
return nginxMgr.ReopenLogs(ctx)
})
rotated, err := rotator.RotateIfNeeded(time.Now())
if err != nil {
logger.Warn("日志轮转失败", "module", "LOGSTORE", "file", name, "error", err.Error())
continue
}
if rotated {
logger.Info("日志已轮转", "module", "LOGSTORE", "file", name)
}
}
}
func (a *App) bootstrapNginx(ctx context.Context, proxySvc *service.ProxyService) error {
if err := proxySvc.ReloadAll(ctx); err != nil {
a.logger.Warn("initial nginx apply skipped", "module", "NGINX", "error", err.Error())
}
return nil
}
func (a *App) Run() error {
socket := strings.TrimSpace(a.cfg.GatewaySocket)
if socket == "" {
return a.server.ListenAndServe()
}
listeners := make([]net.Listener, 0, 2)
// 原生版显式把 TCP 地址置空,只保留 Unix Socket,避免和 Docker 版抢 6893。
if addr := strings.TrimSpace(a.server.Addr); addr != "" {
tcp, err := net.Listen("tcp", addr)
if err != nil {
return err
}
defer tcp.Close()
listeners = append(listeners, tcp)
}
if err := os.Remove(socket); err != nil && !os.IsNotExist(err) {
return err
}
unixListener, err := net.Listen("unix", socket)
if err != nil {
return err
}
defer unixListener.Close()
defer os.Remove(socket)
if err := os.Chmod(socket, 0o660); err != nil {
return err
}
listeners = append(listeners, unixListener)
errCh := make(chan error, len(listeners))
for _, listener := range listeners {
go func(l net.Listener) { errCh <- a.server.Serve(l) }(listener)
}
return <-errCh
}
func (a *App) Shutdown(ctx context.Context) error {
a.logger.Info("application shutting down", "module", "SYSTEM")
if a.shutdownFn != nil {
a.shutdownFn()
}
if err := a.server.Shutdown(ctx); err != nil {
return err
}
if socket := strings.TrimSpace(a.cfg.GatewaySocket); socket != "" {
_ = os.Remove(socket)
}
if err := a.nginx.Stop(ctx); err != nil {
a.logger.Error("nginx stop failed", "module", "NGINX", "error", err.Error())
}
if a.frpMulti != nil {
// 退出时保留「上次在运行」标记,供下次启用应用时自动恢复 frpc
if err := a.frpMulti.StopForShutdown(ctx); err != nil {
a.logger.Error("frpc stop failed", "module", "FRP", "error", err.Error())
}
}
// cloudflared 不保留「上次在运行」:AutoStart 是用户的显式选择,
// 这里只负责把当前子进程收干净,避免退出后残留进程占着 Cloudflare 连接。
// 放在 nginx 之后:ingress 还指向本机 Nginx,先收隧道再做别的没有意义。
if a.cloudflare != nil {
a.cloudflare.StopAll(ctx)
}
if a.db != nil {
return a.db.Close()
}
return nil
}
func stripPrefixIfPresent(prefix string, next http.Handler) http.Handler {
prefix = strings.TrimRight(prefix, "/")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == prefix || strings.HasPrefix(r.URL.Path, prefix+"/") {
r.URL.Path = strings.TrimPrefix(r.URL.Path, prefix)
if r.URL.Path == "" {
r.URL.Path = "/"
}
}
next.ServeHTTP(w, r)
})
}
func ResolveMigrationsDir() (string, error) {
candidates := []string{
"migrations",
filepath.Join("..", "migrations"),
filepath.Join("..", "..", "migrations"),
}
for _, c := range candidates {
if info, err := os.Stat(c); err == nil && info.IsDir() {
return c, nil
}
}
return "", fmt.Errorf("migrations directory not found")
}
+81
View File
@@ -0,0 +1,81 @@
package app
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"github.com/havline/havline/internal/config"
)
func TestGatewayPrefix(t *testing.T) {
for _, tc := range []struct{ input, want string }{
{"/app/havline/api/version", "/api/version"},
{"/app/havline", "/"},
{"/api/version", "/api/version"},
{"/app/havline-other/api/version", "/app/havline-other/api/version"},
} {
t.Run(tc.input, func(t *testing.T) {
handler := stripPrefixIfPresent("/app/havline/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != tc.want {
t.Errorf("路径为 %q,期望 %q", r.URL.Path, tc.want)
}
}))
handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, tc.input, nil))
})
}
}
func TestRunGatewaySocketWithoutTCP(t *testing.T) {
socket := filepath.Join(t.TempDir(), "app.sock")
server := &http.Server{
Addr: "",
Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("havline-gateway-ok"))
}),
}
app := &App{
cfg: config.Config{GatewaySocket: socket},
server: server,
}
errCh := make(chan error, 1)
go func() { errCh <- app.Run() }()
response := requestUnixSocket(t, socket)
if !strings.Contains(response, "havline-gateway-ok") {
t.Fatalf("unix socket response %q", response)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = server.Shutdown(ctx)
if err := <-errCh; err != nil && !errors.Is(err, http.ErrServerClosed) {
t.Fatalf("Run() error: %v", err)
}
}
func requestUnixSocket(t *testing.T, socket string) string {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
conn, err := net.Dial("unix", socket)
if err == nil {
defer conn.Close()
_, _ = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
data, _ := io.ReadAll(conn)
return string(data)
}
time.Sleep(20 * time.Millisecond)
}
t.Fatalf("unix socket not ready: %s", socket)
return ""
}
+241
View File
@@ -0,0 +1,241 @@
package app
import (
"context"
"fmt"
"log/slog"
"github.com/havline/havline/internal/cloudflared"
"github.com/havline/havline/internal/frp"
"github.com/havline/havline/internal/monitor"
"github.com/havline/havline/internal/traffic"
)
// monitorSource 把 frp 服务适配成 monitor.Source:monitor 只关心「状态快照」,
// 怎么从 frp / agent 取是这里的事,两边因此互不依赖。
type monitorSource struct {
frp *frp.Service
cloudflare *cloudflared.Service
logger *slog.Logger
traffic *traffic.Collector
}
func (s monitorSource) CloudflareRoutes(ctx context.Context) ([]monitor.CloudflareRouteStatus, error) {
if s.cloudflare == nil {
return []monitor.CloudflareRouteStatus{}, nil
}
statuses, err := s.cloudflare.HealthStatuses(ctx)
if err != nil {
return nil, err
}
out := make([]monitor.CloudflareRouteStatus, 0, len(statuses))
for _, item := range statuses {
out = append(out, monitor.CloudflareRouteStatus{
TunnelID: item.TunnelID,
Name: item.Name,
Domain: item.Domain,
State: item.State,
Reason: item.Reason,
Detail: item.Detail,
Known: item.Known,
})
}
return out, nil
}
func (s monitorSource) RecordCloudflareHealth(ctx context.Context, samples []monitor.CloudflareHealthSample) error {
if s.cloudflare == nil {
return nil
}
converted := make([]cloudflared.HealthSample, 0, len(samples))
for _, sample := range samples {
converted = append(converted, cloudflared.HealthSample{
TunnelID: sample.TunnelID,
Name: sample.Name,
Domain: sample.Domain,
State: sample.State,
Reason: sample.Reason,
Detail: sample.Detail,
})
}
return s.cloudflare.RecordHealth(ctx, converted)
}
func (s monitorSource) PruneCloudflareHealth(ctx context.Context) error {
if s.cloudflare == nil {
return nil
}
_, err := s.cloudflare.PruneHealth(ctx)
return err
}
func (s monitorSource) Routes(ctx context.Context) ([]monitor.RouteStatus, error) {
servers, err := s.enabledServers(ctx)
if err != nil {
return nil, err
}
routes := make([]monitor.RouteStatus, 0, len(servers))
for _, server := range servers {
// 单台服务端探测失败不影响其它服务端:它本轮跳过,等下一轮
health, err := s.frp.RouteHealth(ctx, server.ID)
if err != nil {
s.logger.Warn("巡检跳过服务端隧道", "module", "MONITOR", "server_id", server.ID, "error", err.Error())
continue
}
for _, item := range health {
routes = append(routes, monitor.RouteStatus{
ServerID: server.ID,
Domain: item.Domain,
TunnelOK: item.TunnelOK,
DNSOK: item.DNSOK,
ServiceOK: item.ServiceOK,
Known: item.TunnelKnown,
Detail: item.TunnelDetail,
})
}
}
return routes, nil
}
func (s monitorSource) Servers(ctx context.Context) ([]monitor.ServerStatus, error) {
servers, err := s.enabledServers(ctx)
if err != nil {
return nil, err
}
out := make([]monitor.ServerStatus, 0, len(servers))
for _, server := range servers {
out = append(out, monitor.ServerStatus{
ID: server.ID,
Name: server.Name,
DesiredState: server.DesiredState,
ProcessState: server.ProcessState,
ConnectionState: server.ConnectionState,
Detail: server.LastError,
})
}
return out, nil
}
func (s monitorSource) Agents(ctx context.Context) ([]monitor.AgentStatus, error) {
servers, err := s.enabledServers(ctx)
if err != nil {
return nil, err
}
out := make([]monitor.AgentStatus, 0, len(servers))
for _, server := range servers {
// AgentClient 只在「地址与令牌都可用」时才返回 ok:没配 agent 的服务端不参与可达性判定
client, ok := s.frp.AgentClient(ctx, server.ID)
if !ok {
continue
}
status := monitor.AgentStatus{ID: server.ID, Name: server.Name, Reachable: true}
if err := client.Ping(ctx); err != nil {
status.Reachable = false
status.Detail = err.Error()
}
out = append(out, status)
}
return out, nil
}
func (s monitorSource) Drift(ctx context.Context) ([]monitor.DriftStatus, error) {
servers, err := s.enabledServers(ctx)
if err != nil {
return nil, err
}
out := make([]monitor.DriftStatus, 0, len(servers))
for _, server := range servers {
report, err := s.frp.RouteDrift(ctx, server.ID)
if err != nil {
s.logger.Warn("巡检跳过漂移检测", "module", "MONITOR", "server_id", server.ID, "error", err.Error())
continue
}
status := monitor.DriftStatus{ID: server.ID, Name: server.Name, Count: len(report.Items)}
for _, item := range report.Items {
status.Items = append(status.Items, fmt.Sprintf("%s %s", item.Domain, driftKindText(item.Kind)))
}
out = append(out, status)
}
return out, nil
}
// Traffic 返回若干域名的当前上下行速率:流量采集器内部按 host:port 累计,这里按域名合并。
func (s monitorSource) Traffic(ctx context.Context, domains []string) (map[string]monitor.TrafficRate, error) {
if s.traffic == nil {
return nil, nil
}
snapshot := s.traffic.SnapshotByHost(domains)
rates := make(map[string]monitor.TrafficRate, len(snapshot))
for host, item := range snapshot {
rates[host] = monitor.TrafficRate{Upload: item.UploadRate, Download: item.DownloadRate}
}
return rates, nil
}
func (s monitorSource) enabledServers(ctx context.Context) ([]frp.Server, error) {
servers, err := s.frp.ListServers(ctx)
if err != nil {
return nil, err
}
enabled := make([]frp.Server, 0, len(servers))
for _, server := range servers {
// 停用中的服务端是用户主动关掉的,不该参与任何告警判定
if server.Enabled {
enabled = append(enabled, server)
}
}
return enabled, nil
}
// driftKindText 与公网反代页漂移清单的文案保持一致,通知里才不用回页面去对照。
func driftKindText(kind string) string {
switch kind {
case frp.RouteDriftMissing:
return "未部署"
case frp.RouteDriftOrphan:
return "孤儿配置"
case frp.RouteDriftNotLoaded:
return "未生效"
case frp.RouteDriftContentMismatch:
return "内容不一致"
default:
return kind
}
}
// healthRecorder 把 monitor 的健康结论翻成 frp 侧样本并落库(
// 两侧的状态字面量由 healthStateValue 显式翻译,改动一侧会在这里编译期报错)。
type healthRecorder struct {
frp *frp.Service
}
func (r healthRecorder) RecordRouteHealth(ctx context.Context, samples []monitor.HealthSample) error {
converted := make([]frp.RouteHealthSample, 0, len(samples))
for _, sample := range samples {
converted = append(converted, frp.RouteHealthSample{
ServerID: sample.ServerID,
Domain: sample.Domain,
State: healthStateValue(sample.State),
Reason: sample.Reason,
Detail: sample.Detail,
})
}
_, err := r.frp.RecordRouteHealth(ctx, converted)
return err
}
func (r healthRecorder) PruneRouteHealth(ctx context.Context) error {
_, err := r.frp.PruneRouteHealth(ctx)
return err
}
func healthStateValue(state string) string {
switch state {
case monitor.HealthUp:
return frp.RouteHealthUp
case monitor.HealthDown:
return frp.RouteHealthDown
default:
return frp.RouteHealthUnknown
}
}
+24
View File
@@ -0,0 +1,24 @@
package app
import (
"testing"
"github.com/havline/havline/internal/frp"
"github.com/havline/havline/internal/monitor"
)
// monitor 与 frp 两侧的状态字面量必须一致,落库前由 healthStateValue 翻译一次;
// 这个测试把翻译钉住,避免以后改一侧的常量而另一侧悄悄写错值。
func TestHealthStateValue(t *testing.T) {
cases := map[string]string{
monitor.HealthUp: frp.RouteHealthUp,
monitor.HealthDown: frp.RouteHealthDown,
monitor.HealthUnknown: frp.RouteHealthUnknown,
"其他": frp.RouteHealthUnknown,
}
for input, want := range cases {
if got := healthStateValue(input); got != want {
t.Fatalf("%q 应翻译为 %q,实际 %q", input, want, got)
}
}
}
+270
View File
@@ -0,0 +1,270 @@
package auth
import (
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"log/slog"
"os"
"strings"
"time"
"golang.org/x/crypto/bcrypt"
"github.com/havline/havline/internal/validate"
)
const sessionTTL = 7 * 24 * time.Hour
var ErrUnauthorized = errors.New("unauthorized")
var ErrNotInitialized = errors.New("not initialized")
type Service struct {
db *sql.DB
}
func New(db *sql.DB) *Service {
return &Service{db: db}
}
func (s *Service) IsInitialized(ctx context.Context) (bool, error) {
var count int
err := s.db.QueryRowContext(ctx, `SELECT COUNT(1) FROM admins`).Scan(&count)
return count > 0, err
}
const defaultAdminUsername = "admin"
func (s *Service) EnsureDefaultAdmin(ctx context.Context, log *slog.Logger) error {
initialized, err := s.IsInitialized(ctx)
if err != nil {
return err
}
if initialized {
return nil
}
password := strings.TrimSpace(os.Getenv("HAVLINE_INITIAL_ADMIN_PASSWORD"))
generated := false
if password == "" {
var err error
password, err = generatePassword(16)
if err != nil {
return err
}
generated = true
}
if err := s.Setup(ctx, defaultAdminUsername, password); err != nil {
return err
}
if generated {
log.Info(
"首次启动已创建管理员账户,请使用以下凭据登录,并在「设置」中尽快修改密码",
"module", "SYSTEM",
"username", defaultAdminUsername,
"password", password,
)
} else {
log.Info(
"首次启动已使用 HAVLINE_INITIAL_ADMIN_PASSWORD 创建管理员账户,请在登录后尽快修改密码",
"module", "SYSTEM",
"username", defaultAdminUsername,
"password_source", "environment",
)
}
return nil
}
func (s *Service) Setup(ctx context.Context, username, password string) error {
if err := validate.Username(username); err != nil {
return err
}
if err := validate.Password(password); err != nil {
return err
}
initialized, err := s.IsInitialized(ctx)
if err != nil {
return err
}
if initialized {
return fmt.Errorf("管理员已初始化")
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
_, err = s.db.ExecContext(ctx, `INSERT INTO admins(username, password_hash) VALUES (?, ?)`, username, string(hash))
return err
}
func (s *Service) Login(ctx context.Context, username, password string) (string, error) {
var adminID int
var hash string
err := s.db.QueryRowContext(ctx, `SELECT id, password_hash FROM admins WHERE username = ?`, username).Scan(&adminID, &hash)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", ErrUnauthorized
}
return "", err
}
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)); err != nil {
return "", ErrUnauthorized
}
return s.createSession(ctx, adminID)
}
func (s *Service) AdminIDForSession(ctx context.Context, sessionID string) (int, error) {
if sessionID == "" {
return 0, ErrUnauthorized
}
var adminID int
err := s.db.QueryRowContext(ctx, `SELECT admin_id FROM sessions WHERE id = ?`, sessionID).Scan(&adminID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return 0, ErrUnauthorized
}
return 0, err
}
return adminID, nil
}
// AdminUsername 反查管理员用户名:审计记录要写清「谁」操作的。
func (s *Service) AdminUsername(ctx context.Context, adminID int) (string, error) {
var username string
err := s.db.QueryRowContext(ctx, `SELECT username FROM admins WHERE id = ?`, adminID).Scan(&username)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", ErrUnauthorized
}
return "", err
}
return username, nil
}
// VerifyPassword 校验管理员密码,供终端二次认证使用。
// 复用登录密码的 bcrypt hash,不新增任何存储;密码本身不落日志、不落盘。
func (s *Service) VerifyPassword(ctx context.Context, adminID int, password string) error {
if adminID <= 0 || password == "" {
return ErrUnauthorized
}
var hash string
err := s.db.QueryRowContext(ctx, `SELECT password_hash FROM admins WHERE id = ?`, adminID).Scan(&hash)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return ErrUnauthorized
}
return err
}
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)); err != nil {
return ErrUnauthorized
}
return nil
}
func (s *Service) ChangePassword(ctx context.Context, adminID int, oldPassword, newPassword, keepSessionID string) error {
if err := validate.Password(newPassword); err != nil {
return err
}
var hash string
err := s.db.QueryRowContext(ctx, `SELECT password_hash FROM admins WHERE id = ?`, adminID).Scan(&hash)
if err != nil {
return err
}
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(oldPassword)); err != nil {
return fmt.Errorf("当前密码不正确")
}
newHash, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
if err != nil {
return err
}
if _, err := s.db.ExecContext(ctx, `UPDATE admins SET password_hash = ? WHERE id = ?`, string(newHash), adminID); err != nil {
return err
}
// 改密后失效该账号的其他会话(保留当前这次,否则用户会被自己踢下线)
_, err = s.db.ExecContext(ctx, `DELETE FROM sessions WHERE admin_id = ? AND id <> ?`, adminID, keepSessionID)
return err
}
func (s *Service) Logout(ctx context.Context, sessionID string) error {
_, err := s.db.ExecContext(ctx, `DELETE FROM sessions WHERE id = ?`, sessionID)
return err
}
// PruneExpiredSessions 删除已经过期的会话,返回删除条数。
// 过期会话只有在自己被再次访问时才会删掉自己,于是「登录过又再也不回来的设备」
// 会永久留着一条记录;这里由日任务统一清掉,顺便让会话表大小与实际活跃设备一致。
func (s *Service) PruneExpiredSessions(ctx context.Context) (int64, error) {
res, err := s.db.ExecContext(ctx,
`DELETE FROM sessions WHERE expires_at < ?`, time.Now().UTC().Format(time.RFC3339))
if err != nil {
return 0, err
}
return res.RowsAffected()
}
func (s *Service) ValidateSession(ctx context.Context, sessionID string) error {
if sessionID == "" {
return ErrUnauthorized
}
var expiresAt string
err := s.db.QueryRowContext(ctx, `SELECT expires_at FROM sessions WHERE id = ?`, sessionID).Scan(&expiresAt)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return ErrUnauthorized
}
return err
}
expires, err := time.Parse(time.RFC3339, expiresAt)
if err != nil {
return ErrUnauthorized
}
if time.Now().After(expires) {
_, _ = s.db.ExecContext(ctx, `DELETE FROM sessions WHERE id = ?`, sessionID)
return ErrUnauthorized
}
return nil
}
func (s *Service) createSession(ctx context.Context, adminID int) (string, error) {
id, err := randomToken(32)
if err != nil {
return "", err
}
expires := time.Now().Add(sessionTTL).UTC().Format(time.RFC3339)
_, err = s.db.ExecContext(ctx, `INSERT INTO sessions(id, admin_id, expires_at) VALUES (?, ?, ?)`, id, adminID, expires)
if err != nil {
return "", err
}
return id, nil
}
func randomToken(n int) (string, error) {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
func generatePassword(length int) (string, error) {
const letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"
if length < 8 {
length = 8
}
out := make([]byte, length)
randBytes := make([]byte, length)
if _, err := rand.Read(randBytes); err != nil {
return "", err
}
for i := range out {
out[i] = letters[int(randBytes[i])%len(letters)]
}
return string(out), nil
}
+104
View File
@@ -0,0 +1,104 @@
package auth
import (
"context"
"errors"
"log/slog"
"os"
"path/filepath"
"testing"
"github.com/havline/havline/internal/db"
)
// TestVerifyPassword:终端二次认证依赖的密码校验——对的放行,错的与不存在的账号都拒绝。
func TestVerifyPassword(t *testing.T) {
conn, err := db.Open(filepath.Join(t.TempDir(), "havline.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
defer conn.Close()
if err := db.Migrate(context.Background(), conn, filepath.Join("..", "..", "migrations")); err != nil {
t.Fatalf("migrate: %v", err)
}
ctx := context.Background()
svc := New(conn)
if err := svc.Setup(ctx, "admin", "admin-password-123"); err != nil {
t.Fatalf("setup: %v", err)
}
sessionID, err := svc.Login(ctx, "admin", "admin-password-123")
if err != nil {
t.Fatalf("login: %v", err)
}
adminID, err := svc.AdminIDForSession(ctx, sessionID)
if err != nil {
t.Fatalf("admin id: %v", err)
}
if err := svc.VerifyPassword(ctx, adminID, "admin-password-123"); err != nil {
t.Fatalf("正确密码应当通过:%v", err)
}
if err := svc.VerifyPassword(ctx, adminID, "admin-password-124"); !errors.Is(err, ErrUnauthorized) {
t.Fatalf("错误密码应当拒绝,实际 %v", err)
}
if err := svc.VerifyPassword(ctx, adminID, ""); !errors.Is(err, ErrUnauthorized) {
t.Fatalf("空密码应当拒绝,实际 %v", err)
}
if err := svc.VerifyPassword(ctx, 9999, "admin-password-123"); !errors.Is(err, ErrUnauthorized) {
t.Fatalf("不存在的账号应当拒绝,实际 %v", err)
}
}
func TestEnsureDefaultAdminCreatesOnce(t *testing.T) {
conn, err := db.Open(filepath.Join(t.TempDir(), "havline.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
defer conn.Close()
if err := db.Migrate(context.Background(), conn, filepath.Join("..", "..", "migrations")); err != nil {
t.Fatalf("migrate: %v", err)
}
svc := New(conn)
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
if err := svc.EnsureDefaultAdmin(context.Background(), logger); err != nil {
t.Fatalf("first bootstrap: %v", err)
}
initialized, err := svc.IsInitialized(context.Background())
if err != nil || !initialized {
t.Fatalf("expected initialized admin, got initialized=%v err=%v", initialized, err)
}
if err := svc.EnsureDefaultAdmin(context.Background(), logger); err != nil {
t.Fatalf("second bootstrap: %v", err)
}
if _, err := svc.Login(context.Background(), "admin", "wrong-password"); err != ErrUnauthorized {
t.Fatalf("expected unauthorized for wrong password, got %v", err)
}
}
func TestEnsureDefaultAdminUsesEnvPassword(t *testing.T) {
conn, err := db.Open(filepath.Join(t.TempDir(), "havline.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
defer conn.Close()
if err := db.Migrate(context.Background(), conn, filepath.Join("..", "..", "migrations")); err != nil {
t.Fatalf("migrate: %v", err)
}
t.Setenv("HAVLINE_INITIAL_ADMIN_PASSWORD", "env-password-123")
svc := New(conn)
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
if err := svc.EnsureDefaultAdmin(context.Background(), logger); err != nil {
t.Fatalf("bootstrap with env password: %v", err)
}
if _, err := svc.Login(context.Background(), "admin", "env-password-123"); err != nil {
t.Fatalf("expected env password login to succeed, got %v", err)
}
}
+87
View File
@@ -0,0 +1,87 @@
package auth
import (
"context"
"database/sql"
"path/filepath"
"testing"
"time"
"github.com/havline/havline/internal/db"
)
// TestPruneExpiredSessions 过期会话应被日任务清掉,未过期的必须留着。
func TestPruneExpiredSessions(t *testing.T) {
conn, err := db.Open(filepath.Join(t.TempDir(), "havline.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
defer conn.Close()
ctx := context.Background()
if err := db.Migrate(ctx, conn, filepath.Join("..", "..", "migrations")); err != nil {
t.Fatalf("migrate: %v", err)
}
svc := New(conn)
if err := svc.Setup(ctx, "admin", "admin-password-123"); err != nil {
t.Fatalf("setup: %v", err)
}
adminID, err := svc.AdminIDForSession(ctx, mustLogin(t, svc))
if err != nil {
t.Fatalf("admin id: %v", err)
}
now := time.Now().UTC()
expired := []string{"expired-1", "expired-2"}
for _, id := range expired {
if _, err := conn.ExecContext(ctx,
`INSERT INTO sessions(id, admin_id, expires_at) VALUES (?, ?, ?)`,
id, adminID, now.Add(-time.Hour).Format(time.RFC3339)); err != nil {
t.Fatalf("insert expired session: %v", err)
}
}
future := "still-valid"
if _, err := conn.ExecContext(ctx,
`INSERT INTO sessions(id, admin_id, expires_at) VALUES (?, ?, ?)`,
future, adminID, now.Add(time.Hour).Format(time.RFC3339)); err != nil {
t.Fatalf("insert valid session: %v", err)
}
before := countSessions(t, conn)
removed, err := svc.PruneExpiredSessions(ctx)
if err != nil {
t.Fatalf("prune: %v", err)
}
if removed != int64(len(expired)) {
t.Fatalf("应删除 %d 条过期会话,实际 %d", len(expired), removed)
}
if after := countSessions(t, conn); after != before-int64(len(expired)) {
t.Fatalf("会话数不符:before=%d after=%d", before, after)
}
if err := svc.ValidateSession(ctx, future); err != nil {
t.Fatalf("未过期会话不应被删:%v", err)
}
// 再跑一次应当没有可删的(幂等)
if removed, err = svc.PruneExpiredSessions(ctx); err != nil || removed != 0 {
t.Fatalf("重复清理应为空操作:removed=%d err=%v", removed, err)
}
}
func mustLogin(t *testing.T, svc *Service) string {
t.Helper()
sessionID, err := svc.Login(context.Background(), "admin", "admin-password-123")
if err != nil {
t.Fatalf("login: %v", err)
}
return sessionID
}
func countSessions(t *testing.T, conn *sql.DB) int64 {
t.Helper()
var count int64
if err := conn.QueryRowContext(context.Background(), `SELECT COUNT(1) FROM sessions`).Scan(&count); err != nil {
t.Fatalf("count sessions: %v", err)
}
return count
}
+166
View File
@@ -0,0 +1,166 @@
package auth
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
)
// API Token 给无法保存会话 cookie 的调用方(脚本、HomeAssistant、手机快捷指令)用。
//
// 明文只在创建响应里返回一次,库里只存 SHA-256:令牌由 crypto/rand 生成、熵足够高,
// 不像人类密码那样需要 bcrypt 这类慢哈希(慢哈希在这里只会拖慢每个 API 请求)。
const (
TokenScopeRead = "read"
TokenScopeWrite = "write"
// lastUsedWriteInterval 限制回写频率:单连接 SQLite 上每个请求都写一次不划算,
// 同一分钟内重复使用不再写。
lastUsedWriteInterval = time.Minute
maxTokenNameLength = 64
)
type APIToken struct {
ID int64 `json:"id"`
Name string `json:"name"`
Scope string `json:"scope"`
ExpiresAt string `json:"expires_at,omitempty"`
LastUsedAt string `json:"last_used_at,omitempty"`
CreatedAt string `json:"created_at"`
}
// CreatedAPIToken 只在创建响应里出现:Token 是明文,之后无法再取回。
type CreatedAPIToken struct {
APIToken
Token string `json:"token"`
}
func (s *Service) ListAPITokens(ctx context.Context) ([]APIToken, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT id, name, scope, COALESCE(expires_at, ''), COALESCE(last_used_at, ''), created_at
FROM api_tokens ORDER BY id DESC`)
if err != nil {
return nil, err
}
defer rows.Close()
tokens := make([]APIToken, 0, 8)
for rows.Next() {
var token APIToken
if err := rows.Scan(&token.ID, &token.Name, &token.Scope, &token.ExpiresAt, &token.LastUsedAt, &token.CreatedAt); err != nil {
return nil, err
}
tokens = append(tokens, token)
}
return tokens, rows.Err()
}
// CreateAPIToken 新建令牌并返回一次明文;expiresAt 为零值表示永不过期。
func (s *Service) CreateAPIToken(ctx context.Context, name, scope string, expiresAt time.Time) (CreatedAPIToken, error) {
name = strings.TrimSpace(name)
if name == "" {
return CreatedAPIToken{}, fmt.Errorf("请填写令牌名称")
}
if len([]rune(name)) > maxTokenNameLength {
return CreatedAPIToken{}, fmt.Errorf("令牌名称最长 %d 个字", maxTokenNameLength)
}
if scope != TokenScopeRead && scope != TokenScopeWrite {
return CreatedAPIToken{}, fmt.Errorf("无效的权限范围")
}
plain, err := randomToken(32)
if err != nil {
return CreatedAPIToken{}, err
}
expires := ""
if !expiresAt.IsZero() {
expires = expiresAt.UTC().Format(time.RFC3339)
}
res, err := s.db.ExecContext(ctx,
`INSERT INTO api_tokens(name, token_hash, scope, expires_at) VALUES (?, ?, ?, ?)`,
name, hashToken(plain), scope, expires)
if err != nil {
return CreatedAPIToken{}, err
}
id, err := res.LastInsertId()
if err != nil {
return CreatedAPIToken{}, err
}
token, err := s.apiTokenByID(ctx, id)
if err != nil {
return CreatedAPIToken{}, err
}
return CreatedAPIToken{APIToken: token, Token: plain}, nil
}
func (s *Service) DeleteAPIToken(ctx context.Context, id int64) error {
res, err := s.db.ExecContext(ctx, `DELETE FROM api_tokens WHERE id = ?`, id)
if err != nil {
return err
}
affected, err := res.RowsAffected()
if err != nil {
return err
}
if affected == 0 {
return fmt.Errorf("令牌不存在")
}
return nil
}
// ValidateAPIToken 校验明文令牌并返回权限范围;校验通过后限频回写最后使用时间。
func (s *Service) ValidateAPIToken(ctx context.Context, plain string) (string, error) {
plain = strings.TrimSpace(plain)
if plain == "" {
return "", ErrUnauthorized
}
var (
id int64
scope string
expiresAt string
)
err := s.db.QueryRowContext(ctx,
`SELECT id, scope, COALESCE(expires_at, '') FROM api_tokens WHERE token_hash = ?`, hashToken(plain)).
Scan(&id, &scope, &expiresAt)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", ErrUnauthorized
}
return "", err
}
if expiresAt != "" {
expires, err := time.Parse(time.RFC3339, expiresAt)
if err != nil || time.Now().After(expires) {
return "", ErrUnauthorized
}
}
now := time.Now().UTC()
cutoff := now.Add(-lastUsedWriteInterval).Format(time.RFC3339)
// 回写失败不影响本次调用:last_used_at 只是审计信息
_, _ = s.db.ExecContext(ctx,
`UPDATE api_tokens SET last_used_at = ? WHERE id = ? AND (last_used_at IS NULL OR last_used_at < ?)`,
now.Format(time.RFC3339), id, cutoff)
return scope, nil
}
func (s *Service) apiTokenByID(ctx context.Context, id int64) (APIToken, error) {
var token APIToken
err := s.db.QueryRowContext(ctx, `
SELECT id, name, scope, COALESCE(expires_at, ''), COALESCE(last_used_at, ''), created_at
FROM api_tokens WHERE id = ?`, id).
Scan(&token.ID, &token.Name, &token.Scope, &token.ExpiresAt, &token.LastUsedAt, &token.CreatedAt)
return token, err
}
func hashToken(plain string) string {
sum := sha256.Sum256([]byte(plain))
return hex.EncodeToString(sum[:])
}
+118
View File
@@ -0,0 +1,118 @@
package auth
import (
"context"
"path/filepath"
"testing"
"time"
"github.com/havline/havline/internal/db"
)
func newTestService(t *testing.T) *Service {
t.Helper()
conn, err := db.Open(filepath.Join(t.TempDir(), "havline.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
t.Cleanup(func() { _ = conn.Close() })
if err := db.Migrate(context.Background(), conn, filepath.Join("..", "..", "migrations")); err != nil {
t.Fatalf("migrate: %v", err)
}
return New(conn)
}
func TestAPITokenLifecycle(t *testing.T) {
svc := newTestService(t)
ctx := context.Background()
created, err := svc.CreateAPIToken(ctx, "homeassistant", TokenScopeRead, time.Time{})
if err != nil {
t.Fatalf("create: %v", err)
}
if created.Token == "" || created.Scope != TokenScopeRead || created.ID == 0 {
t.Fatalf("unexpected created token: %+v", created)
}
// 库里只存 SHA-256:明文不落盘
var stored string
if err := svc.db.QueryRowContext(ctx, `SELECT token_hash FROM api_tokens WHERE id = ?`, created.ID).Scan(&stored); err != nil {
t.Fatalf("read hash: %v", err)
}
if stored == created.Token || len(stored) != 64 {
t.Fatalf("令牌应以 SHA-256 存储,实际 %q", stored)
}
scope, err := svc.ValidateAPIToken(ctx, created.Token)
if err != nil || scope != TokenScopeRead {
t.Fatalf("validate: scope=%q err=%v", scope, err)
}
var lastUsed string
if err := svc.db.QueryRowContext(ctx, `SELECT COALESCE(last_used_at, '') FROM api_tokens WHERE id = ?`, created.ID).Scan(&lastUsed); err != nil {
t.Fatalf("read last_used_at: %v", err)
}
if lastUsed == "" {
t.Fatal("校验通过后应回写 last_used_at")
}
if _, err := svc.ValidateAPIToken(ctx, "not-a-real-token"); err != ErrUnauthorized {
t.Fatalf("未知令牌应拒绝,实际 %v", err)
}
if err := svc.DeleteAPIToken(ctx, created.ID); err != nil {
t.Fatalf("delete: %v", err)
}
if _, err := svc.ValidateAPIToken(ctx, created.Token); err != ErrUnauthorized {
t.Fatalf("删除后令牌应失效,实际 %v", err)
}
if err := svc.DeleteAPIToken(ctx, created.ID); err == nil {
t.Fatal("重复删除应报错")
}
}
func TestAPITokenExpiry(t *testing.T) {
svc := newTestService(t)
ctx := context.Background()
expired, err := svc.CreateAPIToken(ctx, "old-script", TokenScopeWrite, time.Now().Add(-time.Hour))
if err != nil {
t.Fatalf("create: %v", err)
}
if _, err := svc.ValidateAPIToken(ctx, expired.Token); err != ErrUnauthorized {
t.Fatalf("过期令牌应拒绝,实际 %v", err)
}
}
func TestAPITokenRejectsBadInput(t *testing.T) {
svc := newTestService(t)
ctx := context.Background()
if _, err := svc.CreateAPIToken(ctx, " ", TokenScopeRead, time.Time{}); err == nil {
t.Fatal("空名称应报错")
}
if _, err := svc.CreateAPIToken(ctx, "bad-scope", "admin", time.Time{}); err == nil {
t.Fatal("未知权限范围应报错")
}
if _, err := svc.ValidateAPIToken(ctx, " "); err != ErrUnauthorized {
t.Fatalf("空令牌应拒绝,实际 %v", err)
}
}
func TestListAPITokensReturnsNewestFirst(t *testing.T) {
svc := newTestService(t)
ctx := context.Background()
if _, err := svc.CreateAPIToken(ctx, "first", TokenScopeRead, time.Time{}); err != nil {
t.Fatalf("create first: %v", err)
}
if _, err := svc.CreateAPIToken(ctx, "second", TokenScopeWrite, time.Time{}); err != nil {
t.Fatalf("create second: %v", err)
}
tokens, err := svc.ListAPITokens(ctx)
if err != nil {
t.Fatalf("list: %v", err)
}
if len(tokens) != 2 || tokens[0].Name != "second" {
t.Fatalf("应按 id 倒序返回:%+v", tokens)
}
}
+236
View File
@@ -0,0 +1,236 @@
package backup
import (
"archive/tar"
"compress/gzip"
"context"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"github.com/havline/havline/internal/settings"
)
// 保留份数的边界:0/负数按默认值处理,上限防止把磁盘塞满
const (
DefaultKeepCount = 7
MaxKeepCount = 60
)
// archiveNamePattern 备份命名格式(Export 用 CreateTemp 生成,后缀是随机数字)。
// List / Path 都按它过滤,避免把 backups 目录里任意文件当成备份读写或删除。
var archiveNamePattern = regexp.MustCompile(`^havline-backup-\d{8}-\d{6}-\d+\.tar\.gz$`)
// Archive 留在磁盘上的一份备份
type Archive struct {
Name string `json:"name"`
Size int64 `json:"size"`
ModTime time.Time `json:"mod_time"`
}
func (s *Service) backupsDir() string {
return filepath.Join(s.dataDir, "backups")
}
// List 按新的在前列出备份;目录不存在返回空列表(还没备份过是正常状态)。
func (s *Service) List() ([]Archive, error) {
entries, err := os.ReadDir(s.backupsDir())
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
archives := make([]Archive, 0, len(entries))
for _, entry := range entries {
if entry.IsDir() || !archiveNamePattern.MatchString(entry.Name()) {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
archives = append(archives, Archive{Name: entry.Name(), Size: info.Size(), ModTime: info.ModTime().UTC()})
}
// 文件名前缀就是时间戳,按名倒序即按时间倒序
sort.Slice(archives, func(i, j int) bool { return archives[i].Name > archives[j].Name })
return archives, nil
}
// Prune 只保留最新的 keep 份,返回删除数量;keep <= 0 表示不剪枝。
func (s *Service) Prune(keep int) (int, error) {
if keep <= 0 {
return 0, nil
}
archives, err := s.List()
if err != nil {
return 0, err
}
removed := 0
for _, archive := range archives[min(keep, len(archives)):] {
if err := s.Remove(archive.Name); err != nil {
return removed, err
}
removed++
}
return removed, nil
}
// Path 把备份名解析成绝对路径;名字必须匹配备份命名格式,避免被用来读写目录外的文件。
func (s *Service) Path(name string) (string, error) {
if !archiveNamePattern.MatchString(name) {
return "", fmt.Errorf("备份名无效")
}
return filepath.Join(s.backupsDir(), name), nil
}
// Remove 删除指定备份
func (s *Service) Remove(name string) error {
path, err := s.Path(name)
if err != nil {
return err
}
if err := os.Remove(path); err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("备份不存在")
}
return err
}
return nil
}
// Verify 回读归档并返回条目数:确认这份备份不是写了一半的残件,
// 同时要求包内必须有 havline.db(否则多半不是 Havline 的备份)。
func (s *Service) Verify(ctx context.Context, path string) (int, error) {
return s.VerifyWith(ctx, path, Options{})
}
// VerifyWith 校验归档;加密归档需要提供口令才能验证内容。
// 自动备份若启用口令,必须把口令传进来,否则一份好备份会被判成坏包而删掉。
func (s *Service) VerifyWith(ctx context.Context, path string, opts Options) (int, error) {
encrypted, err := IsEncrypted(path)
if err != nil {
return 0, err
}
file, err := os.Open(path)
if err != nil {
return 0, err
}
defer file.Close()
var reader io.Reader = file
if encrypted {
passphrase := strings.TrimSpace(opts.Passphrase)
if passphrase == "" {
return 0, ErrPassphraseRequired
}
plain, err := openSealedFile(file, passphrase)
if err != nil {
return 0, err
}
reader = plain
}
gr, err := gzip.NewReader(reader)
if err != nil {
return 0, fmt.Errorf("备份文件无法解压:%w", err)
}
defer gr.Close()
tr := tar.NewReader(gr)
count := 0
hasDatabase := false
hasSecret := false
for {
header, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return count, fmt.Errorf("备份文件已损坏:%w", err)
}
if err := ctx.Err(); err != nil {
return count, err
}
count++
switch header.Name {
case "havline.db":
hasDatabase = true
case "session_secret":
hasSecret = true
}
}
if !hasDatabase {
return count, fmt.Errorf("备份里没有 havline.db,可能不是 Havline 的备份")
}
// 缺少 session_secret 的归档不能判成坏包(旧版本导出的备份本来就长这样,
// 而且数据库与证书都还在,多半仍值得恢复),只是恢复后凭据解不开。
// 这个差别交给 MissingSessionSecret 单独告知调用方,别混进校验错误里。
_ = hasSecret
return count, nil
}
// MissingSessionSecret 判断归档是否缺少凭据加密密钥。
// 只服务于「恢复后要不要提示用户」,不参与备份有效性判定。
func (s *Service) MissingSessionSecret(ctx context.Context, path string, opts Options) (bool, error) {
encrypted, err := IsEncrypted(path)
if err != nil {
return false, err
}
file, err := os.Open(path)
if err != nil {
return false, err
}
defer file.Close()
var reader io.Reader = file
if encrypted {
passphrase := strings.TrimSpace(opts.Passphrase)
if passphrase == "" {
return false, ErrPassphraseRequired
}
plain, err := openSealedFile(file, passphrase)
if err != nil {
return false, err
}
reader = plain
}
gr, err := gzip.NewReader(reader)
if err != nil {
return false, fmt.Errorf("备份文件无法解压:%w", err)
}
defer gr.Close()
tr := tar.NewReader(gr)
for {
header, err := tr.Next()
if err == io.EOF {
return true, nil
}
if err != nil {
return false, err
}
if header.Name == "session_secret" {
return false, nil
}
}
}
// KeepCount 读取保留份数(未配置或越界时回落到默认值)。
// 自动备份任务与「立即备份」共用它,避免两处各写一套默认值。
func KeepCount(ctx context.Context, store *settings.Store) int {
keep, err := store.GetInt(ctx, settings.KeyBackupKeepCount)
if err != nil || keep <= 0 {
return DefaultKeepCount
}
if keep > MaxKeepCount {
return MaxKeepCount
}
return keep
}

Some files were not shown because too many files have changed in this diff Show More