From 78a1aae7e885cc4a82162842ac57d2aa844e72d8 Mon Sep 17 00:00:00 2001 From: alex Date: Fri, 9 Dec 2022 23:57:18 +0100 Subject: [PATCH] cmd/noxy: add CORS headers to all endpoints the simplest approach at the moment: allow requests from all origins, only GET and OPTIONS methods. allowed headers are '*'. this prevents clients from providing credentials via cookies which isn't used anyway. nuff cookies. --- cmd/noxy/main.go | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/cmd/noxy/main.go b/cmd/noxy/main.go index bd9c4fb..c014149 100644 --- a/cmd/noxy/main.go +++ b/cmd/noxy/main.go @@ -130,7 +130,7 @@ func main() { log.Printf("listening on %s", *listenAddr) log.Printf("known relays: %s", strings.Join(knownRelays, ", ")) - http.ListenAndServe(*listenAddr, logHandler(mux)) + http.ListenAndServe(*listenAddr, logHandler(cors(mux))) } // handles requests to / @@ -198,6 +198,21 @@ func writeError(w http.ResponseWriter, err error) { fmt.Fprint(w, err.Error()) } +func cors(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "*") // nb: wildcard prevents authentication + w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS") + if r.Method == "OPTIONS" { + w.Header().Set("Access-Control-Max-Age", "2592000") // valid for 30 days + w.WriteHeader(http.StatusNoContent) + return + } + w.Header().Set("Access-Control-Expose-Headers", "*"); + h.ServeHTTP(w, r) + }) +} + func logHandler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf("%s %s", r.Method, r.RequestURI)