diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b8eed52b..8a7c8f70 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -61,6 +61,7 @@ Each subject has one doc in `docs/architecture/`. `pnpm run check:docs` enforces | --- | --- | | [Account model](docs/architecture/account-model.md) | Entity relationships, Device/relay data ownership and cross-Runner job routing | | [Identity](docs/architecture/identity.md) | Key pairs and the identity device, pairing and unpairing, Devices and Runners, what the relay sees, the account's provider credentials | +| [Device names](docs/architecture/device-names.md) | Account aliases, machine names and durable roster intent | | [Device revocation](docs/architecture/device-revocation.md) | Lost, un-wiped Device boundaries and the proposed, unimplemented containment and rotation contract | | [Relay](docs/architecture/relay.md) | `crates/relay`: storage on SQLite or Postgres, files, housekeeping, quotas, metrics, rate limits, auth, tables and migrations, the blob, sync socket, and push APIs, deploys | | [Computer display](docs/architecture/computer-display.md) | Proposed authenticated display/input transport, Device-bound sessions, lifecycle fences, client feasibility and measurement gaps | diff --git a/crates/cli/src/api.rs b/crates/cli/src/api.rs index 9644069d..2910b76e 100644 --- a/crates/cli/src/api.rs +++ b/crates/cli/src/api.rs @@ -170,6 +170,12 @@ pub async fn dispatch(app: &Arc, method: &str, params: Value) -> Result { + let id = string(¶ms, "id")?; + let name = params["name"].as_str().ok_or("missing name")?; + app.set_device_name(&id, name).map_err(|e| e.to_string())?; + Ok(Value::Null) + } "device.rename" => { let name = string(¶ms, "name")?; app.rename_device(&name).map_err(|e| e.to_string())?; diff --git a/crates/cli/src/app.rs b/crates/cli/src/app.rs index 089b5d1f..4686ffdd 100644 --- a/crates/cli/src/app.rs +++ b/crates/cli/src/app.rs @@ -55,6 +55,8 @@ impl Slot { #[derive(Debug, Clone, Default)] pub struct State { pub devices: Vec, + pub device_names: std::collections::BTreeMap, + pub device_name_edits: std::collections::BTreeMap, pub bots: Vec, pub chats: Vec, pub routines: Vec, @@ -798,6 +800,40 @@ impl App { Ok(()) } + /// Gives a known Device an account alias; blank restores its machine name. + pub fn set_device_name(&self, id: &str, name: &str) -> anyhow::Result<()> { + let name = name.trim(); + anyhow::ensure!(name.chars().count() <= 64, "Device names must be at most 64 characters"); + let _edit = self.roster_edit.lock().unwrap(); + let lifecycle = self.plugin_admission(None).map_err(anyhow::Error::msg)?; + let dek = self.machine_file().ok_or_else(|| anyhow::anyhow!("No identity on this Device"))?.dek()?; + { + let mut state = self.state.lock().unwrap(); + let device = state.devices.iter().find(|device| device.id == id) + .ok_or_else(|| anyhow::anyhow!("Unknown Device"))?; + let alias = (!name.is_empty() && name != device.name).then(|| name.to_owned()); + let mut snapshot = state.clone(); + match alias { + Some(name) => { snapshot.device_names.insert(id.to_owned(), name); } + None => { snapshot.device_names.remove(id); } + } + snapshot.device_name_edits.insert(id.to_owned(), uuid::Uuid::new_v4().to_string()); + let item = OutboxItem { + id: uuid::Uuid::new_v4().to_string(), kind: "roster".into(), recipient: None, + ciphertext: crate::crypto::encrypt_json(&dek, "roster", &Self::roster_from_state(&snapshot))?, + slot: Some(Slot::latest("roster")), group: None, + }; + remember_applied(&mut snapshot, &item.id); + self.store.queue_outbox_with_state(&item, &snapshot)?; + *state = snapshot; + } + drop(_edit); + drop(lifecycle); + self.outbox_notify.notify_waiters(); + self.emit(self.roster_summary()); + Ok(()) + } + /// Forgets the identity on this Device: keys, credentials, and everything synced. The /// relay keeps the account; another Device or the backup phrase brings it back. pub fn forget_identity(&self) -> anyhow::Result<()> { @@ -941,11 +977,21 @@ impl App { pub fn push_roster(&self) { let Some(dek) = self.dek() else { return }; - let roster = { - let state = self.state.lock().unwrap(); - RosterBlob { + let roster = Self::roster_from_state(&self.state.lock().unwrap()); + match crate::crypto::encrypt_json(&dek, "roster", &roster) { + Ok(ciphertext) => { + self.push_slot_blob("roster", Slot::latest("roster"), None, ciphertext); + } + Err(error) => tracing::error!(%error, "encrypting roster"), + } + } + + pub(crate) fn roster_from_state(state: &State) -> RosterBlob { + RosterBlob { bots: state.bots.clone(), chats: state.chats.iter().map(|c| c.meta.clone()).collect(), + device_names: state.device_names.clone(), + device_name_edits: state.device_name_edits.clone(), routines: state.routines.clone(), workflows: state.workflows.clone(), auto_review: state.auto_review.clone(), @@ -956,13 +1002,6 @@ impl App { policy_capabilities: state.policy_capabilities.clone(), deleted_bot_versions: state.deleted_bot_versions.clone(), updated_at: config::now_secs(), - } - }; - match crate::crypto::encrypt_json(&dek, "roster", &roster) { - Ok(ciphertext) => { - self.push_slot_blob("roster", Slot::latest("roster"), None, ciphertext); - } - Err(error) => tracing::error!(%error, "encrypting roster"), } } @@ -1084,7 +1123,10 @@ impl App { } pub fn device(&self, id: &str) -> Option { - self.state.lock().unwrap().devices.iter().find(|d| d.id == id).cloned() + let state = self.state.lock().unwrap(); + let mut device = state.devices.iter().find(|d| d.id == id).cloned()?; + if let Some(name) = state.device_names.get(id) { device.name = name.clone(); } + Some(device) } /// A chat's name as the apps show it: a group's title, else its members' names; a direct @@ -2270,7 +2312,8 @@ impl App { fn devices_out(&self, state: &State) -> Vec { let this_id = self.this_device_id(); let mut devices: Vec<&Device> = state.devices.iter().collect(); - devices.sort_by_key(|d| (Some(d.id.clone()) != this_id, d.name.to_lowercase())); + let name = |device: &Device| state.device_names.get(&device.id).unwrap_or(&device.name).clone(); + devices.sort_by_key(|d| (Some(d.id.clone()) != this_id, name(d).to_lowercase())); let mut out: Vec = devices .into_iter() .map(|device| { @@ -2279,7 +2322,8 @@ impl App { let status = if is_this || state.device_online.contains(&device.id) { "online" } else { "offline" }; json!({ "id": device.id, - "name": device.name, + "name": name(device), + "machine_name": device.name, "model": device.model, "os": device.os, "os_version": device.os_version, @@ -2540,6 +2584,118 @@ mod tests { assert_eq!(recovered.error_code.as_deref(),Some("response_lost")); } + #[test] + fn device_alias_preserves_machine_name_and_survives_restart() { + let scratch = scratch_app(); + let app = &scratch.0; + crate::identity::create(app, Some("Workbench".into())).unwrap(); + app.state.lock().unwrap().devices.push(Device { id: "peer".into(), name: "Machine".into(), ..Default::default() }); + app.set_device_name("peer", " Office ").unwrap(); + assert_eq!(app.device("peer").unwrap().name, "Office"); + let restarted = App::load(Config { home: scratch.1.clone(), port: 0 }).unwrap(); + let snapshot = restarted.snapshot(); + let row = snapshot["devices"].as_array().unwrap().iter().find(|d| d["id"] == "peer").unwrap(); + assert_eq!(row["name"], "Office"); + assert_eq!(row["machine_name"], "Machine"); + assert!(restarted.set_device_name("missing", "Name").is_err()); + assert!(restarted.set_device_name("peer", &"界".repeat(65)).is_err()); + restarted.set_device_name("peer", &"界".repeat(64)).unwrap(); + restarted.state.lock().unwrap().devices.iter_mut().find(|d| d.id == "peer").unwrap().name = "New machine name".into(); + restarted.set_device_name("peer", " \n ").unwrap(); + let reset = App::load(Config { home: scratch.1.clone(), port: 0 }).unwrap(); + assert!(!reset.state.lock().unwrap().device_names.contains_key("peer")); + assert_eq!(reset.device("peer").unwrap().name, "New machine name"); + } + + #[tokio::test] + async fn device_alias_api_keeps_machine_rename_and_forget_boundaries() { + let scratch = scratch_app(); + let app = &scratch.0; + crate::identity::create(app, Some("Machine".into())).unwrap(); + let id = app.this_device_id().unwrap(); + crate::api::dispatch(app, "device.set_name", json!({"id":id,"name":"Office"})).await.unwrap(); + crate::api::dispatch(app, "device.rename", json!({"name":"New machine"})).await.unwrap(); + assert_eq!(app.device(&id).unwrap().name, "Office"); + assert_eq!(app.machine_file().unwrap().name, "New machine"); + for value in [Value::Null, json!(17), json!(false)] { + assert!(crate::api::dispatch(app, "device.set_name", json!({"id":id,"name":value})).await.is_err()); + } + crate::api::dispatch(app, "device.set_name", json!({"id":id,"name":""})).await.unwrap(); + assert_eq!(app.device(&id).unwrap().name, "New machine"); + app.set_device_name(&id, "Old account").unwrap(); + app.forget_identity().unwrap(); + assert!(app.set_device_name(&id, "Late alias").is_err()); + crate::identity::create(app, Some("Replacement".into())).unwrap(); + assert!(app.state.lock().unwrap().device_names.is_empty()); + assert!(app.store.load_state().unwrap().device_names.is_empty()); + assert!(app.set_device_name(&id, "Late alias").is_err()); + } + + fn assert_device_alias_transaction_failure(table: &str, operation: &str) { + let scratch = scratch_app(); + let app = &scratch.0; + crate::identity::create(app, Some("Workbench".into())).unwrap(); + app.state.lock().unwrap().devices.push(Device { id: "peer".into(), name: "Machine".into(), ..Default::default() }); + app.set_device_name("peer", "Old alias").unwrap(); + let before = app.store.load_state().unwrap(); + let queued = app.store.queued_roster().unwrap().unwrap(); + let ancestor = serde_json::to_value(app.store.roster_baseline("queued").unwrap()).unwrap(); + let db = rusqlite::Connection::open(app.config.database_path()).unwrap(); + db.execute_batch(&format!("CREATE TRIGGER fail_alias BEFORE {operation} ON {table} BEGIN SELECT RAISE(ABORT, 'synthetic alias failure'); END;")).unwrap(); + let mut events = app.events.subscribe(); + let error = app.set_device_name("peer", "New alias").unwrap_err(); + assert!(error.to_string().contains("synthetic alias failure")); + let persisted = app.store.load_state().unwrap(); + assert_eq!(app.state.lock().unwrap().device_names, before.device_names); + assert_eq!(persisted.device_names, before.device_names); + assert_eq!(persisted.device_name_edits, before.device_name_edits); + assert_eq!(app.state.lock().unwrap().device_name_edits, before.device_name_edits); + assert_eq!(app.state.lock().unwrap().applied_blob_ids, before.applied_blob_ids); + assert_eq!(persisted.applied_blob_ids, before.applied_blob_ids); + let retained = app.store.queued_roster().unwrap().unwrap(); + assert_eq!(retained.id, queued.id); + assert_eq!(retained.ciphertext, queued.ciphertext); + assert_eq!(serde_json::to_value(app.store.roster_baseline("queued").unwrap()).unwrap(), ancestor); + assert!(matches!(events.try_recv(), Err(broadcast::error::TryRecvError::Empty))); + } + + #[test] + fn device_alias_state_failure_rejects_without_publication() { + assert_device_alias_transaction_failure("device_names", "UPDATE"); + } + + #[test] + fn device_alias_outbox_failure_rolls_back_state_and_receipt() { + assert_device_alias_transaction_failure("outbox", "UPDATE"); + } + + #[test] + fn device_alias_committed_intent_survives_dropped_app() { + let home = tempfile::tempdir().unwrap(); + let config = Config { home: home.path().into(), port: 0 }; + let (queued_id, dek, ancestor) = { + let app = App::load(config.clone()).unwrap(); + crate::identity::create(&app, Some("Workbench".into())).unwrap(); + app.state.lock().unwrap().devices.push(Device { id: "peer".into(), name: "Machine".into(), ..Default::default() }); + app.set_device_name("peer", "Office").unwrap(); + let ancestor = serde_json::to_value(app.store.roster_baseline("queued").unwrap().unwrap()).unwrap(); + let queued = app.store.queued_roster().unwrap().unwrap(); + (queued.id, app.dek().unwrap(), ancestor) + }; + // The original App and its SQLite connection are dropped before admission. + let reopened = App::load(config).unwrap(); + assert_eq!(reopened.device("peer").unwrap().name, "Office"); + let persisted = reopened.store.load_state().unwrap(); + assert_eq!(persisted.device_names.get("peer").unwrap(), "Office"); + let queued = reopened.store.queued_roster().unwrap().unwrap(); + assert_eq!(queued.id, queued_id); + assert!(persisted.applied_blob_ids.contains(&queued_id)); + assert_eq!(queued.slot, Some(Slot::latest("roster"))); + let roster: RosterBlob = crate::crypto::decrypt_json(&dek, "roster", &queued.ciphertext).unwrap(); + assert_eq!(roster.device_names, persisted.device_names); + assert_eq!(serde_json::to_value(reopened.store.roster_baseline("queued").unwrap().unwrap()).unwrap(), ancestor); + } + #[test] fn load_propagates_final_normalization_save_failure() { let home = tempfile::tempdir().unwrap(); diff --git a/crates/cli/src/local_store.rs b/crates/cli/src/local_store.rs index a249cbf1..f2ee5b29 100644 --- a/crates/cli/src/local_store.rs +++ b/crates/cli/src/local_store.rs @@ -588,6 +588,11 @@ impl LocalStore { seq INTEGER NOT NULL, json TEXT NOT NULL ); + CREATE TABLE IF NOT EXISTS device_names ( + id TEXT PRIMARY KEY NOT NULL, + position INTEGER NOT NULL, + json TEXT NOT NULL + ); CREATE TABLE IF NOT EXISTS blob_deletes ( id TEXT PRIMARY KEY NOT NULL, position INTEGER NOT NULL @@ -756,6 +761,8 @@ impl LocalStore { let policy: crate::model::RosterBlob = serde_json::from_str(&policy_json).context("decoding policy state")?; Ok(State { devices: load_json_table(&connection, "devices")?, + device_name_edits: policy.device_name_edits, + device_names: load_json_table::<(String, String)>(&connection, "device_names")?.into_iter().collect(), bots: load_json_table(&connection, "bots")?, chats: load_json_table(&connection, "chats")?, routines: load_json_table(&connection, "routines")?, @@ -785,14 +792,19 @@ impl LocalStore { } pub fn save_state(&self, state: &State) -> anyhow::Result<()> { - self.save_state_removing_device_turns(state, None) + self.save_state_removing_device_turns(state, None, None) } - pub(crate) fn save_state_removing_device_turns(&self, state: &State, device_id: Option<&str>) -> anyhow::Result<()> { + pub(crate) fn save_state_removing_device_turns(&self, state: &State, device_id: Option<&str>, roster: Option<&OutboxItem>) -> anyhow::Result<()> { let mut connection = self.connection.lock().unwrap(); let tx = connection.transaction()?; save_state_tx(&tx, state)?; if let Some(id) = device_id { tx.execute("DELETE FROM device_turns WHERE id = ?1", [id])?; } + if let Some(item) = roster { + tx.execute("INSERT OR IGNORE INTO roster_baseline (name, seq, json) SELECT 'queued', seq, json FROM roster_baseline WHERE name = 'observed'", [])?; + tx.execute("INSERT OR IGNORE INTO roster_baseline (name, seq, json) VALUES ('queued', 0, ?1)", [serde_json::to_string(&crate::model::RosterBlob::default())?])?; + queue_outbox_tx(&tx, item)?; + } tx.commit()?; Ok(()) } @@ -1535,6 +1547,9 @@ impl LocalStore { )?; } save_metadata_tx(&tx, state)?; + sync_json_table(&tx, "device_names", state.device_names.iter() + .map(|(id, name)| (id.clone(), serde_json::to_string(&(id, name)))) + .collect())?; sync_json_table( &tx, "devices", @@ -1745,6 +1760,7 @@ impl LocalStore { "outbox", "sent_jobs", "device_turns", + "device_names", ] { tx.execute(&format!("DELETE FROM {table}"), [])?; } @@ -1810,6 +1826,9 @@ fn reconcile_schedules_tx(tx: &Transaction<'_>, state: &State) -> anyhow::Result fn save_state_tx(tx: &Transaction<'_>, state: &State) -> anyhow::Result<()> { reconcile_schedules_tx(tx,state)?; save_metadata_tx(tx, state)?; + sync_json_table(tx, "device_names", state.device_names.iter() + .map(|(id, name)| (id.clone(), serde_json::to_string(&(id, name)))) + .collect())?; sync_json_table( tx, "devices", @@ -1874,6 +1893,7 @@ fn save_metadata_tx(tx: &Transaction<'_>, state: &State) -> anyhow::Result<()> { state.credentials_uploaded, state.paused, serde_json::to_string(&crate::model::RosterBlob { + device_name_edits: state.device_name_edits.clone(), policy_clock: state.policy_clock, pause_version: state.pause_version.clone(), capability_versions: state.capability_versions.clone(), diff --git a/crates/cli/src/model.rs b/crates/cli/src/model.rs index 84a5cf25..851f037b 100644 --- a/crates/cli/src/model.rs +++ b/crates/cli/src/model.rs @@ -785,6 +785,12 @@ pub struct WorkflowRecord { pub struct RosterBlob { pub bots: Vec, pub chats: Vec, + /// Account aliases keyed by Device id; machine metadata keeps the original name. + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub device_names: std::collections::BTreeMap, + /// Opaque edit ids include resets, whose alias value is absent. + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub device_name_edits: std::collections::BTreeMap, #[serde(default)] pub routines: Vec, #[serde(default)] diff --git a/crates/cli/src/sync.rs b/crates/cli/src/sync.rs index 2f67a2a0..8cd2d72c 100644 --- a/crates/cli/src/sync.rs +++ b/crates/cli/src/sync.rs @@ -717,7 +717,7 @@ async fn drain_outbox(app: &Arc, url: &str, token: &str) -> Result<(), Rela if let (Some(current), Some((_, base))) = (newer, baseline) { let dek = app.dek().ok_or_else(|| roster_conflict("account key unavailable"))?; let local: RosterBlob = crate::crypto::decrypt_json(&dek, "roster", ¤t.ciphertext).map_err(local_relay_error)?; - let base = accepted_roster_baseline(base, &roster); + let base = accepted_roster_baseline(base, &roster, None); let merged = merge_rosters(roster, &base, &local); validate_merged_groups(&merged)?; let rebased = OutboxItem { id: uuid::Uuid::new_v4().to_string(), kind: "roster".into(), recipient: None, @@ -928,11 +928,27 @@ fn commit_unpair(app: &Arc, id: &str, owner: &RelayAuthority) -> Result anyhow::Result<()> { + let mut snapshot = state.clone(); + let roster = if snapshot.device_names.remove(id).is_some() { + snapshot.device_name_edits.insert(id.to_owned(), uuid::Uuid::new_v4().to_string()); + let dek = app.dek().ok_or_else(|| anyhow::anyhow!("account key unavailable"))?; + let item = OutboxItem { id: uuid::Uuid::new_v4().to_string(), kind: "roster".into(), recipient: None, + ciphertext: crate::crypto::encrypt_json(&dek, "roster", &App::roster_from_state(&snapshot))?, + slot: Some(Slot::latest("roster")), group: None }; + crate::app::remember_applied(&mut snapshot, &item.id); + Some(item) + } else { None }; + app.store.save_state_removing_device_turns(&snapshot, Some(id), roster.as_ref())?; + *state = snapshot; + Ok(()) + })(); + Ok(persisted.map_err(local_relay_error)) }) } fn publish_unpair(app: &Arc) { + app.outbox_notify.notify_waiters(); // Ownership is released before notification; this tail cannot purge a replacement // account's turns or write its SQLite state. app.emit(app.roster_summary()); @@ -1088,16 +1104,21 @@ fn apply_incoming_blob(app: &Arc, machine_file: &crate::keys::MachineFile, |((_, base), (submitted_seq, sent))| blob.seq > *submitted_seq && sent.routines.iter().any(|routine| !base.routines.iter().any(|old| old.id == routine.id) && roster.routines.iter().any(|remote| remote.id == routine.id && remote.bot_id == routine.bot_id))); - let recovering = own_accepted || !accepted_ids.is_empty() || routine_creation_accepted; + let alias_change_accepted = baseline.as_ref().zip(submitted.as_ref()).is_some_and( + |((_, base), (submitted_seq, sent))| blob.seq > *submitted_seq + && base.device_names.keys().chain(sent.device_names.keys()) + .chain(base.device_name_edits.keys()).chain(sent.device_name_edits.keys()).any(|id| + !same_device_alias(base, sent, id) && same_device_alias(&roster, sent, id))); + let recovering = own_accepted || !accepted_ids.is_empty() || routine_creation_accepted || alias_change_accepted; let projection = match (&queue, baseline) { (Some(item), Some((_, base))) => { let queued: RosterBlob = crate::crypto::decrypt_json(&dek, "roster", &item.ciphertext).map_err(local_relay_error)?; let base = if !recovering { base } - else if own_accepted { accepted_roster_baseline(base, &roster) } + else if own_accepted { accepted_roster_baseline(base, &roster, None) } else { let (_, submitted) = submitted .ok_or_else(|| roster_conflict("accepted creation lacks its original submitted roster"))?; - accepted_roster_baseline(base, &submitted) + accepted_roster_baseline(base, &submitted, Some(&roster)) }; let projected = merge_rosters(roster.clone(), &base, &queued); validate_merged_groups(&projected)?; @@ -1394,8 +1415,13 @@ fn merge_ids(remote: &mut Vec, base: &[String], local: &[String]) { } } -// The queued snapshot describes intent relative to the last roster this Device observed. -// Compare fields, not whole entities: remote changes to other fields remain intact. +fn same_device_alias(left: &RosterBlob, right: &RosterBlob, id: &str) -> bool { + left.device_names.get(id) == right.device_names.get(id) + && left.device_name_edits.get(id) == right.device_name_edits.get(id) +} + +// The queued snapshot describes intent relative to the last observed roster. +// Compare fields, not whole entities, to preserve unrelated remote edits. fn merge_rosters(mut remote: RosterBlob, base: &RosterBlob, queued: &RosterBlob) -> RosterBlob { macro_rules! merge_entities { ($field:ident, $($member:ident),+ $(,)?) => { @@ -1416,6 +1442,20 @@ fn merge_rosters(mut remote: RosterBlob, base: &RosterBlob, queued: &RosterBlob) } }; } + // Apply only locally changed aliases; unrelated remote names and resets survive CAS rebase. + for id in base.device_names.keys().chain(queued.device_names.keys()) + .chain(base.device_name_edits.keys()).chain(queued.device_name_edits.keys()) { + if !same_device_alias(queued, base, id) { + match queued.device_name_edits.get(id) { + Some(edit) => { remote.device_name_edits.insert(id.clone(), edit.clone()); } + None => { remote.device_name_edits.remove(id); } + } + match queued.device_names.get(id) { + Some(name) => { remote.device_names.insert(id.clone(), name.clone()); } + None => { remote.device_names.remove(id); } + } + } + } merge_entities!(bots, name, description, symbol_name, accent, avatar, look, runner_id, provider, model, thinking, legacy_instructions, workdir, capabilities); merge_entities!(chats, kind, title, description, owner_bot_id, is_pinned); @@ -1453,7 +1493,7 @@ fn merge_rosters(mut remote: RosterBlob, base: &RosterBlob, queued: &RosterBlob) // Only creations from our submitted snapshot have become a common ancestor. // A later remote roster can also contain unrelated creations by other Devices. -fn accepted_roster_baseline(mut base: RosterBlob, submitted: &RosterBlob) -> RosterBlob { +fn accepted_roster_baseline(mut base: RosterBlob, submitted: &RosterBlob, observed: Option<&RosterBlob>) -> RosterBlob { macro_rules! accept_creations { ($field:ident) => { for entry in &submitted.$field { @@ -1467,6 +1507,21 @@ fn accepted_roster_baseline(mut base: RosterBlob, submitted: &RosterBlob) -> Ros accept_creations!(chats); accept_creations!(routines); accept_creations!(workflows); + // Extend the accepted ancestor only with alias intent actually submitted by this Device. + for id in base.device_names.keys().chain(submitted.device_names.keys()) + .chain(base.device_name_edits.keys()).chain(submitted.device_name_edits.keys()).cloned().collect::>() { + if same_device_alias(&base, submitted, &id) { continue; } + // A different Device's later roster proves acceptance only for matching keys. + if observed.is_some_and(|remote| !same_device_alias(remote, submitted, &id)) { continue; } + match submitted.device_name_edits.get(&id) { + Some(edit) => { base.device_name_edits.insert(id.clone(), edit.clone()); } + None => { base.device_name_edits.remove(&id); } + } + match submitted.device_names.get(&id) { + Some(name) => { base.device_names.insert(id, name.clone()); } + None => { base.device_names.remove(&id); } + } + } base } @@ -1610,6 +1665,8 @@ fn apply_roster(app: &Arc, mut roster: RosterBlob) { let kept_checks = this_device.is_some_and(|this| crate::routines::keep_checks(&state.routines, &mut roster.routines, &roster.bots, &this)); state.bots = roster.bots; state.routines = roster.routines; + state.device_name_edits = roster.device_name_edits; + state.device_names = roster.device_names; let bot_ids = state.bots.iter().map(|bot| bot.id.clone()).collect(); let admitted = crate::workflow::admit(std::mem::take(&mut roster.workflows), &state.workflows, &bot_ids); state.workflows = admitted; @@ -2171,6 +2228,54 @@ mod tests { bot } + #[test] + fn device_alias_rebase_preserves_concurrent_names_and_reset_after_restart() { + let scratch = scratch_app(); + let app = &scratch.0; + crate::identity::create(app, Some("Runner".into())).unwrap(); + let mut base = RosterBlob::default(); + base.device_names.insert("a".into(), "Old A".into()); + base.device_names.insert("b".into(), "Old B".into()); + let mut local = base.clone(); + local.device_names.insert("a".into(), "Local A".into()); + let mut remote = base.clone(); + remote.device_names.insert("b".into(), "Remote B".into()); + remote.device_names.insert("c".into(), "Remote C".into()); + let merged = merge_rosters(remote, &base, &local); + assert_eq!(merged.device_names.get("a").unwrap(), "Local A"); + assert_eq!(merged.device_names.get("b").unwrap(), "Remote B"); + assert_eq!(merged.device_names.get("c").unwrap(), "Remote C"); + apply_roster(app, merged.clone()); + let restarted = App::load(crate::config::Config { home: scratch.1.clone(), port: 0 }).unwrap(); + assert_eq!(restarted.state.lock().unwrap().device_names, merged.device_names); + let accepted = accepted_roster_baseline(base, &local, None); + local.device_names.remove("a"); + let reset = merge_rosters(merged, &accepted, &local); + assert!(!reset.device_names.contains_key("a")); + assert_eq!(reset.device_names.get("b").unwrap(), "Remote B"); + assert!(!accepted_roster_baseline(accepted, &local, None).device_names.contains_key("a")); + } + + #[test] + fn partial_alias_acceptance_does_not_advance_unmatched_keys() { + let mut base = RosterBlob::default(); + base.device_names.insert("a".into(), "Old A".into()); + base.device_names.insert("b".into(), "Old B".into()); + let mut sent = base.clone(); + sent.device_names.insert("a".into(), "Sent A".into()); + sent.device_names.insert("b".into(), "Sent B".into()); + let mut remote = sent.clone(); + remote.device_names.insert("b".into(), "Remote B".into()); + let mut queued = sent.clone(); + queued.device_names.insert("b".into(), "Old B".into()); + let accepted = accepted_roster_baseline(base, &sent, Some(&remote)); + assert_eq!(accepted.device_names.get("a").unwrap(), "Sent A"); + assert_eq!(accepted.device_names.get("b").unwrap(), "Old B"); + let merged = merge_rosters(remote, &accepted, &queued); + assert_eq!(merged.device_names.get("a").unwrap(), "Sent A"); + assert_eq!(merged.device_names.get("b").unwrap(), "Remote B"); + } + #[test] fn appearance_merge_preserves_remote_look_on_unrelated_edit_and_applies_replace_reset() { use serde_json::json; @@ -3656,6 +3761,74 @@ mod tests { assert_eq!(recovered.chats.iter().find(|chat| chat.id == "G").unwrap().title.as_deref(), Some("Local edit after upload")); } + #[test] + fn lost_alias_reply_then_reset_and_remote_overwrite_preserves_reset() { + for desired in ["", "Office"] { + let scratch = scratch_app(); + let app = &scratch.0; + crate::identity::create(app, Some("Runner".into())).unwrap(); + let initial = app.store.queued_roster().unwrap().unwrap(); + app.store.remove_outbox_roster_with_state(&initial.id, &app.state.lock().unwrap().clone(), &[]).unwrap(); + app.store.observe_roster(0, &RosterBlob::default()).unwrap(); + app.state.lock().unwrap().devices.push(Device { id: "peer".into(), name: "Machine".into(), ..Default::default() }); + app.set_device_name("peer", "Office").unwrap(); + let sent = app.store.queued_roster().unwrap().unwrap(); + let mut remote: RosterBlob = crate::crypto::decrypt_json(&app.dek().unwrap(), "roster", &sent.ciphertext).unwrap(); + app.store.record_submitted_roster(0, &remote).unwrap(); + app.set_device_name("peer", "").unwrap(); + let reopened = App::load(Config { home: scratch.1.clone(), port: 0 }).unwrap(); + remote.device_names.insert("peer".into(), "Remote".into()); + remote.device_name_edits.insert("peer".into(), "remote-edit".into()); + remote.device_names.insert("unrelated".into(), "Other".into()); + remote.device_name_edits.insert("unrelated".into(), "other-edit".into()); + let blob = BlobIn { id: "remote-overwrite".into(), kind: "roster".into(), recipient_machine_pubkey: None, + ciphertext: crate::keys::b64(&crate::crypto::encrypt_json(&reopened.dek().unwrap(), "roster", &remote).unwrap()), + seq: 2, created_at: 2 }; + // Reaffirm a reset or return to Office after resetting and restarting. + reopened.set_device_name("peer", desired).unwrap(); + let edit = reopened.state.lock().unwrap().device_name_edits["peer"].clone(); + let reopened = App::load(Config { home: scratch.1.clone(), port: 0 }).unwrap(); + assert_eq!(reopened.state.lock().unwrap().device_name_edits["peer"], edit); + apply_incoming_blob(&reopened, &reopened.machine_file().unwrap(), &blob, true).unwrap(); + assert_eq!(reopened.state.lock().unwrap().device_names.get("peer").map(String::as_str), (!desired.is_empty()).then_some(desired)); + let retained = reopened.store.queued_roster().unwrap().unwrap(); + let queued: RosterBlob = crate::crypto::decrypt_json(&reopened.dek().unwrap(), "roster", &retained.ciphertext).unwrap(); + assert_eq!(queued.device_names.get("peer").map(String::as_str), (!desired.is_empty()).then_some(desired)); + assert_eq!(queued.device_name_edits["peer"], edit); + assert_eq!(reopened.state.lock().unwrap().device_name_edits["peer"], edit); + assert_eq!(reopened.state.lock().unwrap().device_name_edits["unrelated"], "other-edit"); + assert_eq!(reopened.store.roster_baseline("observed").unwrap().unwrap().0, 2); + assert!(reopened.state.lock().unwrap().applied_blob_ids.contains(&blob.id)); + } + } + + #[test] + fn lost_alias_reply_then_reset_preserves_another_devices_name() { + let scratch = scratch_app(); + let app = &scratch.0; + crate::identity::create(app, Some("Runner".into())).unwrap(); + let initial = app.store.queued_roster().unwrap().unwrap(); + app.store.remove_outbox_roster_with_state(&initial.id, &app.state.lock().unwrap().clone(), &[]).unwrap(); + app.store.observe_roster(0, &RosterBlob::default()).unwrap(); + app.state.lock().unwrap().devices.push(Device { id: "peer".into(), name: "Machine".into(), ..Default::default() }); + app.set_device_name("peer", "Submitted").unwrap(); + let item = app.store.queued_roster().unwrap().unwrap(); + let sent: RosterBlob = crate::crypto::decrypt_json(&app.dek().unwrap(), "roster", &item.ciphertext).unwrap(); + app.store.record_submitted_roster(0, &sent).unwrap(); + app.set_device_name("peer", "").unwrap(); + let reopened = App::load(Config { home: scratch.1.clone(), port: 0 }).unwrap(); + let mut remote = sent; + remote.device_names.insert("other".into(), "Remote".into()); + let blob = BlobIn { id: "peer-alias-roster".into(), kind: "roster".into(), recipient_machine_pubkey: None, + ciphertext: crate::keys::b64(&crate::crypto::encrypt_json(&reopened.dek().unwrap(), "roster", &remote).unwrap()), + seq: 2, created_at: 2 }; + apply_incoming_blob(&reopened, &reopened.machine_file().unwrap(), &blob, true).unwrap(); + let queued = reopened.store.queued_roster().unwrap().unwrap(); + let result: RosterBlob = crate::crypto::decrypt_json(&reopened.dek().unwrap(), "roster", &queued.ciphertext).unwrap(); + assert!(!result.device_names.contains_key("peer")); + assert_eq!(result.device_names.get("other").unwrap(), "Remote"); + } + #[test] fn lost_routine_creation_reply_preserves_later_deletion_and_remote_edits() { let scratch = scratch_app(); diff --git a/crates/cli/src/sync/ownership_tests.rs b/crates/cli/src/sync/ownership_tests.rs index ae86c6df..9dfd1307 100644 --- a/crates/cli/src/sync/ownership_tests.rs +++ b/crates/cli/src/sync/ownership_tests.rs @@ -196,3 +196,31 @@ async fn unpair_ownership_network_awaits_cannot_publish_into_replacement_source( } } } + +#[test] +fn unpair_alias_intent_and_turn_removal_commit_together() { + let (home, app, owner) = fixture("http://127.0.0.1:19001"); + app.set_device_name("revoked", "Office").unwrap(); + let queued = app.store.queued_roster().unwrap().unwrap(); + let db = rusqlite::Connection::open(app.config.database_path()).unwrap(); + db.execute_batch("CREATE TRIGGER fail_alias_unpair BEFORE UPDATE ON outbox BEGIN SELECT RAISE(ABORT, 'synthetic alias unpair failure'); END;").unwrap(); + assert!(commit_unpair(&app, "revoked", &owner).unwrap().is_err()); + assert!(!app.state.lock().unwrap().devices.iter().any(|d| d.id == "revoked")); + let saved = app.store.load_state().unwrap(); + assert_eq!(saved.device_names["revoked"], "Office"); + assert!(saved.device_turns.contains_key("revoked")); + assert_eq!(app.store.queued_roster().unwrap().unwrap().id, queued.id); + db.execute_batch("DROP TRIGGER fail_alias_unpair").unwrap(); + commit_unpair(&app, "revoked", &owner).unwrap().unwrap(); + drop(db); + drop(app); + let reopened = App::load(Config { home: home.path().into(), port: 0 }).unwrap(); + let saved = reopened.store.load_state().unwrap(); + assert!(!saved.device_names.contains_key("revoked")); + assert!(!saved.device_turns.contains_key("revoked")); + let item = reopened.store.queued_roster().unwrap().unwrap(); + assert_ne!(item.id, queued.id); + assert!(saved.applied_blob_ids.contains(&item.id)); + let roster: RosterBlob = crate::crypto::decrypt_json(&reopened.dek().unwrap(), "roster", &item.ciphertext).unwrap(); + assert!(!roster.device_names.contains_key("revoked")); +} diff --git a/docs/architecture/device-names.md b/docs/architecture/device-names.md new file mode 100644 index 00000000..0b30325c --- /dev/null +++ b/docs/architecture/device-names.md @@ -0,0 +1,22 @@ +# Device names + +A Device's machine metadata holds its original name. The account's encrypted roster adds `device_names`, a map from Device id to account alias. Absent maps decode as empty. The encrypted `device_name_edits` map records an opaque UUID for each explicit edit, including resets whose alias value is absent. `App::device`, snapshots and roster events use the alias as `name`; known Device rows also expose the underlying `machine_name`. Unknown Devices keep their existing unknown presentation. Display sorting uses the effective name. + +## Local methods + +| Method | Params | Result | +| --- | --- | --- | +| `device.rename` | `name` | `name`; renames this Device's machine metadata | +| `device.set_name` | `id`, `name` | `null`; sets a known Device's account alias | + +`device.set_name` trims whitespace and accepts at most 64 Unicode scalar values. Blank text or the current machine name removes the alias. Missing or non-string names answer `missing name`; the id uses the local API's required-string validation. An unknown Device or unavailable account rejects before persistence. Existing clients retain `device.rename`; it changes the underlying machine name even when an alias currently masks it. + +## Persistence and synchronization + +Alias edits acquire the roster edit lock before account lifecycle admission. The state snapshot, encrypted latest-roster outbox item, applied receipt and frozen ancestor commit in one SQLite transaction before memory changes or events. State or queue failure leaves the previous alias and pending intent unchanged. Restart recovers the same queued intent. Forget clears the alias table with the rest of the account state. + +Roster CAS rebase applies only alias keys changed relative to the frozen baseline, preserving unrelated remote edits and resets. Before upload, the submitted roster remains durable. A known accepted upload advances the alias ancestor for its submitted keys. A later remote roster after a lost response proves acceptance only for matching keys; one matching alias does not acknowledge every submitted alias. Newer local resets survive recovery. Each explicit edit gets a fresh per-key edit id in the same transaction as the state and outbox. Merge and acceptance compare both value and edit id, so resetting and returning to an earlier value remains a newer intent. Reset edit ids remain as tombstones. Unrelated remote values and edit ids are preserved. + +Unpair keeps its account and relay ownership checks. Local membership removal, live-turn purge and any alias-removal roster intent commit together. After remote revocation, storage failure keeps membership removed in memory, retains the alias intent for retry and returns an error; retry completes persistence before dropping the retained alias. Notifications do not write account state. + +These fields do not negotiate a new relay protocol. A core predating `device_names` can discard this map when publishing its roster. Alias preservation therefore requires all roster-writing Devices to run an alias-aware core. The additive local method retains existing app compatibility; alias editors are separate client consumers. diff --git a/docs/architecture/identity.md b/docs/architecture/identity.md index 2ddb001b..6d37ef26 100644 --- a/docs/architecture/identity.md +++ b/docs/architecture/identity.md @@ -75,6 +75,7 @@ Create holds the local lifecycle boundary through key publication. When the call A machine the relay lists that never sent a `machine` blob is an unknown Device (`sync::settle_unknown_machines`): the snapshot and `roster.changed` list it after the others with `unknown: true` and no name or `os`, and the apps show Unknown Device with a note to unpair a machine nobody recognizes. Any paired Device can attest one, so none stays hidden from the Device list. A Device takes a machine for unknown only once its pull has caught up since its socket opened, so one still reading the log does not mistake the Devices whose blobs it has yet to read, and only ten minutes after the relay attested it, which is time enough for a Device that pairs to send its blob (`beans pair ` sends it before it exits). A blob that arrives later makes it a Device like any other. +Account aliases use [Device names](device-names.md). See [Device revocation](device-revocation.md) for lost, un-wiped Device boundaries and the proposed, unimplemented containment and rotation contract. ## Devices and Runners diff --git a/docs/architecture/local-api.md b/docs/architecture/local-api.md index a1a580de..3ec314ec 100644 --- a/docs/architecture/local-api.md +++ b/docs/architecture/local-api.md @@ -61,7 +61,7 @@ The required string parameters that `api.rs` reads through its `string` helper ( | `pair.status` | `nonce` | `{state:"waiting"}`, `{state:"completed",device}` or `{state:"failed",error}` | | `pair.cancel`, `pair.abort` | `nonce` (cancel only) | `null` | | `pair.accept` | `pairing_string`, `device_name?` | `id`, `name`, `os`, `identity_id` | -| `device.rename` | `name` | `name` | +| Device naming | see [Device names](device-names.md) | | | `device.unpair` | `id` (this Device's id forgets the identity) | `null` | | `device.update`, `device.auto_update` | any | always the error `SELF_UPDATE_UNAVAILABLE` | | `sync.account` | none | `providers` (masked); waits up to 30 s for the pull | diff --git a/docs/architecture/protocols.md b/docs/architecture/protocols.md index 4c80c1a4..cb5d96ea 100644 --- a/docs/architecture/protocols.md +++ b/docs/architecture/protocols.md @@ -26,6 +26,8 @@ All sealed remote request verbs wrap their body in `{ payload, signature }`. The Custom credentials and provider statuses add optional `capabilities { context_window?, images?, tools? }`; status deserialization defaults absent declarations. Positive integer context windows and boolean/null support values are validated before HTTP. Omitted saves keep declarations, null clears them, objects replace them. Model statuses carry effective declarations ahead of discovery; declaration status separately lets sheets reopen Unknown/Yes/No choices. This is an additive protocol-5 field, without storage-format or home migration. +Account alias merge and recovery: [Device names](device-names.md). + ## CLI ↔ relay - Account requests, including registration, challenge/verify, pairing mailboxes and the sync socket upgrade, require exactly one `Beans-Protocol: 5` and one `Beans-Format: beans-v2` capability. Missing, malformed or duplicated capabilities fail closed before account effects. `User-Agent: beans/ ()` belongs to the relay client, never a provider. Protocol 5 is the incompatible fresh Beans boundary; it retains paging, attestation, durable policy actions, roster CAS and appearance preservation. Health advertises `format: "beans-v2"`, `protocol`, effective `min_protocol` and `min_roster_protocol`, both at least 5 regardless of an operator lowering the setting. Clients reject missing, malformed, wrong-format or unsupported evidence before sync or pairing. Older account requests receive `426`; there is no old-protocol account-route exception. Public health and plaintext catalogs remain separate from account routes.