Skip to main content

vertigo_cli/serve/
request_headers.rs

1//! The headers of a browser's request that change how the server renders a page, and what the
2//! app gets from them during SSR.
3
4use std::collections::HashMap;
5
6/// The headers of a browser's request that change how the server renders a page, for
7/// [`ServerState::request_with_headers`](super::ServerState::request_with_headers).
8#[derive(Clone, Copy, Debug, Default)]
9pub struct RequestHeaders<'a> {
10    /// `Cookie`. It goes out with the SSR fetches to the server's own origin, and the cookies
11    /// named with [`MountConfigBuilder::ssr_cookie`](super::MountConfigBuilder::ssr_cookie) are
12    /// what `get_driver().cookie_get()` gives the app.
13    pub cookie: Option<&'a str>,
14    /// `Accept-Language`: what `get_driver().languages()` gives the app.
15    pub accept_language: Option<&'a str>,
16}
17
18/// The language tags of an `Accept-Language` header, the most preferred first: by their weight,
19/// and those of the same weight in the order of the header. What the browser doesn't want
20/// (`q=0`), the wildcard `*` and what doesn't parse are left out.
21///
22/// Browsers send the header from the list in `navigator.languages`, so this is the list the
23/// browser will tell the app after hydration.
24pub fn accept_languages(header: &str) -> Vec<String> {
25    let mut weighted: Vec<(f32, &str)> = header.split(',').filter_map(weighted_tag).collect();
26    // Stable, so those of the same weight keep the header's order.
27    weighted.sort_by(|(left, _), (right, _)| right.total_cmp(left));
28    weighted
29        .into_iter()
30        .map(|(_, tag)| tag.to_string())
31        .collect()
32}
33
34/// A language range of `Accept-Language` with its weight, unless the browser doesn't want it or
35/// it doesn't parse.
36fn weighted_tag(range: &str) -> Option<(f32, &str)> {
37    let mut parts = range.split(';').map(str::trim);
38    let tag = parts.next().filter(|tag| is_language_tag(tag))?;
39    let mut weight = 1.0;
40    for param in parts {
41        let Some((name, value)) = param.split_once('=') else {
42            continue;
43        };
44        if name.trim().eq_ignore_ascii_case("q") {
45            weight = value
46                .trim()
47                .parse::<f32>()
48                .ok()
49                .filter(|weight| (0.0..=1.0).contains(weight))?;
50        }
51    }
52    (weight > 0.0).then_some((weight, tag))
53}
54
55/// A language tag as browsers send them: letters and digits, in parts joined by `-`.
56fn is_language_tag(tag: &str) -> bool {
57    tag.split('-')
58        .all(|part| !part.is_empty() && part.chars().all(|char| char.is_ascii_alphanumeric()))
59}
60
61/// The cookies of a `Cookie` header named in `names`, as the driver reads them in the browser
62/// (`Cookies.get`): the value URI-decoded, and a part that isn't one `name=value` left out. Of
63/// two with the same name, the first counts, as there.
64pub fn readable_cookies(header: &str, names: &[String]) -> HashMap<String, String> {
65    let mut cookies = HashMap::new();
66    for cookie in header.split(';') {
67        let chunks: Vec<&str> = cookie.trim().split('=').collect();
68        let [name, value] = chunks[..] else {
69            continue;
70        };
71        if !names.iter().any(|wanted| wanted == name) || cookies.contains_key(name) {
72            continue;
73        }
74        if let Some(value) = decode_uri_component(value) {
75            cookies.insert(name.to_string(), value);
76        }
77    }
78    cookies
79}
80
81/// `value` decoded as `decodeURIComponent` decodes it, `None` where that throws: a `%` without two
82/// hex digits after it, or bytes that aren't UTF-8.
83fn decode_uri_component(value: &str) -> Option<String> {
84    let mut bytes = Vec::with_capacity(value.len());
85    let mut rest = value.as_bytes();
86    while let Some((&byte, tail)) = rest.split_first() {
87        if byte == b'%' {
88            let hex = tail
89                .get(..2)
90                .filter(|hex| hex.iter().all(u8::is_ascii_hexdigit))?;
91            let hex = std::str::from_utf8(hex).ok()?;
92            bytes.push(u8::from_str_radix(hex, 16).ok()?);
93            rest = &tail[2..];
94        } else {
95            bytes.push(byte);
96            rest = tail;
97        }
98    }
99    String::from_utf8(bytes).ok()
100}
101
102#[cfg(test)]
103mod tests {
104    use super::{accept_languages, readable_cookies};
105
106    #[test]
107    fn languages_come_the_most_preferred_first() {
108        assert_eq!(
109            accept_languages("pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7"),
110            ["pl-PL", "pl", "en-US", "en"]
111        );
112        assert_eq!(
113            accept_languages("en;q=0.5, de, fr;Q=0.9"),
114            ["de", "fr", "en"]
115        );
116    }
117
118    #[test]
119    fn languages_of_the_same_weight_keep_the_order_of_the_header() {
120        assert_eq!(
121            accept_languages("da, en-GB;q=0.8, en;q=0.8"),
122            ["da", "en-GB", "en"]
123        );
124    }
125
126    #[test]
127    fn what_the_browser_doesnt_want_or_doesnt_parse_is_left_out() {
128        assert_eq!(accept_languages("fr;q=0, *;q=0.1, it"), ["it"]);
129        assert_eq!(
130            accept_languages(" , ;q=1, en;q=x, de;q=2, <b>, en--US, zh-Hant-TW;level=1"),
131            ["zh-Hant-TW"]
132        );
133        assert!(accept_languages("").is_empty());
134    }
135
136    fn names(names: &[&str]) -> Vec<String> {
137        names.iter().map(|name| name.to_string()).collect()
138    }
139
140    #[test]
141    fn only_the_cookies_named_are_read() {
142        let cookies = readable_cookies("session=secret; lang=en; theme=dark", &names(&["lang"]));
143
144        assert_eq!(cookies.len(), 1);
145        assert_eq!(cookies.get("lang").map(String::as_str), Some("en"));
146    }
147
148    #[test]
149    fn cookies_are_read_as_the_driver_reads_them_in_the_browser() {
150        let wanted = names(&["note", "json", "bad", "twice", "plus", "eq"]);
151        let cookies = readable_cookies(
152            "note=Za%C5%BC%C3%B3%C5%82%C4%87%20g%C4%99%C5%9Bl%C4%85; json=%7B%22a%22%3A1%7D; \
153             bad=%E0%A4%A; twice=first; twice=second; plus=a+b; eq=a=b",
154            &wanted,
155        );
156
157        assert_eq!(cookies["note"], "Zażółć gęślą");
158        assert_eq!(cookies["json"], r#"{"a":1}"#);
159        // `decodeURIComponent` throws on these, and `Cookies.get` skips a part with two `=`.
160        assert!(!cookies.contains_key("bad") && !cookies.contains_key("eq"));
161        assert_eq!(cookies["twice"], "first");
162        assert_eq!(cookies["plus"], "a+b");
163    }
164}