//! REVIEWER ACCOUNTS (`pnpm review:accounts`, coordinator, 22 Nov 2026; assets/design/LAUNCH.md §1): one invented //! account per app sent to review (Words, Days, Story), each on its own invented number, signed in once on a NAMED //! server and filled with believable invented content, so the App Store and Play reviewers see the signed-in parts //! and sync with something in them. //! //! Each account is made as a phone of that app makes it: a core opened as the app's flavour over its own container, //! signed in with the number's own code (`personal.code`, `personal.signIn`, `personal.connect`; the server proves //! the code through OTP_TEST_CODES, so it never reaches Twilio), the account's key founded (`vault.unlock`) and a //! recovery code made (`recovery.make`), then the content written through the app's own doors and synced up: //! //! - Words (`notes`): `notes.import` of eight invented notes (a shopping checklist, a trip plan, a reading list…). //! - Days (`days`): `days.add` of the week around today: to-dos, timed events, one with no day (Sometime). //! - Story (`story`): `story.bring_in` of a short invented screenplay, "The Night Ferry". //! //! Nothing here is a real person's: every name, place and line is made up. Nothing secret is in the repo: the //! server, the numbers and their codes come from the environment, and each account's recovery code is printed on //! one `RECOVERY-CODE ` line that the review accounts script writes to a private file and never shows. //! //! Environment (SKIPPED unless COTTON_REVIEW_SERVER is set): //! - COTTON_REVIEW_SERVER: the Worker to make them on (dev for a try; the coordinator runs it on live). //! - COTTON_REVIEW_APPS: which of notes,days,story (default all three). //! - COTTON_REVIEW__NUMBER and COTTON_REVIEW__CODE, APP one of NOTES, DAYS, STORY: the reviewer number //! (an invented +1 555 number, refused otherwise) and its own six-digit code as OTP_TEST_CODES holds it. //! //! An account is seeded once: a number whose account already holds a key is refused, so a second run never doubles //! its content. use std::ffi::{c_char, CStr, CString}; use std::path::Path; 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 = "review-accounts"; const ZONE: &str = "America/Los_Angeles"; fn var(name: &str) -> Option { std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty()) } /// One reviewer: the app, its number and its code, from the environment. struct Reviewer { app: String, number: String, code: String, } impl Reviewer { fn from_env(app: &str) -> Reviewer { let key = app.to_uppercase(); let number = var(&format!("COTTON_REVIEW_{key}_NUMBER")).unwrap_or_else(|| panic!("COTTON_REVIEW_{key}_NUMBER is not set")); let code = var(&format!("COTTON_REVIEW_{key}_CODE")).unwrap_or_else(|| panic!("COTTON_REVIEW_{key}_CODE is not set")); assert!(invented(&number), "{app}: {number} is not an invented +1 555 number; a reviewer account never takes a number that can be a person's"); assert!(code.len() == 6 && code.chars().all(|c| c.is_ascii_digit()), "{app}: the code is not six digits"); Reviewer { app: app.to_string(), number, code } } } /// +1 555 01xx is the range kept for fiction; +1 555 itself never reaches a person through this server's test codes. fn invented(number: &str) -> bool { number.starts_with("+1555") && number.len() == 12 && number[1..].chars().all(|c| c.is_ascii_digit()) } /// One app's phone: a core over its own container, as that app opens it. struct Phone { handle: *mut CottonHandle, _container: tempfile::TempDir, flavour: String, private_key: String, } impl Phone { fn open(server: &str, flavour: &str, number: &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 review {number} {flavour} {:?}", std::time::SystemTime::now()); let config = json!({ "containerPath": container.path().join("cotton").to_string_lossy(), "appVersion": APP_VERSION, "timeZone": ZONE, "deviceSecret": URL_SAFE_NO_PAD.encode(Sha256::digest(seed.as_bytes())), "flavor": "dev", "manifest": manifest(server, flavour), }); 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, flavour: flavour.to_string(), private_key } } 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.flavour, 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 SignIn form's calls, then `personal.connect`, as `shell/core/Session.kt` asks them. fn sign_in(&self, server: &str, who: &Reviewer) { self.must("personal.standLocal", json!({ "signedOut": true })); let challenge = self.must("personal.code", json!({ "server": server, "phone": who.number })); let mut ask = json!({ "server": server, "challengeId": challenge["challengeId"], "code": who.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("personal.signIn named no database").to_string(); let credential = answer["credential"].as_str().expect("personal.signIn granted no credential"); self.must("personal.connect", json!({ "server": server, "databaseId": database, "credential": credential, "deviceName": "Review account setup", "appVersion": APP_VERSION })); } /// The account's key founded here, as a new account's first phone founds it; an account that already has one was /// seeded before and is refused. fn found_key(&self) { for attempt in 0..20 { let status = self.must("seal.status", json!({})); let yes = |name: &str| status[name] == json!(true) || status[name] == json!("true"); if yes("keyHeld") { return; } // A new account's first status may say a key is needed before a pass has said this phone founds it: // refused only once a few passes still say another holds it (launch-ios, 22 Nov 2026). if yes("needsKey") && !yes("founds") && attempt >= 4 { panic!("{}: this number's account already has a key; it was seeded before, and a second run would double its content", self.flavour); } if yes("needsKey") { let said = self.call("vault.unlock", json!({ "privateKey": self.private_key, "name": "Review account setup" })); eprintln!("KEY {} try {attempt}: {}", self.flavour, said.err().unwrap_or_else(|| "founded".into())); } let _ = self.call("sync.now", json!({})); std::thread::sleep(std::time::Duration::from_secs(2)); } panic!("{}: the account's key was never held", self.flavour); } /// `sync.now` until nothing waits to go up. fn push_all(&self) { for round in 0..200 { let said = self.call("sync.now", json!({})); let pending = self.must("sync.status", json!({}))["pending"].as_u64().unwrap_or(0); eprintln!("PUSH {} round {round}: pending {pending} {}", self.flavour, said.err().unwrap_or_default()); if pending == 0 { return; } } panic!("{}: rows were still waiting to go up", self.flavour); } } 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: 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 } fn manifest(server: &str, flavour: &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 } // ── the invented content ──────────────────────────────────────────────────── /// Words: eight notes a person might keep, every name and place made up. pub const NOTES: &[(&str, &str)] = &[ ("Groceries for the week.md", "# Groceries for the week\n\n- [x] Oat milk\n- [x] Bananas\n- [ ] Basmati rice\n- [ ] Lemons (4)\n- [ ] Coriander\n- [ ] Greek yoghurt\n- [ ] Dark chocolate, the 70% one\n\n#home"), ("Lisbon in March.md", "# Lisbon in March\n\n## Getting there\nFlight lands 10:40. Tram 28 from Martim Moniz is slow but worth it once.\n\n## Places to see\n- Miradouro da Senhora do Monte at sunset\n- The tile museum\n- A day trip to Sintra, early train\n\n## To book\n- [ ] Hotel for 4 nights\n- [x] Train to Sintra\n\n#travel"), ("Books to read.md", "# Books to read\n\n1. The Lighthouse Keeper's Year\n2. A Short History of Rivers\n3. Notes from a Small Kitchen\n4. The Map Room\n\n> Ask Priya which one she meant by \"the blue one\".\n\n#reading"), ("Ideas for the balcony garden.md", "# Ideas for the balcony garden\n\nThe balcony gets sun from about **11 to 3**, so herbs will do well.\n\n- Basil and mint in the long box\n- Cherry tomatoes on the left, by the railing\n- A small lemon tree if the pot is big enough\n\nWater every other day in summer.\n\n#home"), ("Team offsite notes.md", "# Team offsite notes\n\n## What went well\n- Shipping the new onboarding on time\n- Fewer meetings on Wednesdays\n\n## What to change\n- Write decisions down the same day\n- One planning doc instead of three\n\n## Next steps\n- [ ] Share the summary with everyone by Friday\n- [ ] Book the room for the next one\n\n#work"), ("Lemon dal.md", "# Lemon dal\n\nServes 4.\n\n1. Rinse 1 cup of yellow lentils, cook with 3 cups of water and turmeric until soft.\n2. Heat ghee, add cumin seeds, garlic and green chilli.\n3. Pour over the dal, add salt and the juice of one lemon.\n4. Finish with chopped coriander.\n\n#recipes"), ("Birthday gift ideas.md", "# Birthday gift ideas\n\n- **Dad**: a good flask for his walks\n- **Anna**: watercolour set, the travel size\n- **Sam**: concert tickets, ask about dates first\n\n#people"), ("Running plan.md", "# Running plan\n\n| Day | Run |\n| --- | --- |\n| Tue | 5 km easy |\n| Thu | Intervals, 6 x 400 m |\n| Sat | 10 km slow |\n\nStretch after every run.\n\n#health"), ]; /// Days: what the week around today holds, as (days from today or None for Sometime, time or None, words). pub const DAYS: &[(Option, Option<&str>, &str)] = &[ (Some(0), Some("09:30"), "Stand-up with the design team"), (Some(0), None, "Pay the electricity bill"), (Some(0), Some("18:00"), "Yoga class"), (Some(0), None, "Pick up the dry cleaning"), (Some(1), Some("10:00"), "Dentist"), (Some(1), None, "Call the landlord about the heater"), (Some(1), Some("19:30"), "Dinner with Anna and Sam"), (Some(2), None, "Send the offsite summary"), (Some(2), Some("14:00"), "Project review"), (Some(3), Some("08:00"), "Run, 10 km slow"), (Some(3), None, "Water the balcony plants"), (Some(4), Some("11:00"), "Haircut"), (Some(5), None, "Book the hotel in Lisbon"), (Some(6), Some("17:00"), "Dad's birthday tea"), (Some(-1), None, "Return the library books"), (Some(-1), Some("12:30"), "Lunch with Priya"), (None, None, "Fix the squeaky door"), (None, None, "Learn to make sourdough"), ]; /// Story: a short invented screenplay, five scenes. No FADE IN: words before the first heading are kept as a scene of /// their own (the import is lossless), which a reviewer would read as an empty "New scene" (launch-ios, 22 Nov 2026). pub const STORY: &str = "Title: The Night Ferry Author: Cotton Story review EXT. HARBOUR - NIGHT Rain on the water. A small ferry waits at the end of the pier, its deck lights blinking. NINA (30s), soaked, runs along the planks with a suitcase that has lost a wheel. NINA Wait! Please, wait! On deck, the FERRYMAN (60s) coils a rope without looking up. FERRYMAN Last crossing left an hour ago. NINA Then what is this one? FERRYMAN (finally looking at her) This one only goes where people need to go. INT. FERRY CABIN - NIGHT A narrow room with two benches and a stove. Nina drips onto the floor. Across from her sits OMAR (40s), reading a paper map by lamplight. OMAR You're not on the list. NINA There's a list? OMAR There's always a list. He folds the map and holds out a thermos. OMAR (CONT'D) Tea. You'll need it before the island. EXT. FERRY DECK - LATER The rain has stopped. Fog. Nina stands at the rail. A lighthouse beam sweeps across her face. NINA (to herself) Twelve years. You said you'd wait twelve years. The Ferryman joins her. FERRYMAN Who said that? NINA My sister. Before she moved out here. FERRYMAN Then she'll be at the dock. They always are. EXT. ISLAND DOCK - DAWN The ferry bumps against the old stones. On the dock, holding a lantern that no longer needs lighting, stands LEA (40s). She looks older than Nina expected. She looks exactly the same. LEA You took the night ferry. NINA You told me it was the only one that comes here. LEA I told you a lot of things. They look at each other. Then Lea laughs, and Nina drops the suitcase. INT. LEA'S KITCHEN - MORNING Sunlight. Two cups. A window full of sea. LEA Stay a week. NINA I only packed for two days. LEA That's what I said. Twelve years ago. They both laugh. Outside, the ferry sounds its horn and pulls away. FADE OUT. "; fn seed_notes(phone: &Phone, dir: &Path) -> usize { let folder = dir.join("Notes"); std::fs::create_dir_all(&folder).unwrap(); for (name, body) in NOTES { std::fs::write(folder.join(name), body).unwrap(); } let answer = phone.must("notes.import", json!({ "files": [{ "path": folder.to_string_lossy() }] })); eprintln!("WORDS imported: {answer}"); NOTES.len() } fn seed_days(phone: &Phone) -> usize { let today = chrono::Utc::now().with_timezone(&chrono_tz::America::Los_Angeles).date_naive(); for (day, time, words) in DAYS { let mut ask = json!({ "words": words, "today": today.format("%Y-%m-%d").to_string(), "timezone": ZONE, "where": if day.is_some() { "days" } else { "sometime" } }); if let Some(day) = day { ask["day"] = json!((today + chrono::Duration::days(*day)).format("%Y-%m-%d").to_string()); } if let Some(time) = time { ask["time"] = json!(time); } phone.must("days.add", ask); } DAYS.len() } fn seed_story(phone: &Phone, dir: &Path) -> usize { let path = dir.join("The Night Ferry.fountain"); std::fs::write(&path, STORY).unwrap(); let answer = phone.must("story.bring_in", json!({ "path": path.to_string_lossy(), "name": "The Night Ferry.fountain" })); eprintln!("STORY brought in: {}", answer.to_string().chars().take(300).collect::()); STORY.matches("\nINT. ").count() + STORY.matches("\nEXT. ").count() } #[test] fn reviewer_accounts_are_made_on_the_named_server() { let Some(server) = var("COTTON_REVIEW_SERVER") else { eprintln!("SKIPPED: no COTTON_REVIEW_SERVER"); return; }; let apps = var("COTTON_REVIEW_APPS").unwrap_or_else(|| "notes,days,story".into()); let scratch = tempfile::tempdir().expect("a scratch dir"); for app in apps.split(',').map(str::trim).filter(|a| !a.is_empty()) { assert!(["notes", "days", "story"].contains(&app), "no reviewer account for {app}"); let who = Reviewer::from_env(app); let phone = Phone::open(&server, app, &who.number); phone.sign_in(&server, &who); phone.found_key(); let made = phone.must("recovery.make", json!({ "privateKey": phone.private_key })); println!("RECOVERY-CODE {} {}", who.app, made["code"].as_str().expect("recovery.make made no code")); let items = match app { "notes" => seed_notes(&phone, scratch.path()), "days" => seed_days(&phone), _ => seed_story(&phone, scratch.path()), }; phone.push_all(); println!("MADE {app}: {items} items on {}", who.number.chars().take(6).collect::() + "…"); } } // ── what can be checked without a server ──────────────────────────────────── #[test] fn only_invented_numbers_are_taken() { assert!(invented("+15550100123")); assert!(!invented("+919876543210"), "an Indian mobile"); assert!(!invented("+14155550123"), "a real San Francisco number"); assert!(!invented("+1555010012"), "too short"); } #[test] fn the_content_is_whole_and_invented() { assert_eq!(NOTES.len(), 8); assert!(NOTES.iter().all(|(name, body)| name.ends_with(".md") && body.starts_with("# "))); assert!(DAYS.iter().any(|(day, _, _)| day.is_none()), "something for Sometime"); assert!(DAYS.iter().any(|(day, time, _)| *day == Some(0) && time.is_some()), "an event today"); assert!(DAYS.iter().any(|(day, time, _)| *day == Some(0) && time.is_none()), "a to-do today"); assert_eq!(STORY.matches("\nINT. ").count() + STORY.matches("\nEXT. ").count(), 5, "five scenes"); assert!(STORY.starts_with("Title: The Night Ferry")); }