Cotton code
858 lines · 41.6 KB · RustRaw
//! `keys.*` — Cotton Keys as a whole password manager, answered by the core//! on this device. Every kind of secret, its one-time code, the generator,//! Health, AutoFill's questions, the bin and the exports.//!//! ```text//! keys.add            any kind: login, code, note, card, identity, wifi, address, api key//! keys.change         its plain columns and its fields; a login's old password goes to its history//! keys.history        a login's last ten passwords                                  (behind the unlock)//! keys.favourite      on or off the Favourites view//! keys.code           a code's (or a login's) one-time code and the seconds it has left//! keys.codes          every code at once, for the Codes view's dials//! keys.generate       a password by a recipe (random switches or EFF words), its bits and strength//! keys.strength       how strong a password reads, on the device//! keys.health         weak, reused (keyed hashes inside the unlock) and old, named by id//! keys.breachPrefixes the five SHA-1 characters the breach range is asked by (an act the person runs)//! keys.breachCheck    the range answers read against the rest, named by id and count//! keys.forService     the logins that fill on a site (or an Android app's), the same host first, never by substring//! keys.identities     what AutoFill's identity store takes beside passkey.identities: logins and codes//! keys.used           a fill: last used now, uses one more//! keys.offerSave      after a manual fill: save, update or nothing//! keys.afterFill      the code to copy once a login with a code has filled//! keys.restore        out of the bin//! keys.emptyBin       what has been in the bin over thirty days, gone//! keys.exportCsv      the logins as CSV, with the plain warning              (behind the unlock)//! keys.exportCxf      everything as Credential Exchange, with the warning   (behind the unlock)//! ```//!//! **Nothing here decides in the shell.** The answers carry what a face//! shows and what an act does; a shell draws them. **No value reaches a log//! line, a refusal or a `data` event**: a value is answered to its one caller//! (a reveal, a code, an export) and nowhere else. The rows are the object's//! `secret` table (`cotton_secrets` here), sealed as `password.*` seals them//! ([`cotton_core::keys::password_row`], v2 under the VMK), and the VMK is//! the five-minute unlock's or lent for the call (`privateKey`).use serde_json::{json, Map, Value};use cotton_core::constants::BinKind;use cotton_core::keys::autofill::{self, Candidate, Kept};use cotton_core::keys::domain::host_of;use cotton_core::keys::autofill::site_of_app;use cotton_core::keys::export;use cotton_core::keys::generator::{strength, Recipe};use cotton_core::keys::health::{self, ReuseKey, RANGE_URL};use cotton_core::keys::history::{trash_due, History, HISTORY_ENC};use cotton_core::keys::password_import;use cotton_core::keys::password_row;use cotton_core::keys::totp::Totp;use cotton_core::vault::payload::{SecretKind, SecretPayload};use cotton_core::vault::Vmk;use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{insert_row, update_row};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::phone::passkeys::with_vmk;use crate::phone::passwords::{json_row, live, row_of, sealed_here, SECRETS};use crate::shell::client::ClientController;/// Every method this family answers.pub const METHODS: [&str; 20] = [    "keys.add",    "keys.afterFill",    "keys.breachCheck",    "keys.breachPrefixes",    "keys.change",    "keys.code",    "keys.codes",    "keys.emptyBin",    "keys.exportCsv",    "keys.exportCxf",    "keys.favourite",    "keys.forService",    "keys.generate",    "keys.health",    "keys.history",    "keys.identities",    "keys.offerSave",    "keys.restore",    "keys.strength",    "keys.used",];/// `keys.*` over this device's own database.pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    over(&handle.client(), method, request)}/// The same, over a named controller (the suite's phone).pub fn over(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "keys.add" => add(client, request),        "keys.change" => change(client, request),        "keys.history" => history(client, request),        "keys.favourite" => favourite(client, request),        "keys.code" => code(client, request),        "keys.codes" => codes(client, request),        "keys.generate" => generate(request),        "keys.strength" => strength_of(request),        "keys.health" => health_of(client, request),        "keys.breachPrefixes" => breach_prefixes(client, request),        "keys.breachCheck" => breach_check(client, request),        "keys.forService" => for_service(client, request),        "keys.identities" => identities(client, request),        "keys.used" => used(client, request),        "keys.offerSave" => offer_save(client, request),        "keys.afterFill" => after_fill(client, request),        "keys.restore" => restore(client, request),        "keys.emptyBin" => empty_bin(client),        "keys.exportCsv" => export_csv(client, request),        "keys.exportCxf" => export_cxf(client, request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a keys method"))),    }}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 refused(reason: String) -> MethodError {    MethodError::new("write_refused", reason)}fn not_found() -> MethodError {    MethodError::new("secret_not_found", "Nothing with this id is kept here.")}fn unix_of(iso: &str) -> Option<u64> {    chrono::DateTime::parse_from_rfc3339(iso).ok().map(|at| at.timestamp().max(0) as u64)}fn now_unix(client: &ClientController) -> u64 {    client.now().timestamp().max(0) as u64}/// A payload from a kind and its fields, every field checked against the/// kind's declaration: an unknown field is refused by name, never dropped.fn payload_of(kind: SecretKind, fields: &Map<String, Value>) -> Result<SecretPayload, MethodError> {    let spec = kind.spec();    let mut object = Map::new();    object.insert("kind".into(), json!(kind.as_str()));    for (key, value) in fields {        if !spec.fields.iter().any(|field| field.name == key) {            return Err(bad(&format!("fields.{key}"), &format!("not a field of a {} secret", kind.as_str())));        }        match value {            Value::Null => {}            Value::String(text) if text.trim().is_empty() && key != spec.primary => {}            Value::String(text) => {                object.insert(key.clone(), json!(text));            }            _ => return Err(bad(&format!("fields.{key}"), "text")),        }    }    let payload: SecretPayload = serde_json::from_value(Value::Object(object)).map_err(|_| bad(&format!("fields.{}", spec.primary), "required text"))?;    if let SecretPayload::Code { secret, .. } = &payload {        Totp::parse(secret).map_err(|error| MethodError::new("bad_code", error.to_string()))?;    }    if let SecretPayload::Login { totp: Some(address), .. } = &payload {        Totp::parse(address).map_err(|error| MethodError::new("bad_code", error.to_string()))?;    }    Ok(payload)}/// The payload with `fields` laid over it: a field given replaces, null or/// blank (an optional one) removes, one not given stays.fn merged(held: &SecretPayload, fields: &Map<String, Value>) -> Result<SecretPayload, MethodError> {    let mut object = match serde_json::to_value(held).map_err(|error| MethodError::new("unreadable", error.to_string()))? {        Value::Object(object) => object,        _ => Map::new(),    };    object.remove("kind");    for (key, value) in fields {        object.insert(key.clone(), value.clone());    }    payload_of(held.kind(), &object)}fn fields_of(request: &Value) -> Result<Map<String, Value>, MethodError> {    match request.get("fields") {        None | Some(Value::Null) => Ok(Map::new()),        Some(Value::Object(fields)) => Ok(fields.clone()),        Some(_) => Err(bad("fields", "an object of text")),    }}/// The password a kind's history keeps: a login's (and a wifi network's).fn kept_password(payload: &SecretPayload) -> Option<&str> {    match payload {        SecretPayload::Login { password, .. } | SecretPayload::Wifi { password, .. } => Some(password),        _ => None,    }}/// `keys.add {kind, name?, site?, username?, fields, favourite?, privateKey?}`/// — one secret of any kind, its fields sealed v2 under the VMK and bound to/// the new row. A login's site is the host of the address given, and a login/// already kept for the same site and user name refuses `password_held`.fn add(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let kind = SecretKind::parse(text(request, "kind")?).ok_or_else(|| bad("kind", "a kind of secret"))?;    let payload = payload_of(kind, &fields_of(request)?)?;    let site = match optional(request, "site") {        Some(site) => Some(password_import::site_of(site).ok_or_else(|| bad("site", "an address"))?),        None => None,    };    let username = optional(request, "username").map(str::to_string);    let name = optional(request, "name")        .map(str::to_string)        .or_else(|| site.clone())        .or_else(|| match &payload {            SecretPayload::Code { secret, .. } => Totp::parse(secret).ok().and_then(|totp| totp.issuer.or(totp.account)),            _ => None,        })        .ok_or_else(|| bad("name", "required text"))?;    let favourite = request.get("favourite").and_then(Value::as_bool).unwrap_or(false);    let now = client.now_iso();    with_vmk(client, request, |vmk, version| {        let answer = client            .write_rows("keys.add", &mut |ctx| {                if kind == SecretKind::Login {                    let same = live(                        ctx,                        "id",                        "kind = 'login' AND coalesce(site, '') = ? AND coalesce(username, '') = ?",                        vec![rusqlite::types::Value::Text(site.clone().unwrap_or_default()), rusqlite::types::Value::Text(username.clone().unwrap_or_default())],                    )?;                    if !same.is_empty() {                        return Ok(json!({ "held": true }));                    }                }                let id = ctx.new_uuid();                let sealed = password_row::seal(&payload, vmk, &id, version).map_err(|error| error.to_string())?;                let mut row = sealed.columns();                row.insert("kind".into(), json!(kind.as_str()));                row.insert("name".into(), json!(cotton_core::vault::columns::shorten(&name, cotton_core::vault::columns::NAME_MAX)));                row.insert("site".into(), json!(site));                row.insert("username".into(), json!(username));                row.insert("favourite_at".into(), if favourite { json!(now) } else { Value::Null });                row.insert("changed_at".into(), if kept_password(&payload).is_some() { json!(now) } else { Value::Null });                for column in ["service", "hint", "last_used_at", "expires_at", "trashed_at", "passkey_id", HISTORY_ENC] {                    row.insert(column.into(), Value::Null);                }                insert_row(ctx, SECRETS, &id, row).map_err(|failure| failure.to_string())?;                Ok(json!({ "id": id }))            })            .map_err(refused)?;        let answer = crate::authoring::own_answer(answer);        if answer["held"] == json!(true) {            return Err(MethodError::new("password_held", "A login for this site and user name is already kept here."));        }        Ok(json!({ "id": answer["id"], "kind": kind.as_str() }))    })}/// `keys.change {id, name?, site?, username?, passkeyId?, fields?, privateKey?}`/// — plain columns need no vault; fields open, change and reseal at the/// vault's version. A login's (or wifi network's) password that changes goes/// to the front of its history, sealed, at most ten, and `changed_at` is now.fn change(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = text(request, "id")?.to_string();    let fields = fields_of(request)?;    let mut plain = Map::new();    if let Some(name) = optional(request, "name") {        plain.insert("name".into(), json!(cotton_core::vault::columns::shorten(name, cotton_core::vault::columns::NAME_MAX)));    }    if let Some(site) = request.get("site") {        let site = site.as_str().map(str::trim).filter(|site| !site.is_empty());        plain.insert("site".into(), json!(site.map(|site| password_import::site_of(site)).flatten()));    }    if let Some(username) = request.get("username") {        plain.insert("username".into(), json!(username.as_str().map(str::trim).filter(|user| !user.is_empty())));    }    if let Some(passkey) = request.get("passkeyId") {        plain.insert("passkey_id".into(), json!(passkey.as_str().filter(|id| !id.is_empty())));    }    let now = client.now_iso();    let write = |vmk: Option<(&Vmk, u32)>| -> Result<Value, MethodError> {        let answer = client            .write_rows("keys.change", &mut |ctx| {                let Some(row) = row_of(ctx, &id, "id, kind, value_enc, vmk_version, history_enc")? else {                    return Ok(json!({ "found": false }));                };                let mut patch = plain.clone();                let mut password_changed = false;                if let Some((vmk, version)) = vmk {                    if !sealed_here(&row) {                        return Ok(json!({ "found": true, "sealed_here": false }));                    }                    let held = match password_row::open(&row, &id, vmk) {                        Ok(payload) => payload,                        Err(error) => return Ok(json!({ "found": true, "refused": error.to_string() })),                    };                    let next = match merged(&held, &fields) {                        Ok(next) => next,                        Err(error) => return Ok(json!({ "found": true, "bad": error.message })),                    };                    if let (Some(old), Some(new)) = (kept_password(&held), kept_password(&next)) {                        if old != new {                            password_changed = true;                            let mut past = History::open(&row, &id, vmk).map_err(|error| error.to_string())?;                            past.push(old, &now);                            patch.insert(HISTORY_ENC.into(), json!(past.seal(vmk, &id, version).map_err(|error| error.to_string())?));                            patch.insert("changed_at".into(), json!(now));                        }                    }                    patch.extend(password_row::seal(&next, vmk, &id, version).map_err(|error| error.to_string())?.columns());                }                if !patch.is_empty() {                    update_row(ctx, SECRETS, &id, patch).map_err(|failure| failure.to_string())?;                }                Ok(json!({ "found": true, "id": id, "password_changed": password_changed }))            })            .map_err(refused)?;        let answer = crate::authoring::own_answer(answer);        if answer["found"] == json!(false) {            return Err(not_found());        }        if answer["sealed_here"] == json!(false) {            return Err(MethodError::new("not_sealed_here", "This was saved before your vault was encrypted on your devices. It opens once it is moved."));        }        if let Some(reason) = answer["refused"].as_str() {            return Err(MethodError::new("does_not_open", reason.to_string()));        }        if let Some(reason) = answer["bad"].as_str() {            return Err(MethodError::new("bad_request", reason.to_string()));        }        Ok(json!({ "id": answer["id"], "passwordChanged": answer["password_changed"] }))    };    if fields.is_empty() {        write(None)    } else {        with_vmk(client, request, |vmk, version| write(Some((vmk, version))))    }}/// Open one live row's payload under the VMK: `Err` in words, never its value.fn opened(ctx: &Ctx<'_>, id: &str, vmk: &Vmk, columns: &str) -> Result<Option<(Map<String, Value>, SecretPayload)>, String> {    let Some(row) = row_of(ctx, id, columns)? else {        return Ok(None);    };    if !sealed_here(&row) {        return Err("this was saved before your vault sealed on your devices".to_string());    }    let payload = password_row::open(&row, id, vmk).map_err(|error| error.to_string())?;    Ok(Some((row, payload)))}/// Every live row of these kinds this device can open, opened: `(row, payload)`.fn all_opened(ctx: &Ctx<'_>, vmk: &Vmk, kinds: &[SecretKind], columns: &str) -> Result<Vec<(Map<String, Value>, SecretPayload)>, String> {    let list: Vec<String> = kinds.iter().map(|kind| format!("'{}'", kind.as_str())).collect();    let rows = live(ctx, columns, &format!("kind IN ({}) ORDER BY lower(name), id", list.join(", ")), vec![])?;    Ok(rows        .into_iter()        .filter(sealed_here)        .filter_map(|row| {            let id = row.get("id").and_then(Value::as_str)?.to_string();            password_row::open(&row, &id, vmk).ok().map(|payload| (row, payload))        })        .collect())}fn read<R>(client: &ClientController, label: &'static str, work: impl FnOnce(&mut Ctx<'_>) -> Result<R, String>) -> Result<R, MethodError>where    R: serde::Serialize + serde::de::DeserializeOwned,{    let mut work = Some(work);    let answer = client        .write_rows(label, &mut |ctx| {            let work = work.take().ok_or_else(|| "called twice".to_string())?;            serde_json::to_value(work(ctx)?).map_err(|error| error.to_string())        })        .map_err(refused)?;    serde_json::from_value(crate::authoring::own_answer(answer)).map_err(|error| MethodError::new("unreadable", error.to_string()))}/// `keys.history {id, privateKey?}` — a login's earlier passwords, newest first.fn history(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = text(request, "id")?.to_string();    with_vmk(client, request, |vmk, _| {        let past: Option<History> = read(client, "keys.history", |ctx| {            let Some(row) = row_of(ctx, &id, "id, vmk_version, history_enc")? else {                return Ok(None);            };            History::open(&row, &id, vmk).map(Some).map_err(|error| error.to_string())        })?;        let past = past.ok_or_else(not_found)?;        Ok(json!({ "id": id, "history": past }))    })}/// `keys.favourite {id, on}` — on or off the Favourites view. No vault.fn favourite(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = text(request, "id")?.to_string();    let on = request.get("on").and_then(Value::as_bool).ok_or_else(|| bad("on", "true or false"))?;    let now = client.now_iso();    let found: bool = read(client, "keys.favourite", |ctx| {        if row_of(ctx, &id, "id")?.is_none() {            return Ok(false);        }        let mut patch = Map::new();        patch.insert("favourite_at".into(), if on { json!(now) } else { Value::Null });        update_row(ctx, SECRETS, &id, patch).map_err(|failure| failure.to_string())?;        Ok(true)    })?;    if !found {        return Err(not_found());    }    Ok(json!({ "id": id, "favourite": on }))}/// The code item's (or login's) address, if it has one.fn code_address(payload: &SecretPayload) -> Option<&str> {    match payload {        SecretPayload::Code { secret, .. } => Some(secret),        SecretPayload::Login { totp: Some(address), .. } => Some(address),        _ => None,    }}/// The seconds a code's dial turns red for.const EXPIRING_SECONDS: u64 = 5;fn code_answer(id: &str, name: &Value, address: &str, now: u64) -> Result<Value, String> {    let totp = Totp::parse(address).map_err(|error| error.to_string())?;    let code = totp.now(now);    Ok(json!({        "id": id,        "name": name,        "issuer": totp.issuer,        "account": totp.account,        "code": code.code,        "secondsLeft": code.seconds_left,        "period": code.period,        "expiring": code.seconds_left <= EXPIRING_SECONDS,    }))}/// `keys.code {id, privateKey?}` — the one-time code now and the seconds it has left.fn code(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = text(request, "id")?.to_string();    let now = now_unix(client);    with_vmk(client, request, |vmk, _| {        let answer: Result<Value, String> = read(client, "keys.code", |ctx| {            let Some((row, payload)) = opened(ctx, &id, vmk, "id, name, value_enc, vmk_version")? else {                return Ok(Err("not_found".to_string()));            };            let Some(address) = code_address(&payload) else {                return Ok(Err("no_code".to_string()));            };            Ok(code_answer(&id, &row["name"], address, now))        })?;        match answer {            Ok(value) => Ok(value),            Err(reason) if reason == "not_found" => Err(not_found()),            Err(reason) if reason == "no_code" => Err(MethodError::new("no_code", "This keeps no one-time code.")),            Err(reason) => Err(MethodError::new("bad_code", reason)),        }    })}/// `keys.codes {privateKey?}` — every code and every login's code, now.fn codes(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let now = now_unix(client);    with_vmk(client, request, |vmk, _| {        let codes: Vec<Value> = read(client, "keys.codes", |ctx| {            let all = all_opened(ctx, vmk, &[SecretKind::Code, SecretKind::Login], "id, name, value_enc, vmk_version")?;            Ok(all                .iter()                .filter_map(|(row, payload)| {                    let id = row.get("id").and_then(Value::as_str)?;                    code_address(payload).and_then(|address| code_answer(id, &row["name"], address, now).ok())                })                .collect())        })?;        Ok(json!({ "codes": codes }))    })}/// `keys.generate {recipe?}` — a password by the recipe (the shipped one: 20/// random characters), with the bits the recipe draws and its strength.fn generate(request: &Value) -> Result<Value, MethodError> {    let recipe = match request.get("recipe") {        None | Some(Value::Null) => Recipe::shipped(),        Some(value) => Recipe::from_value(value).map_err(|error| MethodError::new("bad_recipe", error.to_string()))?,    };    let made = 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()))?;    Ok(json!({ "password": made.as_str(), "recipe": recipe, "bits": (bits * 10.0).round() / 10.0, "strength": strength(&made) }))}/// `keys.strength {password}` — how strong a password reads, on the device.fn strength_of(request: &Value) -> Result<Value, MethodError> {    let password = request.get("password").and_then(Value::as_str).ok_or_else(|| bad("password", "text"))?;    Ok(json!(strength(password)))}/// `keys.health {privateKey?}` — weak, reused and old, by id, with the counts.fn health_of(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let now = now_unix(client);    with_vmk(client, request, |vmk, _| {        let key = ReuseKey::from_vmk(vmk);        let findings: Vec<Value> = read(client, "keys.health", |ctx| {            let all = all_opened(ctx, vmk, &[SecretKind::Login], "id, name, site, changed_at, created_at, value_enc, vmk_version")?;            let items: Vec<health::Item<'_>> = all                .iter()                .filter_map(|(row, payload)| {                    Some(health::Item {                        id: row.get("id").and_then(Value::as_str)?,                        password: kept_password(payload)?,                        changed_at: row.get("changed_at").or_else(|| row.get("created_at")).and_then(Value::as_str).and_then(unix_of),                    })                })                .collect();            let names: std::collections::HashMap<&str, &Value> = all.iter().filter_map(|(row, _)| Some((row.get("id")?.as_str()?, &row["name"]))).collect();            Ok(health::check(&items, &key, now)                .into_iter()                .map(|finding| {                    let mut value = json!(finding);                    value["name"] = names.get(finding.id.as_str()).map(|name| (*name).clone()).unwrap_or(Value::Null);                    value                })                .collect())        })?;        let count = |flag: &dyn Fn(&Value) -> bool| findings.iter().filter(|finding| flag(finding)).count();        let counts = json!({            "weak": count(&|finding| finding["weak"] == json!(true)),            "reused": count(&|finding| finding["reused_with"].as_array().is_some_and(|with| !with.is_empty())),            "old": count(&|finding| finding["old"] == json!(true)),        });        Ok(json!({ "findings": findings, "counts": counts }))    })}/// `keys.breachPrefixes {privateKey?}` — the distinct five-character SHA-1/// prefixes of every login's password, and the address each is asked at./// Only the prefixes leave the core; the shell asks them when the person runs the check.fn breach_prefixes(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    with_vmk(client, request, |vmk, _| {        let prefixes: Vec<String> = read(client, "keys.breachPrefixes", |ctx| {            let all = all_opened(ctx, vmk, &[SecretKind::Login], "id, value_enc, vmk_version")?;            let mut set: Vec<String> = all.iter().filter_map(|(_, payload)| kept_password(payload)).map(|password| health::breach_range(password).0).collect();            set.sort();            set.dedup();            Ok(set)        })?;        let addresses: Vec<String> = prefixes.iter().map(|prefix| RANGE_URL.replace("{prefix}", prefix)).collect();        Ok(json!({ "prefixes": prefixes, "addresses": addresses, "padding": true }))    })}/// `keys.breachCheck {ranges: {prefix: body}, privateKey?}` — each login whose/// password the range answers have seen, by id and count. A prefix with no/// answer or one that does not read is named in `unread`.fn breach_check(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let ranges = request.get("ranges").and_then(Value::as_object).ok_or_else(|| bad("ranges", "an object of range answers by prefix"))?.clone();    with_vmk(client, request, |vmk, _| {        let (breached, unread): (Vec<Value>, Vec<String>) = read(client, "keys.breachCheck", |ctx| {            let all = all_opened(ctx, vmk, &[SecretKind::Login], "id, name, value_enc, vmk_version")?;            let mut breached = Vec::new();            let mut unread = std::collections::BTreeSet::new();            for (row, payload) in &all {                let Some(password) = kept_password(payload) else { continue };                let (prefix, suffix) = health::breach_range(password);                match ranges.get(&prefix).and_then(Value::as_str).filter(|body| health::is_range_body(body)) {                    None => {                        unread.insert(prefix);                    }                    Some(body) => {                        let count = health::breach_count(body, &suffix);                        if count > 0 {                            breached.push(json!({ "id": row["id"], "name": row["name"], "count": count }));                        }                    }                }            }            Ok((breached, unread.into_iter().collect()))        })?;        Ok(json!({ "breached": breached, "unread": unread }))    })}/// `keys.forService {service | app, fillable?, users?, privateKey?}` — the/// logins that fill on a site (a domain or an address), the same host first,/// then the same site by last use; never by substring. With the vault open a/// login's other addresses count. An Android app that names no web domain/// asks by its application id (`app`), read as a site by/// [`site_of_app`]; the answer's `service` is the site it was read as (where a/// save from that app is kept). `fillable` keeps only the logins that open on/// this phone (sealed here), the ones a fill can hand over; `users` (the/// request's allowed user names, Credential Manager's `allowedUserIds`) keeps/// only those when it names any.fn for_service(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let service = match optional(request, "service").filter(|service| !service.trim().is_empty()) {        Some(service) => service.to_string(),        None => {            let app = text(request, "app").map_err(|_| bad("service", "a domain or an address (or `app`, an Android application id)"))?;            site_of_app(app).ok_or_else(|| bad("app", "an application id that names a site"))?        }    };    host_of(&service).ok_or_else(|| bad("service", "a domain or an address"))?;    let fillable = request.get("fillable").and_then(Value::as_bool).unwrap_or(false);    let users: Vec<String> = match request.get("users") {        None | Some(Value::Null) => Vec::new(),        Some(Value::Array(names)) => names.iter().map(|name| name.as_str().map(str::to_string).ok_or_else(|| bad("users", "a list of user names"))).collect::<Result<_, _>>()?,        Some(_) => return Err(bad("users", "a list of user names")),    };    let rank = |vmk: Option<&Vmk>| -> Result<Value, MethodError> {        let logins: Vec<Value> = read(client, "keys.forService", |ctx| {            let rows = live(ctx, "id, name, site, username, last_used_at, value_enc, vmk_version", "kind = 'login' ORDER BY id", vec![])?;            let urls: Vec<Option<String>> = rows                .iter()                .map(|row| {                    let id = row.get("id").and_then(Value::as_str)?;                    let vmk = vmk?;                    match password_row::open(row, id, vmk).ok()? {                        SecretPayload::Login { urls, .. } => urls,                        _ => None,                    }                })                .collect();            let candidates: Vec<Candidate<'_>> = rows                .iter()                .zip(&urls)                .filter_map(|(row, urls)| {                    Some(Candidate {                        id: row.get("id").and_then(Value::as_str)?,                        name: row.get("name").and_then(Value::as_str).unwrap_or(""),                        site: row.get("site").and_then(Value::as_str),                        urls: urls.as_deref(),                        last_used_at: row.get("last_used_at").and_then(Value::as_str),                    })                })                .collect();            let by_id: std::collections::HashMap<&str, &Map<String, Value>> = rows.iter().filter_map(|row| Some((row.get("id")?.as_str()?, row))).collect();            Ok(autofill::rank(&service, &candidates)                .into_iter()                .filter_map(|ranked| {                    let row = by_id.get(ranked.id.as_str())?;                    if fillable && !sealed_here(row) {                        return None;                    }                    if !users.is_empty() && !users.iter().any(|user| row.get("username").and_then(Value::as_str) == Some(user.as_str())) {                        return None;                    }                    Some(json!({ "id": ranked.id, "name": row["name"], "site": row["site"], "username": row["username"], "match": ranked.matched, "opens": sealed_here(row) }))                })                .collect())        })?;        Ok(json!({ "service": service, "logins": logins }))    };    if request.get("privateKey").is_some_and(|key| !key.is_null()) || client.vault().ok().is_some_and(|door| door.with_vmk(client.now(), |_, _| ()).is_some()) {        with_vmk(client, request, |vmk, _| rank(Some(vmk)))    } else {        rank(None)    }}/// `keys.identities {privateKey?}` — what AutoFill's identity store takes/// beside `passkey.identities`: every login that opens here (site, user name,/// record id) and, with the vault open, every one-time code (its login's or/// its own site, label, record id).fn identities(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let passwords: Vec<Value> = read(client, "keys.identities", |ctx| {        let rows = live(ctx, "id, name, site, username, value_enc", "kind = 'login' AND site IS NOT NULL ORDER BY id", vec![])?;        Ok(rows.iter().filter(|row| sealed_here(row)).map(|row| json!({ "id": row["id"], "service": row["site"], "user": row["username"].as_str().unwrap_or("") })).collect())    })?;    let codes = if request.get("privateKey").is_some_and(|key| !key.is_null()) || client.vault().ok().is_some_and(|door| door.with_vmk(client.now(), |_, _| ()).is_some()) {        with_vmk(client, request, |vmk, _| {            read(client, "keys.identities", |ctx| {                let all = all_opened(ctx, vmk, &[SecretKind::Code, SecretKind::Login], "id, name, site, value_enc, vmk_version")?;                Ok(all                    .iter()                    .filter_map(|(row, payload)| {                        let address = code_address(payload)?;                        let totp = Totp::parse(address).ok()?;                        let service = row.get("site").and_then(Value::as_str).map(str::to_string).or_else(|| totp.issuer.clone())?;                        Some(json!({ "id": row["id"], "service": service, "label": totp.account.clone().or(totp.issuer.clone()).unwrap_or_default() }))                    })                    .collect::<Vec<Value>>())            })        })?    } else {        Vec::new()    };    Ok(json!({ "passwords": passwords, "codes": codes }))}/// `keys.used {id}` — a fill: last used now, one use more. No vault.fn used(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = text(request, "id")?.to_string();    let now = client.now_iso();    let uses: Option<i64> = read(client, "keys.used", |ctx| {        let Some(row) = row_of(ctx, &id, "id, uses")? else {            return Ok(None);        };        let uses = row.get("uses").and_then(Value::as_i64).unwrap_or(0) + 1;        let mut patch = Map::new();        patch.insert("last_used_at".into(), json!(now));        patch.insert("uses".into(), json!(uses));        update_row(ctx, SECRETS, &id, patch).map_err(|failure| failure.to_string())?;        Ok(Some(uses))    })?;    let uses = uses.ok_or_else(not_found)?;    Ok(json!({ "id": id, "uses": uses, "lastUsedAt": now }))}/// `keys.offerSave {site, username?, password, privateKey?}` — after a manual/// fill: `save` (no login for this site and user name), `update` (kept with/// another password) or `nothing`. The passwords are compared opened, here.fn offer_save(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let site = text(request, "site")?.to_string();    let username = optional(request, "username").map(str::to_string);    let password = request.get("password").and_then(Value::as_str).filter(|value| !value.is_empty()).ok_or_else(|| bad("password", "required text"))?.to_string();    with_vmk(client, request, |vmk, _| {        let offer: Option<autofill::Offer> = read(client, "keys.offerSave", |ctx| {            let all = all_opened(ctx, vmk, &[SecretKind::Login], "id, site, username, value_enc, vmk_version")?;            let kept: Vec<Kept<'_>> = all                .iter()                .filter_map(|(row, payload)| {                    Some(Kept { id: row.get("id")?.as_str()?, site: row.get("site").and_then(Value::as_str), username: row.get("username").and_then(Value::as_str), password: kept_password(payload)? })                })                .collect();            Ok(autofill::offer(&site, username.as_deref(), &password, &kept))        })?;        offer.map(|offer| json!(offer)).ok_or_else(|| bad("site", "a domain or an address"))    })}/// `keys.afterFill {id, privateKey?}` — once a login has filled: its code to/// copy now, when it keeps one (`copies` null when it does not).fn after_fill(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = text(request, "id")?.to_string();    let now = now_unix(client);    with_vmk(client, request, |vmk, _| {        let (found, copies): (bool, Option<String>) = read(client, "keys.afterFill", |ctx| {            let Some((_, payload)) = opened(ctx, &id, vmk, "id, value_enc, vmk_version")? else {                return Ok((false, None));            };            Ok((true, code_address(&payload).and_then(|address| Totp::parse(address).ok()).map(|totp| totp.code_at(now))))        })?;        if !found {            return Err(not_found());        }        Ok(json!({ "id": id, "copies": copies }))    })}/// `keys.restore {id}` — out of the bin.fn restore(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = text(request, "id")?.to_string();    let found: bool = read(client, "keys.restore", |ctx| {        let held = ctx            .db()            .get(&format!("SELECT id FROM {SECRETS} WHERE workspace_id = ? AND id = ? AND trashed_at IS NOT NULL"), &[ctx.workspace_id.to_string().into(), id.clone().into()])            .map_err(|error| error.to_string())?;        if held.is_none() {            return Ok(false);        }        cotton_tools::mcp::handlers::secrets::set_trashed(ctx, &id, false).map_err(|failure| failure.to_string())?;        Ok(true)    })?;    if !found {        return Err(MethodError::new("secret_not_found", "Nothing with this id is in the bin."));    }    Ok(json!({ "id": id, "restored": true }))}/// `keys.emptyBin {}` — every secret in the bin over thirty days, gone for good.fn empty_bin(client: &ClientController) -> Result<Value, MethodError> {    let now = now_unix(client);    let erased: usize = read(client, "keys.emptyBin", |ctx| {        let binned = ctx            .db()            .all(&format!("SELECT id, trashed_at FROM {SECRETS} WHERE workspace_id = ? AND trashed_at IS NOT NULL"), &[ctx.workspace_id.to_string().into()])            .map_err(|error| error.to_string())?;        let due: Vec<String> = binned            .iter()            .map(json_row)            .filter(|row| row.get("trashed_at").and_then(Value::as_str).and_then(unix_of).is_some_and(|at| trash_due(at, now)))            .filter_map(|row| row.get("id").and_then(Value::as_str).map(str::to_string))            .collect();        if due.is_empty() {            return Ok(0);        }        cotton_tools::mcp::handlers::bin::erase(ctx, BinKind::Secret, &due).map_err(|failure| failure.to_string())?;        Ok(due.len())    })?;    Ok(json!({ "erased": erased }))}const EXPORT_COLUMNS: &str = "id, kind, name, site, username, favourite_at, created_at, value_enc, vmk_version";/// `keys.exportCsv {privateKey?}` — every login as an Apple Passwords CSV, and/// the warning the shell shows before it is saved.fn export_csv(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    crate::phone::recovery::with_fresh_vmk(client, request, |vmk, _| {        let (text, left_out): (String, usize) = read(client, "keys.exportCsv", |ctx| {            let all = all_opened(ctx, vmk, &SecretKind::ALL, EXPORT_COLUMNS)?;            let items = export_items(&all);            let csv = export::to_csv(&items);            Ok((csv.text.to_string(), csv.left_out))        })?;        Ok(json!({ "text": text, "leftOut": left_out, "warning": export::WARNING, "fileName": "Cotton Vault.csv" }))    })}/// `keys.exportCxf {privateKey?}` — every secret and passkey as Credential Exchange.fn export_cxf(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let now = now_unix(client);    crate::phone::recovery::with_fresh_vmk(client, request, |vmk, _| {        let keys = crate::phone::passkeys::opened_all(client, vmk)?;        let text: String = read(client, "keys.exportCxf", |ctx| {            let all = all_opened(ctx, vmk, &SecretKind::ALL, EXPORT_COLUMNS)?;            let items = export_items(&all);            let passkeys: Vec<export::PasskeyItem<'_>> = keys                .iter()                .map(|held| export::PasskeyItem {                    id: &held.id,                    rp_name: &held.rp_name,                    user_name: &held.user_name,                    user_display_name: &held.user_name,                    passkey: &held.passkey,                    created_at: held.created_at.as_deref().and_then(unix_of),                })                .collect();            Ok(export::to_cxf(&items, &passkeys, now)?.to_string())        })?;        Ok(json!({ "text": text, "warning": export::WARNING, "fileName": "Cotton Vault.json" }))    })}fn export_items(all: &[(Map<String, Value>, SecretPayload)]) -> Vec<export::Item<'_>> {    all.iter()        .filter_map(|(row, payload)| {            Some(export::Item {                id: row.get("id")?.as_str()?,                name: row.get("name").and_then(Value::as_str).unwrap_or(""),                site: row.get("site").and_then(Value::as_str),                username: row.get("username").and_then(Value::as_str),                payload,                created_at: row.get("created_at").and_then(Value::as_str).and_then(unix_of),                favourite: row.get("favourite_at").is_some_and(|at| !at.is_null()),            })        })        .collect()}#[cfg(test)]#[path = "keys_tests.rs"]mod tests;