Cotton code
184 lines · 9.4 KB · RustRaw
//! FIRST SYNC, TRACED ON DEV (mail-design's find, 26 Nov 2026: a new phone pulling a half-seeded account parks its//! sealed rows `seal_key_missing`, and they stay parked after `recovery.open`).//!//! A new phone (the shared core through its C ABI, opened as a flavour, as the Android app opens it) on an invented//! dev account that already holds sealed rows://!//! 1. It signs in and pulls with NO key: every pass is timed, and what it parks is counted by table.//! 2. It opens the key with the account's recovery code (`recovery.open`), as the copy's ask would.//! 3. It pulls again, pass by pass: timed, with what is still parked, until nothing is parked or the passes run out.//!//! Each step prints one `FIRST SYNC` line; the last says whether every parked row opened. SKIPPED unless//! COTTON_WALK_SERVER (the dev Worker), COTTON_WALK_CODE_FILE (the dev sign-in code's file), COTTON_FIRST_NUMBER (an//! invented number) and COTTON_FIRST_CODE_FILE (its recovery code's file) are set. COTTON_FIRST_FLAVOUR picks the app//! (default `notes`). Never point it at the live server.use std::collections::BTreeMap;use std::ffi::{c_char, CStr, CString};use std::path::PathBuf;use std::time::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-first-sync";fn var(name: &str) -> Option<String> {    std::env::var(name).ok().filter(|v| !v.trim().is_empty())}fn home(path: &str) -> PathBuf {    match path.strip_prefix("~/") {        Some(rest) => PathBuf::from(std::env::var("HOME").expect("HOME")).join(rest),        None => PathBuf::from(path),    }}fn take(text: *mut c_char) -> String {    if text.is_null() {        return String::new();    }    // SAFETY: an owned string from the C ABI, freed once with its own free.    let owned = unsafe { CStr::from_ptr(text) }.to_string_lossy().into_owned();    unsafe { cotton_string_free(text) };    owned}struct Phone {    handle: *mut CottonHandle,    _container: tempfile::TempDir,    private_key: String,}impl Phone {    fn open(server: &str, number: &str, flavour: &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 first sync {number} {:?}", std::time::SystemTime::now());        let path = cotton_store::manifest_dir().join(format!("../../apps/cotton/App/Flavours/{flavour}/flavour.json"));        let mut manifest: Value = serde_json::from_str(&std::fs::read_to_string(&path).expect("the flavour's manifest")).expect("JSON");        manifest["business"]["server"] = json!(server);        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,        });        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 {flavour}: {}", take(error));        let private_key = URL_SAFE_NO_PAD.encode(Sha256::digest(format!("vault {seed}").as_bytes()));        Phone { handle, _container: container, private_key }    }    fn call(&self, method: &str, request: Value) -> Result<Value, (String, 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).unwrap_or_else(|e| panic!("{method}: the answer is not JSON ({e})"));        if answer["ok"] == json!(true) {            return Ok(answer["data"].clone());        }        let error = &answer["error"];        Err((error["code"].as_str().unwrap_or("?").to_string(), error["message"].as_str().unwrap_or("?").to_string()))    }    fn must(&self, method: &str, request: Value) -> Value {        self.call(method, request).unwrap_or_else(|(code, message)| panic!("{method}: {code} {message}"))    }    fn sign_in(&self, server: &str, number: &str, code: &str) -> Value {        self.must("personal.standLocal", json!({ "signedOut": true }));        let challenge = self.must("personal.code", json!({ "server": server, "phone": number }));        let mut ask = json!({ "server": server, "challengeId": challenge["challengeId"], "code": 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").to_string();        let connect = json!({ "server": server, "databaseId": database, "credential": credential, "deviceName": "first sync trace", "appVersion": APP_VERSION, "unmetered": true });        self.must("personal.connect", connect.clone());        connect    }    /// What is parked now, by table and code, and whether the key is held.    fn parked(&self) -> (bool, usize, BTreeMap<String, usize>) {        let status = self.must("seal.status", json!({}));        let mut by: BTreeMap<String, usize> = BTreeMap::new();        let rows = status["parked"].as_array().cloned().unwrap_or_default();        for row in &rows {            *by.entry(format!("{} {}", row["table"].as_str().unwrap_or("?"), row["code"].as_str().unwrap_or("?"))).or_default() += 1;        }        (status["keyHeld"] == json!(true), rows.len(), by)    }    /// One `sync.now`, timed, with what it said.    fn pass(&self, step: &str, n: usize) -> bool {        let began = Instant::now();        let said = self.call("sync.now", json!({}));        let (held, parked, by) = self.parked();        let behind = said.as_ref().is_ok_and(|s| s["behind"] == json!(true));        let what = match &said {            Ok(s) => format!("behind {behind}, pulled {}", s.get("pulled").or(s.get("applied")).cloned().unwrap_or(Value::Null)),            Err((code, message)) => format!("refused {code}: {message}"),        };        println!("FIRST SYNC {step} pass {n}: {:.1}s, {what}; key held {held}, parked {parked} {by:?}", began.elapsed().as_secs_f64());        behind || said.is_err()    }}impl Drop for Phone {    fn drop(&mut self) {        // SAFETY: the pointer cotton_open answered, closed once.        unsafe { cotton_close(self.handle) };    }}#[test]fn a_new_phone_opens_what_it_parked_before_the_key() {    let (Some(server), Some(number), Some(code_file)) = (var("COTTON_WALK_SERVER"), var("COTTON_FIRST_NUMBER"), var("COTTON_FIRST_CODE_FILE")) else {        eprintln!("SKIPPED: no COTTON_WALK_SERVER, COTTON_FIRST_NUMBER and COTTON_FIRST_CODE_FILE");        return;    };    assert!(server.contains("-dev") || server.contains("localhost") || server.contains("127.0.0.1"), "traced on the dev server only, not {server}");    let otp = var("COTTON_WALK_CODE_FILE").map(|f| std::fs::read_to_string(home(&f)).expect("the dev code file").trim().to_string()).expect("the dev sign-in code");    let code = std::fs::read_to_string(home(&code_file)).expect("the recovery code file").trim().to_string();    let flavour = var("COTTON_FIRST_FLAVOUR").unwrap_or_else(|| "notes".into());    let before_passes: usize = var("COTTON_FIRST_BEFORE").and_then(|n| n.parse().ok()).unwrap_or(6);    let phone = Phone::open(&server, &number, &flavour);    let connect = phone.sign_in(&server, &number, &otp);    println!("FIRST SYNC {flavour} on {number}, database {}", connect["databaseId"].as_str().unwrap_or("?"));    // 1. Before the key.    for n in 1..=before_passes {        if !phone.pass("before the key", n) {            break;        }    }    let (held, parked_before, _) = phone.parked();    assert!(!held, "the key must not be held before recovery.open, or this traces nothing");    // 2. The key, from the recovery code.    let began = Instant::now();    let opened = phone.call("recovery.open", json!({ "code": code, "privateKey": phone.private_key, "name": "first sync trace" }));    let (held, parked, _) = phone.parked();    println!("FIRST SYNC recovery.open {:.1}s: {:?}; key held {held}, parked {parked}", began.elapsed().as_secs_f64(), opened.as_ref().map(|_| "opened").map_err(|e| e.clone()));    // 3. After the key.    let mut left = parked;    for n in 1..=20 {        let more = phone.pass("after the key", n);        left = phone.parked().1;        if left == 0 && !more {            break;        }    }    println!("FIRST SYNC {}: parked before the key {parked_before}, still parked {left}", if left == 0 { "PASSED" } else { "FAILED" });    assert_eq!(left, 0, "rows parked before the key stayed parked after it");}