garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

cartopolis-agent · 2026-11-30T15:13:21Z

feat(bluetooth): keep this device's identity, and paired devices' keys

The bt service makes this device's identity resolving key once and keeps
it in the vault (data:/bt/identity), handing it to every device it pairs
with, so they know it whatever happens to its address. Bonds are read and
written at their own length, with the peer's IRK where it gave one; the
ones kept before still read. After a pairing the device list goes to the
apps again, so a device that paired from a private address is listed by
its identity.

Sync keeps data:/bt/identity on its device, as it does the bonds: a second
device with the same identity would pass for this one.
docs/backup-and-sync.md |  1 +
 programs/src/bin/bt.rs  | 79 +++++++++++++++++++++++++++++++++++--------------
 sync/src/lib.rs         |  2 +-
 sync/src/tests.rs       | 16 ++++++++++
 4 files changed, 74 insertions(+), 24 deletions(-)

diff --git a/docs/backup-and-sync.md b/docs/backup-and-sync.md
index 914dab6..d13fd0c 100644
--- a/docs/backup-and-sync.md
+++ b/docs/backup-and-sync.md
@@ -48,6 +48,7 @@ Every file in the vault (`data:/`), but what belongs to one device:
 |---|---|
 | `data:/p2p/identity` | Each device keeps its own identity key, so a lost one can be dropped alone and its key never travels. |
 | `data:/bt/bonds` | A Bluetooth bond is the key of one radio with one other radio. |
+| `data:/bt/identity` | This device's Bluetooth identity key: devices paired with know it by it, and a second device with it would pass for this one. |
 | `data:/sync/` | The sync service's own state: what each device last agreed on. |
 
 So the apps' folders (`data:/apps/notes`, …), the address book and the
diff --git a/programs/src/bin/bt.rs b/programs/src/bin/bt.rs
index 2cd248f..496d5c5 100644
--- a/programs/src/bin/bt.rs
+++ b/programs/src/bin/bt.rs
@@ -9,8 +9,11 @@
 //! pair with a connected device, the number to compare goes to the apps
 //! (and, asked by a device nearby while no app listens, to a notification
 //! that opens Bluetooth), and each device paired with is kept in the data
-//! vault (`data:/bt/bonds`: its address, key and name), so its link is
-//! encrypted again on every connection without asking.
+//! vault (`data:/bt/bonds`: its address, key, identity key and name), so
+//! its link is encrypted again on every connection without asking, and a
+//! phone or watch that moves to a new private address is still known. This
+//! device's own identity key, handed to each device it pairs with, is made
+//! once and kept beside them (`data:/bt/identity`).
 
 #![no_std]
 #![no_main]
@@ -49,27 +52,42 @@ fn services(card: &[u8]) -> Vec<Service> {
     ]
 }
 
-/// Where the paired devices are kept: in the vault, once there is one.
-fn bonds_path() -> &'static str {
+/// Where Bluetooth keeps `what` (the paired devices, this device's
+/// identity): in the vault, once there is one.
+fn kept(what: &str) -> String {
     if fs::disk("data").is_some() {
-        "data:/bt/bonds"
+        alloc::format!("data:/bt/{what}")
     } else {
-        "system:/bt-bonds"
+        alloc::format!("system:/bt-{what}")
     }
 }
 
+/// This device's identity resolving key, made once and kept: devices
+/// paired with know it by it, so it must not change between starts.
+fn identity() -> [u8; 16] {
+    let path = kept("identity");
+    if let Some(irk) = fs::read(&path).and_then(|b| <[u8; 16]>::try_from(b.as_slice()).ok()) {
+        return irk;
+    }
+    let mut irk = [0u8; 16];
+    pinnacle_rt::random(&mut irk);
+    fs::create_dir(path.rsplit_once('/').map_or("system:/", |(dir, _)| dir));
+    fs::write(&path, &irk);
+    irk
+}
+
 /// The paired devices kept: each a bond, a name length and the name.
 fn load_bonds() -> Vec<(Bond, String)> {
-    let b = fs::read(bonds_path()).unwrap_or_default();
+    let b = fs::read(&kept("bonds")).unwrap_or_default();
     let mut out = Vec::new();
     let mut at = 0;
-    while let Some(bond) = b.get(at..at + Bond::SIZE).and_then(Bond::from_bytes) {
-        let len = b.get(at + Bond::SIZE).copied().unwrap_or(0) as usize;
-        let Some(name) = b.get(at + Bond::SIZE + 1..at + Bond::SIZE + 1 + len) else {
+    while let Some((bond, size)) = b.get(at..).and_then(Bond::from_bytes) {
+        let len = b.get(at + size).copied().unwrap_or(0) as usize;
+        let Some(name) = b.get(at + size + 1..at + size + 1 + len) else {
             break;
         };
         out.push((bond, String::from_utf8_lossy(name).into_owned()));
-        at += Bond::SIZE + 1 + len;
+        at += size + 1 + len;
     }
     out
 }
@@ -82,9 +100,9 @@ fn save_bonds(bonds: &[(Bond, String)]) {
         b.push(name.len() as u8);
         b.extend_from_slice(name);
     }
-    let path = bonds_path();
+    let path = kept("bonds");
     fs::create_dir(path.rsplit_once('/').map_or("system:/", |(dir, _)| dir));
-    fs::write(path, &b);
+    fs::write(&path, &b);
 }
 
 fn bonds_bytes(bonds: &[(Bond, String)]) -> Vec<u8> {
@@ -100,12 +118,14 @@ fn bonds_bytes(bonds: &[(Bond, String)]) -> Vec<u8> {
 }
 
 /// A host for this device: its name, its services, pairing on (fresh
-/// secrets from the kernel, a screen with yes and no), the bonds kept.
-fn new_host(name: &str, card: &[u8], bonds: &[(Bond, String)]) -> Host {
+/// secrets from the kernel, a screen with yes and no, its identity), the
+/// bonds kept.
+fn new_host(name: &str, card: &[u8], irk: [u8; 16], bonds: &[(Bond, String)]) -> Host {
     let mut host = Host::new(name, services(card));
     let mut seed = [0u8; 32];
     pinnacle_rt::random(&mut seed);
     host.enable_pairing(seed, smp::DISPLAY_YES_NO);
+    host.set_identity(irk);
     for (bond, _) in bonds {
         host.remember(*bond);
     }
@@ -113,6 +133,17 @@ fn new_host(name: &str, card: &[u8], bonds: &[(Bond, String)]) -> Host {
     host
 }
 
+/// The devices heard, for [`protocol::DEVICES_ARE`]: paired ones by their
+/// identity, whatever address they moved to.
+fn devices_bytes(host: &Host) -> Vec<u8> {
+    let found = host.found();
+    let mut b = alloc::vec![found.len().min(255) as u8];
+    for f in found.iter().take(255) {
+        b.extend(protocol::device_bytes(f.address, f.rssi, f.name.as_deref()));
+    }
+    b
+}
+
 fn said(clients: &[Channel], kind: u8, body: &[u8]) {
     let m = protocol::message(kind, body);
     for c in clients {
@@ -141,7 +172,8 @@ fn main(_argument: u64) -> u64 {
     let mut pending = Vec::new();
     let card = p2p.as_ref().map(|c| c.card(&mut pending)).unwrap_or_default();
     let mut bonds = load_bonds();
-    let mut host = new_host(&name, &card, &bonds);
+    let irk = identity();
+    let mut host = new_host(&name, &card, irk, &bonds);
     // A pairing asked by a device nearby, waiting on the person: told to
     // every app that connects until it is answered.
     let mut asking: Option<Vec<u8>> = None;
@@ -172,7 +204,7 @@ fn main(_argument: u64) -> u64 {
                 host.poll(now);
                 if !host.ready() && now >= started + READY_RETRY_MS {
                     // Ask again: the first reset may have gone nowhere.
-                    host = new_host(&name, &card, &bonds);
+                    host = new_host(&name, &card, irk, &bonds);
                     started = now;
                 }
             }
@@ -221,12 +253,10 @@ fn main(_argument: u64) -> u64 {
                         }
                     }
                     (protocol::DEVICES, _) => {
-                        let found = host.found();
-                        let mut b = alloc::vec![found.len().min(255) as u8];
-                        for f in found.iter().take(255) {
-                            b.extend(protocol::device_bytes(f.address, f.rssi, f.name.as_deref()));
-                        }
-                        clients[index - 2].send(&protocol::message(protocol::DEVICES_ARE, &b), Vec::new());
+                        clients[index - 2].send(
+                            &protocol::message(protocol::DEVICES_ARE, &devices_bytes(&host)),
+                            Vec::new(),
+                        );
                     }
                     (protocol::PAIR, Some(c)) => host.pair(c),
                     (protocol::CONFIRM, Some(c)) => {
@@ -421,6 +451,9 @@ fn main(_argument: u64) -> u64 {
                     b.push(u8::from(bond.compared));
                     said(&clients, protocol::PAIRED, &b);
                     said(&clients, protocol::BONDS_ARE, &bonds_bytes(&bonds));
+                    // A device paired from a private address is listed by
+                    // its identity from now on.
+                    said(&clients, protocol::DEVICES_ARE, &devices_bytes(&host));
                 }
                 Event::PairingFailed {
                     connection,
diff --git a/sync/src/lib.rs b/sync/src/lib.rs
index 40c84d3..74011bb 100644
--- a/sync/src/lib.rs
+++ b/sync/src/lib.rs
@@ -49,7 +49,7 @@ const NAME_MAX: usize = 58;
 /// What is kept in step: every path in the vault but what belongs to one
 /// device. Paths are the vault's (`/apps/notes/x`, no `data:`).
 pub fn synced(path: &str) -> bool {
-    !(path == "/p2p/identity" || path == "/bt/bonds" || path.starts_with("/sync/"))
+    !(path == "/p2p/identity" || path == "/bt/bonds" || path == "/bt/identity" || path.starts_with("/sync/"))
 }
 
 /// A file as one device has it.
diff --git a/sync/src/tests.rs b/sync/src/tests.rs
index e244efd..ec7318d 100644
--- a/sync/src/tests.rs
+++ b/sync/src/tests.rs
@@ -400,3 +400,19 @@ fn a_backup_restores_and_says_nothing() {
     bad[0] ^= 1;
     assert!(backup::open_blob(&key, &index[0].hash, &bad).is_none());
 }
+
+/// Each device's Bluetooth identity and bonds stay its own: another device
+/// with the same identity would answer as this one.
+#[test]
+fn bluetooth_keys_stay_on_their_device() {
+    let mut laptop = Disk::with(&[
+        ("/apps/notes/shopping", "bread\n"),
+        ("/bt/identity", "laptop's radio"),
+        ("/bt/bonds", "laptop's bonds"),
+    ]);
+    let mut phone = Disk::with(&[("/bt/identity", "phone's radio")]);
+    sync(&mut laptop, &mut phone, &[], None);
+    assert_eq!(phone.text("/apps/notes/shopping"), Some("bread\n"));
+    assert_eq!(phone.text("/bt/identity"), Some("phone's radio"));
+    assert_eq!(phone.text("/bt/bonds"), None);
+}