/// Cookies (RFC 6265): reading a request's `Cookie` headers and building /// `Set-Cookie` response headers. /// /// import std/http/cookie /// /// match cookie.cookie(req, "session") { /// Some(token) -> home(token), /// None -> http.html(views.login("")), /// } /// /// http.text(200, "ok") |> cookie.set_cookie(cookie.new("session", token)) /// /// `new` fills in the safe defaults (`Path=/`, `Secure`, `HttpOnly`, /// `SameSite=Lax`); change them with a record update: /// `SetCookie(..cookie.new("theme", "dark"), http_only: False)`. /// (`set_cookie` is here, not in `std/http`: imports form a DAG, and this /// module already imports that one for `Request` and `Response`.) /// /// Out of scope, on purpose: signing cookies (a `std/crypto` /// `hmac_sha256` helper could follow), and `Expires` (`Max-Age` covers /// it). Names prefixed `__Host-` or `__Secure-` promise the browser a /// `Secure` cookie (and, for `__Host-`, `Path=/` and no `Domain`): that /// is what `new` builds, but it is not checked here. import std/bytes import std/http import std/list import std/option import std/string /// The `SameSite` attribute. `NoneSite` is RFC 6265bis's `SameSite=None` /// (a cross-site cookie, which must also be `Secure`): it is not called /// `None`, which is `Option`'s and would shadow it in this module, and /// clash with it for anyone importing both. For no `SameSite` attribute /// at all, set `same_site` to `None`. @derive Eq Show pub type SameSite { Lax, Strict, NoneSite } /// A `Set-Cookie` header, as a record: `new` fills in the defaults, /// record updates change them. @derive Eq Show pub type SetCookie { SetCookie( name: String , value: String , path: Option , domain: Option /// Seconds the cookie lives; 0 deletes it (see `expire`). , max_age: Option , secure: Bool , http_only: Bool /// `None`: no `SameSite` attribute at all. , same_site: Option ) } /// A cookie named `name` holding `value`, with safe defaults: `Path=/`, /// `Secure`, `HttpOnly`, `SameSite=Lax`. Panics if `name` or `value` /// contains a character a cookie cannot (see `to_header`). pub fn new :: name: String value: String -> SetCookie { SetCookie( name: checked_name name , value: checked value "value" , path: Some("/") , domain: None , max_age: None , secure: True , http_only: True , same_site: Some(Lax) ) } /// A cookie that deletes `name` (an empty value, `Max-Age=0`): the /// answer to a logout. pub fn expire :: name: String -> SetCookie { SetCookie(..new name "", max_age: Some(0)) } /// The `Set-Cookie` header value for `c`. Panics when a field holds a /// character a header cannot — `;`, `,`, a space or a control character /// (RFC 6265's cookie-octets), and for a name also `=` or emptiness — /// which a record update can introduce past `new`'s check. pub fn to_header :: c: SetCookie -> String { let path = attribute "Path" c.path let domain = attribute "Domain" c.domain let max_age = option.map c.max_age fn n { "; Max-Age=" <> show n } |> option.unwrap_or "" let secure = if c.secure { "; Secure" } else { "" } let http_only = if c.http_only { "; HttpOnly" } else { "" } let same_site = option.map c.same_site same_site_attribute |> option.unwrap_or "" string.concat [ checked_name c.name , "=" , checked c.value "value" , path , domain , max_age , secure , http_only , same_site ] } /// `resp` with a `Set-Cookie` header for `c` added (a response can set /// several cookies: each is its own header). pub fn set_cookie :: resp: http.Response c: SetCookie -> http.Response { http.with_header resp "Set-Cookie" (to_header c) } /// The request's cookies: the `(name, value)` pairs of its `Cookie` /// headers (a request can have several), parsed per RFC 6265 §5.4: each /// pair is split on its first `=`, trimmed of surrounding spaces and /// unquoted; a pair without `=` or with an empty name is skipped. pub fn cookies :: req: http.Request -> List<(String, String)> { use h <- list.flat_map req.headers if string.to_lower h.0 == "cookie" { pairs h.1 } else { [] } } /// The value of the request's cookie `name` (the first, if repeated). pub fn cookie :: req: http.Request name: String -> Option { find (cookies req) name } fn find :: pairs: List<(String, String)> name: String -> Option { match pairs { [] -> None , [(k, v), ..rest] -> if k == name { Some(v) } else { find rest name } } } /// The pairs of one `Cookie` header's value. fn pairs :: header: String -> List<(String, String)> { use part <- list.flat_map (string.split header ";") match pair (string.trim part) { Some(p) -> [p], None -> [] } } /// One `name=value` pair: split on the first `=` (the value may hold /// more), name and value trimmed, the value unquoted; `None` when there /// is no `=` or the name is empty. fn pair :: part: String -> Option<(String, String)> { match string.split part "=" { [name, value, ..rest] -> { let name = string.trim name if name == "" { None } else { Some((name, unquote (string.trim (string.join [value, ..rest] "=")))) } } , _ -> None } } /// `v` without its surrounding quotes, if it is `"quoted"` (a cookie /// value may be, RFC 6265 §4.1.1). fn unquote :: v: String -> String { let b = bytes.from_string v if bytes.length b >= 2 && string.starts_with v "\"" && string.ends_with v "\"" { bytes.to_string_lossy (bytes.slice b 1 (bytes.length b - 1)) } else { v } } /// `; Name=value` for a present attribute; its value checked. fn attribute :: name: String value: Option -> String { option.map value fn v { "; " <> name <> "=" <> checked v (string.to_lower name) } |> option.unwrap_or "" } fn same_site_attribute :: s: SameSite -> String { "; SameSite=" <> match s { Lax -> "Lax", Strict -> "Strict", NoneSite -> "None" } } /// `s`, when it can go in a cookie; panics otherwise. A name or value /// cannot contain `;`, `,`, a space or a control character (RFC 6265's /// cookie-octets: printable ASCII but those two). fn checked :: s: String what: String -> String { if list.all (string.chars s) cookie_char { s } else { panic "cookie: a {what} cannot contain `;`, `,`, a space or a control character: {s:?}" } } /// `name`, when it can name a cookie: `checked`, and neither empty nor /// holding `=` (which would split it in two when read back). fn checked_name :: name: String -> String { if name == "" || string.contains name "=" { panic "cookie: a name cannot be empty or contain `=`: {name:?}" } else { checked name "name" } } /// A cookie-octet (RFC 6265 §4.1.1): a printable ASCII character but `;` /// and `,`. fn cookie_char :: c: String -> Bool { c > " " && c < "\u{7f}" && c != ";" && c != "," }