//! `password.*` — Cotton Keys' passwords, sealed and opened on this device. //! //! ```text //! password.list every login: site, user name, name, id; never a value (AutoFill's identities) //! password.reveal one login's payload, on an unlocked vault (reveal, copy, fill) //! password.add a login, its payload sealed v2 under the VMK //! password.change its plain columns; its payload resealed when it changes //! password.remove to the bin, as the table's own Delete //! password.generate a new password by the rule (length and classes as data) //! password.importCsv Apple Passwords' CSV export, each login sealed as add's //! password.save a site's login as AutoFill hands it: added, or its password changed //! password.mirror the logins the provider's keychain lacks or holds stale, opened //! password.used one login's last use, as the provider filled it //! password.new a login for a site with a new password by the rule (Plus's New password) //! ``` //! (`passkey.importCxf` lands a Credential Exchange export's passwords beside //! its passkeys, through [`land`].) //! //! **The rows are the object's `secret` table**, the one Cotton's Passwords //! draws, kept on this device in the store's `cotton_secrets` (the storage //! map), where `vault.*` keeps Cotton's. A row this family writes keeps its //! payload in `value_enc`, sealed by `cotton_core::keys::password_row` — the //! rule a passkey's private key is sealed by — under a key only the owner's //! devices hold, and writes no `hint` (the map keeps a hint on the device //! that wrote it, never on the object). A row the Worker sealed (`sealed`, //! `k1:` under its `VAULT_KEY`) or one still under the scheme before the //! vault is listed and left as it is: it cannot be revealed or resealed //! here, and says so (`not_sealed_here`); moving those rows is the //! coordinator's. //! //! **The writes are this device's**, through the one write every phone write //! takes (`write_rows`, the outbox, a `data` event naming the table), as //! `vault.create` writes; `value_enc` and `vmk_version` are readonly on the //! object's definition, so no person, token or connector names them. //! //! **No value reaches a log line, a refusal or a `data` event.** A payload is //! answered by `password.reveal` to its one caller; a generated password by //! `password.generate`; nothing else answers one. The VMK is the five-minute //! unlock's, or lent for the call (`privateKey`), as `passkey.*` takes it. use serde_json::{json, Map, Value}; use cotton_core::keys::password_import::{self, ImportedPassword}; use cotton_core::keys::password_row::{self, VALUE_ENC}; use cotton_core::keys::password_rule::PasswordRule; use cotton_core::vault::payload::SecretPayload; use cotton_core::vault::Vmk; use cotton_tools::mcp::dispatch::Ctx; use cotton_tools::mcp::handlers::common::{insert_row, update_row}; use crate::handle::CottonHandle; use crate::methods::MethodError; use crate::phone::passkeys::with_vmk; use crate::shell::client::ClientController; /// The store's table a password is a row of: the object's `secret`. pub const SECRETS: &str = "cotton_secrets"; /// Every method this family answers. pub const METHODS: [&str; 11] = [ "password.add", "password.change", "password.generate", "password.importCsv", "password.list", "password.mirror", "password.new", "password.remove", "password.reveal", "password.save", "password.used", ]; /// The columns a list names: never `value_enc`, `sealed` or `hint`. const LISTED: &str = "id, name, site, username, last_used_at, (value_enc IS NOT NULL AND value_enc LIKE 'v2:%') AS opens"; const SAVED_BEFORE_KEYS: &str = "This password was saved before your vault sealed passwords on your devices. It opens once it is moved."; /// `password.*` over this device's own database. pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result { over(&handle.client(), method, request) } /// The same, over a named controller (the suite's phone). pub fn over(client: &ClientController, method: &str, request: &Value) -> Result { match method { "password.list" => list(client, request), "password.reveal" => reveal(client, request), "password.add" => add(client, request), "password.change" => change(client, request), "password.remove" => remove(client, request), "password.generate" => generate(request), "password.importCsv" => import_csv(client, request), "password.save" => save(client, request), "password.mirror" => mirror(client, request), "password.used" => used(client, request), "password.new" => new(client, request), other => Err(MethodError::new("unknown_method", format!("`{other}` is not a password method"))), } } fn bad(field: &str, shape: &str) -> MethodError { MethodError::new("bad_request", format!("`{field}` is {shape}")) } fn text<'a>(request: &'a Value, field: &str) -> Result<&'a str, MethodError> { request.get(field).and_then(Value::as_str).filter(|value| !value.trim().is_empty()).ok_or_else(|| bad(field, "required text")) } fn optional<'a>(request: &'a Value, field: &str) -> Option<&'a str> { request.get(field).and_then(Value::as_str) } fn refused(reason: String) -> MethodError { MethodError::new("write_refused", reason) } /// A row of `cotton_secrets` not in the bin, by id, as the columns asked. pub(crate) fn row_of(ctx: &Ctx<'_>, id: &str, columns: &str) -> Result>, String> { Ok(live(ctx, columns, "id = ?", vec![rusqlite::types::Value::Text(id.to_string())])?.into_iter().next()) } /// The rows of `cotton_secrets` not in the bin matching `condition`. pub(crate) fn live(ctx: &Ctx<'_>, columns: &str, condition: &str, args: Vec) -> Result>, String> { let mut all = vec![rusqlite::types::Value::Text(ctx.workspace_id.to_string())]; all.extend(args); let found = ctx .db() .all(&format!("SELECT {columns} FROM {SECRETS} WHERE workspace_id = ? AND trashed_at IS NULL AND {condition}"), &all) .map_err(|error| error.to_string())?; Ok(found.iter().map(json_row).collect()) } /// Whether a row's value is sealed on the owner's devices (v2): what this /// family opens. Anything else is the Worker's, or no value at all. pub(crate) fn sealed_here(row: &Map) -> bool { row.get(VALUE_ENC).and_then(Value::as_str).is_some_and(|value| !cotton_core::vault::is_legacy(value)) } pub(crate) fn json_row(row: &cotton_store::driver::Row) -> Map { use rusqlite::types::Value as Sql; row.columns() .iter() .map(|(name, value)| { let value = match value { Sql::Null | Sql::Blob(_) => Value::Null, Sql::Integer(n) => Value::from(*n), Sql::Real(x) => Value::from(*x), Sql::Text(text) => Value::from(text.clone()), }; (name.clone(), value) }) .collect() } /// `password.list {q?}` — every login not in the bin: id, name, site, user /// name, last used, and `opens` (sealed on the owner's devices, so this /// phone can reveal it). Never a value. What AutoFill's identity store takes. fn list(client: &ClientController, request: &Value) -> Result { let query = optional(request, "q").map(str::trim).filter(|q| !q.is_empty()).map(|q| format!("%{}%", q.to_lowercase())); let answer = client .with_file(|replica| { let mut args = vec![rusqlite::types::Value::Text(replica.workspace_id.to_string())]; let mut condition = String::new(); if let Some(query) = &query { condition = " AND (lower(name) LIKE ? OR lower(coalesce(site, '')) LIKE ? OR lower(coalesce(username, '')) LIKE ?)".to_string(); args.extend(std::iter::repeat_n(rusqlite::types::Value::Text(query.clone()), 3)); } let found = replica .driver .all( &format!( "SELECT {LISTED} FROM {SECRETS} WHERE workspace_id = ? AND trashed_at IS NULL AND kind = 'login'{condition} ORDER BY lower(coalesce(site, name)), lower(name), id" ), &args, ) .map_err(|error| error.to_string())?; Ok(found.iter().map(json_row).collect::>()) }) .map_err(|reason| MethodError::new("unreadable", reason))?; let passwords: Vec = answer .into_iter() .map(|mut row| { let opens = row.get("opens").and_then(Value::as_i64).unwrap_or(0) == 1; row.insert("opens".to_string(), json!(opens)); Value::Object(row) }) .collect(); Ok(json!({ "passwords": passwords })) } /// `password.reveal {id, privateKey?}` — one password's payload, opened /// under the VMK at the row's own version, and `last_used_at` stamped; /// `copies` is the value Copy puts on the clipboard (the kind's primary /// field: a login's password, an API key's key), so no shell picks one. A /// locked vault refuses `vault_locked`; a row the Worker sealed refuses /// `not_sealed_here`; a row that does not open says why, never its value. fn reveal(client: &ClientController, request: &Value) -> Result { let id = text(request, "id")?.to_string(); let now = client.now_iso(); with_vmk(client, request, |vmk, _| { let answer = client .write_rows("password.reveal", &mut |ctx| { let Some(row) = row_of(ctx, &id, "id, name, site, username, value_enc, vmk_version")? else { return Ok(json!({ "found": false })); }; if !sealed_here(&row) { return Ok(json!({ "found": true, "sealed_here": false })); } let payload = match password_row::open(&row, &id, vmk) { Ok(payload) => payload, Err(error) => return Ok(json!({ "found": true, "sealed_here": true, "refused": error.to_string() })), }; let mut patch = Map::new(); patch.insert("last_used_at".to_string(), json!(now)); update_row(ctx, SECRETS, &id, patch).map_err(|failure| failure.to_string())?; let copies = payload.primary_field().to_string(); Ok(json!({ "found": true, "sealed_here": true, "id": id, "name": row["name"], "site": row["site"], "username": row["username"], "payload": payload, "copies": copies })) }) .map_err(refused)?; let answer = crate::authoring::own_answer(answer); if answer["found"] == json!(false) { return Err(MethodError::new("password_not_found", "No password with this id is kept here.")); } if answer["sealed_here"] == json!(false) { return Err(MethodError::new("not_sealed_here", SAVED_BEFORE_KEYS)); } if let Some(reason) = answer["refused"].as_str() { return Err(MethodError::new("does_not_open", reason.to_string())); } Ok(json!({ "id": answer["id"], "name": answer["name"], "site": answer["site"], "username": answer["username"], "payload": answer["payload"], "copies": answer["copies"] })) }) } /// One login landed as a `secret` row: its plain columns made, then its /// payload sealed v2 under the VMK and bound to the new row's id. A login /// with the same site and user name already kept here is not made again: /// `Ok(None)`. pub(crate) fn land(ctx: &mut Ctx<'_>, vmk: &Vmk, version: u32, login: &ImportedPassword, created_at: Option<&str>) -> Result, String> { // A login already kept for the same site and user name is held; a note never is. if matches!(login.payload, SecretPayload::Login { .. }) { let same = live( ctx, "id", "kind = 'login' AND trashed_at IS NULL AND coalesce(site, '') = ? AND coalesce(username, '') = ?", vec![ rusqlite::types::Value::Text(login.site.clone().unwrap_or_default()), rusqlite::types::Value::Text(login.username.clone().unwrap_or_default()), ], )?; if !same.is_empty() { return Ok(None); } } let id = ctx.new_uuid(); let sealed = password_row::seal(&login.payload, vmk, &id, version).map_err(|error| error.to_string())?; let mut row = sealed.columns(); row.insert("kind".to_string(), json!(login.payload.kind().as_str())); row.insert("name".to_string(), json!(login.name)); row.insert("site".to_string(), json!(login.site)); row.insert("username".to_string(), json!(login.username)); // Written out loud: the table carries no defaults for these. for column in ["service", "hint", "last_used_at", "expires_at", "trashed_at"] { row.insert(column.to_string(), Value::Null); } if let Some(at) = created_at { row.insert("created_at".to_string(), json!(at)); } insert_row(ctx, SECRETS, &id, row).map_err(|failure| failure.to_string())?; Ok(Some(id)) } /// `password.add {site, username?, password, name?, notes?, totp?, /// privateKey?}` — a login, its payload sealed v2 under the VMK and bound to /// the new row; the site is the host of the address given. A login with the /// same site and user name already kept here refuses `password_held`. fn add(client: &ClientController, request: &Value) -> Result { let site = text(request, "site")?; let password = request.get("password").and_then(Value::as_str).filter(|value| !value.is_empty()).ok_or_else(|| bad("password", "required text"))?; let login = password_import::login( optional(request, "name").unwrap_or(""), Some(site), optional(request, "username"), password, optional(request, "notes"), optional(request, "totp"), None, ) .map_err(|reason| MethodError::new("bad_request", format!("This login cannot be kept: {reason}.")))?; with_vmk(client, request, |vmk, version| { let answer = client .write_rows("password.add", &mut |ctx| Ok(json!({ "id": land(ctx, vmk, version, &login, None)? }))) .map_err(refused)?; let answer = crate::authoring::own_answer(answer); if answer["id"].is_null() { return Err(MethodError::new("password_held", "A login for this site and user name is already kept here.")); } Ok(json!({ "id": answer["id"] })) }) } /// `password.change {id, name?, site?, username?, password?, notes?, totp?, /// privateKey?}` — the plain columns as given; when the password, notes or /// code change, the payload is opened, changed and sealed again at the /// vault's current version (the vault must be open, and the row sealed /// here). `notes` or `totp` as null clears it. fn change(client: &ClientController, request: &Value) -> Result { let id = text(request, "id")?.to_string(); let mut plain = Map::new(); if let Some(name) = optional(request, "name") { if !cotton_core::vault::columns::fits(name.trim(), cotton_core::vault::columns::NAME_MAX) { return Err(bad("name", "1 to 120 characters")); } plain.insert("name".to_string(), json!(name.trim())); } if let Some(site) = optional(request, "site") { let site = password_import::site_of(site).ok_or_else(|| bad("site", "an address"))?; if !cotton_core::vault::columns::fits(&site, cotton_core::vault::columns::SITE_MAX) { return Err(bad("site", "at most 255 characters")); } plain.insert("site".to_string(), json!(site)); } if let Some(username) = request.get("username") { let username = username.as_str().map(str::trim).filter(|value| !value.is_empty()); if username.is_some_and(|value| !cotton_core::vault::columns::fits(value, cotton_core::vault::columns::USERNAME_MAX)) { return Err(bad("username", "at most 255 characters")); } plain.insert("username".to_string(), json!(username)); } let password = request.get("password").and_then(Value::as_str); if password == Some("") { return Err(bad("password", "not empty")); } let secret_changes = password.is_some() || request.get("notes").is_some() || request.get("totp").is_some(); let write = |vmk: Option<(&Vmk, u32)>| -> Result { let answer = client .write_rows("password.change", &mut |ctx| { let Some(row) = row_of(ctx, &id, "id, kind, value_enc, vmk_version")? else { return Ok(json!({ "found": false })); }; let mut patch = plain.clone(); if let Some((vmk, version)) = vmk { if !sealed_here(&row) { return Ok(json!({ "found": true, "sealed_here": false })); } let opened = match password_row::open(&row, &id, vmk) { Ok(payload) => payload, Err(error) => return Ok(json!({ "found": true, "sealed_here": true, "refused": error.to_string() })), }; let SecretPayload::Login { password: held, notes, totp, urls } = opened else { return Ok(json!({ "found": true, "sealed_here": true, "refused": "only a login's password changes here" })); }; let field = |key: &str, held: Option| match request.get(key) { None => held, Some(value) => value.as_str().map(str::trim).filter(|value| !value.is_empty()).map(str::to_string), }; let next = SecretPayload::Login { password: password.map(str::to_string).unwrap_or(held), notes: field("notes", notes), totp: field("totp", totp), urls: field("urls", urls), }; let sealed = password_row::seal(&next, vmk, &id, version).map_err(|error| error.to_string())?; patch.extend(sealed.columns()); } if !patch.is_empty() { update_row(ctx, SECRETS, &id, patch).map_err(|failure| failure.to_string())?; } Ok(json!({ "found": true, "sealed_here": true, "id": id })) }) .map_err(refused)?; let answer = crate::authoring::own_answer(answer); if answer["found"] == json!(false) { return Err(MethodError::new("password_not_found", "No password with this id is kept here.")); } if answer["sealed_here"] == json!(false) { return Err(MethodError::new("not_sealed_here", SAVED_BEFORE_KEYS)); } if let Some(reason) = answer["refused"].as_str() { return Err(MethodError::new("does_not_open", reason.to_string())); } Ok(json!({ "id": answer["id"] })) }; if secret_changes { with_vmk(client, request, |vmk, version| write(Some((vmk, version)))) } else { write(None) } } /// `password.remove {id}` — the row to the bin, through the one write every /// door shares (`secrets::set_trashed`, as `vault.trash`); restoring it from /// the bin brings it back. No vault needed. fn remove(client: &ClientController, request: &Value) -> Result { let id = text(request, "id")?.to_string(); let answer = client .write_rows("password.remove", &mut |ctx| { if row_of(ctx, &id, "id")?.is_none() { return Ok(json!({ "found": false })); } cotton_tools::mcp::handlers::secrets::set_trashed(ctx, &id, true).map_err(|failure| failure.to_string())?; Ok(json!({ "found": true, "id": id })) }) .map_err(refused)?; let answer = crate::authoring::own_answer(answer); if answer["found"] == json!(false) { return Err(MethodError::new("password_not_found", "No password with this id is kept here.")); } Ok(json!({ "id": answer["id"], "removed": true })) } /// `password.generate {rule?}` — a new password by the rule: the shipped one /// (`cotton_core::keys::password_rule`, length and classes as data), or the /// rule given, checked. Answers the password and the rule it was made by. fn generate(request: &Value) -> Result { let rule = match request.get("rule") { None | Some(Value::Null) => PasswordRule::shipped(), Some(value) => PasswordRule::from_value(value).map_err(|error| MethodError::new("bad_rule", error.to_string()))?, }; let made = rule.generate().map_err(|error| MethodError::new("bad_rule", error.to_string()))?; Ok(json!({ "password": made.as_str(), "rule": rule })) } /// `password.importCsv {csv, privateKey?}` — a password manager's CSV export /// (Apple Passwords, 1Password, Bitwarden, Chrome, Dashlane, LastPass, /// Firefox; the header says which), each login landed as `password.add` /// lands one and each secure note as a note. A login already kept here /// (same site and user name) is skipped and said; a locked vault refuses the /// whole file before anything is written; a file that is no export refuses /// in its words. Answers `{imported: [{id, site, username}], skipped: [{title, /// reason}], unnamed}` — `unnamed` the header columns the reader does not name. fn import_csv(client: &ClientController, request: &Value) -> Result { let csv = text(request, "csv")?; let read = password_import::read_csv(csv).map_err(|error| MethodError::new("bad_export", error.to_string()))?; let mut skipped: Vec = read.skipped.iter().map(|skip| json!({ "title": skip.title, "reason": skip.reason })).collect(); let answer = with_vmk(client, request, |vmk, version| { let answer = client .write_rows("password.importCsv", &mut |ctx| landed(ctx, vmk, version, &read.passwords, &[])) .map_err(refused)?; Ok(crate::authoring::own_answer(answer)) })?; if let Some(held) = answer["held"].as_array() { skipped.extend(held.iter().cloned()); } let said = csv_said(answer["imported"].as_array().map_or(0, Vec::len), &skipped); Ok(json!({ "format": read.format, "imported": answer["imported"], "skipped": skipped, "unnamed": read.unnamed, "said": said })) } /// What an import says, the same on every phone: how many came in and how /// many were skipped, then each skip and why (`passwords` lines). fn csv_said(imported: usize, skipped: &[Value]) -> String { let say = |name: &str, fill: &[(&str, &str)]| { cotton_core::rules::shell_lines::LineSet::shipped("passwords").and_then(|lines| lines.say(name, fill)).unwrap_or_else(|| name.to_string()) }; let (p, m) = (imported.to_string(), skipped.len().to_string()); let mut said = say(if imported == 1 { "passkeys.passwords_imported_one" } else { "passkeys.passwords_imported_many" }, &[("p", &p), ("m", &m)]); for skip in skipped { let title = skip["title"].as_str().filter(|t| !t.is_empty()).map(str::to_string).unwrap_or_else(|| say("passkeys.import_untitled", &[])); said.push('\n'); said.push_str(&say("passkeys.import_skip", &[("title", &title), ("reason", skip["reason"].as_str().unwrap_or_default())])); } said } /// Land each login, in one write: `{imported: [{id, site, username}], held: /// [{title, reason}]}`. `created_at` is each login's own stamp, when it has one. pub(crate) fn landed(ctx: &mut Ctx<'_>, vmk: &Vmk, version: u32, logins: &[ImportedPassword], created_at: &[Option]) -> Result { let mut imported = Vec::new(); let mut held = Vec::new(); for (index, login) in logins.iter().enumerate() { let at = created_at.get(index).and_then(Option::as_deref); match land(ctx, vmk, version, login, at)? { Some(id) => imported.push(json!({ "id": id, "site": login.site, "username": login.username })), None => held.push(json!({ "title": login.name, "reason": "this login is already kept here" })), } } Ok(json!({ "imported": imported, "held": held })) } /// `password.save {site, username?, password, name?, privateKey?}` — a login /// as Cotton Keys' provider hands it from a site's form (iOS 26.2's save /// request): a new site and user name is added as `password.add` adds one; a /// login already kept for them, sealed here, keeps its notes and code and /// takes the new password, sealed again. A kept login the Worker sealed is /// left as it is and refuses `not_sealed_here`. Answers `{id, made}`. fn save(client: &ClientController, request: &Value) -> Result { let site = text(request, "site")?; let password = request.get("password").and_then(Value::as_str).filter(|value| !value.is_empty()).ok_or_else(|| bad("password", "required text"))?; let login = password_import::login(optional(request, "name").unwrap_or(""), Some(site), optional(request, "username"), password, None, None, None) .map_err(|reason| MethodError::new("bad_request", format!("This login cannot be kept: {reason}.")))?; with_vmk(client, request, |vmk, version| { let answer = client .write_rows("password.save", &mut |ctx| { let same = live( ctx, "id, value_enc, vmk_version", "kind = 'login' AND coalesce(site, '') = ? AND coalesce(username, '') = ?", vec![ rusqlite::types::Value::Text(login.site.clone().unwrap_or_default()), rusqlite::types::Value::Text(login.username.clone().unwrap_or_default()), ], )?; let Some(row) = same.into_iter().next() else { return Ok(json!({ "id": land(ctx, vmk, version, &login, None)?, "made": true })); }; let id = row.get("id").and_then(Value::as_str).unwrap_or_default().to_string(); if !sealed_here(&row) { return Ok(json!({ "sealed_here": false })); } let (notes, totp, urls) = match password_row::open(&row, &id, vmk) { Ok(SecretPayload::Login { notes, totp, urls, .. }) => (notes, totp, urls), Ok(_) => return Ok(json!({ "refused": "only a login's password changes here" })), Err(error) => return Ok(json!({ "refused": error.to_string() })), }; let next = SecretPayload::Login { password: password.to_string(), notes, totp, urls }; let sealed = password_row::seal(&next, vmk, &id, version).map_err(|error| error.to_string())?; update_row(ctx, SECRETS, &id, sealed.columns()).map_err(|failure| failure.to_string())?; Ok(json!({ "id": id, "made": false })) }) .map_err(refused)?; let answer = crate::authoring::own_answer(answer); if answer["sealed_here"] == json!(false) { return Err(MethodError::new("not_sealed_here", SAVED_BEFORE_KEYS)); } if let Some(reason) = answer["refused"].as_str() { return Err(MethodError::new("does_not_open", reason.to_string())); } Ok(json!({ "id": answer["id"], "made": answer["made"] })) }) } /// What a mirrored login is held at: its site, user name, name and sealed /// text, hashed. A change to any of them (a reseal makes new sealed text) /// makes a new stamp; a use does not. fn stamp(row: &Map) -> String { use sha2::{Digest, Sha256}; let mut hash = Sha256::new(); for column in ["site", "username", "name", VALUE_ENC] { hash.update(row.get(column).and_then(Value::as_str).unwrap_or_default().as_bytes()); hash.update([0u8]); } hex::encode(&hash.finalize()[..12]) } /// `password.mirror {held: {id: stamp}, privateKey?}` — what Cotton Keys' /// provider fills from: the shared keychain group keeps each login sealed /// here that has a site, opened, under the stamp this answers. `held` is what /// the keychain keeps now. Answers `passwords` — each login it lacks or holds /// at another stamp, opened: `{id, site, username, name, password, stamp}` — /// and `gone`, the held ids that are no longer a live login sealed here (to /// leave the keychain). The vault is opened only when something must be: /// locked, `gone` is still answered, with no passwords and `locked: true`. A /// login that does not open is named in `refused` by id, never by value. fn mirror(client: &ClientController, request: &Value) -> Result { let held = match request.get("held") { None | Some(Value::Null) => Map::new(), Some(Value::Object(held)) => held.clone(), Some(_) => return Err(bad("held", "a map of id to stamp")), }; let rows: Vec> = client .with_file(|replica| { let found = replica .driver .all( &format!( "SELECT id, name, site, username, value_enc, vmk_version FROM {SECRETS} WHERE workspace_id = ? AND trashed_at IS NULL AND kind = 'login' AND site IS NOT NULL ORDER BY id" ), &[rusqlite::types::Value::Text(replica.workspace_id.to_string())], ) .map_err(|error| error.to_string())?; Ok(found.iter().map(json_row).filter(sealed_here).collect()) }) .map_err(|reason| MethodError::new("unreadable", reason))?; let live_ids: std::collections::BTreeSet<&str> = rows.iter().filter_map(|row| row.get("id").and_then(Value::as_str)).collect(); let gone: Vec<&String> = held.keys().filter(|id| !live_ids.contains(id.as_str())).collect(); let needed: Vec<&Map> = rows .iter() .filter(|row| { let id = row.get("id").and_then(Value::as_str).unwrap_or_default(); held.get(id).and_then(Value::as_str) != Some(stamp(row).as_str()) }) .collect(); if needed.is_empty() { return Ok(json!({ "passwords": [], "gone": gone, "refused": [], "locked": false })); } let opened = with_vmk(client, request, |vmk, _| { let mut passwords = Vec::new(); let mut refused = Vec::new(); for row in &needed { let id = row.get("id").and_then(Value::as_str).unwrap_or_default(); match password_row::open(row, id, vmk) { Ok(SecretPayload::Login { password, .. }) => passwords.push(json!({ "id": id, "site": row["site"], "username": row["username"], "name": row["name"], "password": password, "stamp": stamp(row), })), Ok(_) => refused.push(json!({ "id": id, "reason": "it is not a login" })), Err(error) => refused.push(json!({ "id": id, "reason": error.to_string() })), } } Ok((passwords, refused)) }); match opened { Ok((passwords, refused)) => Ok(json!({ "passwords": passwords, "gone": gone, "refused": refused, "locked": false })), Err(error) if error.code == "vault_locked" => Ok(json!({ "passwords": [], "gone": gone, "refused": [], "locked": true })), Err(error) => Err(error), } } /// The device method a `secret` Plus door's act names (`create.doors[].act`, /// whose name is a plain id): the deck's typed words run here, on this /// device, never as an object act on the Worker (`shell.input`'s commit). pub fn door_method(act: &str) -> Option<&'static str> { match act { "password_new" => Some("password.new"), _ => None, } } /// `password.new {site, username?, privateKey?}` — Plus's New password: a /// login for the site typed, its password made by the shipped rule /// (`password.generate`) and sealed as `password.add` seals one. Answers /// `{id}` (the deck stands on it, where Copy takes the new password to the /// site's sign-up) — never the password. A login already kept for the site /// and user name refuses `password_held`. fn new(client: &ClientController, request: &Value) -> Result { let made = PasswordRule::shipped().generate().map_err(|error| MethodError::new("bad_rule", error.to_string()))?; let mut asked = request.clone(); asked["password"] = json!(made.as_str()); add(client, &asked) } /// `password.used {id}` — the provider filled this login: its last use is /// stamped, as a reveal stamps it. No vault needed; a login gone since is /// `password_not_found`. fn used(client: &ClientController, request: &Value) -> Result { let id = text(request, "id")?.to_string(); let at = optional(request, "usedAt").map(str::to_string).unwrap_or_else(|| client.now_iso()); let answer = client .write_rows("password.used", &mut |ctx| { if row_of(ctx, &id, "id")?.is_none() { return Ok(json!({ "found": false })); } let mut patch = Map::new(); patch.insert("last_used_at".to_string(), json!(at)); update_row(ctx, SECRETS, &id, patch).map_err(|failure| failure.to_string())?; Ok(json!({ "found": true, "id": id })) }) .map_err(refused)?; let answer = crate::authoring::own_answer(answer); if answer["found"] == json!(false) { return Err(MethodError::new("password_not_found", "No password with this id is kept here.")); } Ok(json!({ "id": answer["id"], "last_used_at": at })) } #[cfg(test)] #[path = "passwords_tests.rs"] pub(crate) mod tests; /// The Worker's route a password saved over MCP moves under the vault key by (business.ts `secretsToRewrap`). const REWRAP_PATH: &str = "/v1/secret/rewrap"; /// After a pass, while the vault is open on this phone (OPEN-TABLES.md §3): every password the Worker still seals /// under its own `VAULT_KEY` (`k1:`, one saved over MCP) is asked for, opened to this device alone, sealed here under /// the vault key as every password this family writes ([`password_row::seal`]), and handed back, the Worker then /// letting its old value go. Resumable a batch at a time; a locked vault, a signed-out phone or a database that is /// not personal asks nothing. Answers how many moved. A payload that is not a password's shape is left where it is. pub(crate) fn rewrap(client: &ClientController) -> Result { if !client.signed_in() || client.require_personal().is_err() { return Ok(0); } let Some(door) = client.object_door() else { return Ok(0) }; let Ok(vault) = client.vault() else { return Ok(0) }; // Nothing is asked of the Worker while the vault is shut: the values would have nowhere to go. if vault.with_vmk(client.now(), |_, _| ()).is_none() { return Ok(0); } let mut moved = 0; loop { let asked = door.send("GET", REWRAP_PATH, None)?; let rows = asked["rows"].as_array().cloned().unwrap_or_default(); if rows.is_empty() { return Ok(moved); } // A value the object sealed to the arrival key (keys DECISIONS.md S3, `a2:`) comes as `arrival`: opened here // with the DK, which the object never holds. With no DK held, those wait for a pass that holds it. let database = client.current_database().ok(); let dk = database.as_deref().and_then(|database| cotton_client::seal::DataKeyStore::data_key(client.data_keys().as_ref(), database).ok().flatten()); let opened = |row: &Value| -> Option { if let Some(payload) = row["payload"].as_str() { return Some(payload.to_string()); } let (Some(dk), Some(database)) = (dk.as_ref(), database.as_deref()) else { return None }; cotton_core::seal::arrival::open_arrival_value(dk, database, row["id"].as_str()?, row["arrival"].as_str()?).ok() }; let sealed = vault.with_vmk(client.now(), |vmk, version| { rows.iter() .filter_map(|row| { let (id, row_version) = (row["id"].as_str()?, row["version"].as_i64()?); let payload: SecretPayload = serde_json::from_str(&opened(row)?).ok()?; let sealed = password_row::seal(&payload, vmk, id, version).ok()?; Some(json!({ "id": id, "version": row_version, VALUE_ENC: sealed.value_enc, "vmk_version": sealed.vmk_version })) }) .collect::>() }); // The vault shut while the batch was read: what is left waits for the next pass. let Some(sealed) = sealed else { return Ok(moved) }; if sealed.is_empty() { return Ok(moved); } let answer = door.send("POST", REWRAP_PATH, Some(&json!({ "rows": sealed })))?; let now_moved = answer["moved"].as_u64().unwrap_or(0) as usize; moved += now_moved; // Nothing taken (each row changed meanwhile, or none of a batch is a password's shape): the next pass asks again. if now_moved == 0 { return Ok(moved); } } }