Cotton code
303 lines · 12.5 KB · RustRaw
//! What Cotton Keys hands another app: a CSV of logins, or a Credential//! Exchange export of everything.//!//! ```text//! to_csv(items)                               → Csv { text, left_out }   Apple Passwords' header, logins only//! to_cxf(items, passkeys, timestamp)          → JSON, CXF 1.0 (cxf-v1.0-ps-20250814)//! WARNING                                     the line the shell shows before either is written//! ```//!//! Both are made behind the unlock and only for the person to save: the//! values are in the clear in what they return, which is why [`WARNING`]//! says so. The CSV is the header Cotton Keys reads first//! (`Title,URL,Username,Password,Notes,OTPAuth`), so a file written here reads//! back here; a kind a CSV has no column for is counted in `left_out`.//!//! The CXF export is one account holding one item per secret and per//! passkey: `basic-auth` with the item's `scope.urls` and its `totp` and//! `note` beside it (§3.3.2, §3.3.21, §3.3.15), `api-key`, `note`,//! `credit-card`, `identity-document`, `wifi`, `address` (§3.3), and//! `passkey` with its PKCS#8 key (§3.3.12). Item ids are the row ids,//! base64url (§2.1).//!//! **Pure**: the timestamp is the caller's.use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use p256::pkcs8::EncodePrivateKey;use serde_json::{json, Map, Value};use zeroize::Zeroizing;use super::passkey::Passkey;use super::totp::Totp;use crate::vault::payload::SecretPayload;/// The line shown before an export is written. A line key's English, kept here as data the kit's lines mirror.pub const WARNING: &str = "This file holds your passwords in the clear. Anyone who opens it can read them: keep it somewhere only you can reach, and delete it once it has been read.";/// One opened secret, as an export takes it.pub struct Item<'a> {    pub id: &'a str,    pub name: &'a str,    pub site: Option<&'a str>,    pub username: Option<&'a str>,    pub payload: &'a SecretPayload,    /// UNIX seconds.    pub created_at: Option<u64>,    pub favourite: bool,}/// One opened passkey.pub struct PasskeyItem<'a> {    pub id: &'a str,    pub rp_name: &'a str,    pub user_name: &'a str,    pub user_display_name: &'a str,    pub passkey: &'a Passkey,    pub created_at: Option<u64>,}/// A CSV export and how many items it could not carry.pub struct Csv {    pub text: Zeroizing<String>,    pub left_out: usize,}fn csv_field(out: &mut String, value: &str) {    if value.contains([',', '"', '\n', '\r']) {        out.push('"');        out.push_str(&value.replace('"', "\"\""));        out.push('"');    } else {        out.push_str(value);    }}/// Every login as an Apple Passwords CSV row.pub fn to_csv(items: &[Item<'_>]) -> Csv {    let mut text = Zeroizing::new(String::from("Title,URL,Username,Password,Notes,OTPAuth\n"));    let mut left_out = 0;    for item in items {        let SecretPayload::Login { password, notes, totp, .. } = item.payload else {            left_out += 1;            continue;        };        let url = item.site.map(|site| if site.contains("://") { site.to_string() } else { format!("https://{site}/") }).unwrap_or_default();        let fields = [item.name, url.as_str(), item.username.unwrap_or(""), password.as_str(), notes.as_deref().unwrap_or(""), totp.as_deref().unwrap_or("")];        for (at, field) in fields.iter().enumerate() {            if at > 0 {                text.push(',');            }            csv_field(&mut text, field);        }        text.push('\n');    }    Csv { text, left_out }}fn b64(bytes: &[u8]) -> String {    URL_SAFE_NO_PAD.encode(bytes)}fn field(kind: &str, value: &str) -> Value {    json!({ "fieldType": kind, "value": value })}fn text_field(value: &str) -> Value {    field("string", value)}fn concealed(value: &str) -> Value {    field("concealed-string", value)}fn note_of(value: &Option<String>) -> Option<Value> {    value.as_deref().filter(|note| !note.is_empty()).map(|note| json!({ "type": "note", "content": text_field(note) }))}fn totp_credential(address: &str, username: Option<&str>) -> Option<Value> {    let totp = Totp::parse(address).ok()?;    let mut entry = json!({        "type": "totp",        "secret": super::totp::base32_encode(totp.secret_bytes()),        "period": totp.period,        "digits": totp.digits,        "algorithm": totp.algorithm.as_str().to_lowercase(),    });    if let Some(issuer) = &totp.issuer {        entry["issuer"] = json!(issuer);    }    if let Some(user) = totp.account.as_deref().or(username) {        entry["username"] = json!(user);    }    Some(entry)}fn credentials_of(item: &Item<'_>) -> Vec<Value> {    let mut out = Vec::new();    match item.payload {        SecretPayload::Login { password, notes, totp, .. } => {            out.push(json!({ "type": "basic-auth", "username": text_field(item.username.unwrap_or("")), "password": concealed(password) }));            out.extend(totp.as_deref().and_then(|address| totp_credential(address, item.username)));            out.extend(note_of(notes));        }        SecretPayload::ApiKey { key, notes } => {            out.push(json!({ "type": "api-key", "key": concealed(key) }));            out.extend(note_of(notes));        }        SecretPayload::Note { body } => out.push(json!({ "type": "note", "content": text_field(body) })),        SecretPayload::Card { number, holder, expiry, cvv, notes } => {            let mut card = json!({ "type": "credit-card", "number": concealed(number) });            if let Some(holder) = holder {                card["fullName"] = text_field(holder);            }            if let Some(expiry) = expiry.as_deref().and_then(year_month) {                card["expiryDate"] = field("year-month", &expiry);            }            if let Some(cvv) = cvv {                card["verificationNumber"] = concealed(cvv);            }            out.push(card);            out.extend(note_of(notes));        }        SecretPayload::Identity { number, id_type, holder, issued, expires, country, notes } => {            let mut document = json!({ "type": "identity-document", "documentNumber": concealed(number) });            for (key, value) in [("identificationType", id_type), ("fullName", holder), ("issueDate", issued), ("expiryDate", expires), ("issuingCountry", country)] {                if let Some(value) = value {                    document[key] = text_field(value);                }            }            out.push(document);            out.extend(note_of(notes));        }        SecretPayload::Document { password } => out.push(json!({ "type": "basic-auth", "username": text_field(""), "password": concealed(password) })),        SecretPayload::Code { secret, notes } => {            out.extend(totp_credential(secret, item.username));            out.extend(note_of(notes));        }        SecretPayload::Wifi { password, security, notes } => {            let mut wifi = json!({ "type": "wifi", "ssid": text_field(item.name), "passphrase": concealed(password) });            if let Some(security) = security {                wifi["networkSecurityType"] = text_field(security);            }            out.push(wifi);            out.extend(note_of(notes));        }        SecretPayload::Address { address, full_name, email, phone, notes } => {            let mut entry = json!({ "type": "address", "streetAddress": text_field(address) });            if let Some(phone) = phone {                entry["tel"] = text_field(phone);            }            out.push(entry);            let mut extra = Vec::new();            if let Some(name) = full_name {                extra.push(json!({ "fieldType": "string", "value": name, "label": "full_name" }));            }            if let Some(email) = email {                extra.push(json!({ "fieldType": "email", "value": email, "label": "email" }));            }            if !extra.is_empty() {                out.push(json!({ "type": "custom-fields", "fields": extra }));            }            out.extend(note_of(notes));        }        // A kept file travels as concealed custom fields: CXF's own `file`        // credential points at a separate attachment, which a CSV-or-one-file        // export has nowhere to put. Its name and passwords go beside it.        SecretPayload::File { content, file_name, store_password, key_alias, key_password, notes } => {            let mut fields = vec![json!({ "fieldType": "concealed-string", "value": content, "label": "file_base64" })];            if let Some(name) = file_name {                fields.push(json!({ "fieldType": "string", "value": name, "label": "file_name" }));            }            for (label, value) in [("store_password", store_password), ("key_alias", key_alias), ("key_password", key_password)] {                if let Some(value) = value {                    let kind = if label == "key_alias" { "string" } else { "concealed-string" };                    fields.push(json!({ "fieldType": kind, "value": value, "label": label }));                }            }            out.push(json!({ "type": "custom-fields", "fields": fields }));            out.extend(note_of(notes));        }    }    out}/// `MM/YY` or `MM/YYYY` as `YYYY-MM`.fn year_month(expiry: &str) -> Option<String> {    let (month, year) = expiry.trim().split_once('/')?;    let month: u32 = month.trim().parse().ok().filter(|month| (1..=12).contains(month))?;    let year = year.trim();    let year: u32 = match year.len() {        2 => 2000 + year.parse::<u32>().ok()?,        4 => year.parse().ok()?,        _ => return None,    };    Some(format!("{year:04}-{month:02}"))}/// The Credential Exchange export of every item and passkey given.pub fn to_cxf(items: &[Item<'_>], passkeys: &[PasskeyItem<'_>], timestamp: u64) -> Result<Zeroizing<String>, String> {    let mut out_items = Vec::new();    for item in items {        let mut entry = Map::new();        entry.insert("id".into(), json!(b64(item.id.as_bytes())));        entry.insert("title".into(), json!(item.name));        if let Some(created) = item.created_at {            entry.insert("creationAt".into(), json!(created));        }        if item.favourite {            entry.insert("favorite".into(), json!(true));        }        let mut urls: Vec<String> = item.site.map(|site| vec![if site.contains("://") { site.to_string() } else { format!("https://{site}/") }]).unwrap_or_default();        if let SecretPayload::Login { urls: Some(more), .. } = item.payload {            urls.extend(more.lines().map(str::trim).filter(|url| !url.is_empty()).map(str::to_string));        }        if !urls.is_empty() {            entry.insert("scope".into(), json!({ "urls": urls, "androidApps": [] }));        }        entry.insert("credentials".into(), Value::Array(credentials_of(item)));        out_items.push(Value::Object(entry));    }    for key in passkeys {        let scalar = key.passkey.private_scalar();        let secret = p256::SecretKey::from_slice(&scalar).map_err(|_| "a passkey's key could not be read".to_string())?;        let der = secret.to_pkcs8_der().map_err(|_| "a passkey's key could not be written".to_string())?;        let credential_id = URL_SAFE_NO_PAD.decode(&key.passkey.credential_id).map_err(|_| "a passkey's credential id is not base64url".to_string())?;        let user_handle = URL_SAFE_NO_PAD.decode(&key.passkey.user_handle).map_err(|_| "a passkey's user handle is not base64url".to_string())?;        let mut entry = json!({            "id": b64(key.id.as_bytes()),            "title": key.rp_name,            "credentials": [{                "type": "passkey",                "credentialId": b64(&credential_id),                "rpId": key.passkey.rp_id,                "username": key.user_name,                "userDisplayName": key.user_display_name,                "userHandle": b64(&user_handle),                "key": b64(der.as_bytes()),            }],        });        if let Some(created) = key.created_at {            entry["creationAt"] = json!(created);        }        out_items.push(entry);    }    let export = json!({        "version": { "major": 1, "minor": 0 },        "exporterRpId": "cottondb.com",        "exporterDisplayName": "Cotton Vault",        "timestamp": timestamp,        "accounts": [{            "id": b64(b"cotton-keys"),            "username": "",            "email": "",            "collections": [],            "items": out_items,        }],    });    Ok(Zeroizing::new(serde_json::to_string(&export).map_err(|error| error.to_string())?))}#[cfg(test)]#[path = "export_tests.rs"]mod tests;