//! COTTON POST'S ARCHIVED SENDERS, PROVEN ON DEV (the coordinator, 25 Nov 2026, before 398521f239 goes live): two //! phones of one invented person against the dev Worker. On the first a whole sender is archived in one write (the //! `email_cut` row); the second sees it after a sync, with the counts; one mail moved back to the Inbox stays there on //! both; a mail from that sender landed afterwards is not archived; Undo brings everything back on both. The run then //! archives the sender again and leaves the account, so an older build (one that does not know `email_cut`) can sign //! in and sync it: COTTON_POST_CUT_SHARE names a file this run writes the account's number, run and recovery code to. //! //! Every number, 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. 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-post-cut"; const FLAVOUR: &str = "mail"; const WAIT: Duration = Duration::from_secs(90); const SENDER: &str = "offers@kitebox.example"; const ME: &str = "mira.cut@invented.example"; struct Walk { server: String, code: String, run: String, } impl Walk { fn from_env() -> Option { 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"), "Post 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 { private_key: String, handle: *mut CottonHandle, _container: tempfile::TempDir, number: String, name: &'static str, } 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 post {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)); Phone { handle, _container: container, number: number.into(), name, private_key: URL_SAFE_NO_PAD.encode(Sha256::digest(format!("vault {seed}").as_bytes())) } } fn call(&self, method: &str, request: Value) -> Result { 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}")) } fn sign_in(&self, walk: &Walk) { self.must("personal.standLocal", json!({ "signedOut": true })); let challenge = self.must("personal.code", json!({ "server": walk.server, "phone": self.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"); self.must("personal.connect", json!({ "server": walk.server, "databaseId": database, "credential": credential, "deviceName": format!("headless post {}", self.name), "appVersion": APP_VERSION })); } /// The account's key founded on this, its first phone, so its data key and vault are held. /// The key held here: founded on the account's first phone, else opened with its recovery code. fn hold_key(&self, code: &str) { let mut opened = false; for _ in 0..30 { let status = self.must("seal.status", json!({})); if status["keyHeld"] == json!(true) { return; } if status["needsKey"] == json!(true) { let name = format!("headless post {}", self.name); let again = if opened { self.call("vault.unlock", json!({ "privateKey": self.private_key, "name": name })) } else { Err(String::new()) }; if again.is_err() { opened |= self.call("recovery.open", json!({ "code": code, "privateKey": self.private_key, "name": name })).is_ok(); } } let _ = self.call("sync.now", json!({})); std::thread::sleep(Duration::from_secs(2)); } panic!("{}: the account's key was never held", self.name); } /// `sync.now` until nothing waits to go up, and nothing was refused. fn push_all(&self) { for _ in 0..120 { let _ = self.call("sync.now", json!({})); if self.must("sync.status", json!({}))["pending"].as_u64().unwrap_or(0) == 0 { break; } } let rejected = self.call("sync.rejected", json!({})).unwrap_or(Value::Null); assert!(rejected.get("rows").and_then(Value::as_array).is_none_or(|r| r.is_empty()), "{}: the object refused rows: {rejected}", self.name); } 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 post {}", 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(); loop { if let Ok(answer) = self.call(method, request.clone()) { if until(&answer) { return answer; } } assert!(started.elapsed() < WAIT, "{}: {what} did not happen in {}s", 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 } fn step(name: &str, started: Instant) { println!("POST CUT PROOF {name} ({:.1} s)", started.elapsed().as_secs_f64()); } fn subjects(answer: &Value) -> Vec { answer["rows"].as_array().into_iter().flatten().filter_map(|r| r["subject"].as_str().map(str::to_string)).collect() } fn invented(id: &str, subject: &str, at: &str) -> Value { json!({ "id": id, "thread": id, "subject": subject, "from": { "address": SENDER, "name": "Kitebox" }, "at": at, "body": "Shop now. An invented offer." }) } #[test] fn archived_senders_sync_and_stay_exact_on_dev() { let Some(walk) = Walk::from_env() else { eprintln!("skipped: COTTON_WALK_SERVER and COTTON_WALK_CODE_FILE are not set"); return; }; let started = Instant::now(); let number = walk.number(5); let a = Phone::open(&walk, &number, "first"); a.sign_in(&walk); a.found_key(); let code = a.must("recovery.make", json!({ "privateKey": a.private_key }))["code"].as_str().expect("a recovery code").to_string(); if let Ok(file) = std::env::var("COTTON_POST_CUT_SHARE") { std::fs::write(file.trim(), format!("{number}\n{code}\n")).expect("the share file"); } let mail = json!([ invented("cut-1", "Winter list 40% off", "2026-11-20T08:00:00Z"), invented("cut-2", "Socks for winter", "2026-11-21T08:00:00Z"), invented("cut-3", "Boots are back", "2026-11-22T08:00:00Z"), { "id": "cut-p", "thread": "cut-p", "subject": "Flat keys", "from": { "address": "asha.cut@invented.example", "name": "Asha Example" }, "at": "2026-11-22T09:00:00Z", "body": "Are you home on Friday?" }, ]); a.must("developer.inventMail", json!({ "me": { "address": ME }, "mail": mail })); a.push_all(); step("first phone signed in, four invented mails written and pushed", started); let b = Phone::open(&walk, &number, "second"); b.sign_in(&walk); b.hold_key(&code); let inbox = |p: &Phone| subjects(&p.must("mail.list", json!({ "place": "inbox" }))); let has = |rows: &[String], s: &str| rows.iter().any(|r| r == s); b.until("mail.list", json!({ "place": "inbox" }), "the four mails on the second phone", |l| subjects(l).len() >= 4 || { let _ = b.call("sync.now", json!({})); false }); step("second phone holds the mail", started); let done = a.must("mail.archive", json!({ "scope": "sender", "key": SENDER })); assert_eq!(done["count"], 3, "{done}"); a.push_all(); let sync_until = |p: &Phone, what: &str, ok: &dyn Fn(&[String]) -> bool| { let t = Instant::now(); loop { let _ = p.call("sync.now", json!({})); let rows = inbox(p); if ok(&rows) { return rows; } assert!(t.elapsed() < WAIT, "{}: {what} never came: {rows:?}", p.name); std::thread::sleep(Duration::from_secs(2)); } }; let rows = sync_until(&b, "the archive", &|r| !has(r, "Socks for winter") && has(r, "Flat keys")); assert!(!has(&rows, "Winter list 40% off") && !has(&rows, "Boots are back")); let archived = subjects(&b.must("mail.list", json!({ "place": "archived" }))); assert!(has(&archived, "Boots are back"), "{archived:?}"); let page = b.must("mail.sender", json!({ "key": "@kitebox.example" })); let shown = page.to_string(); println!("POST CUT PROOF second phone, the sender page: {}", &shown[..shown.len().min(400)]); step("archived in one write on the first phone; the second shows it after a sync", started); a.must("mail.act", json!({ "act": "restore", "email": "cut-2" })); a.push_all(); let rows = sync_until(&b, "the mail moved back", &|r| has(r, "Socks for winter")); assert!(!has(&rows, "Boots are back"), "only that one came back: {rows:?}"); assert!(has(&inbox(&a), "Socks for winter") && !has(&inbox(&a), "Boots are back")); step("one mail moved back stays in the Inbox on both", started); a.must("developer.inventMail", json!({ "me": { "address": ME }, "mail": [invented("cut-4", "New arrivals", "2026-11-21T10:00:00Z")] })); a.push_all(); assert!(has(&inbox(&a), "New arrivals"), "landed after the Archive, though dated before it: in the Inbox"); sync_until(&b, "the new mail", &|r| has(r, "New arrivals")); step("mail landed after the Archive is in the Inbox on both", started); a.must("mail.undo", json!({ "after": done["after"] })); a.push_all(); sync_until(&b, "the Undo", &|r| has(r, "Winter list 40% off") && has(r, "Boots are back")); step("Undo brought everything back on both", started); let again = a.must("mail.archive", json!({ "scope": "sender", "key": SENDER })); a.push_all(); println!("POST CUT PROOF archived again for the older build: {}", again["line"]); println!("POST CUT PROOF PASSED ({:.1} s)", started.elapsed().as_secs_f64()); }