Cotton code
1617 lines · 88.7 KB · RustRaw
//! Cotton Vault on this phone: the screens' methods, answered from the//! phone's own copy in the shapes `cotton_core::keys::app::shapes` publishes//! (the vault core's `shapes.md` says them in prose).//!//! ```text//! vault.items vault.item vault.field vault.code vault.history vault.edit//! vault.save vault.generate vault.security vault.settings vault.act vault.look//! ```//!//! Everything a person can do is the existing core's: the writes are//! `keys.add`/`keys.change`/`keys.favourite`/`keys.restore`, a reveal is//! `password.reveal`, a code `keys.code`, history `keys.history`, health//! `keys.health`, the waiting card and windows `unlock.*`, recovery//! `recovery.status`. This module decides what each screen SAYS around them.//! **No secret value reaches an answer here** but `vault.field`'s,//! `vault.code`'s and `vault.history`'s, each to its one caller, and none//! reaches a log line or a refusal.//!//! Speed (2,000 items, release): the list reads the plain columns once, by//! one query, and decides in memory; health marks are computed once per//! change of the rows while the vault is open, and kept in memory by the//! rows' fingerprint, never on disk.use std::collections::HashMap;use std::sync::{Arc, Mutex};use serde_json::{json, Map, Value};use cotton_core::keys::app::list::{self, say, Ask, Entry};use cotton_core::keys::app::look::Look;use cotton_core::keys::app::shapes::*;use cotton_core::keys::generator::{strength, Random, Recipe, Words, WORDS_MAX, WORDS_MIN};use cotton_core::keys::health::OLD_DAYS;use cotton_core::keys::history::TRASH_DAYS;use cotton_core::keys::password_row;use cotton_core::rules::shell_lines::LineSet;use cotton_core::vault::payload::{SecretKind, SECRET_KINDS};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; 13] = [    "vault.act",    "vault.breach",    "vault.code",    "vault.edit",    "vault.field",    "vault.generate",    "vault.history",    "vault.item",    "vault.items",    "vault.look",    "vault.save",    "vault.security",    "vault.settings",];/// Where this device keeps Vault's own choices (lock, clipboard, appearance).pub const PREFERENCES: &str = "vault-preferences.json";/// The passkey rows' table, as the passkeys family names it.const PASSKEYS: &str = "cotton_passkey";/// Lock choices, in minutes (0: straight away).pub const LOCK_CHOICES: [u32; 5] = [0, 1, 5, 15, 60];/// Clipboard choices, in seconds (0: never).pub const CLIPBOARD_CHOICES: [u32; 5] = [30, 60, 90, 120, 0];/// Fields a screen keeps hidden until presence: the kind's secrets.const CONCEALED: &[(&str, &str)] = &[    ("login", "password"),    ("api_key", "key"),    ("card", "number"),    ("card", "cvv"),    ("identity", "number"),    ("document", "password"),    ("code", "secret"),    ("wifi", "password"),];/// Fields drawn in the mono face.pub(crate) const MONO: &[&str] = &["password", "key", "number", "cvv", "secret", "totp"];/// What a sign-in or passkey sheet asks the open host (`signin.*`): the handle's/// own exchange on a phone, a stub in a test. `None` when this phone has none.pub type Remote<'a> = &'a dyn Fn(&str, &Value) -> Result<Value, MethodError>;pub fn call(client: &ClientController, method: &str, request: &Value, remote: Option<Remote<'_>>) -> Result<Value, MethodError> {    let answer = match method {        "vault.items" => serde_json::to_value(items(client, request)?),        "vault.item" => serde_json::to_value(item(client, text(request, "id")?)?),        "vault.field" => serde_json::to_value(field(client, request)?),        "vault.code" => serde_json::to_value(code(client, request)?),        "vault.history" => serde_json::to_value(history(client, request)?),        "vault.edit" => serde_json::to_value(edit(client, request)?),        "vault.save" => {            // A secret someone holds, changed: ask whether the new one goes to them (launch-ios's walk, 25 Nov 2026:            // the change saved and never reached the holder, since nothing asked).            let mut answer = serde_json::to_value(save(client, request)?).map_err(|error| MethodError::new("unanswerable", error.to_string()))?;            if let Some(ask) = request.get("id").and_then(Value::as_str).and_then(|id| crate::phone::secrets_app::reshare_ask(client, id)) {                answer["ask"] = ask;            }            Ok(answer)        }        "vault.generate" => serde_json::to_value(generate(request, preferences(client)?.clipboard_seconds)?),        "vault.security" => serde_json::to_value(security(client, request, remote)?),        "vault.breach" => serde_json::to_value(breach(client, request)?),        "vault.settings" => serde_json::to_value(settings(client, request)?),        "vault.act" => serde_json::to_value(act(client, request)?),        "vault.look" => serde_json::to_value(Look::shipped()),        other => return Err(MethodError::new("unknown_method", format!("`{other}` is not a vault screen"))),    };    answer.map_err(|error| MethodError::new("unanswerable", error.to_string()))}// ── small helpers ──────────────────────────────────────────────────────fn lines() -> &'static LineSet {    list::lines()}fn s(line: &str) -> String {    say(lines(), line, &[])}fn sf(line: &str, fills: &[(&str, &str)]) -> String {    say(lines(), line, fills)}fn bad(field: &str, shape: &str) -> MethodError {    MethodError::new("bad_request", format!("`{field}` is {shape}"))}fn text<'a>(request: &'a Value, field: &str) -> Result<&'a str, MethodError> {    request.get(field).and_then(Value::as_str).filter(|value| !value.trim().is_empty()).ok_or_else(|| bad(field, "required text"))}fn optional<'a>(request: &'a Value, field: &str) -> Option<&'a str> {    request.get(field).and_then(Value::as_str).map(str::trim).filter(|value| !value.is_empty())}fn act_of(id: &str, label: String, method: &str, request: Value) -> Act {    Act { id: id.into(), label, method: method.into(), request, presence: false, confirm: None, tone: Tone::Neutral, symbol: None, input: None }}fn with_presence(mut act: Act) -> Act {    act.presence = true;    act}fn with_symbol(mut act: Act, symbol: &str) -> Act {    act.symbol = Some(symbol.into());    act}fn unreadable(reason: String) -> MethodError {    MethodError::new("unreadable", reason)}/// The lent key, passed on to the family that opens the vault, and nothing else.fn lent(request: &Value, mut onward: Value) -> Value {    if let Some(key) = request.get("privateKey").filter(|key| !key.is_null()) {        onward["privateKey"] = key.clone();    }    onward}/// Whether the vault is open on this device now (the five-minute unlock).fn is_open(client: &ClientController) -> bool {    client.vault().ok().is_some_and(|door| door.until(client.now()).is_some())}fn day_of(iso: &str) -> String {    chrono::DateTime::parse_from_rfc3339(iso).map(|at| at.format("%-d %b %Y").to_string()).unwrap_or_else(|_| iso.to_string())}fn days_since(client: &ClientController, iso: &str) -> Option<u64> {    let at = chrono::DateTime::parse_from_rfc3339(iso).ok()?;    Some((client.now() - at.with_timezone(&chrono::Utc)).num_days().max(0) as u64)}// ── the preferences (this device's) ────────────────────────────────────/// Vault's choices on this device: lock after (minutes), clipboard (seconds), appearance.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]#[serde(rename_all = "camelCase", default)]pub struct Preferences {    pub lock_minutes: u32,    pub clipboard_seconds: u32,    /// `system`, `light` or `dark`.    pub appearance: String,}impl Default for Preferences {    fn default() -> Self {        Preferences { lock_minutes: 5, clipboard_seconds: CLIPBOARD_SECONDS, appearance: "system".into() }    }}static PREFERENCES_LOCK: Mutex<()> = Mutex::new(());fn preferences_path(client: &ClientController) -> std::path::PathBuf {    client.layout().client_dir().join(PREFERENCES)}pub fn preferences(client: &ClientController) -> Result<Preferences, MethodError> {    match std::fs::read(preferences_path(client)) {        Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| unreadable(format!("{PREFERENCES}: {error}"))),        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Preferences::default()),        Err(error) => Err(unreadable(format!("{PREFERENCES}: {error}"))),    }}fn set_preference(client: &ClientController, key: &str, value: &Value) -> Result<Preferences, MethodError> {    let _guard = PREFERENCES_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner());    let mut prefs = preferences(client)?;    match key {        "lockMinutes" => {            let n = value.as_u64().filter(|n| LOCK_CHOICES.contains(&(*n as u32))).ok_or_else(|| bad("value", "one of the lock choices"))?;            prefs.lock_minutes = n as u32;        }        "clipboardSeconds" => {            let n = value.as_u64().filter(|n| CLIPBOARD_CHOICES.contains(&(*n as u32))).ok_or_else(|| bad("value", "one of the clipboard choices"))?;            prefs.clipboard_seconds = n as u32;        }        "appearance" => {            let mode = value.as_str().filter(|mode| ["system", "light", "dark"].contains(mode)).ok_or_else(|| bad("value", "system, light or dark"))?;            prefs.appearance = mode.into();        }        _ => return Err(bad("key", "lockMinutes, clipboardSeconds or appearance")),    }    let path = preferences_path(client);    if let Some(parent) = path.parent() {        std::fs::create_dir_all(parent).map_err(|error| MethodError::new("unwritable", format!("{PREFERENCES}: {error}")))?;    }    let partial = path.with_extension(format!("json.{}.partial", std::process::id()));    // not a copy: vault files.    std::fs::write(&partial, serde_json::to_vec_pretty(&prefs).expect("preferences serialise")).map_err(|error| MethodError::new("unwritable", format!("{PREFERENCES}: {error}")))?;    // not a copy: vault files.    std::fs::rename(&partial, &path).map_err(|error| MethodError::new("unwritable", format!("{PREFERENCES}: {error}")))?;    Ok(prefs)}fn copied_toast(seconds: u32) -> String {    if seconds == 0 { s("item.copied_plain") } else { sf("item.copied", &[("n", &seconds.to_string())]) }}// ── reading the rows ───────────────────────────────────────────────────/// One secret row's plain columns, as the screens read them.#[derive(Debug, Clone, Default)]struct Plain {    entry: Entry,    changed_at: Option<String>,    created_at: Option<String>,    updated_at: Option<String>,    uses: i64,    passkey_id: Option<String>,    trashed_at: Option<String>,    sealed_here: bool,}const PLAIN: &str = "id, kind, name, site, username, favourite_at, last_used_at, changed_at, created_at, updated_at, uses, passkey_id, trashed_at, (value_enc IS NOT NULL AND value_enc LIKE 'v2:%') AS opens";fn plain_of(row: &Map<String, Value>) -> Plain {    let get = |key: &str| row.get(key).and_then(Value::as_str).map(str::to_string).filter(|text| !text.is_empty());    Plain {        entry: Entry {            id: get("id").unwrap_or_default(),            kind: get("kind").unwrap_or_else(|| "login".into()),            title: get("name").or_else(|| get("site")).unwrap_or_default(),            site: get("site"),            username: get("username"),            favourite: get("favourite_at").is_some(),            last_used: get("last_used_at"),            passkey: get("passkey_id").is_some(),            in_bin: get("trashed_at").is_some(),            second: None,        },        changed_at: get("changed_at"),        created_at: get("created_at"),        updated_at: get("updated_at"),        uses: row.get("uses").and_then(Value::as_i64).unwrap_or(0),        passkey_id: get("passkey_id"),        trashed_at: get("trashed_at"),        sealed_here: row.get("opens").and_then(Value::as_i64).unwrap_or(0) == 1,    }}fn holds(replica: &crate::shell::file::ReadFile<'_>, table: &str) -> Result<bool, String> {    Ok(replica.driver.get("SELECT 1 AS found FROM sqlite_master WHERE type = 'table' AND name = ?", &[rusqlite::types::Value::Text(table.into())]).map_err(|error| error.to_string())?.is_some())}type Rows = (Vec<Plain>, Vec<Map<String, Value>>);/// The plain rows last read, per database, by the fingerprint they were read at.static ROWS: Mutex<Option<HashMap<String, (String, Arc<Rows>)>>> = Mutex::new(None);/// The rows, from memory while nothing changed, else read and kept.fn rows_cached(client: &ClientController) -> Result<Arc<Rows>, MethodError> {    let database = client.reading_database_id().unwrap_or_default();    // The reader's own change stamp: any commit to the file, from any connection, changes it.    let print = client.with_file(|replica| Ok(format!("{}#{:?}", replica.workspace_id, replica.driver.change_stamp().map_err(|error| error.to_string())?))).map_err(unreadable)?;    if let Some((held, rows)) = ROWS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().and_then(|map| map.get(&database)) {        if *held == print {            return Ok(rows.clone());        }    }    let rows = Arc::new(read_rows(client)?);    ROWS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get_or_insert_with(HashMap::new).insert(database, (print, rows.clone()));    Ok(rows)}/// Every secret (live and binned) and every passkey no login carries, owned.fn all_rows(client: &ClientController) -> Result<Rows, MethodError> {    Ok((*rows_cached(client)?).clone())}fn read_rows(client: &ClientController) -> Result<Rows, MethodError> {    client        .with_file(|replica| {            let ws = vec![rusqlite::types::Value::Text(replica.workspace_id.to_string())];            let secrets = if holds(replica, SECRETS)? {                replica.driver.all(&format!("SELECT {PLAIN} FROM {SECRETS} WHERE workspace_id = ?"), &ws).map_err(|error| error.to_string())?.iter().map(|row| plain_of(&json_row(row))).collect()            } else {                Vec::new()            };            let passkeys = if holds(replica, PASSKEYS)? {                replica                    .driver                    .all(&format!("SELECT id, rp_id, rp_name, user_name, last_used_at, created_at, uses FROM {PASSKEYS} WHERE workspace_id = ? AND deleted_at IS NULL"), &ws)                    .map_err(|error| error.to_string())?                    .iter()                    .map(json_row)                    .collect()            } else {                Vec::new()            };            Ok((secrets, passkeys))        })        .map_err(unreadable)}fn entries(secrets: &[Plain], passkeys: &[Map<String, Value>]) -> Vec<Entry> {    let carried: std::collections::HashSet<&str> = secrets.iter().filter(|plain| !plain.entry.in_bin).filter_map(|plain| plain.passkey_id.as_deref()).collect();    let mut all: Vec<Entry> = secrets.iter().map(|plain| plain.entry.clone()).collect();    for passkey in passkeys {        let id = passkey.get("id").and_then(Value::as_str).unwrap_or_default();        if carried.contains(id) {            continue;        }        let rp = passkey.get("rp_id").and_then(Value::as_str).unwrap_or_default();        all.push(Entry {            id: id.into(),            kind: "passkey".into(),            title: passkey.get("rp_name").and_then(Value::as_str).filter(|name| !name.is_empty()).unwrap_or(rp).to_string(),            site: Some(rp.to_string()).filter(|rp| !rp.is_empty()),            username: passkey.get("user_name").and_then(Value::as_str).map(str::to_string),            favourite: false,            last_used: passkey.get("last_used_at").and_then(Value::as_str).map(str::to_string),            passkey: true,            in_bin: false,            second: None,        });    }    all}// ── health, kept in memory by the rows' fingerprint ────────────────────/// One health reading: each login's findings, and the counts.#[derive(Debug, Clone, Default)]struct Reading {    marks: HashMap<String, Vec<String>>,    breach_counts: HashMap<String, u64>,    reused_with: HashMap<String, usize>,    age_days: HashMap<String, u64>,}static HEALTH: Mutex<Option<HashMap<String, (String, Reading)>>> = Mutex::new(None);fn fingerprint(client: &ClientController, secrets: &[Plain]) -> String {    let newest = secrets.iter().filter_map(|plain| plain.updated_at.as_deref().or(plain.changed_at.as_deref())).max().unwrap_or_default();    let version = client.vault().ok().and_then(|door| door.version(client.now())).unwrap_or(0);    format!("{}|{}|{}|{}", secrets.len(), newest, version, client.now().format("%Y-%m-%d"))}/// The health reading: the full one while the vault is open (weak, reused,/// old), else `old` alone from the plain date. `None` key means locked.fn reading(client: &ClientController, secrets: &[Plain], request: &Value) -> Result<(Reading, bool), MethodError> {    let (mut found, open) = health_reading(client, secrets, request)?;    let breaches = breaches(client)?;    for plain in secrets.iter().filter(|plain| !plain.entry.in_bin) {        if let Some(seen) = breaches.standing(plain) {            found.marks.entry(plain.entry.id.clone()).or_default().insert(0, "breached".into());            found.breach_counts.insert(plain.entry.id.clone(), seen);        }    }    Ok((found, open))}fn health_reading(client: &ClientController, secrets: &[Plain], request: &Value) -> Result<(Reading, bool), MethodError> {    let lent_key = request.get("privateKey").is_some_and(|key| !key.is_null());    if !(is_open(client) || lent_key) {        let mut plain = Reading::default();        // RFC 3339 instants in UTC compare as text: one cutoff, no date parsed per row.        let cutoff = (client.now() - chrono::Duration::days(OLD_DAYS as i64)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);        for row in secrets.iter().filter(|row| row.entry.kind == "login" && !row.entry.in_bin) {            let Some(at) = row.changed_at.as_deref().or(row.created_at.as_deref()) else { continue };            if at >= cutoff.as_str() {                continue;            }            if let Some(age) = days_since(client, at) {                if age >= OLD_DAYS {                    plain.marks.entry(row.entry.id.clone()).or_default().push("old".into());                    plain.age_days.insert(row.entry.id.clone(), age);                }            }        }        return Ok((plain, false));    }    let key = format!("{}:{}", client.reading_database_id().unwrap_or_default(), fingerprint(client, secrets));    {        let held = HEALTH.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        if let Some((print, found)) = held.as_ref().and_then(|map| map.get(&client.reading_database_id().unwrap_or_default())) {            if *print == key {                return Ok((found.clone(), true));            }        }    }    let answer = crate::phone::keys::over(client, "keys.health", &lent(request, json!({})))?;    let mut fresh = Reading::default();    for finding in answer["findings"].as_array().into_iter().flatten() {        let Some(id) = finding["id"].as_str() else { continue };        let mut marks = Vec::new();        if finding["weak"] == json!(true) {            marks.push("weak".to_string());        }        let reused = finding["reused_with"].as_array().map_or(0, Vec::len);        if reused > 0 {            marks.push("reused".to_string());            fresh.reused_with.insert(id.into(), reused);        }        if finding["old"] == json!(true) {            marks.push("old".to_string());        }        if let Some(age) = finding["age_days"].as_u64() {            fresh.age_days.insert(id.into(), age);        }        if !marks.is_empty() {            fresh.marks.insert(id.into(), marks);        }    }    HEALTH.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get_or_insert_with(HashMap::new).insert(client.reading_database_id().unwrap_or_default(), (key, fresh.clone()));    Ok((fresh, true))}// ── breaches: the last check's findings, on this device only ───────────/// Where this device keeps the last breach check: which items were found and/// how often, each with the password-changed stamp it was found at, so a/// password changed since stops being called breached. Never synced, no value.pub const BREACHES: &str = "vault-breaches.json";#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]#[serde(rename_all = "camelCase", default)]pub struct Breaches {    /// Per database: when it was last checked, and what was found.    pub databases: HashMap<String, Checked>,}#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]#[serde(rename_all = "camelCase", default)]pub struct Checked {    pub checked_at: String,    /// id → (times seen, `changed_at` when found).    pub found: HashMap<String, (u64, Option<String>)>,    #[serde(skip)]    pub here: bool,}impl Checked {    /// The count while this item's password is the one that was checked.    fn standing(&self, plain: &Plain) -> Option<u64> {        let (seen, at) = self.found.get(&plain.entry.id)?;        (at.as_deref() == plain.changed_at.as_deref().or(plain.created_at.as_deref())).then_some(*seen)    }}static BREACHES_LOCK: Mutex<()> = Mutex::new(());fn breaches_path(client: &ClientController) -> std::path::PathBuf {    client.layout().client_dir().join(BREACHES)}fn all_breaches(client: &ClientController) -> Result<Breaches, MethodError> {    match std::fs::read(breaches_path(client)) {        Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| unreadable(format!("{BREACHES}: {error}"))),        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Breaches::default()),        Err(error) => Err(unreadable(format!("{BREACHES}: {error}"))),    }}/// This database's last check (empty, `here: false`, when never checked).fn breaches(client: &ClientController) -> Result<Checked, MethodError> {    let mut all = all_breaches(client)?;    Ok(all.databases.remove(&client.reading_database_id().unwrap_or_default()).map(|mut checked| {        checked.here = true;        checked    }).unwrap_or_default())}fn keep_breaches(client: &ClientController, checked: Checked) -> Result<(), MethodError> {    let _guard = BREACHES_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner());    let mut all = all_breaches(client)?;    all.databases.insert(client.reading_database_id().unwrap_or_default(), checked);    let path = breaches_path(client);    if let Some(parent) = path.parent() {        std::fs::create_dir_all(parent).map_err(|error| MethodError::new("unwritable", format!("{BREACHES}: {error}")))?;    }    let partial = path.with_extension(format!("json.{}.partial", std::process::id()));    // not a copy: vault files.    std::fs::write(&partial, serde_json::to_vec(&all).expect("breaches serialise")).map_err(|error| MethodError::new("unwritable", format!("{BREACHES}: {error}")))?;    // not a copy: vault files.    std::fs::rename(&partial, &path).map_err(|error| MethodError::new("unwritable", format!("{BREACHES}: {error}")))}/// `vault.breach {privateKey?}` → the ranges to ask (`platform.action:/// fetch_ranges`); `vault.breach {ranges: {prefix: body}, privateKey?}` → the/// check read and kept. Only five SHA-1 characters per password ever leave the/// phone, padded, and only when the person runs the check.fn breach(client: &ClientController, request: &Value) -> Result<ActAnswer, MethodError> {    let Some(ranges) = request.get("ranges").filter(|ranges| !ranges.is_null()) else {        let asked = crate::phone::keys::over(client, "keys.breachPrefixes", &lent(request, json!({})))?;        return Ok(ActAnswer {            act: "breach".into(),            id: None,            toast: None,            item: None,            gone: false,            platform: Some(json!({                "action": "fetch_ranges",                "prefixes": asked["prefixes"],                "addresses": asked["addresses"],                "headers": {"Add-Padding": "true"},                "then": "vault.breach",            })),        });    };    let checked = crate::phone::keys::over(client, "keys.breachCheck", &lent(request, json!({"ranges": ranges})))?;    let (secrets, _) = all_rows(client)?;    let stamp = |id: &str| secrets.iter().find(|plain| plain.entry.id == id).and_then(|plain| plain.changed_at.clone().or_else(|| plain.created_at.clone()));    let found: HashMap<String, (u64, Option<String>)> = checked["breached"]        .as_array()        .into_iter()        .flatten()        .filter_map(|hit| {            let id = hit["id"].as_str()?;            Some((id.to_string(), (hit["count"].as_u64().unwrap_or(1), stamp(id))))        })        .collect();    let unread = checked["unread"].as_array().map_or(0, Vec::len);    let n = found.len();    keep_breaches(client, Checked { checked_at: client.now_iso(), found, here: true })?;    let text = if unread > 0 {        s("security.breach_unread")    } else if n == 0 {        s("security.breach_none")    } else {        sf("security.breach_found", &[("n", &n.to_string())])    };    Ok(ActAnswer { act: "breach".into(), id: None, toast: Some(Toast { text, undo: None }), item: None, gone: false, platform: None })}// ── vault.items ────────────────────────────────────────────────────────fn items(client: &ClientController, request: &Value) -> Result<ItemsAnswer, MethodError> {    let rows = rows_cached(client)?;    let (secrets, passkeys) = (&rows.0, &rows.1);    let (health, open) = reading(client, secrets, &json!({}))?;    let filter = optional(request, "kind").or_else(|| optional(request, "filter")).unwrap_or("all");    let ask = Ask { filter: filter.into(), q: request.get("q").and_then(Value::as_str).unwrap_or_default().into(), after: optional(request, "after").map(str::to_string) };    let mut all = entries(secrets, passkeys);    if open {        let seconds = second_lines(client, secrets)?;        for entry in &mut all {            entry.second = seconds.get(&entry.id).cloned();        }    }    Ok(list::items(&all, &health.marks, &ask, open))}/// Each card's, token's and file's second line, worked out from its opened/// value while the vault is open, and kept in memory only, by the rows'/// fingerprint (DECISIONS.md S2: the server writes no hint, the phone says/// it). A row that does not open here has none.static SECONDS: Mutex<Option<HashMap<String, (String, Arc<HashMap<String, String>>)>>> = Mutex::new(None);fn second_lines(client: &ClientController, secrets: &[Plain]) -> Result<Arc<HashMap<String, String>>, MethodError> {    let database = client.reading_database_id().unwrap_or_default();    let print = fingerprint(client, secrets);    if let Some((held, seconds)) = SECONDS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().and_then(|map| map.get(&database)) {        if *held == print {            return Ok(seconds.clone());        }    }    let wanted: Vec<&Plain> = secrets.iter().filter(|plain| plain.sealed_here && !plain.entry.in_bin && list::SECOND_KINDS.contains(&plain.entry.kind.as_str())).collect();    let mut seconds = HashMap::new();    if !wanted.is_empty() {        let ids: Vec<String> = wanted.iter().map(|plain| plain.entry.id.clone()).collect();        let rows = client            .with_file(|replica| {                let marks = vec!["?"; ids.len()].join(", ");                let mut args = vec![rusqlite::types::Value::Text(replica.workspace_id.to_string())];                args.extend(ids.iter().map(|id| rusqlite::types::Value::Text(id.clone())));                let found = replica.driver.all(&format!("SELECT id, value_enc, vmk_version FROM {SECRETS} WHERE workspace_id = ? AND id IN ({marks})"), &args).map_err(|error| error.to_string())?;                Ok(found.iter().map(json_row).collect::<Vec<_>>())            })            .map_err(unreadable)?;        crate::phone::passkeys::with_vmk(client, &json!({}), |vmk, _| {            for row in &rows {                let id = row.get("id").and_then(Value::as_str).unwrap_or_default();                if let Ok(payload) = password_row::open(row, id, vmk) {                    if let Some(line) = list::second_line(list::lines(), &payload) {                        seconds.insert(id.to_string(), line);                    }                }            }            Ok(())        })?;    }    let seconds = Arc::new(seconds);    SECONDS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get_or_insert_with(HashMap::new).insert(database, (print, seconds.clone()));    Ok(seconds)}// ── vault.item ─────────────────────────────────────────────────────────fn concealed(kind: &str, field: &str) -> bool {    CONCEALED.iter().any(|(k, f)| *k == kind && *f == field)}/// One of the secret's own page's words (`item.username`, `item.website`), for a page that stands beside it.pub(crate) fn item_word(key: &str) -> String {    s(&format!("item.{key}"))}pub(crate) fn field_label(kind: &str, field: &str) -> String {    lines().say(&format!("fields.{kind}.{field}"), &[]).unwrap_or_else(|| s(&format!("fields.{field}")))}/// The payload of one row, opened under the session's key (or the lent one); `None` when shut.fn opened_payload(client: &ClientController, request: &Value, id: &str) -> Result<Option<Map<String, Value>>, MethodError> {    if !(is_open(client) || request.get("privateKey").is_some_and(|key| !key.is_null())) {        return Ok(None);    }    crate::phone::passkeys::with_vmk(client, request, |vmk, _| {        let row = client            .with_file(|replica| {                let found = replica                    .driver                    .get(&format!("SELECT id, value_enc, vmk_version FROM {SECRETS} WHERE workspace_id = ? AND id = ?"), &[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(unreadable)?            .ok_or_else(not_found)?;        if !crate::phone::passwords::sealed_here(&row) {            return Err(MethodError::new("not_sealed_here", s("item.not_sealed_here")));        }        let payload = password_row::open(&row, id, vmk).map_err(|error| MethodError::new("does_not_open", error.to_string()))?;        match serde_json::to_value(&payload).map_err(|error| unreadable(error.to_string()))? {            Value::Object(mut fields) => {                fields.remove("kind");                Ok(Some(fields))            }            _ => Ok(Some(Map::new())),        }    })}fn not_found() -> MethodError {    MethodError::new("secret_not_found", s("item.not_found"))}fn history_count(client: &ClientController, request: &Value, id: &str) -> Option<usize> {    crate::phone::keys::over(client, "keys.history", &lent(request, json!({"id": id}))).ok().and_then(|answer| answer["history"].as_array().map(Vec::len))}fn item(client: &ClientController, id: &str) -> Result<ItemAnswer, MethodError> {    item_with(client, &json!({}), id)}fn item_with(client: &ClientController, request: &Value, id: &str) -> Result<ItemAnswer, MethodError> {    let (secrets, passkeys) = all_rows(client)?;    if let Some(passkey) = passkeys.iter().find(|row| row.get("id").and_then(Value::as_str) == Some(id)) {        return Ok(passkey_item(passkey));    }    let plain = secrets.iter().find(|plain| plain.entry.id == id).ok_or_else(not_found)?.clone();    let open = is_open(client) || request.get("privateKey").is_some_and(|key| !key.is_null());    let (health, _) = reading(client, &secrets, request)?;    let kind = plain.entry.kind.clone();    let payload = if open && plain.sealed_here { opened_payload(client, request, id)? } else { None };    let mut fields = Vec::new();    if let Some(user) = plain.entry.username.as_deref() {        fields.push(Field {            key: "username".into(),            label: s("item.username"),            value: Some(user.into()),            concealed: false,            mono: false,            live_code: false,            acts: vec![with_symbol(act_of("copy", s("item.copy"), "vault.field", json!({"id": id, "field": "username"})), "copy")],        });    }    let spec = SecretKind::parse(&kind).map(|kind| kind.spec());    for declared in spec.map(|spec| spec.fields).unwrap_or_default() {        let name = declared.name;        let present = match &payload {            Some(fields) => fields.get(name).and_then(Value::as_str).is_some_and(|value| !value.is_empty()),            None => declared.required,        };        if !present {            continue;        }        if name == "totp" {            fields.push(Field {                key: "totp".into(),                label: field_label(&kind, "totp"),                value: None,                concealed: false,                mono: true,                live_code: true,                acts: vec![with_symbol(with_presence(act_of("copy", s("item.copy"), "vault.code", json!({"id": id}))), "copy")],            });            continue;        }        if kind == "code" && name == "secret" {            fields.push(Field { key: "code".into(), label: field_label(&kind, "code"), value: None, concealed: false, mono: true, live_code: true, acts: vec![with_symbol(with_presence(act_of("copy", s("item.copy"), "vault.code", json!({"id": id}))), "copy")] });            continue;        }        if name == "urls" {            continue; // listed under Where it fills        }        let hidden = concealed(&kind, name);        let value = if hidden { None } else { payload.as_ref().and_then(|fields| fields.get(name)).and_then(Value::as_str).map(str::to_string) };        let acts = if hidden {            vec![                with_symbol(with_presence(act_of("reveal", s("item.reveal"), "vault.field", json!({"id": id, "field": name}))), "eye"),                with_symbol(with_presence(act_of("copy", s("item.copy"), "vault.field", json!({"id": id, "field": name}))), "copy"),            ]        } else {            vec![with_symbol(act_of("copy", s("item.copy"), "vault.field", json!({"id": id, "field": name})), "copy")]        };        fields.push(Field { key: name.into(), label: field_label(&kind, name), value, concealed: hidden, mono: MONO.contains(&name), live_code: false, acts });    }    let mut blocks = vec![Block { id: "fields".into(), title: None, fields }];    let mut fills = Vec::new();    if let Some(site) = plain.entry.site.as_deref() {        fills.push(Field {            key: "site".into(),            label: s("item.website"),            value: Some(site.into()),            concealed: false,            mono: false,            live_code: false,            acts: vec![with_symbol(act_of("open", s("item.open_site"), "vault.act", json!({"act": "open_site", "id": id})), "safari"), with_symbol(act_of("copy", s("item.copy"), "vault.field", json!({"id": id, "field": "site"})), "copy")],        });    }    if let Some(urls) = payload.as_ref().and_then(|fields| fields.get("urls")).and_then(Value::as_str) {        for (n, url) in urls.lines().map(str::trim).filter(|url| !url.is_empty()).enumerate() {            fills.push(Field { key: format!("url.{n}"), label: s("item.website"), value: Some(url.into()), concealed: false, mono: false, live_code: false, acts: vec![] });        }    }    if let Some(passkey) = plain.passkey_id.as_deref().and_then(|pk| passkeys.iter().find(|row| row.get("id").and_then(Value::as_str) == Some(pk))) {        let rp = passkey.get("rp_id").and_then(Value::as_str).unwrap_or_default();        fills.push(Field { key: "passkey".into(), label: s("item.passkey"), value: Some(sf("item.passkey_for", &[("site", rp)])), concealed: false, mono: false, live_code: false, acts: vec![] });    }    if !fills.is_empty() {        blocks.push(Block { id: "fills".into(), title: Some(s("item.fills")), fields: fills });    }    if open && matches!(kind.as_str(), "login" | "wifi") {        if let Some(n) = history_count(client, request, id).filter(|n| *n > 0) {            blocks.push(Block {                id: "history".into(),                title: Some(s("item.history")),                fields: vec![Field {                    key: "history".into(),                    label: sf("item.history_row", &[("n", &n.to_string())]),                    value: None,                    concealed: false,                    mono: false,                    live_code: false,                    acts: vec![with_presence(act_of("open", s("item.history_open"), "vault.history", json!({"id": id})))],                }],            });        }    }    let mut facts = Vec::new();    let fact = |key: &str, label: String, value: String| Field { key: key.into(), label, value: Some(value), concealed: false, mono: false, live_code: false, acts: vec![] };    if let Some(at) = &plain.created_at {        facts.push(fact("created", s("item.created"), day_of(at)));    }    if let Some(at) = plain.changed_at.as_ref().filter(|_| matches!(kind.as_str(), "login" | "wifi")) {        facts.push(fact("changed", s("item.changed"), day_of(at)));    }    facts.push(fact("used", s("item.used"), plain.entry.last_used.as_deref().map(day_of).unwrap_or_else(|| s("item.never_used"))));    if plain.uses > 0 {        facts.push(fact("uses", sf("item.uses", &[("n", &plain.uses.to_string())]), String::new()));    }    blocks.push(Block { id: "facts".into(), title: Some(s("item.facts")), fields: facts });    let banner = health.marks.get(id).and_then(|marks| {        let (line, tone) = if marks.iter().any(|m| m == "breached") {            (sf("item.banner_breached", &[("n", &health.breach_counts.get(id).copied().unwrap_or(1).to_string())]), Tone::Danger)        } else if marks.iter().any(|m| m == "weak") {            (s("item.banner_weak"), Tone::Danger)        } else if marks.iter().any(|m| m == "reused") {            (sf("item.banner_reused", &[("n", &health.reused_with.get(id).copied().unwrap_or(1).to_string())]), Tone::Attention)        } else if marks.iter().any(|m| m == "old") {            (s("item.banner_old"), Tone::Attention)        } else {            return None;        };        Some(Banner { text: line, tone, act: Some(with_presence(act_of("change_password", s("item.change_password"), "vault.edit", json!({"id": id})))) })    });    let in_bin = plain.trashed_at.is_some();    let mut acts = Vec::new();    if in_bin {        acts.push(with_symbol(act_of("restore", s("item.restore"), "vault.act", json!({"act": "restore", "id": id})), "arrow.uturn.left"));    } else {        acts.push(with_symbol(with_presence(act_of("edit", s("item.edit"), "vault.edit", json!({"id": id}))), "pencil"));        let (act, line, symbol) = if plain.entry.favourite { ("unfavourite", "item.unfavourite", "star.fill") } else { ("favourite", "item.favourite", "star") };        acts.push(with_symbol(act_of(act, s(line), "vault.act", json!({"act": act, "id": id})), symbol));        let mut trash = with_symbol(act_of("trash", s("item.trash"), "vault.act", json!({"act": "trash", "id": id})), "trash");        trash.tone = Tone::Danger;        trash.confirm = Some(Confirm { title: s("item.trash_title"), body: s("item.trash_body"), yes: s("item.trash_yes"), no: s("item.trash_no") });        acts.push(trash);    }    let shut = !open && plain.sealed_here;    Ok(ItemAnswer {        id: id.into(),        kind: kind.clone(),        kind_label: s(&format!("kinds.{kind}")),        title: plain.entry.title.clone(),        subtitle: plain.entry.username.clone().or_else(|| plain.entry.site.clone()).unwrap_or_else(|| s(&format!("kinds.{kind}"))),        picture: list::picture(&plain.entry),        favourite: plain.entry.favourite,        banner,        blocks,        acts,        open: !shut,        unlock: shut.then(|| with_presence(act_of("unlock", s("item.unlock"), "vault.unlock", json!({})))),        in_bin,    })}fn passkey_item(row: &Map<String, Value>) -> ItemAnswer {    let get = |key: &str| row.get(key).and_then(Value::as_str).unwrap_or_default().to_string();    let entry = Entry { id: get("id"), kind: "passkey".into(), title: Some(get("rp_name")).filter(|n| !n.is_empty()).unwrap_or_else(|| get("rp_id")), site: Some(get("rp_id")), ..Default::default() };    let mut fields = Vec::new();    if !get("user_name").is_empty() {        fields.push(Field { key: "username".into(), label: s("item.username"), value: Some(get("user_name")), concealed: false, mono: false, live_code: false, acts: vec![] });    }    let fills = vec![Field { key: "passkey".into(), label: s("item.passkey"), value: Some(sf("item.passkey_for", &[("site", &get("rp_id"))])), concealed: false, mono: false, live_code: false, acts: vec![] }];    let mut facts = vec![];    if !get("created_at").is_empty() {        facts.push(Field { key: "created".into(), label: s("item.created"), value: Some(day_of(&get("created_at"))), concealed: false, mono: false, live_code: false, acts: vec![] });    }    let used = row.get("last_used_at").and_then(Value::as_str).map(day_of).unwrap_or_else(|| s("item.never_used"));    facts.push(Field { key: "used".into(), label: s("item.used"), value: Some(used), concealed: false, mono: false, live_code: false, acts: vec![] });    ItemAnswer {        id: entry.id.clone(),        kind: "passkey".into(),        kind_label: s("kinds.passkey"),        title: entry.title.clone(),        subtitle: get("rp_id"),        picture: list::picture(&entry),        favourite: false,        banner: None,        blocks: vec![Block { id: "fields".into(), title: None, fields }, Block { id: "fills".into(), title: Some(s("item.fills")), fields: fills }, Block { id: "facts".into(), title: Some(s("item.facts")), fields: facts }],        acts: vec![],        open: true,        unlock: None,        in_bin: false,    }}// ── vault.field / vault.code / vault.history ───────────────────────────fn field(client: &ClientController, request: &Value) -> Result<FieldAnswer, MethodError> {    let id = text(request, "id")?.to_string();    let name = text(request, "field")?.to_string();    let clear = preferences(client)?.clipboard_seconds;    if name == "username" || name == "site" {        let (secrets, _) = all_rows(client)?;        let plain = secrets.into_iter().find(|plain| plain.entry.id == id).ok_or_else(not_found)?;        let value = if name == "username" { plain.entry.username } else { plain.entry.site }.ok_or_else(|| bad("field", "a field this item keeps"))?;        return Ok(FieldAnswer { id, field: name, value, mono: false, clear_after: 0, copied_toast: copied_toast(0) });    }    let shown = crate::phone::passwords::over(client, "password.reveal", &lent(request, json!({"id": id})))?;    let value = shown["payload"].get(&name).and_then(Value::as_str).ok_or_else(|| bad("field", "a field this item keeps"))?.to_string();    let kind = shown["payload"]["kind"].as_str().unwrap_or_default().to_string();    let hidden = concealed(&kind, &name);    let clear_after = if hidden { clear } else { 0 };    Ok(FieldAnswer { id, field: name.clone(), value, mono: MONO.contains(&name.as_str()), clear_after, copied_toast: copied_toast(clear_after) })}fn code(client: &ClientController, request: &Value) -> Result<CodeAnswer, MethodError> {    let id = text(request, "id")?.to_string();    let answer = crate::phone::keys::over(client, "keys.code", &lent(request, json!({"id": id})))?;    let code = answer["code"].as_str().unwrap_or_default().to_string();    let shown = if code.len() == 6 || code.len() == 8 { format!("{} {}", &code[..code.len() / 2], &code[code.len() / 2..]) } else { code.clone() };    let clear = preferences(client)?.clipboard_seconds;    Ok(CodeAnswer { id, code, shown, seconds_left: answer["secondsLeft"].as_u64().unwrap_or(0), period: answer["period"].as_u64().unwrap_or(30), clear_after: clear, copied_toast: copied_toast(clear) })}fn history(client: &ClientController, request: &Value) -> Result<HistoryAnswer, MethodError> {    let id = text(request, "id")?.to_string();    let answer = crate::phone::keys::over(client, "keys.history", &lent(request, json!({"id": id})))?;    let rows: Vec<PastRow> = answer["history"]        .as_array()        .into_iter()        .flatten()        .map(|past| PastRow {            value: past["password"].as_str().unwrap_or_default().to_string(),            until: sf("item.history_until", &[("date", &day_of(past["until"].as_str().unwrap_or_default()))]),            acts: vec![with_symbol(act_of("copy", s("item.copy"), "vault.act", json!({"act": "copied"})), "copy")],        })        .collect();    let empty = rows.is_empty().then(|| s("item.history_empty"));    let clear_after = preferences(client)?.clipboard_seconds;    Ok(HistoryAnswer { id, title: s("item.history_title"), rows, empty, clear_after })}// ── vault.edit / vault.save ────────────────────────────────────────────fn input_of(kind: &str, field: &str) -> Input {    match (kind, field) {        (_, "notes") | ("note", "body") | ("address", "address") | ("login", "urls") => Input::Multiline,        (_, "email") => Input::Email,        (_, "phone") => Input::Phone,        ("card", "expiry") => Input::Month,        ("identity", "issued") | ("identity", "expires") => Input::Date,        ("card", "number") | ("card", "cvv") => Input::Number,        ("code", "secret") | (_, "totp") => Input::Code,        ("wifi", "security") => Input::Choice,        (kind, field) if concealed(kind, field) => Input::Secret,        _ => Input::Text,    }}fn edit(client: &ClientController, request: &Value) -> Result<EditAnswer, MethodError> {    let id = optional(request, "id").map(str::to_string);    let (kind, plain, payload) = match &id {        Some(id) => {            let (secrets, _) = all_rows(client)?;            let plain = secrets.into_iter().find(|plain| &plain.entry.id == id).ok_or_else(not_found)?;            let payload = if plain.sealed_here { crate::phone::passkeys::with_vmk(client, request, |_, _| Ok(()))?; opened_payload(client, request, id)? } else { None };            (plain.entry.kind.clone(), Some(plain), payload)        }        None => (optional(request, "kind").unwrap_or("login").to_string(), None, None),    };    let spec = SecretKind::parse(&kind).map(|kind| kind.spec()).ok_or_else(|| bad("kind", "a kind of item"))?;    let mut fields = vec![FormField {        key: "name".into(),        label: s("edit.name"),        input: Input::Text,        required: kind != "login" && kind != "code",        value: plain.as_ref().map(|plain| plain.entry.title.clone()),        placeholder: Some(s("edit.name_hint")),        generate: false,        sealed: false,        choices: vec![],    }];    if kind == "login" {        fields.push(FormField { key: "site".into(), label: s("edit.website"), input: Input::Url, required: false, value: plain.as_ref().and_then(|p| p.entry.site.clone()), placeholder: Some(s("edit.website_hint")), generate: false, sealed: false, choices: vec![] });        fields.push(FormField { key: "username".into(), label: s("edit.username"), input: Input::Email, required: false, value: plain.as_ref().and_then(|p| p.entry.username.clone()), placeholder: None, generate: false, sealed: false, choices: vec![] });    }    for declared in spec.fields {        let input = input_of(&kind, declared.name);        let choices = if input == Input::Choice { ["WPA3", "WPA2", "WEP", "none"].iter().map(|v| Choice { value: v.to_string(), label: v.to_string() }).collect() } else { vec![] };        fields.push(FormField {            key: declared.name.into(),            label: field_label(&kind, declared.name),            input,            required: declared.required,            value: payload.as_ref().and_then(|fields| fields.get(declared.name)).and_then(Value::as_str).map(str::to_string),            placeholder: None,            generate: matches!((kind.as_str(), declared.name), ("login" | "wifi" | "document", "password")),            sealed: true,            choices,        });    }    let kind_word = s(&format!("kinds.{kind}"));    let title = if id.is_some() { sf("edit.edit", &[("kind", &kind_word)]) } else { sf("edit.new", &[("kind", &kind_word)]) };    let mut save = act_of("save", s("edit.save"), "vault.save", json!({"id": id, "kind": kind}));    save.tone = Tone::Accent;    Ok(EditAnswer { id, kind, title, fields, save, cancel: s("edit.cancel") })}fn save(client: &ClientController, request: &Value) -> Result<ActAnswer, MethodError> {    let fields = match request.get("fields") {        None | Some(Value::Null) => Map::new(),        Some(Value::Object(fields)) => fields.clone(),        Some(_) => return Err(bad("fields", "an object of text")),    };    let id = match optional(request, "id") {        Some(id) => {            let mut onward = lent(request, json!({"id": id, "fields": fields}));            for key in ["name", "site", "username"] {                if let Some(value) = request.get(key) {                    onward[key] = value.clone();                }            }            if fields.is_empty() {                onward.as_object_mut().map(|o| o.remove("fields"));            }            crate::phone::keys::over(client, "keys.change", &onward)?;            id.to_string()        }        None => {            let mut onward = lent(request, json!({"kind": text(request, "kind")?, "fields": fields}));            for key in ["name", "site", "username", "favourite"] {                if let Some(value) = request.get(key).filter(|value| !value.is_null()) {                    onward[key] = value.clone();                }            }            crate::phone::keys::over(client, "keys.add", &onward)?["id"].as_str().unwrap_or_default().to_string()        }    };    let item = item_with(client, request, &id).ok().map(Box::new);    Ok(ActAnswer { act: "save".into(), id: Some(id), toast: Some(Toast { text: s("item.saved"), undo: None }), item, gone: false, platform: None })}// ── vault.generate ─────────────────────────────────────────────────────fn flag(request: &Value, key: &str, default: bool) -> bool {    request.get(key).and_then(Value::as_bool).unwrap_or(default)}fn number(request: &Value, key: &str, default: u32, min: u32, max: u32) -> u32 {    request.get(key).and_then(Value::as_u64).map(|n| (n as u32).clamp(min, max)).unwrap_or(default)}fn generate(request: &Value, clear_after: u32) -> Result<GenerateAnswer, MethodError> {    let mode = optional(request, "mode").unwrap_or("chars");    let (recipe, controls, made_request) = match mode {        "words" => {            let count = number(request, "words", 4, WORDS_MIN as u32, WORDS_MAX as u32);            let separator = optional(request, "separator").filter(|sep| ["-", " ", ".", "_"].contains(sep)).unwrap_or("-").to_string();            let capitalize = flag(request, "capitalize", true);            let digit = flag(request, "number", true);            let seps = [("-", "generator.sep_hyphen"), (" ", "generator.sep_space"), (".", "generator.sep_dot"), ("_", "generator.sep_underscore")];            let controls = vec![                Control { key: "words".into(), label: s("generator.word_count"), control: "range".into(), value: json!(count), min: Some(WORDS_MIN as u32), max: Some(WORDS_MAX as u32), choices: vec![] },                Control { key: "separator".into(), label: s("generator.separator"), control: "choice".into(), value: json!(separator), min: None, max: None, choices: seps.iter().map(|(v, l)| Choice { value: v.to_string(), label: s(l) }).collect() },                Control { key: "capitalize".into(), label: s("generator.capitalize"), control: "switch".into(), value: json!(capitalize), min: None, max: None, choices: vec![] },                Control { key: "number".into(), label: s("generator.number"), control: "switch".into(), value: json!(digit), min: None, max: None, choices: vec![] },            ];            let made = json!({"mode": "words", "words": count, "separator": separator, "capitalize": capitalize, "number": digit});            (Recipe::Words(Words { count: count as usize, separator, capitalize, number: digit }), controls, made)        }        "pin" => {            let length = number(request, "length", 6, 4, 12);            let controls = vec![Control { key: "length".into(), label: s("generator.length"), control: "range".into(), value: json!(length), min: Some(4), max: Some(12), choices: vec![] }];            (Recipe::Random(Random { length: length as usize, lower: false, upper: false, digits: true, symbols: false, no_look_alikes: false }), controls, json!({"mode": "pin", "length": length}))        }        "chars" => {            let length = number(request, "length", 20, 8, 64);            let mut switches = [("lower", flag(request, "lower", true)), ("upper", flag(request, "upper", true)), ("digits", flag(request, "digits", true)), ("symbols", flag(request, "symbols", true))];            if switches.iter().all(|(_, on)| !on) {                switches[0].1 = true; // one class always: the last switch turned off turns lower case back on            }            let on = |key: &str| switches.iter().find(|(k, _)| *k == key).map(|(_, on)| *on).unwrap_or(true);            let mut controls = vec![Control { key: "length".into(), label: s("generator.length"), control: "range".into(), value: json!(length), min: Some(8), max: Some(64), choices: vec![] }];            for (switch, value) in switches {                controls.push(Control { key: switch.into(), label: s(&format!("generator.{switch}")), control: "switch".into(), value: json!(value), min: None, max: None, choices: vec![] });            }            let made = json!({"mode": "chars", "length": length, "lower": on("lower"), "upper": on("upper"), "digits": on("digits"), "symbols": on("symbols")});            (Recipe::Random(Random { length: length as usize, lower: on("lower"), upper: on("upper"), digits: on("digits"), symbols: on("symbols"), no_look_alikes: true }), controls, made)        }        _ => return Err(bad("mode", "chars, words or pin")),    };    let value = recipe.generate().map_err(|error| MethodError::new("bad_recipe", error.to_string()))?;    let bits = recipe.bits().map_err(|error| MethodError::new("bad_recipe", error.to_string()))?;    let measured = strength(&value);    // A made password is as strong as the recipe's draw, whatever its shape reads as.    let shown_bits = bits.max(measured.bits);    let score = if mode == "pin" { measured.score.min(1) } else { measured.score.max(score_of(bits)) };    let word = ["very_weak", "weak", "fair", "good", "strong"][score as usize];    let tone = match score {        0 | 1 => Tone::Danger,        2 => Tone::Attention,        _ => Tone::Safe,    };    let modes = ["chars", "words", "pin"].iter().map(|m| Choice { value: m.to_string(), label: s(&format!("generator.{m}")) }).collect();    let mut copy = with_symbol(act_of("copy", s("generator.copy"), "vault.act", json!({"act": "copied"})), "copy");    copy.tone = Tone::Accent;    Ok(GenerateAnswer {        title: s("generator.title"),        mode: mode.into(),        modes,        value: value.to_string(),        strength: StrengthLine { score, label: s(&format!("generator.strength.{word}")), tone, detail: sf("generator.bits", &[("bits", &format!("{}", shown_bits.round() as i64))]) },        controls,        request: made_request,        again: s("generator.again"),        copy,        use_new: act_of("use_new", s("generator.use_new"), "vault.edit", json!({"kind": "login"})),        use_here: s("generator.use_here"),        clear_after,        copied_toast: copied_toast(clear_after),    })}/// The score a drawn password earns from its bits alone (the estimate's own floors).fn score_of(bits: f64) -> u8 {    match bits {        b if b >= 80.0 => 4,        b if b >= 60.0 => 3,        b if b >= 40.0 => 2,        b if b >= 28.0 => 1,        _ => 0,    }}// ── vault.security ─────────────────────────────────────────────────────fn finding_group(id: &str, mark: &str, secrets: &[Plain], health: &Reading) -> Group {    let mut rows: Vec<Row> = secrets        .iter()        .filter(|plain| !plain.entry.in_bin && health.marks.get(&plain.entry.id).is_some_and(|marks| marks.iter().any(|m| m == mark)))        .map(|plain| {            let detail = match mark {                "reused" => Some(sf("security.reused_with", &[("n", &health.reused_with.get(&plain.entry.id).copied().unwrap_or(1).to_string())])),                "old" => health.age_days.get(&plain.entry.id).map(|n| sf("security.age", &[("n", &n.to_string())])),                "breached" => health.breach_counts.get(&plain.entry.id).map(|n| sf("security.breach_count", &[("n", &n.to_string())])),                _ => plain.entry.username.clone().or_else(|| plain.entry.site.clone()),            };            Row {                id: plain.entry.id.clone(),                title: plain.entry.title.clone(),                detail,                tone: if matches!(mark, "weak" | "breached") { Tone::Danger } else { Tone::Attention },                picture: Some(list::picture(&plain.entry)),                open: Some(act_of("open", s("security.review"), "vault.item", json!({"id": plain.entry.id}))),                acts: vec![],            }        })        .collect();    rows.sort_by_key(|row| list::fold(&row.title));    Group { id: id.into(), title: s(&format!("security.{id}")), detail: Some(s(&format!("security.{id}_detail"))), empty: rows.is_empty().then(|| s(&format!("security.none_{id}"))), rows, acts: vec![] }}fn security(client: &ClientController, request: &Value, remote: Option<Remote<'_>>) -> Result<SecurityAnswer, MethodError> {    let (secrets, _) = all_rows(client)?;    let (health, open) = reading(client, &secrets, request)?;    let count = |mark: &str| health.marks.values().filter(|marks| marks.iter().any(|m| m == mark)).count() as u32;    let (weak, reused, old, breached) = (count("weak"), count("reused"), count("old"), count("breached"));    let to_look_at = health.marks.len() as u32;    let summary = if !open && to_look_at == 0 {        s("security.health_locked")    } else if to_look_at == 0 {        s("security.all_good")    } else {        sf("security.to_look_at", &[("n", &to_look_at.to_string())])    };    let tone = if weak > 0 || breached > 0 { Tone::Danger } else if to_look_at > 0 { Tone::Attention } else if open { Tone::Safe } else { Tone::Neutral };    let counts = [("breached", breached), ("weak", weak), ("reused", reused), ("old", old)].iter().filter(|(id, n)| *id != "breached" || *n > 0).map(|(id, n)| Chip { id: id.to_string(), label: s(&format!("marks.{id}")), count: *n, on: false }).collect();    let health_head = Health { title: s("security.health"), summary, tone, weak, reused, old, breached, counts, open, unlock: (!open).then(|| with_presence(act_of("unlock", s("item.unlock"), "vault.unlock", json!({})))) };    let mut groups = vec![waiting(client, remote)?, windows(client)?];    let mut breach_group = finding_group("breached", "breached", &secrets, &health);    let last = breaches(client)?;    breach_group.detail = Some(if last.here { sf("security.breach_checked", &[("date", &day_of(&last.checked_at))]) } else { s("security.breach_never") });    if !last.here {        breach_group.empty = Some(s("security.breach_never_body"));    }    let mut check = with_presence(act_of("check", s("security.breach_check"), "vault.breach", json!({})));    check.tone = if last.here { Tone::Neutral } else { Tone::Accent };    breach_group.acts = vec![check];    groups.push(breach_group);    if open || old > 0 {        groups.push(finding_group("weak", "weak", &secrets, &health));        groups.push(finding_group("reused", "reused", &secrets, &health));        groups.push(finding_group("old", "old", &secrets, &health));    }    groups.push(devices(client)?);    groups.push(reads(client)?);    groups.push(recovery(client, optional(request, "platform").unwrap_or("android")));    groups.push(cotton_passkeys(remote));    Ok(SecurityAnswer { title: s("security.title"), health: health_head, groups })}/// Requests that need a yes or no: an assistant's unlock, a device waiting on this vault, a sign-in to approve.fn waiting(client: &ClientController, remote: Option<Remote<'_>>) -> Result<Group, MethodError> {    let mut rows = Vec::new();    let card = crate::phone::unlock::call_on(client, "unlock.card", &json!({}))?;    if let Some(card) = card.get("card").filter(|card| card.is_object()) {        let fields = &card["fields"];        let request_id = card.get("requestId").or_else(|| fields.get("requestId")).cloned().unwrap_or(Value::Null);        let mut decline = act_of("decline", s("security.decline"), "unlock.decline", json!({"requestId": request_id}));        decline.tone = Tone::Neutral;        rows.push(Row {            id: format!("unlock:{}", request_id.as_str().unwrap_or_default()),            title: fields["title"].as_str().unwrap_or_default().to_string(),            detail: [fields["asker"].as_str(), fields["expires"].as_str()].into_iter().flatten().collect::<Vec<_>>().join(" · ").into(),            tone: Tone::Attention,            picture: None,            open: Some(act_of("review", s("security.review"), "unlock.card", json!({}))),            acts: vec![decline],        });    }    let this = client.self_device_id();    let keys = client.with_file(|replica| cotton_client::vault::devices::keys(replica.driver, replica.workspace_id)).unwrap_or_default();    for device in keys.iter().filter(|device| !device.wrapped && Some(&device.device_id) != this.as_ref()) {        let name = device.name.clone().unwrap_or_else(|| s("security.this_device"));        let mut refuse = act_of("refuse", s("security.refuse"), "vault.refuseDevice", json!({"deviceId": device.device_id}));        refuse.tone = Tone::Danger;        rows.push(Row { id: format!("device:{}", device.device_id), title: sf("security.device_ask", &[("name", &name)]), detail: device.fingerprint.clone(), tone: Tone::Attention, picture: None, open: None, acts: vec![refuse] });    }    match crate::phone::recovery::call_on(client, "recovery.helpAsks", &json!({})) {        Ok(asks) => rows.extend(help_rows(&asks)),        Err(error) if error.code == "sign_in_first" => {}        Err(error) => rows.push(Row { id: "help:unreadable".into(), title: s("security.help_unreadable"), detail: Some(error.message), tone: Tone::Attention, picture: None, open: None, acts: vec![] }),    }    if let Some(remote) = remote {        match remote("signin.asks", &json!({})) {            Ok(asks) => {                for ask in asks["waiting"].as_array().into_iter().flatten() {                    let id = ask["askId"].clone();                    rows.push(Row {                        id: format!("signin:{}", id.as_str().unwrap_or_default()),                        title: ask["name"].as_str().map(str::to_string).unwrap_or_else(|| s("security.sign_in_ask")),                        detail: ask["line"].as_str().map(str::to_string),                        tone: Tone::Attention,                        picture: None,                        open: Some(act_of("review", s("security.review"), "signin.show", json!({"askId": id}))),                        acts: vec![],                    });                }            }            Err(error) if error.code == "not_connected" => {}            Err(error) => rows.push(Row { id: "signin:unreadable".into(), title: s("security.sign_in_ask"), detail: Some(error.message), tone: Tone::Attention, picture: None, open: None, acts: vec![] }),        }    }    Ok(Group { id: "waiting".into(), title: s("security.waiting"), detail: Some(s("security.waiting_detail")), empty: rows.is_empty().then(|| s("security.none_waiting")), rows, acts: vec![] })}/// The help asks a trusted person answers, as Waiting rows: Approve (presence, confirmed with the code to compare) or Decline.fn help_rows(asks: &Value) -> Vec<Row> {    let mut rows = Vec::new();    for ask in asks["asks"].as_array().into_iter().flatten() {        let id = ask["id"].clone();        let name = ask["name"].as_str().unwrap_or_default().to_string();        let mut approve = with_presence(act_of("approve", s("security.approve"), "recovery.helpApprove", json!({"id": id})));        approve.tone = Tone::Accent;        approve.confirm = Some(Confirm { title: sf("security.help_title", &[("name", &name)]), body: ask["line"].as_str().unwrap_or_default().to_string(), yes: s("security.approve"), no: s("item.trash_no") });        let decline = act_of("decline", s("security.decline"), "recovery.helpDecline", json!({"id": id}));        rows.push(Row { id: format!("help:{}", id.as_str().unwrap_or_default()), title: sf("security.help_ask", &[("name", &name)]), detail: ask["line"].as_str().map(str::to_string), tone: Tone::Attention, picture: None, open: None, acts: vec![approve, decline] });    }    rows}fn windows(client: &ClientController) -> Result<Group, MethodError> {    let answer = crate::phone::unlock::call_on(client, "unlock.windows", &json!({}))?;    let rows: Vec<Row> = answer["windows"]        .as_array()        .into_iter()        .flatten()        .map(|window| {            let client_name = window["client"].as_str().unwrap_or_default().to_string();            let mut end = act_of("end", s("security.end_now"), "unlock.end", json!({"grantId": window["grantId"]}));            end.tone = Tone::Danger;            end.confirm = Some(Confirm { title: s("security.end_title"), body: sf("security.end_body", &[("client", &client_name)]), yes: s("security.end_now"), no: s("item.trash_no") });            Row { id: window["grantId"].as_str().unwrap_or_default().to_string(), title: client_name, detail: window["said"].as_str().map(str::to_string), tone: Tone::Attention, picture: None, open: None, acts: vec![end] }        })        .collect();    Ok(Group { id: "windows".into(), title: s("security.windows"), detail: Some(s("security.windows_detail")), empty: rows.is_empty().then(|| s("security.none_windows")), rows, acts: vec![] })}/// What a device calls itself on its own device row, when this copy holds one.fn device_name(client: &ClientController, device_id: &str) -> Option<String> {    client        .with_file(|file| {            Ok(file                .driver                .get("SELECT name FROM cotton_devices WHERE device_id = ? AND name IS NOT NULL AND name != '' ORDER BY approved_at DESC LIMIT 1", &[rusqlite::types::Value::Text(device_id.to_string())])                .ok()                .flatten()                .and_then(|row| row.text("name").map(str::to_string)))        })        .ok()        .flatten()}fn devices(client: &ClientController) -> Result<Group, MethodError> {    let this = client.self_device_id();    let keys = client.with_file(|replica| cotton_client::vault::devices::keys(replica.driver, replica.workspace_id)).map_err(unreadable)?;    let rows = keys        .iter()        .filter(|key| key.wrapped || Some(&key.device_id) == this.as_ref())        .map(|key| {            let here = Some(&key.device_id) == this.as_ref();            // NEVER THE KEY'S ID (the Android Secrets walk, 26 Nov 2026: "kv-3e_9a3IKp…" stood under Devices): the            // key row's name, else the device's own row's, else words (this device, or a device with no name).            let named = key.name.clone().filter(|name| !name.trim().is_empty()).or_else(|| device_name(client, &key.device_id));            let name = named.clone().unwrap_or_else(|| s(if here { "security.this_device" } else { "security.unnamed_device" }));            let mut acts = vec![];            if !here {                let mut remove = act_of("remove", s("security.remove_device"), "devices.revoke", json!({"deviceId": key.device_id}));                remove.tone = Tone::Danger;                remove.confirm = Some(Confirm { title: s("security.remove_title"), body: sf("security.remove_body", &[("name", &name)]), yes: s("security.remove_device"), no: s("item.trash_no") });                acts.push(remove);            }            let detail = if here && named.is_none() { String::new() } else if here { s("security.this_device") } else if key.wrapped { key.created_at.as_deref().map(day_of).unwrap_or_default() } else { s("security.waiting_key") };            Row { id: key.device_id.clone(), title: name, detail: Some(detail).filter(|d| !d.is_empty()), tone: if key.wrapped { Tone::Neutral } else { Tone::Attention }, picture: None, open: None, acts }        })        .collect();    let rows: Vec<Row> = rows;    Ok(Group { id: "devices".into(), title: s("security.devices"), detail: Some(s("security.devices_detail")), empty: rows.is_empty().then(|| s("security.none_devices")), rows, acts: vec![] })}fn reads(client: &ClientController) -> Result<Group, MethodError> {    let answer = crate::phone::unlock::call_on(client, "unlock.reads", &json!({}))?;    let rows: Vec<Row> = answer["reads"]        .as_array()        .into_iter()        .flatten()        .take(50)        .map(|read| Row { id: read["id"].as_str().unwrap_or_default().to_string(), title: read["client"].as_str().unwrap_or_default().to_string(), detail: read["said"].as_str().map(str::to_string), tone: Tone::Neutral, picture: None, open: None, acts: vec![] })        .collect();    Ok(Group { id: "reads".into(), title: s("security.reads"), detail: Some(s("security.reads_detail")), empty: rows.is_empty().then(|| s("security.none_reads")), rows, acts: vec![] })}/// The ways back in: the recovery code, this phone's platform copy (Google on/// Android, Apple on iPhone), and a trusted person, each with what makes it.fn recovery(client: &ClientController, platform: &str) -> Group {    let status = match crate::phone::recovery::call_on(client, "recovery.status", &json!({})) {        Ok(status) => status,        Err(error) => {            let row = Row { id: "code".into(), title: s("security.recovery"), detail: Some(error.message), tone: Tone::Attention, picture: None, open: None, acts: vec![] };            return Group { id: "recovery".into(), title: s("security.recovery"), detail: Some(s("security.recovery_detail")), rows: vec![row], empty: None, acts: vec![] };        }    };    recovery_of(&status, platform)}/// The recovery group from `recovery.status`'s answer.fn recovery_of(status: &Value, platform: &str) -> Group {    if status["signedIn"] != json!(true) {        let row = Row { id: "code".into(), title: s("security.recovery_sign_in"), detail: None, tone: Tone::Neutral, picture: None, open: None, acts: vec![] };        return Group { id: "recovery".into(), title: s("security.recovery"), detail: Some(s("security.recovery_detail")), rows: vec![row], empty: None, acts: vec![] };    }    let mut rows = Vec::new();    // The code.    let code = status.get("code").filter(|code| code.is_object());    let (title, tone, acts) = match code {        Some(code) if code["current"] == json!(true) => {            (s("security.recovery_made"), Tone::Safe, vec![with_presence(act_of("show", s("security.recovery_show"), "recovery.show", json!({})))])        }        Some(_) => {            let mut make = with_presence(act_of("make", s("security.recovery_make_new"), "recovery.make", json!({})));            make.tone = Tone::Accent;            (s("security.recovery_stale"), Tone::Attention, vec![make])        }        None => {            let mut make = with_presence(act_of("make", s("security.recovery_make"), "recovery.make", json!({})));            make.tone = Tone::Accent;            (s("security.recovery_none"), Tone::Attention, vec![make])        }    };    let detail = code.and_then(|code| code["line"].as_str()).map(str::to_string);    rows.push(Row { id: "code".into(), title, detail, tone, picture: None, open: None, acts });    // This phone's platform copy.    let store = if platform == "ios" { "apple" } else { "google" };    let held = status.get(store).filter(|held| held.is_object());    let make_platform = |line: &str| with_presence(act_of("make_platform", s(line), "recovery.makePlatform", json!({"store": store})));    let (title, tone, acts) = match held {        Some(held) if held["current"] == json!(true) => (s(&format!("security.platform_{store}_on")), Tone::Safe, vec![]),        Some(_) => (s(&format!("security.platform_{store}_stale")), Tone::Attention, vec![make_platform("security.platform_renew")]),        None => (s(&format!("security.platform_{store}_off")), Tone::Neutral, vec![make_platform("security.platform_turn_on")]),    };    rows.push(Row { id: format!("platform.{store}"), title, detail: held.and_then(|held| held["line"].as_str()).map(str::to_string), tone, picture: None, open: None, acts });    // A trusted person.    let trusted = status.get("trusted").filter(|trusted| trusted.is_object());    let mut choose = with_presence(act_of("trust", s(if trusted.is_some() { "security.trusted_change" } else { "security.trusted_choose" }), "recovery.trust", json!({})));    choose.input = Some(Prompt { key: "number".into(), label: s("security.trusted_number"), input: Input::Phone, placeholder: Some(s("security.trusted_number_hint")), choices: Vec::new() });    rows.push(Row {        id: "trusted".into(),        title: trusted.and_then(|t| t["line"].as_str()).map(str::to_string).unwrap_or_else(|| s("security.trusted_none")),        detail: Some(s("security.trusted_detail")),        tone: if trusted.is_some() { Tone::Safe } else { Tone::Neutral },        picture: None,        open: None,        acts: vec![choose],    });    Group { id: "recovery".into(), title: s("security.recovery"), detail: Some(s("security.recovery_detail")), rows, empty: None, acts: vec![] }}fn cotton_passkeys(remote: Option<Remote<'_>>) -> Group {    let mut rows = Vec::new();    if let Some(remote) = remote {        match remote("signin.passkeys", &json!({})) {            Ok(answer) => {                for passkey in answer["passkeys"].as_array().into_iter().flatten() {                    let mut remove = act_of("remove", s("security.passkey_remove"), "signin.passkeyRemove", json!({"id": passkey["id"]}));                    remove.tone = Tone::Danger;                    remove.confirm = Some(Confirm { title: s("security.passkey_remove_title"), body: s("security.passkey_remove_body"), yes: s("security.passkey_remove"), no: s("item.trash_no") });                    rows.push(Row { id: passkey["id"].as_str().unwrap_or_default().into(), title: passkey["name"].as_str().unwrap_or_default().into(), detail: passkey["when"].as_str().map(str::to_string), tone: Tone::Neutral, picture: None, open: None, acts: vec![remove] });                }            }            Err(error) if error.code == "not_connected" => {}            Err(error) => rows.push(Row { id: "passkeys:unreadable".into(), title: s("security.passkeys"), detail: Some(error.message), tone: Tone::Attention, picture: None, open: None, acts: vec![] }),        }    }    let add = with_presence(act_of("add", s("security.passkey_add"), "signin.passkeyOptions", json!({})));    Group { id: "passkeys".into(), title: s("security.passkeys"), detail: Some(s("security.passkeys_detail")), empty: rows.is_empty().then(|| s("security.none_passkeys")), rows, acts: vec![add] }}// ── vault.settings ─────────────────────────────────────────────────────fn choice_row(id: &str, title: String, on: bool, key: &str, value: Value) -> Row {    Row { id: id.into(), title, detail: None, tone: if on { Tone::Accent } else { Tone::Neutral }, picture: None, open: Some(act_of(if on { "chosen" } else { "choose" }, String::new(), "vault.act", json!({"act": "set", "key": key, "value": value}))), acts: vec![] }}fn settings(client: &ClientController, request: &Value) -> Result<SettingsAnswer, MethodError> {    let platform = optional(request, "platform").unwrap_or("android");    let prefs = preferences(client)?;    let status = crate::phone::tool_acts::account_status(client);    // While a sign-in's rows go up (`backing_up`) the phone is signed in as far as a person may act on it, as    // Back up now and Sign out beside this line say (tool_acts::offered_account).    let signed_in = status["signed_in"] == json!(true) || status["backing_up"] == json!(true);    let mut account_acts = Vec::new();    for (act, line) in [("sign_in", "settings.sign_in"), ("back_up", "settings.back_up"), ("sign_out", "settings.sign_out")] {        let id = match act {            "sign_in" => crate::phone::tool_acts::ACCOUNT_SIGN_IN,            "back_up" => crate::phone::tool_acts::ACCOUNT_BACK_UP,            _ => crate::phone::tool_acts::ACCOUNT_SIGN_OUT,        };        if !crate::phone::tool_acts::offered_account(id, &status) {            continue;        }        let mut a = act_of(act, s(line), "vault.act", json!({"act": act}));        if act == "sign_out" {            a.tone = Tone::Danger;            a.confirm = Some(Confirm { title: s("settings.sign_out_title"), body: s("settings.sign_out_body"), yes: s("settings.sign_out"), no: s("item.trash_no") });        }        if act == "sign_in" {            a.tone = Tone::Accent;        }        account_acts.push(a);    }    let account = Group { id: "account".into(), title: s("settings.account"), detail: None, rows: vec![Row { id: "account".into(), title: s(if signed_in { "settings.signed_in" } else { "settings.not_signed_in" }), detail: None, tone: Tone::Neutral, picture: None, open: None, acts: vec![] }], empty: None, acts: account_acts };    let lock_rows = LOCK_CHOICES.iter().map(|n| choice_row(&format!("lock.{n}"), if *n == 0 { s("settings.lock_immediately") } else { sf("settings.lock_minutes", &[("n", &n.to_string())]) }, prefs.lock_minutes == *n, "lockMinutes", json!(n))).collect();    let clip_rows = CLIPBOARD_CHOICES.iter().map(|n| choice_row(&format!("clipboard.{n}"), if *n == 0 { s("settings.clipboard_never") } else { sf("settings.clipboard_seconds", &[("n", &n.to_string())]) }, prefs.clipboard_seconds == *n, "clipboardSeconds", json!(n))).collect();    let steps = if platform == "ios" { ["settings.filling_ios_1", "settings.filling_ios_2", "settings.filling_ios_3"] } else { ["settings.filling_android_1", "settings.filling_android_2", "settings.filling_android_3"] };    let step_rows = steps.iter().enumerate().map(|(n, line)| Row { id: format!("step.{}", n + 1), title: s(line), detail: None, tone: Tone::Neutral, picture: None, open: None, acts: vec![] }).collect();    let mut open_settings = act_of("open_settings", s("settings.filling_open"), "vault.act", json!({"act": "open_fill_settings"}));    open_settings.tone = Tone::Accent;    // YOU as DECISIONS draws it: the app's own rows (Open with, Lock after, Clear copied after, Bring in from    // Dashlane, Take everything out, Look), then Sync, Privacy, Storage, Help and About as in every Cotton app.    let you = crate::phone::secrets_app::you_line;    let page = |id: &str, title: String, detail: Option<String>| Row { id: id.into(), title: title.clone(), detail, tone: Tone::Neutral, picture: None, open: Some(act_of("open_page", title, "vault.act", json!({"act": "open_page", "page": id}))), acts: vec![] };    let group = |id: &str, title: String, detail: Option<String>, rows: Vec<Row>, acts: Vec<Act>| Group { id: id.into(), title, detail, rows, empty: None, acts };    let open_with = group("open_with", you("open_with"), Some(s("settings.filling_detail")), step_rows, vec![open_settings]);    let lock = group("lock", you("lock_after"), Some(you("lock_line")), lock_rows, vec![]);    let clipboard = group("clipboard", you("clear_after"), None, clip_rows, vec![]);    let dashlane = group("dashlane", you("dashlane"), None, vec![page("import", you("dashlane"), Some(you("dashlane_line")))], vec![]);    let export_rows = [("csv", "settings.export_csv", "keys.exportCsv"), ("cxf", "settings.export_cxf", "keys.exportCxf")]        .iter()        .map(|(id, line, method)| Row { id: format!("export.{id}"), title: s(line), detail: None, tone: Tone::Neutral, picture: None, open: Some(with_presence(act_of("export", s(line), method, json!({})))), acts: vec![] })        .collect();    let export = group("export", you("take_out"), Some(s("settings.export_detail")), export_rows, vec![]);    let look = group("look", you("look"), None, vec![page("look", you("look"), None)], vec![]);    // SYNC as every app's home and Sync page say it (SYNC SEEN, owner 25 Nov 2026): the one line    // (`shell_account::sync_said`: Synced at…, Syncing…, N changes waiting to sync, Can't reach Cotton right now ·    // trying again), and when it last synced in words when the line is not that itself.    let said = crate::methods::shell_account::sync_said(client);    let sync_row = Row {        id: "sync".into(),        title: said["title"].as_str().unwrap_or_default().to_string(),        detail: said["last"].as_str().map(str::to_string),        tone: Tone::Neutral,        picture: None,        open: None,        acts: vec![],    };    // UNSENT HEAL (26 Nov 2026): changes that cannot be sent, with Send again and Let go, as every Sync page says them.    let mut sync_rows = vec![sync_row];    if let Some(stuck) = said.get("stuck").filter(|stuck| !stuck.is_null()) {        let acts = stuck["acts"].as_array().into_iter().flatten().map(|act| {            let mut made = act_of(act["id"].as_str().unwrap_or_default(), act["label"].as_str().unwrap_or_default().to_string(), act["method"].as_str().unwrap_or_default(), act["request"].clone());            if act["tone"] == "danger" {                made.tone = Tone::Danger;            }            if let Some(confirm) = act.get("confirm").filter(|c| c.is_object()) {                let word = |key: &str| confirm[key].as_str().unwrap_or_default().to_string();                made.confirm = Some(Confirm { title: word("title"), body: word("body"), yes: word("yes"), no: word("no") });            }            made        }).collect();        sync_rows.push(Row { id: "stuck".into(), title: stuck["title"].as_str().unwrap_or_default().to_string(), detail: stuck["detail"].as_str().map(str::to_string), tone: Tone::Attention, picture: None, open: None, acts });    }    let sync = Group { id: "sync".into(), title: you("sync"), rows: sync_rows, ..account };    let privacy = group("privacy", you("privacy"), None, vec![page("privacy", you("privacy"), Some(you("privacy_line")))], vec![]);    let kept = all_rows(client).map(|(secrets, _)| secrets.len()).unwrap_or(0);    let count = crate::phone::secrets_app::you_count(kept);    let storage = group("storage", you("storage"), None, vec![Row { id: "storage".into(), title: count, detail: Some(you("storage_line")), tone: Tone::Neutral, picture: None, open: None, acts: vec![] }], vec![]);    // DELETE ACCOUNT (owner; DELETE_ACCOUNT.md) is the shell's own part on both phones (DeleteAccountPart, last on    // You while signed in, its words from `account.deletePage`), so You carries no group of its own for it: the    // iPhone drew every group, and a second "Delete account" row stood above the part, its tap going nowhere    // (DELETE ACCOUNT LEFT, 26 Nov 2026).    let help = group("help", you("help"), None, vec![page("help", you("help"), Some(you("help_line")))], vec![]);    let about = group("about", you("about"), None, vec![page("about", crate::phone::secrets_app::app_name(), Some(you("about_line")))], vec![]);    let mut groups = vec![open_with, lock, clipboard, dashlane, export, look, sync];    groups.extend([privacy, storage, help, about]);    Ok(SettingsAnswer { title: you("title"), groups })}/// The apps a CSV is read from, as `password.importCsv` knows them.fn import_sources() -> Vec<(String, String)> {    let formats: Value = serde_json::from_str(include_str!("../../../cotton-core/src/keys/password_csv_formats.json")).unwrap_or(Value::Null);    let list = formats.get("formats").and_then(Value::as_array).cloned().or_else(|| formats.as_array().cloned()).unwrap_or_default();    list.iter().filter_map(|format| Some((format["id"].as_str()?.to_string(), format["name"].as_str().or(format["id"].as_str())?.to_string()))).collect()}// ── vault.act ──────────────────────────────────────────────────────────fn act(client: &ClientController, request: &Value) -> Result<ActAnswer, MethodError> {    let what = text(request, "act")?.to_string();    let id = optional(request, "id").map(str::to_string);    let need_id = || id.clone().ok_or_else(|| bad("id", "required text"));    let done = |toast: Option<Toast>, item: Option<ItemAnswer>, gone: bool| ActAnswer { act: what.clone(), id: id.clone(), toast, item: item.map(Box::new), gone, platform: None };    let platform = |action: Value| ActAnswer { act: what.clone(), id: id.clone(), toast: None, item: None, gone: false, platform: Some(action) };    match what.as_str() {        "favourite" | "unfavourite" => {            let id = need_id()?;            crate::phone::keys::over(client, "keys.favourite", &json!({"id": id, "on": what == "favourite"}))?;            let line = if what == "favourite" { "item.favourited" } else { "item.unfavourited" };            Ok(done(Some(Toast { text: s(line), undo: None }), item(client, &id).ok(), false))        }        "trash" => {            let id = need_id()?;            crate::phone::vault::over(client, "vault.trash", &json!({"id": id}))?;            let undo = act_of("undo", s("item.undo"), "vault.act", json!({"act": "restore", "id": id}));            Ok(done(Some(Toast { text: s("item.trashed"), undo: Some(undo) }), None, true))        }        "restore" => {            let id = need_id()?;            crate::phone::keys::over(client, "keys.restore", &json!({"id": id}))?;            Ok(done(Some(Toast { text: s("item.restored"), undo: None }), item(client, &id).ok(), false))        }        "copied" => {            let seconds = preferences(client)?.clipboard_seconds;            Ok(done(Some(Toast { text: copied_toast(seconds), undo: None }), None, false))        }        "used" => {            let id = need_id()?;            crate::phone::keys::over(client, "keys.used", &json!({"id": id}))?;            Ok(done(None, None, false))        }        "set" => {            let key = text(request, "key")?;            set_preference(client, key, request.get("value").unwrap_or(&Value::Null))?;            Ok(done(None, None, false))        }        "open_site" => {            let id = need_id()?;            let (secrets, _) = all_rows(client)?;            let site = secrets.into_iter().find(|plain| plain.entry.id == id).and_then(|plain| plain.entry.site).ok_or_else(not_found)?;            let address = if site.contains("://") { site } else { format!("https://{site}") };            Ok(platform(json!({"action": "open_url", "url": address})))        }        "open_fill_settings" => Ok(platform(json!({"action": "open_fill_settings"}))),        // A page of the app's own (import, look, privacy, help, about), which the phone draws.        "open_page" => Ok(platform(json!({"action": "open_page", "page": text(request, "page")?}))),        "import" => Ok(platform(json!({"action": "pick_csv", "from": text(request, "from")?, "then": "password.importCsv"}))),        "sign_in" | "back_up" | "sign_out" => {            let id = match what.as_str() {                "sign_in" => crate::phone::tool_acts::ACCOUNT_SIGN_IN,                "back_up" => crate::phone::tool_acts::ACCOUNT_BACK_UP,                _ => crate::phone::tool_acts::ACCOUNT_SIGN_OUT,            };            let answer = crate::phone::tool_acts::account(client, id)?;            // Sign in and Sign out run this device's own flow, as `tools.act`            // answers it (`platform_action: open_flow`): the phone opens it.            if answer.get("platform_action").is_some() {                return Ok(platform(answer));            }            let toast = answer["said"].as_str().map(|said| Toast { text: said.to_string(), undo: None });            Ok(done(toast, None, false))        }        "empty_bin" => {            crate::phone::keys::over(client, "keys.emptyBin", &json!({}))?;            Ok(done(None, None, false))        }        other => Err(bad("act", &format!("an act Vault knows, not `{other}`"))),    }}/// The bin keeps things this many days (the line says it in words).pub const BIN_DAYS: u64 = TRASH_DAYS;/// Every kind the add form knows, as the payload declares them.pub fn kinds() -> Vec<&'static str> {    SECRET_KINDS.iter().map(|spec| spec.kind.as_str()).collect()}#[cfg(test)]#[path = "vault_app_tests.rs"]mod tests;