package tsbridge import ( "net/http" "strconv" "sync/atomic" ) // Cross-origin (CORS) support. Off by default: enabling it lets ANY web page // in any tab on any origin open this server's WebSocket (and read static // resources), which is exactly what you want when hosting your own client // for tsbutt elsewhere, and exactly what you don't want when some unrelated // page starts probing the proxy. The user turns it on deliberately. // corsMaxAgeSecs caps how long browsers may cache the preflight verdict. It // is deliberately short (a few minutes): CORS is a user-facing toggle, and a // long-lived cache would let browsers keep trusting a permissive policy // after the user turned it back off. const corsMaxAgeSecs = 300 var corsEnabled atomic.Bool // SetCORS enables or disables cross-origin browser access to the server. // It is process-wide, takes effect immediately (including for WebSocket // upgrades), and defaults to disabled. Returns an error only for gomobile's // benefit (the bound API is error-returning). func SetCORS(enabled bool) error { corsEnabled.Store(enabled) return nil } // corsMiddleware adds CORS response headers when — and only when — the // option is enabled. The request Origin is reflected: the point of the // option is to admit arbitrary origins, and credentials are never allowed, // so reflection grants no more than the toggle already does. `Vary: Origin` // keeps caches from serving one origin a response minted for another. // // WebSocket connections need no preflight (the handshake is a simple GET), // so "allowed" here just means the handshake response carries the same // Access-Control-Allow-Origin header the browser checks before firing the // open event. Ordinary HTTP requests (healthz, static assets) get the same // treatment, and non-simple requests get a real preflight answer. func corsMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if corsEnabled.Load() { if origin := r.Header.Get("Origin"); origin != "" { h := w.Header() h.Set("Access-Control-Allow-Origin", origin) h.Set("Vary", "Origin") if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { h.Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") h.Set("Access-Control-Allow-Headers", r.Header.Get("Access-Control-Request-Headers")) h.Set("Access-Control-Max-Age", strconv.Itoa(corsMaxAgeSecs)) w.WriteHeader(http.StatusNoContent) return } } } next.ServeHTTP(w, r) }) }