Cotton code
605 lines · 30.9 KB · RustRaw
//! `passkey.*` — what Cotton Keys' iOS credential provider hands the app.//!//! ```text//! provider extension (CryptoKit, no core)           the app (this module)//!   registers → keychain item + mailbox entry  ──▶  passkey.register  a `passkey` row, private_key_enc sealed v2//!   signs     → mailbox entry                  ──▶  passkey.used      uses + 1, last_used_at//!                                                   passkey.identities every row, for ASCredentialIdentityStore;//!                                                                      with {rpId, allow?} the ones a sign-in is offered//!                                                   passkey.mirror     the opened scalar of rows this phone's//!                                                                      keychain lacks (made on another device)//! Android's credential provider (in the app's own process, so no mailbox)://!   creates   → passkey.create   the key made HERE, sealed v2 under the VMK, a row; answers the attestation//!   signs     → passkey.sign     the row opened HERE, signs, uses + 1; answers the assertion//!   (the private half never leaves the core: no scalar crosses to Kotlin, the Keystore or a log)//! Passwords app's Credential Exchange (CXF 1.0 JSON)──▶  passkey.importCxf  each passkey a row, sealed as register's,//!                                                                      and each password a secret row (password.*)//! ```//!//! **The app's own producer path.** `private_key_enc` and `vmk_version` are//! readonly: no person, token or connector names them. The rows here are//! made by the trusted producer path (`create_produced_record` ///! `update_produced_record`, which the songs and books already take and MCP//! dispatch never reaches), so the readonly rule stands as written: an app's//! own producer writes what it produces, and nothing else does.//!//! **The sign count is never written past 0**, here or on the Mac//! (`cotton_mac::vault_passkey`): several devices sign for one row, and a//! counter each kept would diverge. `uses` counts instead.//!//! **Key material.** `privateScalar` (register) arrives from the shared//! keychain for this one call, is checked against the row's public key,//! sealed under the VMK and dropped. `passkey.mirror` answers opened scalars to//! its one caller, which puts each in the shared keychain group and keeps//! nothing else; it is in no tool table and no log or `data` event carries//! one. The VMK is the five-minute unlock's, or lent for the call//! (`privateKey`, this device's vault key after the presence prompt) as//! `vault.approveDevice` takes it.use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use serde_json::{json, Map, Value};use zeroize::Zeroizing;use cotton_core::keys::cxf;use cotton_core::keys::passkey::{from_row, Algorithm, Passkey};use cotton_core::keys::passkey_row;use cotton_core::vault::Vmk;use cotton_tools::mcp::dispatch::Ctx;use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::phone::songs::{made, patched};use crate::phone::vault;use crate::shell::client::ClientController;/// The table a passkey is a row of.pub const PASSKEY: &str = "passkey";/// Every method this family answers.pub const METHODS: [&str; 7] =    ["passkey.create", "passkey.identities", "passkey.importCxf", "passkey.mirror", "passkey.register", "passkey.sign", "passkey.used"];/// The DER head of a P-256 SubjectPublicKeyInfo (RFC 5480): id-ecPublicKey,/// prime256v1, then the 65-byte uncompressed point as a BIT STRING. What/// WebAuthn's `getPublicKey()` answers and Android's response JSON carries.const P256_SPKI_HEAD: [u8; 26] = [    0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01,    0x07, 0x03, 0x42, 0x00,];/// The columns an identity names: never a key.const IDENTITY_COLUMNS: &str = "id, rp_id, rp_name, user_name, user_handle, credential_id";/// `passkey.*` over this device's own database.pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    over(&handle.client(), method, request)}/// The same, over a named controller (the suite's phone).pub fn over(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "passkey.register" => register(client, request),        "passkey.used" => used(client, request),        "passkey.identities" => identities(client, request),        "passkey.mirror" => mirror(client, request),        "passkey.importCxf" => import_cxf(client, request),        "passkey.create" => create(client, request),        "passkey.sign" => sign(client, request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a passkey 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(request: &Value, field: &str) -> Option<Value> {    request.get(field).and_then(Value::as_str).filter(|value| !value.trim().is_empty()).map(Value::from)}/// The scalar the extension made, decoded for one call and wiped on drop./// Never echoed: a refusal names the shape, not what arrived.fn scalar_arg(request: &Value) -> Result<Zeroizing<Vec<u8>>, MethodError> {    let asked = request.get("privateScalar").and_then(Value::as_str).unwrap_or_default();    match URL_SAFE_NO_PAD.decode(asked) {        Ok(bytes) if bytes.len() == 32 => Ok(Zeroizing::new(bytes)),        _ => Err(bad("privateScalar", "32 bytes, base64url without padding")),    }}/// Run `work` with this database's VMK: lent for the call when the request/// carries this device's vault key, else the five-minute unlock's; a locked/// vault refuses as `vault_locked` and nothing is written.pub(crate) fn with_vmk<R>(    client: &ClientController,    request: &Value,    work: impl FnOnce(&Vmk, u32) -> Result<R, MethodError>,) -> Result<R, MethodError> {    if let Some(sentence) = client.write_refusal() {        return Err(MethodError::new(vault::REFUSED_DEVICE, sentence));    }    if request.get("privateKey").is_some_and(|key| !key.is_null()) {        let secret = vault::private_key_arg(request)?;        let (vmk, version) = vault::opened_vmk(client, &secret)?;        return work(&vmk, version);    }    let door = client.vault().map_err(|reason| MethodError::new("unreadable", reason))?;    door.with_vmk(client.now(), |vmk, version| work(vmk, version)).ok_or_else(vault::locked)?}/// The live row holding this credential id, as `(id, columns)`.fn row_of(ctx: &Ctx<'_>, credential_id: &str, columns: &str) -> Result<Option<(String, Map<String, Value>)>, String> {    if !crate::phone::songs::holds_table(ctx, PASSKEY)? {        return Err("this database holds no passkey table: the keys kit has not reached this phone".to_string());    }    let rows = crate::phone::songs::rows_where(ctx, PASSKEY, columns, "credential_id = ?", &[rusqlite::types::Value::Text(credential_id.to_string())])?;    Ok(rows.into_iter().next().map(|row| (row.get("id").and_then(Value::as_str).unwrap_or_default().to_string(), row)))}/// `passkey.register {rp_id, rp_name?, user_name?, user_handle, credential_id,/// algorithm, public_key, created_at?, privateScalar, privateKey?}` — the/// passkey the provider made, as a row: its scalar held to `public_key`, then/// sealed v2 under the VMK and bound to the new row's id; `sign_count` 0,/// `uses` 0. Saying it twice for one credential id answers the row it made.fn register(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let rp_id = text(request, "rp_id")?.to_string();    let user_handle = text(request, "user_handle")?.to_string();    let credential_id = text(request, "credential_id")?.to_string();    let algorithm = text(request, "algorithm")?.to_string();    let public_key = text(request, "public_key")?.to_string();    let scalar = scalar_arg(request)?;    // The scalar must make this row's public key, or nothing is written.    let passkey = from_row(&rp_id, &user_handle, &credential_id, &algorithm, &public_key, 0, &scalar)        .map_err(|error| MethodError::new("bad_request", error.to_string()))?;    debug_assert_eq!(passkey.algorithm, Algorithm::Es256);    drop(scalar);    let mut data = Map::new();    for key in ["rp_id", "user_handle", "credential_id", "algorithm", "public_key"] {        data.insert(key.to_string(), request[key].clone());    }    for key in ["rp_name", "user_name", "transports"] {        if let Some(value) = optional(request, key) {            data.insert(key.to_string(), value);        }    }    data.insert("transports".to_string(), data.get("transports").cloned().unwrap_or_else(|| json!("internal, hybrid")));    data.insert("sign_count".to_string(), json!(0));    data.insert("uses".to_string(), json!(0));    let created_at = optional(request, "created_at");    with_vmk(client, request, |vmk, version| {        let answer = client            .write_rows("passkey.register", &mut |ctx| {                if let Some((id, _)) = row_of(ctx, &credential_id, "id")? {                    return Ok(json!({ "id": id, "made": false }));                }                let id = made(ctx, PASSKEY, data.clone())?;                let sealed = passkey_row::seal(&passkey, vmk, &id, version).map_err(|error| error.to_string())?;                let mut patch = Map::new();                patch.insert("private_key_enc".to_string(), json!(sealed.private_key_enc));                patch.insert("vmk_version".to_string(), json!(sealed.vmk_version));                if let Some(at) = &created_at {                    patch.insert("created_at".to_string(), at.clone());                }                patched(ctx, PASSKEY, &id, patch)?;                Ok(json!({ "id": id, "made": true }))            })            .map_err(|reason| MethodError::new("write_refused", reason))?;        Ok(crate::authoring::own_answer(answer))    })}/// `passkey.used {credential_id, used_at}` — one signature by the provider:/// `uses` + 1 and `last_used_at`; the sign count stays 0. A credential id with/// no row yet (its registration still waits for the vault) refuses as/// `passkey_not_found`, and the entry waits with it.fn used(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let credential_id = text(request, "credential_id")?.to_string();    let used_at = text(request, "used_at")?.to_string();    let answer = client.write_rows("passkey.used", &mut |ctx| {        let Some((id, row)) = row_of(ctx, &credential_id, "id, uses")? else {            return Ok(json!({ "found": false }));        };        let uses = row.get("uses").and_then(Value::as_f64).unwrap_or(0.0) as i64 + 1;        let mut patch = Map::new();        patch.insert("uses".to_string(), json!(uses));        patch.insert("last_used_at".to_string(), json!(used_at));        patched(ctx, PASSKEY, &id, patch)?;        Ok(json!({ "found": true, "id": id, "uses": uses }))    });    let answer = crate::authoring::own_answer(answer.map_err(|reason| MethodError::new("write_refused", reason))?);    if answer["found"] == json!(false) {        return Err(MethodError::new("passkey_not_found", "No passkey with this credential id is kept here yet."));    }    Ok(json!({ "id": answer["id"], "uses": answer["uses"] }))}/// The 32-byte client data hash the platform asked over, base64url.fn client_data_hash(request: &Value) -> Result<Vec<u8>, MethodError> {    let asked = request.get("clientDataHash").and_then(Value::as_str).unwrap_or_default();    match URL_SAFE_NO_PAD.decode(asked.trim_end_matches('=')) {        Ok(bytes) if bytes.len() == 32 => Ok(bytes),        _ => Err(bad("clientDataHash", "32 bytes, base64url")),    }}/// The SubjectPublicKeyInfo DER of a passkey's public half.fn spki(passkey: &Passkey) -> Vec<u8> {    let point = passkey.verifying_key().to_encoded_point(false);    let mut der = P256_SPKI_HEAD.to_vec();    der.extend_from_slice(point.as_bytes());    der}/// `passkey.create {rp_id, rp_name?, user_name?, user_handle, clientDataHash,/// exclude?: [credential_id], privateKey?}` — Android's provider registers a/// passkey: the key pair is made here, its private half sealed v2 under the/// VMK and bound to the new row (as `passkey.register` seals one), and the/// platform's answer comes back: `{id, credential_id, attestation_object,/// authenticator_data, public_key (SPKI DER), algorithm: -7, transports}`,/// every byte string base64url. No private byte is answered. A credential in/// `exclude` already kept here refuses `already_kept` (WebAuthn's/// InvalidStateError) and nothing is made; a locked vault refuses/// `vault_locked` before a key is made.fn create(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let rp_id = text(request, "rp_id")?.to_string();    let user_handle = text(request, "user_handle")?.to_string();    let hash = client_data_hash(request)?;    let exclude: Vec<String> = request        .get("exclude")        .and_then(Value::as_array)        .map(|ids| ids.iter().filter_map(Value::as_str).map(str::to_string).collect())        .unwrap_or_default();    if !exclude.is_empty() {        let kept = rows(client, "credential_id")?;        if kept.iter().any(|row| row.get("credential_id").and_then(Value::as_str).is_some_and(|id| exclude.iter().any(|one| one == id))) {            return Err(MethodError::new("already_kept", "A passkey for this account is already kept in Cotton Vault."));        }    }    let rp_name = optional(request, "rp_name");    let user_name = optional(request, "user_name");    with_vmk(client, request, |vmk, version| {        let passkey = cotton_core::keys::passkey::make(&rp_id, &user_handle, Algorithm::Es256)            .map_err(|error| MethodError::new("bad_request", error.to_string()))?;        let attestation = cotton_core::keys::passkey::attest(&passkey, &rp_id, &hash)            .map_err(|error| MethodError::new("bad_request", error.to_string()))?;        let mut data = Map::new();        data.insert("rp_id".to_string(), json!(rp_id));        data.insert("rp_name".to_string(), rp_name.clone().unwrap_or_else(|| json!(rp_id)));        if let Some(name) = &user_name {            data.insert("user_name".to_string(), name.clone());        }        data.insert("user_handle".to_string(), json!(user_handle));        data.insert("credential_id".to_string(), json!(passkey.credential_id));        data.insert("algorithm".to_string(), json!(passkey.algorithm.as_str()));        data.insert("public_key".to_string(), json!(passkey.public_key));        data.insert("transports".to_string(), json!("internal, hybrid"));        data.insert("sign_count".to_string(), json!(0));        data.insert("uses".to_string(), json!(0));        let answer = client            .write_rows("passkey.create", &mut |ctx| {                let id = made(ctx, PASSKEY, data.clone())?;                let sealed = passkey_row::seal(&passkey, vmk, &id, version).map_err(|error| error.to_string())?;                let mut patch = Map::new();                patch.insert("private_key_enc".to_string(), json!(sealed.private_key_enc));                patch.insert("vmk_version".to_string(), json!(sealed.vmk_version));                patched(ctx, PASSKEY, &id, patch)?;                Ok(json!({ "id": id }))            })            .map_err(|reason| MethodError::new("write_refused", reason))?;        let answer = crate::authoring::own_answer(answer);        Ok(json!({            "id": answer["id"],            "credential_id": passkey.credential_id,            "attestation_object": URL_SAFE_NO_PAD.encode(&attestation.attestation_object),            "authenticator_data": URL_SAFE_NO_PAD.encode(&attestation.authenticator_data),            "public_key": URL_SAFE_NO_PAD.encode(spki(&passkey)),            "algorithm": -7,            "transports": ["internal", "hybrid"],        }))    })}/// `passkey.sign {credential_id, rp_id, clientDataHash, used_at?, privateKey?}`/// — Android's provider signs in with a kept passkey: the row is opened here/// under the VMK, signs authenticatorData || clientDataHash at counter 0 (as/// every Cotton signer does), and counts a use (`uses` + 1, `last_used_at`)./// Answers `{credential_id, authenticator_data, signature, user_handle,/// user_name}`, never a key. No row refuses `passkey_not_found`; a row for/// another site refuses `bad_request`; a locked vault `vault_locked`.fn sign(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let credential_id = text(request, "credential_id")?.to_string();    let rp_id = text(request, "rp_id")?.to_string();    let hash = client_data_hash(request)?;    let used_at = optional(request, "used_at").and_then(|at| at.as_str().map(str::to_string)).unwrap_or_else(|| client.now_iso());    let found = rows(        client,        "id, rp_id, rp_name, user_name, user_handle, credential_id, algorithm, public_key, sign_count, private_key_enc, vmk_version, created_at",    )?    .into_iter()    .find(|row| row.get("credential_id").and_then(Value::as_str) == Some(credential_id.as_str()))    .ok_or_else(|| MethodError::new("passkey_not_found", "No passkey with this credential id is kept here."))?;    let id = found.get("id").and_then(Value::as_str).unwrap_or_default().to_string();    let assertion = with_vmk(client, request, |vmk, _| {        let passkey = passkey_row::open(&found, &id, vmk).map_err(|error| MethodError::new("does_not_open", error.to_string()))?;        cotton_core::keys::passkey::assert(&passkey, &rp_id, &hash, 0).map_err(|error| MethodError::new("bad_request", error.to_string()))    })?;    used(client, &json!({ "credential_id": credential_id, "used_at": used_at }))?;    Ok(json!({        "credential_id": credential_id,        "authenticator_data": URL_SAFE_NO_PAD.encode(&assertion.authenticator_data),        "signature": URL_SAFE_NO_PAD.encode(&assertion.signature),        "user_handle": assertion.user_handle,        "user_name": found.get("user_name").cloned().unwrap_or(Value::Null),    }))}/// One passkey of an export, as the row it lands as (no key in `data`).struct Landing {    title: String,    credential_id: String,    /// Stamped after the row is made, as register's is (the make stamps now).    created_at: String,    data: Map<String, Value>,    passkey: Passkey,}/// `passkey.importCxf {json, privateKey?}` — a Credential Exchange export/// (CXF 1.0, what the Passwords app hands over) read by `keys::cxf::read`, each/// passkey landed as `passkey.register` lands one: sealed v2 under the VMK and/// bound to its row, `sign_count` 0, `uses` 0, `created_at` the export's or/// now, `note` "Imported from <exporter>". A credential id already kept here/// is skipped and said. Each `basic-auth` credential lands as a login, sealed/// as `password.add` seals one (`crate::phone::passwords::landed`); a login/// with the same site and user name already kept is skipped and said. A/// locked vault refuses the whole export before anything is written; an/// export that does not read refuses in its words. Answers `{imported: [{id,/// rp_id, user_name}], passwords: [{id, site, username}], skipped: [{title,/// reason}], exporter, unnamed}` — `unnamed` the field names the spec does not/// name.fn import_cxf(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let json = text(request, "json")?;    let unnamed = cxf::unnamed_fields(json);    let export = cxf::read(json).map_err(|error| MethodError::new("bad_export", error.to_string()))?;    let exporter = if export.exporter.display_name.trim().is_empty() {        export.exporter.rp_id.clone()    } else {        export.exporter.display_name.clone()    };    let mut skipped: Vec<Value> =        export.skipped.iter().map(|skip| json!({ "title": skip.title, "reason": skip.reason })).collect();    let now = client.now_iso();    let logins = export.passwords;    let logins_made: Vec<Option<String>> = logins        .iter()        .map(|login| {            login                .created_at                .and_then(|at| i64::try_from(at).ok())                .and_then(|at| chrono::DateTime::from_timestamp(at, 0))                .map(|at| at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))        })        .collect();    let landings: Vec<Landing> = export        .passkeys        .into_iter()        .map(|one| {            let created_at = one                .created_at                .and_then(|at| i64::try_from(at).ok())                .and_then(|at| chrono::DateTime::from_timestamp(at, 0))                .map(|at| at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))                .unwrap_or_else(|| now.clone());            let note = match one.note.as_deref().map(str::trim).filter(|note| !note.is_empty()) {                Some(subtitle) => format!("Imported from {exporter}\n{subtitle}"),                None => format!("Imported from {exporter}"),            };            let passkey = one.passkey;            let mut data = Map::new();            data.insert("rp_id".to_string(), json!(passkey.rp_id));            data.insert("rp_name".to_string(), json!(one.rp_name));            data.insert("user_name".to_string(), json!(one.user_name));            data.insert("user_handle".to_string(), json!(passkey.user_handle));            data.insert("credential_id".to_string(), json!(passkey.credential_id));            data.insert("algorithm".to_string(), json!(passkey.algorithm.as_str()));            data.insert("public_key".to_string(), json!(passkey.public_key));            data.insert("transports".to_string(), json!("internal, hybrid"));            data.insert("sign_count".to_string(), json!(0));            data.insert("uses".to_string(), json!(0));            data.insert("note".to_string(), json!(note));            Landing { title: one.rp_name, credential_id: passkey.credential_id.clone(), created_at, data, passkey }        })        .collect();    let answer = with_vmk(client, request, |vmk, version| {        let answer = client            .write_rows("passkey.importCxf", &mut |ctx| {                let mut imported = Vec::new();                let mut held = Vec::new();                for landing in &landings {                    if row_of(ctx, &landing.credential_id, "id")?.is_some() {                        held.push(json!({ "title": landing.title, "reason": "this passkey is already kept here" }));                        continue;                    }                    let id = made(ctx, PASSKEY, landing.data.clone())?;                    let sealed = passkey_row::seal(&landing.passkey, vmk, &id, version).map_err(|error| error.to_string())?;                    let mut patch = Map::new();                    patch.insert("private_key_enc".to_string(), json!(sealed.private_key_enc));                    patch.insert("vmk_version".to_string(), json!(sealed.vmk_version));                    patch.insert("created_at".to_string(), json!(landing.created_at));                    patched(ctx, PASSKEY, &id, patch)?;                    imported.push(json!({ "id": id, "rp_id": landing.data["rp_id"], "user_name": landing.data["user_name"] }));                }                let passwords = if logins.is_empty() {                    json!({ "imported": [], "held": [] })                } else {                    crate::phone::passwords::landed(ctx, vmk, version, &logins, &logins_made)?                };                Ok(json!({ "imported": imported, "held": held, "passwords": passwords }))            })            .map_err(|reason| MethodError::new("write_refused", reason))?;        Ok(crate::authoring::own_answer(answer))    })?;    if let Some(held) = answer["held"].as_array() {        skipped.extend(held.iter().cloned());    }    if let Some(held) = answer["passwords"]["held"].as_array() {        skipped.extend(held.iter().cloned());    }    Ok(json!({ "imported": answer["imported"], "passwords": answer["passwords"]["imported"], "skipped": skipped, "exporter": exporter, "unnamed": unnamed }))}/// The live passkey rows, by the columns asked; none when the table has not/// reached this phone.fn rows(client: &ClientController, columns: &str) -> Result<Vec<Map<String, Value>>, MethodError> {    client        .with_file(|replica| {            let made = cotton_tools::mcp::handlers::tables::made_table(PASSKEY);            let held = replica                .driver                .get("SELECT 1 AS found FROM sqlite_master WHERE type = 'table' AND name = ?", &[rusqlite::types::Value::Text(made.clone())])                .map_err(|error| error.to_string())?                .is_some();            if !held {                return Ok(Vec::new());            }            let found = replica                .driver                .all(                    &format!("SELECT {columns} FROM {made} WHERE workspace_id = ? AND deleted_at IS NULL ORDER BY rp_id, id"),                    &[rusqlite::types::Value::Text(replica.workspace_id.to_string())],                )                .map_err(|error| error.to_string())?;            Ok(found                .iter()                .map(|row| {                    row.columns()                        .iter()                        .map(|(name, value)| {                            let value = match value {                                rusqlite::types::Value::Text(text) => Value::from(text.clone()),                                rusqlite::types::Value::Integer(n) => Value::from(*n),                                rusqlite::types::Value::Real(x) => Value::from(*x),                                _ => Value::Null,                            };                            (name.clone(), value)                        })                        .collect()                })                .collect())        })        .map_err(|reason| MethodError::new("unreadable", reason))}/// `passkey.identities {rpId?, allow?}` — every kept passkey as the/// credential identity store takes it: site, site name, account, account id/// and credential id. Never a key, and no vault needed. With `rpId` (Android's/// sign-in, the request's `rpId` and its `allowCredentials` ids as `allow`)/// only the ones that sign-in is offered, by the core's rule/// ([`cotton_core::keys::passkey::offered`]).fn identities(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let mut found = rows(client, IDENTITY_COLUMNS)?;    if let Some(asked) = request.get("rpId").filter(|value| !value.is_null()) {        let asked = asked.as_str().ok_or_else(|| bad("rpId", "text"))?;        let allow: Vec<String> = match request.get("allow") {            None | Some(Value::Null) => Vec::new(),            Some(Value::Array(ids)) => ids.iter().map(|id| id.as_str().map(str::to_string).ok_or_else(|| bad("allow", "a list of credential ids"))).collect::<Result<_, _>>()?,            Some(_) => return Err(bad("allow", "a list of credential ids")),        };        found.retain(|row| {            let field = |name: &str| row.get(name).and_then(Value::as_str).unwrap_or("");            cotton_core::keys::passkey::offered(field("rp_id"), field("credential_id"), asked, &allow)        });    }    Ok(json!({ "identities": found }))}/// `passkey.mirror {credentialIds, privateKey?}` — the opened scalar of each/// asked row (those this phone's keychain lacks: made on another device), for/// the caller to put in the shared keychain group. Each is opened under the/// VMK at the row's own version and held to its public key; a row that does/// not open is named in `refused` by credential id, never by key.fn mirror(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let asked: Vec<String> = request        .get("credentialIds")        .and_then(Value::as_array)        .ok_or_else(|| bad("credentialIds", "a list of credential ids"))?        .iter()        .filter_map(Value::as_str)        .map(str::to_string)        .collect();    if asked.is_empty() {        return Ok(json!({ "keys": [], "refused": [] }));    }    let found: Vec<Map<String, Value>> = rows(        client,        "id, rp_id, rp_name, user_name, user_handle, credential_id, algorithm, public_key, sign_count, private_key_enc, vmk_version, created_at",    )?    .into_iter()    .filter(|row| row.get("credential_id").and_then(Value::as_str).is_some_and(|id| asked.iter().any(|one| one == id)))    .collect();    with_vmk(client, request, |vmk, _| {        let mut keys = Vec::new();        let mut refused = Vec::new();        for row in &found {            let id = row.get("id").and_then(Value::as_str).unwrap_or_default();            let credential = row.get("credential_id").cloned().unwrap_or(Value::Null);            match passkey_row::open(row, id, vmk) {                Ok(passkey) => {                    let scalar = passkey.private_scalar();                    let mut key = Map::new();                    for column in ["rp_id", "rp_name", "user_name", "user_handle", "credential_id", "created_at"] {                        key.insert(column.to_string(), row.get(column).cloned().unwrap_or(Value::Null));                    }                    key.insert("privateScalar".to_string(), json!(URL_SAFE_NO_PAD.encode(scalar.as_slice())));                    keys.push(Value::Object(key));                }                Err(error) => refused.push(json!({ "credential_id": credential, "reason": error.to_string() })),            }        }        Ok(json!({ "keys": keys, "refused": refused }))    })}/// A passkey this device opened, for an export.pub(crate) struct OpenedPasskey {    pub id: String,    pub rp_name: String,    pub user_name: String,    pub created_at: Option<String>,    pub passkey: cotton_core::keys::passkey::Passkey,}/// Every passkey kept here that opens under `vmk`; one that does not is left out.pub(crate) fn opened_all(client: &ClientController, vmk: &Vmk) -> Result<Vec<OpenedPasskey>, MethodError> {    let found = rows(        client,        "id, rp_id, rp_name, user_name, user_handle, credential_id, algorithm, public_key, sign_count, private_key_enc, vmk_version, created_at",    )?;    let text = |row: &Map<String, Value>, column: &str| row.get(column).and_then(Value::as_str).map(str::to_string);    Ok(found        .iter()        .filter_map(|row| {            let id = text(row, "id")?;            let passkey = passkey_row::open(row, &id, vmk).ok()?;            Some(OpenedPasskey {                rp_name: text(row, "rp_name").unwrap_or_else(|| passkey.rp_id.clone()),                user_name: text(row, "user_name").unwrap_or_default(),                created_at: text(row, "created_at"),                id,                passkey,            })        })        .collect())}#[cfg(test)]#[path = "passkeys_tests.rs"]mod tests;