Cotton code
199 lines · 10.2 KB · RustRaw
//! `recovery.screen`: each trusted recovery screen whole, so a shell draws it and writes no word of its own (TRUSTED//! RECOVERY on main, 28 Nov 2026; the drafts are TRUSTED-RECOVERY.md §7, A to H). Each screen is made from what the//! circle methods already answer (`recovery.status`, `recovery.circleHeld`, `recovery.circleAsks`, `recovery.circleWait`),//! with the screen's own words, and names the method each button calls.//!//! ```text//! recovery.screen {screen: "circle", privateKey?}  → A, G, H: choose who helps (the person, on a device holding the vault)//!     {heading, intro, now?, choicesTitle, choices: [{id, k, n, label, note?, default}], peopleTitle,//!      people: [{number, name, checked, line, check?}], empty?, why, ask, act: "recovery.circleSet",//!      gone: [{name, line, again}], pending?, request?, screenLock?}//! recovery.screen {screen: "help"}                 → B, E: a helper's phone//!     {heading, asked: [{account, setup, name, title, body, accept, decline}], helping: [{name, line}],//!      asks: [{…recovery.circleAsks' ask, title, steps: [3 lines]}], nextAt?, nextLine?, empty?}//! recovery.screen {screen: "back", privateKey?}    → C, D, G: a new phone with no other device//!     no recovery under way: {state: "choose", heading, options: [{id: "code"|"helpers", title, line, act}]}//!     waiting:               {state: "waiting", heading, line, helpers, told, endsAt}//!     opened:                {state: "opened", heading, line, again, act: "recovery.screen circle"}//! recovery.screen {screen: "stop"}                 → F: any device of the person while a recovery waits//!     {show: false} | {show: true, heading, line, note, stop, act: "recovery.circleStop"}//! ```use serde_json::{json, Value};use super::recovery::{check_act, say};use crate::methods::MethodError;use crate::shell::client::ClientController;pub const METHODS: [&str; 1] = ["recovery.screen"];pub(crate) fn call(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    if method != "recovery.screen" {        return Err(MethodError::new("unknown_method", format!("`{method}` is not a recovery screen method")));    }    match request.get("screen").and_then(Value::as_str).unwrap_or_default() {        "circle" => circle(client, request),        "help" => help(client),        "back" => back(client, request),        "stop" => stop(client, request),        other => Err(MethodError::new("bad_screen", format!("no recovery screen {other:?}: circle, help, back or stop"))),    }}/// A: choose who helps; G's Choose again opens it; H's lines name who can help no more.fn circle(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let status = super::recovery::call_on(client, "recovery.status", request)?;    let circle = status.get("circle").cloned().unwrap_or(Value::Null);    let notes = super::secrets_app::notes(client)?;    // Only people who added this person back can hold a piece, as for sharing a password.    let people: Vec<Value> = super::secrets_app::your_people_as_they_stand(client)?        .into_iter()        .filter(|(_, accepted)| *accepted)        .map(|(number, _)| {            let name = super::secrets_app::name_of(client, &number);            let checked = notes.contains_key(&super::secrets_app::pin_key(&number));            json!({                "number": number, "name": name, "checked": checked,                "line": if checked { say("screen_people_checked", &[]) } else { say("help_not_checked", &[]) },                "check": if checked { Value::Null } else { check_act(&number) },            })        })        .collect();    let gone: Vec<Value> = circle        .get("members")        .and_then(Value::as_array)        .into_iter()        .flatten()        .filter(|m| m["state"] == json!("gone"))        .map(|m| {            let name = m["name"].as_str().filter(|n| !n.is_empty()).or_else(|| m["number"].as_str()).unwrap_or_default().to_string();            json!({ "name": name, "line": say("screen_helper_gone", &[("name", &name)]), "again": say("screen_choose_else", &[]) })        })        .collect();    let mut screen = json!({        "heading": say("screen_circle_heading", &[]),        "intro": say("screen_circle_intro", &[]),        "now": circle.get("line").filter(|l| l.as_str().is_some_and(|l| !l.is_empty())).cloned(),        "choicesTitle": say("screen_circle_how_many", &[]),        "choices": [            { "id": "two_of_three", "k": 2, "n": 3, "label": say("screen_circle_two_of_three", &[]), "note": say("screen_circle_recommended", &[]), "default": true },            { "id": "one", "k": 1, "n": 1, "label": say("screen_circle_one", &[]), "default": false },        ],        "peopleTitle": say("screen_circle_people", &[]),        "why": say("screen_circle_why", &[]),        "ask": say("screen_circle_ask", &[]),        "act": "recovery.circleSet",        "gone": gone,        "pending": circle.get("pending").cloned().unwrap_or(Value::Null),        "request": circle.get("request").cloned().unwrap_or(Value::Null),        "screenLock": circle.get("screenLock").cloned().unwrap_or(Value::Null),    });    if people.is_empty() {        screen["empty"] = super::secrets_app::your_people_empty();    }    screen["people"] = json!(people);    Ok(screen)}/// B and E: the people who asked this one to help, and the requests to help someone back in now.fn help(client: &ClientController) -> Result<Value, MethodError> {    let held = super::recovery_circle::call(client, "recovery.circleHeld", &json!({}))?;    let asks = super::recovery_circle::call(client, "recovery.circleAsks", &json!({}))?;    let list = |v: &Value, key: &str| v.get(key).and_then(Value::as_array).cloned().unwrap_or_default();    let name_in = |v: &Value| v["name"].as_str().filter(|n| !n.is_empty()).unwrap_or_default().to_string();    let asked: Vec<Value> = list(&held, "held")        .into_iter()        .filter(|h| h["accepted"] != json!(true))        .map(|h| {            let name = name_in(&h);            json!({                "account": h.get("account"), "setup": h.get("setup"), "name": name,                "title": say("screen_asked_title", &[("name", &name)]), "body": say("screen_asked_body", &[("name", &name)]),                "line": h.get("line"), "accept": h.get("accept"), "decline": h.get("decline"),                "acceptAct": "recovery.circleAccept", "declineAct": "recovery.circleDecline",            })        })        .collect();    let helping: Vec<Value> = list(&held, "held").into_iter().filter(|h| h["accepted"] == json!(true)).map(|h| json!({ "name": name_in(&h), "line": h.get("line") })).collect();    let now: Vec<Value> = list(&asks, "asks")        .into_iter()        .map(|mut a| {            let name = name_in(&a);            if let Some(o) = a.as_object_mut() {                o.insert("title".into(), json!(say("screen_helping_title", &[("name", &name)])));                o.insert("steps".into(), json!([say("screen_helping_step_call", &[("name", &name)]), say("screen_helping_step_read", &[]), say("screen_helping_step_type", &[])]));                o.insert("approveAct".into(), json!("recovery.circleApprove"));                o.insert("stopAct".into(), json!("recovery.circleStopFor"));            }            a        })        .collect();    let mut screen = json!({        "heading": say("screen_help_heading", &[]),        "nextAt": asks.get("nextAt").cloned().unwrap_or(Value::Null),        "nextLine": asks.get("nextLine").cloned().unwrap_or(Value::Null),    });    if asked.is_empty() && helping.is_empty() && now.is_empty() {        screen["empty"] = json!(say("screen_help_empty", &[]));    }    screen["asked"] = json!(asked);    screen["helping"] = json!(helping);    screen["asks"] = json!(now);    Ok(screen)}/// C, D and G on a new phone. Without this device's key (behind its screen lock) only the choice is drawn.fn back(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let choose = || {        json!({            "state": "choose",            "heading": say("screen_back_none", &[]),            "options": [                { "id": "code", "title": say("screen_back_code", &[]), "line": say("screen_back_code_line", &[]), "act": "recovery.open" },                { "id": "helpers", "title": say("screen_back_helpers", &[]), "line": say("screen_back_helpers_line", &[]), "act": "recovery.circleStart" },            ],        })    };    if request.get("privateKey").is_none() {        return Ok(choose());    }    let wait = super::recovery_circle::call(client, "recovery.circleWait", request)?;    if wait["opened"] == json!(true) {        return Ok(json!({ "state": "opened", "heading": say("screen_back_in", &[]), "line": say("screen_back_in_line", &[]), "again": say("screen_choose_again", &[]), "act": "recovery.screen", "actScreen": "circle" }));    }    if wait["state"] != json!("waiting") {        let mut screen = choose();        // A recovery stopped says so above the choice; one never started says nothing.        if wait["state"] == json!("stopped") {            screen["line"] = wait["line"].clone();        }        return Ok(screen);    }    Ok(json!({        "state": "waiting",        "heading": say("screen_back_heading", &[]),        "line": wait["line"],        "helpers": wait["helpers"],        "endsAt": wait["endsAt"],        "told": say("screen_back_told", &[]),    }))}/// F: a recovery under way, on any device of the person, with Stop.fn stop(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let status = super::recovery::call_on(client, "recovery.status", request)?;    let Some(under_way) = status.get("circle").and_then(|c| c.get("request")).filter(|r| r.is_object()) else {        return Ok(json!({ "show": false }));    };    Ok(json!({        "show": true,        "heading": say("screen_stop_heading", &[]),        "line": under_way["line"],        "note": say("screen_stop_note", &[]),        "stop": under_way["stop"],        "endsAt": under_way["endsAt"],        "act": "recovery.circleStop",    }))}// Tested end to end in recovery_circle_tests.rs (`each_screen_is_drawn_whole_from_the_core`), on the circle's own stand-in.