Cotton code
389 lines · 17.5 KB · RustRaw
//! COTTON SITES (assets/design/sites/DECISIONS.md, CONTRACT.md): what the app decides that is not the book itself://! the search line (an address, a search, or his own sites, all on the phone), the engines, a link's one-time code//! masked, where a link that leaves the web goes, and which live pages a phone keeps when it switches (like tabs).//! Nothing here leaves the phone.use super::{home_of, host_of, Book, Row};/// A search engine Sites offers; results always load in a throwaway place that keeps nothing (question 6).#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Engine {    DuckDuckGo,    Startpage,    Brave,    Mojeek,    Ecosia,    /// Offered last, said plainly.    Google,}impl Engine {    /// In the order "Search with" offers them: DuckDuckGo first, Google last.    pub const ALL: [Engine; 6] = [Engine::DuckDuckGo, Engine::Startpage, Engine::Brave, Engine::Mojeek, Engine::Ecosia, Engine::Google];    pub fn id(self) -> &'static str {        match self {            Engine::DuckDuckGo => "duckduckgo",            Engine::Startpage => "startpage",            Engine::Brave => "brave",            Engine::Mojeek => "mojeek",            Engine::Ecosia => "ecosia",            Engine::Google => "google",        }    }    /// The engine an id names; DuckDuckGo for anything unknown.    pub fn of(id: &str) -> Engine {        Engine::ALL.into_iter().find(|e| e.id() == id).unwrap_or(Engine::DuckDuckGo)    }    /// The results page for `q`.    pub fn url(self, q: &str) -> String {        let base = match self {            Engine::DuckDuckGo => "https://duckduckgo.com/",            Engine::Startpage => "https://www.startpage.com/do/search",            Engine::Brave => "https://search.brave.com/search",            Engine::Mojeek => "https://www.mojeek.com/search",            Engine::Ecosia => "https://www.ecosia.org/search",            Engine::Google => "https://www.google.com/search",        };        let mut url = url::Url::parse(base).expect("an engine's own address");        url.query_pairs_mut().append_pair("q", q.trim());        url.to_string()    }}/// What the first line of the search line offers for what he typed.#[derive(Clone, Debug, PartialEq, Eq)]pub enum First {    /// Nothing typed.    Empty,    /// It is an address: "Go to ledgerbank.example".    Address { url: String, host: String },    /// Words: "Search for '…'", at the engine's page.    Search { q: String, url: String },}/// What he typed, read on the phone. An address is one only when it reads as one (`home_of`); anything else is a search.pub fn first(q: &str, engine: Engine) -> First {    let q = q.trim();    if q.is_empty() {        return First::Empty;    }    match home_of(q) {        Ok(url) => First::Address { host: host_of(&url), url },        Err(_) => First::Search { q: q.to_string(), url: engine.url(q) },    }}/// His own sites matching what he typed, by name or address, in the list's order. Hidden ones only when shown.pub fn matches<'a>(book: &'a Book, q: &str, unlocked: bool) -> Vec<&'a Row> {    let q = q.trim().to_lowercase();    if q.is_empty() {        return Vec::new();    }    book.ordered(unlocked).into_iter().filter(|r| r.label.to_lowercase().contains(&q) || host_of(&r.home).contains(&q)).collect()}/// Query names that carry a one-time code or a sign-in token.const SECRET_PARAMS: [&str; 16] = ["token", "code", "otp", "key", "sig", "signature", "auth", "ticket", "nonce", "magic", "login_token", "access_token", "id_token", "t", "k", "hash"];/// Path words that mark a one-time sign-in link.const ONCE_PATHS: [&str; 10] = ["magic", "verify", "confirm", "signin", "sign-in", "login", "log-in", "auth", "passwordless", "one-time"];/// A link as the chooser shows it: whole, with any one-time code masked, and whether it looks like a one-time/// sign-in link (it loads only where he chooses, and only once).#[derive(Clone, Debug, PartialEq, Eq)]pub struct Shown {    pub shown: String,    pub once: bool,}pub fn shown(url: &str) -> Shown {    let Ok(mut parsed) = url::Url::parse(url.trim()) else {        return Shown { shown: url.trim().to_string(), once: false };    };    let mut masked = false;    let pairs: Vec<(String, String)> = parsed        .query_pairs()        .map(|(k, v)| {            let secret = SECRET_PARAMS.contains(&k.to_lowercase().as_str()) && v.len() >= 4;            masked |= secret;            let v = if secret { format!("{}•••", v.chars().take(2).collect::<String>()) } else { v.into_owned() };            (k.into_owned(), v)        })        .collect();    if !pairs.is_empty() {        parsed.query_pairs_mut().clear().extend_pairs(pairs);    }    // A long opaque path segment after a sign-in word is a token too: /magic/AbC…    let path = parsed.path().to_string();    let lower = path.to_lowercase();    let once_path = ONCE_PATHS.iter().any(|w| lower.split('/').any(|seg| seg == *w));    let segments: Vec<String> = path        .split('/')        .map(|seg| if once_path && seg.len() >= 16 && seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') { masked = true; format!("{}•••", &seg[..2]) } else { seg.to_string() })        .collect();    parsed.set_path(&segments.join("/"));    let shown = parsed.to_string().replace("%E2%80%A2", "•");    // A sign-in word alone (a site's own /login page) is no one-time link: only a code in the link makes it one, or    // a path that names itself single-use.    let single_use = ["magic", "passwordless", "one-time"].iter().any(|w| lower.split('/').any(|seg| seg == *w));    Shown { shown, once: masked || single_use }}/// Where a tapped link goes when it leaves the web (CONTRACT `sites.exit`): every exit is asked first.#[derive(Clone, Debug, PartialEq, Eq)]pub enum Exit {    /// An ordinary web page: it stays in Sites.    Inside,    Call { number: String },    Map,    Store,    /// `mailto:` goes to Post.    Mail { address: String },    /// Another app's own link.    App,    /// `javascript:`, `file:`, `data:` and the like: never opened.    Refused,}pub fn exit(url: &str) -> Exit {    let Ok(parsed) = url::Url::parse(url.trim()) else { return Exit::Refused };    match parsed.scheme() {        "http" | "https" => Exit::Inside,        "about" if parsed.path() == "blank" => Exit::Inside,        "tel" | "facetime" | "facetime-audio" => Exit::Call { number: percent_decoded(parsed.path()) },        "sms" => Exit::App,        "maps" | "geo" | "comgooglemaps" => Exit::Map,        "itms-apps" | "itms-appss" | "market" => Exit::Store,        "mailto" => Exit::Mail { address: percent_decoded(parsed.path()) },        "javascript" | "file" | "data" | "blob" | "about" | "content" | "chrome" | "view-source" => Exit::Refused,        _ => Exit::App,    }}fn percent_decoded(s: &str) -> String {    let b = s.as_bytes();    let mut out = Vec::with_capacity(b.len());    let mut i = 0;    while i < b.len() {        match (b[i], b.get(i + 1..i + 3).and_then(|h| std::str::from_utf8(h).ok()).and_then(|h| u8::from_str_radix(h, 16).ok())) {            (b'%', Some(byte)) => {                out.push(byte);                i += 3;            }            (c, _) => {                out.push(c);                i += 1;            }        }    }    String::from_utf8_lossy(&out).into_owned()}/// Sites' own list of tracking hosts (`sites_trackers.txt`), one registrable name each.pub fn trackers() -> Vec<&'static str> {    include_str!("sites_trackers.txt").lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).collect()}/// The site a host belongs to, as far as "third-party" goes: its last two names, or three under a two-letter/// country's short second level (`shop.example.co.uk` → `example.co.uk`). An address by number is its own site.pub fn site_of(host: &str) -> String {    let host = host.trim_end_matches('.').to_ascii_lowercase();    if host.parse::<std::net::IpAddr>().is_ok() || host.starts_with('[') {        return host;    }    let parts: Vec<&str> = host.split('.').collect();    let n = parts.len();    let take = if n >= 3 && parts[n - 1].len() == 2 && parts[n - 2].len() <= 3 { 3 } else { 2 };    parts[n.saturating_sub(take)..].join(".")}/// Whether a page's request is a tracker to block: its host is on the list (or under a name on it) and it is/// third-party to the page, so a site's own analytics on its own domain still loads. Android asks this for every/// request a site's page makes while that site blocks trackers; the iPhone loads `content_rules` once.pub fn blocked(page: &str, request: &str) -> bool {    let host = |u: &str| url::Url::parse(u).ok().and_then(|u| u.host_str().map(str::to_ascii_lowercase));    let (Some(page), Some(req)) = (host(page), host(request)) else { return false };    if site_of(&page) == site_of(&req) {        return false;    }    trackers().iter().any(|t| req == *t || req.ends_with(&format!(".{t}")))}/// The same list as WebKit content rules (`WKContentRuleListStore`): each host blocked third-party only.pub fn content_rules() -> serde_json::Value {    let rules: Vec<serde_json::Value> = trackers()        .iter()        .map(|t| {            let escaped = t.replace('.', "\\.");            serde_json::json!({                "trigger": { "url-filter": format!("^https?://([^/]*\\.)?{escaped}[:/]"), "load-type": ["third-party"] },                "action": { "type": "block" }            })        })        .collect();    serde_json::Value::Array(rules)}/// Which pages a phone keeps alive (switching is like tabs): the most recent sites first, up to `budget`. `recent`/// is the phone's order, most recent first; `to` moves to the front. Returns what to keep and what to let go.pub fn live(recent: &mut Vec<String>, to: Option<&str>, budget: usize) -> (Vec<String>, Vec<String>) {    if let Some(id) = to {        recent.retain(|r| r != id);        recent.insert(0, id.to_string());    }    let budget = budget.max(1);    let let_go = if recent.len() > budget { recent.split_off(budget) } else { Vec::new() };    (recent.clone(), let_go)}#[cfg(test)]mod tests {    use super::*;    fn book() -> Book {        let mut b = Book::default();        b.add("a".into(), "Work mail", "mail.example", true, false).unwrap();        b.add("b".into(), "Club", "club.example", false, false).unwrap();        b.add("c".into(), "Bank", "ledgerbank.example", true, true).unwrap();        b.add("d".into(), "Personal mail", "mail.example", true, false).unwrap();        b    }    #[test]    fn the_search_line_tells_an_address_from_words_on_the_phone() {        assert_eq!(first("  ", Engine::DuckDuckGo), First::Empty);        assert_eq!(first("ledgerbank.example", Engine::DuckDuckGo), First::Address { url: "https://ledgerbank.example/".into(), host: "ledgerbank.example".into() });        assert_eq!(first("trains to pune", Engine::DuckDuckGo), First::Search { q: "trains to pune".into(), url: "https://duckduckgo.com/?q=trains+to+pune".into() });        assert_eq!(first("pizza", Engine::Google), First::Search { q: "pizza".into(), url: "https://www.google.com/search?q=pizza".into() });        assert_eq!(Engine::of("nobody"), Engine::DuckDuckGo);        assert_eq!(Engine::ALL.last(), Some(&Engine::Google), "Google is offered last");    }    #[test]    fn matches_are_his_own_sites_in_his_order_and_hidden_only_when_shown() {        let mut b = book();        b.arrange(&["d".into(), "a".into()], &["d".into()]);        let ids = |q: &str, u: bool| matches(&b, q, u).iter().map(|r| r.id.clone()).collect::<Vec<_>>();        assert_eq!(ids("mail", false), ["d", "a"], "pinned first");        assert_eq!(ids("BANK", false), Vec::<String>::new());        assert_eq!(ids("bank", true), ["c"]);        assert_eq!(ids("", true), Vec::<String>::new());    }    #[test]    fn arranging_pins_and_orders_and_keeps_the_unnamed_after() {        let mut b = book();        b.arrange(&["b".into()], &["b".into(), "d".into()]);        assert_eq!(b.rows.iter().map(|r| r.id.as_str()).collect::<Vec<_>>(), ["b", "a", "c", "d"]);        assert_eq!(b.ordered(true).iter().map(|r| r.id.as_str()).collect::<Vec<_>>(), ["b", "d", "a", "c"]);        assert_eq!(b.ordered(false).iter().map(|r| r.id.as_str()).collect::<Vec<_>>(), ["b", "d", "a"]);    }    #[test]    fn a_one_time_link_is_masked_and_marked() {        let s = shown("https://club.example/login?token=Zx81kQpLm2&next=/home");        assert!(s.once);        assert_eq!(s.shown, "https://club.example/login?token=Zx•••&next=%2Fhome");        let s = shown("https://mail.example/magic/AbCdEfGh12345678XyZ");        assert!(s.once);        assert_eq!(s.shown, "https://mail.example/magic/Ab•••");        let s = shown("https://club.example/login?next=/home");        assert!(!s.once, "a site's own sign-in page is not a one-time link");        assert_eq!(s.shown, "https://club.example/login?next=%2Fhome");        assert!(shown("https://club.example/verify/AbCdEfGh12345678XyZ").once, "a code in the path");        let s = shown("https://news.example/story/42?ref=home");        assert!(!s.once);        assert_eq!(s.shown, "https://news.example/story/42?ref=home");    }    #[test]    fn a_link_that_leaves_the_web_is_named_and_the_dangerous_ones_refused() {        assert_eq!(exit("https://club.example/"), Exit::Inside);        assert_eq!(exit("tel:+91%2098765%2043210"), Exit::Call { number: "+91 98765 43210".into() });        assert_eq!(exit("mailto:desk@club.example"), Exit::Mail { address: "desk@club.example".into() });        assert_eq!(exit("maps://?q=Hampi"), Exit::Map);        assert_eq!(exit("itms-apps://apps.apple.com/app/id1"), Exit::Store);        assert_eq!(exit("whatsapp://send?text=hi"), Exit::App);        for bad in ["javascript:alert(1)", "file:///etc/passwd", "data:text/html,hi", "not a link"] {            assert_eq!(exit(bad), Exit::Refused, "{bad}");        }    }    #[test]    fn switching_keeps_the_most_recent_pages_up_to_the_budget() {        let mut recent = Vec::new();        for id in ["a", "b", "c"] {            live(&mut recent, Some(id), 3);        }        assert_eq!(recent, ["c", "b", "a"]);        let (keep, let_go) = live(&mut recent, Some("a"), 3);        assert_eq!(keep, ["a", "c", "b"], "coming back moves it to the front; nothing let go");        assert!(let_go.is_empty());        let (keep, let_go) = live(&mut recent, Some("d"), 3);        assert_eq!((keep, let_go), (vec!["d".into(), "a".into(), "c".into()], vec!["b".to_string()]));        let (keep, let_go) = live(&mut recent, None, 1);        assert_eq!((keep, let_go), (vec!["d".to_string()], vec!["a".to_string(), "c".to_string()]), "a memory warning trims");    }    #[test]    fn a_page_keeps_its_title_and_state_only_while_it_stays_signed_in() {        let mut b = book();        b.rows[0].sign_in_once = true;        b.leave_titled("a", Some("https://mail.example/inbox"), Some(" Inbox (4) ")).unwrap();        b.keep_state("a", Some("c3RhdGU=")).unwrap();        assert_eq!(b.rows[0].title.as_deref(), Some("Inbox (4)"));        assert_eq!(b.rows[0].state.as_deref(), Some("c3RhdGU="));        assert!(!b.rows[0].sign_in_once, "used: no longer Sign in once");        b.leave_titled("b", Some("https://club.example/x"), Some("X")).unwrap();        b.keep_state("b", Some("c3RhdGU=")).unwrap();        assert_eq!((b.rows[1].title.clone(), b.rows[1].state.clone()), (None, None), "a site that forgets keeps nothing");        b.leave("a", None).unwrap();        assert_eq!((b.rows[0].last.clone(), b.rows[0].title.clone(), b.rows[0].state.clone()), (None, None, None), "signed out");    }    #[test]    fn trackers_are_blocked_third_party_only() {        assert!(trackers().len() > 50);        assert!(blocked("https://news.example/a", "https://www.google-analytics.com/collect?v=2"));        assert!(blocked("https://news.example/a", "https://securepubads.g.doubleclick.net/tag/js/gpt.js"));        assert!(!blocked("https://news.example/a", "https://cdn.news.example/app.js"), "the site's own");        assert!(!blocked("https://news.example/a", "https://fonts.example.org/a.woff2"), "not on the list");        assert!(!blocked("https://www.doubleclick.net/", "https://ad.doubleclick.net/x"), "first-party on its own site");        assert!(!blocked("https://news.example/a", "https://notdoubleclick.net/x"), "a name that only ends the same");        assert_eq!(site_of("shop.example.co.uk"), "example.co.uk");        assert_eq!(site_of("a.b.mail.example"), "mail.example");        assert_eq!(site_of("10.0.2.2"), "10.0.2.2");        let rules = content_rules();        assert_eq!(rules.as_array().unwrap().len(), trackers().len());        assert_eq!(rules[0]["action"]["type"], "block");        assert_eq!(rules[0]["trigger"]["load-type"][0], "third-party");        let filter = rules.as_array().unwrap().iter().find(|r| r["trigger"]["url-filter"].as_str().unwrap().contains("doubleclick")).unwrap();        assert_eq!(filter["trigger"]["url-filter"], "^https?://([^/]*\\.)?doubleclick\\.net[:/]");    }    #[test]    fn an_old_book_reads_with_the_new_fields_at_their_defaults() {        let old = r#"{"rows":[{"id":"a","label":"Club","home":"https://club.example/","stay":true,"hidden":false}]}"#;        let b: Book = serde_json::from_str(old).unwrap();        assert!(b.rows[0].trackers, "trackers blocked unless turned off");        assert!(!b.rows[0].pinned);        assert_eq!(b.settings.engine, "duckduckgo");        assert!(b.settings.login_ask);        let again = serde_json::to_string(&b).unwrap();        assert_eq!(again, old, "nothing new is written for defaults");    }}