sky/internal/platform/middleware/cors.go
root 6ed55254a0 chore: initial import of sky project
Go + PostgreSQL + Valkey backend (cmd/internal/migrations),
uni-app mobile frontend, PC web (web/), admin console (admin/),
Android WebView container (android_project/).
Build artifacts, node_modules, local env and debug screenshots excluded.
2026-11-09 22:22:44 +08:00

91 lines
2.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"net/http"
"strconv"
"strings"
"time"
)
// CORS 跨域中间件。
//
// 自己实现而不引入 go-chi/cors:逻辑只有几十行,而依赖越少越好审计。
//
// 安全要点:
// - 绝不用 Access-Control-Allow-Origin: * 配合 Allow-Credentials: true
// 两者同时出现会被浏览器直接拒绝,且是常见配置错误
// - 允许的 Origin 走白名单,不做前缀/后缀模糊匹配
// (evil-example.com 会通过 *.example.com 这类错误配置)
// - 预检结果缓存 Max-Age,避免每个请求都打一次 OPTIONS
type CORS struct {
allowOrigins map[string]bool
allowMethods string
allowHeaders string
maxAge string
debug bool // dev 环境允许 localhost 任意端口
}
func NewCORS(origins []string, devMode bool) *CORS {
m := make(map[string]bool, len(origins))
for _, o := range origins {
o = strings.TrimSpace(o)
if o != "" {
m[o] = true
}
}
return &CORS{
allowOrigins: m,
allowMethods: "GET, POST, PUT, PATCH, DELETE, OPTIONS",
allowHeaders: "Authorization, Content-Type, X-Requested-With",
maxAge: strconv.Itoa(int((12 * time.Hour).Seconds())),
debug: devMode,
}
}
func (c *CORS) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" && c.allowed(origin) {
// 回显具体 origin 而非 *,这样将来要加 Cookie 也不会踩坑
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", c.allowMethods)
w.Header().Set("Access-Control-Allow-Headers", c.allowHeaders)
w.Header().Set("Access-Control-Max-Age", c.maxAge)
// Vary: Origin 必须设置,否则 CDN/代理会缓存住第一个 origin 的响应,
// 导致其他来源拿到错误的 CORS 头
w.Header().Add("Vary", "Origin")
// 暴露给前端 JS 可读的响应头(限流信息前端要展示)
w.Header().Set("Access-Control-Expose-Headers",
"X-RateLimit-Limit, X-RateLimit-Remaining, Retry-After")
}
// 预检直接返回 204,不进业务逻辑
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func (c *CORS) allowed(origin string) bool {
if c.allowOrigins[origin] {
return true
}
// 开发模式放行本机任意端口:前端 dev server 端口经常变(3100/5173/4173)
if c.debug {
if strings.HasPrefix(origin, "http://127.0.0.1:") ||
strings.HasPrefix(origin, "http://localhost:") {
return true
}
// Android 模拟器约定 10.0.2.2 = 宿主机回环(WebView 套壳 dev 模式),
// 离线 WebView 容器的资源源固定为 app.local
return strings.HasPrefix(origin, "http://10.0.2.2:") ||
origin == "http://app.local"
}
return false
}