diff --git a/backend/config/config.go b/backend/config/config.go index 168bff9..352b9d7 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -106,6 +106,7 @@ func defaultCORSOrigins() []string { "http://127.0.0.1:1420", "http://tauri.localhost", "https://tauri.localhost", + "tauri://localhost", // macOS Tauri WebView 实际 Origin // Logan.Li } } diff --git a/backend/middleware/cors.go b/backend/middleware/cors.go index 4dc9dc2..e197a00 100644 --- a/backend/middleware/cors.go +++ b/backend/middleware/cors.go @@ -11,7 +11,7 @@ import ( // CORSMiddleware CORS 中间件,使用显式白名单避免携带凭据时放行任意来源。 // Logan.Li func CORSMiddleware(cfg *config.Config) gin.HandlerFunc { - origins := filterHTTPOrigins(cfg.CORSOrigins) + origins := cfg.CORSOrigins if len(origins) == 0 { origins = []string{ "http://localhost:5181", @@ -20,9 +20,23 @@ func CORSMiddleware(cfg *config.Config) gin.HandlerFunc { "http://127.0.0.1:3000", } } + allowed := make([]string, 0, len(origins)) + for _, o := range origins { + allowed = append(allowed, strings.ToLower(strings.TrimSpace(o))) + } return cors.New(cors.Config{ - AllowOrigins: origins, + // 精确白名单匹配(大小写不敏感)。AllowOrigins 只接受 http/https, + // 而 macOS Tauri WebView 的 Origin 是 tauri://localhost,须用函数匹配 // Logan.Li + AllowOriginFunc: func(origin string) bool { + o := strings.ToLower(strings.TrimSpace(origin)) + for _, a := range allowed { + if o == a { + return true + } + } + return false + }, AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"}, AllowHeaders: []string{"Origin", "Content-Type", "Authorization", "X-Requested-With"}, ExposeHeaders: []string{"Content-Length", "Content-Type"}, @@ -30,18 +44,3 @@ func CORSMiddleware(cfg *config.Config) gin.HandlerFunc { MaxAge: 12 * time.Hour, }) } - -// filterHTTPOrigins keeps only origins gin-contrib/cors accepts (http/https or *). // Logan.Li -func filterHTTPOrigins(origins []string) []string { - out := make([]string, 0, len(origins)) - for _, origin := range origins { - o := strings.TrimSpace(origin) - if o == "" { - continue - } - if o == "*" || strings.HasPrefix(o, "http://") || strings.HasPrefix(o, "https://") { - out = append(out, o) - } - } - return out -}