//! `vault.*` — the passwords, opened by THIS device, on THIS device. //! //! The model itself is `cotton_core::vault` and Cotton note "The vault — the honest sentence". //! //! ## Why this family exists at all, and why it is not a tool //! //! `secrets.set` used to be the phone's one credential write, and its header //! said the reason out loud: encrypting was a RAIL the phone did not have, so //! the value went over the signed transport to the one process that could. That //! is no longer true and the method is gone. Since schema v6 this device holds //! its own X25519 vault key in the Keychain, the server has wrapped the //! workspace's vault master key for it, and the phone can seal and open a //! secret with nothing but its own replica — **no round trip, and no server //! that ever sees a plaintext.** //! //! So the family is a set of METHODS rather than tool calls, for the reason //! [`crate::phone::settings_writes`] gives for its five: a tool runs with //! `ToolServices::none()` on a device, the vault rail is the server's, and //! `create_secret` refuses by name on this build. The write here is the same //! `Ctx::phone`, the same outbox and the same `data` event every other write //! from this device takes — only the SEALING happens before the row is built, //! in this process, under a key nothing else has. //! //! ## The four rules //! //! **The VMK never leaves memory and never outlives [`VAULT_UNLOCK_TTL`].** It //! is held in [`VaultSession`], zeroised on drop (`Vmk` is `ZeroizeOnDrop`), //! and the expiry is measured on the controller's own clock seam — never //! `Utc::now()` inside a function, because a TTL read off a wall clock is a //! test with a computable detonation date. //! //! **A private key crosses as a CALL PARAMETER and is never persisted here.** //! `vault.unlock` takes 32 bytes, unwraps with them, and drops them. Nothing in //! this crate writes a vault private key to a file, a log or an error's //! `details` — the Keychain is the whole of where it lives. //! //! **A refusal is by NAME.** `vault_not_wrapped_yet`, `vault_locked`, //! `vault_key_mismatch`, `vault_sealed_under_the_old_key`. A screen draws the //! sentence; nothing falls back to a weaker scheme, and nothing retries. //! //! **No payload ever reaches a log line or a `data` event.** `vault.reveal` //! answers the payload to its one caller and stamps `last_used_at`; the event //! that write emits carries the TABLE, as every write does, and never a column. use std::collections::BTreeMap; use std::sync::{Arc, Mutex}; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; use chrono::{DateTime, Duration, Utc}; use serde_json::{json, Map, Value}; use cotton_core::vault::{ is_legacy, open as open_sealed, unwrap as unwrap_vmk, Vmk, {self as vault_core}, }; use cotton_client::vault::devices; use cotton_core::vault::placement::PlacementRequest; use cotton_tools::mcp::dispatch::Ctx; use cotton_tools::mcp::writer::Retract; use cotton_tools::mcp::handlers::common::{insert_row, now_iso, update_row}; use crate::handle::CottonHandle; use crate::methods::MethodError; use crate::phone::owner; use crate::shell::client::ClientController; use crate::shell::file::ReadFile; /// How long one unlock lasts: five minutes, the spec's `VAULT_UNLOCK_TTL`. /// /// Long enough to reveal a password, copy a one-time code and correct a typo; /// short enough that a phone left on a table is not an open vault. Measured on /// the controller's clock, so a suite fixes it. pub const VAULT_UNLOCK_TTL_SECONDS: i64 = 300; /// The table the device's own public half is published in. const VAULT_KEYS: &str = "cotton_vault_keys"; /// The workspace's current key version. const VAULT_STATE: &str = "cotton_vault_state"; const RETIRED_KEYS: &str = "cotton_vault_retired_keys"; const SECRETS: &str = "cotton_secrets"; const PLACEMENTS: &str = "cotton_secret_placements"; /// Every method this family answers. /// The code `vault.unlock` and `vault.reveal` answer while the server has /// refused this device for good — the sentence is the crate's own. pub const REFUSED_DEVICE: &str = "device_refused"; pub const METHODS: [&str; 16] = [ "vault.approval", "vault.approveDevice", "vault.create", "vault.keep", "vault.keys", "vault.lock", "vault.place", "vault.publishKey", "vault.refuseDevice", "vault.restore", "vault.reveal", "vault.status", "vault.trash", "vault.unlock", "vault.unplace", "vault.update", ]; // ── the session ──────────────────────────────────────────────────────────── /// The vault master keys this device has unlocked — ONE PER DATABASE. /// /// One session per [`ClientController`], because the controller is what holds /// the files; inside it a key is filed under the id of the database whose wrap /// it was opened from, and it is only ever lent back to a call on that same /// database ([`VaultDoor`]). Every database has its own vault and its own VMK /// (the owner's 3 Oct decision: Passwords exists in every database). Until /// 2026-10-04 this held one key for the whole device, so a password made in /// database B after unlocking A was sealed under A's key: no other device /// could open it and nothing said so. /// /// It lives on the controller rather than on the handle for a second reason /// that is worth the sentence: a `read.*` entry takes a controller and not a /// handle, and the Passwords list has to draw "unlocked until …" — a status /// that lived on the handle would be a question the read could not ask. #[derive(Debug, Default)] pub struct VaultSession { open: Mutex>, } struct Unlocked { vmk: Vmk, /// Which version of the VMK this is — an older one cannot open a row the /// server has since re-sealed, and saying so is better than a blank field. version: u32, until: DateTime, } impl std::fmt::Debug for Unlocked { /// The instant and the version, NEVER the key. A `{:?}` on a controller is /// something a log line holds. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Unlocked") .field("version", &self.version) .field("until", &self.until) .finish() } } impl VaultSession { /// The session as ONE database sees it. There is no way to reach a key /// except through a door, so there is no call that can use a key without /// having said whose it is. pub fn of(self: &Arc, database: &str) -> VaultDoor { VaultDoor { session: Arc::clone(self), database: database.to_string(), } } /// Forget every database's key now. Dropping a `Vmk` zeroises the bytes. pub fn lock_all(&self) { self.slots().clear(); } fn slots(&self) -> std::sync::MutexGuard<'_, BTreeMap> { self.open.lock().unwrap_or_else(|error| error.into_inner()) } } /// One database's side of the [`VaultSession`]: its key, and no other's. #[derive(Debug)] pub struct VaultDoor { session: Arc, database: String, } impl VaultDoor { /// Hold this database's key for [`VAULT_UNLOCK_TTL_SECONDS`], and answer /// when that ends. pub fn unlock(&self, vmk: Vmk, version: u32, now: DateTime) -> DateTime { let until = now + Duration::seconds(VAULT_UNLOCK_TTL_SECONDS); self.session.slots().insert( self.database.clone(), Unlocked { vmk, version, until, }, ); until } /// Hold an open key on, never reopen a shut one: to `now + seconds` while he is in the app (at least as long as /// it already runs), or to exactly `now + seconds` as he leaves (`leaving`), so it is held as long as his own Lock /// after says and no longer. Answers when it now ends, or nothing if it was already shut. pub fn keep(&self, now: DateTime, seconds: i64, leaving: bool) -> Option> { let mut slots = self.swept(now); let open = slots.get_mut(&self.database)?; let to = now + Duration::seconds(seconds); open.until = if leaving { to } else { open.until.max(to) }; Some(open.until) } /// Forget this database's key now. pub fn lock(&self) { self.session.slots().remove(&self.database); } /// When this unlock runs out, or nothing if it already has. /// /// **Reading the state EXPIRES it**, rather than a timer: there is no /// runnable moment between two calls on a phone, so a sweep on read is both /// the cheapest and the only honest implementation — the key is gone the /// first time anybody looks after the deadline. The sweep takes every /// database's expired key, not only this one's. pub fn until(&self, now: DateTime) -> Option> { self.swept(now).get(&self.database).map(|open| open.until) } /// The version of this database's VMK the device is holding, if it is /// holding one. pub fn version(&self, now: DateTime) -> Option { self.swept(now).get(&self.database).map(|open| open.version) } /// Run one piece of crypto with this database's key, or answer `None` when /// it is locked — whatever other database is unlocked. /// /// The key is BORROWED — there is no accessor that hands it out, and there /// must not be: a `Vmk` that can be cloned is a `Vmk` in two places, only /// one of which anybody remembers to zeroise. pub fn with_vmk( &self, now: DateTime, work: impl FnOnce(&Vmk, u32) -> R, ) -> Option { let slots = self.swept(now); let open = slots.get(&self.database)?; Some(work(&open.vmk, open.version)) } fn swept(&self, now: DateTime) -> std::sync::MutexGuard<'_, BTreeMap> { let mut slots = self.session.slots(); slots.retain(|_, open| now < open.until); slots } } // ── dispatch ─────────────────────────────────────────────────────────────── /// `vault.*` — every method, over this device's replica. pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result { if super::vault_app::METHODS.contains(&method) { // Cotton Vault's screens: Security's sign-in asks and Cotton passkeys ask the open host through this handle. let remote = |method: &str, request: &Value| -> Result { if method.starts_with("signin.passkey") { super::account_passkey::call(handle, method, request) } else { super::signin_approval::call(handle, method, request) } }; return super::vault_app::call(&handle.client(), method, request, Some(&remote)); } over(&handle.client(), method, request) } /// The same, over a NAMED controller. /// /// The split is [`crate::phone::secrets`]' old one and it is here for the same /// reason: a suite drives a paired phone assembled by /// `shell::client::phone_tests::attached` and asserts what the file holds /// afterwards, without dragging a runtime and a data directory into a test /// about one method's shape. pub fn over( client: &ClientController, method: &str, request: &Value, ) -> Result { match method { "vault.publishKey" => publish_key(client, request), "vault.unlock" => unlock(client, request), "vault.lock" => { // EVERY database's key, whichever one the call names: "lock" is // the person putting the phone down, not a statement about a file. client.vault_session().lock_all(); Ok(json!({ "locked": true })) } // Secrets locks N minutes after he LEAVES (launch-ios's walk, 25 Nov 2026: the five-minute unlock ran out while // he was editing, and Save asked Face ID again, then Unlock stood over the page). The phone keeps the key held // while it is in front, and as it goes says `leaving`: held exactly as long as Lock after says (Immediately: // gone now). "vault.keep" => { let leaving = request.get("leaving").and_then(Value::as_bool).unwrap_or(false); let minutes = super::vault_app::preferences(client).map(|p| p.lock_minutes).unwrap_or(5); if leaving && minutes == 0 { client.vault_session().lock_all(); return Ok(json!({ "open": false })); } let seconds = if leaving { i64::from(minutes) * 60 } else { VAULT_UNLOCK_TTL_SECONDS }; let until = client.vault().ok().and_then(|door| door.keep(client.now(), seconds, leaving)); Ok(json!({ "open": until.is_some(), "until": until.map(|at| at.to_rfc3339()) })) } "vault.status" => status(client).map_err(unreadable), "vault.reveal" => reveal(client, request), "vault.create" => create(client, request), "vault.update" => update(client, request), "vault.trash" => set_trashed(client, method, request, true), "vault.restore" => set_trashed(client, method, request, false), "vault.place" => place(client, request), "vault.unplace" => unplace(client, request), "vault.keys" => device_keys(client).map_err(unreadable), "vault.approval" => super::vault_approval::approval(client), "vault.approveDevice" => approve_device(client, request), "vault.refuseDevice" => refuse_device(client, request), other if super::vault_app::METHODS.contains(&other) => super::vault_app::call(client, other, request, None), other => Err(MethodError::new( "unknown_method", format!("`{other}` is not a vault method"), )), } } fn unreadable(reason: String) -> MethodError { MethodError::new("unreadable", reason) } fn refused(reason: String) -> MethodError { MethodError::new("write_refused", reason) } /// Run a body as this device, through the ordinary outbox. pub(crate) fn write( client: &ClientController, label: &str, body: &mut dyn FnMut(&mut Ctx<'_>) -> Result, ) -> Result { client.write_rows(label, body).map_err(refused) } // ── vault.place / vault.unplace ──────────────────────────────────────────── /// Put a secret on a Mac: `{secretId, deviceId, path, format?, envName?, /// mode?}`, the Mac's registry id from `devices.list`. /// /// Writing the ROW needs no vault key — nothing is opened here — so a locked /// phone can say where a secret goes; the Mac the row names opens it with its /// own key when the row arrives. On a Mac the row is applied at once as well. fn place(client: &ClientController, request: &Value) -> Result { let id = place_row(client, request)?; Ok(json!({ "id": id, "applied": 0, "problem": Value::Null })) } /// Write one placement row (upserted on the Mac and the path) and answer its id. /// /// The request is judged by `cotton_core::vault::placement` — the rules the /// Mac's applier holds a row to — so a path the Mac would refuse is refused /// here, under the field. Every device's: the phone verb, the Mac's own and an /// approved migration list all write through this. pub fn place_row(client: &ClientController, request: &Value) -> Result { let request = PlacementRequest::from_json(request) .map_err(|reason| MethodError::new("bad_request", reason))?; let answer = write(client, "vault.place", &mut |ctx| upsert_placement(ctx, &request))?; Ok(answer .get("answer") .and_then(|answer| answer.get("id")) .and_then(Value::as_str) .unwrap_or_default() .to_string()) } /// The upsert itself, inside a caller's write — one row per (Mac, path). pub fn upsert_placement(ctx: &mut Ctx<'_>, request: &PlacementRequest) -> Result { let workspace = rusqlite::types::Value::Text(ctx.workspace_id.to_string()); let secret = ctx .db() .get( &format!( "SELECT id FROM {SECRETS} WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL" ), &[ workspace.clone(), rusqlite::types::Value::Text(request.secret_id.clone()), ], ) .map_err(|error| error.to_string())?; if secret.is_none() { return Err("there is no such secret in this database's passwords".to_string()); } let existing = ctx .db() .get( &format!( "SELECT id FROM {PLACEMENTS} WHERE workspace_id = ? AND device_id = ? AND path = ?" ), &[ workspace, rusqlite::types::Value::Text(request.device_id.clone()), rusqlite::types::Value::Text(request.path.clone()), ], ) .map_err(|error| error.to_string())?; let mut patch = Map::new(); patch.insert("secret_id".to_string(), Value::from(request.secret_id.clone())); patch.insert("device_id".to_string(), Value::from(request.device_id.clone())); patch.insert("path".to_string(), Value::from(request.path.clone())); patch.insert("mode".to_string(), Value::from(request.mode)); patch.insert("format".to_string(), Value::from(request.format.as_str())); patch.insert( "env_name".to_string(), request.env_name.clone().map_or(Value::Null, Value::from), ); // A re-placed row starts again: what is on that disk is not what this row // now asks for, and a stamp that says otherwise would stop the applier from // ever looking. patch.insert("applied_at".to_string(), Value::Null); patch.insert("applied_hash".to_string(), Value::Null); patch.insert("apply_problem".to_string(), Value::Null); let id = match existing { Some(row) => { let id = row.text("id").unwrap_or_default().to_string(); update_row(ctx, PLACEMENTS, &id, patch).map_err(|failure| failure.to_string())?; id } None => { let id = ctx.new_uuid(); insert_row(ctx, PLACEMENTS, &id, patch).map_err(|failure| failure.to_string())?; id } }; Ok(json!({ "id": id })) } /// Stop writing a secret onto a Mac. /// /// **The FILE is left alone.** Deleting it from here would be a device reaching /// onto a Mac's disk on the strength of a synced row, and a build that stopped /// working because somebody tidied a placement is worse than a file a person /// removes themselves. The row goes; what it wrote stays. fn unplace(client: &ClientController, request: &Value) -> Result { let id = request .get("id") .and_then(Value::as_str) .filter(|id| !id.trim().is_empty()) .ok_or_else(|| MethodError::new("bad_request", "`id` is required"))? .to_string(); write(client, "vault.unplace", &mut |ctx| { ctx.writer() .map_err(|failure| failure.to_string())? .retract(PLACEMENTS, &id, Retract::Relation); ctx.commit().map_err(|failure| failure.to_string())?; Ok(json!({ "id": id, "removed": true })) })?; Ok(json!({ "id": id, "removed": true })) } // ── vault.publishKey ─────────────────────────────────────────────────────── /// Tell the file this device's PUBLIC half, so a server can wrap for it. /// /// Called at first launch after the update and again after a join, because the /// two paths are different and either can be the one that happens: the join /// request carries `vaultPublicKey` for a server that knows the field, and this /// method is what gets the row there when the server is older, when the join /// predates the vault, or when the Keychain item was lost and minted again. /// Publishing twice is a no-op; that is the point. /// /// **A CHANGED public key clears the wrap.** The `wrapped_vmk` on the row was /// sealed to a key this device no longer has, so keeping it would be a row /// claiming this phone can open the vault when it cannot — the re-wrap worker /// reads `wrapped_vmk IS NULL OR vmk_version < state`, and nulling it is how /// this device asks to be wrapped again. /// /// **INTO EVERY DATABASE THIS DEVICE HOLDS, whichever one the call names.** /// Every database has its own vault and its own key rows, and one device key /// opens them all, so a publish that reached only the database on screen left /// every other vault closed to this device. A database this device was removed /// from is read-only and one made here that the server has not taken yet has /// no vault to be wrapped into; both are left out, and [`publish_owed`] gives /// the second its key on the pass after it is taken. Answers /// `{"deviceId","changed","databases":[{"databaseId","id","changed"}]}`, a /// database whose write was refused carrying `refused` instead; the call is /// refused only when every database refused. fn publish_key(client: &ClientController, request: &Value) -> Result { let public_key = public_key_arg(request)?; let name = owner::optional_text(request, "name"); client.set_vault_public(&public_key); super::founding::local_personal(client, &public_key)?; let mut targets = publish_targets(client).map_err(unreadable)?; if targets.is_empty() { // No connection record names a database: ask the one the call does, // and let its own refusal be the answer. targets.push(client.current_database().map_err(unreadable)?); } publish_into(client, &public_key, name.as_deref(), targets) } /// The databases whose vault this device's key belongs in. fn publish_targets(client: &ClientController) -> Result, String> { Ok(client .databases()? .into_iter() .filter(|database| !database.pending) .map(|database| database.id) .collect()) } /// Publish the key this device last said into every database that does not /// hold it yet, or answer `None` when nothing is owed: no key has been said, /// or every database already has it. /// /// What a sync pass runs when it ends, on a phone as on a Mac — a database /// admitted or taken by the server after the launch's publish gets the key /// here, and a refused publish is asked again. pub fn publish_owed(client: &ClientController) -> Option> { let public_key = client.vault_public()?; let owed: Vec = publish_targets(client) .ok()? .into_iter() .filter(|database| !client.vault_key_published(database)) .collect(); if owed.is_empty() { return None; } Some(publish_into(client, &public_key, None, owed)) } fn publish_into( client: &ClientController, public_key: &str, name: Option<&str>, databases: Vec, ) -> Result { let device_id = this_device(client).map_err(unreadable)?; let mut rows = Vec::new(); let mut changed = false; let mut landed = false; let mut first_refusal = None; for database in databases { match publish_in(client, &database, public_key, name, &device_id) { Ok(answer) => { client.set_vault_key_published(&database); landed = true; let wrote = answer.get("changed").and_then(Value::as_bool).unwrap_or(false); changed |= wrote; rows.push(json!({ "databaseId": database, "id": answer["id"], "changed": wrote })); } Err(refusal) => { rows.push(json!({ "databaseId": database, "refused": refusal.message })); first_refusal.get_or_insert(refusal); } } } match first_refusal { Some(refusal) if !landed => Err(refusal), _ => Ok(json!({ "deviceId": device_id, "changed": changed, "databases": rows })), } } /// This device's key row in ONE database's file. fn publish_in( client: &ClientController, database: &str, public_key: &str, name: Option<&str>, device_id: &str, ) -> Result { let _named = client.name_database(Some(database)).map_err(unreadable)?; let public_key = public_key.to_string(); let name = name.map(str::to_string); let device_id = device_id.to_string(); write(client, "vault.publishKey", &mut |ctx| { let existing = ctx .db() .get( &format!( "SELECT id, public_key FROM {VAULT_KEYS} WHERE workspace_id = ? AND device_id = ?" ), &[ rusqlite::types::Value::Text(ctx.workspace_id.to_string()), rusqlite::types::Value::Text(device_id.clone()), ], ) .map_err(|error| error.to_string())?; // The name rides the object's `vault_key.name`, a column this copy // gains on its first pull; a copy that has none yet keeps the key and // says the name on a later publish. let named = name.clone().filter(|_| devices::has_name(ctx.db()).unwrap_or(false)); let held_name = match (&existing, &named) { (Some(row), Some(_)) => ctx .db() .get( &format!("SELECT name FROM {VAULT_KEYS} WHERE id = ?"), &[rusqlite::types::Value::Text(row.text("id").unwrap_or_default().to_string())], ) .map_err(|error| error.to_string())? .and_then(|row| row.text("name").map(str::to_string)), _ => None, }; if let Some(row) = existing { let id = row.text("id").unwrap_or_default().to_string(); let renamed = named.as_ref().filter(|name| held_name.as_ref() != Some(*name)); if row.text("public_key") == Some(public_key.as_str()) { if let Some(name) = renamed { let mut patch = Map::new(); patch.insert("name".to_string(), Value::from(name.clone())); update_row(ctx, VAULT_KEYS, &id, patch).map_err(|failure| failure.to_string())?; return Ok(json!({ "id": id, "changed": true })); } return Ok(json!({ "id": id, "changed": false })); } let mut patch = Map::new(); if let Some(name) = renamed { patch.insert("name".to_string(), Value::from(name.clone())); } patch.insert("public_key".to_string(), Value::from(public_key.clone())); // The old wrap was for a key that is gone. See the header. patch.insert("wrapped_vmk".to_string(), Value::Null); patch.insert("vmk_version".to_string(), Value::from(0)); update_row(ctx, VAULT_KEYS, &id, patch).map_err(|failure| failure.to_string())?; return Ok(json!({ "id": id, "changed": true })); } let id = ctx.new_uuid(); let mut patch = Map::new(); patch.insert("device_id".to_string(), Value::from(device_id.clone())); patch.insert("public_key".to_string(), Value::from(public_key.clone())); if let Some(name) = &named { patch.insert("name".to_string(), Value::from(name.clone())); } // Written out loud: the DDL has no default for either and a NOT NULL // column left out is a row that will not land. patch.insert("wrapped_vmk".to_string(), Value::Null); patch.insert("vmk_version".to_string(), Value::from(0)); insert_row(ctx, VAULT_KEYS, &id, patch).map_err(|failure| failure.to_string())?; Ok(json!({ "id": id, "changed": true })) }) .map(strip_envelope) } // ── vault.unlock / vault.lock ────────────────────────────────────────────── /// Open the vault with this device's private key, for five minutes. /// /// The private key arrives from the Keychain, AFTER the presence prompt the /// item's access control forces; nothing on this side can perform that check /// and nothing here pretends to. What this side proves is the other half: that /// the key handed in is the one the published row names, and that it opens the /// wrap the server wrote. fn unlock(client: &ClientController, request: &Value) -> Result { // A device the server no longer trusts opens nothing — the same // chokepoint every write asks (`ClientController::write_refusal`). if let Some(sentence) = client.write_refusal() { return Err(MethodError::new(REFUSED_DEVICE, sentence)); } let secret = private_key_arg(request)?; let now = client.now(); // A joining device names itself as it publishes (`name`, what the phone calls itself), so the device that // approves it reads who asks (`vault.approval`). if let Some(name) = owner::optional_text(request, "name") { publish_on_need(client, &URL_SAFE_NO_PAD.encode(vault_core::wrap::public_of(&secret)), Some(&name))?; } // A LOCAL COPY FOUNDS AT ITS UNLOCK TOO (launch-ios on dev, 25 Nov 2026). After Sign out the phone stands on a // local copy of its own; the shell's key publish ran at launch, before that copy stood, so nothing founded it // and Unlock read "Waiting for a device…" for ever, with nothing to tap. The founding is the publish's own // (`founding::local_personal`): a no-op where the copy already has a vault, never a second VMK over sealed rows. if !client.signed_in() { if let Err(refusal) = super::founding::local_personal(client, &URL_SAFE_NO_PAD.encode(vault_core::wrap::public_of(&secret))) { tracing::warn!("vault: the local copy did not found at unlock: {}", refusal.message); } } let (vmk, row_version) = opened_vmk(client, &secret).map_err(|refusal| match refusal.code.as_str() { // On a local copy no other device can ever bring the key: say what gets the person out. "vault_not_wrapped_yet" if !client.signed_in() => needs_sign_in(), _ => refusal, })?; // A signed-in copy whose vault was founded on the object has no person // key yet: it takes or mints one now, while the vault is open. if let Err(refusal) = super::person_key::ensure(client, &vmk, row_version) { tracing::warn!("person key: not kept — {}", refusal.message); } // And the data key sealed tables use, the same way (`seal::ensure`). if let Err(refusal) = super::seal::ensure(client, &vmk, row_version) { tracing::warn!("data key: not taken — {}: {}", refusal.code, refusal.message); } let until = client .vault() .map_err(unreadable)? .unlock(vmk, row_version, now); Ok(json!({ "unlocked": true, "until": iso(until) })) } /// The vault master key this device's own wrap opens to, with the version of /// that wrap — the half of [`unlock`] that proves the key handed in is the one /// the published row names. Also what [`approve_device`] lends a wrap from /// when the call carries the private key. /// /// EVERY VAULT NEED FOUNDS HERE: this is the one place a wrap is opened, so /// `vault.unlock`, a passkey's register or CXF import with a lent key and an /// approval all found a signed-in copy that holds no wrap ([`found_on_need`]). pub(crate) fn opened_vmk(client: &ClientController, secret: &[u8; 32]) -> Result<(Vmk, u32), MethodError> { let public = vault_core::wrap::public_of(secret); let published = URL_SAFE_NO_PAD.encode(public); publish_on_need(client, &published, None)?; found_on_need(client)?; let this = this_device(client).map_err(unreadable)?; let wrap = client .with_file(|replica| { let device_id = this.clone(); let state = state_version(replica)?; let row = replica .driver .get( &format!( "SELECT public_key, wrapped_vmk, vmk_version FROM {VAULT_KEYS} WHERE workspace_id = ? AND device_id = ?" ), &[ rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(device_id), ], ) .map_err(|error| error.to_string())?; Ok(row.map(|row| { ( row.text("public_key").unwrap_or_default().to_string(), row.text("wrapped_vmk").map(|text| text.to_string()), row.int("vmk_version").unwrap_or(0) as u32, state, ) })) }) .map_err(unreadable)?; let Some((row_public, wrapped, row_version, state_version)) = wrap else { return Err(not_wrapped_yet()); }; if wrapped.is_some() { match founding(client)? { Founding::Taken => {} Founding::Queued => return Err(founding_queued()), Founding::Refused => return Err(founding_refused()), } } if row_public != published { // DEVICE-NEUTRAL, AND IT ASKS FOR NOTHING. Until 2026-09-19 this said // "This phone's key … Publish the new key and wait for your Mac" — and // it was read on a MAC, where the word is wrong and the instruction // names a button no screen has. The screen is what publishes now // (`VaultAccess.publish`, on this code), and then it says it is // waiting; the crate states the fact and stops there. return Err(MethodError::new( "vault_key_mismatch", "This device's key is not the one published for it.", )); } let Some(wrapped) = wrapped else { return Err(not_wrapped_yet()); }; // A wrap at an OLDER version than the workspace's is a wrap of a key the // server has already rotated away from: it would open nothing that has been // re-sealed, and half a vault is worse than a named wait. if let Some(state) = state_version { if row_version < state { return Err(not_wrapped_yet()); } } let Some(bytes) = unwrap_vmk(secret, &wrapped) else { return Err(MethodError::new( "vault_key_mismatch", "This device's key did not open the vault key. Nothing was changed.", )); }; let Ok(bytes): Result<[u8; 32], _> = bytes.try_into() else { return Err(MethodError::new( "vault_key_mismatch", "The vault key that came back is not 32 bytes. Nothing was changed.", )); }; let vmk = Vmk::from_bytes(bytes); // KEPT FOUR 3 LOW: on EVERY path that opens the vault (unlock, an approval, an unlock window, a passkey, a // recovery), what a local database founded before sign-in sealed under its own key is sealed again under this // account's key, while this device's private key is in hand; and this device declares the key's identity once it // has proof it holds the account's (VAULT GUARD 2 item 2b). if let Err(reason) = super::vault_carry::carry(client, secret, &vmk, row_version) { eprintln!("[vault-carry] not done this time: {reason}"); } super::vault_carry::declare(client, secret, &vmk, row_version); Ok((vmk, row_version)) } /// The one sentence a device waiting on a device that holds the passwords /// reads: the device that shares the key is another of the person's — a /// phone signed in to Cotton syncs with no Mac ("Waiting for the Mac" in a /// phone's log, Story's launch walk, 22 Nov 2026). /// /// **"THIS DEVICE", NOT "THIS PHONE".** A standby Mac reads it too — it is a /// client of whichever Mac is serving, and on one Mac it read the phone's /// wording on a Mac all day. fn not_wrapped_yet() -> MethodError { MethodError::new( "vault_not_wrapped_yet", "Waiting for a device that holds your passwords to share the key", ) } /// A local copy holding a vault this device's key does not open (sealed on another phone, or under a key this /// phone no longer holds): no device can wrap it here, so the line names the way out, and `secrets.gate` answers /// the acts (Sign in, Getting in on a new phone). fn needs_sign_in() -> MethodError { MethodError::new( "vault_needs_sign_in", "This phone doesn't hold the key to these passwords. Sign in to open them here, or get in another way.", ) } /// Whether this copy holds a vault that this device has no wrap for yet: the state in which Unlock can open nothing /// until another device, a recovery code, or (on a local copy) a sign-in brings the key. A copy with no vault yet is /// not waiting: its unlock founds one. pub(crate) fn waits_for_key(client: &ClientController) -> bool { let Ok(device) = this_device(client) else { return false }; client .with_file(|replica| { if state_version(replica)?.is_none() { return Ok(false); } let own = replica .driver .get( &format!("SELECT wrapped_vmk IS NOT NULL AS wrapped FROM {VAULT_KEYS} WHERE workspace_id = ? AND device_id = ?"), &[rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(device)], ) .map_err(|error| error.to_string())?; Ok(own.map_or(true, |row| row.int("wrapped").unwrap_or(0) == 0)) }) .unwrap_or(false) } // ── vault.keys / vault.approveDevice / vault.refuseDevice ────────────────── /// `vault.keys` — every device of this vault: the ones waiting for approval /// first, then those already let in (`cotton_client::vault::devices`). Each /// names its fingerprint, never a key; `thisDevice` is the caller's own id. fn device_keys(client: &ClientController) -> Result { // Keys › Devices is a first need: a copy whose object holds no vault // founds it here. A founding the object refused is said by the unlock. if let Err(refusal) = found_on_need(client) { if refusal.code != "vault_not_wrapped_yet" { return Err(refusal.message); } } let this = this_device(client).ok(); client.with_file(|replica| { let keys = devices::keys(replica.driver, replica.workspace_id)?; Ok(json!({ "devices": keys.iter().map(devices::DeviceKey::json).collect::>(), "thisDevice": this, })) }) } /// `vault.approveDevice {deviceId, privateKey?}` — REFUSED, always /// (19 Nov 2026): it let a device into the vault on one tap and /// a fingerprint compared by eye, so a fatigued tap on a SIM-swapped number's /// ask handed the vault over. A device is let in only by the typed-code /// compare (`signin.approve` over an ask that names its vault key, or a /// sibling's `signin.approveSibling` over the checked channel); the object /// keeps no wrap onto another device's row without such an ask, and tells an /// app from before `update_app`. Refused `code_needed` with the line saying /// how; nothing is opened or written. fn approve_device(_client: &ClientController, request: &Value) -> Result { owner::text(request, "deviceId")?; Err(MethodError::new("code_needed", super::vault_approval::code_needed())) } /// `vault.refuseDevice {deviceId}` — turn a waiting device away: its row goes. /// Needs no key: nothing is opened or wrapped. fn refuse_device(client: &ClientController, request: &Value) -> Result { let device_id = owner::text(request, "deviceId")?; let answer = write(client, "vault.refuseDevice", &mut |ctx| devices::refuse(ctx, &device_id)) .map_err(name_the_refusal)?; Ok(strip_envelope(answer)) } /// A VAULT NEED PUBLISHES THE KEY IT WAS HANDED /// (12 Nov 2026). The shell publishes this device's public key once at /// launch, from the public half it keeps cached beside the Keychain item; a /// launch whose cache was empty (the item kept across a reinstall, the cache /// not) published nothing, so no database ever held this device's row, the /// pass-end publish had no key to repeat (`publish_owed`), and every need on /// a signed-in copy waited on "the Mac" for a wrap nobody could write. A need /// holds the private key, so it publishes the public half itself into the /// database it is on when that database holds NO row for this device: then /// the founding below finds one. A row already there is never replaced here, /// whatever key it names: a different key is `vault_key_mismatch`, whose one /// remedy is the screen's explicit publish. Signed-in copies only, as the /// founding. pub(crate) fn publish_on_need(client: &ClientController, public_key: &str, name: Option<&str>) -> Result<(), MethodError> { if !client.signed_in() || client.write_refusal().is_some() { return Ok(()); } let Ok(device_id) = this_device(client) else { return Ok(()); }; let held = client .with_file(|replica| { Ok(replica .driver .get( &format!("SELECT 1 AS n FROM {VAULT_KEYS} WHERE workspace_id = ? AND device_id = ?"), &[rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(device_id)], ) .map_err(|error| error.to_string())? .is_some()) }) .map_err(unreadable)?; if held { return Ok(()); } let database = client.current_database().map_err(unreadable)?; if client.vault_public().is_none() { client.set_vault_public(public_key); } publish_into(client, public_key, name, vec![database]).map(|_| ()) } /// A signed-in copy whose object holds no vault founds it the first time it /// needs it (`vault.unlock` before a passkey write or an import, `vault.keys` /// on Keys › Devices), never at sign-in: the vault master key is minted here, /// wrapped for this device's own published key and pushed through the /// ordinary outbox ([`devices::found`]). THE OBJECT IS THE ARBITER: it keeps /// the first founding and refuses a later one `vault_founded`, and until it /// has taken this one the wrap opens nothing ([`founding`]), so no row /// is ever sealed under a key that loses a race. A local copy founds at /// `vault.publishKey` ([`super::founding::local_personal`]), unchanged. /// Before anything is minted, a wrap the object already holds for this /// device's own key is taken ([`take_own_key`]). Answers whether this call /// founded. fn found_on_need(client: &ClientController) -> Result { if !client.signed_in() || client.write_refusal().is_some() { return Ok(false); } take_own_key(client)?; let Ok(device_id) = this_device(client) else { return Ok(false); }; if !knows_the_vault(client)? { return Ok(false); } match founding(client)? { Founding::Taken => {} Founding::Queued => return Ok(false), Founding::Refused => return Err(founding_refused()), } let unfounded = client .with_file(|replica| { let own = replica .driver .get( &format!("SELECT wrapped_vmk IS NOT NULL AS wrapped FROM {VAULT_KEYS} WHERE workspace_id = ? AND device_id = ?"), &[ rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(device_id.clone()), ], ) .map_err(|error| error.to_string())?; let Some(own) = own else { return Ok(false) }; if own.int("wrapped").unwrap_or(0) != 0 { return Ok(false); } Ok(devices::current_version(replica.driver, replica.workspace_id)?.is_none()) }) .map_err(unreadable)?; if !unfounded { return Ok(false); } let answer = write(client, "vault.found", &mut |ctx| devices::found(ctx, &device_id)).map_err(name_the_refusal)?; Ok(answer.get("founded").and_then(Value::as_bool).unwrap_or(false)) } /// Whether a vault need on this copy would FOUND the vault rather than open /// one or wait for a device that holds it (15 Nov /// 2026): signed in, the object's vault rows read ([`knows_the_vault`]), and /// no other device's row holds a wrap. This device's own wrap is its founding /// on its way (it opens once the object has it), so it still founds: the /// shell keeps asking with no question until the data key is held. A shell asks this /// before it founds with no question at the first sign-in of a new person: /// founding mints a key that guards nothing yet, so no presence is owed for /// it; opening a vault that exists still asks for the phone's lock. pub(crate) fn founds_here(client: &ClientController) -> Result { if !client.signed_in() || client.write_refusal().is_some() { return Ok(false); } let Ok(device_id) = this_device(client) else { return Ok(false); }; if !knows_the_vault(client)? { return Ok(false); } client .with_file(|replica| { let others = replica .driver .get( &format!("SELECT 1 AS n FROM {VAULT_KEYS} WHERE workspace_id = ? AND wrapped_vmk IS NOT NULL AND device_id <> ?"), &[rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(device_id.clone())], ) .map_err(|error| error.to_string())? .is_some(); let own = replica .driver .get( &format!("SELECT 1 AS n FROM {VAULT_KEYS} WHERE workspace_id = ? AND wrapped_vmk IS NOT NULL AND device_id = ?"), &[rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(device_id)], ) .map_err(|error| error.to_string())? .is_some(); Ok(!others && (own || devices::current_version(replica.driver, replica.workspace_id)?.is_none())) }) .map_err(unreadable) } /// Whether this signed-in device joins a vault another device holds (GETTING-IN.md, step 2: "then, by itself, the /// waiting page"): another device holds a wrap and this one does not. The shell then publishes this device's key with /// no question (`vault.unlock`): publishing asks nothing and opens nothing, as the wrap comes only after the person /// approves on the device that holds it, so the waiting page stands at once instead of behind an Unlock tap. pub(crate) fn joins_here(client: &ClientController) -> Result { if !client.signed_in() || client.write_refusal().is_some() { return Ok(false); } let Ok(device_id) = this_device(client) else { return Ok(false); }; if !knows_the_vault(client)? { return Ok(false); } client .with_file(|replica| { let wrapped = |mine: bool| -> Result { let op = if mine { "=" } else { "<>" }; Ok(replica .driver .get( &format!("SELECT 1 AS n FROM {VAULT_KEYS} WHERE workspace_id = ? AND wrapped_vmk IS NOT NULL AND device_id {op} ?"), &[rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(device_id.clone())], ) .map_err(|error| error.to_string())? .is_some()) }; Ok(wrapped(false)? && !wrapped(true)?) }) .map_err(unreadable) } /// Whether this copy can tell an unfounded vault from one it has not read: /// its app syncs the object's `vault_key` rows, and a pull has landed since /// launch. Founding mints a NEW vault master key, so a copy that cannot tell /// never founds (12 Nov 2026): Messages, whose kit /// held no `vault_key`, founded over the vault Keys held, and where the two /// apps share one key (the team keychain group) the object took the new wrap /// as the same device's and retired the one every saved secret opens with. fn knows_the_vault(client: &ClientController) -> Result { let kit = crate::phone::tool_acts::app_kit(client)?; if kit.as_ref().is_some_and(|kit| !kit.keeps_table(VAULT_KEY_TABLE)) { return Ok(false); } // A pass for THIS database: the last one may have been another number's (signed out and in again). let Ok(database) = client.current_database() else { return Ok(false) }; Ok(client.pulled(&database)) } /// The object's table of device keys, as a kit names it. const VAULT_KEY_TABLE: &str = "vault_key"; /// A DEVICE IS ITS KEY, NOT ITS ROW ID (8 Nov 2026). A /// phone that founded its vault before it signed in pushed that founding at /// adoption under its founder row id, then published its signed-in row under /// a new one; the copy keeps one row per device, so the founder row's pull /// collides with its own and parks, and the wrap the object holds for this /// device is never seen. A pulled `cotton_vault_keys` row whose public key is /// this device's own (the one its Keychain holds the private half of) IS /// this device's row: its wrap and version are taken over this device's own /// row (unless that already holds a wrap at that version or later), and the /// parked pull ends, through `rejected::discard`, the one way a park ends /// outside a resolution. The object retires the older row once it takes the /// wrap onto this one (one row per device key, the Worker's /// `retireOlderKeyRows`). Run on every vault need and after every pass, so a /// copy already holding the parked collision heals on its next pull. /// Answers whether a wrap was taken. pub(crate) fn take_own_key(client: &ClientController) -> Result { if !client.signed_in() || client.write_refusal().is_some() { return Ok(false); } let Ok(device_id) = this_device(client) else { return Ok(false); }; let keychain = client.vault_public(); let answer = write(client, "vault.takeOwnKey", &mut |ctx| { let own = ctx .db() .get( &format!("SELECT id, public_key, wrapped_vmk, vmk_version FROM {VAULT_KEYS} WHERE workspace_id = ? AND device_id = ?"), &[ rusqlite::types::Value::Text(ctx.workspace_id.to_string()), rusqlite::types::Value::Text(device_id.clone()), ], ) .map_err(|error| error.to_string())?; let Some(own) = own else { return Ok(json!({ "taken": false })) }; let id = own.text("id").unwrap_or_default().to_string(); let public = own.text("public_key").unwrap_or_default().to_string(); if keychain.as_deref().is_some_and(|held| held != public) { return Ok(json!({ "taken": false })); } let held_version = own.text("wrapped_vmk").map(|_| own.int("vmk_version").unwrap_or(0)).unwrap_or(-1); let mine: Vec<(String, String, i64)> = cotton_store::rejected::list_parked(ctx.db(), i64::MAX) .map_err(|error| error.to_string())? .into_iter() .filter(|park| park.direction == "pull" && park.table == VAULT_KEYS && park.row_id != id) .filter_map(|park| { let patch = park.patch?; if patch.get("public_key").and_then(Value::as_str) != Some(public.as_str()) { return None; } let wrapped = patch.get("wrapped_vmk").and_then(Value::as_str)?.to_string(); let version = patch.get("vmk_version").and_then(Value::as_i64).unwrap_or(0); Some((park.op_id, wrapped, version)) }) .collect(); let Some((_, wrapped, version)) = mine.iter().max_by_key(|(_, _, version)| *version).cloned() else { return Ok(json!({ "taken": false })); }; let taken = version > held_version; if taken { let mut patch = Map::new(); patch.insert("wrapped_vmk".to_string(), Value::from(wrapped)); patch.insert("vmk_version".to_string(), Value::from(version)); update_row(ctx, VAULT_KEYS, &id, patch).map_err(|failure| failure.to_string())?; } let parked: Vec = mine.into_iter().map(|(op_id, _, _)| op_id).collect(); cotton_store::rejected::discard(ctx.db(), &parked).map_err(|error| error.to_string())?; Ok(json!({ "taken": taken })) })?; Ok(strip_envelope(answer).get("taken").and_then(Value::as_bool).unwrap_or(false)) } /// Where this device's own founding wrap stands with the object. enum Founding { /// None is waiting: taken, or never written here. Taken, /// Still queued here: it opens nothing until the object has it. Queued, /// The object refused it (`vault_founded`, parked): now let go. Refused, } /// Whether this device's own founding wrap is still queued here: written, /// not yet taken by the object. An unlock card's Allow is held while it is /// (`phone::unlock`). pub(crate) fn founding_waits(client: &ClientController) -> Result { Ok(matches!(founding(client)?, Founding::Queued)) } /// A founding still on its way is a wait, said as one: the phone's screens /// wait on `vault_not_wrapped_yet` and need no word of their own for it. fn founding_queued() -> MethodError { MethodError::new("vault_not_wrapped_yet", "Setting up this device's vault: it opens once Cotton has its key.") } fn founding_refused() -> MethodError { MethodError::new( "vault_not_wrapped_yet", "Another device set up this vault first. Waiting for it to let this device in.", ) } /// Whether this device's own founding wrap, on a signed-in copy, is one the /// object has taken. A founding write still queued here opens nothing yet; /// one the object refused (parked: another device founded first) is let go — /// the wrap cleared, the park dropped — and the device waits for a device /// that holds the vault. A founding is the write that put a version-1 wrap on /// this device's own row; a rotation's re-wrap is at a later version and an /// approval wraps another device's row. fn founding(client: &ClientController) -> Result { if !client.signed_in() { return Ok(Founding::Taken); } let Ok(device_id) = this_device(client) else { return Ok(Founding::Taken); }; let pending = client .with_file(|replica| { let row = replica .driver .get( &format!( "SELECT id FROM {VAULT_KEYS} WHERE workspace_id = ? AND device_id = ? AND wrapped_vmk IS NOT NULL AND vmk_version = 1" ), &[ rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(device_id.clone()), ], ) .map_err(|error| error.to_string())?; let Some(row) = row else { return Ok(None) }; let id = row.text("id").unwrap_or_default().to_string(); let founding = |queue: &str| -> Result { Ok(replica .driver .get( &format!( "SELECT 1 AS n FROM _writes w JOIN {queue} q ON q.op_id = w.op_id WHERE w.tbl = '{VAULT_KEYS}' AND w.row_id = ? AND w.fields LIKE '%\"wrapped_vmk\"%'" ), &[rusqlite::types::Value::Text(id.clone())], ) .map_err(|error| error.to_string())? .is_some()) }; if founding("(SELECT op_id FROM _parked WHERE direction = 'push')")? { return Ok(Some((id, true))); } Ok(founding("_outbox")?.then_some((id, false))) }) .map_err(unreadable)?; match pending { None => Ok(Founding::Taken), Some((_, false)) => Ok(Founding::Queued), Some((id, true)) => { client.vault_session().lock_all(); write(client, "vault.foundingRefused", &mut |ctx| { let mut patch = Map::new(); patch.insert("wrapped_vmk".to_string(), Value::Null); patch.insert("vmk_version".to_string(), Value::from(0)); update_row(ctx, VAULT_KEYS, &id, patch).map_err(|failure| failure.to_string())?; // The object refused this founding, so its parked push is discarded // the one way a park ends outside a resolution: by the owner's hand // through `rejected::discard`, never by a DELETE of our own. let parked: Vec = ctx .db() .all( &format!( "SELECT op_id FROM _parked WHERE direction = 'push' AND tbl = '{VAULT_KEYS}' AND row_id = ?" ), &[rusqlite::types::Value::Text(id.clone())], ) .map_err(|error| error.to_string())? .iter() .filter_map(|row| row.text("op_id").map(str::to_string)) .collect(); cotton_store::rejected::discard(ctx.db(), &parked).map_err(|error| error.to_string())?; Ok(json!({ "id": id })) })?; Ok(Founding::Refused) } } } // ── vault.status ─────────────────────────────────────────────────────────── /// What the Passwords screens need to know before they draw anything. /// /// `hasKey` is whether this device has PUBLISHED a public half — which a phone /// only ever does when it holds the private one, so the row is the honest /// reading of the question from this side of the Keychain. `legacyCount` is how /// many rows are still sealed under the scheme that predates the vault; the /// server's one-time sweep is what clears them, and until it has, the page says /// so rather than showing a Reveal that cannot work. pub fn status(client: &ClientController) -> Result { let now = client.now(); let unlocked_until = client.vault()?.until(now); let this = this_device(client)?; let door = client.vault()?; client.with_file(|replica| { let mut answer = status_of(replica, this.clone(), LegacyScope::WholeVault)?; answer["unlocked"] = json!(unlocked_until.is_some()); answer["until"] = unlocked_until.map_or(Value::Null, |at| json!(iso(at))); let chain = door.with_vmk(now, |vmk, held| { (held, retired_keys(replica.driver, replica.workspace_id, vmk, held)) }); let (older, unreachable) = older_values(replica, chain.as_ref())?; answer["olderCount"] = json!(older.len()); answer["older"] = json!(older); answer["unreachableCount"] = json!(unreachable.len()); answer["unreachable"] = json!(unreachable); Ok(answer) }) } /// The vault settings' two lists (slice 9b): values still sealed under an /// OLDER key the chain reaches, and values sealed under a key this vault no /// longer has. Each is the secrets' ids, oldest version first. /// /// Unlocked, reach is the chain the key in hand walks — the only exact answer, /// since a link is picked by its key check value. Locked, there is no key to /// check a value against, so reach is read off the links' versions alone. fn older_values( replica: &ReadFile<'_>, chain: Option<&(u32, vault_core::chain::RetiredKeys)>, ) -> Result<(Vec, Vec), String> { let Some(current) = state_version(replica)? else { return Ok((Vec::new(), Vec::new())); }; let workspace = || rusqlite::types::Value::Text(replica.workspace_id.to_string()); let rows = replica .driver .all( &format!( "SELECT id, vmk_version FROM {SECRETS} WHERE workspace_id = ? AND value_enc IS NOT NULL AND vmk_version > 0 AND vmk_version < ? ORDER BY vmk_version, id" ), &[workspace(), rusqlite::types::Value::Integer(i64::from(current))], ) .map_err(|error| error.to_string())?; let reaches: Box bool> = match chain { Some((held, keys)) => { let held = *held; Box::new(move |version| version >= held || keys.reaches(version)) } None => { let links = replica .driver .all( &format!( "SELECT version, under_version FROM {RETIRED_KEYS} WHERE workspace_id = ?" ), &[workspace()], ) .map_err(|error| error.to_string())?; let links: Vec<(i64, i64)> = links .iter() .filter_map(|row| Some((row.int("version")?, row.int("under_version")?))) .collect(); let mut reached = vec![i64::from(current)]; let mut frontier = reached.clone(); while let Some(held) = frontier.pop() { for (version, under) in &links { if *under == held && *version < held && !reached.contains(version) { reached.push(*version); frontier.push(*version); } } } Box::new(move |version| reached.contains(&i64::from(version))) } }; let (mut older, mut unreachable) = (Vec::new(), Vec::new()); for row in &rows { let (Some(id), Some(version)) = (row.text("id"), row.int("vmk_version")) else { continue; }; if reaches(version as u32) { older.push(id.to_string()); } else { unreachable.push(id.to_string()); } } Ok((older, unreachable)) } /// Which rows `legacyCount` counts. /// /// The count has two readers with two questions. Settings and a secret's own /// page ask about the VAULT — how much of the Mac's one-time re-seal is still /// owed, over every kind and the bin included, because that job is whole-vault. /// The Passwords LIST asks about itself: its status line sits over the rows it /// draws, and a line saying "125 items are sealed" over a list of four accounts /// was the number a person could not find (the document passwords #1027 took /// off the list were still in the count). So the list's count runs through the /// SAME two filters as its rows — `listed_on_passwords` and the bin side it is /// showing — and can no longer name a row the list does not have. #[derive(Clone, Copy)] enum LegacyScope { /// Every sealed row in the file — the re-seal job's own size. WholeVault, /// Only what the Passwords list shows on the side (`trashed`) it is showing. Listed { trashed: bool }, } impl LegacyScope { fn clause(self) -> String { match self { LegacyScope::WholeVault => String::new(), LegacyScope::Listed { trashed } => format!( " AND trashed_at IS {} NULL{}", if trashed { "NOT" } else { "" }, listed_kinds_clause("kind") ), } } } /// The file's half of the status — everything except the unlock, which is this /// process's and not the file's. fn status_of( replica: &ReadFile<'_>, device_id: String, legacy: LegacyScope, ) -> Result { let row = replica .driver .get( &format!( "SELECT public_key, wrapped_vmk, vmk_version FROM {VAULT_KEYS} WHERE workspace_id = ? AND device_id = ?" ), &[ rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(device_id), ], ) .map_err(|error| error.to_string())?; let state = state_version(replica)?; let row_version = row.as_ref().and_then(|row| row.int("vmk_version")).unwrap_or(0) as u32; let wrapped = row .as_ref() .is_some_and(|row| row.text("wrapped_vmk").is_some()) && state.is_none_or(|state| row_version >= state); let legacy = replica .driver .get( &format!( "SELECT COUNT(*) AS n FROM {SECRETS} WHERE workspace_id = ? AND vmk_version = 0 AND value_enc IS NOT NULL{}", legacy.clause() ), &[rusqlite::types::Value::Text( replica.workspace_id.to_string(), )], ) .map_err(|error| error.to_string())? .and_then(|row| row.int("n")) .unwrap_or(0); Ok(json!({ "hasKey": row.is_some(), "wrapped": wrapped, "unlocked": false, "until": Value::Null, "legacyCount": legacy, "vmkVersion": state.unwrap_or(0), })) } // ── vault.reveal ─────────────────────────────────────────────────────────── /// The payload, opened, to the one caller that asked — and `last_used_at`. /// /// A read AND a write in one transaction, deliberately: the stamp is what makes /// "when did I last use this" true, and doing it in a second call would be a /// second chance for it to be wrong. The event that write emits names the /// TABLE, as every write does, and carries nothing of the row. fn reveal(client: &ClientController, request: &Value) -> Result { if let Some(sentence) = client.write_refusal() { return Err(MethodError::new(REFUSED_DEVICE, sentence)); } let id = owner::text(request, "id")?; let now = client.now(); let session = client.vault().map_err(unreadable)?; if session.until(now).is_none() { return Err(locked()); } let session = &session; let answer = write(client, "vault.reveal", &mut |ctx| { let Some(row) = ctx .db() .get( &format!( "SELECT kind, value_enc, vmk_version FROM {SECRETS} WHERE workspace_id = ? AND id = ?" ), &[ rusqlite::types::Value::Text(ctx.workspace_id.to_string()), rusqlite::types::Value::Text(id.clone()), ], ) .map_err(|error| error.to_string())? else { return Err(NOT_FOUND.to_string()); }; let Some(sealed) = row.text("value_enc").map(|text| text.to_string()) else { return Err(NOTHING_SEALED.to_string()); }; if is_legacy(&sealed) { return Err(OLD_KEY.to_string()); } let version = row.int("vmk_version").unwrap_or(0) as u32; // A value stays at the version it was sealed at: one older than the // key in hand opens through the retired keys that key reaches. let opened = session .with_vmk(now, |vmk, held| { if held == version { return open_sealed(vmk, &id, version, &sealed).ok_or_else(|| STALE.to_string()); } if version > held { return Err(STALE.to_string()); } let retired = retired_keys(ctx.db(), ctx.workspace_id, vmk, held); // A version the chain does not reach is never tried under any // other key: it is sealed under a key this vault no longer has. if !retired.reaches(version) { return Err(LOST.to_string()); } retired.open(&id, version, &sealed).ok_or_else(|| STALE.to_string()) }) .ok_or_else(|| LOCKED.to_string())??; let payload: Value = serde_json::from_slice(&opened).map_err(|error| { // The bytes are not named; only that they did not parse. format!("the sealed payload is not a secret this build understands: {error}") })?; cotton_core::vault::seal::wipe(opened); let mut patch = Map::new(); patch.insert("last_used_at".to_string(), Value::from(now_iso(ctx))); update_row(ctx, SECRETS, &id, patch).map_err(|failure| failure.to_string())?; Ok(json!({ "id": id, "payload": payload })) }) .map_err(name_the_refusal)?; // The body's half of the write envelope — see `strip_envelope`. Ok(strip_envelope(answer)) } /// Every older vault key the key in hand reaches through this file's /// `cotton_vault_retired_keys` facts. A rotation seals nothing again, so this /// is what opens a value sealed before one. Unreadable facts reach nothing. pub(crate) fn retired_keys( driver: &cotton_store::driver::Driver, workspace_id: &str, vmk: &Vmk, version: u32, ) -> vault_core::chain::RetiredKeys { let links: Vec = driver .all( &format!( "SELECT version, under_version, under_kcv, wrapped FROM {RETIRED_KEYS} WHERE workspace_id = ?" ), &[rusqlite::types::Value::Text(workspace_id.to_string())], ) .unwrap_or_default() .iter() .filter_map(|row| { Some(vault_core::chain::RetiredLink { version: u32::try_from(row.int("version")?).ok()?, under_version: u32::try_from(row.int("under_version")?).ok()?, under_kcv: row.text("under_kcv")?.to_string(), wrapped: row.text("wrapped")?.to_string(), }) }) .collect(); vault_core::chain::RetiredKeys::walk(vmk, version, workspace_id, &links) } const NOT_FOUND: &str = "not_found: there is no secret with that id"; const NOTHING_SEALED: &str = "nothing_sealed: this secret has no value stored yet"; const OLD_KEY: &str = "vault_sealed_under_the_old_key: this item is still sealed under the old key — your Mac \ re-seals it once, on its next start"; const STALE: &str = "vault_stale: this phone is holding an older vault key than the one this item is sealed \ under. Unlock again."; const LOST: &str = "vault_key_lost: this item is sealed under a key this vault no longer has"; const LOCKED: &str = "vault_locked: the vault is locked"; const ROTATED: &str = "vault_rotated: the vault's key was rotated since you unlocked it. Unlock again."; /// Turn the one named refusal a write body can carry back into a coded error. /// /// `write_rows` answers `Result`, so a body's refusal arrives as /// a sentence. Rather than a second error channel, each sentence above STARTS /// with its code and this splits it — so a screen gets `vault_locked` and the /// sentence the body wrote, and a refusal that is not one of these is still /// `write_refused` with its reason intact. fn name_the_refusal(error: MethodError) -> MethodError { let message = error.message.clone(); for code in [ "not_found", "nothing_sealed", "vault_sealed_under_the_old_key", "vault_stale", "vault_key_lost", "vault_rotated", "vault_locked", "no_such_device", "already_approved", "unwrappable_key", "approved_stays", "vault_founded", ] { if let Some(rest) = message.strip_prefix(&format!("{code}: ")) { return MethodError::new(code, rest); } } error } pub(crate) fn locked() -> MethodError { MethodError::new( "vault_locked", "The vault is locked. Unlock it to see this.", ) } // ── the person key ───────────────────────────────────────────────────────── /// The table a person key lives in — the PERSONAL database's alone. const PERSON_KEYS: &str = "cotton_person_keys"; /// Sign a message as the person this device belongs to. /// /// **This is a Rust call and NOT a method**: it is in no dispatch table, so no /// request from Swift reaches it, and what it answers is the person key (the /// public half) and a signature — never the sealed private half and never the /// opened one. The seed is opened inside the borrow of the vault key, signs, /// and is wiped when the [`PersonKey`] drops. /// /// The row is the PERSONAL database's (`with_file` names no other), and the /// vault key is that database's — the one `vault.unlock` holds. A locked vault /// refuses as `vault_locked`; a database with no person key yet (its Mac has /// not run its first vault pass, or the row has not synced) as `no_person_key`. // The callers are the membership facts and the invite claim, which land after // this. fn no_person_key() -> MethodError { MethodError::new( "no_person_key", "This database has no person key yet. It is made by the Mac that serves it.", ) } /// The person key's PUBLIC half, which a statement names before it is signed /// (`cotton_core::invite_link::device_statement_bytes` carries it). Needs no /// unlocked vault, and reads the public column alone: the sealed private half /// is read in [`sign_as_person`] and nowhere else (its guard holds that). pub(crate) fn person_public_key(client: &ClientController) -> Result { client.require_personal().map_err(unreadable)?; // The key lives in the PERSONAL database alone: read it there, whichever // database the call names. Read in a shared one it was "no person key", // so its Members and byline took the owner reading them for someone else. let _personal = client.name_database(None).map_err(unreadable)?; client .with_file(|replica| { let row = replica .driver .get( &format!( "SELECT public_key FROM {PERSON_KEYS} WHERE workspace_id = ? ORDER BY created_at, id LIMIT 1" ), &[rusqlite::types::Value::Text( replica.workspace_id.to_string(), )], ) .map_err(|error| error.to_string())?; Ok(row.and_then(|row| row.text("public_key").map(str::to_string))) }) .map_err(unreadable)? .ok_or_else(no_person_key) } /// Whether [`sign_as_person`] would sign now: `vault_locked` otherwise. A /// protocol that ends in a person signature asks this before its first /// request, so a locked phone sends nothing it cannot finish. pub(crate) fn person_can_sign(client: &ClientController) -> Result<(), MethodError> { let now = client.now(); let session = client.vault().map_err(unreadable)?; if session.until(now).is_none() { return Err(locked()); } Ok(()) } pub(crate) fn sign_as_person( client: &ClientController, message: &[u8], ) -> Result<(String, [u8; 64]), MethodError> { client.require_personal().map_err(unreadable)?; let now = client.now(); let session = client.vault().map_err(unreadable)?; if session.until(now).is_none() { return Err(locked()); } // In the personal database, as `person_public_key` reads the public half. let _personal = client.name_database(None).map_err(unreadable)?; let row = client .with_file(|replica| { let row = replica .driver .get( &format!( "SELECT public_key, sealed_private, vmk_version FROM {PERSON_KEYS} WHERE workspace_id = ? ORDER BY created_at, id LIMIT 1" ), &[rusqlite::types::Value::Text( replica.workspace_id.to_string(), )], ) .map_err(|error| error.to_string())?; Ok(row.and_then(|row| { Some(( row.text("public_key")?.to_string(), row.text("sealed_private")?.to_string(), row.int("vmk_version").unwrap_or(0) as u32, )) })) }) .map_err(unreadable)?; let Some((public_key, sealed, version)) = row else { return Err(no_person_key()); }; let signature = session .with_vmk(now, |vmk, held| { if held != version { return None; } cotton_core::keys::PersonKey::open_private(vmk, &public_key, version, &sealed) .map(|key| key.sign(message)) }) .ok_or_else(locked)? .ok_or_else(|| name_the_refusal(refused(STALE.to_string())))?; Ok((public_key, signature)) } // ── vault.create / vault.update ──────────────────────────────────────────── /// Everything a row carries besides its payload. struct Plain { kind: Option, name: Option, site: Option, username: Option, service: Option, expires_at: Option, } fn plain(request: &Value) -> Result { let kind = match owner::optional_text(request, "kind") { None => None, Some(kind) => Some( vault_core::SecretKind::parse(&kind) .ok_or_else(|| { MethodError::new( "bad_request", format!("`{kind}` is not a kind a secret can be"), ) })? .as_str() .to_string(), ), }; Ok(Plain { kind, name: owner::optional_text(request, "name"), site: owner::optional_text(request, "site"), username: owner::optional_text(request, "username"), service: owner::optional_text(request, "service"), expires_at: owner::optional_text(request, "expiresAt"), }) } /// The typed payload, built from the kind and the fields the form filled. /// /// The wire shape is FLAT and tagged on `kind` (`cotton_core::vault::payload`), /// so the fields and the kind are folded into one object and handed to serde — /// which is what makes the six shapes one declaration rather than six parsers /// on this side. fn payload(kind: &str, request: &Value) -> Result { let Some(fields) = request.get("fields").and_then(Value::as_object) else { return Err(MethodError::new( "bad_request", "`fields` is what the secret actually holds", )); }; let mut object = fields.clone(); object.insert("kind".to_string(), Value::from(kind)); serde_json::from_value(Value::Object(object)).map_err(|error| { // NEVER the value — only which field is wrong. This is the one parser // in the crate standing beside a plaintext credential. MethodError::new( "bad_request", format!("a {kind} needs different fields than these: {error}"), ) }) } /// Seal a new secret and write the row. fn create(client: &ClientController, request: &Value) -> Result { let asked = plain(request)?; let Some(kind) = asked.kind.clone() else { return Err(MethodError::new( "bad_request", "`kind` is what this secret is — a login, a key, a note, a card or an ID", )); }; let Some(name) = asked.name.clone() else { return Err(MethodError::new( "bad_request", "`name` is what you call it", )); }; let payload = payload(&kind, request)?; let now = client.now(); let session = client.vault().map_err(unreadable)?; if session.until(now).is_none() { return Err(locked()); } let session = &session; let answer = write(client, "vault.create", &mut |ctx| { let id = ctx.new_uuid(); let (value_enc, version) = seal_payload(ctx, session, now, &id, &payload)?; let hint = payload.hint(); let mut patch = Map::new(); patch.insert("kind".to_string(), Value::from(kind.clone())); patch.insert("name".to_string(), Value::from(name.clone())); patch.insert("site".to_string(), text_or_null(asked.site.as_deref())); patch.insert( "username".to_string(), text_or_null(asked.username.as_deref()), ); patch.insert( "service".to_string(), text_or_null(asked.service.as_deref()), ); patch.insert("value_enc".to_string(), Value::from(value_enc)); patch.insert("vmk_version".to_string(), Value::from(version)); patch.insert("hint".to_string(), Value::from(hint.clone())); // Written out loud: the DDL carries no defaults for these. patch.insert("last_used_at".to_string(), Value::Null); patch.insert( "expires_at".to_string(), text_or_null(asked.expires_at.as_deref()), ); patch.insert("trashed_at".to_string(), Value::Null); insert_row(ctx, SECRETS, &id, patch).map_err(|failure| failure.to_string())?; Ok(json!({ "id": id, "kind": kind, "name": name, "site": asked.site, "username": asked.username, "service": asked.service, "hint": hint, })) }) .map_err(name_the_refusal)?; Ok(strip_envelope(answer)) } /// Change a secret's plain columns, its payload, or both. /// /// **Metadata alone does NOT need the vault open.** Renaming a login is not /// reading it, and making a person hold their thumb down to fix a typo in a /// name would teach them to unlock for everything. fn update(client: &ClientController, request: &Value) -> Result { let id = owner::text(request, "id")?; let asked = plain(request)?; let wants_payload = request.get("fields").is_some(); let now = client.now(); let session = client.vault().map_err(unreadable)?; if wants_payload && session.until(now).is_none() { return Err(locked()); } let session = &session; let answer = write(client, "vault.update", &mut |ctx| { let Some(row) = ctx .db() .get( &format!("SELECT kind FROM {SECRETS} WHERE workspace_id = ? AND id = ?"), &[ rusqlite::types::Value::Text(ctx.workspace_id.to_string()), rusqlite::types::Value::Text(id.clone()), ], ) .map_err(|error| error.to_string())? else { return Err(NOT_FOUND.to_string()); }; let kind = row.text("kind").unwrap_or_default().to_string(); let mut patch = Map::new(); for (column, value) in [ ("name", asked.name.as_deref()), ("site", asked.site.as_deref()), ("username", asked.username.as_deref()), ("service", asked.service.as_deref()), ("expires_at", asked.expires_at.as_deref()), ] { if let Some(value) = value { patch.insert(column.to_string(), Value::from(value)); } } if wants_payload { // The KIND is the row's, never the request's: a login that became // a card would be a payload the page cannot draw and a hint taken // from a field that is not there. let payload = payload(&kind, request).map_err(|error| error.message)?; let (value_enc, version) = seal_payload(ctx, session, now, &id, &payload)?; patch.insert("value_enc".to_string(), Value::from(value_enc)); patch.insert("vmk_version".to_string(), Value::from(version)); patch.insert("hint".to_string(), Value::from(payload.hint())); } if patch.is_empty() { return Ok(json!({ "id": id, "changed": false })); } update_row(ctx, SECRETS, &id, patch).map_err(|failure| failure.to_string())?; Ok(json!({ "id": id, "changed": true })) }) .map_err(name_the_refusal)?; Ok(strip_envelope(answer)) } /// Seal one payload under the key this device is holding. /// /// **NEVER BELOW THE FILE'S VERSION.** A rotation that folded in after this /// unlock leaves the session holding a retired key; a value sealed under it /// would be sealed under a key a revoked device still holds. So the file's /// current version is read first, and a session behind it is ended with /// `vault_rotated` — unlock again, which opens the new wrap. fn seal_payload( ctx: &Ctx<'_>, session: &VaultDoor, now: DateTime, id: &str, payload: &vault_core::SecretPayload, ) -> Result<(String, u32), String> { let current = ctx .db() .get( &format!("SELECT vmk_version FROM {VAULT_STATE} WHERE workspace_id = ?"), &[rusqlite::types::Value::Text(ctx.workspace_id.to_string())], ) .map_err(|error| error.to_string())? .and_then(|row| row.int("vmk_version")); if let (Some(current), Some(held)) = (current, session.version(now)) { if i64::from(held) < current { session.lock(); return Err(ROTATED.to_string()); } } // The rule Cotton Keys' passwords and passkeys are sealed by // (`cotton_core::keys::sealed_row`), one for every password row. let sealed = session .with_vmk(now, |vmk, version| { cotton_core::keys::password_row::seal(payload, vmk, id, version).ok().map(|row| (row.value_enc, version)) }) .ok_or_else(|| LOCKED.to_string())?; sealed.ok_or_else(|| "the secret could not be sealed. Nothing was written.".to_string()) } // ── vault.trash / vault.restore ──────────────────────────────────────────── /// To the bin, or back out of it, through the one write every door shares /// (`secrets::set_trashed`). /// /// `trashed_at` and nothing else: the bin is kind-generic, `restore_from_bin` /// and `empty_bin` already reach a secret (`cotton_core::rules::bin`), and a /// second way to erase one would be a second answer to what "delete" means. fn set_trashed( client: &ClientController, method: &str, request: &Value, trashed: bool, ) -> Result { let id = owner::text(request, "id")?; let answer = write(client, method, &mut |ctx| { let exists = ctx .db() .get( &format!("SELECT id, name FROM {SECRETS} WHERE workspace_id = ? AND id = ?"), &[ rusqlite::types::Value::Text(ctx.workspace_id.to_string()), rusqlite::types::Value::Text(id.clone()), ], ) .map_err(|error| error.to_string())?; let Some(found) = exists else { return Err(NOT_FOUND.to_string()); }; // The receipt says what happened (R4): a login moved to the bin is // not deleted, and the walk read "Deleted …" over a Move to bin. let name = found.text("name").unwrap_or("the password").to_string(); let said = if trashed { let shown = cotton_tools::mcp::handlers::bin::bin_shown(ctx).map_err(|failure| failure.to_string())?; cotton_core::records::receipt::binned_said(&name, shown) } else { format!("Restored {name}") }; cotton_tools::mcp::handlers::secrets::set_trashed(ctx, &id, trashed) .map_err(|failure| failure.to_string())?; Ok(json!({ "id": id, "trashed": trashed, "said": said })) }) .map_err(name_the_refusal)?; Ok(strip_envelope(answer)) } // ── the reads ────────────────────────────────────────────────────────────── /// `read.secrets` — the Passwords list, and the status line above it. /// /// **A document's password is not on this list** ([`listed_on_passwords`]): /// not in the rows, not in the counts, not in what a search finds. It is still /// a secret, sealed like every other and opened by the document it belongs to; /// this read is only what the Passwords screen draws. /// /// **`value_enc` is not in the column list and must never join it.** The whole /// design is that a list is drawn from the plain columns and the four-character /// hint; the payload is opened by one method, on demand, behind a presence /// prompt. /// /// The STATUS rides this read rather than being a second one, because a screen /// with two reads is two answers to one question — `no_two_reads_share_a_name_ /// or_a_screen` says so, and the line above the list is part of the same /// picture as the list itself. pub fn secrets_read( client: &ClientController, args: &Map, ) -> Result { let now = client.now(); let unlocked_until = client.vault()?.until(now); let kind = match args.get("kind").and_then(Value::as_str) { None => None, Some(kind) => Some( vault_core::SecretKind::parse(kind) .ok_or_else(|| format!("`{kind}` is not a kind a secret can be"))? .as_str() .to_string(), ), }; let query = args .get("q") .and_then(Value::as_str) .map(str::trim) .filter(|text| !text.is_empty()) .map(str::to_string); let trashed = args .get("trashed") .and_then(Value::as_bool) .unwrap_or(false); let this = this_device(client)?; client.with_file(|replica| { let mut status = status_of(replica, this.clone(), LegacyScope::Listed { trashed })?; status["unlocked"] = json!(unlocked_until.is_some()); status["until"] = unlocked_until.map_or(Value::Null, |at| json!(iso(at))); Ok(json!({ "secrets": secret_rows(replica, kind.as_deref(), query.as_deref(), trashed)?, "status": status, "kinds": kind_counts(replica, trashed)?, })) }) } /// Does the Passwords list show a secret of this kind? /// /// **`document` does not.** A document's password is only needed where the /// document is — it opens the filed PDF, and on the list it was a wall of /// "… statement / document password" rows burying the person's own accounts /// (the owner's call, 2026-09-27). It stays a secret like any other: nothing is /// deleted, the document still opens with it, and the MCP tools still see it. /// /// A `match` with no `_` arm, so a seventh kind added to the vault fails to /// compile here until somebody says whether this list shows it. pub(crate) const fn listed_on_passwords(kind: vault_core::SecretKind) -> bool { kind.on_passwords() } /// `AND s.kind IN (…)` over exactly the kinds [`listed_on_passwords`] keeps — /// the one clause both the rows and the counts are read through, so the chips /// and the list cannot disagree about what is on it. fn listed_kinds_clause(column: &str) -> String { vault_core::SecretKind::on_passwords_clause(column) } /// The rows, filtered by kind and by what was typed. /// /// `q` runs over `fts_secrets`, which indexes `name, site, username, service` /// and NOTHING else — the payload is never indexed, which is the reason a /// search over passwords is safe to have at all. fn secret_rows( replica: &ReadFile<'_>, kind: Option<&str>, query: Option<&str>, trashed: bool, ) -> Result { let mut sql = format!( "SELECT s.id, s.kind, s.name, s.site, s.username, s.service, s.hint, s.last_used_at, s.expires_at, s.vmk_version, s.value_enc IS NOT NULL AS has_value, s.created_at, s.updated_at FROM {SECRETS} s" ); let mut params: Vec = Vec::new(); if query.is_some() { sql.push_str(" JOIN fts_secrets ON fts_secrets.rowid = s.rowid"); } sql.push_str(if trashed { " WHERE s.workspace_id = ? AND s.trashed_at IS NOT NULL" } else { " WHERE s.workspace_id = ? AND s.trashed_at IS NULL" }); params.push(rusqlite::types::Value::Text( replica.workspace_id.to_string(), )); sql.push_str(&listed_kinds_clause("s.kind")); if let Some(kind) = kind { sql.push_str(" AND s.kind = ?"); params.push(rusqlite::types::Value::Text(kind.to_string())); } if let Some(query) = query { sql.push_str(" AND fts_secrets MATCH ?"); params.push(rusqlite::types::Value::Text(fts_query(query))); } sql.push_str(" ORDER BY s.name COLLATE NOCASE ASC, s.created_at ASC"); let rows = replica .driver .all(&sql, ¶ms) .map_err(|error| error.to_string())?; Ok(Value::Array( rows.iter() .map(|row| { let value_enc_present = row.int("has_value").unwrap_or(0) != 0; json!({ "id": row.text("id"), "kind": row.text("kind"), "name": row.text("name"), "site": row.text("site"), "username": row.text("username"), "service": row.text("service"), // At most four characters, ever — the column's own CHECK. "hint": row.text("hint"), "isSet": value_enc_present, // A row the server has not re-sealed yet cannot be revealed // on this phone, and the list says so rather than offering // a Reveal that refuses. "legacy": value_enc_present && row.int("vmk_version").unwrap_or(0) == 0, "lastUsedAt": row.text("last_used_at"), "expiresAt": row.text("expires_at"), "createdAt": row.text("created_at"), "updatedAt": row.text("updated_at"), }) }) .collect(), )) } /// How many secrets the Passwords list holds: what every screen says for /// Passwords — its own head and Everything's card alike — read through the /// list's one clause (290 walk: the list said 324 and Everything 449, the /// documents' passwords and nothing on the list). pub(crate) fn listed_count(driver: &cotton_store::driver::Driver, workspace_id: &str) -> Result { cotton_tools::mcp::handlers::tables::passwords_listed(driver, workspace_id) } /// How many of each kind there are — what the filter chips count. fn kind_counts(replica: &ReadFile<'_>, trashed: bool) -> Result { let sql = format!( "SELECT kind, COUNT(*) AS n FROM {SECRETS} WHERE workspace_id = ? AND trashed_at IS {} NULL{} GROUP BY kind", if trashed { "NOT" } else { "" }, listed_kinds_clause("kind"), ); let rows = replica .driver .all( &sql, &[rusqlite::types::Value::Text( replica.workspace_id.to_string(), )], ) .map_err(|error| error.to_string())?; let mut counts = Map::new(); // Every kind is PRESENT, at zero when there are none: a chip that vanishes // when its list empties is a chip a person cannot find their way back to. // A kind this list does not show is present too, and ALWAYS zero — the // clause above never counts it — so every client's parser still reads a // total map (Android's refuses one that is not). for kind in vault_core::SecretKind::ALL { counts.insert(kind.as_str().to_string(), json!(0)); } for row in &rows { if let Some(kind) = row.text("kind") { counts.insert(kind.to_string(), json!(row.int("n").unwrap_or(0))); } } Ok(Value::Object(counts)) } /// What a typed query becomes for FTS5. /// /// Every token becomes a PREFIX term, so "gma" finds "gmail" while a person is /// still typing, and every token is quoted so an apostrophe or a hyphen in a /// site name is text rather than syntax. A query with nothing left in it /// matches nothing rather than everything. fn fts_query(raw: &str) -> String { let terms: Vec = raw .split(|character: char| !character.is_alphanumeric()) .filter(|token| !token.is_empty()) .map(|token| format!("\"{token}\"*")) .collect(); if terms.is_empty() { return "\"\"".to_string(); } terms.join(" ") } /// `read.secret` — one secret's page. **Never the payload.** pub fn secret_read( client: &ClientController, args: &Map, ) -> Result { let id = args .get("id") .and_then(Value::as_str) .map(str::to_string) .ok_or_else(|| "id is required".to_string())?; let now = client.now(); let unlocked_until = client.vault()?.until(now); let this = this_device(client)?; client.with_file(|replica| { let Some(row) = replica .driver .get( &format!( "SELECT id, kind, name, site, username, service, hint, last_used_at, expires_at, vmk_version, value_enc IS NOT NULL AS has_value, trashed_at, created_at, updated_at FROM {SECRETS} WHERE workspace_id = ? AND id = ?" ), &[ rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(id.clone()), ], ) .map_err(|error| error.to_string())? else { return Ok(json!({ "secret": Value::Null })); }; let value_enc_present = row.int("has_value").unwrap_or(0) != 0; let mut status = status_of(replica, this.clone(), LegacyScope::WholeVault)?; status["unlocked"] = json!(unlocked_until.is_some()); status["until"] = unlocked_until.map_or(Value::Null, |at| json!(iso(at))); Ok(json!({ "secret": { "id": row.text("id"), "kind": row.text("kind"), "name": row.text("name"), "site": row.text("site"), "username": row.text("username"), "service": row.text("service"), "hint": row.text("hint"), "isSet": value_enc_present, "legacy": value_enc_present && row.int("vmk_version").unwrap_or(0) == 0, "lastUsedAt": row.text("last_used_at"), "expiresAt": row.text("expires_at"), "trashedAt": row.text("trashed_at"), "createdAt": row.text("created_at"), "updatedAt": row.text("updated_at"), }, "placements": placements(replica, &id)?, "projects": projects(replica, &id)?, "status": status, })) }) } /// The machines this secret is written onto as a file — the Mac's work, drawn /// here so the phone can see what its own passwords are doing elsewhere. fn placements(replica: &ReadFile<'_>, secret_id: &str) -> Result { let rows = replica .driver .all( // The device's NAME is deliberately absent. A device is not a row // in the person's file — it lives in the server's own registry — // so the id is all this replica honestly knows, and the screen // resolves a name through `pairing.devices` where it has one. A // join against a table that is not here would be the quiet null // this repo does not allow. "SELECT p.id, p.device_id, p.path, p.mode, p.format, p.env_name, p.applied_at, p.apply_problem, s.name AS secret_name FROM cotton_secret_placements p JOIN cotton_secrets s ON s.id = p.secret_id AND s.workspace_id = p.workspace_id WHERE p.workspace_id = ? AND p.secret_id = ? ORDER BY p.path ASC", &[ rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(secret_id.to_string()), ], ) .map_err(|error| error.to_string())?; Ok(Value::Array( rows.iter() .map(|row| { json!({ "id": row.text("id"), "deviceId": row.text("device_id"), "path": row.text("path"), "mode": row.int("mode"), "format": row.text("format"), "envName": row.text("env_name"), // `applied_hash` is NOT here: it is the applier's own // bookkeeping and says nothing a person reads. "appliedAt": row.text("applied_at"), "problem": row.text("apply_problem"), "problemLine": row.text("apply_problem").map(|sentence| cotton_core::vault::placement::problem_line(row.text("secret_name").unwrap_or(""), sentence)), }) }) .collect(), )) } /// The projects this secret belongs to — a client's portal login belongs to the /// client's project (`primitives.rs`, `project_linkable: Yes`). fn projects(replica: &ReadFile<'_>, secret_id: &str) -> Result { let rows = replica .driver .all( "SELECT p.id, p.slug, p.name FROM cotton_project_links l JOIN cotton_memory_projects p ON p.id = l.project_id WHERE l.workspace_id = ? AND l.record_kind = 'secret' AND l.record_id = ? ORDER BY p.name COLLATE NOCASE ASC", &[ rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(secret_id.to_string()), ], ) .map_err(|error| error.to_string())?; Ok(Value::Array( rows.iter() .map(|row| { json!({ "id": row.text("id"), "slug": row.text("slug"), "name": row.text("name"), }) }) .collect(), )) } // ── the small shared pieces ──────────────────────────────────────────────── /// This device's own id, which every vault row is keyed by. /// THE ID THE SERVER ADMITS THIS DEVICE BY, which is what `cotton_vault_keys` /// files a wrap under. /// /// **Never `replica.device_id`.** That is an AUTHOR id (`device:`) naming /// this device to a FILE, and `cotton_client::replica::resolve_device_id` says /// in as many words that the two must not be conflated. This is where it cost /// something: `vault.publishKey` wrote the phone's key row under the author id /// while `POST /v1/devices/pending/approve` writes it under the Ed25519 one, so /// the row the phone published named a device the registry had never heard of. /// `rotate::pending_rotation` reads exactly that as a REVOKED device — so every /// boot deleted the row and rotated the master key, and the phone read "Waiting /// for your Mac to share the key" for ever. pub(crate) fn this_device(client: &ClientController) -> Result { client .self_device_id() .ok_or_else(|| "this device has no identity yet, so it has no vault key".to_string()) } /// The workspace's current VMK version, or nothing when no server has minted /// one yet. `None` is a real state and never zero: a file whose vault has never /// been set up is not a file at version zero. pub(crate) fn state_version(replica: &ReadFile<'_>) -> Result, String> { Ok(replica .driver .get( &format!("SELECT vmk_version FROM {VAULT_STATE} WHERE workspace_id = ?"), &[rusqlite::types::Value::Text( replica.workspace_id.to_string(), )], ) .map_err(|error| error.to_string())? .and_then(|row| row.int("vmk_version")) .map(|version| version as u32)) } /// A 32-byte base64url public key, checked HERE so a malformed one is a refusal /// under the field rather than a row nothing can ever wrap for. fn public_key_arg(request: &Value) -> Result { let asked = owner::text(request, "publicKey")?; match URL_SAFE_NO_PAD.decode(&asked) { Ok(bytes) if bytes.len() == 32 => Ok(asked), _ => Err(MethodError::new( "bad_request", "`publicKey` is 32 bytes, base64url without padding", )), } } /// The private half, read out of the Keychain after the presence prompt. /// /// It is NEVER echoed, never logged and never put in an error's `details` — the /// refusal names the shape and nothing of what arrived. pub(crate) fn private_key_arg(request: &Value) -> Result<[u8; 32], MethodError> { let asked = request .get("privateKey") .and_then(Value::as_str) .unwrap_or_default(); let bytes = URL_SAFE_NO_PAD.decode(asked).ok(); match bytes.and_then(|bytes| <[u8; 32]>::try_from(bytes).ok()) { Some(bytes) => Ok(bytes), None => Err(MethodError::new( "bad_request", "`privateKey` is 32 bytes, base64url without padding", )), } } fn text_or_null(value: Option<&str>) -> Value { value.map_or(Value::Null, Value::from) } /// The BODY's own answer, out of the write envelope. /// /// The rule this states — **a phone METHOD answers its own shape; the envelope /// is `write`'s alone** — is no longer the vault's own. It is /// [`crate::authoring::own_answer`], beside the two functions that put the /// envelope on, because every method on this bus answers by it: the vault's /// five were merely the first to say so out loud. This name stays because the /// vault's call sites read better for it. fn strip_envelope(answer: Value) -> Value { crate::authoring::own_answer(answer) } fn iso(at: DateTime) -> String { cotton_client::seams::iso(at) } #[cfg(test)] #[path = "vault_tests.rs"] pub(crate) mod tests;