//! GETTING IN ON A NEW DEVICE (assets/design/shared/GETTING-IN.md, 22 Nov 2026). One path: a person //! signs in with their number and a code by text, always; then, while another device of theirs opens their things //! and this one cannot yet, this device goes by itself to "Waiting for your other device": a square code to scan and, //! once the other device has opened the ask, six digits. Nothing to choose first, no dead end, Sign out always there. //! //! ```text //! gettingIn.screen { server, phone, deviceName?, deviceKind?, vaultKey? } //! → { show: false } nothing to wait for (no other device holds the key, or this one does) //! → { show: true, state: waiting | approved | refused | ended | timed_out | busy | offline, //! heading, line, qr: {text, size, rows} | null, code: "482 913" | null, codeLine, never, left?, //! again?, noDevice, signOut, later, slim, slimAct, pollSeconds, sync? } //! gettingIn.again { …the same } → the screen, with a fresh ask that replaces the one before //! ``` //! //! The shell calls `screen` when it draws the page and every `pollSeconds` while it stands; each call polls the ask //! (`personal.askPoll`'s rules) and, with none live, makes one (`personal.ask`'s), naming this device's vault key so //! the approval writes the wrap for it. The ask stands in this process only, as `personal.ask`'s nonce does: an app //! that restarts makes a fresh one, which replaces the old on the server (src/approval.ts `Asks.add`). //! //! `qr.text` is [`cotton_core::vault::approval::scan_text`], never a link; `rows` are the symbol's modules, one string //! of `1` (dark) and `0` per row, for the shell to draw as squares with a quiet border of four. //! //! `approved`: the other device said yes; the claim is made and the credential it brings dropped (this device is //! signed in already). `sync: true` asks the shell for a pass, which brings the wrap; the next `screen` then answers //! `show: false` and the app opens as any device that holds the key. //! //! The ended states (`refused`, `ended` for three wrong codes, `timed_out`) wait for the person's `again`. `busy` //! (too many asks this hour) and `offline` are said and retried by the next `screen`. use std::sync::Mutex; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; use cotton_client::transport::object::ObjectAddress; use cotton_client::transport::{Exchange, SocketExchange}; use cotton_client::vault::devices::{self, DeviceKey}; use cotton_core::rules::shell_lines::resolve; use serde_json::{json, Value}; use crate::handle::CottonHandle; use crate::methods::MethodError; use crate::phone::signin_approval::{self, DeviceSigner}; pub const METHODS: [&str; 2] = ["gettingIn.again", "gettingIn.screen"]; /// How often the shell asks again while the page stands. pub const POLL_SECONDS: u64 = 3; /// The one ask this device waits on, and where it ended if it did. #[derive(Debug, Clone)] pub struct Wait { pub ask_id: String, pub nonce: [u8; 32], pub ended: Option<&'static str>, pub approved: bool, /// Looks since the approval with this device's key still not here: past [STALL_LOOKS] it says so. pub since_approved: u32, /// Whose wait this is: the number, this device and the key the ask named. A wait of another sign-in (signed out /// and in again, another number) is never shown: on the iPhone walk (23 Nov 2026) a fresh sign-in said "Your /// other device said yes" at once, from the approval of the sign-in before. pub owner: String, } /// The owner a request's wait must carry. fn owner_of(signer: &dyn DeviceSigner, request: &Value) -> String { let field = |name: &str| request.get(name).and_then(Value::as_str).unwrap_or_default().trim().to_string(); format!("{}|{}|{}", field("phone"), signer.device_id(), field("vaultKey")) } /// About two minutes of looks after the approval with no key: the other device said yes but never handed it over. pub const STALL_LOOKS: u32 = 40; /// This process's wait. pub fn slot() -> &'static Mutex> { static SLOT: std::sync::OnceLock>> = std::sync::OnceLock::new(); SLOT.get_or_init(|| Mutex::new(None)) } fn say(line: &str, fills: &[(&str, &str)]) -> String { resolve("signin", &format!("getting_in.{line}"), &[], fills).unwrap_or_default() } /// Whether this device waits for another to let it in: it holds no wrap of its own (its key row unwrapped, or not /// published at all) and another device's row holds a wrap. A device founding a vault nobody holds yet waits on /// nobody. /// /// **A ROW NOT PUBLISHED YET STILL WAITS** (GETTING IN, 26 Nov 2026). A new iPhone whose key publish never reached /// the account's copy held no row, so it did not "wait": `seal.status` said `joins` (no locked line, the page would /// ask) while the page needed this very row, and the phone sat on "Loading your data…" for ever with nowhere to give /// its recovery code. Waiting is told by the wrap alone; the shell publishes the key on `joins`, and the page's /// recovery code needs no published row. pub fn waits(this: Option<&str>, keys: &[DeviceKey]) -> bool { let Some(this) = this else { return false }; let mine = keys.iter().find(|key| key.device_id == this); let others_hold = keys.iter().any(|key| key.wrapped && key.device_id != this); mine.is_none_or(|me| !me.wrapped) && others_hold } /// What an empty list says on this device while it waits for another to let it in, or `None` when it does not wait: /// the slim line's words ("Your things from other devices aren't here yet."). Never "Loading your data…", which a /// waiting phone said for as long as it waited, with its sync up to date (walk on dev, 22 Nov 2026), nor "No notes yet". pub fn waiting_line(client: &crate::shell::client::ClientController) -> Option { let this = client.self_device_id(); let keys = client.with_file(|replica| devices::keys(replica.driver, replica.workspace_id)).ok()?; waits(this.as_deref(), &keys).then(|| say("slim", &[])) } pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result { call_with(handle, method, request, &SocketExchange) } pub fn call_with(handle: &CottonHandle, method: &str, request: &Value, exchange: &dyn Exchange) -> Result { let client = handle.client(); let this = client.self_device_id(); let keys = client.with_file(|replica| devices::keys(replica.driver, replica.workspace_id)).map_err(|reason| MethodError::new("unreadable", reason))?; if !waits(this.as_deref(), &keys) { if let Ok(mut held) = slot().lock() { *held = None; } return Ok(json!({ "show": false })); } let signer = client.receipt_signer_slot().get().cloned().ok_or_else(|| MethodError::new("device_key_unreadable", "this device has no device identity"))?; let mut request = request.clone(); if request.get("vaultKey").and_then(Value::as_str).is_none() { // The key the ask names: what this device published, as its own row holds it. let own = this.as_deref().and_then(|id| keys.iter().find(|key| key.device_id == id)).and_then(|key| key.public_key.clone()); if let Some(public) = client.vault_public().or(own) { request["vaultKey"] = json!(public); } } let address = ObjectAddress::open(text(&request, "server")?).map_err(|reason| MethodError::new("bad_request", reason))?; screen(slot(), &address, exchange, &signer, &request, method == "gettingIn.again") } fn text<'a>(request: &'a Value, field: &str) -> Result<&'a str, MethodError> { request.get(field).and_then(Value::as_str).map(str::trim).filter(|v| !v.is_empty()).ok_or_else(|| MethodError::new("bad_request", format!("`{field}` is missing"))) } /// The page, on a device that waits: poll the ask in `slot`, or make one (always, with `again`). pub fn screen(slot: &Mutex>, address: &ObjectAddress, exchange: &dyn Exchange, signer: &dyn DeviceSigner, request: &Value, again: bool) -> Result { let mut held = slot.lock().map_err(|_| MethodError::new("internal_error", "the wait is unreadable"))?; let owner = owner_of(signer, request); if again || held.as_ref().is_some_and(|wait| wait.owner != owner) { *held = None; } let Some(wait) = held.clone() else { return Ok(match make(address, exchange, signer, request) { Ok(wait) => { let page = page(&wait, "waiting", None, None); *held = Some(wait); page } Err(refusal) => trouble(&refusal), }); }; if let Some(ended) = wait.ended { return Ok(page(&wait, ended, None, None)); } let polled = match signin_approval::poll(address, exchange, signer, &wait.ask_id) { Ok(polled) => polled, Err(refusal) => return Ok(trouble(&refusal)), }; let state = polled["state"].as_str().unwrap_or("expired"); let left = polled["left"].as_str().map(str::to_string); match state { "waiting" => Ok(page(&wait, "waiting", polled["code"].as_str(), left.as_deref())), // Approved, and this page still stands: the key is not here yet (once it is, `waits` is false and the page // closes). It never says Approved (coordinator, 22 Nov 2026), and past STALL_LOOKS it says the key never came. "approved" | "used" => { let mut wait = wait; wait.approved = true; wait.since_approved += 1; if wait.since_approved > STALL_LOOKS { wait.ended = Some("stalled"); let said = page(&wait, "stalled", None, None); *held = Some(wait); return Ok(said); } let mut said = page(&wait, "approved", None, None); said["sync"] = json!(true); *held = Some(wait); Ok(said) } "refused" => { let ended = if polled["why"].as_str() == Some("wrong") { "ended" } else { "refused" }; let mut wait = wait; wait.ended = Some(ended); let said = page(&wait, ended, None, None); *held = Some(wait); Ok(said) } _ if wait.approved => { let mut wait = wait; wait.since_approved += 1; let state = if wait.since_approved > STALL_LOOKS { "stalled" } else { "approved" }; if state == "stalled" { wait.ended = Some("stalled"); } let said = page(&wait, state, None, None); *held = Some(wait); Ok(said) } _ => { let mut wait = wait; wait.ended = Some("timed_out"); let said = page(&wait, "timed_out", None, None); *held = Some(wait); Ok(said) } } } fn make(address: &ObjectAddress, exchange: &dyn Exchange, signer: &dyn DeviceSigner, request: &Value) -> Result { let asked = signin_approval::ask(address, exchange, signer, request)?; let ask_id = asked["askId"].as_str().ok_or_else(|| MethodError::new("refused", "the Worker sent no ask"))?.to_string(); let nonce: [u8; 32] = asked["handoff"]["nonce"] .as_str() .and_then(|n| URL_SAFE_NO_PAD.decode(n).ok()) .and_then(|bytes| bytes.try_into().ok()) .ok_or_else(|| MethodError::new("internal_error", "the ask kept no nonce"))?; Ok(Wait { ask_id, nonce, ended: None, approved: false, since_approved: 0, owner: owner_of(signer, request) }) } /// A refusal on the way: too many asks this hour, or no network. Said, and tried again by the next `screen`. fn trouble(refusal: &MethodError) -> Value { let state = if refusal.code == "too_many_asks" || refusal.code == "rate_limited" { "busy" } else { "offline" }; let mut said = acts(json!({ "show": true, "state": state, "heading": say("heading", &[]), "line": say(state, &[]), "qr": null, "code": null, "pollSeconds": POLL_SECONDS * 5 })); said["codeLine"] = json!(null); said } fn acts(mut said: Value) -> Value { said["noDevice"] = json!(say("no_device", &[])); said["signOut"] = json!(say("sign_out", &[])); said["later"] = json!(say("later", &[])); said["slim"] = json!(say("slim", &[])); said["slimAct"] = json!(say("slim_act", &[])); said["never"] = json!(say("never", &[])); // No other device?: what it opens, with the recovery code's act (the shell adds Ask {helper} where one is chosen). said["lost"] = json!({ "heading": say("lost_heading", &[]), "line": say("lost_line", &[]), "code": say("lost_code", &[]) }); said } /// The page for `state`: the square code and digits only while waiting. fn page(wait: &Wait, state: &str, code: Option<&str>, left: Option<&str>) -> Value { let waiting = state == "waiting"; let line = match state { "waiting" => say("line", &[]), "approved" => say("approved", &[]), other => say(other, &[]), }; let mut said = acts(json!({ "show": true, "state": state, "heading": say("heading", &[]), "line": line, "qr": if waiting { square(&wait.ask_id, &wait.nonce) } else { Value::Null }, "code": if waiting { code.map(|c| json!(c)).unwrap_or(Value::Null) } else { Value::Null }, "codeLine": if !waiting { Value::Null } else if code.is_some() { json!(say("digits_line", &[])) } else { json!(say("before_digits", &[])) }, "pollSeconds": POLL_SECONDS, })); if let Some(left) = left.filter(|_| waiting) { said["left"] = json!(left); } if matches!(state, "refused" | "ended" | "timed_out" | "stalled") { said["again"] = json!(say("again", &[])); } if state == "approved" { // Said yes, the key on its way: nothing left to choose but Sign out (iPhone walk, 23 Nov 2026). said["heading"] = json!(say("approved_heading", &[])); for gone in ["noDevice", "later", "lost", "never"] { if let Some(fields) = said.as_object_mut() { fields.remove(gone); } } } said } /// The square code for an ask: its text and the modules to draw. pub fn square(ask_id: &str, nonce: &[u8; 32]) -> Value { cotton_core::vault::approval::scan_symbol(ask_id, nonce).unwrap_or_else(|| { tracing::warn!("getting in: the square code could not be drawn"); Value::Null }) } #[cfg(test)] #[path = "getting_in_tests.rs"] mod tests;