Cotton code
130 lines · 5.2 KB · RustRaw
//! Phone-first vault genesis and signed creator membership.use crate::{methods::MethodError, shell::client::ClientController};use cotton_store::{Driver, StoreError};fn failed(error: impl std::fmt::Display) -> MethodError {    MethodError::new("creator_identity_unavailable", error.to_string())}/// Only a Personal database this phone itself started may mint its identity./// A joined file waits for the serving Mac's key; it must never mint a rival.pub fn local_personal(client: &ClientController, public: &str) -> Result<(), MethodError> {    let Some(connection) =        cotton_client::connection::read_connection(&client.layout().connection_json())            .map_err(failed)?    else {        return Ok(());    };    if connection.mode != cotton_client::connection::ConnectionMode::Local {        return Ok(());    }    let Some(personal) = connection.workspace_id else {        return Ok(());    };    let _scope = client.name_database(Some(&personal)).map_err(failed)?;    let signer = client.receipt_signer_slot();    let signer = signer        .get()        .ok_or_else(|| failed("This device has no signing key."))?;    let now = client.now();    client        .with_writer(|file| {            file.driver                .transaction(|db| {                    if db                        .get("SELECT id FROM cotton_person_keys LIMIT 1", &[])?                        .is_some()                    {                        return Ok(());                    }                    // An existing vault without a person key needs its own unlocked                    // key. Never replace its VMK and orphan any sealed records.                    if db                        .get("SELECT workspace_id FROM cotton_vault_state LIMIT 1", &[])?                        .is_some()                    {                        return Err(StoreError::refused(                            "Unlock the existing Personal vault before creating its person key.",                        ));                    }                    cotton_client::founding::personal(                        db,                        &personal,                        signer.as_ref(),                        public,                        &owner_name(db)?,                        &cotton_client::seams::iso(now),                        now.timestamp_millis(),                        &mut cotton_client::seams::op_ids(std::sync::Arc::new(                            cotton_client::seams::SystemRandom,                        )),                    )                })                .map_err(|error| error.to_string())        })        .map_err(failed)?;    // KEPT FOUR 3 B: the local vault key's wrap into its own file the moment it exists, so no copy, folder or list    // ever holds its only wrap.    let layout = client.layout().clone();    cotton_client::vault_keep::secure(&layout, &personal, &[layout.replica(&personal)], None).map_err(failed)?;    Ok(())}pub fn owner_name(db: &Driver) -> cotton_store::Result<String> {    let display = db        .get(            "SELECT display_name FROM cotton_msg_owner_settings LIMIT 1",            &[],        )?        .and_then(|row| {            row.text("display_name")                .map(str::trim)                .filter(|name| !name.is_empty())                .map(str::to_string)        });    if let Some(name) = display {        return Ok(name);    }    // The personal database is named after its person at the join ("What    // should we call you?"); the one name a phone-founded database can carry    // to its members, who otherwise read "Owner" — the serving Mac's    // `routes::me::owner_name` reads the same two places.    Ok(db        .get("SELECT name FROM cotton_workspaces WHERE kind = 'personal' LIMIT 1", &[])?        .and_then(|row| row.text("name").map(str::trim).map(str::to_string))        .filter(|name| !name.is_empty() && name != "Personal" && name != "Unnamed")        .unwrap_or_else(|| "Owner".into()))}/// Read Personal's key, never the shown database's key, and sign this newly/// made database's founder facts. No private key leaves the vault call.#[cfg(test)]pub fn creator(client: &ClientController, database: &str) -> Result<cotton_tools::founding::Founder, MethodError> {    let _scope = client.name_database(None).map_err(failed)?;    let person = super::vault::person_public_key(client)?;    let public = client        .vault_public()        .ok_or_else(|| failed("Publish this device's vault key before creating a database."))?;    let name = client        .with_file(|file| owner_name(file.driver).map_err(|error| error.to_string()))        .map_err(failed)?;    let slot = client.receipt_signer_slot();    let device = slot        .get()        .ok_or_else(|| failed("This device has no signing key."))?;    cotton_tools::founding::Founder::signing(        database,        &person,        &name,        device.as_ref(),        &public,        "This device",        &cotton_client::seams::iso(client.now()),        |message| {            super::vault::sign_as_person(client, message)                .map(|(_, signature)| signature)                .map_err(|error| StoreError::refused(error.message))        },    )    .map_err(failed)}