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.
alex 2 years ago
parent 813d0501bd
commit b8bde8fbf2
Signed by: x1ddos
GPG Key ID: FDEFB4A63CBD8460

@ -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)

@ -284,18 +284,12 @@ func (x *Noxer) verifyEventLink(ctx context.Context, eventID, relayURL, link str
// link not found in the event text/json.
// check URLs in OGP metadata for each suitable link found in the event.
for _, urlStr := range eventURLs {
u, err := url.Parse(urlStr)
if err != nil {
continue // invalid url
}
if ext := path.Ext(u.Path); ext != "" {
if !strings.HasSuffix(ext, "html") && !strings.HasSuffix(ext, "htm") {
continue // assume not an html page
}
if !validOGPCandidate(urlStr) {
continue
}
meta, err := x.slurpLinkMeta(ctx, urlStr)
if err != nil {
log.Printf("verifyEventLink slurpLinkMeta(%s): %v", u, err)
log.Printf("verifyEventLink slurpLinkMeta(%s): %v", urlStr, err)
continue
}
for _, imgURL := range meta.ImageURLs {
@ -591,3 +585,23 @@ func validURL(urlStr string) bool {
}
return u.Scheme == "" || u.Scheme == "http" || u.Scheme == "https"
}
// must be sorted in lexical order
var knownOGPHosts = []string{
"opengraph.githubassets.com",
}
// reports whether urlStr looks like a URL to an html page.
func validOGPCandidate(urlStr string) bool {
u, err := url.Parse(urlStr)
if err != nil {
return false
}
ext := path.Ext(u.Path)
if ext == "" || strings.HasSuffix(ext, "html") || strings.HasSuffix(ext, "htm") {
return true
}
host := u.Hostname()
i := sort.SearchStrings(knownOGPHosts, host)
return i < len(knownOGPHosts) && knownOGPHosts[i] == host
}

Loading…
Cancel
Save