fix(cors): CORS 全 DB 化,install 模式完全跳过,WebUI 可配

完整方案: 与 auth_key 同思路,让 CORS 也走 DB,彻底干掉 ALLOWED_ORIGINS env。

设计:
- install 模式: CORS 中间件直接 next(无 CORS 头也无 Vary),让装时永远能成功
  (用户首次装不可能提前知道自己的访问域名)
- normal 模式: 走 CORS 检查,但有 2 道防线:
  1) 同源豁免 (isSameOrigin) — Origin 匹配 Host 直接放行
  2) 跨域白名单 — 读 setting.CORS (DB > env)
- DB 字段:
  - cors_allow_all (bool): 允许所有(*)
  - cors_origins (string): 换行分隔白名单,后端 trim+lower+去末尾 /
- WebUI: /admin 设置 tab 加 CORS 段(allow_all checkbox + origins textarea + 保存)
- 顶部 banner: cors_configured=false 时显示黄条提示,引导去设置

新增:
- middleware/cors.go: 顶部 installer.GetMode() == ModeSetup 时直接 next
- setting/config.go: SplitOriginsForCORS 导出 helper(供 controller 复用)
- controller/settings.go: SettingsCORSRequest + SettingsCORSHandler
  - 校验每个 origin 必须 http:// 或 https:// 开头
  - 写完立即刷新 setting.CORS.AllowAll + setting.CORS.Origins(下个跨域请求生效)
  - 拒绝空 body
- router/router.go: 挂 /api/settings/cors (PUT, RequireAdmin)
- router/admin.html: 设置 tab 加 CORS card + 顶部 banner (31.19KB, 略超 30KB 预算可接受)

改造:
- setting/config.go LoadRuntimeConfig: 顺便读 cors_allow_all + cors_origins,
  DB > env 兜底
- controller/settings.go SettingsResponse: 加 cors_allow_all + cors_origins + cors_configured

e2e 跑通(本机)10 场景:
- install 任意 Origin → 200 (install mode 跳 CORS)
- normal 同源 → 200
- normal 跨域无 allowlist → 403
- GET settings cors_configured=false
- PUT /api/settings/cors → 200
- GET settings cors_configured=true
- 跨域命中白名单 → 200
- 跨域未命中白名单 → 403
- allow_all=true → 任意跨域 200
- 重启后 CORS 仍从 DB 加载

未 push(等用户测试 install 是否顺利,以及 CORS banner 是否合适)
This commit is contained in:
sun
2026-08-30 00:08:14 +08:00
parent 1bed8d8ed0
commit 7660db14d8
5 changed files with 229 additions and 0 deletions
+10
View File
@@ -6,6 +6,7 @@ import (
"strings"
"github.com/volcano-tts/tts-api/common"
"github.com/volcano-tts/tts-api/installer"
"github.com/volcano-tts/tts-api/setting"
)
@@ -98,6 +99,15 @@ func splitOrigin(origin string) (host, scheme string) {
func CORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 安装模式完全跳过 CORS:
// - 用户首次装,不可能提前知道自己的访问域名来配 ALLOWED_ORIGINS
// - 装完进 normal 模式后,设的 CORS 才生效(从 DB 读)
// 这样 install 永远能成功,装完再通过 WebUI 配 CORS。
if installer.GetMode() == installer.ModeSetup {
next.ServeHTTP(w, r)
return
}
origin := r.Header.Get("Origin")
// 无 Origin 头:非跨域请求,跳过 CORS 处理