Cotton code
556 lines · 33.4 KB · RustRaw
//! `seal.*` — this device's data key (DK) for sealed tables (sealing plan//! §2.1, §2.4; L3), and what the sync loop could not open.//!//! The DK lives in the platform's key store, never here: iOS keeps it in the//! Keychain (`DataKey.swift`, `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`,//! NO user presence, so a background pull opens rows), Android in the//! Keystore (`DataKeyring.kt`). The shell hands it to the core at launch as a//! call parameter (`seal.useKey`), the same way `vault.unlock` takes the vault//! key, and the core holds it in memory ([`HeldDataKeys`]) for the sealer the//! sync loop seals and opens with ([`cotton_client::seal::Sealer`]).//!//! When the key store holds nothing (a new device, a wiped Keychain) the DK//! is opened from the object's `seal_key` row with the VMK (`seal.openKey`,//! after `vault.unlock`), and the answer hands the key to the shell to store.//! The first vault device of a database mints it (`seal.mintKey`).//!//! A refusal is by NAME: `vault_locked`, `seal_key_not_minted`,//! `seal_key_minted_already`, `seal_key_missing`, `seal_does_not_open`.//! Nothing falls back to clear.use std::sync::Arc;use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use serde_json::{json, Map, Value};use cotton_client::seal::{self as sealing, HeldDataKeys, DK_ROW, SEAL_KEY_TABLE};use cotton_core::seal::DataKey;use cotton_core::vault::Vmk;use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;/// Every method this family answers.pub const METHODS: [&str; 10] = ["seal.bin", "seal.forgetKey", "seal.heldKey", "seal.makeKey", "seal.mintKey", "seal.openKey", "seal.restoreBinned", "seal.search", "seal.status", "seal.useKey"];pub const NOT_MINTED: &str = "seal_key_not_minted";pub const MINTED_ALREADY: &str = "seal_key_minted_already";pub const NOT_LEARNED: &str = "seal_key_not_learned";/// `seal.makeKey` on a phone that is not its own signed-out database: a/// database on an object takes its key from the vault, never one made here.pub const NOT_MADE_HERE: &str = "seal_key_not_made_here";pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    call_on(&handle.client(), method, request)}pub(crate) fn call_on(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    let database = client.current_database().map_err(|why| MethodError::new("not_attached", why))?;    let keys = client.data_keys();    match method {        "seal.useKey" => {            keys.hold(&database, &key_arg(request)?);            client.nudge_sync();            Ok(json!({"held": true}))        }        "seal.forgetKey" => Ok(json!({"forgotten": keys.forget(&database)})),        // The key the core holds, for the shell to keep in its key store        // (DataKey.swift: no presence, after first unlock), so the next        // launch hands it back with seal.useKey and a background pull opens        // sealed rows. Held only after a vault open took it (seal::ensure).        "seal.heldKey" => {            use cotton_client::seal::DataKeyStore as _;            let dk = keys                .data_key(&database)                .map_err(|why| MethodError::new("could_not_read", why))?                .ok_or_else(|| MethodError::new(sealing::SEAL_KEY_MISSING, "this phone holds no data key: open the vault once"))?;            Ok(json!({"key": URL_SAFE_NO_PAD.encode(dk.expose()), "database": database}))        }        "seal.status" => status(client, &database, keys),        "seal.makeKey" => make(client, &database, keys),        "seal.search" => search(client, &database, keys, request),        "seal.bin" => bin(client, &database, keys, request),        "seal.restoreBinned" => restore_binned(client, request),        "seal.openKey" => {            let row = dk_row(client, &database)?.ok_or_else(|| MethodError::new(NOT_MINTED, "this database has no data key yet: the first vault device mints it"))?;            let dk = with_vmk(client, |vmk, version| sealing::open_data_key(vmk, version, &row))?;            keys.hold(&database, &dk);            client.nudge_sync();            Ok(json!({"key": URL_SAFE_NO_PAD.encode(dk.expose())}))        }        "seal.mintKey" => {            if dk_row(client, &database)?.is_some() {                return Err(MethodError::new(MINTED_ALREADY, "this database has its data key: open it with seal.openKey"));            }            let door = client.object_door().ok_or_else(|| MethodError::new("sign_in_first", "a data key is minted once the database is on its object"))?;            let at = client.now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);            let carried = carried_into(client, &database)?;            let (dk, row) = with_vmk(client, |vmk, version| minted_or_carried(vmk, version, carried, &at))?;            keep_minted(&door, row)?;            if client.carried_key_from(&database).is_some() {                client.set_carried_key(None);            }            keys.hold(&database, &dk);            client.nudge_sync();            Ok(json!({"key": URL_SAFE_NO_PAD.encode(dk.expose())}))        }        _ => Err(MethodError::new("unknown_method", format!("`{method}` is not a seal method"))),    }}/// The minted DK's wrap, kept on the object once as `seal_key` row `dk`.fn keep_minted(door: &crate::phone::personal_object::ObjectDoor, row: Map<String, Value>) -> Result<(), MethodError> {    door.send("POST", cotton_client::transport::object::routes::ACT, Some(&json!({"act": "create", "args": {"table": SEAL_KEY_TABLE, "id": DK_ROW, "data": row}})))?;    Ok(())}/// The data key of the database this phone is on, TAKEN WHILE THE VAULT IS/// OPEN (`vmk` at `version`), the way the person key is/// (`person_key::ensure`): the one held already; else opened from the/// object's `seal_key` row; else, when the copy has learned every `seal_key`/// row the object holds and finds none, minted here and kept on the object/// (the first vault device mints it). Held for the sync loop's sealer and/// answered for the caller.////// WHY HERE. The shell keeps no data key of its own yet (no `DataKey.swift`,/// no `DataKeyring.kt`), so a phone that only ever opened its vault held no/// DK, and `unlock.allow` refused every request `seal_key_missing` (lane/// mac-bench-unlock, 12 Nov 2026). Taking it wherever the vault opens means/// a phone that can allow a window can always sign the grant.////// Refused by name: `seal_key_not_learned` (the copy has not yet pulled the/// object's `seal_key` rows, so a mint could race the one there),/// `sign_in_first`, and the sealing errors of a wrap that does not open.pub(crate) fn ensure(client: &ClientController, vmk: &Vmk, version: u32) -> Result<DataKey, MethodError> {    use cotton_client::seal::DataKeyStore as _;    let database = client.current_database().map_err(|why| MethodError::new("not_attached", why))?;    let keys = client.data_keys();    if let Some(dk) = keys.data_key(&database).map_err(|why| MethodError::new("could_not_read", why))? {        return Ok(dk);    }    let sealing_error = |error: cotton_core::seal::SealError| MethodError::new(error.code(), error.to_string());    let dk = match dk_row(client, &database)? {        // The database has its key: a signed-out phone's own key carried        // into it is retired, as its records go up sealed under this one.        Some(row) => {            let dk = sealing::open_data_key(vmk, version, &row).map_err(sealing_error)?;            // Only a key carried into THIS database is retired (FIRST SYNC 6 REVIEW (4), as `take_late_for`).            if client.carried_key_from(&database).is_some() {                client.set_carried_key(None);            }            dk        }        None => {            if !crate::phone::personal_object::sealer_of(client, &database).has_learned() {                return Err(MethodError::new(NOT_LEARNED, "this phone has not yet read the object's data key: let it sync, then ask again"));            }            let door = client.object_door().ok_or_else(|| MethodError::new("sign_in_first", "a data key is minted once the database is on its object"))?;            let at = client.now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);            let carried = carried_into(client, &database)?;            let (dk, row) = minted_or_carried(vmk, version, carried, &at).map_err(sealing_error)?;            keep_minted(&door, row)?;            // As the take above: only a key carried into THIS database is retired (FIRST SYNC 7 REVIEW).            if client.carried_key_from(&database).is_some() {                client.set_carried_key(None);            }            dk        }    };    keys.hold(&database, &dk);    client.nudge_sync();    Ok(dk)}/// SEAL KEY LATE (the coordinator, 26 Nov 2026): a vault opened before the copy held the database's `seal_key` row/// (a recovery code entered before the first pass) took no data key: [`ensure`] answered [`NOT_LEARNED`], and nothing/// asked again once a pass brought the row, so every sealed row stayed parked for good. After each pass, every database/// this phone holds whose vault is unlocked, whose data key is not held and whose copy now holds that row has it opened/// and held, inside the vault's own borrow. Never minted here (a database with no key on its object is founded only/// by the person's own unlock), and one database's vault never opens another's key. Answers the databases that took it.pub(crate) fn take_late(client: &ClientController) -> Vec<String> {    let mut databases: Vec<String> = client.databases().map(|held| held.into_iter().map(|db| db.id).collect()).unwrap_or_default();    if let Ok(current) = client.current_database() {        if !databases.contains(&current) {            databases.push(current);        }    }    databases        .into_iter()        .filter(|database| match take_late_for(client, database) {            Ok(taken) => taken,            // The code alone: a message may name the database (SEAL KEY LATE REVIEW).            Err(refusal) => {                tracing::warn!("seal: a data key was not taken late — {}", refusal.code);                false            }        })        .collect()}/// FIRST SYNC 8 (the coordinator's review of FIRST SYNC 7 (2)): the parks' keys an older build left unfilled, filled/// after each pass, a slice per hold of the writer (500 parks, one short write), for at most [`PARK_FILL_BUDGET`],/// with a breath between slices so a pass never waits long for the writer. Nothing once the copy's keys are full./// Answers whether they are.pub(crate) fn fill_park_keys(client: &ClientController) -> Result<bool, String> {    let started = std::time::Instant::now();    let path = client.attached_database().map(|database| client.layout().replica(&database));    loop {        let (full, held) = client.with_writer(|replica| {            let connection = replica.driver.connection();            if !cotton_client::seal::fill_owed(connection)? {                return Ok((true, None));            }            let holding = std::time::Instant::now();            let full = cotton_client::seal::fill_park_keys(connection, std::time::Duration::ZERO)?;            Ok((full, Some(holding.elapsed())))        })?;        // Each slice that ran is a hold the phone reports.        if let Some((path, held)) = path.as_ref().zip(held) {            let mut holds = FILL_HOLDS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);            let kept = holds.entry(path.clone()).or_default();            if kept.len() < FILL_HOLDS_KEPT {                kept.push(held.as_millis().min(u32::MAX as u128) as u32);            }        }        if full || started.elapsed() >= PARK_FILL_BUDGET {            return Ok(full);        }        std::thread::sleep(std::time::Duration::from_millis(25));    }}/// The holds of the writer by each fill slice this launch, by copy (milliseconds), for the phone's report.static FILL_HOLDS: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::path::PathBuf, Vec<u32>>>> = std::sync::LazyLock::new(Default::default);/// The most slices' holds kept for one copy (280,000 parks fill in 560).const FILL_HOLDS_KEPT: usize = 20_000;/// The fill slices' holds of the copy at `path` this launch: how many, the longest, and the 99th; none when no slice ran.pub(crate) fn fill_holds(path: &std::path::Path) -> Option<cotton_core::device::reported_state::FillHolds> {    let holds = FILL_HOLDS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);    let mut kept = holds.get(path).filter(|kept| !kept.is_empty())?.clone();    kept.sort_unstable();    Some(cotton_core::device::reported_state::FillHolds {        slices: kept.len() as u64,        max_ms: u64::from(*kept.last()?),        p99_ms: u64::from(kept[(kept.len() * 99 / 100).min(kept.len() - 1)]),    })}/// How long one pass's end fills the parks' keys (about 15 slices on a phone; 280,000 parks fill in a few passes).pub(crate) const PARK_FILL_BUDGET: std::time::Duration = std::time::Duration::from_secs(3);/// [`take_late`] for one database: whether its key was taken now.pub(crate) fn take_late_for(client: &ClientController, database: &str) -> Result<bool, MethodError> {    use cotton_client::seal::DataKeyStore as _;    let keys = client.data_keys();    if keys.data_key(database).map_err(|why| MethodError::new("could_not_read", why))?.is_some() {        return Ok(false);    }    let door = client.vault_session().of(database);    let now = client.now();    if door.until(now).is_none() {        return Ok(false);    }    let Some(row) = dk_row(client, database)? else { return Ok(false) };    let opened = door.with_vmk(now, |vmk, version| sealing::open_data_key(vmk, version, &row));    let Some(opened) = opened else { return Ok(false) };    let dk = opened.map_err(|error| MethodError::new(error.code(), error.to_string()))?;    keys.hold(database, &dk);    // Only a key carried into THIS database is retired: another's carried key stays, or a phone moving its signed-out    // copy into one database while another takes its key late would mint a fresh key there (SEAL KEY LATE REVIEW).    if client.carried_key_from(database).is_some() {        client.set_carried_key(None);    }    tracing::info!("seal: the data key of a vault opened before its row came is held now");    client.nudge_sync();    Ok(true)}/// THE KEY OF A PHONE THAT HAS NOT SIGNED IN (Story Android lane, 20 Nov/// 2026): made here with no question, the first time an app that keeps/// sealed tables runs on its own database. Nothing is anywhere else yet, so/// there is no key to wait for: the banner never shows on a phone that has/// not signed in. The copy keeps its rows in the clear on this phone as every/// copy does; the key is what keyed ids (Health, a chat import) and the first/// back-up use. It never leaves the phone but by the shell's own key store,/// and a database on an object never takes one made here/// ([`makes_here`]): that key comes only from the vault.////// Answers `{key}` for the shell to keep exactly as a first sign-in's key/// (`seal.heldKey`); a key held already is answered again, never replaced./// Refused `seal_key_not_made_here` anywhere else.fn make(client: &ClientController, database: &str, keys: &Arc<HeldDataKeys>) -> Result<Value, MethodError> {    use cotton_client::seal::DataKeyStore as _;    if let Some(dk) = keys.data_key(database).map_err(|why| MethodError::new("could_not_read", why))? {        return Ok(json!({"key": URL_SAFE_NO_PAD.encode(dk.expose()), "made": false}));    }    if !makes_here(client, database)? {        return Err(MethodError::new(NOT_MADE_HERE, "this database's key comes from its vault: sign in, or open it with this phone's lock"));    }    let dk = DataKey::mint();    keys.hold(database, &dk);    Ok(json!({"key": URL_SAFE_NO_PAD.encode(dk.expose()), "made": true}))}/// Whether this phone makes its own key with no question ([`make`]): it is/// not signed in, it stands on a database it started itself (a former/// object's copy, kept after a sign-out or a 401, holds definitions an object/// wrote), and the copy keeps no `seal_key` row (a key that came from an/// object, or any sealed row parked from one).pub(crate) fn makes_here(client: &ClientController, database: &str) -> Result<bool, MethodError> {    if client.signed_in() || client.object_door().is_some() {        return Ok(false);    }    let local = cotton_client::connection::read_connection(&client.layout().connection_json())        .map_err(|why| MethodError::new("could_not_read", why.to_string()))?        .is_some_and(|held| held.mode == cotton_client::connection::ConnectionMode::Local && held.workspace_id.as_deref() == Some(database));    if !local {        return Ok(false);    }    let path = client.layout().replica(database);    if crate::phone::adopt::former_copy(&path)? {        return Ok(false);    }    let file = copy(client, database)?;    let kept = sealing::kept_keys(&file).map_err(|why| MethodError::new("could_not_read", why))?;    let parked = sealing::parked(&file).map_err(|why| MethodError::new("could_not_read", why))?;    Ok(kept.is_empty() && parked.is_empty())}/// The key a back-up carries into `database` from this phone's own/// signed-out database ([`ClientController::carried_key_from`]), held still.fn carried_into(client: &ClientController, database: &str) -> Result<Option<DataKey>, MethodError> {    use cotton_client::seal::DataKeyStore as _;    let Some(local) = client.carried_key_from(database) else { return Ok(None) };    client.data_keys().data_key(&local).map_err(|why| MethodError::new("could_not_read", why))}/// A database's first key and its `seal_key` row: the signed-out phone's own/// key carried into it when there is one (the person's records keep the ids/// it made), else a new one.fn minted_or_carried(vmk: &Vmk, version: u32, carried: Option<DataKey>, at: &str) -> Result<(DataKey, Map<String, Value>), cotton_core::seal::SealError> {    match carried {        Some(dk) => sealing::data_key_row(vmk, version, &dk, at).map(|row| (dk, row)),        None => sealing::mint_data_key(vmk, version, at),    }}/// `seal.search {table, query, limit?}`: a sealed table's rows the object/// holds beyond this copy that hold `query` (word, and word start for the/// last word), opened here: what ink and word-start search over the copy/// cannot find, because the copy keeps only its window/// (`cotton_client::seal::search`). The object is asked by blind tokens/// alone. Answers `{hits: [{id, column, row}], unopened: [{id, code}]}`,/// newest first; the copy's own rows are its own search's and are left out./// Refused by name: `not_sealed`, `seal_key_missing`, `sign_in_first`.fn search(client: &ClientController, database: &str, keys: &Arc<HeldDataKeys>, request: &Value) -> Result<Value, MethodError> {    let table = request["table"].as_str().filter(|t| !t.is_empty()).ok_or_else(|| MethodError::new("bad_request", "seal.search needs `table`"))?;    let query = request["query"].as_str().ok_or_else(|| MethodError::new("bad_request", "seal.search needs `query`, the words written"))?;    let limit = request["limit"].as_u64().map_or(50, |n| n.clamp(1, 1000) as usize);    let tables = cotton_client::transport::object::ObjectTables::personal();    let stored = tables.object(table).ok_or_else(|| MethodError::new("not_sealed", format!("{table} is not a table this phone keeps")))?;    let spec = stored.seal.clone().ok_or_else(|| MethodError::new("not_sealed", format!("{table} is not sealed: search the copy as any table")))?;    let date = cotton_core::definitions::builtin_table_definitions().iter().find(|d| d.id == table).and_then(|d| d.date.clone());    let sealer = sealing::Sealer::new(database, Arc::clone(keys) as Arc<dyn sealing::DataKeyStore>);    if !sealer.has_key() {        return Err(MethodError::new("seal_key_missing", "this phone holds no data key yet: seal.useKey or seal.openKey first"));    }    let door = client.object_door().ok_or_else(|| MethodError::new("sign_in_first", "the object is searched once the database is on it"))?;    let file = copy(client, database)?;    let held_sql = format!("SELECT 1 FROM \"{}\" WHERE \"{}\" = ?1", stored.store.replace('"', "\"\""), stored.key_column.replace('"', "\"\""));    let held = |id: &str| file.query_row(&held_sql, [id], |_| Ok(())).is_ok();    let mut get = |path: &str| door.send("GET", path, None).map_err(|error| format!("{}: {}", error.code, error.message));    let found = sealing::search::search_beyond(&sealer, table, &spec, date.as_deref(), query, limit, &held, &mut get).map_err(|why| {        let code = why.split(':').next().filter(|code| code.starts_with("seal_")).unwrap_or("unreachable").to_string();        MethodError::new(&code, why)    })?;    Ok(json!({        "hits": found.hits.iter().map(|hit| json!({"id": hit.id, "column": hit.column, "row": hit.row})).collect::<Vec<_>>(),        "unopened": found.unopened.iter().map(|(id, code)| json!({"id": id, "code": code})).collect::<Vec<_>>(),    }))}/// `seal.bin {tables, after?, limit?}` (TRIM 3, 21 Nov 2026): the binned rows of `tables` (served names)/// the object holds that this copy does not (a copy keeps only the last 7 days of its Bin:/// `phone::trim::BIN_KEPT_DAYS`), opened here, a page at a time (`GET /v1/bin`). The copy's own binned/// rows are its own Bin's and are left out. Answers `{rows: [{table, id, row}], unopened: [{table, id,/// code}], more, after}`; `after` names the next page. Refused by name: `sign_in_first`,/// `seal_key_missing` (a sealed row with no key held), `unreachable`.fn bin(client: &ClientController, database: &str, keys: &Arc<HeldDataKeys>, request: &Value) -> Result<Value, MethodError> {    let tables: Vec<String> = request["tables"].as_array().map(|tables| tables.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();    if tables.is_empty() || tables.iter().any(|t| t.is_empty() || !t.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')) {        return Err(MethodError::new("bad_request", "seal.bin needs `tables`, the served names of the tables whose Bin is listed"));    }    let limit = request["limit"].as_u64().map_or(200, |n| n.clamp(1, 1000));    let door = client.object_door().ok_or_else(|| MethodError::new("sign_in_first", "the Bin beyond this phone is on the object, once the database is there"))?;    let mut path = format!("/v1/bin?tables={}&limit={limit}", tables.join(","));    if let Some(after) = request["after"].as_str().filter(|after| !after.is_empty()) {        let part: String = after.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.~:".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect();        path.push_str(&format!("&after={part}"));    }    let answer = door.send("GET", &path, None).map_err(|error| MethodError::new("unreachable", format!("{}: {}", error.code, error.message)))?;    let rows = answer["rows"].as_array().cloned().unwrap_or_default();    let sealer = sealing::Sealer::new(database, Arc::clone(keys) as Arc<dyn sealing::DataKeyStore>);    let map = cotton_client::transport::object::ObjectTables::personal();    let file = copy(client, database)?;    let (mut opened, mut unopened) = (Vec::new(), Vec::new());    for row in &rows {        let (Some(table), Some(id)) = (row["table"].as_str(), row["id"].as_str()) else { continue };        let Some(data) = row["data"].as_object() else { continue };        if let Some(stored) = map.object(table) {            let held_sql = format!("SELECT 1 FROM \"{}\" WHERE \"{}\" = ?1", stored.store.replace('"', "\"\""), stored.key_column.replace('"', "\"\""));            if file.query_row(&held_sql, [id], |_| Ok(())).is_ok() {                continue;            }        }        // An open row is answered as it stands; a sealed one opened with the key held.        match sealer.open(table, id, data) {            Ok(open) => opened.push(json!({"table": table, "id": id, "row": open})),            Err(error) => unopened.push(json!({"table": table, "id": id, "code": error.code()})),        }    }    let more = answer["more"].as_bool().unwrap_or(false);    let after = rows.last().filter(|_| more).map(|last| format!("{}:{}", last["table"].as_str().unwrap_or_default(), last["id"].as_str().unwrap_or_default()));    Ok(json!({"rows": opened, "unopened": unopened, "more": more, "after": after}))}/// `seal.restoreBinned {table, id}` (TRIM 3): a binned row this copy no longer holds, taken out of the/// Bin on the object: its clear bin mark cleared (`update`, `trashed_at` null, the way any restore goes/// up). The next pass pulls the row back whole, as the object holds it. Answers `{restored: true}`.fn restore_binned(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let table = request["table"].as_str().filter(|t| !t.is_empty()).ok_or_else(|| MethodError::new("bad_request", "seal.restoreBinned needs `table`"))?;    let id = request["id"].as_str().filter(|id| !id.is_empty()).ok_or_else(|| MethodError::new("bad_request", "seal.restoreBinned needs `id`"))?;    let door = client.object_door().ok_or_else(|| MethodError::new("sign_in_first", "a row binned on the object is restored there, once the database is there"))?;    let act = json!({"act": "update", "args": {"table": table, "id": id, "data": {"trashed_at": Value::Null}}});    door.send("POST", "/v1/act", Some(&act)).map_err(|error| MethodError::new(&error.code, error.message))?;    client.nudge_sync();    Ok(json!({"restored": true}))}/// The 32-byte key a call hands over, base64url.fn key_arg(request: &Value) -> Result<DataKey, MethodError> {    let text = request["key"].as_str().ok_or_else(|| MethodError::new("bad_request", "seal.useKey needs `key`, the data key as base64url"))?;    data_key_of(text)}/// A data key as the shell keeps it, base64url.pub(crate) fn data_key_of(text: &str) -> Result<DataKey, MethodError> {    let bytes = URL_SAFE_NO_PAD.decode(text.trim_end_matches('=')).map_err(|_| MethodError::new("bad_request", "`key` is not base64url"))?;    let bytes: [u8; 32] = bytes.as_slice().try_into().map_err(|_| MethodError::new("bad_request", "`key` is not 32 bytes"))?;    Ok(DataKey::from_bytes(bytes))}/// Run `work` with this database's unlocked VMK, or refuse `vault_locked`.fn with_vmk<T>(client: &ClientController, work: impl FnOnce(&cotton_core::vault::Vmk, u32) -> Result<T, cotton_core::seal::SealError>) -> Result<T, MethodError> {    let door = client.vault().map_err(|why| MethodError::new("not_attached", why))?;    door.with_vmk(client.now(), work)        .ok_or_else(crate::phone::vault::locked)?        .map_err(|error| MethodError::new(error.code(), error.to_string()))}/// Whether this app keeps a table the build seals (the kit's `seal`/// blocks): Messages and Email do, and Books does not.fn keeps_sealed(client: &ClientController) -> Result<bool, MethodError> {    let tables = cotton_client::transport::object::ObjectTables::personal();    let kit = crate::phone::tool_acts::app_kit(client)?;    let keeps = tables.names().any(|t| tables.object(t).is_some_and(|s| s.seal.is_some()) && kit.as_ref().is_none_or(|k| k.keeps_table(t)));    // An app that keeps a person's files (R6) seals and opens them with the    // same key: Photos, Books, Music and Cinemas found it or ask for it too.    // Only where the app also keeps the vault's rows, so it can found the key    // or be approved for it: a slip it could never answer is never shown.    let keeps_vault = kit.as_ref().is_none_or(|k| k.keeps_table("vault_key"));    let keeps_files = keeps_vault && cotton_client::media::sealed::FILE_TABLES.iter().any(|t| kit.as_ref().is_none_or(|k| k.keeps_table(t)));    // A table the kit keeps on its own (not in the storage map) that the seal rule seals (R1): Journal's    // journal_entry goes up sealed, and what the app sends is sealed by a key the data key derives (R5).    let keeps_kit_sealed = keeps_vault && kit.as_ref().is_some_and(|k| k.tables.iter().any(|t| rule_seals(t.rsplit('/').next().unwrap_or(t))));    // Cotton Data keeps no sealed table of its own but reads every one (DECISIONS "The data key for an account that    // has only Data"): it needs the key, and founds it on a new account, as any app that keeps a sealed table does.    let reads_everything = keeps_vault && kit.as_ref().is_some_and(|k| k.id == crate::phone::data_app::KIT);    Ok(keeps || keeps_files || keeps_kit_sealed || reads_everything)}/// Whether the seal rule seals the kit's table `id` (its own seal block, or the default a personal table takes).fn rule_seals(id: &str) -> bool {    cotton_core::kit::table_file(id)        .and_then(|file| serde_json::from_slice::<Value>(file).ok())        .is_some_and(|definition| cotton_core::seal::rule::ruled(&definition).get("seal").is_some_and(|block| !block.is_null()))}/// The copy's file, read-only.fn copy(client: &ClientController, database: &str) -> Result<rusqlite::Connection, MethodError> {    let path = client.layout().replica(database);    rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)        .map_err(|error| MethodError::new("could_not_read", format!("this phone's copy could not be read ({error})")))}/// The object's `seal_key` row of the DK, as this copy last pulled it.fn dk_row(client: &ClientController, database: &str) -> Result<Option<Map<String, Value>>, MethodError> {    let file = copy(client, database)?;    let kept = sealing::kept_keys(&file).map_err(|why| MethodError::new("could_not_read", why))?;    Ok(kept.into_iter().find(|(id, _)| id == DK_ROW).map(|(_, row)| row))}/// `seal.status`: whether the key is held, whether the database has one,/// and every row the sync loop parked because it did not open, by name.fn status(client: &ClientController, database: &str, keys: &Arc<HeldDataKeys>) -> Result<Value, MethodError> {    use cotton_client::seal::DataKeyStore as _;    let file = copy(client, database)?;    let parked = sealing::parked(&file).map_err(|why| MethodError::new("could_not_read", why))?;    let minted = sealing::kept_keys(&file).map_err(|why| MethodError::new("could_not_read", why))?.iter().any(|(id, _)| id == DK_ROW);    let held = keys.data_key(database).map_err(|why| MethodError::new("could_not_read", why))?.is_some();    // The person's sharing key, posted to their object the moment this phone holds the data key it derives from    // (R5), once a launch: one of their people who sends before this phone ever opens Send then seals to it, never    // to the made-up key a person with no key posted was answered (walk send-sealed run 6). Offline, a later pass    // posts it. Never on this read's thread: offline it waited out the lookup (OFFLINE START, `post_key_beside`).    if held && client.object_door().is_some() {        crate::phone::send_seal::post_key_beside(client);    }    // The core decides whether this app asks for the key: it keeps a table    // the build seals and holds no key, so it reads none of that table's rows.    let needs_key = !held && keeps_sealed(client)?;    // A phone that has not signed in makes its own key with no question (`seal.makeKey`): nothing is    // anywhere else to wait for, so it is never asked for one and no line is said.    let makes = needs_key && makes_here(client, database)?;    // Before this copy's first pass for this database it holds no wrapped key row and cannot tell whether another    // device holds the vault: it says nothing yet (no "locked on this phone… Unlock"), and the pass decides between    // founding, the waiting page and Unlock. Seen on the iPhone walk (23 Nov 2026) right after a sign-in to another    // number, before the waiting page.    let blind = needs_key && !minted && !client.pulled(database) && {        use cotton_client::vault::devices;        // Its own row, published at the sign-in, tells nothing: only a wrap does (on the walk the card still flashed        // with this device's own unwrapped row in the copy).        client.with_file(|replica| devices::keys(replica.driver, replica.workspace_id)).map(|keys| !keys.iter().any(|key| key.wrapped)).unwrap_or(false)    };    // A new person's first sign-in: no vault and no data key on the object, so the shell founds both with no    // question (the key it mints guards nothing yet); a vault that exists is opened behind the phone's lock.    let founds = needs_key && !minted && crate::phone::vault::founds_here(client)?;    // A new device of a person whose other device holds the vault: the shell publishes this device's key with no    // question, and the waiting page (`gettingIn.screen`) stands by itself (GETTING-IN.md).    let joins = needs_key && !makes && !founds && crate::phone::vault::joins_here(client)?;    // A device that joins says nothing about a locked key: it waits on the getting-in page (on the walk the card    // flashed for a second before the page). One that founds keeps Unlock, its way back if the quiet founding fails.    let said = if needs_key && !makes && !blind && !joins {        let lines = crate::phone::unlock::lines_of(client)?;        json!({"line": lines.say("key_needed", &[]).unwrap_or_default(), "act": lines.say("key_act", &[]).unwrap_or_default()})    } else {        Value::Null    };    Ok(json!({        "database": database,        "keyHeld": held,        "needsKey": needs_key,        "founds": founds,        "joins": joins,        "makes": makes,        "said": said,        "minted": minted,        "parked": parked.iter().map(|row| json!({"table": row.table, "id": row.id, "code": row.code})).collect::<Vec<_>>(),    }))}#[cfg(test)]#[path = "seal_tests.rs"]mod tests;