/// A guard against cross-site request forgery, from the headers browsers /// send: `Sec-Fetch-Site` when there is one, `Origin` against `Host` /// otherwise. import std/http.{type Request} import std/option /// Whether `req` changes something (any method but GET, HEAD and OPTIONS) /// on behalf of a page from another site. A request without either header /// does not come from a browser page, and passes. pub fn cross_site :: req: Request -> Bool { if safe req.method { False } else { match http.header req "Sec-Fetch-Site" { Some(site) -> site != "same-origin" && site != "none" , None -> match http.header req "Origin" { Some(origin) -> !same_host origin (http.header req "Host" |> option.unwrap_or "") , None -> False } } } } fn safe :: method: String -> Bool { method == "GET" || method == "HEAD" || method == "OPTIONS" } fn same_host :: origin: String host: String -> Bool { host != "" && (origin == "https://" <> host || origin == "http://" <> host) }