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/// What of a `Cookie` header goes out with the SSR fetches to the server's own origin: the cookies
82/// named in `names` as they came, or the whole header when no names are given. `None` when nothing
83/// is left.
84pub fn forwarded_cookies(header: &str, names: &[String]) -> Option<String> {
85    if names.is_empty() {
86        return Some(header.to_string());
87    }
88
89    let forwarded: Vec<&str> = header
90        .split(';')
91        .map(str::trim)
92        .filter(|cookie| {
93            cookie
94                .split_once('=')
95                .is_some_and(|(name, _)| names.iter().any(|wanted| wanted == name))
96        })
97        .collect();
98
99    (!forwarded.is_empty()).then(|| forwarded.join("; "))
100}
101
102/// `value` decoded as `decodeURIComponent` decodes it, `None` where that throws: a `%` without two
103/// hex digits after it, or bytes that aren't UTF-8.
104fn decode_uri_component(value: &str) -> Option<String> {
105    let mut bytes = Vec::with_capacity(value.len());
106    let mut rest = value.as_bytes();
107    while let Some((&byte, tail)) = rest.split_first() {
108        if byte == b'%' {
109            let hex = tail
110                .get(..2)
111                .filter(|hex| hex.iter().all(u8::is_ascii_hexdigit))?;
112            let hex = std::str::from_utf8(hex).ok()?;
113            bytes.push(u8::from_str_radix(hex, 16).ok()?);
114            rest = &tail[2..];
115        } else {
116            bytes.push(byte);
117            rest = tail;
118        }
119    }
120    String::from_utf8(bytes).ok()
121}
122
123#[cfg(test)]
124mod tests {
125    use super::{accept_languages, forwarded_cookies, readable_cookies};
126
127    #[test]
128    fn all_cookies_go_out_when_none_are_named() {
129        assert_eq!(
130            forwarded_cookies("session=a; _ga=b", &[]).as_deref(),
131            Some("session=a; _ga=b")
132        );
133    }
134
135    #[test]
136    fn only_the_named_cookies_go_out_as_they_came() {
137        assert_eq!(
138            forwarded_cookies(
139                "_ga=b; session=a=c%20d; theme=dark",
140                &names(&["session", "theme"])
141            )
142            .as_deref(),
143            Some("session=a=c%20d; theme=dark")
144        );
145    }
146
147    #[test]
148    fn nothing_goes_out_without_a_named_cookie() {
149        assert_eq!(forwarded_cookies("_ga=b", &names(&["session"])), None);
150    }
151
152    #[test]
153    fn languages_come_the_most_preferred_first() {
154        assert_eq!(
155            accept_languages("pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7"),
156            ["pl-PL", "pl", "en-US", "en"]
157        );
158        assert_eq!(
159            accept_languages("en;q=0.5, de, fr;Q=0.9"),
160            ["de", "fr", "en"]
161        );
162    }
163
164    #[test]
165    fn languages_of_the_same_weight_keep_the_order_of_the_header() {
166        assert_eq!(
167            accept_languages("da, en-GB;q=0.8, en;q=0.8"),
168            ["da", "en-GB", "en"]
169        );
170    }
171
172    #[test]
173    fn what_the_browser_doesnt_want_or_doesnt_parse_is_left_out() {
174        assert_eq!(accept_languages("fr;q=0, *;q=0.1, it"), ["it"]);
175        assert_eq!(
176            accept_languages(" , ;q=1, en;q=x, de;q=2, <b>, en--US, zh-Hant-TW;level=1"),
177            ["zh-Hant-TW"]
178        );
179        assert!(accept_languages("").is_empty());
180    }
181
182    fn names(names: &[&str]) -> Vec<String> {
183        names.iter().map(|name| name.to_string()).collect()
184    }
185
186    #[test]
187    fn only_the_cookies_named_are_read() {
188        let cookies = readable_cookies("session=secret; lang=en; theme=dark", &names(&["lang"]));
189
190        assert_eq!(cookies.len(), 1);
191        assert_eq!(cookies.get("lang").map(String::as_str), Some("en"));
192    }
193
194    #[test]
195    fn cookies_are_read_as_the_driver_reads_them_in_the_browser() {
196        let wanted = names(&["note", "json", "bad", "twice", "plus", "eq"]);
197        let cookies = readable_cookies(
198            "note=Za%C5%BC%C3%B3%C5%82%C4%87%20g%C4%99%C5%9Bl%C4%85; json=%7B%22a%22%3A1%7D; \
199             bad=%E0%A4%A; twice=first; twice=second; plus=a+b; eq=a=b",
200            &wanted,
201        );
202
203        assert_eq!(cookies["note"], "Zażółć gęślą");
204        assert_eq!(cookies["json"], r#"{"a":1}"#);
205        // `decodeURIComponent` throws on these, and `Cookies.get` skips a part with two `=`.
206        assert!(!cookies.contains_key("bad") && !cookies.contains_key("eq"));
207        assert_eq!(cookies["twice"], "first");
208        assert_eq!(cookies["plus"], "a+b");
209    }
210}