Skip to main content

transitous_core/
agent.rs

1//! The User-Agent. Transitous asks every client to name a contact in it
2//! (<https://transitous.org/api/>), so there is no request without one.
3
4use crate::Error;
5
6/// The project, named in every User-Agent.
7pub const PROJECT_URL: &str = "https://github.com/udondan/transitous";
8
9/// The User-Agent for `product` (like `transitous/1.2.0`) and the contact.
10///
11/// # Errors
12///
13/// [`Error::ContactMissing`] without a contact, [`Error::InvalidContact`] if
14/// it is neither a URL nor an email address.
15pub fn user_agent(product: &str, contact: Option<&str>) -> Result<String, Error> {
16    let contact = contact
17        .map(str::trim)
18        .filter(|contact| !contact.is_empty())
19        .ok_or(Error::ContactMissing)?;
20    check_contact(contact)?;
21    Ok(format!("{product} (+{PROJECT_URL}; contact: {contact})"))
22}
23
24/// Checks that the contact is an `http(s)` or `mailto:` URL, or an email
25/// address, and fits in a User-Agent.
26pub(crate) fn check_contact(contact: &str) -> Result<(), Error> {
27    let invalid = |reason: &str| Err(Error::InvalidContact(reason.to_owned()));
28    if contact
29        .chars()
30        .any(|c| c.is_whitespace() || c.is_control() || matches!(c, '(' | ')' | ';'))
31    {
32        return invalid("it must not contain spaces, parentheses or semicolons");
33    }
34    let lower = contact.to_ascii_lowercase();
35    if lower.starts_with("http://") || lower.starts_with("https://") {
36        return match motis::Url::parse(contact) {
37            Ok(url) if url.host_str().is_some_and(|host| !host.is_empty()) => Ok(()),
38            _ => invalid("the URL is not valid"),
39        };
40    }
41    let address = lower.strip_prefix("mailto:").unwrap_or(&lower);
42    match address.split_once('@') {
43        Some((local, domain))
44            if !local.is_empty() && domain.contains('.') && !domain.contains('@') =>
45        {
46            Ok(())
47        }
48        _ => invalid("use a URL or an email address"),
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn names_product_project_and_contact() {
58        assert_eq!(
59            user_agent("transitous/1.0.0", Some(" mailto:me@example.org ")).unwrap(),
60            "transitous/1.0.0 (+https://github.com/udondan/transitous; contact: mailto:me@example.org)"
61        );
62    }
63
64    #[test]
65    fn needs_a_contact() {
66        for contact in [None, Some(""), Some("  ")] {
67            assert!(matches!(
68                user_agent("t/1", contact),
69                Err(Error::ContactMissing)
70            ));
71        }
72    }
73
74    #[test]
75    fn accepts_urls_and_addresses() {
76        for contact in [
77            "https://github.com/me/bot",
78            "HTTP://example.org",
79            "me@example.org",
80            "mailto:me@example.org",
81        ] {
82            check_contact(contact).unwrap_or_else(|e| panic!("{contact}: {e}"));
83        }
84    }
85
86    #[test]
87    fn rejects_other_contacts() {
88        for contact in [
89            "me",
90            "@example.org",
91            "me@localhost",
92            "me@a@b.org",
93            "https://",
94            "https://exa mple.org",
95            "me@example.org)",
96            "a;b@example.org",
97            "mailto:",
98        ] {
99            assert!(
100                matches!(check_contact(contact), Err(Error::InvalidContact(_))),
101                "{contact}"
102            );
103        }
104    }
105}