//! SITES (assets/design/chat/SITES.md): Comms' list of sessions, each a label //! and a home address with its own walled-off sign-ins on the phone. This is //! the rows' book and how it is sealed. It lives only on the phone: it is never //! synced, never sent to the server, and never written into an export. The //! sign-ins themselves are the phone's (WebKit's store named by the row's id); //! the core holds none. //! //! The book is sealed with AES-256-GCM under a key the phone keeps in its own //! keychain, on this device only (`SitesKey` on iPhone), derived by HKDF. A //! file that key cannot open is never read as empty: the caller sets it aside. use aes_gcm::aead::{Aead, KeyInit, Payload}; use aes_gcm::{Aes256Gcm, Key, Nonce}; use hkdf::Hkdf; use serde::{Deserialize, Serialize}; use sha2::Sha256; use zeroize::Zeroizing; const PREFIX: &[u8] = b"cotton-sites-1:"; const INFO: &[u8] = b"cotton sites book v1"; const NONCE_LEN: usize = 12; /// One session: a label, its home, whether its sign-ins stay after it closes, and whether it is hidden. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Row { /// A UUID: the phone names the row's website store by it. pub id: String, pub label: String, /// Always a whole `http(s)` address (`home_of`). pub home: String, pub stay: bool, pub hidden: bool, /// SITES 4: the one address the row was last on, so it reopens there after the phone let its page go. Kept only /// while Stay signed in is on; replaced each time, never a list; cleared by Sign out and by a new home. #[serde(default, skip_serializing_if = "Option::is_none")] pub last: Option, /// Cotton Sites (assets/design/sites): kept on top of the list, in the book's order among the pinned. #[serde(default, skip_serializing_if = "is_false")] pub pinned: bool, /// Trackers blocked on this site (question 7: on unless he turns it off for this one site). #[serde(default = "yes", skip_serializing_if = "is_true")] pub trackers: bool, /// The id of the Secrets login this site fills with (`sites.login`); never the login itself. #[serde(default, skip_serializing_if = "Option::is_none")] pub login: Option, /// The title of the page at `last`, for the list's second line ("mail.example ยท Inbox (4)"). #[serde(default, skip_serializing_if = "Option::is_none")] pub title: Option, /// The page's saved state (iPhone `interactionState`, Android `saveState`), base64, on this phone only, so a page /// the system took back returns with its history and scroll. Kept only with `last`. #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option, /// Came from Comms or another phone without its sign-in: the list says "Sign in once" until he has used it. #[serde(default, skip_serializing_if = "is_false")] pub sign_in_once: bool, /// A link chosen into this site from the iPhone's share sheet, which cannot open the app (question 10): it waits, /// unopened, and loads when he next opens the site. One at a time; the newest wins. On this phone only. #[serde(default, skip_serializing_if = "Option::is_none")] pub waiting: Option, /// Read from a book an earlier build wrote (SYNC 3's stamp), never written again: a stamped row had synced. #[serde(default, skip_serializing)] pub changed_at: i64, /// The name this phone's website store goes by, when it is not the row's key: a site an earlier build kept only on /// this phone, written into the list under a fresh key, keeps its sign-in under the store it had. #[serde(default, skip_serializing_if = "Option::is_none")] pub store: Option, } fn yes() -> bool { true } fn is_true(b: &bool) -> bool { *b } fn is_zero(n: &u32) -> bool { *n == 0 } fn is_false(b: &bool) -> bool { !*b } impl Row { /// Where the row opens: where it was last, else its home. pub fn reopen(&self) -> &str { self.last.as_deref().unwrap_or(&self.home) } } /// Every row, in his order (the order added until he arranges them), and Sites' own settings. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Book { pub rows: Vec, #[serde(default, skip_serializing_if = "Settings::is_default")] pub settings: Settings, } /// Cotton Sites' settings (You): kept in the book, on this phone. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Settings { /// The engine a search line uses (`app::Engine` id). #[serde(default = "default_engine")] pub engine: String, /// Hidden sites hide a minute after he leaves, not the moment (question 5's setting). #[serde(default)] pub hide_after_minute: bool, /// Trackers blocked for new sites. #[serde(default = "yes")] pub trackers: bool, /// Ask for Face ID before filling a login. #[serde(default = "yes")] pub login_ask: bool, /// Read from books written before 26 Nov 2026 and no longer used: each row's `changed_at` decides now. #[serde(default, skip_serializing_if = "is_false")] pub synced: bool, /// The first Close and forget has said once that forgetting signs him out. #[serde(default)] pub told_forget: bool, } fn default_engine() -> String { "duckduckgo".into() } impl Default for Settings { fn default() -> Self { Settings { engine: default_engine(), hide_after_minute: false, trackers: true, login_ask: true, synced: false, told_forget: false } } } impl Settings { fn is_default(&self) -> bool { *self == Settings::default() } } /// Why an address or a row is refused: the line key under `app.sites.`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Refused { NotAnAddress, NoRow, /// Cotton Sites: `sites.set` with a name or value it does not know. NotASetting, } impl Refused { pub fn line(self) -> &'static str { match self { Refused::NotAnAddress => "app.sites.refused.address", Refused::NoRow => "app.sites.refused.row", Refused::NotASetting => "app.sites.refused.row", } } } /// What he typed as the address it means: "claude.ai" is `https://claude.ai/`. /// Text that is not an address (words with spaces, no dot in the host, another /// scheme) is refused: Sites never turns it into a search. pub fn home_of(text: &str) -> Result { let text = text.trim(); if text.is_empty() || text.chars().any(char::is_whitespace) { return Err(Refused::NotAnAddress); } let whole = if text.contains("://") { text.to_string() } else { format!("https://{text}") }; let url = url::Url::parse(&whole).map_err(|_| Refused::NotAnAddress)?; if !matches!(url.scheme(), "http" | "https") { return Err(Refused::NotAnAddress); } let host = url.host_str().ok_or(Refused::NotAnAddress)?; let is_ip = matches!(url.host(), Some(url::Host::Ipv4(_) | url::Host::Ipv6(_))); if !is_ip && host != "localhost" && (!host.contains('.') || host.starts_with('.') || host.ends_with('.')) { return Err(Refused::NotAnAddress); } Ok(url.to_string()) } /// A home's host as the list shows it: `www.` dropped. pub fn host_of(home: &str) -> String { let host = url::Url::parse(home).ok().and_then(|u| u.host_str().map(str::to_string)).unwrap_or_default(); host.strip_prefix("www.").map(str::to_string).unwrap_or(host) } /// A label as kept: trimmed; refused when nothing is left (the home's domain stands for it). fn label_of(text: &str) -> Result { let label = text.trim(); if label.is_empty() { Err(()) } else { Ok(label.to_string()) } } /// The UUID a row's website store is named by on iPhone (`WKWebsiteDataStore(forIdentifier:)`): the row's id /// when it is one, else a version-4-shaped UUID from its SHA-256, so the same row always names the same store. pub fn store_uuid(id: &str) -> String { if id.len() == 36 && id.chars().filter(|c| *c == '-').count() == 4 && id.chars().all(|c| c == '-' || c.is_ascii_hexdigit()) { return id.to_ascii_lowercase(); } use sha2::Digest; let mut b: [u8; 16] = Sha256::digest(id.as_bytes())[..16].try_into().expect("16 bytes"); b[6] = (b[6] & 0x0f) | 0x40; b[8] = (b[8] & 0x3f) | 0x80; let h: String = b.iter().map(|x| format!("{x:02x}")).collect(); format!("{}-{}-{}-{}-{}", &h[0..8], &h[8..12], &h[12..16], &h[16..20], &h[20..32]) } impl Book { /// The rows drawn now: the hidden ones only once Face ID has passed (`unlocked`). pub fn shown(&self, unlocked: bool) -> impl Iterator { self.rows.iter().filter(move |r| unlocked || !r.hidden) } /// The rows a tapped link may open in, never a hidden one: the rows at the link's own site first (a sign-in link /// for the club offers the club's sessions on top), the rest after, each group in the book's order. pub fn for_link(&self, url: &str) -> Vec<&Row> { let site = host_of(url); let (mut at, rest): (Vec<&Row>, Vec<&Row>) = self.shown(false).partition(|r| !site.is_empty() && host_of(&r.home) == site); at.extend(rest); at } /// A new row; an empty label takes the home's domain. pub fn add(&mut self, id: String, label: &str, home: &str, stay: bool, hidden: bool) -> Result<&Row, Refused> { let home = home_of(home)?; let label = label_of(label).unwrap_or_else(|_| host_of(&home)); let row = Row { id, label, home, stay, hidden, last: None, pinned: false, trackers: self.settings.trackers, login: None, title: None, state: None, sign_in_once: false, waiting: None, changed_at: 0, store: None }; self.rows.push(row); Ok(self.rows.last().expect("pushed")) } /// Change what is given; nothing changes when any part is refused. pub fn edit(&mut self, id: &str, label: Option<&str>, home: Option<&str>, stay: Option, hidden: Option) -> Result<&Row, Refused> { let home = home.map(home_of).transpose()?; let row = self.rows.iter_mut().find(|r| r.id == id).ok_or(Refused::NoRow)?; if let Some(home) = home { // A new home: the row opens there, not where the old one was left. row.home = home; row.last = None; row.title = None; row.state = None; } if let Some(label) = label { // An emptied label takes the home's domain, as a new row's does. row.label = label_of(label).unwrap_or_else(|_| host_of(&row.home)); } if let Some(stay) = stay { row.stay = stay; if !stay { row.last = None; row.title = None; row.state = None; } } if let Some(hidden) = hidden { row.hidden = hidden; } Ok(row) } /// Where a row's page is now (`Some`), or that it was signed out (`None`): the one last address, replaced. A row /// with Stay signed in off keeps none; an address that is not the web's is refused. pub fn leave(&mut self, id: &str, url: Option<&str>) -> Result<(), Refused> { self.leave_titled(id, url, None) } /// `leave`, with the page's title for the list's second line. Signing out (`None`) clears the title and the saved /// state with the address; a new address drops a saved state that belonged to the old one. pub fn leave_titled(&mut self, id: &str, url: Option<&str>, title: Option<&str>) -> Result<(), Refused> { let url = url.map(home_of).transpose()?; let row = self.rows.iter_mut().find(|r| r.id == id).ok_or(Refused::NoRow)?; if url.is_some() { row.sign_in_once = false; } let kept = if row.stay { url } else { None }; if kept.is_none() { row.title = None; row.state = None; } else { row.title = title.map(str::trim).filter(|t| !t.is_empty()).map(|t| t.chars().take(80).collect()); } row.last = kept; Ok(()) } /// Keep a page's saved state (base64), only where Stay signed in keeps its address. pub fn keep_state(&mut self, id: &str, blob: Option<&str>) -> Result<(), Refused> { let row = self.rows.iter_mut().find(|r| r.id == id).ok_or(Refused::NoRow)?; row.state = if row.stay { blob.filter(|b| !b.is_empty()).map(str::to_string) } else { None }; Ok(()) } /// The rows as the list draws them: the pinned first, then the rest, each group in his order. pub fn ordered(&self, unlocked: bool) -> Vec<&Row> { let (mut pinned, rest): (Vec<&Row>, Vec<&Row>) = self.shown(unlocked).partition(|r| r.pinned); pinned.extend(rest); pinned } /// His order: the ids given first, in that order, then any others where they were; `pinned` are the pinned ones. pub fn arrange(&mut self, order: &[String], pinned: &[String]) { let mut rows = std::mem::take(&mut self.rows); let mut next = Vec::with_capacity(rows.len()); for id in order { if let Some(i) = rows.iter().position(|r| &r.id == id) { next.push(rows.remove(i)); } } next.extend(rows); for row in &mut next { row.pinned = pinned.contains(&row.id); } self.rows = next; } /// Comms' list moving in (CONTRACT `sites.move.in`): every row it holds that this book does not, by id, in its /// order, after this book's own; hidden stays hidden. Sign-ins never move (owner, 25 Nov 2026), so each arrives /// at its home, without its last page, its title or its saved state, saying "Sign in once". Returns how many came. pub fn take_in(&mut self, from: &Book) -> usize { let mut came = 0; for row in &from.rows { if self.rows.iter().any(|r| r.id == row.id) { continue; } let mut row = row.clone(); row.last = None; row.title = None; row.state = None; row.login = None; row.sign_in_once = true; self.rows.push(row); came += 1; } came } /// The other rows at a home's site: a new row there "starts empty, with its own sign-in". pub fn at_site(&self, home: &str) -> Vec<&Row> { let site = host_of(home); self.rows.iter().filter(|r| !site.is_empty() && host_of(&r.home) == site).collect() } pub fn delete(&mut self, id: &str) -> Result<(), Refused> { let before = self.rows.len(); self.rows.retain(|r| r.id != id); if self.rows.len() == before { Err(Refused::NoRow) } else { Ok(()) } } /// The book sealed under the phone's Sites key, with a fresh nonce. pub fn seal(&self, phone_key: &[u8; 32], nonce: &[u8; NONCE_LEN]) -> Option> { seal_value(self, phone_key, nonce) } /// The book from its sealed bytes; `None` when this key cannot open them. pub fn open(phone_key: &[u8; 32], bytes: &[u8]) -> Option { open_value(phone_key, bytes) } } /// What Sites keeps on this phone beside the synced rows (SYNC-DESIGN.md, design 2): one sealed file in each /// database's own folder, keyed by row key, holding nothing that ever leaves the phone. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Local { /// Each site's own: its last page and title, saved state, Sign in once, a waiting link, the store it signs in /// with (`store`, when not its key's). A site an earlier build kept only on this phone is held here whole until it /// is a row of the list (`only`). #[serde(default)] pub entries: std::collections::BTreeMap, /// Sites an earlier build kept only on this phone (the switch, removed 27 Nov 2026), at their place in the list: /// each is made a row and leaves here in the same turn (a site is here or a row, never both). Nothing new is ever /// put here. #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub only: std::collections::BTreeMap, #[serde(default)] pub settings: Settings, /// Removed here: the moment (ms) the Undo ends and the row is erased. #[serde(default)] pub erasing: std::collections::BTreeMap, /// Whether the old books were taken in for this database (once, after a caught-up pull). #[serde(default)] pub migrated: bool, /// Each synced site's name and address as this copy last held it, by key: drawn greyed while a copy made again /// is still loading (review of SITES ROWS 2, item 8), so the list is never only an Add. #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub known: std::collections::BTreeMap, /// Keys in `known` whose row is hidden: never drawn greyed while loading unless the hidden sites show, exactly as /// the loaded list draws them. #[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")] pub known_hidden: std::collections::BTreeSet, /// Whether `known_hidden` holds the hidden flag of every key in `known` (false in a file an older build wrote, until /// this copy fills it): while false, nothing from `known` is drawn waiting, so a hidden name never shows. #[serde(default, skip_serializing_if = "is_false")] pub known_hidden_filled: bool, /// Times the old book could not be read from disk: said (`book_stuck`) after three. #[serde(default, skip_serializing_if = "is_zero")] pub book_tries: u32, /// Whether he was told the old book would not open with this phone's key (said once, `sites.home` `book_stuck`). #[serde(default, skip_serializing_if = "is_false")] pub book_stuck: bool, /// Sites removed here, by key: a carried file taken in again (the app killed between the merged write and the /// carried file's removal) never brings one back (review of SITES ROWS 6, item 5). #[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")] pub gone: std::collections::BTreeSet, } impl Local { pub fn seal(&self, phone_key: &[u8; 32], nonce: &[u8; NONCE_LEN]) -> Option> { seal_value(self, phone_key, nonce) } pub fn open(phone_key: &[u8; 32], bytes: &[u8]) -> Option { open_value(phone_key, bytes) } } /// The gap a place is given past the last, and the closest two neighbours may come before the list is placed again. pub const PLACE_GAP: f64 = 1024.0; pub const PLACE_CLOSEST: f64 = 1e-6; /// The places to write so the list reads in `order`, from the places the rows hold now (`held`; a new row holds /// none). The longest run already in order keeps its places and every other row goes between its kept neighbours, /// so a move writes the one row that moved. When neighbours would come closer than [`PLACE_CLOSEST`], every row is /// placed again, [`PLACE_GAP`] apart. Answers only the places that change. pub fn places(order: &[String], held: &std::collections::BTreeMap) -> std::collections::BTreeMap { let had: Vec> = order.iter().map(|k| held.get(k).copied().filter(|p| p.is_finite())).collect(); let mut tails: Vec = Vec::new(); let mut back: Vec> = vec![None; order.len()]; for (i, p) in had.iter().enumerate() { let Some(p) = p else { continue }; let at = tails.partition_point(|&t| had[t].is_some_and(|q| q < *p)); back[i] = at.checked_sub(1).map(|j| tails[j]); if at == tails.len() { tails.push(i); } else { tails[at] = i; } } let mut kept = vec![false; order.len()]; let mut at = tails.last().copied(); while let Some(i) = at { kept[i] = true; at = back[i]; } let mut placed: Vec = vec![0.0; order.len()]; let mut tight = false; let mut i = 0; while i < order.len() { if kept[i] { placed[i] = had[i].unwrap_or_default(); i += 1; continue; } let start = i; while i < order.len() && !kept[i] { i += 1; } let low = start.checked_sub(1).map(|j| placed[j]); let high = had.get(i).copied().flatten().filter(|_| i < order.len()); let n = (i - start) as f64; for (step, slot) in placed[start..i].iter_mut().enumerate() { let step = step as f64 + 1.0; *slot = match (low, high) { (Some(l), Some(h)) => l + (h - l) * step / (n + 1.0), (Some(l), None) => l + PLACE_GAP * step, (None, Some(h)) => h - PLACE_GAP * (n + 1.0 - step), (None, None) => PLACE_GAP * step, }; } if let (Some(l), Some(h)) = (low, high) { tight |= (h - l) / (n + 1.0) < PLACE_CLOSEST; } } if tight { return order.iter().enumerate().map(|(i, k)| (k.clone(), PLACE_GAP * (i as f64 + 1.0))).collect(); } order.iter().zip(placed).filter(|(k, p)| held.get(*k) != Some(p)).map(|(k, p)| (k.clone(), p)).collect() } /// Sites shown twice: the same address under the same name (trimmed, any case), as two phones that added the same /// site before either synced leave it. Each group in the order given; only the rows given are ever named. pub fn twins<'a>(rows: &[&'a Row]) -> Vec> { let same = |r: &Row| (r.label.trim().to_lowercase(), r.home.trim_end_matches('/').to_lowercase()); let mut groups: Vec> = Vec::new(); for row in rows { match groups.iter_mut().find(|g| same(g[0]) == same(row)) { Some(g) => g.push(row), None => groups.push(vec![row]), } } groups.retain(|g| g.len() > 1); groups } fn seal_value(value: &T, phone_key: &[u8; 32], nonce: &[u8; NONCE_LEN]) -> Option> { let plain = Zeroizing::new(serde_json::to_vec(value).ok()?); let key = book_key(phone_key)?; let cipher = Aes256Gcm::new(Key::::from_slice(key.as_slice())); let ct = cipher.encrypt(Nonce::from_slice(nonce), Payload { msg: plain.as_slice(), aad: PREFIX }).ok()?; Some([PREFIX, nonce.as_slice(), &ct].concat()) } fn open_value(phone_key: &[u8; 32], bytes: &[u8]) -> Option { let rest = bytes.strip_prefix(PREFIX)?; if rest.len() < NONCE_LEN + 16 { return None; } let (nonce, ct) = rest.split_at(NONCE_LEN); let key = book_key(phone_key)?; let cipher = Aes256Gcm::new(Key::::from_slice(key.as_slice())); let plain = Zeroizing::new(cipher.decrypt(Nonce::from_slice(nonce), Payload { msg: ct, aad: PREFIX }).ok()?); serde_json::from_slice(&plain).ok() } #[path = "sites_app.rs"] pub mod app; fn book_key(phone_key: &[u8; 32]) -> Option> { let mut key = Zeroizing::new([0u8; 32]); Hkdf::::new(None, phone_key).expand(INFO, key.as_mut_slice()).ok()?; Some(key) } #[cfg(test)] mod tests { use super::*; fn order(held: &std::collections::BTreeMap) -> Vec { let mut keys: Vec<(&String, &f64)> = held.iter().collect(); keys.sort_by(|a, b| a.1.total_cmp(b.1).then(a.0.cmp(b.0))); keys.into_iter().map(|(k, _)| k.clone()).collect() } // RULE (SITES ROWS, 26 Nov 2026): a move writes the one site that moved; halving down to the closest two places // the whole list again, and the order read back from the places alone is always the order he made. #[test] fn a_move_writes_one_place_and_fifty_halvings_keep_the_order() { let mut held = std::collections::BTreeMap::new(); let mut list: Vec = ["a", "b", "c", "d"].iter().map(|s| s.to_string()).collect(); for (k, p) in places(&list, &held) { held.insert(k, p); } assert_eq!(order(&held), list); list = vec!["a".into(), "d".into(), "b".into(), "c".into()]; let moved = places(&list, &held); assert_eq!(moved.keys().collect::>(), ["d"], "{moved:?}"); let mut again = 0; for n in 0..60 { let m = if n % 2 == 0 { list.pop().unwrap() } else { list.remove(2) }; list.insert(1, m); let changed = places(&list, &held); if changed.len() > 1 { again += 1; } held.extend(changed); assert_eq!(order(&held), list, "move {n}"); } assert!(again >= 1, "the halvings came close enough to place the list again"); } #[test] fn a_new_site_goes_after_the_last_and_a_new_first_before_the_first() { let held: std::collections::BTreeMap = [("a".to_string(), 1024.0), ("b".to_string(), 2048.0)].into(); assert_eq!(places(&["a".into(), "b".into(), "c".into()], &held), [("c".to_string(), 3072.0)].into()); assert_eq!(places(&["z".into(), "a".into(), "b".into()], &held), [("z".to_string(), 0.0)].into()); } #[test] fn twins_are_the_same_name_at_the_same_address_only() { let mut book = Book::default(); book.add("a".into(), "Club", "club.example", true, false).unwrap(); book.add("b".into(), " club ", "https://club.example", true, false).unwrap(); book.add("c".into(), "Club two", "club.example", true, false).unwrap(); let rows: Vec<&Row> = book.rows.iter().collect(); let found = twins(&rows); assert_eq!(found.len(), 1); assert_eq!(found[0].iter().map(|r| r.id.as_str()).collect::>(), ["a", "b"]); } #[test] fn a_row_reopens_where_it_was_left_and_only_there() { let mut book = Book::default(); book.add("a".into(), "Club", "club.example", true, false).unwrap(); book.add("b".into(), "Bank", "bank.example", false, false).unwrap(); assert_eq!(book.rows[0].reopen(), "https://club.example/"); book.leave("a", Some("https://club.example/code?wait=1")).unwrap(); book.leave("a", Some("https://club.example/inbox")).unwrap(); assert_eq!(book.rows[0].reopen(), "https://club.example/inbox", "replaced, never a list"); book.leave("b", Some("https://bank.example/accounts")).unwrap(); assert_eq!(book.rows[1].last, None, "Stay signed in off keeps nothing"); assert_eq!(book.leave("a", Some("about:blank")), Err(Refused::NotAnAddress)); assert_eq!(book.leave("nobody", Some("https://club.example/")), Err(Refused::NoRow)); book.leave("a", None).unwrap(); assert_eq!(book.rows[0].reopen(), "https://club.example/", "signed out: home again"); book.leave("a", Some("https://club.example/inbox")).unwrap(); book.edit("a", None, Some("club.example/start"), None, None).unwrap(); assert_eq!(book.rows[0].reopen(), "https://club.example/start", "a new home clears it"); book.leave("a", Some("https://club.example/inbox")).unwrap(); book.edit("a", None, None, Some(false), None).unwrap(); assert_eq!(book.rows[0].last, None, "turning Stay signed in off clears it"); } #[test] fn a_links_own_site_comes_first_and_hidden_never() { let mut book = Book::default(); book.add("a".into(), "Shop", "shop.example", true, false).unwrap(); book.add("b".into(), "Club", "https://www.club.example/home", true, false).unwrap(); book.add("c".into(), "Club 2", "club.example", true, true).unwrap(); book.add("d".into(), "Club work", "club.example", true, false).unwrap(); let ids = |url: &str| book.for_link(url).iter().map(|r| r.id.clone()).collect::>(); assert_eq!(ids("https://club.example/in?t=1"), ["b", "d", "a"]); assert_eq!(ids("https://elsewhere.example/"), ["a", "b", "d"]); assert_eq!(ids("not a link"), ["a", "b", "d"]); } #[test] fn a_typed_address_is_written_whole_and_words_are_refused() { assert_eq!(home_of("claude.ai"), Ok("https://claude.ai/".into())); assert_eq!(home_of(" https://mail.example.com/inbox?x=1 "), Ok("https://mail.example.com/inbox?x=1".into())); assert_eq!(home_of("http://192.168.1.4:8080"), Ok("http://192.168.1.4:8080/".into())); assert_eq!(home_of("localhost:3000"), Ok("https://localhost:3000/".into())); for words in ["", "best pizza", "pizza", "ftp://example.com", "javascript:alert(1)", "file:///etc/passwd", ".com"] { assert_eq!(home_of(words), Err(Refused::NotAnAddress), "{words}"); } } #[test] fn the_host_drops_www() { assert_eq!(host_of("https://www.example.com/a"), "example.com"); assert_eq!(host_of("https://claude.ai/"), "claude.ai"); } #[test] fn the_same_site_twice_is_two_rows_and_hidden_ones_wait_for_the_unlock() { let mut book = Book::default(); book.add("a".into(), "Work Claude", "claude.ai", true, false).unwrap(); book.add("b".into(), "Home Claude", "claude.ai", false, false).unwrap(); book.edit("b", None, None, None, Some(true)).unwrap(); assert_eq!(book.shown(false).map(|r| r.id.as_str()).collect::>(), ["a"]); assert_eq!(book.shown(true).map(|r| r.id.as_str()).collect::>(), ["a", "b"]); assert_eq!(book.add("c".into(), " ", "https://www.claude.ai/x", true, true).unwrap().label, "claude.ai", "an empty label takes the domain"); // A refused part changes nothing. assert_eq!(book.edit("a", Some("New"), Some("not an address"), None, None).err(), Some(Refused::NotAnAddress)); assert_eq!(book.rows[0].label, "Work Claude"); assert_eq!(book.delete("zz"), Err(Refused::NoRow)); book.delete("a").unwrap(); assert_eq!(book.rows.len(), 2); } #[test] fn the_book_opens_only_under_its_own_key_and_holds_no_plain_label() { let mut book = Book::default(); book.add("a".into(), "Secret bank", "bank.example", true, false).unwrap(); let key = [7u8; 32]; let sealed = book.seal(&key, &[1u8; NONCE_LEN]).unwrap(); assert!(!sealed.windows(6).any(|w| w == b"Secret"), "the label is sealed"); assert!(!sealed.windows(4).any(|w| w == b"bank"), "the home is sealed"); assert_eq!(Book::open(&key, &sealed), Some(book)); assert_eq!(Book::open(&[8u8; 32], &sealed), None); assert_eq!(Book::open(&key, &sealed[..20]), None); } }