//! The signed fact that the person who creates a database owns it. //! The device carries these public proofs to the serving Mac when it adopts //! an offline database. Membership facts themselves are never pushed. //! //! A shared database's proof also carries the maker's person CLAIM (architect, //! 11 Oct 2026: "a member is a person in every database they are in"): the //! person row the maker is in that database, signed as theirs over //! `member_person::claim_bytes` against the owner admission. It travels here //! for the same reason the admission does — a claim is a membership fact, made //! where it is signed and never pushed — and it is optional, because the //! personal database's owner is `owner_person_id`, not a claim. use cotton_core::keys::{statements, PersonKey}; use cotton_store::mint::{Act, Change, Held, History}; use cotton_store::signed::{sig_text, ReceiptSigner}; use cotton_store::{Driver, Result, StoreError}; use serde::{Deserialize, Serialize}; use serde_json::json; #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Founder { pub person_key: String, pub person_name: String, pub device_key: String, pub vault_public_key: String, pub device_name: String, pub made_at: String, pub admission_signature: String, pub statement_signature: String, pub consent_signature: String, /// The person the maker is in this database, when the proof claims one. #[serde(default, skip_serializing_if = "Option::is_none")] pub person_id: Option, /// The maker's signature over that claim (`member_person::claim_bytes`). #[serde(default, skip_serializing_if = "Option::is_none")] pub claim_signature: Option, } /// The owner admission's id in a founded database. pub fn owner_admission_id(person_key: &str) -> String { format!("owner:{person_key}") } /// The founder claim's id: one per maker, so the device's copy and the /// serving Mac's write the same row. pub fn owner_claim_id(person_key: &str) -> String { format!("owner-claim:{person_key}") } impl Founder { pub fn signed( database: &str, person: &PersonKey, name: &str, device: &dyn ReceiptSigner, vault_public: &str, device_name: &str, made_at: &str, ) -> Result { Self::signing( database, &person.public_key(), name, device, vault_public, device_name, made_at, |message| Ok(person.sign(message)), ) } pub fn signing( database: &str, person: &str, name: &str, device: &dyn ReceiptSigner, vault_public: &str, device_name: &str, made_at: &str, mut sign: impl FnMut(&[u8]) -> Result<[u8; 64]>, ) -> Result { let key = device.device_key(); Ok(Self { person_key: person.into(), person_name: name.into(), device_key: key.clone(), vault_public_key: vault_public.into(), device_name: device_name.into(), made_at: made_at.into(), admission_signature: sig_text(&sign(&statements::admission_bytes( database, person, "owner", None, made_at, ))?), statement_signature: sig_text(&sign(&statements::device_statement_bytes( database, person, &key, vault_public, ))?), consent_signature: sig_text( &device .sign(&statements::device_consent_bytes( database, person, &key, vault_public, )) .map_err(StoreError::refused)?, ), person_id: None, claim_signature: None, }) } /// This proof with the maker's person claimed: `person_id` is the person /// row the maker is in this database, signed as theirs. pub fn claiming( mut self, database: &str, person_id: &str, mut sign: impl FnMut(&[u8]) -> Result<[u8; 64]>, ) -> Result { let bytes = self.claim_bytes(database, person_id); self.claim_signature = Some(sig_text(&sign(&bytes)?)); self.person_id = Some(person_id.into()); Ok(self) } fn claim_bytes(&self, database: &str, person_id: &str) -> Vec { cotton_store::member_person::claim_bytes( database, &owner_admission_id(&self.person_key), &self.person_key, person_id, &self.made_at, ) } pub fn verifies(&self, database: &str) -> bool { let claim = match (&self.person_id, &self.claim_signature) { (None, None) => true, (Some(person), Some(signature)) => statements::verifies( &self.person_key, &self.claim_bytes(database, person), signature, ), _ => false, }; claim && self.verifies_membership(database) } fn verifies_membership(&self, database: &str) -> bool { statements::verifies( &self.person_key, &statements::admission_bytes(database, &self.person_key, "owner", None, &self.made_at), &self.admission_signature, ) && statements::verifies( &self.person_key, &statements::device_statement_bytes( database, &self.person_key, &self.device_key, &self.vault_public_key, ), &self.statement_signature, ) && statements::verifies( &self.device_key, &statements::device_consent_bytes( database, &self.person_key, &self.device_key, &self.vault_public_key, ), &self.consent_signature, ) } /// The caller establishes that this person may found this database (a /// local birth, or the serving Mac's authenticated Personal owner). pub fn record( &self, db: &Driver, database: &str, now_ms: i64, ids: &mut dyn cotton_store::outbox::IdSource, ) -> Result<()> { if !self.verifies(database) { return Err(StoreError::refused( "the creator's signed membership does not verify for this database", )); } if cotton_store::membership::owner(db)?.is_some_and(|owner| owner != self.person_key) { return Err(StoreError::refused( "this database already belongs to another person", )); } let admission = owner_admission_id(&self.person_key); let statement = format!("owner-device:{}", self.device_key); let mut rows = vec![ ( "cotton_admissions", admission.clone(), json!({"workspace_id":database,"person_key":self.person_key,"person_name":self.person_name,"rights":"owner","invite_id":null,"admitted_by_person":self.person_key,"p_sig":self.admission_signature,"admitted_at":self.made_at}), ), ( "cotton_device_statements", statement, json!({"workspace_id":database,"person_key":self.person_key,"device_key":self.device_key,"vault_public_key":self.vault_public_key,"device_name":self.device_name,"p_sig":self.statement_signature,"d_sig":self.consent_signature,"made_at":self.made_at}), ), ]; if let (Some(person), Some(signature)) = (&self.person_id, &self.claim_signature) { rows.push(( cotton_store::member_person::TABLE, owner_claim_id(&self.person_key), json!({"workspace_id":database,"admission_id":admission,"person_key":self.person_key,"person_id":person,"p_sig":signature,"claimed_at":self.made_at}), )); } let mut changes = Vec::new(); for (table, id, value) in rows { if db .get( &format!("SELECT id FROM {table} WHERE id = ?"), &[rusqlite::types::Value::Text(id.clone())], )? .is_none() { changes.push(Change::create( table, &id, value.as_object().unwrap().clone(), )); } } if changes.is_empty() { return Ok(()); } 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_database".into(), history: History::None, changes, }, &clock, ids, Held::Served, )?; Ok(()) } pub fn read(db: &Driver, device: &str) -> Result> { let row = db.get("SELECT a.person_key,a.person_name,a.p_sig AS admission_signature,a.admitted_at,s.device_key,s.vault_public_key,s.device_name,s.p_sig AS statement_signature,s.d_sig AS consent_signature,c.person_id AS claimed_person,c.p_sig AS claim_signature FROM cotton_admissions a JOIN cotton_device_statements s ON s.person_key=a.person_key LEFT JOIN cotton_member_person_claims c ON c.id='owner-claim:'||a.person_key AND c.admission_id=a.id AND c.claimed_at=a.admitted_at WHERE a.rights='owner' AND s.device_key=? ORDER BY a._hlc,s._hlc LIMIT 1", &[rusqlite::types::Value::Text(device.into())])?; Ok(row.map(|row| Self { person_key: row.text("person_key").unwrap_or_default().into(), person_name: row.text("person_name").unwrap_or_default().into(), device_key: row.text("device_key").unwrap_or_default().into(), vault_public_key: row.text("vault_public_key").unwrap_or_default().into(), device_name: row.text("device_name").unwrap_or_default().into(), made_at: row.text("admitted_at").unwrap_or_default().into(), admission_signature: row.text("admission_signature").unwrap_or_default().into(), statement_signature: row.text("statement_signature").unwrap_or_default().into(), consent_signature: row.text("consent_signature").unwrap_or_default().into(), person_id: row.text("claimed_person").map(str::to_string), claim_signature: row.text("claim_signature").map(str::to_string), })) } } #[cfg(test)] mod tests { use super::*; 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 founder_is_signed_by_person_and_device_and_cannot_move_to_another_database() { let db = file(); let person = PersonKey::mint(); let device = cotton_client::DeviceIdentity::from_secret(&[23u8; 32]).unwrap(); let founder = Founder::signed( DATABASE, &person, "Synthetic owner", &device, "vault", "Test phone", AT, ) .unwrap(); assert!(founder.verifies(DATABASE)); assert!(!founder.verifies("another-database")); let mut ids = cotton_client::seams::op_ids(Arc::new(cotton_client::seams::SystemRandom)); founder .record(&db, DATABASE, 1_791_072_000_000, &mut ids) .unwrap(); assert_eq!( cotton_store::membership::device(&db, &device.device_id()).unwrap(), Some((person.public_key(), cotton_store::membership::Rights::Owner)) ); founder .record(&db, DATABASE, 1_791_072_000_001, &mut ids) .unwrap(); assert_eq!( db.all("SELECT id FROM cotton_admissions", &[]) .unwrap() .len(), 1 ); let mut forged = founder.clone(); forged.device_key = cotton_client::DeviceIdentity::from_secret(&[24u8; 32]) .unwrap() .device_id(); assert!(forged .record(&db, DATABASE, 1_791_072_000_002, &mut ids) .is_err()); assert_eq!( cotton_store::outbox::pending_count(&db).unwrap(), 0, "facts travel through authenticated adoption, never a forbidden pushed membership op" ); } // RULE: Making a shared database makes exactly one person, the maker, // claimed (architect, 11 Oct 2026): the founder proof carries the maker's // signed claim, its record writes it beside the owner admission, the claim // binds that person once the row is there, the proof read back carries it, // and a claim moved to another person does not verify. #[test] fn a_founder_claims_the_makers_person_in_the_database() { let db = file(); let person = PersonKey::mint(); let device = cotton_client::DeviceIdentity::from_secret(&[25u8; 32]).unwrap(); let founder = Founder::signed(DATABASE, &person, "Synthetic owner", &device, "vault", "Test phone", AT) .unwrap() .claiming(DATABASE, "maker-person", |message| Ok(person.sign(message))) .unwrap(); assert!(founder.verifies(DATABASE)); let mut moved = founder.clone(); moved.person_id = Some("somebody-else".into()); assert!(!moved.verifies(DATABASE), "a claim is for the person it was signed for"); let mut ids = cotton_client::seams::op_ids(Arc::new(cotton_client::seams::SystemRandom)); founder.record(&db, DATABASE, 1_791_072_000_000, &mut ids).unwrap(); db.run( "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES ('maker-person', ?, 'Synthetic owner', ?, ?)", &[ rusqlite::types::Value::Text(DATABASE.into()), rusqlite::types::Value::Text(AT.into()), rusqlite::types::Value::Text(AT.into()), ], ) .unwrap(); let bound = cotton_store::member_person::bound_person(&db, DATABASE, &person.public_key()).unwrap(); assert_eq!(bound.map(|bound| bound.person_id).as_deref(), Some("maker-person")); let read = Founder::read(&db, &device.device_id()).unwrap().expect("the proof"); assert_eq!(read.person_id.as_deref(), Some("maker-person")); assert!(read.verifies(DATABASE), "the proof read back is the one signed"); assert_eq!(cotton_store::outbox::pending_count(&db).unwrap(), 0); } }