//! The databases a person joined at other people's Macs, known to every device //! of the person. //! //! An invite admits ONE device. The place it joined — which Mac serves the //! database, pinned to that Mac's key — is written as a row of //! `cotton_joined_places` in the person's own personal database, so it syncs //! through the household to their other devices. A device that reads a place //! it does not hold is "elsewhere": it presents itself to that Mac as another //! device of the same person — a device statement signed with the person key //! (which every device of the person holds, sealed under the personal vault) //! and the device's own consent — and the Mac admits it without an invite //! ([`cotton_server::members::devices`]). The person key signs only while the //! vault is unlocked, so presenting is an act the app asks for //! (`databases.present`), never a silent pass. A leave deletes the row: the //! person left, on every device. use cotton_client::connection::joined::JoinedDatabase; use cotton_tools::mcp::writer::Retract; use serde_json::{json, Map, Value}; use crate::{handle::CottonHandle, methods::MethodError, shell::client::ClientController}; pub const TABLE: &str = "cotton_joined_places"; /// The row that names `database`, if the personal database holds one. fn row_of(client: &ClientController, database: &str) -> Result, String> { client.with_file(|replica| { replica .driver .get( &format!("SELECT id FROM {TABLE} WHERE workspace_id = ? AND database_id = ? LIMIT 1"), &[ rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Text(database.to_string()), ], ) .map(|row| row.and_then(|row| row.text("id").map(str::to_string))) .map_err(|error| error.to_string()) }) } /// Write the place a claim admitted this device to, for the person's other /// devices: one row per database (the row it has, else a fresh id — never /// the database's own id, so a rejoin after a leave is a new row). pub fn record(client: &ClientController, database: &JoinedDatabase, now: &str) -> Result<(), String> { let mut row = Map::new(); row.insert("database_id".into(), json!(database.id)); row.insert("name".into(), json!(database.name)); row.insert("origin".into(), json!(database.origin)); row.insert("server_device_id".into(), json!(database.server_device_id)); row.insert("joined_at".into(), json!(now)); let id = row_of(client, &database.id)?; client .write_rows_with_vault("a joined place", None, &mut |ctx| { let id = id .clone() .unwrap_or_else(|| cotton_tools::random::uuid_v4(ctx.random.as_ref())); ctx.writer() .map_err(|failure| failure.message().to_string())? .upsert(TABLE, &id, row.clone()); Ok(Value::Null) }) .map(|_| ()) } /// The person left `database`: no device of theirs presents itself there again. pub fn forget(client: &ClientController, database: &str) -> Result<(), String> { let Some(id) = row_of(client, database)? else { return Ok(()) }; client .write_rows_with_vault("a left place", None, &mut |ctx| { ctx.writer() .map_err(|failure| failure.message().to_string())? .retract(TABLE, &id, Retract::Relation); Ok(Value::Null) }) .map(|_| ()) } /// A place the person holds on another device and not on this one. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Elsewhere { pub database: String, pub name: String, pub origin: String, pub server_device_id: String, } impl Elsewhere { pub fn to_json(&self) -> Value { json!({ "databaseId": self.database, "name": self.name, "origin": self.origin, "serverDeviceId": self.server_device_id, }) } } /// The places this device does not hold: every joined place of the personal /// database minus the databases the connection record holds (held, removed or /// pending alike) and the ones this device explicitly left. pub fn elsewhere(client: &ClientController) -> Result, String> { let record = cotton_client::connection::read_record(&client.layout().connection_json()) .map_err(|error| error.to_string())?; let held: Vec = record .as_ref() .map(|record| { record .places .iter() .map(|place| place.id.clone()) .chain(record.left_databases.iter().cloned()) .chain(record.mine.workspace_id.iter().cloned()) .collect() }) .unwrap_or_default(); let rows = client.with_file(|replica| { replica .driver .all( &format!( "SELECT database_id, name, origin, server_device_id FROM {TABLE} \ WHERE workspace_id = ? ORDER BY joined_at, id" ), &[rusqlite::types::Value::Text(replica.workspace_id.to_string())], ) .map_err(|error| error.to_string()) })?; Ok(rows .iter() .filter_map(|row| { let database = row.text("database_id")?.to_string(); let origin = row.text("origin")?.to_string(); let server_device_id = row.text("server_device_id")?.to_string(); (!held.contains(&database) && !origin.is_empty() && !server_device_id.is_empty()).then( || Elsewhere { database, name: row.text("name").unwrap_or_default().to_string(), origin, server_device_id, }, ) }) .collect()) } /// `databases.present { databaseId }` — this device presented itself to the /// Mac that serves a place the person holds elsewhere; it signs no request to /// one, so a held place elsewhere is named and refused. pub fn present(handle: &CottonHandle, request: &Value) -> Result { let database = super::owner::text(request, "databaseId")?; elsewhere(&handle.client()) .map_err(|error| MethodError::new("database_not_held", error))? .into_iter() .find(|place| place.database == database) .ok_or_else(|| { MethodError::new( "database_not_held", "This person holds no such database on another device.", ) })?; Err(MethodError::new("device_key_unreadable", super::owner::NO_DEVICE_IDENTITY)) }