nolint:revive
(allowAll bool, origins ...string)
| 27 | |
| 28 | //nolint:revive |
| 29 | func Cors(allowAll bool, origins ...string) func(next http.Handler) http.Handler { |
| 30 | if len(origins) == 0 { |
| 31 | // The default behavior is '*', so putting the empty string defaults to |
| 32 | // the secure behavior of blocking CORS requests. |
| 33 | origins = []string{""} |
| 34 | } |
| 35 | if allowAll { |
| 36 | origins = []string{"*"} |
| 37 | } |
| 38 | |
| 39 | // Standard CORS for most endpoints |
| 40 | standardCors := cors.Handler(cors.Options{ |
| 41 | AllowedOrigins: origins, |
| 42 | // We only need GET for latency requests |
| 43 | AllowedMethods: []string{http.MethodOptions, http.MethodGet}, |
| 44 | AllowedHeaders: []string{"Accept", "Content-Type", "X-LATENCY-CHECK", "X-CSRF-TOKEN"}, |
| 45 | // Do not send any cookies |
| 46 | AllowCredentials: false, |
| 47 | }) |
| 48 | |
| 49 | // Permissive CORS for OAuth2 and MCP endpoints |
| 50 | permissiveCors := cors.Handler(cors.Options{ |
| 51 | AllowedOrigins: []string{"*"}, |
| 52 | AllowedMethods: []string{ |
| 53 | http.MethodGet, |
| 54 | http.MethodPost, |
| 55 | http.MethodDelete, |
| 56 | http.MethodOptions, |
| 57 | }, |
| 58 | AllowedHeaders: []string{ |
| 59 | "Content-Type", |
| 60 | "Accept", |
| 61 | "Authorization", |
| 62 | "x-api-key", |
| 63 | "Mcp-Session-Id", |
| 64 | "MCP-Protocol-Version", |
| 65 | "Last-Event-ID", |
| 66 | }, |
| 67 | ExposedHeaders: []string{ |
| 68 | "Content-Type", |
| 69 | "Authorization", |
| 70 | "x-api-key", |
| 71 | "Mcp-Session-Id", |
| 72 | "MCP-Protocol-Version", |
| 73 | }, |
| 74 | MaxAge: 86400, // 24 hours in seconds |
| 75 | AllowCredentials: false, |
| 76 | }) |
| 77 | |
| 78 | return func(next http.Handler) http.Handler { |
| 79 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 80 | // Use permissive CORS for OAuth2, MCP, and well-known endpoints |
| 81 | if strings.HasPrefix(r.URL.Path, "/oauth2/") || |
| 82 | strings.HasPrefix(r.URL.Path, "/api/experimental/mcp/") || |
| 83 | strings.HasPrefix(r.URL.Path, "/.well-known/oauth-") { |
| 84 | permissiveCors(next).ServeHTTP(w, r) |
| 85 | return |
| 86 | } |