Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Make pairing completion acknowledged and add the CLI
Beefea8a2d538df
diff --git a/Cargo.lock b/Cargo.lockindex 73e018e..350e98e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -70,6 +70,62 @@ dependencies = ["libc",]+[[package]]+name = "anstream"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"+dependencies = [+ "anstyle",+ "anstyle-parse",+ "anstyle-query",+ "anstyle-wincon",+ "colorchoice",+ "is_terminal_polyfill",+ "utf8parse",+]++[[package]]+name = "anstyle"+version = "1.0.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"++[[package]]+name = "anstyle-parse"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"+dependencies = [+ "utf8parse",+]++[[package]]+name = "anstyle-query"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "anstyle-wincon"+version = "3.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"+dependencies = [+ "anstyle",+ "once_cell_polyfill",+ "windows-sys 0.61.2",+]++[[package]]+name = "anyhow"+version = "1.0.104"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"+[[package]]name = "arc-swap"version = "1.9.2"@@ -292,6 +348,46 @@ dependencies = ["inout",]+[[package]]+name = "clap"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"+dependencies = [+ "clap_builder",+ "clap_derive",+]++[[package]]+name = "clap_builder"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"+dependencies = [+ "anstream",+ "anstyle",+ "clap_lex",+ "strsim",+]++[[package]]+name = "clap_derive"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "clap_lex"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"+[[package]]name = "cmov"version = "0.5.4"@@ -307,6 +403,12 @@ dependencies = ["thiserror 2.0.21",]+[[package]]+name = "colorchoice"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"+[[package]]name = "combine"version = "4.6.8"@@ -545,6 +647,27 @@ dependencies = ["ctutils",]+[[package]]+name = "dirs"+version = "7.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f"+dependencies = [+ "dirs-sys",+]++[[package]]+name = "dirs-sys"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"+dependencies = [+ "libc",+ "option-ext",+ "redox_users",+ "windows-sys 0.61.2",+]+[[package]]name = "dispatch2"version = "0.3.1"@@ -974,6 +1097,17 @@ dependencies = ["digest",]+[[package]]+name = "hostname"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"+dependencies = [+ "cfg-if",+ "libc",+ "windows-link",+]+[[package]]name = "http"version = "1.5.0"@@ -1464,6 +1598,12 @@ dependencies = ["ws_stream_wasm",]+[[package]]+name = "is_terminal_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"+[[package]]name = "itoa"version = "1.0.18"@@ -1567,6 +1707,15 @@ version = "0.2.190"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"+[[package]]+name = "libredox"+version = "0.1.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"+dependencies = [+ "libc",+]+[[package]]name = "libsqlite3-sys"version = "0.38.2"@@ -1753,7 +1902,15 @@ checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"name = "nectarlink-cli"version = "0.0.1"dependencies = [+ "anyhow",+ "clap",+ "dirs",+ "hostname","nectarlink-core",+ "qrcode",+ "tokio",+ "tracing",+ "tracing-subscriber",][[package]]@@ -2167,6 +2324,12 @@ dependencies = ["portable-atomic",]+[[package]]+name = "once_cell_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"+[[package]]name = "opaque-debug"version = "0.3.1"@@ -2179,6 +2342,12 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"+[[package]]+name = "option-ext"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"+[[package]]name = "papaya"version = "0.2.5"@@ -2411,6 +2580,12 @@ dependencies = ["unicode-ident",]+[[package]]+name = "qrcode"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"+[[package]]name = "quick-xml"version = "0.42.0"@@ -2470,6 +2645,16 @@ dependencies = ["bitflags",]+[[package]]+name = "redox_users"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0"+dependencies = [+ "libredox",+ "thiserror 2.0.21",+]+[[package]]name = "regex-automata"version = "0.4.18"@@ -2954,6 +3139,12 @@ version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"+[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"+[[package]]name = "strum"version = "0.28.0"@@ -3457,6 +3648,12 @@ version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"+[[package]]+name = "utf8parse"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"+[[package]]name = "valuable"version = "0.1.1"diff --git a/Cargo.toml b/Cargo.tomlindex fd791bd..90cf90a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -21,10 +21,13 @@ anyhow = "1"ciborium = "0.2"clap = { version = "4.6", features = ["derive"] }data-encoding = "2.11"+dirs = "7"+hostname = "0.4"hmac = "0.13"iroh = "1.3"iroh-mdns-address-lookup = "0.6"n0-future = "0.3"+qrcode = { version = "0.14", default-features = false }rand = "0.10"rusqlite = { version = "0.40", features = ["bundled"] }serde = { version = "1", features = ["derive"] }diff --git a/core/nectarlink-cli/Cargo.toml b/core/nectarlink-cli/Cargo.tomlindex d516245..d969991 100644--- a/core/nectarlink-cli/Cargo.toml+++ b/core/nectarlink-cli/Cargo.toml@@ -14,6 +14,14 @@ path = "src/main.rs"[dependencies]nectarlink-core.workspace = true+anyhow.workspace = true+clap = { workspace = true, features = ["env"] }+dirs.workspace = true+hostname.workspace = true+qrcode.workspace = true+tokio = { workspace = true, features = ["signal"] }+tracing.workspace = true+tracing-subscriber.workspace = true[lints]workspace = truediff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex 2af84e4..20a5a9b 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -1,2 +1,364 @@// SPDX-License-Identifier: GPL-3.0-or-later-fn main() {}+//! `nectarlink`: a command-line client for development, testing and scripting.+//!+//! It runs its own node with its own identity (separate from the desktop+//! app), so it can pair with phones, PCs or another CLI instance.++use std::{io::Write, net::SocketAddr, path::PathBuf, sync::Arc, time::Duration};++use anyhow::{Context, Result, bail};+use clap::{Parser, Subcommand};+use nectarlink_core::{+ DeviceId, DeviceInfo, DeviceKind, LinkState, Node, NodeConfig, NodeEvent, PairedDevice, PairingEvent,+ Platform,+};+use tokio::sync::broadcast::error::RecvError;++#[derive(Parser, Debug)]+#[command(name = "nectarlink", version, about = "Nectarlink command-line client")]+struct Cli {+ /// Where this client keeps its identity and paired devices.+ #[arg(long, global = true, env = "NECTARLINK_DATA_DIR")]+ data_dir: Option<PathBuf>,+ /// Name announced to other devices (defaults to the computer name).+ #[arg(long, global = true)]+ name: Option<String>,+ /// Fixed UDP port to listen on (default: any).+ #[arg(long, global = true, default_value_t = 0)]+ port: u16,+ /// Disable discovery on the local network (mDNS).+ #[arg(long, global = true)]+ no_lan: bool,+ /// Allow connections through relay servers when away from home.+ #[arg(long, global = true)]+ away: bool,+ /// Log verbosity (error, warn, info, debug, trace).+ #[arg(long, global = true, default_value = "warn")]+ log: String,+ #[command(subcommand)]+ command: Command,+}++#[derive(Subcommand, Debug)]+enum Command {+ /// Print this device's ID and addresses.+ Id,+ /// Show a pairing code and wait for a device to pair.+ Pair,+ /// Pair with a device using its pairing link.+ Join { link: String },+ /// Pair with a nearby device by comparing a 6-digit code.+ Nearby {+ /// Device ID to pair with (omit to list devices found on the network).+ device: Option<String>,+ /// Seconds to search for devices when listing.+ #[arg(long, default_value_t = 5)]+ wait: u64,+ },+ /// List paired devices and whether they're connected.+ Devices {+ /// Seconds to wait for connections before printing.+ #[arg(long, default_value_t = 3)]+ wait: u64,+ },+ /// Ring a paired device (find my device).+ Ring {+ device: String,+ /// Stop ringing instead.+ #[arg(long)]+ off: bool,+ },+ /// Tell a device where to reach this one (when discovery is blocked).+ Connect {+ device: String,+ /// Address like 192.168.1.20:41641 (repeatable).+ #[arg(required = true)]+ addrs: Vec<SocketAddr>,+ },+ /// Unpair a device.+ Unpair { device: String },+ /// Stay online and print events until Ctrl+C.+ Run,+}++/// Rings by printing to the terminal (the CLI has no speaker access).+#[derive(Debug)]+struct TerminalPlatform;++impl Platform for TerminalPlatform {+ fn start_ringing(&self) {+ println!("\x07🔔 Ringing! (stop it from the other device)");+ }+ fn stop_ringing(&self) {+ println!("🔕 Stopped ringing.");+ }+}++#[tokio::main]+async fn main() -> Result<()> {+ let cli = Cli::parse();+ tracing_subscriber::fmt()+ .with_env_filter(tracing_subscriber::EnvFilter::try_new(&cli.log).unwrap_or_else(|_| "warn".into()))+ .with_writer(std::io::stderr)+ .init();++ let node = start_node(&cli).await?;+ let result = run(&cli, &node).await;+ node.shutdown().await;+ result+}++async fn start_node(cli: &Cli) -> Result<Node> {+ let data_dir = match &cli.data_dir {+ Some(dir) => dir.clone(),+ None => dirs::data_local_dir().context("no local data directory")?.join("Nectarlink").join("cli"),+ };+ let name = cli.name.clone().unwrap_or_else(|| {+ hostname::get().ok().and_then(|h| h.into_string().ok()).unwrap_or_else(|| "Nectarlink CLI".into())+ });+ let device = DeviceInfo {+ name,+ kind: DeviceKind::Desktop,+ os: std::env::consts::OS.into(),+ os_ver: String::new(),+ model: None,+ accent: None,+ };+ let mut config = NodeConfig::new(data_dir, device, env!("CARGO_PKG_VERSION"));+ config.port = cli.port;+ config.lan_discovery = !cli.no_lan;+ config.away_mode = cli.away;+ Node::start(config, Arc::new(TerminalPlatform)).await.context("failed to start")+}++async fn run(cli: &Cli, node: &Node) -> Result<()> {+ match &cli.command {+ Command::Id => {+ println!("Device ID: {}", node.device_id());+ for addr in node.direct_addrs().await {+ println!("Address: {addr}");+ }+ }+ Command::Pair => pair(node).await?,+ Command::Join { link } => {+ println!("Pairing…");+ node.pairing_join(link).await.context("pairing failed")?;+ println!("✓ Paired.");+ }+ Command::Nearby { device: None, wait } => {+ println!("Looking for devices on this network for {wait}s…");+ tokio::time::sleep(Duration::from_secs(*wait)).await;+ let found = node.discovered_devices();+ if found.is_empty() {+ println!("No devices found. Make sure the other device is showing its pairing screen.");+ }+ for d in found {+ println!("{} {}", d.id, d.name.as_deref().unwrap_or("(unnamed)"));+ }+ }+ Command::Nearby { device: Some(device), .. } => nearby(node, parse_id(device)?).await?,+ Command::Devices { wait } => {+ tokio::time::sleep(Duration::from_secs(*wait)).await;+ let devices = node.paired_devices()?;+ if devices.is_empty() {+ println!("No paired devices. Run `nectarlink pair` to pair one.");+ }+ for d in devices {+ print_device(&d);+ }+ }+ Command::Ring { device, off } => {+ let id = resolve(node, device)?;+ wait_until_online(node, id).await?;+ node.ring(id, !off).await.context("ring failed")?;+ println!("{}", if *off { "Stopped ringing." } else { "Ringing…" });+ }+ Command::Connect { device, addrs } => {+ let id = resolve(node, device)?;+ node.add_known_addrs(id, addrs);+ wait_until_online(node, id).await?;+ println!("✓ Connected.");+ }+ Command::Unpair { device } => {+ let id = resolve(node, device)?;+ node.unpair(id).await?;+ println!("✓ Unpaired.");+ }+ Command::Run => watch(node).await?,+ }+ Ok(())+}++async fn pair(node: &Node) -> Result<()> {+ let mut events = node.events();+ let link = node.pairing_start_qr().await?;+ let uri = link.to_uri();+ print_qr(&uri);+ println!("\nScan this code in the Nectarlink app, or run on another machine:");+ println!(" nectarlink join \"{uri}\"\n");+ println!("Waiting for a device (pairing mode ends in 5 minutes)…");+ loop {+ match events.recv().await {+ Ok(NodeEvent::Pairing(PairingEvent::Paired(d))) => {+ println!("✓ Paired with {}.", d.info.name);+ return Ok(());+ }+ Ok(NodeEvent::Pairing(PairingEvent::SasCode { code, .. })) => {+ node.pairing_confirm(confirm_code(code).await?)?;+ }+ Ok(NodeEvent::Pairing(PairingEvent::Failed(why))) => bail!("pairing failed: {why:?}"),+ Ok(_) | Err(RecvError::Lagged(_)) => {}+ Err(RecvError::Closed) => bail!("node stopped"),+ }+ }+}++async fn nearby(node: &Node, peer: DeviceId) -> Result<()> {+ let mut events = node.events();+ let mut task = {+ let node = node.clone();+ tokio::spawn(async move { node.pairing_start_nearby(peer).await })+ };+ loop {+ tokio::select! {+ result = &mut task => {+ result.context("pairing task failed")?.context("pairing failed")?;+ println!("✓ Paired.");+ return Ok(());+ }+ event = events.recv() => match event {+ Ok(NodeEvent::Pairing(PairingEvent::SasCode { code, .. })) => {+ node.pairing_confirm(confirm_code(code).await?)?;+ }+ Ok(_) | Err(RecvError::Lagged(_)) => {}+ Err(RecvError::Closed) => bail!("node stopped"),+ }+ }+ }+}++/// Asks the user to compare the 6-digit code (stdin is read off the runtime).+async fn confirm_code(code: String) -> Result<bool> {+ tokio::task::spawn_blocking(move || -> Result<bool> {+ print!("Does the other device show {} {}? [y/N] ", &code[..3], &code[3..]);+ std::io::stdout().flush()?;+ let mut answer = String::new();+ std::io::stdin().read_line(&mut answer)?;+ Ok(matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes"))+ })+ .await?+}++async fn watch(node: &Node) -> Result<()> {+ println!("Online as {}. Press Ctrl+C to stop.", node.device_id());+ for d in node.paired_devices()? {+ print_device(&d);+ }+ let mut events = node.events();+ loop {+ tokio::select! {+ _ = tokio::signal::ctrl_c() => return Ok(()),+ event = events.recv() => match event {+ Ok(event) => print_event(node, &event),+ Err(RecvError::Lagged(n)) => println!("(missed {n} events)"),+ Err(RecvError::Closed) => return Ok(()),+ }+ }+ }+}++fn print_event(node: &Node, event: &NodeEvent) {+ let name = |id: &DeviceId| {+ node.paired_devices()+ .ok()+ .and_then(|ds| ds.into_iter().find(|d| d.id == *id).map(|d| d.info.name))+ .unwrap_or_else(|| id.short())+ };+ match event {+ NodeEvent::LinkChanged { device, link } => println!("{}: {}", name(device), describe_link(link)),+ NodeEvent::Battery { device, battery } => println!(+ "{}: battery {}%{}",+ name(device),+ battery.level,+ if battery.charging { " (charging)" } else { "" }+ ),+ NodeEvent::Ring { device, on } => {+ println!("{}: {}", name(device), if *on { "asked us to ring" } else { "stopped ringing" })+ }+ NodeEvent::DeviceAdded(d) => println!("Paired with {}", d.info.name),+ NodeEvent::DeviceRemoved(id) => println!("{} unpaired", id.short()),+ NodeEvent::PeerInfoChanged { device, info } => {+ println!("{} is now called {}", device.short(), info.name)+ }+ NodeEvent::Discovered(d) => {+ println!("Found nearby: {} ({})", d.name.as_deref().unwrap_or("unnamed"), d.id.short())+ }+ _ => {}+ }+}++fn print_device(d: &PairedDevice) {+ println!("{:<24} {:<10} {} {}", d.info.name, format!("{:?}", d.info.kind), describe_link(&d.link), d.id);+}++fn describe_link(link: &LinkState) -> String {+ match link {+ LinkState::Online { path, rtt_ms } => format!("online ({path:?}, {rtt_ms} ms)"),+ LinkState::Connecting => "connecting".into(),+ LinkState::Offline { .. } => "offline".into(),+ }+}++/// Accepts a full device ID, or a unique prefix / name of a paired device.+fn resolve(node: &Node, query: &str) -> Result<DeviceId> {+ if let Ok(id) = query.parse::<DeviceId>() {+ return Ok(id);+ }+ let q = query.to_ascii_lowercase();+ let matches: Vec<_> = node+ .paired_devices()?+ .into_iter()+ .filter(|d| d.id.to_string().starts_with(&q) || d.info.name.to_ascii_lowercase() == q)+ .collect();+ match matches.as_slice() {+ [one] => Ok(one.id),+ [] => bail!("no paired device matches {query:?}"),+ _ => bail!("{query:?} matches more than one device; use more of the ID"),+ }+}++fn parse_id(s: &str) -> Result<DeviceId> {+ s.parse().with_context(|| format!("{s:?} is not a device ID"))+}++async fn wait_until_online(node: &Node, id: DeviceId) -> Result<()> {+ let mut events = node.events();+ let is_online = |node: &Node| {+ node.paired_devices()+ .map(|ds| ds.iter().any(|d| d.id == id && matches!(d.link, LinkState::Online { .. })))+ .unwrap_or(false)+ };+ let deadline = tokio::time::Instant::now() + Duration::from_secs(20);+ while !is_online(node) {+ match tokio::time::timeout_at(deadline, events.recv()).await {+ Ok(_) => {}+ Err(_) => bail!("the device didn't come online within 20 seconds"),+ }+ }+ Ok(())+}++fn print_qr(data: &str) {+ match qrcode::QrCode::new(data.as_bytes()) {+ Ok(code) => {+ let image = code+ .render::<qrcode::render::unicode::Dense1x2>()+ .dark_color(qrcode::render::unicode::Dense1x2::Light)+ .light_color(qrcode::render::unicode::Dense1x2::Dark)+ .quiet_zone(true)+ .build();+ println!("{image}");+ }+ Err(e) => tracing::warn!(error = %e, "could not render QR code"),+ }+}diff --git a/core/nectarlink-core/src/pairing.rs b/core/nectarlink-core/src/pairing.rsindex 85931b8..af09b4e 100644--- a/core/nectarlink-core/src/pairing.rs+++ b/core/nectarlink-core/src/pairing.rs@@ -6,6 +6,12 @@//! joiner (phone) proves knowledge of it.//! - **Nearby**: numeric comparison. Both screens show a 6-digit code derived//! from both identities and committed nonces; both users confirm.+//!+//! Both flows end the same way, so a pairing is never stored on only one+//! side in normal operation: the host sends the last protocol message, the+//! initiator acknowledges it with `pair.done`, the host stores the pairing+//! and closes with [`CLOSE_PAIRED`], and the initiator stores it when it sees+//! that close. Failures close with [`CLOSE_FAILED`] and nobody stores.use std::{sync::{Arc, Mutex},@@ -14,7 +20,7 @@ use std::{use iroh::{EndpointAddr,- endpoint::{Connection, RecvStream, SendStream, VarInt},+ endpoint::{Connection, ConnectionError, RecvStream, SendStream, VarInt},};use nectarlink_protocol::{ALPN_PAIR, DeviceId, Envelope, ErrorCode,@@ -39,6 +45,15 @@ const STEP_TIMEOUT: Duration = Duration::from_secs(20);/// Wrong proofs tolerated before pairing mode ends.const MAX_FAILED_ATTEMPTS: u32 = 5;const DIAL_TIMEOUT: Duration = Duration::from_secs(15);+/// How long the initiator waits for the host to store the pairing and close.+const FINISH_TIMEOUT: Duration = Duration::from_secs(10);+/// How long a host that failed waits for the initiator to read its error.+const LINGER_TIMEOUT: Duration = Duration::from_secs(2);++/// Close code: the host stored the pairing.+const CLOSE_PAIRED: u32 = 0;+/// Close code: the ceremony failed; nothing was stored.+const CLOSE_FAILED: u32 = 1;/// Host-side pairing mode, active while a QR code is shown.struct HostMode {@@ -61,9 +76,13 @@ impl std::fmt::Debug for PairingState {}}+fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {+ m.lock().unwrap_or_else(|e| e.into_inner())+}+impl PairingState {fn host_secret(&self) -> Option<[u8; SECRET_LEN]> {- let mut host = self.host.lock().unwrap_or_else(|e| e.into_inner());+ let mut host = lock(&self.host);match host.as_ref() {Some(mode) if mode.expires_at > Instant::now() => Some(mode.secret),Some(_) => {@@ -79,12 +98,12 @@ impl PairingState {}fn end_host(&self) {- *self.host.lock().unwrap_or_else(|e| e.into_inner()) = None;+ *lock(&self.host) = None;}/// Records a failed attempt; returns true if pairing mode just ended.fn record_failure(&self) -> bool {- let mut host = self.host.lock().unwrap_or_else(|e| e.into_inner());+ let mut host = lock(&self.host);if let Some(mode) = host.as_mut() {mode.failures += 1;if mode.failures >= MAX_FAILED_ATTEMPTS {@@ -97,8 +116,7 @@ impl PairingState {/// Delivers the local user's decision about the 6-digit code.pub(crate) fn decide(&self, matches: bool) -> Result<()> {- let slot = self.sas_decision.lock().unwrap_or_else(|e| e.into_inner()).take();- match slot {+ match lock(&self.sas_decision).take() {Some((_, tx)) => {let _ = tx.send(matches);Ok(())@@ -109,19 +127,19 @@ impl PairingState {fn await_decision(&self, peer: DeviceId) -> oneshot::Receiver<bool> {let (tx, rx) = oneshot::channel();- *self.sas_decision.lock().unwrap_or_else(|e| e.into_inner()) = Some((peer, tx));+ *lock(&self.sas_decision) = Some((peer, tx));rx}fn clear_decision(&self) {- *self.sas_decision.lock().unwrap_or_else(|e| e.into_inner()) = None;+ *lock(&self.sas_decision) = None;}}/// Starts host pairing mode and returns the link to show as a QR code.pub(crate) async fn start_host(shared: &Arc<Shared>) -> Result<PairingUri> {let secret: [u8; SECRET_LEN] = rand::random();- *shared.pairing.host.lock().unwrap_or_else(|e| e.into_inner()) =+ *lock(&shared.pairing.host) =Some(HostMode { secret, expires_at: Instant::now() + PAIRING_TTL, failures: 0 });// Expire quietly; tell the UI if nobody paired in time.@@ -129,13 +147,7 @@ pub(crate) async fn start_host(shared: &Arc<Shared>) -> Result<PairingUri> {tokio::spawn(async move {tokio::time::sleep(PAIRING_TTL).await;if let Some(shared) = weak.upgrade() {- let still_ours = shared- .pairing- .host- .lock()- .unwrap_or_else(|e| e.into_inner())- .as_ref()- .is_some_and(|m| m.secret == secret);+ let still_ours = lock(&shared.pairing.host).as_ref().is_some_and(|m| m.secret == secret);if still_ours {shared.pairing.end_host();shared.emit(NodeEvent::Pairing(PairingEvent::Failed(PairingFailure::Expired)));@@ -143,7 +155,7 @@ pub(crate) async fn start_host(shared: &Arc<Shared>) -> Result<PairingUri> {}});- let name = shared.local.read().unwrap_or_else(|e| e.into_inner()).device.name.clone();+ let name = local_device(shared).name;Ok(PairingUri { id: shared.id, secret, name, addrs: shared.direct_addrs().await })}@@ -152,55 +164,81 @@ pub(crate) fn cancel(shared: &Shared) {shared.pairing.clear_decision();}+// ---- Initiator side ----+/// Joins a host by scanning its pairing link (the phone side of the QR flow).pub(crate) async fn join_qr(shared: &Arc<Shared>, uri: &PairingUri) -> Result<()> {shared.remember_addrs(&uri.id, &uri.addrs);let conn = dial(shared, &uri.id).await?;let result = async {let (mut send, mut recv) = conn.open_bi().await.map_err(crate::error::net)?;- let device = shared.local.read().unwrap_or_else(|e| e.into_inner()).device.clone();+ let device = local_device(shared);let proof = proto::pair_proof(&uri.secret, &shared.id, &uri.id).to_vec();send_env(&mut send, Envelope::new(types::PAIR_REQUEST, &PairRequest { device, proof })?).await?;- let accept: PairAccept = recv_env(&mut recv).await?.expect_body(types::PAIR_ACCEPT)?;- finish_initiator(&conn, send, recv).await;+ let accept: PairAccept = recv_env(&mut recv, STEP_TIMEOUT).await?.expect_body(types::PAIR_ACCEPT)?;+ finish_initiator(&conn, send).await?;Ok(accept.device)}.await;- conn.close(VarInt::from_u32(0), b"done");- match result {- Ok(device) => shared.complete_pairing(uri.id, device).await,- Err(err) => Err(fail(shared, err)),- }+ settle_initiator(shared, &conn, uri.id, result).await}-/// Starts the nearby (numeric comparison) flow with a discovered device.-/// The 6-digit code arrives as [`PairingEvent::SasCode`]; answer with+/// Starts the nearby (numeric comparison) flow with a device in pairing+/// mode. The 6-digit code arrives as [`PairingEvent::SasCode`]; answer with/// [`crate::Node::pairing_confirm`].pub(crate) async fn start_nearby(shared: &Arc<Shared>, peer: DeviceId) -> Result<()> {let conn = dial(shared, &peer).await?;let result = async {let (mut send, mut recv) = conn.open_bi().await.map_err(crate::error::net)?;- let device = shared.local.read().unwrap_or_else(|e| e.into_inner()).device.clone();let n_a: [u8; NONCE_LEN] = rand::random();-- let commit = PairCommit { device, c: proto::commitment(&n_a).to_vec() };+ let commit = PairCommit { device: local_device(shared), c: proto::commitment(&n_a).to_vec() };send_env(&mut send, Envelope::new(types::PAIR_COMMIT, &commit)?).await?;- let nonce: PairNonce = recv_env(&mut recv).await?.expect_body(types::PAIR_NONCE)?;+ let nonce: PairNonce = recv_env(&mut recv, STEP_TIMEOUT).await?.expect_body(types::PAIR_NONCE)?;send_env(&mut send, Envelope::new(types::PAIR_REVEAL, &PairReveal { n_a: n_a.to_vec() })?).await?;+ // We are A (initiator), the host is B.let code = proto::sas_code(&n_a, &nonce.n_b, &shared.id, &peer);- compare_codes(shared, peer, code, &mut send, &mut recv).await?;- finish_initiator(&conn, send, recv).await;+ exchange_decisions(shared, peer, code, &mut send, &mut recv, Role::Initiator).await?;+ finish_initiator(&conn, send).await?;Ok(nonce.device)}.await;- conn.close(VarInt::from_u32(0), b"done");+ settle_initiator(shared, &conn, peer, result).await+}++/// Sends `pair.done` and waits for the host to store the pairing and close+/// with [`CLOSE_PAIRED`]. Any other outcome means the host didn't store it.+async fn finish_initiator(conn: &Connection, mut send: SendStream) -> Result<()> {+ send_env(&mut send, Envelope::empty(types::PAIR_DONE)).await?;+ let _ = send.finish();+ match tokio::time::timeout(FINISH_TIMEOUT, conn.closed()).await {+ Ok(ConnectionError::ApplicationClosed(close))+ if close.error_code == VarInt::from_u32(CLOSE_PAIRED) =>+ {+ Ok(())+ }+ Ok(other) => Err(Error::Network(format!("pairing ended unexpectedly: {other}"))),+ Err(_) => Err(Error::Timeout),+ }+}++async fn settle_initiator(+ shared: &Arc<Shared>,+ conn: &Connection,+ peer: DeviceId,+ result: Result<DeviceInfo>,+) -> Result<()> {match result {Ok(device) => shared.complete_pairing(peer, device).await,- Err(err) => Err(fail(shared, err)),+ Err(err) => {+ conn.close(VarInt::from_u32(CLOSE_FAILED), b"failed");+ Err(fail(shared, err))+ }}}+// ---- Host side ----+/// Handles an incoming pairing connection (host side of both flows).pub(crate) async fn accept(shared: Arc<Shared>, conn: Connection) {let peer = crate::device_id(&conn.remote_id());@@ -217,30 +255,40 @@ pub(crate) async fn accept(shared: Arc<Shared>, conn: Connection) {}};let result = async {- let first = recv_env(&mut recv).await?;- match first.t.as_str() {- types::PAIR_REQUEST => accept_qr(&shared, peer, first, &mut send).await,- types::PAIR_COMMIT => {- accept_nearby(&shared, peer, first, &mut send, &mut recv).await.map_err(|e| fail(&shared, e))- }+ let first = recv_env(&mut recv, STEP_TIMEOUT).await?;+ let device = match first.t.as_str() {+ types::PAIR_REQUEST => accept_qr(&shared, peer, first, &mut send).await?,+ types::PAIR_COMMIT => accept_nearby(&shared, peer, first, &mut send, &mut recv)+ .await+ .map_err(|e| fail(&shared, e))?,other => {let reply = Envelope::error(ErrorCode::Unsupported, format!("unexpected {other}"));send_env(&mut send, reply).await?;- Err(Error::Protocol(format!("unexpected pairing message {other}")))+ return Err(Error::Protocol(format!("unexpected pairing message {other}")));}- }+ };+ // Store only once the initiator acknowledged our last message.+ recv_env(&mut recv, STEP_TIMEOUT).await?.expect(types::PAIR_DONE)?;+ Ok(device)}.await;- // Store before closing, so the joiner's first session is accepted.+match result {- Ok(device) => {- if let Err(e) = shared.complete_pairing(peer, device).await {+ Ok(device) => match shared.complete_pairing(peer, device).await {+ Ok(()) => conn.close(VarInt::from_u32(CLOSE_PAIRED), b"paired"),+ Err(e) => {tracing::warn!(error = %e, "failed to store pairing");+ conn.close(VarInt::from_u32(CLOSE_FAILED), b"storage");}+ },+ Err(err) => {+ tracing::info!(peer = %peer.short(), error = %err, "pairing attempt failed");+ // Let the initiator read our error before the connection goes away.+ let _ = send.finish();+ let _ = tokio::time::timeout(LINGER_TIMEOUT, conn.closed()).await;+ conn.close(VarInt::from_u32(CLOSE_FAILED), b"failed");}- Err(err) => tracing::info!(peer = %peer.short(), error = %err, "pairing attempt failed"),}- finish_host(&conn, send).await;}async fn accept_qr(@@ -262,8 +310,7 @@ async fn accept_qr(return Err(Error::Denied);}shared.pairing.end_host();- let device = shared.local.read().unwrap_or_else(|e| e.into_inner()).device.clone();- send_env(send, Envelope::new(types::PAIR_ACCEPT, &PairAccept { device })?).await?;+ send_env(send, Envelope::new(types::PAIR_ACCEPT, &PairAccept { device: local_device(shared) })?).await?;Ok(request.device)}@@ -275,95 +322,95 @@ async fn accept_nearby(recv: &mut RecvStream,) -> Result<DeviceInfo> {let commit: PairCommit = env.body()?;- let device = shared.local.read().unwrap_or_else(|e| e.into_inner()).device.clone();let n_b: [u8; NONCE_LEN] = rand::random();- send_env(send, Envelope::new(types::PAIR_NONCE, &PairNonce { device, n_b: n_b.to_vec() })?).await?;+ let nonce = PairNonce { device: local_device(shared), n_b: n_b.to_vec() };+ send_env(send, Envelope::new(types::PAIR_NONCE, &nonce)?).await?;- let reveal: PairReveal = recv_env(recv).await?.expect_body(types::PAIR_REVEAL)?;+ let reveal: PairReveal = recv_env(recv, STEP_TIMEOUT).await?.expect_body(types::PAIR_REVEAL)?;if !proto::verify_commitment(&commit.c, &reveal.n_a) {send_env(send, Envelope::error(ErrorCode::Denied, "commitment mismatch")).await?;return Err(Error::Denied);}// The initiator is A, we are B.let code = proto::sas_code(&reveal.n_a, &n_b, &peer, &shared.id);- compare_codes(shared, peer, code, send, recv).await?;+ exchange_decisions(shared, peer, code, send, recv, Role::Host).await?;shared.pairing.end_host();Ok(commit.device)}-/// Shows the code, waits for the local decision, exchanges confirmations.-/// Succeeds only if both users confirmed.-async fn compare_codes(+// ---- Code comparison ----++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Role {+ /// Sends its confirmation as soon as the local user confirms.+ Initiator,+ /// Replies last: only after both the local user and the initiator confirmed.+ Host,+}++/// Shows the 6-digit code and exchanges both users' decisions. Watches the+/// peer while waiting for the local user, so a decline on the other device+/// ends the comparison right away.+async fn exchange_decisions(shared: &Arc<Shared>,peer: DeviceId,code: String,send: &mut SendStream,recv: &mut RecvStream,+ role: Role,) -> Result<()> {let decision = shared.pairing.await_decision(peer);shared.emit(NodeEvent::Pairing(PairingEvent::SasCode { peer, code }));- let local_ok = match tokio::time::timeout(SAS_DECISION_TIMEOUT, decision).await {- Ok(Ok(ok)) => ok,- Ok(Err(_)) => false, // cancelled- Err(_) => {- shared.pairing.clear_decision();- false+ let mut decision = Box::pin(tokio::time::timeout(SAS_DECISION_TIMEOUT, decision));+ // Created once: reading a frame isn't cancel-safe, so it must not be+ // restarted when the other branch wins.+ let mut remote = Box::pin(recv_env(recv, SAS_DECISION_TIMEOUT));+ let (mut local_ok, mut remote_ok) = (false, false);+ while !(local_ok && remote_ok) {+ tokio::select! {+ outcome = &mut decision, if !local_ok => {+ if !matches!(outcome, Ok(Ok(true))) {+ shared.pairing.clear_decision();+ send_env(send, Envelope::error(ErrorCode::Denied, "codes did not match")).await?;+ return Err(Error::Declined);+ }+ local_ok = true;+ if role == Role::Initiator {+ send_env(send, Envelope::empty(types::PAIR_CONFIRM)).await?;+ }+ }+ reply = &mut remote, if !remote_ok => {+ let outcome = reply.and_then(|env| Ok(env.expect(types::PAIR_CONFIRM)?));+ if let Err(err) = outcome {+ shared.pairing.clear_decision();+ return Err(err);+ }+ remote_ok = true;+ }}- };- if !local_ok {- send_env(send, Envelope::error(ErrorCode::Denied, "codes did not match")).await?;- return Err(Error::Declined);}- if let Err(err) = send_env(send, Envelope::empty(types::PAIR_CONFIRM)).await {- // The peer may already have declined and stopped reading; prefer its reason.- if let Ok(Ok(Some(frame))) = tokio::time::timeout(Duration::from_secs(2), read_frame(recv)).await- && let Ok(env) = Envelope::from_cbor(&frame)- {- env.expect(types::PAIR_CONFIRM)?;- }- return Err(err);+ if role == Role::Host {+ send_env(send, Envelope::empty(types::PAIR_CONFIRM)).await?;}-- let remote =- tokio::time::timeout(SAS_DECISION_TIMEOUT, read_frame(recv)).await.map_err(|_| Error::Timeout)??;- let remote = Envelope::from_cbor(&remote.ok_or(Error::Offline)?)?;- remote.expect(types::PAIR_CONFIRM)?;Ok(())}-/// How long to wait for the other side to finish the ceremony cleanly.-const CLOSE_TIMEOUT: Duration = Duration::from_secs(5);--/// Initiator side: lets the host read our last message and close the-/// connection. Closing first would discard data the host hasn't read yet.-async fn finish_initiator(conn: &Connection, mut send: SendStream, mut recv: RecvStream) {- let _ = send.finish();- let _ = recv.stop(VarInt::from_u32(0));- let _ = tokio::time::timeout(CLOSE_TIMEOUT, conn.closed()).await;-}+// ---- Helpers -----/// Host side: waits until the initiator has received everything we sent,-/// then closes the connection.-async fn finish_host(conn: &Connection, mut send: SendStream) {- let _ = send.finish();- let _ = tokio::time::timeout(CLOSE_TIMEOUT, send.stopped()).await;- conn.close(VarInt::from_u32(0), b"done");+fn local_device(shared: &Shared) -> DeviceInfo {+ shared.local.read().unwrap_or_else(|e| e.into_inner()).device.clone()}async fn dial(shared: &Arc<Shared>, peer: &DeviceId) -> Result<Connection> {let addr = EndpointAddr::new(crate::public_key(peer)?);- match tokio::time::timeout(DIAL_TIMEOUT, shared.endpoint.connect(addr, ALPN_PAIR)).await {- Ok(Ok(conn)) => Ok(conn),- Ok(Err(e)) => {- shared.emit(NodeEvent::Pairing(PairingEvent::Failed(PairingFailure::Unreachable)));- Err(crate::error::net(e))- }- Err(_) => {- shared.emit(NodeEvent::Pairing(PairingEvent::Failed(PairingFailure::Unreachable)));- Err(Error::Timeout)- }- }+ let err = match tokio::time::timeout(DIAL_TIMEOUT, shared.endpoint.connect(addr, ALPN_PAIR)).await {+ Ok(Ok(conn)) => return Ok(conn),+ Ok(Err(e)) => crate::error::net(e),+ Err(_) => Error::Timeout,+ };+ shared.emit(NodeEvent::Pairing(PairingEvent::Failed(PairingFailure::Unreachable)));+ Err(err)}async fn send_env(send: &mut SendStream, env: Envelope) -> Result<()> {@@ -371,8 +418,8 @@ async fn send_env(send: &mut SendStream, env: Envelope) -> Result<()> {Ok(())}-async fn recv_env(recv: &mut RecvStream) -> Result<Envelope> {- let frame = tokio::time::timeout(STEP_TIMEOUT, read_frame(recv)).await.map_err(|_| Error::Timeout)??;+async fn recv_env(recv: &mut RecvStream, timeout: Duration) -> Result<Envelope> {+ let frame = tokio::time::timeout(timeout, read_frame(recv)).await.map_err(|_| Error::Timeout)??;Ok(Envelope::from_cbor(&frame.ok_or(Error::Offline)?)?)}diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 1b56335..941fb95 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -24,6 +24,7 @@ pub mod types {pub const PAIR_NONCE: &str = "pair.nonce";pub const PAIR_REVEAL: &str = "pair.reveal";pub const PAIR_CONFIRM: &str = "pair.confirm";+ pub const PAIR_DONE: &str = "pair.done";pub const PAIR_REVOKE: &str = "pair.revoke";}diff --git a/docs/protocol/v0.md b/docs/protocol/v0.mdindex 00f013f..deca5c1 100644--- a/docs/protocol/v0.md+++ b/docs/protocol/v0.md@@ -247,7 +247,7 @@ already authenticates the raw public keys; the ceremony proves that the```4. The PC verifies `proof` against the phone's TLS-authenticated Device ID. On- success it stores the phone as trusted and replies:+ success it replies:```t = "pair.accept" re = 1 b = { device: DeviceInfo }@@ -255,8 +255,8 @@ already authenticates the raw public keys; the ceremony proves that theOn failure it replies `error DENIED` and leaves pairing mode after 5 failedattempts.-5. The phone stores the PC as trusted. Both devices close the pairing- connection and open a normal `nectarlink/0` session.+5. The ceremony finishes as described in §9.4, after which the phone opens a+ normal `nectarlink/0` session.Because the phone learned the PC's Device ID from the QR code and the PCverifies knowledge of `S`, both directions are authenticated with no codes to@@ -278,9 +278,12 @@ initiator is **A**, the responder **B**.```shown as a 6-digit code on both screens.-5. The user confirms the codes match on **both** devices. Each sends- `pair.confirm`. Only after receiving the peer's `pair.confirm` and- confirming locally does each device store the other as trusted.+5. The user confirms the codes match on **both** devices. A sends+ `pair.confirm` as soon as its user confirms. B replies `pair.confirm` only+ after both its own user and A confirmed, so B always sends the last+ message. A decline on either side is sent as `error DENIED` and ends the+ ceremony immediately.+6. The ceremony finishes as described in §9.4.The commitment in step 1 prevents an attacker from choosing a nonce to force amatching code; a man-in-the-middle would have different Device IDs on each@@ -291,7 +294,24 @@ side and therefore different codes.When an ADB connection exists, the PC can exchange Device IDs with the phoneapp over ADB directly. Specified in v0.1 together with the ADB integration.-### 9.4 Unpairing+### 9.4 Finishing a ceremony++A QUIC connection close discards data the peer hasn't read yet, so the end of+a ceremony is acknowledged explicitly:++1. The host (B) sends the last protocol message (`pair.accept` or+ `pair.confirm`).+2. The initiator (A) replies `t = "pair.done"` and finishes its stream.+3. The host, after reading `pair.done`, stores the initiator as trusted and+ closes the connection with application code **0**.+4. The initiator stores the host as trusted only when it observes the close+ with code 0.++Any failure closes with application code **1** and neither side stores+anything. A host that fails waits briefly (up to 2 s) for the initiator to+close first, so its `error` message is read before the connection goes away.++### 9.5 UnpairingEither device may send `pair.revoke` on an established session, then deletesthe trust entry. A device receiving it deletes its entry too. Unpairing