Cotton code
1271 lines · 68.0 KB · RustRaw
//! Cotton Secrets on this phone: the gate, people, the one-time check, sharing//! a secret with one of your people, who holds what, take back, a secret//! shared with you, and asking (assets/design/keys/DECISIONS.md, CONTRACT.md//! "The core calls each screen needs"). The list, one secret, add and edit,//! the generator and Health stay `vault.*` (`phone::vault_app`).//!//! **Sealed on the phone.** A share is two `p1:` boxes sealed here to the//! holder's sharing key (`keys::share`): the card, and the value at a version.//! The objects route them and count the value's fetches; neither can open one.//!//! **The giver's own record** (who holds which secret, a person's pinned key)//! is a note on the giver's own object, sealed here to the giver's own sharing//! key (`/v1/secret/note`), so every phone of theirs reads it and the object//! does not.//!//! **What reaches an answer.** A secret's value reaches only//! `secrets.shared.field`'s answer, to its one caller. Nothing of a value//! reaches a log line or a refusal.use std::collections::{BTreeMap, HashMap};use chrono::{DateTime, TimeZone, Utc};use serde_json::{json, Map, Value};use zeroize::Zeroizing;use cotton_core::keys::app::list::say;use cotton_core::keys::password_row;use cotton_core::keys::share::{self, Before, Facts, May, ShareCard, ShareValue, Side, Standing};use cotton_core::rules::shell_lines::LineSet;use cotton_core::seal::share::{key_from_text, key_text, open_from_person, seal_to_person};use cotton_core::vault::wrap::public_of;use cotton_core::vault::SecretPayload;use super::cotton_chat::{ask, e164, person_of};use cotton_client::transport::object::ObjectRefusal;use super::send_seal;use crate::methods::MethodError;use crate::phone::passwords::{json_row, SECRETS};use crate::shell::client::ClientController;/// Every method this module answers.pub const METHODS: &[&str] = &[    "secrets.gate",    "secrets.needs",    "secrets.people",    "secrets.person",    "secrets.check",    "secrets.check.confirm",    "secrets.check.scan",    "secrets.share.plan",    "secrets.share",    "secrets.holders",    "secrets.held",    "secrets.take.plan",    "secrets.take",    "secrets.changed",    "secrets.reshare",    "secrets.inbox",    "secrets.shared",    "secrets.shared.field",    "secrets.shared.remove",    "secrets.shared.longer",    "secrets.ask",    "secrets.asks",    "secrets.ask.answer",    "secrets.ask.no",    "secrets.ask.withdraw",    "secrets.import.plan",    "secrets.import",];/// The object's routes (meetings-comms builds them: CONTRACT.md "The Worker").mod routes {    pub const NOTE: &str = "/v1/secret/note";    pub const SHARE: &str = "/v1/secret/share";    pub const SHARE_UPDATE: &str = "/v1/secret/share/update";    pub const SHARE_TAKE: &str = "/v1/secret/share/take";    pub const SHARE_OUT: &str = "/v1/secret/share/out";    pub const SHARE_IN: &str = "/v1/secret/share/in";    pub const SHARE_VALUE: &str = "/v1/secret/share/value";    pub const SHARE_DROP: &str = "/v1/secret/share/drop";    pub const ASK: &str = "/v1/secret/ask";    pub const ASK_IN: &str = "/v1/secret/ask/in";    pub const ASK_ANSWER: &str = "/v1/secret/ask/answer";    pub const ASK_WITHDRAW: &str = "/v1/secret/ask/withdraw";    pub const ASK_OUT: &str = "/v1/secret/ask/out";    pub const PEOPLE: &str = "/v1/send/people";    pub const KEY: &str = "/v1/send/key";}pub fn call(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "secrets.gate" => gate(client, request),        "secrets.needs" => needs(client),        "secrets.people" => people(client),        "secrets.person" => person(client, request),        "secrets.check" => check(client, request),        "secrets.check.confirm" => check_confirm(client, request),        "secrets.check.scan" => check_scan(client, request),        "secrets.share.plan" => share_plan(client, request),        "secrets.share" => share_one(client, request),        "secrets.holders" => holders(client, request),        "secrets.held" => held(client),        "secrets.take.plan" => take_plan(client, request),        "secrets.take" => take(client, request),        "secrets.changed" => changed(client, request),        "secrets.reshare" => reshare(client, request),        "secrets.inbox" => inbox(client),        "secrets.shared" => shared(client, request),        "secrets.shared.field" => shared_field(client, request),        "secrets.shared.remove" => shared_remove(client, request),        "secrets.shared.longer" => shared_longer(client, request),        "secrets.ask" => ask_for(client, request),        "secrets.asks" => asks(client),        "secrets.ask.answer" => ask_answer(client, request),        "secrets.ask.no" => ask_no(client, request),        "secrets.ask.withdraw" => ask_withdraw(client, request),        "secrets.import.plan" => import_plan(request),        "secrets.import" => import(client, request),        other => Err(MethodError::new("unknown_method", format!("{other} is not a Secrets method"))),    }}// ── words and small helpers ────────────────────────────────────────────fn lines() -> &'static LineSet {    static LINES: std::sync::OnceLock<LineSet> = std::sync::OnceLock::new();    LINES.get_or_init(|| LineSet::shipped("secrets").expect("the kit ships the secrets line set"))}/// One of the `you` words, for `vault.settings` (You).pub(crate) fn you_line(key: &str) -> String {    s(&format!("you.{key}"))}/// The app's own name, as the `secrets` set says it.pub(crate) fn app_name() -> String {    s("app_name")}/// "1 secret" / "12 secrets", for You's Storage row.pub(crate) fn you_count(n: usize) -> String {    sf(if n == 1 { "you.count.one" } else { "you.count.other" }, &[("n", &n.to_string())])}fn s(line: &str) -> String {    say(lines(), line, &[])}fn sf(line: &str, fills: &[(&str, &str)]) -> String {    say(lines(), line, fills)}fn said(code: &str, line: &str, fills: &[(&str, &str)]) -> MethodError {    MethodError::new(code, sf(line, fills))}/// Whatever kept the server's answer away (offline, signed out, a Worker without the Secrets routes yet, a refusal),/// the person is told in the `secrets` words, never the transport's; the cause goes to the log. Seen on the iPhone on/// dev (25 Nov 2026): a screen said "nothing answers GET /v1/secret/note".fn refused(refusal: ObjectRefusal) -> MethodError {    tracing::warn!("secrets: the server did not answer as asked ({} {}: {})", refusal.status, refusal.code, refusal.message);    let (code, line) = match (refusal.status, refusal.code.as_str()) {        (_, "share_gone") => ("share_gone", "inbox.ended"),        (_, "not_your_people") => ("not_your_people", "net.not_your_people"),        (_, "not_connected") => ("not_connected", "net.signed_out"),        (0, _) | (_, "offline") => ("offline", "net.offline"),        (404 | 405 | 501, _) => ("not_ready", "net.not_ready"),        (500.., _) => ("server_busy", "net.busy"),        _ => ("refused", "net.refused"),    };    MethodError::new(code, s(line))}fn bad(field: &str, shape: &str) -> MethodError {    MethodError::new("bad_request", format!("{field} must be {shape}"))}fn text<'a>(request: &'a Value, field: &str) -> Result<&'a str, MethodError> {    request.get(field).and_then(Value::as_str).filter(|text| !text.is_empty()).ok_or_else(|| bad(field, "a non-empty string"))}fn number_in(request: &Value, field: &str) -> Result<String, MethodError> {    e164(text(request, field)?).ok_or_else(|| bad(field, "a phone number"))}fn fresh_id() -> String {    let mut bytes = [0u8; 16];    rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut bytes);    bytes.iter().map(|byte| format!("{byte:02x}")).collect()}fn ms(at: DateTime<Utc>) -> i64 {    at.timestamp_millis()}fn from_ms(value: &Value) -> Option<DateTime<Utc>> {    value.as_i64().and_then(|n| Utc.timestamp_millis_opt(n).single())}fn day_words(at: DateTime<Utc>) -> String {    at.format("%-d %b").to_string()}pub(crate) fn name_of(client: &ClientController, number: &str) -> String {    person_of(client, number).1.filter(|name| !name.trim().is_empty()).unwrap_or_else(|| number.to_string())}/// The number this person checked (S1) for a sharing key, from its own pins: who a sealed box is really from, whatever/// a server labels it (TRUSTED RECOVERY BUILD 2, review M1). None when no pin holds that key.pub(crate) fn pinned_number(notes: &BTreeMap<String, Value>, key: &[u8; 32]) -> Option<String> {    let text = key_text(key);    notes.iter().filter(|(slot, _)| slot.starts_with("pin:")).find(|(_, pin)| pin["key"].as_str() == Some(text.as_str())).and_then(|(_, pin)| pin["number"].as_str().map(str::to_string))}/// A number's name as this phone's own people list holds it (never as a server says it).pub(crate) fn own_name_of(client: &ClientController, number: &str) -> String {    name_of(client, number)}fn first_name(name: &str) -> String {    name.split_whitespace().next().unwrap_or(name).to_string()}fn times_words(n: u32) -> String {    if n == 1 { s("take.once") } else { sf("take.times", &[("n", &n.to_string())]) }}// ── the sharing key and the giver's own notes ──────────────────────────/// This person's sharing key on this phone (its public half posted), secret and public.pub(crate) fn me(client: &ClientController) -> Result<(Zeroizing<[u8; 32]>, [u8; 32]), MethodError> {    let secret = send_seal::post_key(client)?;    let public = public_of(&secret);    Ok((secret, public))}/// A person's sharing key as their object answers it, and this person's own number.fn their_key(client: &ClientController, number: &str) -> Result<([u8; 32], String), MethodError> {    let answer = ask(client, "GET", &format!("{}?number={}", routes::KEY, enc(number)), None).map_err(refused)?;    let key = answer["key"].as_str().and_then(key_from_text).ok_or_else(|| said("not_your_people", "share.not_your_people", &[]))?;    Ok((key, answer["me"].as_str().unwrap_or_default().to_string()))}pub(crate) fn note_context(key: &str) -> String {    format!("secret-note:{key}")}/// Every note of this person's, opened. A note that does not open as this/// person's own (sealed by anyone else) is left out.pub(crate) fn notes(client: &ClientController) -> Result<BTreeMap<String, Value>, MethodError> {    let (secret, public) = me(client)?;    let answer = ask(client, "GET", routes::NOTE, None).map_err(refused)?;    let mut out = BTreeMap::new();    for note in answer["notes"].as_array().into_iter().flatten() {        let (Some(key), Some(boxed)) = (note["key"].as_str(), note["box"].as_str()) else { continue };        let Ok(opened) = open_from_person(&secret, boxed, &note_context(key)) else { continue };        if opened.sender != public {            continue;        }        if let Ok(value) = serde_json::from_slice::<Value>(&opened.payload) {            out.insert(key.to_string(), value);        }    }    Ok(out)}pub(crate) fn put_note(client: &ClientController, key: &str, value: &Value) -> Result<(), MethodError> {    let (secret, public) = me(client)?;    let boxed = seal_to_person(&secret, &public, &note_context(key), &serde_json::to_vec(value).expect("a note serialises")).map_err(|error| MethodError::new(error.code(), error.to_string()))?;    ask(client, "PUT", routes::NOTE, Some(&json!({ "key": key, "box": boxed }))).map_err(refused)?;    Ok(())}pub(crate) fn pin_key(number: &str) -> String {    format!("pin:{}", share::key_print(&sha_of(number)))}fn sha_of(text: &str) -> [u8; 32] {    use sha2::Digest as _;    sha2::Sha256::digest(text.as_bytes()).into()}fn share_note_key(share: &str) -> String {    format!("share:{share}")}/// Where a person's key stands against the pin.#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Pin {    Never,    Checked,    Changed,}fn pin_of(notes: &BTreeMap<String, Value>, number: &str, key: &[u8; 32]) -> Pin {    match notes.get(&pin_key(number)).and_then(|pin| pin["key"].as_str()) {        None => Pin::Never,        Some(pinned) if pinned == key_text(key) => Pin::Checked,        Some(_) => Pin::Changed,    }}/// The giver's shares, from its notes, each with what its object says now.#[derive(Debug, Clone)]struct Out {    share: String,    secret_id: String,    number: String,    may: May,    version: u32,    facts: Facts,}fn outs(client: &ClientController, notes: &BTreeMap<String, Value>) -> Result<Vec<Out>, MethodError> {    let answer = ask(client, "GET", routes::SHARE_OUT, None).map_err(refused)?;    let live: HashMap<String, &Value> = answer["shares"].as_array().into_iter().flatten().filter_map(|row| Some((row["share"].as_str()?.to_string(), row))).collect();    let mut all = Vec::new();    for (key, note) in notes {        let Some(share) = key.strip_prefix("share:") else { continue };        let server = live.get(share).copied().cloned().unwrap_or(Value::Null);        let secret_id = note["secret_id"].as_str().unwrap_or_default().to_string();        all.push(Out {            share: share.to_string(),            secret_id: secret_id.clone(),            number: note["number"].as_str().unwrap_or_default().to_string(),            may: note["may"].as_str().and_then(May::parse).unwrap_or_default(),            version: note["version"].as_u64().unwrap_or(1) as u32,            facts: Facts {                delivered_at: from_ms(&server["delivered_at"]),                opens: server["opens"].as_u64().unwrap_or(0).max(note["opens"].as_u64().unwrap_or(0)) as u32,                last_open: from_ms(&server["last_open"]).or_else(|| from_ms(&note["last_open"])),                until: from_ms(&note["until"]),                taken_back_at: from_ms(&note["taken_back_at"]),                changed_at: from_ms(&note["changed_at"]),            },        });    }    Ok(all)}/// One secret this person gave that its holder still holds, as Remove and a person's page need it.#[derive(Debug, Clone)]pub(crate) struct HeldBy {    pub number: String,    pub secret_id: String,    pub title: String,    pub opened: bool,}/// AUDIT D: the secrets this person gave to any of `numbers` that are still held, read from the shares themselves/// (`secrets.held` names holders by first name only, so a number never matched there and Remove took nothing back)./// Nothing is asked of the server while no share was ever made; a share list that cannot be read is an error.pub(crate) fn held_by(client: &ClientController, numbers: &[String]) -> Result<Vec<HeldBy>, MethodError> {    // A phone with no sharing key never shared a secret: nothing to take back, and nothing is asked.    if send_seal::sharing(client).is_err() {        return Ok(Vec::new());    }    let notes = notes(client)?;    if !notes.keys().any(|k| k.starts_with("share:")) {        return Ok(Vec::new());    }    let names = own_names(client)?;    let now = client.now();    Ok(outs(client, &notes)?        .into_iter()        .filter(|out| numbers.contains(&out.number) && out.facts.standing(now) == Standing::Holds)        .map(|out| HeldBy { title: names.get(&out.secret_id).map(|(n, _)| n.clone()).unwrap_or_default(), opened: out.facts.opens > 0, number: out.number, secret_id: out.secret_id })        .collect())}// ── a secret of this person's own ──────────────────────────────────────#[derive(Debug, Clone)]struct Own {    id: String,    name: String,    kind: String,    site: Option<String>,    username: Option<String>,    row: Map<String, Value>,}fn own(client: &ClientController, id: &str) -> Result<Own, MethodError> {    let row = client        .with_file(|replica| {            let found = replica                .driver                .get(                    &format!("SELECT id, kind, name, site, username, value_enc, vmk_version FROM {SECRETS} WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL"),                    &[rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(id.into())],                )                .map_err(|error| error.to_string())?;            Ok(found.map(|row| json_row(&row)))        })        .map_err(|why| MethodError::new("unreadable", why))?        .ok_or_else(|| MethodError::new("secret_not_found", "That secret is not here any more."))?;    let get = |key: &str| row.get(key).and_then(Value::as_str).map(str::to_string).filter(|text| !text.is_empty());    Ok(Own { id: id.to_string(), name: get("name").or_else(|| get("site")).unwrap_or_default(), kind: get("kind").unwrap_or_else(|| "login".into()), site: get("site"), username: get("username"), row })}fn own_names(client: &ClientController) -> Result<HashMap<String, (String, String)>, MethodError> {    client        .with_file(|replica| {            let rows = replica                .driver                .all(&format!("SELECT id, name, site, kind FROM {SECRETS} WHERE workspace_id = ? AND trashed_at IS NULL"), &[rusqlite::types::Value::Text(replica.workspace_id.to_string())])                .map_err(|error| error.to_string())?;            Ok(rows                .iter()                .map(json_row)                .filter_map(|row| {                    let id = row.get("id")?.as_str()?.to_string();                    let name = row.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).or_else(|| row.get("site").and_then(Value::as_str)).unwrap_or_default().to_string();                    Some((id, (name, row.get("kind").and_then(Value::as_str).unwrap_or("login").to_string())))                })                .collect())        })        .map_err(|why| MethodError::new("unreadable", why))}fn opened(client: &ClientController, request: &Value, own: &Own) -> Result<SecretPayload, MethodError> {    crate::phone::passkeys::with_vmk(client, request, |vmk, _| password_row::open(&own.row, &own.id, vmk).map_err(|error| MethodError::new("does_not_open", error.to_string())))}// ── the gate ───────────────────────────────────────────────────────────/// `secrets.gate { passcode }`: Secrets opens only on a phone with a passcode/// or screen lock (DECISIONS.md question 14). The phone says whether it has one.fn gate(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let passcode = request.get("passcode").and_then(Value::as_bool).ok_or_else(|| bad("passcode", "true or false"))?;    if passcode {        // Unlock always has a way out (launch-ios, 25 Nov 2026): while this phone holds no key to the vault on it,        // the gate says so and offers Sign in (on a local copy, as after Sign out) and Getting in on a new phone.        if !crate::phone::vault::waits_for_key(client) {            return Ok(json!({ "open": true }));        }        let signed_in = client.signed_in();        let mut acts = Vec::new();        if !signed_in {            acts.push(json!({ "id": "sign_in", "label": s("gate.stuck_sign_in"), "method": "vault.act", "request": { "act": "sign_in" }, "tone": "accent" }));        }        acts.push(json!({ "id": "recovery", "label": s("gate.stuck_recovery"), "method": "vault.act", "request": { "act": "open_page", "page": "recovery" }, "tone": if signed_in { "accent" } else { "neutral" } }));        let line = if signed_in { "gate.stuck_waiting" } else { "gate.stuck_signed_out" };        return Ok(json!({ "open": true, "stuck": { "title": s("gate.stuck_title"), "line": s(line), "acts": acts } }));    }    Ok(json!({ "open": false, "needsPasscode": true, "title": s("gate.no_lock_title"), "line": s("gate.no_lock_body"), "act": { "id": "open_settings", "label": s("gate.no_lock_go"), "platform": "screen_lock_settings" } }))}// ── people and the check ───────────────────────────────────────────────/// Your people, each with whether they added this person back (accepted both ways). One who has not is listed and/// says so, and nothing is shared with or asked of them: the object drops a share to anyone not accepted both ways/// and answers ok all the same (send/secrets.ts WHO), so a share made then reached no one and said nothing (the/// Android Secrets walk, 26 Nov 2026).pub(crate) fn your_people_as_they_stand(client: &ClientController) -> Result<Vec<(String, bool)>, MethodError> {    Ok(your_people_named(client)?.into_iter().map(|(number, accepted, _)| (number, accepted)).collect())}/// [`your_people_as_they_stand`], with the name each gave themselves (the server's), for one not in his contacts.fn your_people_named(client: &ClientController) -> Result<Vec<(String, bool, Option<String>)>, MethodError> {    let mut answer = ask(client, "GET", routes::PEOPLE, None).map_err(refused)?;    super::circle::open_sealed(client, &mut answer);    Ok(answer["people"]        .as_array()        .into_iter()        .flatten()        .filter_map(|p| Some((p["number"].as_str()?.to_string(), p["waiting"].as_bool() != Some(true), p["name"].as_str().map(str::to_string))))        .collect())}/// Refused in words when `number` is one of your people who has not added this person back yet.fn accepted_or_said(client: &ClientController, number: &str) -> Result<(), MethodError> {    match your_people_as_they_stand(client)?.into_iter().find(|(n, _)| n == number) {        None => Err(said("not_your_people", "share.not_your_people", &[])),        Some((_, false)) => Err(said("not_accepted", "people.not_accepted_share", &[("name", &first_name(&name_of(client, number)))])),        Some((_, true)) => Ok(()),    }}fn people(client: &ClientController) -> Result<Value, MethodError> {    let given = your_people_named(client)?;    let standing: Vec<(String, bool)> = given.iter().map(|(number, accepted, _)| (number.clone(), *accepted)).collect();    let numbers: Vec<String> = standing.iter().map(|(number, _)| number.clone()).collect();    if numbers.is_empty() {        return Ok(json!({ "title": s("people.title"), "people": [], "empty": { "title": s("people.empty_title"), "line": s("people.empty_line") } }));    }    let notes = notes(client)?;    let outs = outs(client, &notes)?;    let now = client.now();    let theirs = inbox_rows(client)?;    let waiting = ask_rows(client)?;    let mut rows: Vec<Value> = numbers        .iter()        .map(|number| {            // Named by his contacts, else by the name they gave, marked (PEOPLE BUILD 1, C7).            let named = crate::phone::your_people::named(client, number, given.iter().find(|(n, _, _)| n == number).and_then(|(_, _, name)| name.as_deref()));            let name = named.shown.clone();            let holds = outs.iter().filter(|out| out.number == *number && out.facts.standing(now) == Standing::Holds).count();            let shares = theirs.iter().filter(|row| row.from == *number).count();            let asks = waiting.iter().filter(|row| row.from == *number && row.state == "waiting").count();            let checked = notes.contains_key(&pin_key(number));            let accepted = standing.iter().any(|(n, yes)| n == number && *yes);            let line = if !accepted { sf("people.not_accepted", &[("name", &first_name(&name))]) } else { match (holds, shares) {                (0, 0) => s("people.nothing"),                (h, 0) => if h == 1 { s("people.holds_one") } else { sf("people.holds_many", &[("n", &h.to_string())]) },                (0, t) => if t == 1 { s("people.shares_one") } else { sf("people.shares_many", &[("n", &t.to_string())]) },                (h, _) => if h == 1 { s("people.holds_one") } else { sf("people.holds_many", &[("n", &h.to_string())]) },            } };            json!({ "number": number, "name": name, "detail": named.detail(number), "inContacts": named.in_contacts, "line": line, "checked": checked, "holds": holds, "shares": shares, "waiting": asks > 0, "accepted": accepted })        })        .collect();    rows.sort_by(|a, b| (!a["waiting"].as_bool().unwrap_or(false), a["name"].as_str().unwrap_or_default().to_lowercase()).cmp(&(!b["waiting"].as_bool().unwrap_or(false), b["name"].as_str().unwrap_or_default().to_lowercase())));    Ok(json!({ "title": s("people.title"), "people": rows, "byPerson": s("people.by_person"), "bySecret": s("people.by_secret") }))}fn person(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let number = number_in(request, "number")?;    let name = name_of(client, &number);    let notes = notes(client)?;    let outs = outs(client, &notes)?;    let names = own_names(client)?;    let now = client.now();    let mine: Vec<&Out> = outs.iter().filter(|out| out.number == number).collect();    let row = |out: &Out| holder_row(out, names.get(&out.secret_id).map(|(n, _)| n.as_str()).unwrap_or_default(), now);    let now_rows: Vec<Value> = mine.iter().filter(|out| out.facts.standing(now) == Standing::Holds).map(|out| row(out)).collect();    let before: Vec<Value> = mine.iter().filter(|out| out.facts.standing(now) != Standing::Holds).map(|out| row(out)).collect();    let theirs: Vec<Value> = inbox_rows(client)?.into_iter().filter(|row| row.from == number).map(|row| json!({ "share": row.share, "title": row.card.name, "kind": row.card.kind })).collect();    let checked = notes.contains_key(&pin_key(&number));    // THE ASKS WAITING between the two (launch-ios's shape, 25 Nov 2026): what this person asked of them, with    // Withdraw; what they asked of this person, with Answer (the answer page, as `secrets.needs` opens it).    let mut asks: Vec<Value> = waiting_mine(client, &notes)        .into_iter()        .filter(|(_, to, _)| *to == number)        .map(|(id, _, what)| json!({ "id": id, "line": sf("people.asked_mine", &[("item", &what)]), "act": { "label": s("people.withdraw"), "method": "secrets.ask.withdraw", "request": { "ask": id } } }))        .collect();    let first = first_name(&name);    for row in ask_rows(client)?.into_iter().filter(|row| row.state == "waiting" && row.from == number) {        asks.push(json!({ "id": row.ask, "line": sf("people.asked_theirs", &[("name", &first), ("item", &row.what)]), "act": { "label": s("people.answer"), "method": "secrets.asks", "request": { "ask": row.ask } } }));    }    let take_all = (!now_rows.is_empty()).then(|| json!({ "label": sf("people.take_all", &[("n", &now_rows.len().to_string())]), "method": "secrets.take", "request": { "number": number, "all": true } }));    Ok(json!({        "number": number, "name": name, "checked": checked, "checkedLine": if checked { s("people.checked") } else { s("people.not_checked") },        "now": now_rows, "nowTitle": sf("people.now", &[("n", &mine.iter().filter(|out| out.facts.standing(now) == Standing::Holds).count().to_string())]),        "before": before, "beforeTitle": s("people.before"),        "theirs": theirs, "theirsTitle": s("people.theirs"), "none": s("people.none"),        "takeAll": take_all,        "asks": asks,    }))}/// `secrets.check { number }`: the six words and this phone's code, and where the person's key stands.fn check(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let number = number_in(request, "number")?;    let name = first_name(&name_of(client, &number));    let (_, mine) = me(client)?;    let (theirs, my_number) = their_key(client, &number)?;    let words = share::check_words(&Side { number: &my_number, key: &mine }, &Side { number: &number, key: &theirs });    let notes = notes(client)?;    let pin = pin_of(&notes, &number, &theirs);    Ok(json!({        "number": number, "title": sf("check.title", &[("name", &name)]), "line": sf("check.line", &[("name", &name)]),        "words": words, "wordsLine": s("check.words"), "a11y": sf("a11y.check_words", &[("words", &words.join(", "))]),        "qr": share::check_code(&Side { number: &my_number, key: &mine }),        "square": square_of(&share::check_code(&Side { number: &my_number, key: &mine })),        "scan": s("check.scan"), "show": s("check.show"), "match": s("check.match"), "noMatch": s("check.no_match"),        "checked": pin == Pin::Checked, "changed": pin == Pin::Changed,        "changedLine": (pin == Pin::Changed).then(|| sf("check.changed", &[("name", &name)])),    }))}/// The square code a phone draws for a text: its size in modules and one string per row of `1` (dark) and `0`,/// drawn with a quiet border of four modules, as Getting in's (`vault::approval::scan_symbol`).fn square_of(text: &str) -> Value {    match cotton_core::qr::encode_qr(text) {        Ok(matrix) => json!({ "text": text, "size": matrix.size, "rows": matrix.modules.iter().map(|row| row.iter().map(|dark| if *dark { '1' } else { '0' }).collect::<String>()).collect::<Vec<_>>() }),        Err(_) => Value::Null,    }}fn pin(client: &ClientController, number: &str, key: &[u8; 32]) -> Result<(), MethodError> {    put_note(client, &pin_key(number), &json!({ "number": number, "key": key_text(key), "checked_at": ms(client.now()) }))}/// `secrets.check.confirm { number }`: the six words matched; the key the object answers now is pinned.fn check_confirm(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let number = number_in(request, "number")?;    let name = first_name(&name_of(client, &number));    let (theirs, _) = their_key(client, &number)?;    pin(client, &number, &theirs)?;    Ok(json!({ "checked": true, "line": sf("check.done", &[("name", &name)]) }))}/// `secrets.check.scan { code }`: their code, scanned. It pins only a key the/// object also answers for that number; any difference is said, never pinned.fn check_scan(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let (number, scanned) = share::read_code(text(request, "code")?).ok_or_else(|| bad("code", "a Cotton Secrets check code"))?;    let name = first_name(&name_of(client, &number));    let (theirs, _) = their_key(client, &number)?;    if theirs != scanned {        return Ok(json!({ "checked": false, "number": number, "line": sf("check.mismatch", &[("name", &name)]) }));    }    pin(client, &number, &theirs)?;    Ok(json!({ "checked": true, "number": number, "line": sf("check.done", &[("name", &name)]) }))}// ── sharing ────────────────────────────────────────────────────────────fn until_words(until: Option<DateTime<Utc>>) -> String {    match until {        Some(at) => sf("holders.until_date", &[("date", &day_words(at))]),        None => s("holders.until_taken"),    }}fn opened_words(facts: &Facts) -> String {    match (facts.delivered_at, facts.opens) {        (_, 0) if facts.delivered_at.is_some() => s("holders.received"),        (_, 0) => s("holders.opened_never"),        (_, 1) => s("holders.opened_once"),        (_, n) => sf("holders.opened_many", &[("n", &n.to_string())]),    }}fn holder_row(out: &Out, secret_name: &str, now: DateTime<Utc>) -> Value {    let standing = out.facts.standing(now);    let may = if out.may == May::Copy { s("holders.copy") } else { s("holders.see") };    let line = match standing {        Standing::Holds => format!("{may} · {} · {}", until_words(out.facts.until), opened_words(&out.facts)),        Standing::StillKnown => s("holders.still_known"),        Standing::Ended | Standing::Changed => match out.facts.taken_back_at {            Some(at) => sf("holders.taken", &[("date", &day_words(at))]),            None => sf("holders.expired", &[("date", &day_words(out.facts.ended_at(now).unwrap_or(now)))]),        },    };    json!({        "share": out.share, "secretId": out.secret_id, "secret": secret_name, "number": out.number,        "may": out.may.as_str(), "until": out.facts.until.map(ms), "opens": out.facts.opens, "lastOpen": out.facts.last_open.map(ms),        "state": match standing { Standing::Holds => "holds", Standing::Ended => "ended", Standing::StillKnown => "still_known", Standing::Changed => "changed" },        "line": line,    })}/// `secrets.share.plan { id }`: whom it may go to, the levels and the expiries, in words.fn share_plan(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let own = own(client, text(request, "id")?)?;    if !share::shareable(&own.kind) {        return Err(said("not_shareable", "share.passkey", &[]));    }    let notes = notes(client)?;    // Only people who added this person back can be chosen (one who has not says so on People).    let people: Vec<Value> = your_people_as_they_stand(client)?        .into_iter()        .filter(|(_, accepted)| *accepted)        .map(|(number, _)| {            let name = name_of(client, &number);            let checked = notes.contains_key(&pin_key(&number));            json!({ "number": number, "name": name, "checked": checked, "line": if checked { s("people.checked") } else { sf("check.first", &[("name", &first_name(&name))]) } })        })        .collect();    let until: Vec<Value> = share::UNTIL_CHOICES.iter().map(|id| json!({ "id": id, "label": s(&format!("share.until_{id}")), "default": *id == "week" })).chain(std::iter::once(json!({ "id": "date", "label": s("share.until_date"), "default": false }))).collect();    Ok(json!({        "id": own.id, "title": sf("share.title", &[("secret", &own.name)]), "with": s("share.with"), "people": people,        "may": [{ "id": "see", "label": s("share.see"), "line": s("share.see_detail"), "default": false }, { "id": "copy", "label": s("share.copy"), "line": s("share.copy_detail"), "default": true }],        "mayTitle": s("share.may"), "until": until, "untilTitle": s("share.until"),        "empty": your_people_empty(),    }))}pub(crate) fn your_people_empty() -> Value {    json!({ "title": s("people.empty_title"), "line": s("people.empty_line") })}/// The card and value boxes for one holder, sealed here.fn sealed_pair(client: &ClientController, holder_key: &[u8; 32], share_id: &str, card: &ShareCard, value: &ShareValue) -> Result<(String, String), MethodError> {    let (secret, _) = me(client)?;    let seal = |context: String, bytes: Vec<u8>| seal_to_person(&secret, holder_key, &context, &bytes).map_err(|error| MethodError::new(error.code(), error.to_string()));    let card_box = seal(share::card_context(share_id), serde_json::to_vec(card).expect("a card serialises"))?;    let value_box = seal(share::value_context(share_id, value.version), serde_json::to_vec(value).expect("a value serialises"))?;    Ok((card_box, value_box))}/// The holder's key, refused unless it is the pinned one (S1).pub(crate) fn checked_key(client: &ClientController, notes: &BTreeMap<String, Value>, number: &str) -> Result<[u8; 32], MethodError> {    let name = first_name(&name_of(client, number));    let (key, _) = their_key(client, number)?;    match pin_of(notes, number, &key) {        Pin::Checked => Ok(key),        Pin::Never => Err(said("not_checked", "check.first", &[("name", &name)])),        Pin::Changed => Err(said("key_changed", "share.paused", &[("name", &name)])),    }}/// `secrets.share { id, number, may, until }`: sealed here to their pinned/// sharing key, posted as two boxes, and kept in this person's own notes.fn share_one(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let own = own(client, text(request, "id")?)?;    if !share::shareable(&own.kind) {        return Err(said("not_shareable", "share.passkey", &[]));    }    let number = number_in(request, "number")?;    accepted_or_said(client, &number)?;    let may = May::parse(request.get("may").and_then(Value::as_str).unwrap_or("copy")).ok_or_else(|| bad("may", "see or copy"))?;    let now = client.now();    let until = share::until_of(request.get("until").and_then(Value::as_str).unwrap_or("week"), now).map_err(|_| bad("until", "day, week, month, taken or a date to come"))?;    let notes = notes(client)?;    let key = checked_key(client, &notes, &number)?;    let payload = opened(client, request, &own)?;    let share_id = fresh_id();    let card = ShareCard { name: own.name.clone(), kind: own.kind.clone(), site: own.site.clone(), username: own.username.clone(), from_name: request.get("fromName").and_then(Value::as_str).map(str::to_string), may, until: until.map(|at| at.to_rfc3339()), fields: Some(share::filled(&payload)) };    let value = ShareValue { version: 1, payload };    let (card_box, value_box) = sealed_pair(client, &key, &share_id, &card, &value)?;    ask(client, "POST", routes::SHARE, Some(&json!({ "to": number, "share": share_id, "card": card_box, "value": value_box, "version": 1, "until": until.map(ms), "may_copy": may == May::Copy }))).map_err(refused)?;    put_note(client, &share_note_key(&share_id), &json!({ "secret_id": own.id, "number": number, "may": may.as_str(), "until": until.map(ms), "version": 1, "made_at": ms(now) }))?;    let name = first_name(&name_of(client, &number));    Ok(json!({ "share": share_id, "line": sf("share.done", &[("name", &name)]) }))}/// `secrets.holders { id }`: who holds one secret, and what each may do.fn holders(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = text(request, "id")?;    let own = own(client, id)?;    let notes = notes(client)?;    let now = client.now();    let mut rows: Vec<Value> = outs(client, &notes)?        .iter()        .filter(|out| out.secret_id == id)        .map(|out| {            let mut row = holder_row(out, &own.name, now);            row["name"] = json!(name_of(client, &out.number));            row        })        .collect();    rows.sort_by_key(|row| (row["state"] != "still_known", row["state"] != "holds", row["name"].as_str().unwrap_or_default().to_lowercase()));    let known: Vec<String> = rows.iter().filter(|row| row["state"] == "still_known").map(|row| first_name(row["name"].as_str().unwrap_or_default())).collect();    Ok(json!({ "id": id, "title": s("holders.title"), "holders": rows, "none": s("holders.none"), "stillKnown": still_known(client, request, &own, &known)? }))}/// The still-known block of a secret's page, when anyone may still know it.fn still_known(client: &ClientController, request: &Value, own: &Own, names: &[String]) -> Result<Value, MethodError> {    if names.is_empty() {        return Ok(Value::Null);    }    let start = token_start(client, request, own);    let (where_, url) = share::change_at(own.site.as_deref(), start.as_deref()).unwrap_or_else(|| (s("take.the_site"), None));    let joined = names.join(", ");    Ok(json!({        "title": sf("take.known_title", &[("names", &joined)]),        "stepsTitle": sf("take.steps_title", &[("where", &where_)]),        "steps": [            { "id": "open", "label": sf("take.step_open", &[("where", &where_)]), "url": url },            { "id": "make", "label": s("take.step_make") },            { "id": "paste", "label": s("take.step_paste"), "method": "vault.edit", "request": { "id": own.id } },        ],        "changed": { "label": s("take.changed"), "method": "secrets.changed", "request": { "id": own.id } },        "remind": { "label": s("take.remind"), "platform": "remind_tonight" },    }))}/// A token's first characters, for its provider: only while the vault is open, never kept.fn token_start(client: &ClientController, request: &Value, own: &Own) -> Option<String> {    if own.kind != "api_key" {        return None;    }    match opened(client, request, own) {        Ok(SecretPayload::ApiKey { key, .. }) => Some(key.chars().take(12).collect()),        _ => None,    }}/// `secrets.held`: every shared secret and its holders; still known first.fn held(client: &ClientController) -> Result<Value, MethodError> {    let notes = notes(client)?;    let names = own_names(client)?;    let now = client.now();    let mut by: BTreeMap<String, Vec<Out>> = BTreeMap::new();    for out in outs(client, &notes)? {        by.entry(out.secret_id.clone()).or_default().push(out);    }    let mut rows: Vec<Value> = by        .iter()        .filter_map(|(id, outs)| {            let (name, kind) = names.get(id)?.clone();            let holding: Vec<String> = outs.iter().filter(|out| out.facts.standing(now) == Standing::Holds).map(|out| first_name(&name_of(client, &out.number))).collect();            let known: Vec<String> = outs.iter().filter(|out| out.facts.standing(now) == Standing::StillKnown).map(|out| first_name(&name_of(client, &out.number))).collect();            if holding.is_empty() && known.is_empty() {                return None;            }            let line = if !known.is_empty() { if known.len() == 1 { sf("needs.known_one", &[("name", &known[0])]) } else { sf("needs.known_many", &[("n", &known.len().to_string())]) } } else { holding.join(", ") };            Some(json!({ "id": id, "title": name, "kind": kind, "line": line, "holders": holding, "stillKnown": !known.is_empty(), "act": (!known.is_empty()).then(|| json!({ "label": s("needs.known_act"), "method": "vault.item", "request": { "id": id } })) }))        })        .collect();    rows.sort_by_key(|row| (!row["stillKnown"].as_bool().unwrap_or(false), row["title"].as_str().unwrap_or_default().to_lowercase()));    let total = names.len();    let line = if rows.is_empty() { s("people.held_empty") } else { sf("people.held_count", &[("n", &rows.len().to_string()), ("total", &total.to_string())]) };    Ok(json!({ "rows": rows, "line": line }))}/// `secrets.take.plan { id, number? }`: what a take back will do, said/// only as far as the server saw (S5), and who else keeps it.fn take_plan(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let own = own(client, text(request, "id")?)?;    let notes = notes(client)?;    let now = client.now();    let live: Vec<Out> = outs(client, &notes)?.into_iter().filter(|out| out.secret_id == own.id && out.facts.standing(now) == Standing::Holds).collect();    let wanted = request.get("number").and_then(Value::as_str).and_then(e164);    let (picked, others): (Vec<&Out>, Vec<&Out>) = live.iter().partition(|out| wanted.as_ref().is_none_or(|number| out.number == *number));    let target = picked.first().ok_or_else(|| MethodError::new("not_shared", "That secret is not with them."))?;    let name = first_name(&name_of(client, &target.number));    let start = token_start(client, request, &own);    let where_ = share::change_at(own.site.as_deref(), start.as_deref()).map(|(where_, _)| where_).unwrap_or_else(|| s("take.the_site"));    let after = match share::before_take(&target.facts) {        Before::NeverReceived => sf("take.never", &[("name", &name)]),        Before::Received => sf("take.received", &[("name", &name), ("where", &where_)]),        Before::Opened(n) => sf("take.opened", &[("name", &name), ("times", &times_words(n)), ("where", &where_)]),    };    let others: Vec<Value> = others.iter().map(|out| { let other = first_name(&name_of(client, &out.number)); json!({ "number": out.number, "name": other, "line": sf("take.others", &[("name", &other)]), "detail": s("take.others_line"), "also": sf("take.go_too", &[("name", &other)]) }) }).collect();    Ok(json!({        "id": own.id, "number": target.number, "title": sf("take.title", &[("secret", &own.name), ("name", &name)]),        "does": s("take.does"), "after": after, "others": others, "go": s("take.go"),    }))}/// `secrets.take { id, numbers[] }` or `{ number, all: true }`: the boxes go/// on both objects at once; this person's note keeps when.fn take(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let notes = notes(client)?;    let now = client.now();    let all = outs(client, &notes)?;    let picked: Vec<&Out> = if request.get("all").and_then(Value::as_bool) == Some(true) {        let number = number_in(request, "number")?;        all.iter().filter(|out| out.number == number && out.facts.standing(now) == Standing::Holds).collect()    } else {        let id = text(request, "id")?;        let numbers: Vec<String> = request.get("numbers").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).filter_map(e164).collect();        if numbers.is_empty() {            return Err(bad("numbers", "one or more phone numbers"));        }        all.iter().filter(|out| out.secret_id == id && numbers.contains(&out.number) && out.facts.standing(now) == Standing::Holds).collect()    };    let mut lines = Vec::new();    for out in &picked {        ask(client, "POST", routes::SHARE_TAKE, Some(&json!({ "share": out.share }))).map_err(refused)?;        let mut note = notes.get(&share_note_key(&out.share)).cloned().unwrap_or_else(|| json!({}));        note["taken_back_at"] = json!(ms(now));        note["opens"] = json!(out.facts.opens);        note["last_open"] = json!(out.facts.last_open.map(ms));        note["delivered"] = json!(out.facts.delivered_at.is_some());        put_note(client, &share_note_key(&out.share), &note)?;        let name = first_name(&name_of(client, &out.number));        lines.push(if out.facts.delivered_at.is_none() { sf("take.done_never", &[("name", &name)]) } else { sf("take.done", &[("name", &name)]) });    }    Ok(json!({ "taken": picked.len(), "lines": lines }))}/// `secrets.changed { id }`: "I changed it". Every ended share of the secret/// that was still known is now done.fn changed(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = text(request, "id")?;    let notes = notes(client)?;    let now = client.now();    let mut done = Vec::new();    for out in outs(client, &notes)?.into_iter().filter(|out| out.secret_id == id && out.facts.standing(now) == Standing::StillKnown) {        let mut note = notes.get(&share_note_key(&out.share)).cloned().unwrap_or_else(|| json!({}));        note["changed_at"] = json!(ms(now));        put_note(client, &share_note_key(&out.share), &note)?;        done.push(first_name(&name_of(client, &out.number)));    }    let line = done.first().map(|name| sf("take.after", &[("name", name)]));    Ok(json!({ "changed": done.len(), "line": line }))}/// The question a save of a shared secret answers with (CONTRACT "Add and edit": `ask { line, yes, no, id }`), when/// someone still holds it; answered by `secrets.reshare`. Nothing when no one does, or the server can't be asked (the/// save stands either way, and the secret's page still offers I changed it).pub(crate) fn reshare_ask(client: &ClientController, id: &str) -> Option<Value> {    let notes = notes(client).ok()?;    let now = client.now();    let names: Vec<String> = outs(client, &notes)        .ok()?        .into_iter()        .filter(|out| out.secret_id == id && matches!(out.facts.standing(now), Standing::Holds))        .map(|out| first_name(&name_of(client, &out.number)))        .collect();    if names.is_empty() {        return None;    }    Some(json!({ "id": id, "line": sf("reshare.ask", &[("names", &names.join(", "))]), "yes": s("reshare.yes"), "no": s("reshare.no") }))}/// `secrets.reshare { id }`: a changed value goes to every holder who still/// may see it, at the next version; people taken back and ended shares get/// nothing. Also marks a still-known take back as changed.fn reshare(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let own = own(client, text(request, "id")?)?;    let payload = opened(client, request, &own)?;    let notes = notes(client)?;    let now = client.now();    let mut sent = Vec::new();    for out in outs(client, &notes)?.into_iter().filter(|out| out.secret_id == own.id) {        match out.facts.standing(now) {            Standing::Holds => {                let key = checked_key(client, &notes, &out.number)?;                let version = out.version + 1;                let card = ShareCard { name: own.name.clone(), kind: own.kind.clone(), site: own.site.clone(), username: own.username.clone(), from_name: None, may: out.may, until: out.facts.until.map(|at| at.to_rfc3339()), fields: Some(share::filled(&payload)) };                let (_, value_box) = sealed_pair(client, &key, &out.share, &card, &ShareValue { version, payload: payload.clone() })?;                ask(client, "POST", routes::SHARE_UPDATE, Some(&json!({ "share": out.share, "value": value_box, "version": version }))).map_err(refused)?;                let mut note = notes.get(&share_note_key(&out.share)).cloned().unwrap_or_else(|| json!({}));                note["version"] = json!(version);                put_note(client, &share_note_key(&out.share), &note)?;                sent.push(first_name(&name_of(client, &out.number)));            }            Standing::StillKnown => {                let mut note = notes.get(&share_note_key(&out.share)).cloned().unwrap_or_else(|| json!({}));                note["changed_at"] = json!(ms(now));                put_note(client, &share_note_key(&out.share), &note)?;            }            Standing::Ended | Standing::Changed => {}        }    }    // One holder "still has access", more "still have" (the line set's plural forms, by `n`).    let line = (!sent.is_empty()).then(|| sf("take.after_others", &[("names", &sent.join(", ")), ("n", &sent.len().to_string())]));    Ok(json!({ "sent": sent, "line": line }))}// ── shared with this person ────────────────────────────────────────────#[derive(Debug, Clone)]struct In {    share: String,    from: String,    card: ShareCard,    until: Option<DateTime<Utc>>,    may_copy: bool,}fn inbox_rows(client: &ClientController) -> Result<Vec<In>, MethodError> {    let (secret, _) = me(client)?;    let answer = ask(client, "GET", routes::SHARE_IN, None).map_err(refused)?;    let mut out = Vec::new();    for row in answer["shares"].as_array().into_iter().flatten() {        let (Some(share), Some(from), Some(boxed)) = (row["share"].as_str(), row["from"].as_str(), row["card"].as_str()) else { continue };        let Ok(opened) = open_from_person(&secret, boxed, &share::card_context(share)) else { continue };        let Ok(card) = serde_json::from_slice::<ShareCard>(&opened.payload) else { continue };        out.push(In { share: share.into(), from: from.into(), card, until: from_ms(&row["until"]), may_copy: row["may_copy"].as_bool().unwrap_or(false) });    }    Ok(out)}/// `secrets.inbox`: the secrets shared with this person, by their cards.fn inbox(client: &ClientController) -> Result<Value, MethodError> {    let rows: Vec<Value> = inbox_rows(client)?        .iter()        .map(|row| {            let name = first_name(&row.card.from_name.clone().unwrap_or_else(|| name_of(client, &row.from)));            json!({ "share": row.share, "title": row.card.name, "kind": row.card.kind, "group": cotton_core::keys::app::list::group_of(&row.card.kind), "from": row.from, "line": sf("inbox.from", &[("name", &name)]) })        })        .collect();    Ok(json!({ "rows": rows }))}fn one_in(client: &ClientController, share_id: &str) -> Result<In, MethodError> {    inbox_rows(client)?.into_iter().find(|row| row.share == share_id).ok_or_else(|| MethodError::new("share_gone", s("inbox.ended")))}/// `secrets.shared { share }`: one secret shared with this person: whose it/// is, what they may do and until when, its fields by name (values hidden).fn shared(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let row = one_in(client, text(request, "share")?)?;    let name = first_name(&row.card.from_name.clone().unwrap_or_else(|| name_of(client, &row.from)));    let fields: Vec<Value> = cotton_core::vault::SecretKind::parse(&row.card.kind)        .map(|kind| kind.spec().fields.iter().filter(|field| row.card.fields.as_ref().is_none_or(|held| held.iter().any(|name| name == field.name))).map(|field| json!({ "key": field.name, "label": crate::phone::vault_app::field_label(&row.card.kind, field.name), "concealed": true, "mono": crate::phone::vault_app::MONO.contains(&field.name) })).collect())        .unwrap_or_default();    // The user name and site travel on the card in the open, so they stand plain above the sealed fields, in the words    // the secret's own page uses.    let plain: Vec<Value> = [("username", "username", row.card.username.as_deref()), ("site", "website", row.card.site.as_deref())]        .into_iter()        .filter_map(|(key, word, value)| value.filter(|v| !v.trim().is_empty()).map(|v| json!({ "key": key, "label": crate::phone::vault_app::item_word(word), "value": v })))        .collect();    Ok(json!({        "share": row.share, "title": row.card.name, "kind": row.card.kind, "site": row.card.site, "username": row.card.username, "plain": plain,        "from": sf("inbox.from", &[("name", &name)]), "whose": sf("inbox.whose", &[("name", &name)]),        "may": if row.may_copy { s("inbox.may_copy") } else { s("inbox.may_see") }, "mayCopy": row.may_copy,        "until": match row.until { Some(at) => sf("inbox.until", &[("date", &day_words(at))]), None => sf("inbox.until_taken", &[("name", &name)]) },        "fields": fields, "offline": sf("inbox.offline", &[("name", &name)]),        "longer": { "label": sf("inbox.longer", &[("name", &name)]), "method": "secrets.shared.longer", "request": { "share": row.share } },        "remove": { "label": s("inbox.remove"), "method": "secrets.shared.remove", "request": { "share": row.share } },        "secure": !row.may_copy,    }))}/// `secrets.shared.field { share, field }`: the value, fetched from this/// person's object (which counts the open and tells the giver), opened here,/// never stored.fn shared_field(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let share_id = text(request, "share")?;    let field = text(request, "field")?;    let row = one_in(client, share_id)?;    let (secret, _) = me(client)?;    let answer = ask(client, "POST", routes::SHARE_VALUE, Some(&json!({ "share": share_id }))).map_err(refused)?;    let version = answer["version"].as_u64().unwrap_or(1) as u32;    let boxed = answer["value"].as_str().ok_or_else(|| MethodError::new("share_gone", s("inbox.ended")))?;    let opened = open_from_person(&secret, boxed, &share::value_context(share_id, version)).map_err(|error| MethodError::new(error.code(), error.to_string()))?;    let value: ShareValue = serde_json::from_slice(&opened.payload).map_err(|_| MethodError::new("does_not_open", "That share does not open."))?;    if value.version != version {        return Err(MethodError::new("does_not_open", "That share does not open."));    }    let fields = match serde_json::to_value(&value.payload) {        Ok(Value::Object(fields)) => fields,        _ => Map::new(),    };    let text = fields.get(field).and_then(Value::as_str).ok_or_else(|| bad("field", "a field of that secret"))?.to_string();    let clear_after = crate::phone::vault_app::preferences(client)?.clipboard_seconds;    Ok(json!({ "value": text, "mayCopy": row.may_copy, "clearAfter": if row.may_copy { clear_after } else { 0 }, "mono": true }))}fn shared_remove(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    ask(client, "POST", routes::SHARE_DROP, Some(&json!({ "share": text(request, "share")? }))).map_err(refused)?;    Ok(json!({ "removed": true }))}/// `secrets.shared.longer { share }`: an ask, to the giver, for longer.fn shared_longer(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let row = one_in(client, text(request, "share")?)?;    let what = format!("{} ({})", row.card.name, s("inbox.longer").replace(" {name}", ""));    send_ask(client, &row.from, &what, None, Some(&row.share))}// ── asking ─────────────────────────────────────────────────────────────#[derive(Debug, Clone)]struct AskRow {    ask: String,    from: String,    what: String,    why: Option<String>,    longer: Option<String>,    state: String,}fn send_ask(client: &ClientController, to: &str, what: &str, why: Option<&str>, longer: Option<&str>) -> Result<Value, MethodError> {    let (key, _) = their_key(client, to)?;    let (secret, _) = me(client)?;    let ask_id = fresh_id();    let boxed = seal_to_person(&secret, &key, &share::ask_context(&ask_id), &serde_json::to_vec(&json!({ "what": what, "why": why, "longer": longer })).expect("an ask serialises")).map_err(|error| MethodError::new(error.code(), error.to_string()))?;    ask(client, "POST", routes::ASK, Some(&json!({ "to": to, "ask": ask_id, "box": boxed }))).map_err(refused)?;    // The asker's own record, sealed to themselves: what they asked whom, so their person page says it waits.    put_note(client, &ask_note_key(&ask_id), &json!({ "to": to, "what": what, "at": ms(client.now()), "state": "waiting" }))?;    let name = first_name(&name_of(client, to));    Ok(json!({ "ask": ask_id, "line": sf("ask.waiting", &[("name", &name)]) }))}fn ask_note_key(ask: &str) -> String {    format!("ask:{ask}")}/// The asks this person sent that still wait: (ask, to, what), from their own notes, each state as the server last/// said it (`/ask/out`) where it answers, else as the note keeps it.fn waiting_mine(client: &ClientController, notes: &BTreeMap<String, Value>) -> Vec<(String, String, String)> {    let said: HashMap<String, String> = ask(client, "GET", routes::ASK_OUT, None)        .ok()        .map(|answer| answer["asks"].as_array().into_iter().flatten().filter_map(|row| Some((row["ask"].as_str()?.to_string(), row["state"].as_str()?.to_string()))).collect())        .unwrap_or_default();    notes        .iter()        .filter_map(|(key, note)| {            let id = key.strip_prefix("ask:")?;            let state = said.get(id).map(String::as_str).or(note["state"].as_str()).unwrap_or("waiting");            (state == "waiting").then(|| (id.to_string(), note["to"].as_str().unwrap_or_default().to_string(), note["what"].as_str().unwrap_or_default().to_string()))        })        .collect()}/// `secrets.ask.withdraw { ask }`: take back an ask this person sent. The server drops it from the other side's/// list; the asker's note says withdrawn, so it waits no more.fn ask_withdraw(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = text(request, "ask")?;    let notes = notes(client)?;    let mut note = notes.get(&ask_note_key(id)).cloned().ok_or_else(|| MethodError::new("ask_gone", s("ask.none")))?;    ask(client, "POST", routes::ASK_WITHDRAW, Some(&json!({ "ask": id }))).map_err(refused)?;    note["state"] = json!("withdrawn");    put_note(client, &ask_note_key(id), &note)?;    let name = first_name(&name_of(client, note["to"].as_str().unwrap_or_default()));    Ok(json!({ "withdrawn": true, "line": sf("people.withdrawn", &[("name", &name)]) }))}/// `secrets.ask { number, text, why? }`: ask one of your people for a secret,/// from Secrets or from a Comms chat (`thread` stands for the number there).fn ask_for(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let number = match request.get("thread").and_then(Value::as_str) {        Some(thread) => crate::phone::cotton_chat::thread_number(client, thread)?,        None => number_in(request, "number")?,    };    accepted_or_said(client, &number)?;    send_ask(client, &number, text(request, "text")?, request.get("why").and_then(Value::as_str).filter(|why| !why.trim().is_empty()), None)}fn ask_rows(client: &ClientController) -> Result<Vec<AskRow>, MethodError> {    let (secret, _) = me(client)?;    let answer = ask(client, "GET", routes::ASK_IN, None).map_err(refused)?;    let mut out = Vec::new();    for row in answer["asks"].as_array().into_iter().flatten() {        let (Some(id), Some(from), Some(boxed)) = (row["ask"].as_str(), row["from"].as_str(), row["box"].as_str()) else { continue };        let Ok(opened) = open_from_person(&secret, boxed, &share::ask_context(id)) else { continue };        let Ok(body) = serde_json::from_slice::<Value>(&opened.payload) else { continue };        out.push(AskRow {            ask: id.into(),            from: from.into(),            what: body["what"].as_str().unwrap_or_default().to_string(),            why: body["why"].as_str().map(str::to_string),            longer: body["longer"].as_str().map(str::to_string),            state: row["state"].as_str().unwrap_or("waiting").to_string(),        });    }    Ok(out)}/// The secret an ask most likely means: every word of the ask that begins a/// word of the secret's name or site counts; the most wins.fn suggest(client: &ClientController, what: &str) -> Result<Option<(String, String)>, MethodError> {    let words: Vec<String> = what.to_lowercase().split(|c: char| !c.is_alphanumeric()).filter(|w| w.len() > 1).map(str::to_string).collect();    let mut best: Option<(usize, String, String)> = None;    for (id, (name, kind)) in own_names(client)? {        if !share::shareable(&kind) {            continue;        }        let folded = name.to_lowercase();        let parts: Vec<&str> = folded.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).collect();        let score = words.iter().filter(|word| parts.iter().any(|part| part.starts_with(word.as_str()))).count();        if score > 0 && best.as_ref().is_none_or(|(top, _, _)| score > *top) {            best = Some((score, id, name));        }    }    Ok(best.map(|(_, id, name)| (id, name)))}/// `secrets.asks`: what this person's people asked for, each with the secret it probably means.fn asks(client: &ClientController) -> Result<Value, MethodError> {    let rows: Vec<Value> = ask_rows(client)?        .into_iter()        .filter(|row| row.state == "waiting")        .map(|row| {            let name = first_name(&name_of(client, &row.from));            let suggested = row.longer.as_ref().and_then(|_| None::<(String, String)>).or_else(|| suggest(client, &row.what).ok().flatten());            json!({                "ask": row.ask, "from": row.from, "title": sf("ask.asks", &[("name", &name)]), "what": row.what, "why": row.why, "longer": row.longer.is_some(),                "line": sf("needs.ask", &[("name", &name), ("what", &row.what)]),                "suggest": suggested.map(|(id, title)| json!({ "id": id, "title": title, "line": s("ask.suggest"), "change": s("ask.change") })),                "share": sf("ask.share", &[("name", &name)]), "no": s("ask.no"), "reply": s("ask.reply"),                "until": "day",            })        })        .collect();    Ok(json!({ "rows": rows, "none": s("ask.none") }))}/// `secrets.ask.answer { ask, id, may, until }`: an ordinary share, and the ask answered.fn ask_answer(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let ask_id = text(request, "ask")?;    let row = ask_rows(client)?.into_iter().find(|row| row.ask == ask_id).ok_or_else(|| MethodError::new("ask_gone", s("ask.none")))?;    let mut onward = request.clone();    onward["number"] = json!(row.from);    if onward.get("until").is_none() {        onward["until"] = json!("day");    }    let shared = share_one(client, &onward)?;    ask(client, "POST", routes::ASK_ANSWER, Some(&json!({ "ask": ask_id, "state": "shared" }))).map_err(refused)?;    Ok(shared)}/// `secrets.ask.no { ask }`: they are told only that the answer was no.fn ask_no(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    ask(client, "POST", routes::ASK_ANSWER, Some(&json!({ "ask": text(request, "ask")?, "state": "no" }))).map_err(refused)?;    Ok(json!({ "answered": true }))}// ── above the list ─────────────────────────────────────────────────────/// `secrets.needs`: what sits above the list, only when there is something:/// an ask waiting, a secret still known after a take back, a person whose key/// changed. Health stays `vault.items`' own line.fn needs(client: &ClientController) -> Result<Value, MethodError> {    let mut rows = Vec::new();    for row in ask_rows(client)?.into_iter().filter(|row| row.state == "waiting") {        let name = first_name(&name_of(client, &row.from));        rows.push(json!({ "kind": "ask", "line": sf("needs.ask", &[("name", &name), ("what", &row.what)]), "act": { "label": s("needs.ask_act"), "method": "secrets.asks", "request": { "ask": row.ask } } }));    }    let notes = notes(client)?;    let names = own_names(client)?;    let now = client.now();    let mut known: BTreeMap<String, Vec<String>> = BTreeMap::new();    for out in outs(client, &notes)?.into_iter().filter(|out| out.facts.standing(now) == Standing::StillKnown) {        known.entry(out.secret_id.clone()).or_default().push(first_name(&name_of(client, &out.number)));    }    for (id, people) in known {        let Some((title, _)) = names.get(&id) else { continue };        let line = if people.len() == 1 { sf("needs.known_one", &[("name", &people[0])]) } else { sf("needs.known_many", &[("n", &people.len().to_string())]) };        rows.push(json!({ "kind": "still_known", "title": title, "line": line, "act": { "label": s("needs.known_act"), "method": "vault.item", "request": { "id": id } } }));    }    Ok(json!({ "rows": rows }))}// ── bringing in from Dashlane ──────────────────────────────────────────fn export_files(request: &Value) -> Result<Vec<(String, String)>, MethodError> {    let files: Vec<(String, String)> = request        .get("files")        .and_then(Value::as_array)        .into_iter()        .flatten()        .filter_map(|file| Some((file["name"].as_str().unwrap_or("file").to_string(), file["csv"].as_str()?.to_string())))        .collect();    if files.is_empty() {        return Err(bad("files", "one or more { name, csv }"));    }    Ok(files)}/// `secrets.import.plan { files: [{ name, csv }] }`: what a whole Dashlane/// export holds, counted by kind, and what does not come across, said before/// anything lands.fn import_plan(request: &Value) -> Result<Value, MethodError> {    let read = cotton_core::keys::dashlane::read(&export_files(request)?);    let n = read.items.len();    let vault = cotton_core::keys::app::list::lines();    // Counted by the list's groups (an ID and a note are both Notes), the largest first, as the drawing's 212, 14, 3.    let mut groups: Vec<(String, usize)> = Vec::new();    for (kind, count) in &read.counts {        let group = cotton_core::keys::app::list::group_of(kind).to_string();        match groups.iter_mut().find(|(g, _)| *g == group) {            Some((_, n)) => *n += *count,            None => groups.push((group, *count)),        }    }    groups.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));    let kinds: Vec<Value> = groups.iter().map(|(group, count)| json!({ "group": group, "kind": group, "count": count, "label": say(vault, &format!("chips.{group}"), &[]) })).collect();    Ok(json!({        "title": s("import.title"), "steps": s("import.steps"),        "found": sf("import.found", &[("n", &n.to_string())]), "kinds": kinds,        "lost": s("import.lost"), "go": (n > 0).then(|| sf("import.go", &[("n", &n.to_string())])),        "after": s("import.after"), "skipped": read.skipped.len(), "unknown": read.unknown,        "notDashlane": (n == 0).then(|| s("import.not_dashlane")),    }))}/// `secrets.import { files }`: every item sealed here under the vault key, in one write.fn import(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let read = cotton_core::keys::dashlane::read(&export_files(request)?);    if read.items.is_empty() {        return Err(said("not_dashlane", "import.not_dashlane", &[]));    }    let answer = crate::phone::passkeys::with_vmk(client, request, |vmk, version| {        let answer = client.write_rows("secrets.import", &mut |ctx| crate::phone::passwords::landed(ctx, vmk, version, &read.items, &[])).map_err(|why| MethodError::new("write_refused", why))?;        Ok(crate::authoring::own_answer(answer))    })?;    let imported = answer["imported"].as_array().map_or(0, Vec::len);    Ok(json!({ "imported": imported, "held": answer["held"], "skipped": read.skipped.len(), "after": s("import.after") }))}fn enc(text: &str) -> String {    text.bytes()        .map(|b| match b {            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),            _ => format!("%{b:02X}"),        })        .collect()}#[cfg(test)]#[path = "secrets_app_tests.rs"]mod tests;