Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
fix(core): only a device you pair can take over an older pairing
Bee68a97e500daa
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rsindex 6ff6cd9..4197c4c 100644--- a/core/nectarlink-core/src/node.rs+++ b/core/nectarlink-core/src/node.rs@@ -924,24 +924,33 @@ impl Shared {// The same physical device paired again (after a reinstall it has a new identity):// move its history and queue to the new pairing and forget the old one. Only the// install ID decides; same-name devices (two family phones) stay separate.- if let Some(install_id) = info.install_id.as_deref()- && let Ok(existing_peers) = self.store.list_peers()- {- for old in existing_peers {- if old.id != peer- && self.session(&old.id).is_none()- && old.info.kind == info.kind- && old.info.install_id.as_deref() == Some(install_id)- {- let _ = self.store.reassign_timeline(&old.id, &peer);- if self.store.reassign_send_queue_peer(&old.id, &peer).unwrap_or(0) > 0 {- reassigned_queue = true;- }- let _ = self.forget_peer(&old.id).await;- }- }- }+ let replaced: Vec<DeviceId> = match info.install_id.as_deref() {+ Some(install_id) => self+ .store+ .list_peers()+ .unwrap_or_default()+ .into_iter()+ .filter(|old| {+ old.id != peer+ && self.session(&old.id).is_none()+ && old.info.kind == info.kind+ && old.info.install_id.as_deref() == Some(install_id)+ })+ .map(|old| old.id)+ .collect(),+ None => Vec::new(),+ };+ // Store the new pairing first: if that fails, the old one is untouched.+ // Storing it also moves the old entry's history and queue over.self.store.upsert_peer(&peer, &info, paired_at)?;+ for old in replaced {+ let _ = self.store.reassign_timeline(&old, &peer);+ let _ = self.store.reassign_send_queue_peer(&old, &peer);+ reassigned_queue = true;+ let _ = self.forget_peer(&old).await;+ // Its row is already gone, so forget_peer doesn't announce it.+ self.emit(NodeEvent::DeviceRemoved(old));+ }tracing::info!(peer = %peer.short(), "paired");let device = PairedDevice {id: peer,diff --git a/core/nectarlink-core/src/store.rs b/core/nectarlink-core/src/store.rsindex b2770a8..f90f348 100644--- a/core/nectarlink-core/src/store.rs+++ b/core/nectarlink-core/src/store.rs@@ -682,14 +682,17 @@ impl Store {}/// Updates the stored description of a device (e.g. after a rename).+ ///+ /// Never its install ID: that is recorded only when the user pairs the+ /// device, so a paired device can't later claim to be another one and+ /// take over its pairing and history.pub fn update_info(&self, id: &DeviceId, info: &DeviceInfo) -> Result<()> {let screen = encode_screen(info.screen.as_ref());self.with(|c| {c.execute("UPDATE peers SET name = ?2, kind = ?3, os = ?4, os_ver = ?5, model = ?6,accent = COALESCE(?7, accent),- screen = CASE WHEN ?8 = '' THEN screen ELSE ?8 END,- install_id = COALESCE(?9, install_id)+ screen = CASE WHEN ?8 = '' THEN screen ELSE ?8 ENDWHERE id = ?1",params![id.as_bytes().as_slice(),@@ -700,13 +703,8 @@ impl Store {info.model,info.accent.map(i64::from),screen,- valid_install_id(info)],)?;- if valid_install_id(info).is_some() {- cleanup_peers(c, Some(id))?;- self.toggle_cache().clear();- }c.execute("UPDATE timeline SET device_name = ?2 WHERE device_id = ?1",params![id.as_bytes().as_slice(), info.name],@@ -3311,6 +3309,32 @@ mod tests {assert_eq!(store.list_peers().unwrap().len(), 3);}+ #[test]+ fn a_paired_device_cannot_claim_another_ones_install_id_later() {+ let dir = tempfile::tempdir().unwrap();+ let store = Store::open(dir.path()).unwrap();+ let (phone, other) = (DeviceId([0x01; 32]), DeviceId([0x02; 32]));+ let mut mine = info("My Phone");+ mine.install_id = Some("0123456789abcdef0123456789abcdef".into());+ let mut theirs = info("Their Phone");+ theirs.install_id = Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into());+ store.upsert_peer(&phone, &mine, 100).unwrap();+ store.upsert_peer(&other, &theirs, 200).unwrap();++ // On a later connection the other device reports this phone's install ID.+ let mut claimed = theirs.clone();+ claimed.install_id = mine.install_id.clone();+ store.update_info(&other, &claimed).unwrap();+ // Nor at the next start, when duplicates are merged.+ drop(store);+ let store = Store::open(dir.path()).unwrap();++ let mut peers = store.list_peers().unwrap();+ peers.sort_by_key(|p| p.id.0);+ assert_eq!(peers.iter().map(|p| p.id).collect::<Vec<_>>(), vec![phone, other], "both stay paired");+ assert_eq!(peers[1].info.install_id, theirs.install_id, "its own install ID is kept");+ }+#[test]fn send_queue_fifo_clipboard_replacement_capacity_ttl_recovery_and_reassign() {let store = Store::in_memory().unwrap();diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex 5c2cf39..d7be4b4 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -6325,3 +6325,52 @@ async fn bench_file_throughput() {pc.node.shutdown().await;phone.node.shutdown().await;}++/// A phone whose app reports `install_id` (the same on this phone after a reinstall).+async fn phone_with_install_id(name: &'static str, install_id: &str) -> TestDevice {+ init_logging();+ let dir = tempfile::tempdir().unwrap();+ let mut phone_info = info(name, DeviceKind::Phone);+ phone_info.install_id = Some(install_id.into());+ let mut config = NodeConfig::new(dir.path(), phone_info, "0.0.1-test");+ config.lan_discovery = false;+ config.away_mode = false;+ config.key_protector = Some(Arc::new(PlainKeyProtector));+ config.capabilities = vec!["media.control".into()];+ let platform = Arc::new(RecordingPlatform::default());+ let node = Node::start(config, platform.clone()).await.expect("node starts");+ let events = node.events();+ TestDevice { node, events, platform, dir, name }+}++#[tokio::test(flavor = "multi_thread")]+async fn a_reinstalled_phone_replaces_its_old_pairing() {+ const INSTALL: &str = "0123456789abcdef0123456789abcdef";+ let mut pc = device("pc", DeviceKind::Desktop).await;+ let mut old = phone_with_install_id("phone", INSTALL).await;+ pair_qr(&mut pc, &mut old).await;+ let old_id = old.node.device_id();+ old.node.shutdown().await;+ wait_for(&mut pc, "old phone offline", |e| match e {+ NodeEvent::LinkChanged { device, link: LinkState::Offline { .. } } if *device == old_id => Some(()),+ _ => None,+ })+ .await;++ // Reinstalled: a new identity, the same install ID. Pairing it replaces the old entry.+ let mut new = phone_with_install_id("phone", INSTALL).await;+ let mut pc_events = pc.node.events();+ pair_qr(&mut pc, &mut new).await;+ let new_id = new.node.device_id();+ let mut removed = false;+ while let Ok(event) = pc_events.try_recv() {+ removed |= matches!(event, NodeEvent::DeviceRemoved(device) if device == old_id);+ }+ assert!(removed, "the old entry is announced as removed");+ let ids: Vec<nectarlink_core::DeviceId> =+ pc.node.paired_devices().unwrap().into_iter().map(|d| d.id).collect();+ assert_eq!(ids, vec![new_id]);++ pc.node.shutdown().await;+ new.node.shutdown().await;+}