Cotton code
471 lines · 22.6 KB · RustRaw
//! COTTON SITES, TWO PHONES ON DEV (review of 26 Nov 2026, SITES SYNC FIXED): two phones of one invented person, each//! Cotton Sites through the C ABI against the dev Worker, sealed as the phones are. Each makes a list before it//! signs in; the second phone's first sync must delete nothing of the first's; a removal on one removes it on the//! other and nowhere brings it back; a site added on one phone while the other has its list drawn survives the//! other's next edit; sign-ins and last pages never cross. Every name and address is invented.//!//! SKIPPED unless COTTON_WALK_SERVER (the dev Worker) and COTTON_WALK_CODE_FILE (the dev sign-in code's file: read,//! never printed) are set. COTTON_WALK_RUN picks the invented number (+1555019<run><slot>). Never the live server.use std::ffi::{c_char, CStr, CString};use std::path::PathBuf;use std::time::{Duration, Instant};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use cotton_ffi::{cotton_call, cotton_close, cotton_open, cotton_string_free, CottonHandle};use serde_json::{json, Value};use sha2::{Digest, Sha256};const APP_VERSION: &str = "headless-sites";const FLAVOUR: &str = "sites";const WAIT: Duration = Duration::from_secs(90);struct Walk {    server: String,    code: String,    run: String,}impl Walk {    fn from_env() -> Option<Walk> {        let var = |name: &str| std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty());        let (server, file) = (var("COTTON_WALK_SERVER")?, var("COTTON_WALK_CODE_FILE")?);        assert!(server.contains("-dev") || server.contains("localhost") || server.contains("127.0.0.1"), "Sites is proven on the dev server only, not {server}");        let file = match file.strip_prefix("~/") {            Some(rest) => PathBuf::from(std::env::var("HOME").expect("HOME")).join(rest),            None => PathBuf::from(file),        };        let code = std::fs::read_to_string(&file).unwrap_or_else(|e| panic!("the dev code file {} could not be read: {e}", file.display())).trim().to_string();        let run = var("COTTON_WALK_RUN").unwrap_or_else(|| format!("{:03}", (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() % 900) + 100));        Some(Walk { server, code, run })    }    fn number(&self, slot: u32) -> String {        format!("+1555019{}{slot}", self.run)    }}struct Phone {    handle: *mut CottonHandle,    _container: tempfile::TempDir,    number: String,    name: &'static str,    private_key: String,}impl Phone {    fn open(walk: &Walk, number: &str, name: &'static str) -> Phone {        let container = tempfile::tempdir().expect("a tempdir");        std::fs::create_dir_all(container.path().join("cotton")).expect("the container");        let seed = format!("cotton headless sites {number} {:?}", std::time::SystemTime::now());        let config = json!({            "containerPath": container.path().join("cotton").to_string_lossy(),            "appVersion": APP_VERSION,            "timeZone": "Asia/Kolkata",            "deviceSecret": URL_SAFE_NO_PAD.encode(Sha256::digest(seed.as_bytes())),            "flavor": "dev",            "manifest": manifest(&walk.server),        });        let text = CString::new(config.to_string()).expect("no NUL");        let mut error: *mut c_char = std::ptr::null_mut();        // SAFETY: a NUL-terminated config and a writable error slot, as the JNI hands them.        let handle = unsafe { cotton_open(text.as_ptr(), &mut error) };        assert!(!handle.is_null(), "cotton_open refused: {}", take(error));        let private_key = URL_SAFE_NO_PAD.encode(Sha256::digest(format!("vault {seed}").as_bytes()));        Phone { handle, _container: container, number: number.into(), name, private_key }    }    fn call(&self, method: &str, request: Value) -> Result<Value, String> {        let method_c = CString::new(method).expect("no NUL");        let request_c = CString::new(request.to_string()).expect("no NUL");        // SAFETY: a live handle and NUL-terminated strings; the answer is owned and freed by `take`.        let answer = take(unsafe { cotton_call(self.handle, method_c.as_ptr(), request_c.as_ptr()) });        let answer: Value = serde_json::from_str(&answer).map_err(|e| format!("{method}: the answer is not JSON ({e})"))?;        if answer["ok"] == json!(true) {            return Ok(answer["data"].clone());        }        let error = &answer["error"];        Err(format!("{} {method}: {} {}", self.name, error["code"].as_str().unwrap_or("?"), error["message"].as_str().unwrap_or("?")))    }    fn must(&self, method: &str, request: Value) -> Value {        self.call(method, request).unwrap_or_else(|e| panic!("{e}"))    }    /// The call with this phone's vault key lent, as the shell lends it after Face ID.    fn lent(&self, method: &str, mut request: Value) -> Value {        request["privateKey"] = json!(self.private_key);        self.must(method, request)    }    fn sign_in(&self, walk: &Walk) {        self.sign_in_as(walk, &self.number.clone());    }    /// Signed out of whatever account this phone holds, and in to `number`'s.    fn sign_in_as(&self, walk: &Walk, number: &str) {        self.must("personal.standLocal", json!({ "signedOut": true }));        let challenge = self.must("personal.code", json!({ "server": walk.server, "phone": number }));        let mut ask = json!({ "server": walk.server, "challengeId": challenge["challengeId"], "code": walk.code });        if let Some(database) = challenge.get("databaseId").filter(|d| !d.is_null()) {            ask["databaseId"] = database.clone();        }        let answer = self.must("personal.signIn", ask);        let database = answer["databaseId"].as_str().or(challenge["databaseId"].as_str()).expect("a database").to_string();        let credential = answer["credential"].as_str().expect("a credential");        let connected = self.must("personal.connect", json!({ "server": walk.server, "databaseId": database, "credential": credential, "deviceName": format!("headless sites {}", self.name), "appVersion": APP_VERSION }));        // A phone that made rows before signing in adopts them into the account on its own thread: wait it out (done,        // or waiting for the data key, which the copy takes once connected).        if connected.get("adopt").is_some() {            self.until("personal.adoptStatus", json!({}), "the adopt ended or waits for the key", |status| {                let at = status["adopt"]["status"].as_str().or(status["status"].as_str()).unwrap_or_default().to_string();                !matches!(at.as_str(), "started" | "sending" | "making_copy")            });        }    }    /// The account's key founded on this, its first phone, so its data key and vault are held.    fn found_key(&self) {        for _ in 0..20 {            let status = self.must("seal.status", json!({}));            if status["keyHeld"] == json!(true) {                return;            }            if status["needsKey"] == json!(true) && status["founds"] == json!(true) {                let _ = self.call("vault.unlock", json!({ "privateKey": self.private_key, "name": format!("headless sites {}", self.name) }));            }            let _ = self.call("sync.now", json!({}));            std::thread::sleep(Duration::from_secs(1));        }        panic!("{}: the account's key was never held", self.name);    }    /// Asked until `until` holds of the answer, or WAIT passes: a share crosses from one object to another.    fn until(&self, method: &str, request: Value, what: &str, until: impl Fn(&Value) -> bool) -> Value {        let started = Instant::now();        let mut last = String::new();        loop {            match self.call(method, request.clone()) {                Ok(answer) if until(&answer) => return answer,                Ok(answer) => last = answer.to_string(),                Err(e) => last = e,            }            assert!(started.elapsed() < WAIT, "{}: {what} did not happen in {}s; last {method}: {last}", self.name, WAIT.as_secs());            std::thread::sleep(Duration::from_secs(2));        }    }}impl Drop for Phone {    fn drop(&mut self) {        // SAFETY: the pointer cotton_open answered, closed once.        unsafe { cotton_close(self.handle) };    }}fn take(text: *mut c_char) -> String {    if text.is_null() {        return String::new();    }    // SAFETY: a string the core allocated, read once and freed by the core.    let owned = unsafe { CStr::from_ptr(text) }.to_string_lossy().into_owned();    unsafe { cotton_string_free(text) };    owned}fn manifest(server: &str) -> Value {    let path = cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours").join(FLAVOUR).join("flavour.json");    let mut whole: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{} reads: {error}", path.display()))).expect("JSON");    if whole["business"]["server"].is_object() {        whole["business"]["server"] = json!(server);    }    whole}/// This phone's Sites key, as its keychain keeps it: invented, one per phone.fn sites_key(phone: &Phone) -> String {    URL_SAFE_NO_PAD.encode(Sha256::digest(format!("sites key {}", phone.private_key).as_bytes()))}impl Phone {    fn sites(&self, method: &str, mut request: Value) -> Value {        request["key"] = json!(sites_key(self));        self.must(method, request)    }    fn labels(&self) -> Vec<String> {        let _ = self.call("sync.now", json!({}));        let home = self.sites("sites.home", json!({}));        home["rows"].as_array().into_iter().flatten().map(|r| r["label"].as_str().unwrap_or_default().to_string()).collect()    }    /// Synced and drawn until the list holds exactly `want` (any order), or WAIT passes.    fn shows(&self, want: &[&str]) -> Vec<String> {        let started = Instant::now();        loop {            let mut have = self.labels();            have.sort();            let mut wanted: Vec<String> = want.iter().map(|s| s.to_string()).collect();            wanted.sort();            if have == wanted {                return have;            }            assert!(started.elapsed() < WAIT, "{}: the list is {have:?}, not {wanted:?}, after {}s", self.name, WAIT.as_secs());            std::thread::sleep(Duration::from_secs(2));        }    }    fn id_of(&self, label: &str) -> String {        let home = self.sites("sites.home", json!({}));        home["rows"].as_array().into_iter().flatten().find(|r| r["label"] == label).and_then(|r| r["id"].as_str()).unwrap_or_else(|| panic!("{}: no {label}", self.name)).to_string()    }    fn row(&self, label: &str) -> Value {        let home = self.sites("sites.home", json!({}));        home["rows"].as_array().into_iter().flatten().find(|r| r["label"] == label).cloned().unwrap_or_else(|| panic!("{}: no {label} in {home}", self.name))    }    /// A removal, past its five seconds of Undo, so the row is erased.    fn removes(&self, label: &str) {        let id = self.id_of(label);        self.sites("sites.delete", json!({ "id": id }));        std::thread::sleep(Duration::from_secs(6));        let _ = self.sites("sites.home", json!({}));        let _ = self.call("sync.now", json!({}));    }    /// Until `label`'s row says `what`, or WAIT passes.    fn row_until(&self, label: &str, what: &str, until: impl Fn(&Value) -> bool) -> Value {        let started = Instant::now();        loop {            let _ = self.call("sync.now", json!({}));            let home = self.sites("sites.home", json!({}));            if let Some(r) = home["rows"].as_array().into_iter().flatten().find(|r| r["label"] == label) {                if until(r) {                    return r.clone();                }            }            assert!(started.elapsed() < WAIT, "{}: {label} is not {what} after {}s: {home}", self.name, WAIT.as_secs());            std::thread::sleep(Duration::from_secs(2));        }    }}/// SITES ROWS (SYNC-DESIGN.md, design 2), two phones on one account: B's first sync deletes nothing of A's; edits to/// two columns of one site on two phones both stand; two edits of one column end at the later; a removal stands over/// an edit made on a phone that had not heard of it; nothing of a sign-in or a last page crosses.#[test]fn two_phones_one_list() {    let Some(walk) = Walk::from_env() else {        eprintln!("skipped: COTTON_WALK_SERVER and COTTON_WALK_CODE_FILE are not set");        return;    };    let number = walk.number(7);    // A makes its list before it signs in; every site joins the account.    let a = Phone::open(&walk, &number, "a");    // The phone's own database, as the app's Start makes it at first open.    a.must("workspace.startLocal", json!({ "deviceName": "headless sites a" }));    a.sites("sites.add", json!({ "label": "Work mail", "home": "mail.example" }));    a.sites("sites.add", json!({ "label": "Club", "home": "club.example" }));    a.sign_in(&walk);    a.found_key();    let work = a.id_of("Work mail");    a.sites("sites.left", json!({ "id": work, "url": "https://mail.example/inbox/77", "title": "Inbox (4)" }));    assert_eq!(a.shows(&["Work mail", "Club"]).len(), 2);    println!("SITES two phones: a signed in with its two sites");    // B makes a list of its own before it signs in, signs in to the same account and gets in by a recovery code.    let b = Phone::open(&walk, &number, "b");    b.must("workspace.startLocal", json!({ "deviceName": "headless sites b" }));    b.sites("sites.add", json!({ "label": "Bank", "home": "ledgerbank.example" }));    b.sign_in(&walk);    let made = a.lent("recovery.make", json!({}));    let opened = b.lent("recovery.open", json!({ "code": made["code"], "name": "headless sites b" }));    assert_eq!(opened["opened"], json!(true));    b.until("seal.status", json!({}), "b holds the data key", |status| {        if status["keyHeld"] != json!(true) {            if status["needsKey"] == json!(true) {                let _ = b.call("vault.unlock", json!({ "privateKey": b.private_key, "name": "headless sites b" }));            }            let _ = b.call("sync.now", json!({}));        }        status["keyHeld"] == json!(true)    });    b.shows(&["Work mail", "Club", "Bank"]);    a.shows(&["Work mail", "Club", "Bank"]);    println!("SITES two phones: b's first sync deleted nothing of a's");    let work_on_b = b.row("Work mail");    assert_eq!(work_on_b["line"], "Sign in once", "no sign-in crossed");    assert!(!work_on_b.to_string().contains("inbox/77") && !work_on_b.to_string().contains("Inbox (4)"), "no last page crossed: {work_on_b}");    // Two columns of one site, one on each phone: both stand.    a.sites("sites.edit", json!({ "id": work, "label": "Office mail" }));    b.sites("sites.edit", json!({ "id": work, "pinned": true }));    for p in [&a, &b] {        p.row_until("Office mail", "renamed and pinned", |r| r["pinned"] == true);    }    println!("SITES two phones: a's rename and b's pin of one site both stood");    // One column on both phones, b's a little later: b's word is the one both keep.    let club = a.id_of("Club");    a.sites("sites.edit", json!({ "id": club, "label": "Chess club" }));    let _ = a.call("sync.now", json!({}));    std::thread::sleep(Duration::from_secs(2));    b.sites("sites.edit", json!({ "id": club, "label": "Board club" }));    a.shows(&["Office mail", "Board club", "Bank"]);    b.shows(&["Office mail", "Board club", "Bank"]);    println!("SITES two phones: one column edited on both ended at the later edit");    // Removed on b; a, not yet told, renames it: the removal stands on both.    b.removes("Bank");    let bank = a.id_of("Bank");    // Made on a's copy, which still holds the row: taken here, refused by the Worker (the row is erased there), parked.    let edited = a.call("sites.edit", json!({ "key": sites_key(&a), "id": bank, "label": "Ledger bank" }));    assert!(edited.is_ok(), "a's edit is taken on a's own copy: {edited:?}");    a.shows(&["Office mail", "Board club"]);    b.shows(&["Office mail", "Board club"]);    println!("SITES two phones: a removal stood over an edit made by a phone that had not heard of it");    let office = a.row("Office mail");    assert_eq!(office["line"], "mail.example · Inbox (4)", "a's own last page stays a's");    println!("SITES TWO PHONES PASSED");}/// SITES ROWS: a phone signing in to a huge account (an invented one made by `pnpm dev:big-account`, given as/// COTTON_BIG_NUMBER and its recovery code as COTTON_BIG_CODE) draws only what has come, never brings back a site/// removed elsewhere, and its change made mid-pull reaches the other phone.#[test]fn a_huge_account_still_pulling_loses_nothing() {    let Some(walk) = Walk::from_env() else {        eprintln!("skipped: COTTON_WALK_SERVER and COTTON_WALK_CODE_FILE are not set");        return;    };    let (Ok(number), Ok(code)) = (std::env::var("COTTON_BIG_NUMBER"), std::env::var("COTTON_BIG_CODE")) else {        eprintln!("skipped: COTTON_BIG_NUMBER and COTTON_BIG_CODE (pnpm dev:big-account) are not set");        return;    };    let a = Phone::open(&walk, &number, "big a");    a.sign_in(&walk);    assert_eq!(a.lent("recovery.open", json!({ "code": code, "name": "headless sites big a" }))["opened"], json!(true));    a.until("seal.status", json!({}), "a holds the data key", |status| {        if status["keyHeld"] != json!(true) {            let _ = a.call("sync.now", json!({}));        }        status["keyHeld"] == json!(true)    });    a.sites("sites.add", json!({ "label": "Work mail", "home": "mail.example" }));    a.sites("sites.add", json!({ "label": "Club", "home": "club.example" }));    a.shows(&["Work mail", "Club"]);    a.removes("Club");    a.shows(&["Work mail"]);    let b = Phone::open(&walk, &number, "big b");    b.sign_in(&walk);    assert_eq!(b.lent("recovery.open", json!({ "code": code, "name": "headless sites big b" }))["opened"], json!(true));    // Mid-pull: whatever has come is drawn, and Club never is.    let started = Instant::now();    let mut added = false;    loop {        let _ = b.call("sync.now", json!({}));        let shown = b.labels();        assert!(!shown.iter().any(|l| l == "Club"), "a site removed elsewhere came back mid-pull: {shown:?}");        if !added && b.call("seal.status", json!({})).is_ok_and(|s| s["keyHeld"] == json!(true)) {            b.sites("sites.add", json!({ "label": "News", "home": "news.example" }));            added = true;        }        if added && shown.len() == 2 {            break;        }        assert!(started.elapsed() < WAIT * 10, "b never caught up: {shown:?}");        std::thread::sleep(Duration::from_secs(3));    }    a.shows(&["Work mail", "News"]);    println!("SITES HUGE ACCOUNT PASSED");}/// RE-REVIEW item 4: a phone signed out of one account and in to another takes none of the first account's sites to/// the second: the second account's list starts empty there and on its own other phone, and the first account's list/// is still the first's when it signs back in.#[test]fn another_account_on_the_same_phone_never_receives_the_first_accounts_sites() {    let Some(walk) = Walk::from_env() else {        eprintln!("skipped: COTTON_WALK_SERVER and COTTON_WALK_CODE_FILE are not set");        return;    };    let (first, second) = (walk.number(8), walk.number(9));    let phone = Phone::open(&walk, &first, "shared");    phone.sign_in(&walk);    phone.found_key();    phone.sites("sites.add", json!({ "label": "Work mail", "home": "mail.example" }));    phone.sites("sites.add", json!({ "label": "Club", "home": "club.example" }));    phone.shows(&["Work mail", "Club"]);    println!("SITES accounts: the first account holds two sites");    phone.sign_in_as(&walk, &second);    phone.found_key();    assert!(phone.shows(&[]).is_empty(), "the second account's list starts empty on this phone");    phone.sites("sites.add", json!({ "label": "Bank", "home": "ledgerbank.example" }));    phone.shows(&["Bank"]);    let other = Phone::open(&walk, &second, "second's other");    other.sign_in(&walk);    let made = phone.lent("recovery.make", json!({}));    assert_eq!(other.lent("recovery.open", json!({ "code": made["code"], "name": "headless sites second" }))["opened"], json!(true));    other.until("seal.status", json!({}), "the other phone holds the data key", |status| {        if status["keyHeld"] != json!(true) {            // "Unlock it once with your phone's lock": the shell lends the vault key after Face ID.            if status["needsKey"] == json!(true) {                let _ = other.call("vault.unlock", json!({ "privateKey": other.private_key, "name": "headless sites second" }));            }            let _ = other.call("sync.now", json!({}));        }        status["keyHeld"] == json!(true)    });    other.shows(&["Bank"]);    println!("SITES accounts: the second account's database holds only its own site");    phone.sign_in_as(&walk, &first);    phone.shows(&["Work mail", "Club"]);    println!("SITES ACCOUNTS PASSED");}/// SITES ROWS: signed out, Sites shows the phone's own list, never the account's. Before the next sign-in Sites asks;/// "Leave them off" keeps them off that account (and nothing is refused), "Add them" brings them in; the first/// account's list is back when it signs in again.#[test]fn signed_out_sites_ask_before_they_join() {    let Some(walk) = Walk::from_env() else {        eprintln!("skipped: COTTON_WALK_SERVER and COTTON_WALK_CODE_FILE are not set");        return;    };    let (x, y, z) = (walk.number(3), walk.number(4), walk.number(5));    let phone = Phone::open(&walk, &x, "out");    phone.sign_in(&walk);    phone.found_key();    phone.sites("sites.add", json!({ "label": "Work mail", "home": "mail.example" }));    phone.shows(&["Work mail"]);    phone.must("personal.standLocal", json!({ "signedOut": true }));    assert!(phone.labels().is_empty(), "signed out: the account's list is not shown");    phone.sites("sites.add", json!({ "label": "Signed-out note", "home": "notes.example" }));    assert_eq!(phone.labels(), ["Signed-out note"]);    println!("SITES signed out: a list of its own");    phone.sign_in_as(&walk, &y);    phone.found_key();    phone.shows(&["Signed-out note"]);    println!("SITES signed out: the signed-out list joined the next account, nothing of X's");    phone.must("personal.standLocal", json!({ "signedOut": true }));    phone.sites("sites.add", json!({ "label": "Recipes", "home": "recipes.example" }));    phone.sign_in_as(&walk, &z);    phone.found_key();    phone.shows(&["Recipes"]);    println!("SITES signed out: added, the site joined the account it was asked for");    phone.sign_in_as(&walk, &x);    phone.shows(&["Work mail"]);    println!("SITES SIGNED OUT PASSED");}