Cotton code
211 lines · 8.8 KB · RustRaw
//! Vault and person-key genesis for a Personal database started on this device.//! This is a device lifecycle operation. It is not linked into any MCP tool.use cotton_core::keys::PersonKey;use cotton_store::mint::{Act, Change, Held, History};use cotton_store::signed::ReceiptSigner;use cotton_store::{Driver, Result, StoreError};use cotton_tools::founding::Founder;use serde_json::json;/// A database's OWN IDENTITY: the rows its founding writes (here and in [`Founder::record`]), each with why it never/// travels into another database (KEPT FOUR, 27 Nov 2026). Every database founds its own: a local database started/// before sign-in founds one, and the signed-in database it is adopted into or gives way to already has its own. Sent/// there, they would plant a rival person, vault and admission (one device key, two VMKs); so a copy leaving into/// another database never carries them (`persons_rows`) and never keeps or counts them as the person's unsent work/// (`copy_keep`). In a copy kept under its own database they are that database's, and wait like any other change.pub const FOUNDING_TABLES: &[(&str, &str)] = &[    ("cotton_admissions", "the founding person's admission of this database's owner: the signed-in database admits its own, by the person's own sign-in"),    ("cotton_device_statements", "this device's statement under the local person's key: the signed-in database takes this device by its own admission"),    ("cotton_person_keys", "the local database's person key, sealed under the local vault: the signed-in database's person has a key of its own"),    ("cotton_vault_state", "the local vault's version: the signed-in database's vault has its own, and a second would be a rival vault"),    ("cotton_vault_keys", "the local vault's key wrapped to this device: in the signed-in database this device is wrapped that database's key, and a row wrapping another would say it opens a vault it cannot"),    ("cotton_member_person_claims", "the local admission's claim on a person row: it names an admission the signed-in database never holds"),];/// Whether `table` (a store table) is one of a database's [`FOUNDING_TABLES`].#[must_use]pub fn is_founding(table: &str) -> bool {    FOUNDING_TABLES.iter().any(|(name, _)| *name == table)}/// Create the local Personal vault and its one person identity. Every private/// byte is sealed or wrapped before the transaction can write a row.pub fn personal(    db: &Driver,    personal: &str,    signer: &dyn ReceiptSigner,    public: &str,    name: &str,    at: &str,    now_ms: i64,    ids: &mut dyn cotton_store::outbox::IdSource,) -> Result<()> {    use cotton_core::vault::{wrap, Vmk};    db.transaction(|db| {    if db.get("SELECT id FROM cotton_person_keys LIMIT 1", &[])?.is_some() { return Ok(()); }    if db.get("SELECT workspace_id FROM cotton_vault_state LIMIT 1", &[])?.is_some() {        return Err(StoreError::refused("The existing vault must be unlocked; its key is never replaced by a new Personal identity."));    }    let public_bytes: [u8; 32] = cotton_core::device::base64url::base64url_decode(public)        .and_then(|bytes| bytes.try_into().ok())        .ok_or_else(|| StoreError::refused("This device's vault public key is unreadable."))?;    let vmk = Vmk::mint();    let wrapped = wrap::wrap(&public_bytes, vmk.expose())        .ok_or_else(|| StoreError::refused("This device's vault key cannot receive a wrap."))?;    let key = PersonKey::mint();    let sealed = key        .seal_private(&vmk, 1)        .ok_or_else(|| StoreError::refused("The person key could not be sealed."))?;    let founder = Founder::signed(personal, &key, name, signer, public, "This device", at)?;    let mut changes = Vec::new();    let old_key = db        .get(            "SELECT id FROM cotton_vault_keys WHERE device_id=?",            &[rusqlite::types::Value::Text(signer.device_key())],        )?        .and_then(|row| row.text("id").map(str::to_string));    for (table, id, value) in [        (            "cotton_person_keys",            key.fingerprint(),            json!({"workspace_id":personal,"public_key":key.public_key(),"name":name,"sealed_private":sealed,"vmk_version":1,"created_at":at}),        ),        (            "cotton_vault_state",            personal.to_string(),            json!({"workspace_id":personal,"vmk_version":1,"rotated_at":at,"created_at":at,"updated_at":at}),        ),        (            "cotton_vault_keys",            old_key                .clone()                .unwrap_or_else(|| format!("founder:{}", signer.device_key())),            json!({"workspace_id":personal,"device_id":signer.device_key(),"public_key":public,"wrapped_vmk":wrapped,"vmk_version":1,"created_at":at,"updated_at":at}),        ),    ] {        let patch = value.as_object().unwrap().clone();        changes.push(if table == "cotton_vault_keys" && old_key.is_some() {            Change::update(table, &id, patch)        } else {            Change::create(table, &id, patch)        });    }    let clock = cotton_store::mint::clock::writer_clock(db, now_ms, ids)?;    cotton_store::mint::mint(        db,        &Act {            actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named(                "birth",            )?),            verb: "found_personal".into(),            history: History::None,            changes,        },        &clock,        ids,        Held::Served,    )?;    founder.record(db, personal, now_ms, ids)    })}#[cfg(test)]mod tests {    use super::*;    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};    use std::sync::Arc;    const DATABASE: &str = "00000000-0000-4000-8000-000000000111";    const AT: &str = "2026-10-04T00:00:00.000Z";    fn file() -> Driver {        let db = cotton_store::test_template::create_workspace_in_memory_for_test(            &cotton_store::meta::Meta {                workspace_id: DATABASE.into(),                owner_id: "synthetic-owner".into(),                device_id: "device:synthetic".into(),                last_server_seq: 0,                last_hlc: None,            },        )        .unwrap();        db.run("INSERT INTO cotton_workspaces (id,name,owner_user_id,created_at) VALUES (?, 'Garden','synthetic-owner',?)", &[rusqlite::types::Value::Text(DATABASE.into()),rusqlite::types::Value::Text(AT.into())]).unwrap();        db    }    #[test]    fn phone_first_person_is_sealed_to_its_device_vault_and_can_sign_after_unlock() {        let db = file();        let device = crate::DeviceIdentity::from_secret(&[25u8; 32]).unwrap();        let public = URL_SAFE_NO_PAD.encode(cotton_core::vault::wrap::public_of(&[26u8; 32]));        let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SystemRandom));        personal(            &db,            DATABASE,            &device,            &public,            "Synthetic owner",            AT,            1_791_072_000_000,            &mut ids,        )        .unwrap();        let wrapped = db            .get("SELECT wrapped_vmk FROM cotton_vault_keys", &[])            .unwrap()            .unwrap();        let bytes =            cotton_core::vault::wrap::unwrap(&[26u8; 32], wrapped.text("wrapped_vmk").unwrap())                .unwrap();        assert!(cotton_core::vault::wrap::unwrap(            &[27u8; 32],            wrapped.text("wrapped_vmk").unwrap()        )        .is_none());        let vmk = cotton_core::vault::Vmk::from_bytes(bytes.try_into().unwrap());        let row = db            .get(                "SELECT public_key,sealed_private FROM cotton_person_keys",                &[],            )            .unwrap()            .unwrap();        let person = PersonKey::open_private(            &vmk,            row.text("public_key").unwrap(),            1,            row.text("sealed_private").unwrap(),        )        .unwrap();        assert_eq!(            cotton_store::membership::owner(&db).unwrap(),            Some(person.public_key())        );        assert!(cotton_core::keys::person::verify(            &person.public_key(),            b"proof",            &person.sign(b"proof")        ));        personal(            &db,            DATABASE,            &device,            &public,            "Changed name",            AT,            1_791_072_000_001,            &mut ids,        )        .unwrap();        let again = db            .get(                "SELECT public_key,sealed_private FROM cotton_person_keys",                &[],            )            .unwrap()            .unwrap();        assert_eq!(again.text("public_key"), row.text("public_key"));        assert_eq!(            again.text("sealed_private"),            row.text("sealed_private"),            "a repeated launch cannot mint or reseal a different person"        );    }}