//! (adapted from headless_secrets.rs) COTTON SECRETS, PROVEN ON DEV (assets/design/keys/CONTRACT.md row 19): two invented people, each a Secrets phone//! through the C ABI against the dev Worker, who accept each other, check each other's sharing key, share a secret,//! open it, take it back, change it, and ask and answer, through the calls the screens use. Every number, name and//! value is invented. The secrets proof script runs it.//!//! What it shows: the holder opens the secret on their own phone; each open is counted where the value is fetched;//! a take back is said as far as the server saw; a secret seen and taken back stays "still known" until it is//! changed; an ask is answered from the app. What the server keeps is checked by the Worker's own tests and by the//! in-memory network in `phone/secrets_app_tests.rs` (`the_server_reads_none_of_it`): the phones post only sealed//! boxes, which this run's phones did too, through the same code.//!//! 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 numbers (+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::Engineas _;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-getting-in";const FLAVOUR: &str = "notes";const WAIT: Duration = Duration::from_secs(45);const VALUE: &str = "sk_test_SYNTHETIC_PROOF_0000004f2a";const CHANGED: &str = "sk_test_SYNTHETIC_PROOF_000000NEW1";structWalk { server: String, code: String, run: String,}implWalk {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"), "Secrets 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) }}structPhone { handle: *mutCottonHandle, _container: tempfile::TempDir, number: String, name: &'static str, private_key: String,}implPhone {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 secrets {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");letmut 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) {returnOk(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.must("personal.standLocal", json!({ "signedOut": true }));let challenge = self.must("personal.code", json!({ "server": walk.server, "phone": self.number }));letmut ask = json!({ "server": walk.server, "challengeId": challenge["challengeId"], "code": walk.code });ifletSome(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 secrets {}", self.name), "appVersion": APP_VERSION })); }/// The account's key founded on this, its first phone, so its data key and vault are held.fn found_key(&self) {for _ in0..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 secrets {}", 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: implFn(&Value) -> bool) -> Value {let started = Instant::now();loop {ifletOk(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)); } }}implDropforPhone {fn drop(&mutself) {// SAFETY: the pointer cotton_open answered, closed once.unsafe { cotton_close(self.handle) }; }}fn take(text: *mut c_char) -> String {if text.is_null() {returnString::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");letmut 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}/// GETTING IN ON A NEW PHONE (coordinator, 26 Nov 2026, launch-ios's walk): a person whose account holds sealed/// data, founded on one phone, signs in on a fresh one the way the iPhone does (sign in, then the launch's key publish)./// The new phone must be asked to get in (`vault.approval` `mine`, the page, the waiting line), never left on/// "Loading your data…". Skipped without the dev settings.#[test]fn a_fresh_phone_on_a_sealed_account_is_asked_to_get_in() {letSome(walk) = Walk::from_env() else { eprintln!("skipped: COTTON_WALK_SERVER and COTTON_WALK_CODE_FILE are not set");return; };let number = walk.number(5);let first = Phone::open(&walk, &number, "first"); first.sign_in(&walk); first.found_key();// The account's vault and data key are founded; a Words copy has sealed tables whether or not it holds a row.let _ = first.call("keys.add", json!({ "kind": "api_key", "name": "Invented sealed key", "fields": { "key": "sk_test_SYNTHETIC_GETTING_IN" }, "privateKey": first.private_key }));let _ = first.call("sync.now", json!({})); println!("GETTING IN first phone founded and sealed a secret");// A: as the iPhone after a fresh install: signs in, then the launch publish lands in the account's copy.let after = Phone::open(&walk, &number, "after"); after.sign_in(&walk);let public = URL_SAFE_NO_PAD.encode(cotton_core::vault::wrap::public_of(&key_bytes(&after.private_key)));let published = after.call("vault.publishKey", json!({ "publicKey": public, "name": "headless getting in after" })); println!("GETTING IN after: publishKey -> {}", published.as_ref().map(|_| "ok".to_string()).unwrap_or_else(|e| e.clone()));// B: a shell whose publish never ran (its cached public half was empty).let never = Phone::open(&walk, &number, "never"); never.sign_in(&walk);for _ in0..6 {let _ = after.call("sync.now", json!({}));let _ = never.call("sync.now", json!({})); std::thread::sleep(Duration::from_secs(2)); }for phone in [&after, &never] {let status = phone.must("seal.status", json!({}));let approval = phone.must("vault.approval", json!({})); println!("GETTING IN {}: needsKey={} joins={} founds={} said={} mine={}", phone.name, status["needsKey"], status["joins"], status["founds"], status["said"], approval["mine"]); } assert!(after.must("vault.approval", json!({}))["mine"].is_object(), "published after sign-in: asked to get in"); assert!(never.must("vault.approval", json!({}))["mine"].is_object(), "never published: still asked to get in, never left loading");// The page as the shells ask for it (server and number), with no key of this phone's published anywhere.let screen = never.must("gettingIn.screen", json!({ "server": walk.server, "phone": never.number, "deviceName": "headless getting in never" })); println!("GETTING IN never: gettingIn.screen show={} state={} heading={}", screen["show"], screen["state"], screen["heading"]); assert_eq!(screen["show"], json!(true), "the getting-in page comes up, never an endless Loading your data");// Code given -> data opens: the first phone makes a recovery code; the phone with no published key types it.let made = first.lent("recovery.make", json!({}));let code = made["code"].as_str().expect("a recovery code").to_string();let opened = never.lent("recovery.open", json!({ "code": code, "name": "headless getting in never" })); assert_eq!(opened["opened"], json!(true), "the recovery code opens the vault");let held = never.until("seal.status", json!({}), "the data key is held", |status| {if status["keyHeld"] != json!(true) {let _ = never.call("sync.now", json!({})); } status["keyHeld"] == json!(true) }); println!("GETTING IN never: after the code keyHeld={} needsKey={}", held["keyHeld"], held["needsKey"]); assert!(never.must("vault.approval", json!({}))["mine"].is_null(), "in: no longer asked");}fn key_bytes(text: &str) -> [u8; 32] { URL_SAFE_NO_PAD.decode(text).expect("base64").try_into().expect("32 bytes")}