完整方案: 与 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 是否合适)
135 lines
5.6 KiB
Go
135 lines
5.6 KiB
Go
package router
|
|
|
|
import (
|
|
_ "embed"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gorilla/mux"
|
|
"github.com/volcano-tts/tts-api/controller"
|
|
"github.com/volcano-tts/tts-api/installer"
|
|
"github.com/volcano-tts/tts-api/metrics"
|
|
"github.com/volcano-tts/tts-api/middleware"
|
|
)
|
|
|
|
//go:embed health.html
|
|
var dashboardHTML []byte
|
|
|
|
//go:embed setup.html
|
|
var setupHTML []byte
|
|
|
|
//go:embed admin.html
|
|
var adminHTML []byte
|
|
|
|
// Setup 返回主路由。
|
|
// 中间件顺序(由外向内):
|
|
// SecurityHeaders → InstallGuard → RateLimit → ConcurrencyLimit → Logger → handler
|
|
// 关键: InstallGuard 必须在 RateLimit 之前,避免安装模式被限流计数污染。
|
|
//
|
|
// /admin 和 /api/admin/* 都加 RequireAdmin;InstallGuard 不预先放行(让安装模式下
|
|
// 自动 302 跳 /setup,体验一致)。
|
|
func Setup() *mux.Router {
|
|
r := mux.NewRouter()
|
|
|
|
r.Use(middleware.SecurityHeaders)
|
|
r.Use(middleware.InstallGuard(installer.GetMode))
|
|
r.Use(middleware.RateLimitWithMetrics)
|
|
r.Use(middleware.ConcurrencyLimitWithMetrics)
|
|
r.Use(middleware.Logger)
|
|
|
|
// mux 路由未匹配时 NotFoundHandler 单独处理(不走 r.Use() 中间件链);
|
|
// 安装模式 + 浏览器访问任意未注册路径 → 302 跳 /setup。
|
|
r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
|
if installer.GetMode() == installer.ModeSetup && acceptsHTML(req.Header.Get("Accept")) {
|
|
http.Redirect(w, req, "/setup", http.StatusFound)
|
|
return
|
|
}
|
|
http.NotFound(w, req)
|
|
})
|
|
|
|
// 安装相关路由(InstallGuard 已在 setup 模式放行;完成后由 controller 二次校验 404)
|
|
// /setup 页面本身:装完后必须不可用,否则用户敲 /setup 还会看到安装表单,容易误以为要重装。
|
|
r.HandleFunc("/setup", func(w http.ResponseWriter, req *http.Request) {
|
|
if installer.GetMode() == installer.ModeNormal {
|
|
http.Redirect(w, req, "/admin", http.StatusFound)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
_, _ = w.Write(setupHTML)
|
|
}).Methods("GET")
|
|
r.HandleFunc("/api/setup/status", controller.SetupStatusHandler).Methods("GET")
|
|
r.HandleFunc("/api/setup/prefill", controller.SetupPrefillHandler).Methods("GET")
|
|
r.HandleFunc("/api/setup", controller.SetupSubmitHandler).Methods("POST")
|
|
|
|
// /admin 管理后台(M2);HTML 本身公开,鉴权由前端 JS 拦截
|
|
// (sessionStorage 没 key 就显示登录页;有 key 调 /api/admin/overview 触发 401 跳登录)
|
|
// API 端点(/api/admin/* /api/voices*)才需要 RequireAdmin。
|
|
r.HandleFunc("/admin", func(w http.ResponseWriter, req *http.Request) {
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
_, _ = w.Write(adminHTML)
|
|
}).Methods("GET")
|
|
|
|
// /api/admin/overview (鉴权)
|
|
r.Handle("/api/admin/overview", middleware.RequireAdmin(http.HandlerFunc(controller.AdminOverviewHandler))).Methods("GET")
|
|
// /api/admin/metrics (鉴权);返 Prometheus 文本
|
|
r.Handle("/api/admin/metrics", middleware.RequireAdmin(http.HandlerFunc(controller.AdminMetricsHandler))).Methods("GET")
|
|
|
|
// /api/voices 音色 CRUD (鉴权)
|
|
r.Handle("/api/voices", middleware.RequireAdmin(http.HandlerFunc(controller.AdminVoicesListHandler))).Methods("GET")
|
|
r.Handle("/api/voices", middleware.RequireAdmin(http.HandlerFunc(controller.AdminVoiceCreateHandler))).Methods("POST")
|
|
r.Handle("/api/voices/{name}", middleware.RequireAdmin(http.HandlerFunc(controller.AdminVoiceDeleteHandler))).Methods("DELETE")
|
|
r.Handle("/api/voices/{name}/toggle", middleware.RequireAdmin(http.HandlerFunc(controller.AdminVoiceToggleHandler))).Methods("PATCH")
|
|
|
|
// /api/settings 全局设置 (鉴权) — M3
|
|
r.Handle("/api/settings", middleware.RequireAdmin(http.HandlerFunc(controller.SettingsGetHandler))).Methods("GET")
|
|
r.Handle("/api/settings", middleware.RequireAdmin(http.HandlerFunc(controller.SettingsUpdateHandler))).Methods("PUT")
|
|
r.Handle("/api/settings/api-key", middleware.RequireAdmin(http.HandlerFunc(controller.SettingsAPIKeyHandler))).Methods("PUT")
|
|
r.Handle("/api/settings/auth-key", middleware.RequireAdmin(http.HandlerFunc(controller.SettingsAuthKeyHandler))).Methods("PUT")
|
|
r.Handle("/api/settings/cors", middleware.RequireAdmin(http.HandlerFunc(controller.SettingsCORSHandler))).Methods("PUT")
|
|
|
|
// 业务路由
|
|
r.HandleFunc("/v1/audio/speech", controller.OpenaiTTSHandler).Methods("POST", "OPTIONS")
|
|
r.HandleFunc("/health", controller.HealthHandler).Methods("GET")
|
|
r.HandleFunc("/dashboard", func(w http.ResponseWriter, req *http.Request) {
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
_, _ = w.Write(dashboardHTML)
|
|
}).Methods("GET")
|
|
r.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
|
|
// 安装模式下,根路径跳 /setup
|
|
if installer.GetMode() == installer.ModeSetup {
|
|
http.Redirect(w, req, "/setup", http.StatusFound)
|
|
return
|
|
}
|
|
// 正常模式:跳 /admin(M2 之后优先于 /dashboard)
|
|
http.Redirect(w, req, "/admin", http.StatusFound)
|
|
}).Methods("GET")
|
|
|
|
// /metrics 不做鉴权(对齐 /health 策略),但仍然走 RateLimit / ConcurrencyLimit。
|
|
// Prometheus 抓取不带 Origin,因此经过 CORS 中间件时会直接 pass-through。
|
|
r.Handle("/metrics", metrics.Meter.Handler()).Methods("GET")
|
|
|
|
return r
|
|
}
|
|
|
|
// acceptsHTML 在 router 包内复刻,middleware 包的版本未导出。
|
|
// 用途:NotFoundHandler 判断浏览器 Accept。
|
|
func acceptsHTML(accept string) bool {
|
|
if accept == "" {
|
|
return false
|
|
}
|
|
for _, part := range strings.Split(accept, ",") {
|
|
mt := strings.TrimSpace(part)
|
|
if mt == "" {
|
|
continue
|
|
}
|
|
if idx := strings.Index(mt, ";"); idx >= 0 {
|
|
mt = strings.TrimSpace(mt[:idx])
|
|
}
|
|
mt = strings.ToLower(mt)
|
|
if mt == "text/html" || mt == "text/*" {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|