//! 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::Engineas _;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};usecrate::handle::CottonHandle;usecrate::methods::MethodError;usecrate::phone::signin_approval::{self, DeviceSigner};pubconst METHODS: [&str; 2] = ["gettingIn.again", "gettingIn.screen"];/// How often the shell asks again while the page stands.pubconst POLL_SECONDS: u64 = 3;/// The one ask this device waits on, and where it ended if it did.#[derive(Debug, Clone)]pubstructWait {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: &dynDeviceSigner, 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.pubconst STALL_LOOKS: u32 = 40;/// This process's wait.pubfn slot() -> &'staticMutex<Option<Wait>> {static SLOT: std::sync::OnceLock<Mutex<Option<Wait>>> = 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.pubfn waits(this: Option<&str>, keys: &[DeviceKey]) -> bool {letSome(this) = this else { returnfalse };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".pubfn waiting_line(client: &crate::shell::client::ClientController) -> Option<String> {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", &[]))}pubfn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> { call_with(handle, method, request, &SocketExchange)}pubfn call_with(handle: &CottonHandle, method: &str, request: &Value, exchange: &dynExchange) -> Result<Value, MethodError> {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) {ifletOk(mut held) = slot().lock() { *held = None; }returnOk(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"))?;letmut 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());ifletSome(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`).pubfn screen(slot: &Mutex<Option<Wait>>, address: &ObjectAddress, exchange: &dynExchange, signer: &dynDeviceSigner, request: &Value, again: bool) -> Result<Value, MethodError> {letmut 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; }letSome(wait) = held.clone() else {returnOk(match make(address, exchange, signer, request) {Ok(wait) => {let page = page(&wait, "waiting", None, None); *held = Some(wait); page }Err(refusal) => trouble(&refusal), }); };ifletSome(ended) = wait.ended {returnOk(page(&wait, ended, None, None)); }let polled = match signin_approval::poll(address, exchange, signer, &wait.ask_id) {Ok(polled) => polled,Err(refusal) => returnOk(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" => {letmut 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);returnOk(said); }letmut 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" };letmut wait = wait; wait.ended = Some(ended);let said = page(&wait, ended, None, None); *held = Some(wait);Ok(said) } _ if wait.approved => {letmut 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) } _ => {letmut 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: &dynExchange, signer: &dynDeviceSigner, request: &Value) -> Result<Wait, MethodError> {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" };letmut 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, &[]), };letmut 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 } elseif code.is_some() { json!(say("digits_line", &[])) } else { json!(say("before_digits", &[])) },"pollSeconds": POLL_SECONDS, }));ifletSome(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"] {ifletSome(fields) = said.as_object_mut() { fields.remove(gone); } } } said}/// The square code for an ask: its text and the modules to draw.pubfn 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;