package services import ( "net/http" "net/url" "github.com/gin-gonic/gin" ) // IsSiteOrigin reports whether an Origin header names the site itself (the // apex or www). In dev DOMAIN is localhost, which covers Vite on any port. func IsSiteOrigin(origin, domain string) bool { u, err := url.Parse(origin) if err != nil { return false } host := u.Hostname() return domain != "" && (host == domain || host == "www."+domain) } // RequireSameOrigin refuses state-changing requests a browser sent from // elsewhere. SameSite=Lax does not cover this: radar. and git. are the same // site, so their pages get the auth cookies. A request with neither header is // not from a browser and passes. func RequireSameOrigin(domain string) gin.HandlerFunc { return func(c *gin.Context) { switch c.Request.Method { case http.MethodGet, http.MethodHead, http.MethodOptions: c.Next() return } allowed := true if origin := c.GetHeader("Origin"); origin != "" { allowed = IsSiteOrigin(origin, domain) } else if site := c.GetHeader("Sec-Fetch-Site"); site != "" { allowed = site == "same-origin" || site == "none" } if !allowed { c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "cross-origin request refused"}) return } c.Next() } }