//! Cotton Sites' own calls (assets/design/sites/CONTRACT.md). Every address is invented.use serde_json::{json, Value};usecrate::handle::CottonHandle;const KEY: &str = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";fn ask(handle: &CottonHandle, method: &str, mut request: Value) -> Value { request["key"] = json!(KEY);crate::methods::dispatch(handle, method, &request).unwrap_or_else(|e| panic!("{method}: {} {}", e.code, e.message))}fn refused(handle: &CottonHandle, method: &str, mut request: Value) -> (String, String) { request["key"] = json!(KEY);let e = crate::methods::dispatch(handle, method, &request).expect_err(method); (e.code, e.message)}fn phone(dir: &tempfile::TempDir) -> CottonHandle {crate::phone::chat_app::mail::tests::comms(dir, cotton_core::flavor::Flavor::Dev)}fn id(answer: &Value) -> String { answer["row"]["id"].as_str().unwrap().to_string()}fn labels(rows: &Value) -> Vec<String> { rows.as_array().unwrap().iter().map(|r| r["label"].as_str().unwrap().to_string()).collect()}#[test]fn the_list_opens_first_run_then_his_sites_pinned_first_and_hidden_behind_the_unlock() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir);let empty = ask(&h, "sites.home", json!({})); assert_eq!(empty["title"], "Sites"); assert_eq!(empty["search"]["line"], "Search, or type an address"); assert_eq!(empty["first"]["line"], "Each site here keeps its own sign-in."); assert_eq!(empty["quick"], json!({ "label": "Quick visit", "line": "Keeps nothing at all" })); assert_eq!(empty["hidden"]["line"], "Face ID to show");let work = id(&ask(&h, "sites.add", json!({ "label": "Work mail", "home": "mail.example" })));let club = id(&ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example", "stay": false })));let bank = id(&ask(&h, "sites.add", json!({ "label": "Bank", "home": "ledgerbank.example", "hidden": true })));let home = id(&ask(&h, "sites.add", json!({ "label": "Personal mail", "home": "mail.example", "pinned": true }))); ask(&h, "sites.left", json!({ "id": work, "url": "https://mail.example/inbox", "title": "Inbox (4)" }));let list = ask(&h, "sites.home", json!({})); assert!(list.get("first").is_none()); assert_eq!(labels(&list["rows"]), ["Personal mail", "Work mail", "Club"], "pinned first; hidden not at all");let rows = list["rows"].as_array().unwrap(); assert_eq!(rows[1]["line"], "mail.example · Inbox (4)"); assert_eq!(rows[1]["letter"], "W"); assert_eq!(rows[2]["line"], "club.example · forgets when closed"); assert_eq!(list["hidden"]["locked"], true); assert!(list["hidden"].get("rows").is_none());let shown = ask(&h, "sites.home", json!({ "unlocked": true })); assert_eq!(shown["hidden"]["label"], "Hidden, showing"); assert_eq!(labels(&shown["hidden"]["rows"]), ["Bank"]);let arranged = ask(&h, "sites.arrange", json!({ "order": [club, work], "pinned": [club] })); assert_eq!(arranged["said"], "Arranged"); assert_eq!(labels(&ask(&h, "sites.home", json!({}))["rows"]), ["Club", "Work mail", "Personal mail"]);let _ = (bank, home);}#[test]fn adding_suggests_a_name_and_says_when_the_address_is_already_used() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir);let plan = ask(&h, "sites.add.plan", json!({ "home": "www.mail.example/inbox" })); assert_eq!(plan["home"], "https://www.mail.example/inbox"); assert_eq!(plan["label"], "Mail"); assert!(plan.get("line").is_none()); assert_eq!(ask(&h, "sites.add.plan", json!({ "home": "http://10.0.2.2:8787/" }))["label"], "10.0.2.2:8787", "an address by number is named as written"); assert_eq!(ask(&h, "sites.add.plan", json!({ "home": "http://localhost:3000" }))["label"], "localhost:3000"); ask(&h, "sites.add", json!({ "label": "Work mail", "home": "mail.example" }));let plan = ask(&h, "sites.add.plan", json!({ "home": "mail.example" })); assert_eq!(plan["line"], "This starts empty, with its own sign-in."); assert_eq!(refused(&h, "sites.add.plan", json!({ "home": "best pizza" })), ("not_web".into(), "That isn't a web address.".into()));}#[test]fn the_search_line_reads_on_the_phone_and_matches_only_his_sites() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir); ask(&h, "sites.add", json!({ "label": "Work mail", "home": "mail.example" })); ask(&h, "sites.add", json!({ "label": "Bank", "home": "ledgerbank.example", "hidden": true }));let words = ask(&h, "sites.search", json!({ "q": "trains to pune" })); assert_eq!(words["first"]["kind"], "search"); assert_eq!(words["first"]["label"], "Search for 'trains to pune'"); assert_eq!(words["first"]["line"], "With DuckDuckGo, in a place that keeps nothing"); assert_eq!(words["first"]["url"], "https://duckduckgo.com/?q=trains+to+pune"); assert_eq!(words["none"], "None of your sites match.");let address = ask(&h, "sites.search", json!({ "q": "ledgerbank.example" })); assert_eq!(address["first"]["label"], "Go to ledgerbank.example"); assert_eq!(address["matches"], json!([]), "a hidden site never matches while hidden"); assert_eq!(labels(&ask(&h, "sites.search", json!({ "q": "bank", "unlocked": true }))["matches"]), ["Bank"]); assert_eq!(labels(&ask(&h, "sites.search", json!({ "q": "MAIL" }))["matches"]), ["Work mail"]); assert_eq!(ask(&h, "sites.search", json!({ "q": "" }))["first"]["label"], "Open the copied link"); ask(&h, "sites.set", json!({ "name": "engine", "value": "google" }));let g = ask(&h, "sites.search", json!({ "q": "pizza" })); assert_eq!(g["first"]["url"], "https://www.google.com/search?q=pizza"); assert_eq!(g["first"]["line"], "With Google, in a place that keeps nothing");}#[test]fn the_chooser_puts_the_links_own_site_first_masks_a_one_time_code_and_loads_nothing() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir); ask(&h, "sites.add", json!({ "label": "Shop", "home": "shop.example" })); ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" })); ask(&h, "sites.add", json!({ "label": "Club 2", "home": "club.example", "hidden": true }));let c = ask(&h, "sites.choose", json!({ "url": "https://club.example/login?token=Zx81kQpLm2", "from": "post" })); assert_eq!(c["title"], "Open a link from Post"); assert_eq!(c["shown"], "https://club.example/login?token=Zx•••"); assert_eq!(c["url"], "https://club.example/login?token=Zx81kQpLm2", "the whole link stays for the load"); assert_eq!(c["once"], "This link signs you in. It loads only where you choose, and only once."); assert_eq!(c["at_site"]["label"], "At club.example"); assert_eq!(labels(&c["at_site"]["rows"]), ["Club"]); assert_eq!(labels(&c["others"]["rows"]), ["Shop"]); assert!(c["hidden"].get("rows").is_none()); assert_eq!(c["nothing_yet"], "Nothing loads until you choose.");let plain = ask(&h, "sites.choose", json!({ "url": "https://news.example/a", "unlocked": true })); assert_eq!(plain["title"], "Open this in"); assert!(plain.get("once").is_none()); assert_eq!(labels(&plain["hidden"]["rows"]), ["Club 2"]);let moving = ask(&h, "sites.choose", json!({ "url": "https://club.example/login?token=Zx81kQpLm2", "moving": true })); assert_eq!(moving["once"], "This link may already be used. If the page says so, ask the site for a new one."); assert_eq!(refused(&h, "sites.choose", json!({ "url": "javascript:alert(1)" })).0, "not_web");}#[test]fn opening_from_a_link_says_where_it_came_from_and_a_quick_visit_keeps_nothing() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir);let work = id(&ask(&h, "sites.add", json!({ "label": "Work mail", "home": "mail.example" })));let o = ask(&h, "sites.open", json!({ "id": work, "url": "https://mail.example/m/1", "from": "post" })); assert_eq!(o["arrived"], json!({ "line": "From Post, opened in Work mail.", "wrong": "Wrong place?" })); assert_eq!(o["trackers"], true);let q = ask(&h, "sites.open", json!({ "url": "https://duckduckgo.com/?q=x", "search": true })); assert!(q["store"].as_str().unwrap().starts_with("quick-")); assert_eq!(q["stay"], false); assert_eq!(q["quick"]["strip"], "Search · nothing kept"); assert_eq!(q["quick"]["name_line"], "Gone when you leave");let v = ask(&h, "sites.open", json!({ "url": "news.example", "quick": true })); assert_eq!(v["quick"]["strip"], "Quick visit. Nothing is kept: close it and it's gone.");}#[test]fn switching_keeps_recent_pages_alive_and_a_saved_state_waits_only_where_it_stays_signed_in() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir);let a = id(&ask(&h, "sites.add", json!({ "label": "A", "home": "a.example" })));let b = id(&ask(&h, "sites.add", json!({ "label": "B", "home": "b.example", "stay": false })));let c = id(&ask(&h, "sites.add", json!({ "label": "C", "home": "c.example" }))); ask(&h, "sites.live", json!({ "id": a, "budget": 2 })); ask(&h, "sites.live", json!({ "id": b, "budget": 2 }));let went = ask(&h, "sites.live", json!({ "id": c, "budget": 2 })); assert_eq!(went["keep"], json!([c, b])); assert_eq!(went["let_go"], json!([a])); ask(&h, "sites.left", json!({ "id": a, "url": "https://a.example/deep", "title": "Deep" })); ask(&h, "sites.state", json!({ "id": a, "blob": "c3RhdGU=" })); assert_eq!(ask(&h, "sites.state", json!({ "id": a }))["blob"], "c3RhdGU="); assert_eq!(ask(&h, "sites.open", json!({ "id": a }))["state"], "c3RhdGU="); ask(&h, "sites.state", json!({ "id": b, "blob": "c3RhdGU=" })); assert_eq!(ask(&h, "sites.state", json!({ "id": b }))["blob"], Value::Null, "a site that forgets keeps nothing"); assert_eq!(ask(&h, "sites.close", json!({ "id": a }))["said"], "A closed");let forget = ask(&h, "sites.close", json!({ "id": b })); assert_eq!(forget["ask"]["line"], "Close B? You'll be signed out, and this phone forgets everything the site kept."); assert_eq!(forget["ask"]["yes"], "Close and forget"); assert_eq!(forget["first"], "Sites that forget sign you out each time you close them."); assert!(ask(&h, "sites.forget", json!({ "id": b })).get("first").is_none(), "said once");}#[test]fn leaving_the_web_is_asked_and_a_pages_words_are_headed_by_its_address() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir); assert_eq!(ask(&h, "sites.exit", json!({ "url": "https://club.example/" })), json!({ "inside": true }));let call = ask(&h, "sites.exit", json!({ "url": "tel:+91%2098765%2043210" })); assert_eq!(call, json!({ "kind": "call", "line": "Call +91 98765 43210?", "go": "Call", "stay": "Stay here" })); assert_eq!(ask(&h, "sites.exit", json!({ "url": "maps://?q=Hampi" }))["line"], "This opens Maps, outside Sites."); assert_eq!(ask(&h, "sites.exit", json!({ "url": "mailto:desk@club.example" }))["line"], "Write to desk@club.example in Post?"); assert_eq!(refused(&h, "sites.exit", json!({ "url": "file:///etc/passwd" })), ("refused_link".into(), "Sites doesn't open that kind of link.".into())); assert_eq!(ask(&h, "sites.panel", json!({ "kind": "alert", "url": "https://www.club.example/x" })), json!({ "head": "club.example says", "ok": "OK" })); assert_eq!(ask(&h, "sites.panel", json!({ "kind": "leave", "url": "https://club.example/x" }))["line"], "Anything you typed here may be lost."); assert_eq!(ask(&h, "sites.panel", json!({ "kind": "upload", "url": "https://club.example/x" }))["head"], "Give club.example a file");}#[test]fn a_page_that_cannot_load_says_whose_fault_and_that_the_sign_in_is_safe() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir);let s = id(&ask(&h, "sites.add", json!({ "label": "Shipyard", "home": "shipyard.example" })));let f = ask(&h, "sites.failed", json!({ "id": s, "url": "https://shipyard.example/builds", "offline": false })); assert_eq!(f["title"], "shipyard.example didn't answer"); assert_eq!(f["line"], "Your phone is online, so the site itself may be down or slow. Nothing is lost: Shipyard is still signed in."); assert_eq!(f["when_back"], "Try again when it's back"); assert_eq!(ask(&h, "sites.failed", json!({ "url": "https://x.example/", "offline": true }))["title"], "You're offline");}#[test]fn settings_answer_in_words_and_keep_what_he_sets() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir);let a = id(&ask(&h, "sites.add", json!({ "label": "Work mail", "home": "mail.example" })));let b = id(&ask(&h, "sites.add", json!({ "label": "Bank", "home": "ledgerbank.example", "hidden": true })));let you = ask(&h, "sites.settings", json!({})); assert_eq!(you["card"]["count"], "2 sites");let rows = you["rows"].as_array().unwrap(); assert_eq!(rows[1]["value"], "DuckDuckGo");let engines: Vec<&str> = rows[1]["choices"].as_array().unwrap().iter().map(|e| e["id"].as_str().unwrap()).collect(); assert_eq!(engines.last(), Some(&"google"), "Google last"); assert_eq!(you["shared"][1]["line"], "Assistants never see Sites."); assert_eq!(you["shared"][0]["line"], "Your list, never sign-ins");let after = ask(&h, "sites.set", json!({ "name": "trackers", "value": false })); assert_eq!(after["rows"][4]["line"], "Allowed"); ask(&h, "sites.set", json!({ "name": "hide_after", "value": "minute" })); assert_eq!(ask(&h, "sites.settings", json!({}))["rows"][3]["value"], "minute"); assert_eq!(refused(&h, "sites.set", json!({ "name": "nonsense", "value": 1 })).0, "bad_request");let new = ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" })); assert_eq!(new["row"]["store"], format!("site-{}", id(&new)));let edited = ask(&h, "sites.edit", json!({ "id": a, "pinned": true, "trackers": false })); assert_eq!(edited["said"], "Saved");let st = ask(&h, "sites.storage", json!({ "sizes": { a.clone(): 14_200_000u64, b.clone(): 9_000_000u64 } })); assert_eq!(st["rows"][0], json!({ "id": a, "letter": "W", "label": "Work mail", "size": "14.2 MB" })); assert_eq!(st["rows"].as_array().unwrap().len(), 2, "a hidden site is not listed in Storage"); assert_eq!(st["all"], "Sign out of every site");}#[test]fn an_old_comms_book_still_opens_and_comms_calls_still_answer() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir); ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" }));let list = ask(&h, "sites.list", json!({})); assert_eq!(list["private"]["label"], "Private", "Comms' words are untouched"); assert_eq!(labels(&ask(&h, "sites.home", json!({}))["rows"]), ["Club"]);}/// Comms' list moves to Sites, the list only: each site arrives at its home saying "Sign in once", hidden stays/// hidden, nothing twice; Comms deletes its copy only when told. Here one phone stands for both apps, the second/// book under its own key.#[test]fn the_list_moves_in_from_comms_without_sign_ins_and_comms_lets_go_only_when_told() {let comms_dir = tempfile::tempdir().unwrap();let comms = phone(&comms_dir);let work = id(&ask(&comms, "sites.add", json!({ "label": "Work mail", "home": "mail.example" }))); ask(&comms, "sites.add", json!({ "label": "Bank", "home": "ledgerbank.example", "hidden": true })); ask(&comms, "sites.left", json!({ "id": work, "url": "https://mail.example/inbox", "title": "Inbox (4)" }));const HAND: &str = "ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj8";let out = ask(&comms, "sites.move.out", json!({ "to": HAND })); assert_eq!(out["count"], 2);let sites_dir = tempfile::tempdir().unwrap();let sites = phone(&sites_dir); ask(&sites, "sites.add", json!({ "label": "Club", "home": "club.example" }));let came = ask(&sites, "sites.move.in", json!({ "bytes": out["bytes"], "from_key": HAND })); assert_eq!(came["title"], "Your sites from Comms are here."); assert_eq!(came["count"], "2 sites moved in"); assert_eq!(labels(&came["rows"]), ["Club", "Work mail"], "hidden stays hidden");let moved = &came["rows"][1]; assert_eq!(moved["line"], "Sign in once"); assert_eq!(moved["open"], "https://mail.example/", "at its home: the sign-in did not move"); assert_eq!(labels(&ask(&sites, "sites.home", json!({ "unlocked": true }))["hidden"]["rows"]), ["Bank"]);let again = ask(&sites, "sites.move.in", json!({ "bytes": out["bytes"], "from_key": HAND })); assert_eq!(again["count"], "0 sites moved in", "nothing twice"); assert_eq!(refused(&sites, "sites.move.in", json!({ "bytes": out["bytes"], "from_key": KEY })).0, "unreadable"); assert_eq!(ask(&comms, "sites.list", json!({}))["rows"].as_array().unwrap().len(), 1, "Comms keeps its list until told"); ask(&comms, "sites.move.done", json!({})); assert_eq!(ask(&comms, "sites.list", json!({}))["rows"], json!([])); ask(&sites, "sites.left", json!({ "id": work, "url": "https://mail.example/inbox" })); assert_eq!(ask(&sites, "sites.home", json!({}))["rows"][1]["line"], "mail.example", "used once: no longer Sign in once");}/// Secrets fills the login per site: the logins at the site's address, which other site uses each, the pick kept in/// the row, and the fill only through the Secrets core with the phone's own check. Invented logins only.#[test]fn each_site_fills_its_own_login_from_secrets() {usecrate::phone::passwords::tests::{lent, phone as vault_phone, wrapped};let (_dir, h) = vault_phone(); wrapped(&h);let add = |user: &str, password: &str| {let request = json!({ "kind": "login", "site": "mail.example", "username": user, "fields": { "password": password }, "privateKey": lent() });crate::phone::keys::over(&h.client(), "keys.add", &request).expect("keys.add")["id"].as_str().unwrap().to_string() };let work_login = add("kiran.work@mail.example", "SYNTHETIC-work-1");let home_login = add("kiran@mail.example", "SYNTHETIC-home-1");let work = id(&ask(&h, "sites.add", json!({ "label": "Work mail", "home": "mail.example" })));let home = id(&ask(&h, "sites.add", json!({ "label": "Personal mail", "home": "mail.example" }))); assert_eq!(refused(&h, "sites.fill", json!({ "id": work })), ("no_login".into(), "Pick a login for this site first.".into()));let offered = ask(&h, "sites.logins", json!({ "id": work })); assert_eq!(offered["title"], "Which login is Work mail?");let secrets: Vec<&str> = offered["rows"].as_array().unwrap().iter().map(|r| r["secret"].as_str().unwrap()).collect(); assert!(secrets.contains(&work_login.as_str()) && secrets.contains(&home_login.as_str()), "both logins at mail.example"); assert!(!offered.to_string().contains("SYNTHETIC"), "no password in the list"); ask(&h, "sites.login", json!({ "id": work, "secret": work_login }));let other = ask(&h, "sites.logins", json!({ "id": home }));let used = other["rows"].as_array().unwrap().iter().find(|r| r["secret"] == work_login.as_str()).unwrap(); assert_eq!(used["used_by"], "Used by Work mail"); assert_eq!(refused(&h, "sites.fill", json!({ "id": work })).0, "vault_locked", "never without the phone's own check");let filled = ask(&h, "sites.fill", json!({ "id": work, "privateKey": lent() })); assert_eq!(filled["user"], "kiran.work@mail.example"); assert_eq!(filled["password"], "SYNTHETIC-work-1"); assert_eq!(filled["reason"], "Fill your login for Work mail"); assert_eq!(ask(&h, "sites.home", json!({}))["rows"][0]["login"], work_login.as_str());}/// Save to Words writes a new note with the page's address through the Words core; Words is never opened.#[test]fn a_page_is_saved_to_words_with_its_address() {usecrate::phone::passwords::tests::phone as personal_phone;let (_dir, h) = personal_phone();let saved = ask(&h, "sites.save_to_words", json!({ "url": "https://news.example/story/42", "title": "Rain in Pune", "note": "for the trip", "text": "Showers all week." })); assert_eq!(saved["said"], "Saved to Words");let note = crate::methods::dispatch(&h, "notes.open", &json!({ "id": saved["note"] })).unwrap();let body = note.to_string();for part in ["Rain in Pune", "for the trip", "Showers all week.", "https://news.example/story/42"] { assert!(body.contains(part), "{part}"); } assert_eq!(refused(&h, "sites.save_to_words", json!({ "url": "javascript:alert(1)" })).0, "not_web");}/// A phone on Cotton Sites' own kit, which carries the synced `site` table.fn sites_phone(dir: &tempfile::TempDir) -> CottonHandle {crate::phone::sites::reset_for_tests();let manifest = json!({"genesis": "personal", "flavour": "sites", "name": "Cotton Sites", "databases": "single", "database": "personal", "kit": "sites", });let handle = CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(crate::fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Dev, manifest: Some(manifest), }) .expect("an open core");crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started"); handle}fn synced(h: &CottonHandle) -> Vec<Value> {let listed = crate::phone::sites::table_for_tests(&h.client(), false, "list_records", json!({ "table": "site", "limit": 100 })).unwrap(); listed["records"].as_array().unwrap().iter().filter(|r| r.get("deleted_at").is_none_or(Value::is_null)).map(|r| r["data"].clone()).collect()}/// The list is the sealed `site` rows (SYNC-DESIGN.md): each change goes in, another phone's site comes out saying/// "Sign in once", a removal elsewhere removes it here, and never a sign-in or a last page. Comms' book never syncs.#[test]fn the_list_syncs_through_the_site_table_and_never_a_sign_in() {let dir = tempfile::tempdir().unwrap();let h = sites_phone(&dir);let work = id(&ask(&h, "sites.add", json!({ "label": "Work mail", "home": "mail.example" }))); ask(&h, "sites.left", json!({ "id": work, "url": "https://mail.example/inbox", "title": "Inbox (4)" }));let rows = synced(&h); assert_eq!(rows.len(), 1); assert_eq!(rows[0]["key"], work.as_str()); assert_eq!(rows[0]["label"], "Work mail"); assert_eq!(rows[0]["home"], "https://mail.example/"); assert!(!rows[0].to_string().contains("inbox") && !rows[0].to_string().contains("Inbox"), "never the last page or its title");// Another phone's site arrives.let club = "6b1f4c1e-2f0a-4d6e-9a1b-0c2d3e4f5a6b";crate::phone::sites::table_for_tests(&h.client(), true, "create_record", json!({ "table": "site", "data": { "key": club, "label": "Club", "home": "https://club.example/", "stay": true, "position": 1_000_000 } })).unwrap();let home = ask(&h, "sites.home", json!({})); assert_eq!(labels(&home["rows"]), ["Work mail", "Club"]); assert_eq!(home["rows"][1]["line"], "Sign in once"); assert_eq!(home["rows"][0]["line"], "mail.example · Inbox (4)", "this phone's last page is its own");// Removed on the other phone: gone here.crate::phone::sites::table_for_tests(&h.client(), true, "delete_record", json!({ "table": "site", "id": club })).unwrap(); assert_eq!(labels(&ask(&h, "sites.home", json!({}))["rows"]), ["Work mail"]);}#[test]fn comms_book_never_syncs() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir); ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" })); assert!(crate::phone::sites::table_for_tests(&h.client(), false, "list_records", json!({ "table": "site", "limit": 1 })).is_err(), "Comms' copy holds no site table"); assert_eq!(labels(&ask(&h, "sites.home", json!({}))["rows"]), ["Club"]);}/// A link chosen into a site from the iPhone's share sheet waits there, unopened, and loads once when he opens that/// site (question 10).#[test]fn a_shared_link_waits_in_its_site_until_he_opens_it() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir);let work = id(&ask(&h, "sites.add", json!({ "label": "Work mail", "home": "mail.example" }))); assert_eq!(ask(&h, "sites.wait", json!({ "id": work, "url": "https://mail.example/m/77" }))["said"], "It waits in Work mail until you open it."); assert_eq!(ask(&h, "sites.home", json!({}))["rows"][0]["line"], "A link waits: mail.example");let opened = ask(&h, "sites.open", json!({ "id": work })); assert_eq!(opened["url"], "https://mail.example/m/77"); assert_eq!(opened["from_share"], true); assert_eq!(ask(&h, "sites.open", json!({ "id": work }))["url"], "https://mail.example/", "once"); assert_eq!(refused(&h, "sites.wait", json!({ "id": work, "url": "javascript:x" })).0, "not_web");}/// A phone with no screen lock cannot keep hidden sites hidden: they show, and the list says why (Android).#[test]fn with_no_screen_lock_hidden_sites_show_and_say_why() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir); ask(&h, "sites.add", json!({ "label": "Bank", "home": "ledgerbank.example", "hidden": true }));let locked = ask(&h, "sites.home", json!({})); assert!(locked["hidden"].get("rows").is_none()); assert!(locked["hidden"].get("no_lock").is_none());let open = ask(&h, "sites.home", json!({ "no_lock": true })); assert_eq!(labels(&open["hidden"]["rows"]), ["Bank"]); assert_eq!(open["hidden"]["no_lock"], "This phone has no screen lock, so your hidden sites show to anyone holding it."); assert_eq!(open["hidden"]["set_lock"], "Set a screen lock");}/// The copy's own SQL, one column of one row, read for a test.fn one(h: &CottonHandle, sql: &str) -> Option<String> { h.client().with_file(|file| Ok(file.driver.get(sql, &[]).map_err(|e| e.to_string())?.and_then(|row| row.text("v").map(str::to_string)))).unwrap()}// RULE (genesis makes a kit's tables, 25 Nov 2026): a phone's own copy holds the kit's `site` table though no tool// draws it, and no tool names it, so nothing new is offered to an assistant; `site` stays closed to every grant.#[test]fn a_fresh_copy_holds_the_kits_own_table_and_no_tool_names_it() {let dir = tempfile::tempdir().unwrap();let h = sites_phone(&dir); assert_eq!(one(&h, "SELECT id AS v FROM cotton_table_definitions WHERE id = 'site'").as_deref(), Some("site"));let tools = h.client().with_file(|file| Ok(file.driver.all("SELECT definition FROM cotton_tool_definitions", &[]).map_err(|e| e.to_string())?.iter().filter_map(|r| r.text("definition").map(str::to_string)).collect::<Vec<_>>())).unwrap(); assert!(tools.iter().all(|t| !t.contains("\"site\"")), "no tool draws the site table"); assert!(cotton_core::seal::agent::closed("site"));}// RULE: a copy made before genesis laid kit tables gains them at its next open, and keeps every row it had; a row in// `site` made before sign-in is the person's, so it goes up at sign-in with the rest.#[test]fn an_older_copy_gains_the_table_at_its_next_open_with_nothing_lost() {let dir = tempfile::tempdir().unwrap();let h = sites_phone(&dir); ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" }));// As a copy made before: the definition gone (its storage, empty, stays as an old build left it). h.client().with_writer(|file| file.driver.run("DELETE FROM cotton_table_definitions WHERE id = 'site'", &[]).map(|_| ()).map_err(|e| e.to_string())).unwrap(); drop(h);let h = reopened(&dir); assert_eq!(one(&h, "SELECT id AS v FROM cotton_table_definitions WHERE id = 'site'").as_deref(), Some("site"), "laid at the open"); assert_eq!(labels(&ask(&h, "sites.home", json!({}))["rows"]), ["Club"], "nothing lost"); ask(&h, "sites.add", json!({ "label": "Work mail", "home": "mail.example" }));let workspace = h.client().with_file(|file| Ok(file.workspace_id.to_string())).unwrap();let path = h.client().layout().replica(&workspace);let rows = crate::phone::personal_object::persons_rows(&path).unwrap(); assert!(rows.made.iter().any(|(table, _)| table == "cotton_site"), "a site row made before sign-in goes up: {:?}", rows.made);}fn reopened(dir: &tempfile::TempDir) -> CottonHandle {let manifest = json!({"genesis": "personal", "flavour": "sites", "name": "Cotton Sites", "databases": "single", "database": "personal", "kit": "sites", });CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(crate::fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Dev, manifest: Some(manifest), }) .expect("the core opens again on the same copy")}/// A site blocks trackers while its own switch is on (You's sets it for new sites): Android asks each request, the iPhone loads the rules.#[test]fn a_site_blocks_trackers_while_its_switch_is_on() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir);let news = id(&ask(&h, "sites.add", json!({ "label": "News", "home": "news.example" })));let t = ask(&h, "sites.trackers", json!({ "id": news })); assert_eq!(t["on"], true); assert!(t["hosts"].as_array().unwrap().iter().any(|h| h == "doubleclick.net")); assert_eq!(t["ios_rules"].as_array().unwrap().len(), t["hosts"].as_array().unwrap().len()); assert_eq!(ask(&h, "sites.block", json!({ "page": "https://news.example/", "url": "https://stats.g.doubleclick.net/j" }))["block"], true); assert_eq!(ask(&h, "sites.block", json!({ "page": "https://news.example/", "url": "https://img.news.example/a.png" }))["block"], false); ask(&h, "sites.edit", json!({ "id": news, "trackers": false })); assert_eq!(ask(&h, "sites.trackers", json!({ "id": news }))["on"], false); ask(&h, "sites.set", json!({ "name": "trackers", "value": false }));let club = id(&ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" }))); assert_eq!(ask(&h, "sites.trackers", json!({ "id": club }))["on"], false, "You's switch sets it for new sites");}/// RULE (ANDROID READY 2, 27 Nov 2026): You's Trackers row says "Blocked" only from a phone that truly blocks. The/// phone says so on `sites.settings` and `sites.set` with `blocks_trackers: true` (Android, which checks each request/// by `sites.block`); a phone that does not send it (the iPhone, until WebKit's rules are loaded) is told "Not/// blocking yet" while the switch is on. Off is "Allowed" on either. The switch itself is kept as it was set.#[test]fn the_trackers_row_says_blocked_only_from_a_phone_that_blocks() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir);let trackers = |answer: &Value| answer["rows"].as_array().unwrap().iter().find(|r| r["id"] == "trackers").cloned().unwrap();let plain = trackers(&ask(&h, "sites.settings", json!({}))); assert_eq!((plain["value"].clone(), plain["line"].clone()), (json!(true), json!("Not blocking yet")), "{plain}");let blocking = trackers(&ask(&h, "sites.settings", json!({ "blocks_trackers": true }))); assert_eq!((blocking["value"].clone(), blocking["line"].clone()), (json!(true), json!("Blocked")), "{blocking}"); assert_eq!(trackers(&ask(&h, "sites.settings", json!({ "blocks_trackers": false })))["line"], "Not blocking yet");let off = ask(&h, "sites.set", json!({ "name": "trackers", "value": false, "blocks_trackers": true })); assert_eq!(trackers(&off)["line"], "Allowed"); assert_eq!(trackers(&ask(&h, "sites.settings", json!({})))["line"], "Allowed");let on = ask(&h, "sites.set", json!({ "name": "trackers", "value": true, "blocks_trackers": true })); assert_eq!(trackers(&on)["line"], "Blocked", "sites.set answers the settings in the same phone's terms"); assert_eq!(trackers(&ask(&h, "sites.set", json!({ "name": "trackers", "value": true })))["line"], "Not blocking yet");}/// A quick visit and a search's throwaway place have no row: `sites.trackers` with no `id` answers You's switch (the/// one a new site takes), so they block as a new site would.#[test]fn a_quick_visit_blocks_as_youve_set_for_new_sites() {let dir = tempfile::tempdir().unwrap();let h = phone(&dir);let quick = ask(&h, "sites.trackers", json!({})); assert_eq!(quick["on"], true, "{quick}"); assert!(quick["hosts"].as_array().unwrap().iter().any(|h| h == "doubleclick.net")); ask(&h, "sites.set", json!({ "name": "trackers", "value": false })); assert_eq!(ask(&h, "sites.trackers", json!({}))["on"], false); assert_eq!(refused(&h, "sites.trackers", json!({ "id": "no-such-site" })).0, "no_row", "a named site that is not there is still refused");}/// A login cleared on this phone is cleared in the table (an empty login, written), and the site is not left owing/// anything: the next change and the list still work (re-review item 1).#[test]fn a_cleared_login_is_written_and_nothing_sticks() {let dir = tempfile::tempdir().unwrap();let h = sites_phone(&dir);let work = id(&ask(&h, "sites.add", json!({ "label": "Work mail", "home": "mail.example" })));crate::phone::sites::table_for_tests(&h.client(), false, "list_records", json!({ "table": "site", "limit": 1 })).unwrap(); ask(&h, "sites.edit", json!({ "id": work, "label": "Office mail" }));let set = crate::phone::sites::with_book_for_tests(&h, |b| b.rows[0].login = Some("login-1".into())); assert!(set.is_ok()); assert_eq!(synced(&h)[0]["login"], "login-1");crate::phone::sites::with_book_for_tests(&h, |b| b.rows[0].login = None).unwrap(); assert_eq!(synced(&h)[0]["login"], "", "the clear is written"); ask(&h, "sites.edit", json!({ "id": work, "label": "Work mail" })); assert_eq!(labels(&ask(&h, "sites.home", json!({}))["rows"]), ["Work mail"]); assert_eq!(synced(&h)[0]["label"], "Work mail");}/// A whole number that comes back from the table as a float still reads as the same number: nothing is put again.#[test]fn a_position_read_back_as_a_float_is_the_same_position() {let dir = tempfile::tempdir().unwrap();let h = sites_phone(&dir); ask(&h, "sites.add", json!({ "label": "Work mail", "home": "mail.example" })); ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" }));let rows = synced(&h); assert!(rows.iter().all(|r| r["position"].as_f64().is_some_and(|p| p.fract() == 0.0)));let before = crate::phone::sites::table_for_tests(&h.client(), false, "list_records", json!({ "table": "site", "limit": 100 })).unwrap(); ask(&h, "sites.home", json!({}));let after = crate::phone::sites::table_for_tests(&h.client(), false, "list_records", json!({ "table": "site", "limit": 100 })).unwrap();let stamp = |v: &Value| v["records"].as_array().unwrap().iter().map(|r| r["updated_at"].clone()).collect::<Vec<_>>(); assert_eq!(stamp(&before), stamp(&after), "drawing the list writes nothing");}/// A table holding more than one page of rows is read whole.#[test]fn a_table_past_one_page_is_read_whole() {let dir = tempfile::tempdir().unwrap();let h = sites_phone(&dir);for n in0..501 {let key = format!("00000000-0000-4000-8000-{n:012}");crate::phone::sites::table_for_tests(&h.client(), true, "create_record", json!({ "table": "site", "data": { "key": key, "label": format!("Site {n}"), "home": "https://site.example/", "position": n } })).unwrap(); }let home = ask(&h, "sites.home", json!({})); assert_eq!(home["rows"].as_array().unwrap().len(), 501); assert_eq!(home["rows"][500]["label"], "Site 500");}// RULE (QUEUE BAD OP 3): a database holding a change set aside because it did not read is never empty, so a sign-in// never lets it give way; it is never removed while no other copy carries the change; signing out sets it aside whole,// the change with it.#[test]fn a_set_aside_change_keeps_its_database_at_sign_in_and_sign_out() {let dir = tempfile::tempdir().unwrap();let h = sites_phone(&dir);let workspace = h.client().with_file(|file| Ok(file.workspace_id.to_string())).unwrap();let layout = h.client().layout().clone();let path = layout.replica(&workspace); assert!(crate::phone::personal_object::persons_rows(&path).unwrap().is_empty(), "a fresh database is empty"); h.client() .with_writer(|file| cotton_store::rejected::set_aside_undecodable(file.driver, "bad-op", Some(&[0, 255]), None, "cotton_site", "site-damaged", "it does not read", "2026-11-26T20:00:00.000Z").map(|_| ()).map_err(|e| e.to_string())) .unwrap();let rows = crate::phone::personal_object::persons_rows(&path).unwrap(); assert_eq!(rows.set_aside, 1); assert!(!rows.is_empty(), "never empty while a set-aside change stands");// Signed out: the copy is set aside whole, the change with it, bytes and all.let held = crate::phone::copy_aside::held(&layout).expect("a connection"); h.client().detach();let aside = crate::phone::copy_aside::set_aside(&layout, &held).unwrap().expect("set aside");let moved = crate::phone::copy_aside::aside_of(&layout, &aside).join(path.file_name().unwrap());let db = cotton_store::Driver::open_snapshot_reader(&moved).expect("the copy set aside");let kept = cotton_store::rejected::set_aside(&db).unwrap(); drop(db); assert_eq!((kept.len(), kept[0].op_id.as_str(), kept[0].bytes.as_slice()), (1, "bad-op", &[0u8, 255][..]), "the change went with it, bytes and all");// Removed by any path but the person's own Remove (QUEUE BAD OP 4): the copy is kept whole aside, never deleted.let aside_folder = moved.parent().unwrap().to_path_buf();let gone = cotton_client::copy_keep::retire_folder(&layout, &workspace, &aside_folder, cotton_client::copy_keep::Ending::keep("a test removal")); assert!(matches!(gone, Ok(cotton_client::copy_keep::Retired::Kept(_))), "{gone:?}");let kept = cotton_client::copy_keep::kept_changes(&layout, &workspace); assert!(kept.iter().any(|change| change.op_id == "bad-op" && change.bytes == vec![0u8, 255]), "{kept:?}");}