From ff785f409ffe52b6832494cef845561ad40cdbad Mon Sep 17 00:00:00 2001 From: talksik Date: Wed, 18 Mar 2026 07:56:08 -0700 Subject: [PATCH] fix: handle pre-flight requests --- go/cmd/orion/main.go | 6 +++++- go/internal/middleware/cors.go | 39 ++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 go/internal/middleware/cors.go diff --git a/go/cmd/orion/main.go b/go/cmd/orion/main.go index 7b867f3..5d30d9a 100644 --- a/go/cmd/orion/main.go +++ b/go/cmd/orion/main.go @@ -119,9 +119,13 @@ func main() { mux.Handle("POST /depot/upload", withAuth(h.PrepareUpload)) mux.Handle("POST /depot/objects/{id}/confirm", withAuth(h.ConfirmUpload)) + // Apply middleware + // nil allows all origins (required for electron app) + muxWithCors := middleware.CORS(nil)(mux) + addr := fmt.Sprintf("0.0.0.0:%s", port) slog.Info("running server", "addr", addr) - if err := http.ListenAndServe(addr, mux); err != nil { + if err := http.ListenAndServe(addr, muxWithCors); err != nil { slog.Error("server failed", "error", err) os.Exit(1) } diff --git a/go/internal/middleware/cors.go b/go/internal/middleware/cors.go new file mode 100644 index 0000000..f790338 --- /dev/null +++ b/go/internal/middleware/cors.go @@ -0,0 +1,39 @@ +package middleware + +import "net/http" + +// CORS wraps a handler to add CORS headers and handle preflight requests. +func CORS(allowedOrigins []string) func(http.Handler) http.Handler { + originSet := make(map[string]struct{}, len(allowedOrigins)) + for _, o := range allowedOrigins { + originSet[o] = struct{}{} + } + + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + origin := r.Header.Get("Origin") + + // Check if the origin is allowed (empty allowedOrigins means allow all) + allowed := len(originSet) == 0 + if !allowed { + _, allowed = originSet[origin] + } + + if allowed && origin != "" { + w.Header().Set("Access-Control-Allow-Origin", origin) + w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") + w.Header().Set("Access-Control-Allow-Credentials", "true") + w.Header().Set("Access-Control-Max-Age", "86400") + } + + // Handle preflight + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusNoContent) + return + } + + next.ServeHTTP(w, r) + }) + } +}