From b62e12bca636375be94d1471f614d11880b631b5 Mon Sep 17 00:00:00 2001 From: DorJay Date: Wed, 11 Nov 2026 19:16:53 +0800 Subject: [PATCH 01/12] fix(security,relay,companion): isolate cloud discovery to paired hosts, add pairing code rendezvous, and sync desktop sessions --- Cargo.lock | 21 + Cargo.toml | 1 + crates/relay-server/Cargo.toml | 27 + crates/relay-server/src/lib.rs | 1057 +++++++++++++++++ crates/relay-server/src/main.rs | 43 + .../tests/multi_tenant_isolation.rs | 418 +++++++ crates/server/src/host/conversation.rs | 10 + crates/utils/src/tunnel.rs | 2 +- docs/companion/android-frontend.md | 6 +- .../webrtc-remote-connectivity-spec.md | 397 +++++++ mobile/android | 2 +- mobile/ios | 2 +- scripts/deploy-relay-server.sh | 54 + src-tauri/src/commands/host_tunnel.rs | 73 +- src-tauri/src/commands/web_service.rs | 14 +- 15 files changed, 2095 insertions(+), 32 deletions(-) create mode 100644 crates/relay-server/Cargo.toml create mode 100644 crates/relay-server/src/lib.rs create mode 100644 crates/relay-server/src/main.rs create mode 100644 crates/relay-server/tests/multi_tenant_isolation.rs create mode 100644 docs/companion/webrtc-remote-connectivity-spec.md create mode 100644 scripts/deploy-relay-server.sh diff --git a/Cargo.lock b/Cargo.lock index ddfcc650e..ed18f78a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5141,6 +5141,27 @@ version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" +[[package]] +name = "relay-server" +version = "0.4.4" +dependencies = [ + "anyhow", + "axum", + "base64 0.22.1", + "chrono", + "futures", + "reqwest 0.12.28", + "rustls", + "serde", + "serde_json", + "sha2", + "tokio", + "tokio-tungstenite", + "tracing", + "tracing-subscriber", + "uuid", +] + [[package]] name = "remote-protocol" version = "0.4.4" diff --git a/Cargo.toml b/Cargo.toml index 687ad2655..d80cd2286 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ members = [ "crates/automation", "crates/workflows", "crates/remote-protocol", + "crates/relay-server", "crates/application", "crates/server", "src-tauri", diff --git a/crates/relay-server/Cargo.toml b/crates/relay-server/Cargo.toml new file mode 100644 index 000000000..c039b15bb --- /dev/null +++ b/crates/relay-server/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "relay-server" +version = "0.4.4" +edition = "2024" + +[[bin]] +name = "vibex-relay-server" +path = "src/main.rs" + +[dependencies] +anyhow = { workspace = true } +axum = { workspace = true } +base64 = "0.22" +chrono = { workspace = true } +futures = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +sha2 = "0.10" +tokio = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +uuid = { workspace = true } + +[dev-dependencies] +reqwest = { workspace = true } +rustls = { workspace = true } +tokio-tungstenite = { version = "0.29", features = ["connect"] } diff --git a/crates/relay-server/src/lib.rs b/crates/relay-server/src/lib.rs new file mode 100644 index 000000000..e98fe9301 --- /dev/null +++ b/crates/relay-server/src/lib.rs @@ -0,0 +1,1057 @@ +use std::{ + collections::{HashMap, VecDeque}, + net::SocketAddr, + path::PathBuf, + sync::{ + Arc, + atomic::{AtomicU64, Ordering}, + }, + time::{Duration, Instant}, +}; + +use axum::{ + Json, Router, + body::{Body, to_bytes}, + extract::{Path, Request, State}, + http::{HeaderMap, HeaderName, HeaderValue, StatusCode, header}, + response::{IntoResponse, Response}, + routing::{any, get, post}, +}; +use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64}; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use sha2::{Digest, Sha256}; +use tokio::{ + io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}, + net::{TcpListener, TcpStream}, + sync::{Mutex, RwLock, mpsc, oneshot}, +}; + +pub const DEFAULT_RELAY_PORT: u16 = 17890; +const CTRL_PING_INTERVAL: Duration = Duration::from_secs(15); +const CTRL_READ_TIMEOUT: Duration = Duration::from_secs(45); +const HTTP_PROXY_TIMEOUT: Duration = Duration::from_secs(25); +const DATA_OPEN_TIMEOUT: Duration = Duration::from_secs(6); +const PREWARM_MAX_IDLE: Duration = Duration::from_secs(40); +const PREWARM_TARGET_POOL_SIZE: usize = 3; +const MAX_HTTP_BODY_BYTES: usize = 16 * 1024 * 1024; +const BEACON_TTL: Duration = Duration::from_secs(600); + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum ControlServerFrame { + Ping { + ts: i64, + }, + ReplenishPool { + count: usize, + }, + OpenData { + host_id: String, + conn_id: String, + }, + HttpReq { + host_id: String, + id: String, + method: String, + path: String, + headers: Vec<(String, String)>, + body_b64: String, + }, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum ControlClientFrame { + Pong { + ts: i64, + }, + UpdateMeta { + name: String, + lan_origins: Vec, + }, + HttpRes { + host_id: String, + id: String, + status: u16, + headers: Vec<(String, String)>, + body_b64: String, + }, +} + +#[derive(Debug, Clone)] +pub struct ProxiedHttpResponse { + pub host_id: String, + pub status: u16, + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +struct PrewarmedStream { + created_at: Instant, + stream: TcpStream, +} + +pub struct HostSession { + pub session_id: u64, + pub host_id: String, + pub token_sha256: String, + pub host_name: RwLock, + pub lan_origins: RwLock>, + pub peer_slash24: Option, + ctrl_tx: mpsc::UnboundedSender, + pending_http: Mutex>>, + prewarmed_data: Mutex>, + pending_data: Mutex>>, +} + +#[derive(Clone)] +struct BeaconEntry { + created_at: Instant, + timestamp_unix: i64, + payload: serde_json::Value, +} + +pub struct RelayServerState { + next_session_id: AtomicU64, + hosts: RwLock>>, + bound_tokens: RwLock>, + token_store_path: Option, + beacons: RwLock>>, +} + +impl Default for RelayServerState { + fn default() -> Self { + Self::new(None) + } +} + +impl RelayServerState { + pub fn new(token_store_path: Option) -> Self { + let initial_tokens = token_store_path + .as_ref() + .and_then(|path| std::fs::read_to_string(path).ok()) + .and_then(|raw| serde_json::from_str::>(&raw).ok()) + .unwrap_or_default(); + Self { + next_session_id: AtomicU64::new(1), + hosts: RwLock::new(HashMap::new()), + bound_tokens: RwLock::new(initial_tokens), + token_store_path, + beacons: RwLock::new(HashMap::new()), + } + } + + async fn verify_and_bind_host_token(&self, host_id: &str, token: &str) -> bool { + if host_id.is_empty() || token.len() < 16 { + return false; + } + let candidate_hash = sha256_hex(token); + { + let guard = self.bound_tokens.read().await; + if let Some(existing) = guard.get(host_id) { + return constant_time_eq(existing.as_bytes(), candidate_hash.as_bytes()); + } + } + let mut guard = self.bound_tokens.write().await; + if let Some(existing) = guard.get(host_id) { + return constant_time_eq(existing.as_bytes(), candidate_hash.as_bytes()); + } + guard.insert(host_id.to_string(), candidate_hash); + if let Some(path) = &self.token_store_path + && let Ok(serialized) = serde_json::to_string_pretty(&*guard) + { + let _ = std::fs::write(path, serialized); + } + true + } + + async fn verify_existing_host_token(&self, host_id: &str, token: &str) -> bool { + let candidate_hash = sha256_hex(token); + let guard = self.bound_tokens.read().await; + guard.get(host_id).is_some_and(|existing| { + constant_time_eq(existing.as_bytes(), candidate_hash.as_bytes()) + }) + } + + async fn get_host(&self, host_id: &str) -> Option> { + self.hosts.read().await.get(host_id).cloned() + } +} + +pub fn sha256_hex(input: &str) -> String { + let mut hasher = Sha256::new(); + hasher.update(input.as_bytes()); + let digest = hasher.finalize(); + let mut out = String::with_capacity(64); + for b in digest { + use std::fmt::Write; + let _ = write!(&mut out, "{b:02x}"); + } + out +} + +fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { + if a.len() != b.len() { + return false; + } + let mut diff = 0u8; + for (x, y) in a.iter().zip(b.iter()) { + diff |= x ^ y; + } + diff == 0 +} + +pub fn ipv4_slash24(addr: SocketAddr) -> Option { + match addr.ip() { + std::net::IpAddr::V4(ip) => { + let o = ip.octets(); + Some(format!("{}.{}.{}", o[0], o[1], o[2])) + } + std::net::IpAddr::V6(ip) => ip.to_ipv4_mapped().map(|v4| { + let o = v4.octets(); + format!("{}.{}.{}", o[0], o[1], o[2]) + }), + } +} + +struct ChannelListener { + rx: mpsc::UnboundedReceiver<(TcpStream, SocketAddr)>, + local_addr: SocketAddr, +} + +#[derive(Clone, Copy, Debug)] +#[allow(dead_code)] +struct ClientPeerAddr(SocketAddr); + +impl axum::extract::connect_info::Connected> + for ClientPeerAddr +{ + fn connect_info(stream: axum::serve::IncomingStream<'_, ChannelListener>) -> Self { + Self(*stream.remote_addr()) + } +} + +impl axum::serve::Listener for ChannelListener { + type Io = TcpStream; + type Addr = SocketAddr; + + async fn accept(&mut self) -> (Self::Io, Self::Addr) { + match self.rx.recv().await { + Some(pair) => pair, + None => std::future::pending().await, + } + } + + fn local_addr(&self) -> tokio::io::Result { + Ok(self.local_addr) + } +} + +pub async fn run_relay_server( + listener: TcpListener, + state: Arc, +) -> anyhow::Result<()> { + let local_addr = listener.local_addr()?; + let (http_tx, http_rx) = mpsc::unbounded_channel::<(TcpStream, SocketAddr)>(); + let channel_listener = ChannelListener { + rx: http_rx, + local_addr, + }; + + let router = build_http_router(state.clone()); + let _axum_task = tokio::spawn(async move { + let _ = axum::serve( + channel_listener, + router.into_make_service_with_connect_info::(), + ) + .await; + }); + + loop { + let (stream, peer_addr) = match listener.accept().await { + Ok(pair) => pair, + Err(err) => { + tracing::warn!("accept error on relay listener: {err}"); + continue; + } + }; + let _ = stream.set_nodelay(true); + let state = state.clone(); + let http_tx = http_tx.clone(); + tokio::spawn(async move { + dispatch_connection(stream, peer_addr, state, http_tx).await; + }); + } +} + +async fn dispatch_connection( + stream: TcpStream, + peer_addr: SocketAddr, + state: Arc, + http_tx: mpsc::UnboundedSender<(TcpStream, SocketAddr)>, +) { + let mut peek_buf = [0u8; 2048]; + let n = match tokio::time::timeout(Duration::from_secs(4), stream.peek(&mut peek_buf)).await { + Ok(Ok(n)) if n > 0 => n, + _ => return, + }; + let head = &peek_buf[..n]; + + if head.starts_with(b"VIBEX-CTRL ") { + handle_control_connection(stream, peer_addr, state).await; + return; + } + if head.starts_with(b"VIBEX-DATA ") { + handle_data_connection(stream, state).await; + return; + } + if is_tunnel_upgrade_request(head) { + handle_tunnel_upgrade_connection(stream, peer_addr, state).await; + return; + } + if is_websocket_upgrade_for_tenant(head) { + handle_websocket_proxy_connection(stream, state).await; + return; + } + + let _ = http_tx.send((stream, peer_addr)); +} + +fn is_tunnel_upgrade_request(head: &[u8]) -> bool { + head.starts_with(b"GET /v1/tunnel ") || head.starts_with(b"GET /v1/tunnel?") +} + +async fn handle_tunnel_upgrade_connection( + mut stream: TcpStream, + peer_addr: SocketAddr, + state: Arc, +) { + let mut peek_buf = [0u8; 4096]; + let mut header_end = None; + for _ in 0..8 { + let Ok(Ok(n)) = + tokio::time::timeout(Duration::from_secs(4), stream.peek(&mut peek_buf)).await + else { + return; + }; + if n == 0 { + return; + } + if let Some(pos) = peek_buf[..n].windows(4).position(|w| w == b"\r\n\r\n") { + header_end = Some(pos + 4); + break; + } + tokio::time::sleep(Duration::from_millis(15)).await; + } + let Some(end_len) = header_end else { + return; + }; + + let mut header_bytes = vec![0u8; end_len]; + if tokio::time::timeout(Duration::from_secs(4), stream.read_exact(&mut header_bytes)) + .await + .is_err() + { + return; + } + + let header_text = String::from_utf8_lossy(&header_bytes); + let effective_peer = extract_forwarded_peer_addr(&header_text, peer_addr); + + let response = + b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n"; + if tokio::time::timeout(Duration::from_secs(4), stream.write_all(response)) + .await + .is_err() + { + return; + } + + let mut inner_peek = [0u8; 512]; + let Ok(Ok(n)) = + tokio::time::timeout(Duration::from_secs(5), stream.peek(&mut inner_peek)).await + else { + return; + }; + let head = &inner_peek[..n]; + if head.starts_with(b"VIBEX-CTRL ") { + handle_control_connection(stream, effective_peer, state).await; + } else if head.starts_with(b"VIBEX-DATA ") { + handle_data_connection(stream, state).await; + } +} + +fn extract_forwarded_peer_addr(headers: &str, fallback: SocketAddr) -> SocketAddr { + for line in headers.lines() { + let lower = line.to_ascii_lowercase(); + if let Some(rest) = lower.strip_prefix("x-real-ip:") + && let Ok(ip) = rest.trim().parse::() + { + return SocketAddr::new(ip, fallback.port()); + } + if let Some(rest) = lower.strip_prefix("x-forwarded-for:") + && let Some(first) = rest.split(',').next() + && let Ok(ip) = first.trim().parse::() + { + return SocketAddr::new(ip, fallback.port()); + } + } + fallback +} + +fn is_websocket_upgrade_for_tenant(head: &[u8]) -> bool { + let text = String::from_utf8_lossy(head); + let mut lines = text.lines(); + let Some(first_line) = lines.next() else { + return false; + }; + if !first_line.starts_with("GET /t/") { + return false; + } + lines.any(|line| { + let lower = line.to_ascii_lowercase(); + lower.starts_with("upgrade:") && lower.contains("websocket") + }) +} + +async fn handle_control_connection( + stream: TcpStream, + peer_addr: SocketAddr, + state: Arc, +) { + let (reader, mut writer) = stream.into_split(); + let mut lines = BufReader::new(reader).lines(); + let Ok(Ok(Some(first_line))) = + tokio::time::timeout(Duration::from_secs(5), lines.next_line()).await + else { + return; + }; + + let parts: Vec<&str> = first_line.trim().split_whitespace().collect(); + // Format: VIBEX-CTRL v2 [name_b64] [lan_origins_b64] + let (host_id, token, host_name, lan_origins) = if parts.len() >= 4 && parts[1] == "v2" { + let host_id = parts[2].trim().to_string(); + let token = parts[3].trim().to_string(); + let host_name = parts + .get(4) + .and_then(|b64| BASE64.decode(b64).ok()) + .and_then(|bytes| String::from_utf8(bytes).ok()) + .filter(|s| !s.trim().is_empty()) + .unwrap_or_else(|| "VibeX Desktop".to_string()); + let lan_origins = parts + .get(5) + .and_then(|b64| BASE64.decode(b64).ok()) + .and_then(|bytes| serde_json::from_slice::>(&bytes).ok()) + .unwrap_or_default(); + (host_id, token, host_name, lan_origins) + } else if parts.len() == 2 { + ( + "default".to_string(), + parts[1].trim().to_string(), + "VibeX Desktop".to_string(), + Vec::new(), + ) + } else { + return; + }; + + if !state.verify_and_bind_host_token(&host_id, &token).await { + let _ = writer.write_all(b"ERR unauthorized_host_token\n").await; + return; + } + + let (ctrl_tx, mut ctrl_rx) = mpsc::unbounded_channel::(); + let session_id = state.next_session_id.fetch_add(1, Ordering::Relaxed); + let session = Arc::new(HostSession { + session_id, + host_id: host_id.clone(), + token_sha256: sha256_hex(&token), + host_name: RwLock::new(host_name), + lan_origins: RwLock::new(lan_origins), + peer_slash24: ipv4_slash24(peer_addr), + ctrl_tx: ctrl_tx.clone(), + pending_http: Mutex::new(HashMap::new()), + prewarmed_data: Mutex::new(VecDeque::new()), + pending_data: Mutex::new(HashMap::new()), + }); + + state + .hosts + .write() + .await + .insert(host_id.clone(), session.clone()); + let _ = ctrl_tx.send(format!("OK {host_id}\n")); + if let Ok(replenish) = serde_json::to_string(&ControlServerFrame::ReplenishPool { + count: PREWARM_TARGET_POOL_SIZE, + }) { + let _ = ctrl_tx.send(format!("{replenish}\n")); + } + + let write_task = tokio::spawn(async move { + while let Some(msg) = ctrl_rx.recv().await { + if writer.write_all(msg.as_bytes()).await.is_err() { + break; + } + } + }); + + let mut ping_interval = tokio::time::interval(CTRL_PING_INTERVAL); + ping_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + + loop { + tokio::select! { + _ = ping_interval.tick() => { + if let Ok(frame) = serde_json::to_string(&ControlServerFrame::Ping { + ts: chrono::Utc::now().timestamp_millis(), + }) { + if ctrl_tx.send(format!("{frame}\n")).is_err() { + break; + } + } + // Evict stale pre-warmed streams and ask Host to replenish if needed + let needed = { + let mut pool = session.prewarmed_data.lock().await; + while pool.front().is_some_and(|item| item.created_at.elapsed() >= PREWARM_MAX_IDLE) { + pool.pop_front(); + } + PREWARM_TARGET_POOL_SIZE.saturating_sub(pool.len()) + }; + if needed > 0 + && let Ok(replenish) = serde_json::to_string(&ControlServerFrame::ReplenishPool { count: needed }) + { + let _ = ctrl_tx.send(format!("{replenish}\n")); + } + } + line_res = tokio::time::timeout(CTRL_READ_TIMEOUT, lines.next_line()) => { + let Ok(Ok(Some(line))) = line_res else { + break; + }; + let trimmed = line.trim(); + if trimmed.is_empty() || trimmed == "PONG" { + continue; + } + if let Ok(frame) = serde_json::from_str::(trimmed) { + match frame { + ControlClientFrame::Pong { .. } => {} + ControlClientFrame::UpdateMeta { name, lan_origins } => { + if !name.trim().is_empty() { + *session.host_name.write().await = name; + } + *session.lan_origins.write().await = lan_origins; + } + ControlClientFrame::HttpRes { + host_id: res_host_id, + id, + status, + headers, + body_b64, + } => { + // Strict tenant check: never accept a response whose host_id mismatches this control stream + if res_host_id != session.host_id { + tracing::warn!( + "tenant mismatch on HttpRes: expected {}, got {}", + session.host_id, + res_host_id + ); + continue; + } + let Some(sender) = session.pending_http.lock().await.remove(&id) else { + continue; + }; + let body = BASE64.decode(body_b64).unwrap_or_default(); + let _ = sender.send(ProxiedHttpResponse { + host_id: res_host_id, + status, + headers, + body, + }); + } + } + } + } + } + } + + write_task.abort(); + let mut hosts = state.hosts.write().await; + if hosts + .get(&host_id) + .is_some_and(|current| current.session_id == session_id) + { + hosts.remove(&host_id); + } +} + +async fn handle_data_connection(stream: TcpStream, state: Arc) { + let mut reader = BufReader::new(stream); + let mut first_line = String::new(); + let Ok(Ok(n)) = + tokio::time::timeout(Duration::from_secs(5), reader.read_line(&mut first_line)).await + else { + return; + }; + if n == 0 { + return; + } + let parts: Vec<&str> = first_line.trim().split_whitespace().collect(); + // Format: VIBEX-DATA v2 + let (host_id, token, conn_id) = if parts.len() >= 5 && parts[1] == "v2" { + (parts[2].trim(), parts[3].trim(), parts[4].trim()) + } else if parts.len() == 3 { + ("default", parts[1].trim(), parts[2].trim()) + } else { + return; + }; + + if !state.verify_existing_host_token(host_id, token).await { + return; + } + let Some(session) = state.get_host(host_id).await else { + return; + }; + + let stream = reader.into_inner(); + if conn_id == "POOL" { + let mut pool = session.prewarmed_data.lock().await; + while pool.len() >= PREWARM_TARGET_POOL_SIZE * 2 { + pool.pop_front(); + } + pool.push_back(PrewarmedStream { + created_at: Instant::now(), + stream, + }); + } else if let Some(sender) = session.pending_data.lock().await.remove(conn_id) { + let _ = sender.send(stream); + } +} + +async fn acquire_host_data_stream(session: &Arc) -> Option { + // 1. Try pre-warmed stream first (0ms handshake) + loop { + let candidate = session.prewarmed_data.lock().await.pop_front(); + let Some(mut item) = candidate else { + break; + }; + if item.created_at.elapsed() >= PREWARM_MAX_IDLE { + continue; + } + let activate_line = format!("USE {}\n", session.host_id); + if item + .stream + .write_all(activate_line.as_bytes()) + .await + .is_ok() + { + if let Ok(replenish) = + serde_json::to_string(&ControlServerFrame::ReplenishPool { count: 1 }) + { + let _ = session.ctrl_tx.send(format!("{replenish}\n")); + } + return Some(item.stream); + } + } + + // 2. Fallback: request an immediate on-demand data stream from the Host + let conn_id = uuid::Uuid::new_v4().simple().to_string(); + let (tx, rx) = oneshot::channel(); + session + .pending_data + .lock() + .await + .insert(conn_id.clone(), tx); + let open_frame = serde_json::to_string(&ControlServerFrame::OpenData { + host_id: session.host_id.clone(), + conn_id: conn_id.clone(), + }) + .ok()?; + if session.ctrl_tx.send(format!("{open_frame}\n")).is_err() { + session.pending_data.lock().await.remove(&conn_id); + return None; + } + match tokio::time::timeout(DATA_OPEN_TIMEOUT, rx).await { + Ok(Ok(stream)) => Some(stream), + _ => { + session.pending_data.lock().await.remove(&conn_id); + None + } + } +} + +async fn handle_websocket_proxy_connection( + mut client_stream: TcpStream, + state: Arc, +) { + // Read up to the end of HTTP headers (\r\n\r\n) + let mut header_buf = Vec::with_capacity(2048); + let mut byte = [0u8; 1]; + let read_res = tokio::time::timeout(Duration::from_secs(5), async { + while header_buf.len() < 16384 { + let n = client_stream.read(&mut byte).await?; + if n == 0 { + break; + } + header_buf.push(byte[0]); + if header_buf.ends_with(b"\r\n\r\n") { + break; + } + } + Ok::<_, std::io::Error>(()) + }) + .await; + if read_res.is_err() || !header_buf.ends_with(b"\r\n\r\n") { + return; + } + + let raw_headers = String::from_utf8_lossy(&header_buf); + let mut lines = raw_headers.split("\r\n"); + let Some(request_line) = lines.next() else { + return; + }; + let req_parts: Vec<&str> = request_line.split_whitespace().collect(); + if req_parts.len() < 3 { + return; + } + let method = req_parts[0]; + let full_uri = req_parts[1]; + let version = req_parts[2]; + + let Some((host_id, stripped_path)) = parse_tenant_path(full_uri) else { + let _ = client_stream + .write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n") + .await; + return; + }; + + let Some(session) = state.get_host(&host_id).await else { + let _ = client_stream + .write_all(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n") + .await; + return; + }; + + let Some(mut host_stream) = acquire_host_data_stream(&session).await else { + let _ = client_stream + .write_all(b"HTTP/1.1 504 Gateway Timeout\r\nContent-Length: 0\r\n\r\n") + .await; + return; + }; + + // Rewrite request line and normalize Host / strip Origin so Host local server accepts WebSocket + let mut rewritten = format!("{method} {stripped_path} {version}\r\nHost: 127.0.0.1\r\n"); + for line in lines { + if line.is_empty() { + continue; + } + let lower = line.to_ascii_lowercase(); + if lower.starts_with("host:") || lower.starts_with("origin:") { + continue; + } + rewritten.push_str(line); + rewritten.push_str("\r\n"); + } + rewritten.push_str("\r\n"); + + if host_stream.write_all(rewritten.as_bytes()).await.is_err() { + return; + } + + let _ = tokio::io::copy_bidirectional(&mut client_stream, &mut host_stream).await; +} + +fn parse_tenant_path(uri: &str) -> Option<(String, String)> { + let rest = uri.strip_prefix("/t/")?; + let (host_id, tail) = match rest.find(['/', '?']) { + Some(idx) => (&rest[..idx], &rest[idx..]), + None => (rest, "/"), + }; + if host_id.trim().is_empty() { + return None; + } + let normalized_tail = if tail.starts_with('?') { + format!("/{tail}") + } else if tail.is_empty() { + "/".to_string() + } else { + tail.to_string() + }; + Some((host_id.to_string(), normalized_tail)) +} + +fn build_http_router(state: Arc) -> Router { + Router::new() + .route("/health", get(relay_health_handler)) + .route("/v1/discover/same-net", get(discover_same_net_handler)) + .route( + "/v1/beacon/{topic}", + post(publish_beacon_handler).get(query_beacon_handler), + ) + .route("/t/{host_id}", any(proxy_tenant_root_handler)) + .route("/t/{host_id}/", any(proxy_tenant_root_handler)) + .route("/t/{host_id}/{*path}", any(proxy_tenant_path_handler)) + .with_state(state) +} + +async fn relay_health_handler(State(state): State>) -> impl IntoResponse { + let online_hosts = state.hosts.read().await.len(); + Json(json!({ + "status": "ok", + "service": "vibex-relay-server", + "online_hosts": online_hosts, + })) +} + +async fn discover_same_net_handler() -> impl IntoResponse { + // Public subnet enumeration is disabled to prevent cross-user host and LAN IP disclosure. + Json(json!({ + "slash24": serde_json::Value::Null, + "hosts": [], + })) +} + +fn is_allowed_private_beacon_topic(topic: &str) -> bool { + let Some(hex_part) = topic + .strip_prefix("vbx-h-") + .or_else(|| topic.strip_prefix("vbx-p-")) + else { + return false; + }; + hex_part.len() == 32 && hex_part.bytes().all(|b| b.is_ascii_hexdigit()) +} + +async fn publish_beacon_handler( + State(state): State>, + Path(topic): Path, + body: String, +) -> impl IntoResponse { + let topic = topic.trim().to_string(); + if !is_allowed_private_beacon_topic(&topic) { + return StatusCode::FORBIDDEN.into_response(); + } + let Ok(payload) = serde_json::from_str::(&body) else { + return StatusCode::BAD_REQUEST.into_response(); + }; + let mut beacons = state.beacons.write().await; + let queue = beacons.entry(topic).or_default(); + while queue + .front() + .is_some_and(|item| item.created_at.elapsed() >= BEACON_TTL) + { + queue.pop_front(); + } + while queue.len() >= 16 { + queue.pop_front(); + } + queue.push_back(BeaconEntry { + created_at: Instant::now(), + timestamp_unix: chrono::Utc::now().timestamp(), + payload, + }); + StatusCode::OK.into_response() +} + +async fn query_beacon_handler( + State(state): State>, + Path(topic): Path, +) -> impl IntoResponse { + let topic = topic.trim(); + if !is_allowed_private_beacon_topic(topic) { + return Json(json!({ "entries": [] })); + } + let mut beacons = state.beacons.write().await; + let Some(queue) = beacons.get_mut(topic) else { + return Json(json!({ "entries": [] })); + }; + while queue + .front() + .is_some_and(|item| item.created_at.elapsed() >= BEACON_TTL) + { + queue.pop_front(); + } + let entries: Vec = queue + .iter() + .rev() + .map(|entry| { + json!({ + "ts": entry.timestamp_unix, + "payload": entry.payload, + }) + }) + .collect(); + Json(json!({ "entries": entries })) +} + +async fn proxy_tenant_root_handler( + State(state): State>, + Path(host_id): Path, + request: Request, +) -> Response { + proxy_tenant_inner(state, host_id, "/".to_string(), request).await +} + +async fn proxy_tenant_path_handler( + State(state): State>, + Path((host_id, path)): Path<(String, String)>, + request: Request, +) -> Response { + let normalized = if path.starts_with('/') { + path + } else { + format!("/{path}") + }; + proxy_tenant_inner(state, host_id, normalized, request).await +} + +async fn proxy_tenant_inner( + state: Arc, + host_id: String, + stripped_path: String, + request: Request, +) -> Response { + let host_id = host_id.trim().to_string(); + let Some(session) = state.get_host(&host_id).await else { + return ( + StatusCode::BAD_GATEWAY, + Json(json!({ + "status": "offline", + "host_id": host_id, + "message": "Target VibeX Host is not currently connected to the relay", + })), + ) + .into_response(); + }; + + if stripped_path == "/health" && request.method() == axum::http::Method::GET { + let host_name = session.host_name.read().await.clone(); + let mut resp = Json(json!({ + "status": "ok", + "version": "0.4.3", + "release": false, + "host_id": session.host_id, + "name": host_name, + })) + .into_response(); + if let Ok(hv) = HeaderValue::from_str(&session.host_id) { + resp.headers_mut().insert("x-vibex-routed-host-id", hv); + } + return resp; + } + + let method = request.method().as_str().to_string(); + let path_and_query = match request.uri().query() { + Some(q) if !q.is_empty() => format!("{stripped_path}?{q}"), + _ => stripped_path, + }; + + let mut headers = Vec::new(); + for (name, value) in request.headers() { + let lower = name.as_str().to_ascii_lowercase(); + if matches!( + lower.as_str(), + "host" | "origin" | "connection" | "transfer-encoding" | "content-length" + ) { + continue; + } + if let Ok(val_str) = value.to_str() { + headers.push((name.as_str().to_string(), val_str.to_string())); + } + } + + let Ok(body_bytes) = to_bytes(request.into_body(), MAX_HTTP_BODY_BYTES).await else { + return StatusCode::PAYLOAD_TOO_LARGE.into_response(); + }; + + let req_id = uuid::Uuid::new_v4().to_string(); + let (tx, rx) = oneshot::channel(); + session.pending_http.lock().await.insert(req_id.clone(), tx); + + let frame = match serde_json::to_string(&ControlServerFrame::HttpReq { + host_id: host_id.clone(), + id: req_id.clone(), + method, + path: path_and_query, + headers, + body_b64: BASE64.encode(&body_bytes), + }) { + Ok(s) => s, + Err(_) => { + session.pending_http.lock().await.remove(&req_id); + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + } + }; + + if session.ctrl_tx.send(format!("{frame}\n")).is_err() { + session.pending_http.lock().await.remove(&req_id); + return StatusCode::BAD_GATEWAY.into_response(); + } + + let proxied = match tokio::time::timeout(HTTP_PROXY_TIMEOUT, rx).await { + Ok(Ok(res)) => res, + _ => { + session.pending_http.lock().await.remove(&req_id); + return StatusCode::GATEWAY_TIMEOUT.into_response(); + } + }; + + // Double check tenant isolation before returning response to caller + if proxied.host_id != host_id { + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + } + + let status = StatusCode::from_u16(proxied.status).unwrap_or(StatusCode::BAD_GATEWAY); + let mut response_headers = HeaderMap::new(); + for (k, v) in proxied.headers { + let lower = k.to_ascii_lowercase(); + if matches!( + lower.as_str(), + "transfer-encoding" | "connection" | "content-length" + ) { + continue; + } + if let (Ok(name), Ok(val)) = ( + HeaderName::from_bytes(k.as_bytes()), + HeaderValue::from_str(&v), + ) { + response_headers.insert(name, val); + } + } + if let Ok(routed_val) = HeaderValue::from_str(&host_id) { + response_headers.insert( + HeaderName::from_static("x-vibex-routed-host-id"), + routed_val, + ); + } + response_headers.insert( + header::ACCESS_CONTROL_ALLOW_ORIGIN, + HeaderValue::from_static("*"), + ); + + (status, response_headers, Body::from(proxied.body)).into_response() +} + +#[cfg(test)] +mod security_tests { + use super::*; + + #[test] + fn shared_cloud_discovery_beacon_topic_is_rejected() { + assert!(!is_allowed_private_beacon_topic("vbx-cloud-hosts-v1")); + assert!(!is_allowed_private_beacon_topic("")); + assert!(!is_allowed_private_beacon_topic("vbx-h-short")); + assert!(!is_allowed_private_beacon_topic( + "vbx-h-zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + )); + } + + #[test] + fn private_host_and_pairing_code_beacon_topics_are_accepted() { + let host_hash = &sha256_hex("vibex-host-v1:test-host")[..32]; + let pair_hash = &sha256_hex("vibex-pair-code-v1:ABCD2345")[..32]; + assert!(is_allowed_private_beacon_topic(&format!( + "vbx-h-{host_hash}" + ))); + assert!(is_allowed_private_beacon_topic(&format!( + "vbx-p-{pair_hash}" + ))); + } +} diff --git a/crates/relay-server/src/main.rs b/crates/relay-server/src/main.rs new file mode 100644 index 000000000..fc40dd620 --- /dev/null +++ b/crates/relay-server/src/main.rs @@ -0,0 +1,43 @@ +use std::{net::SocketAddr, path::PathBuf, sync::Arc}; + +use relay_server::{DEFAULT_RELAY_PORT, RelayServerState, run_relay_server}; +use tokio::net::TcpListener; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), + ) + .init(); + + let listen_raw = std::env::var("VIBEX_RELAY_LISTEN") + .ok() + .or_else(|| { + let mut args = std::env::args().skip(1); + while let Some(arg) = args.next() { + if arg == "--listen" { + return args.next(); + } + } + None + }) + .unwrap_or_else(|| format!("0.0.0.0:{DEFAULT_RELAY_PORT}")); + + let listen_addr: SocketAddr = listen_raw.parse()?; + let token_store_path = std::env::var("VIBEX_RELAY_TOKEN_STORE") + .ok() + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("vibex-relay-tokens.json")); + + let listener = TcpListener::bind(listen_addr).await?; + tracing::info!( + "VibeX Multi-Tenant Relay Server listening on {} (token store: {})", + listener.local_addr()?, + token_store_path.display() + ); + + let state = Arc::new(RelayServerState::new(Some(token_store_path))); + run_relay_server(listener, state).await +} diff --git a/crates/relay-server/tests/multi_tenant_isolation.rs b/crates/relay-server/tests/multi_tenant_isolation.rs new file mode 100644 index 000000000..473124287 --- /dev/null +++ b/crates/relay-server/tests/multi_tenant_isolation.rs @@ -0,0 +1,418 @@ +use std::{sync::Arc, time::Duration}; + +use axum::{ + Json, Router, + extract::{ + WebSocketUpgrade, + ws::{Message, WebSocket}, + }, + routing::{get, post}, +}; +use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64}; +use futures::{SinkExt, StreamExt}; +use relay_server::{ControlClientFrame, ControlServerFrame, RelayServerState, run_relay_server}; +use serde_json::{Value, json}; +use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + net::{TcpListener, TcpStream}, +}; + +async fn spawn_mock_desktop_host(host_id: &str, host_name: &str) -> u16 { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind mock host"); + let port = listener.local_addr().unwrap().port(); + let id = host_id.to_string(); + let name = host_name.to_string(); + + let app = Router::new() + .route( + "/health", + get({ + let id = id.clone(); + let name = name.clone(); + move || { + let id = id.clone(); + let name = name.clone(); + async move { + Json(json!({ + "status": "ok", + "host_id": id, + "name": name, + })) + } + } + }), + ) + .route( + "/api/v1/echo", + post({ + let id = id.clone(); + move |Json(payload): Json| { + let id = id.clone(); + async move { + Json(json!({ + "served_by_host_id": id, + "echo": payload, + })) + } + } + }), + ) + .route( + "/api/v1/ws", + get(move |ws: WebSocketUpgrade| { + let id = id.clone(); + async move { + ws.protocols(["vibex.v1"]) + .on_upgrade(move |socket| handle_mock_ws(socket, id)) + } + }), + ) + .with_state(()); + + tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + + port +} + +async fn handle_mock_ws(mut socket: WebSocket, host_id: String) { + while let Some(Ok(Message::Text(text))) = socket.next().await { + let reply = json!({ + "type": "pong", + "host_id": host_id, + "received": text.to_string(), + }) + .to_string(); + if socket.send(Message::Text(reply.into())).await.is_err() { + break; + } + } +} + +async fn spawn_host_relay_agent( + relay_addr: std::net::SocketAddr, + host_id: String, + token: String, + host_name: String, + local_port: u16, +) { + let stream = TcpStream::connect(relay_addr).await.expect("connect relay"); + let _ = stream.set_nodelay(true); + let (reader, mut writer) = stream.into_split(); + let name_b64 = BASE64.encode(host_name.as_bytes()); + let lan_b64 = BASE64 + .encode(serde_json::to_vec(&vec![format!("http://192.168.1.10:{local_port}")]).unwrap()); + writer + .write_all(format!("VIBEX-CTRL v2 {host_id} {token} {name_b64} {lan_b64}\n").as_bytes()) + .await + .expect("send ctrl hello"); + + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::(); + tokio::spawn(async move { + while let Some(line) = rx.recv().await { + if writer.write_all(line.as_bytes()).await.is_err() { + break; + } + } + }); + + let client = reqwest::Client::builder().no_proxy().build().unwrap(); + tokio::spawn(async move { + let mut lines = BufReader::new(reader).lines(); + while let Ok(Some(line)) = lines.next_line().await { + let trimmed = line.trim(); + if trimmed.starts_with("OK ") || trimmed.is_empty() { + continue; + } + let Ok(frame) = serde_json::from_str::(trimmed) else { + continue; + }; + match frame { + ControlServerFrame::Ping { ts } => { + let pong = serde_json::to_string(&ControlClientFrame::Pong { ts }).unwrap(); + let _ = tx.send(format!("{pong}\n")); + } + ControlServerFrame::ReplenishPool { count } => { + for _ in 0..count { + let host_id = host_id.clone(); + let token = token.clone(); + tokio::spawn(async move { + let Ok(data_stream) = TcpStream::connect(relay_addr).await else { + return; + }; + let _ = data_stream.set_nodelay(true); + let mut buf_stream = BufReader::new(data_stream); + if buf_stream + .get_mut() + .write_all( + format!("VIBEX-DATA v2 {host_id} {token} POOL\n").as_bytes(), + ) + .await + .is_err() + { + return; + } + let mut cmd_line = String::new(); + loop { + cmd_line.clear(); + let Ok(n) = buf_stream.read_line(&mut cmd_line).await else { + return; + }; + if n == 0 { + return; + } + let cmd = cmd_line.trim(); + if cmd == "NOOP" { + continue; + } + if let Some(target_host_id) = cmd.strip_prefix("USE ") { + if target_host_id.trim() != host_id { + return; + } + break; + } + } + let Ok(mut local) = TcpStream::connect(("127.0.0.1", local_port)).await + else { + return; + }; + let _ = local.set_nodelay(true); + let buffered = buf_stream.buffer().to_vec(); + let mut remote = buf_stream.into_inner(); + if !buffered.is_empty() && local.write_all(&buffered).await.is_err() { + return; + } + let _ = tokio::io::copy_bidirectional(&mut remote, &mut local).await; + }); + } + } + ControlServerFrame::OpenData { + host_id: target_host_id, + conn_id, + } => { + if target_host_id != host_id { + continue; + } + let host_id = host_id.clone(); + let token = token.clone(); + tokio::spawn(async move { + let Ok(mut remote) = TcpStream::connect(relay_addr).await else { + return; + }; + let _ = remote.set_nodelay(true); + if remote + .write_all( + format!("VIBEX-DATA v2 {host_id} {token} {conn_id}\n").as_bytes(), + ) + .await + .is_err() + { + return; + } + let Ok(mut local) = TcpStream::connect(("127.0.0.1", local_port)).await + else { + return; + }; + let _ = local.set_nodelay(true); + let _ = tokio::io::copy_bidirectional(&mut remote, &mut local).await; + }); + } + ControlServerFrame::HttpReq { + host_id: req_host_id, + id, + method, + path, + headers, + body_b64, + } => { + if req_host_id != host_id { + continue; + } + let client = client.clone(); + let tx = tx.clone(); + let host_id = host_id.clone(); + tokio::spawn(async move { + let url = format!("http://127.0.0.1:{local_port}{path}"); + let m = reqwest::Method::from_bytes(method.as_bytes()) + .unwrap_or(reqwest::Method::GET); + let mut req = client.request(m, &url); + for (k, v) in headers { + req = req.header(&k, &v); + } + let body = BASE64.decode(body_b64).unwrap_or_default(); + if !body.is_empty() { + req = req.body(body); + } + if let Ok(resp) = req.send().await { + let status = resp.status().as_u16(); + let mut out_headers = Vec::new(); + for (k, v) in resp.headers() { + if let Ok(s) = v.to_str() { + out_headers.push((k.as_str().to_string(), s.to_string())); + } + } + let resp_bytes = resp.bytes().await.unwrap_or_default(); + let frame = serde_json::to_string(&ControlClientFrame::HttpRes { + host_id, + id, + status, + headers: out_headers, + body_b64: BASE64.encode(&resp_bytes), + }) + .unwrap(); + let _ = tx.send(format!("{frame}\n")); + } + }); + } + } + } + }); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn multi_tenant_http_keepalive_and_websocket_strictly_isolated() { + let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let relay_listener = TcpListener::bind("127.0.0.1:0").await.expect("bind relay"); + let relay_addr = relay_listener.local_addr().unwrap(); + let state = Arc::new(RelayServerState::default()); + let state_clone = state.clone(); + tokio::spawn(async move { + let _ = run_relay_server(relay_listener, state_clone).await; + }); + + let port_alpha = spawn_mock_desktop_host("host-alpha", "MacBook Alpha").await; + let port_beta = spawn_mock_desktop_host("host-beta", "Workstation Beta").await; + + spawn_host_relay_agent( + relay_addr, + "host-alpha".to_string(), + "token_alpha_secret_123456".to_string(), + "MacBook Alpha".to_string(), + port_alpha, + ) + .await; + + spawn_host_relay_agent( + relay_addr, + "host-beta".to_string(), + "token_beta_secret_654321".to_string(), + "Workstation Beta".to_string(), + port_beta, + ) + .await; + + tokio::time::sleep(Duration::from_millis(80)).await; + + // 1. Verify token hijacking attempt against host-alpha is rejected + { + let mut attacker = TcpStream::connect(relay_addr).await.unwrap(); + attacker + .write_all(b"VIBEX-CTRL v2 host-alpha wrong_attacker_token_999999\n") + .await + .unwrap(); + let mut reader = BufReader::new(attacker); + let mut line = String::new(); + reader.read_line(&mut line).await.unwrap(); + assert!(line.starts_with("ERR unauthorized_host_token")); + } + + // 2. Fire 30 concurrent interleaved HTTP requests over a single Keep-Alive client pool + let client = reqwest::Client::builder() + .no_proxy() + .pool_max_idle_per_host(8) + .build() + .unwrap(); + + let mut handles = Vec::new(); + for i in 0..30 { + let client = client.clone(); + let target_host = if i % 2 == 0 { + "host-alpha" + } else { + "host-beta" + }; + handles.push(tokio::spawn(async move { + let url = format!("http://{relay_addr}/t/{target_host}/api/v1/echo"); + let resp = client + .post(&url) + .json(&json!({ "seq": i, "expected": target_host })) + .send() + .await + .expect("http echo"); + assert_eq!(resp.status(), 200); + let routed_header = resp + .headers() + .get("x-vibex-routed-host-id") + .unwrap() + .to_str() + .unwrap() + .to_string(); + assert_eq!(routed_header, target_host); + let body: Value = resp.json().await.unwrap(); + assert_eq!(body["served_by_host_id"], target_host); + assert_eq!(body["echo"]["seq"], i); + assert_eq!(body["echo"]["expected"], target_host); + })); + } + for h in handles { + h.await.unwrap(); + } + + // 3. Verify same-net and shared cloud discovery never leak online hosts across tenants + let disc: Value = client + .get(format!("http://{relay_addr}/v1/discover/same-net")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let hosts = disc["hosts"].as_array().unwrap(); + assert_eq!(hosts.len(), 0); + + let shared_beacon_post = client + .post(format!("http://{relay_addr}/v1/beacon/vbx-cloud-hosts-v1")) + .body(r#"{"host_id":"host-alpha"}"#) + .send() + .await + .unwrap(); + assert_eq!(shared_beacon_post.status(), 403); + + // 4. Verify concurrent WebSockets to host-alpha and host-beta never cross messages + let ws_url_alpha = format!("ws://{relay_addr}/t/host-alpha/api/v1/ws"); + let ws_url_beta = format!("ws://{relay_addr}/t/host-beta/api/v1/ws"); + + let (mut ws_alpha, _) = tokio_tungstenite::connect_async(&ws_url_alpha) + .await + .expect("connect ws alpha"); + let (mut ws_beta, _) = tokio_tungstenite::connect_async(&ws_url_beta) + .await + .expect("connect ws beta"); + + ws_alpha + .send(tokio_tungstenite::tungstenite::Message::Text( + "hello-alpha".into(), + )) + .await + .unwrap(); + ws_beta + .send(tokio_tungstenite::tungstenite::Message::Text( + "hello-beta".into(), + )) + .await + .unwrap(); + + let msg_a = ws_alpha.next().await.unwrap().unwrap().into_text().unwrap(); + let msg_b = ws_beta.next().await.unwrap().unwrap().into_text().unwrap(); + + let json_a: Value = serde_json::from_str(&msg_a).unwrap(); + let json_b: Value = serde_json::from_str(&msg_b).unwrap(); + + assert_eq!(json_a["host_id"], "host-alpha"); + assert_eq!(json_a["received"], "hello-alpha"); + assert_eq!(json_b["host_id"], "host-beta"); + assert_eq!(json_b["received"], "hello-beta"); +} diff --git a/crates/server/src/host/conversation.rs b/crates/server/src/host/conversation.rs index c7ca73360..76b84578e 100644 --- a/crates/server/src/host/conversation.rs +++ b/crates/server/src/host/conversation.rs @@ -252,6 +252,16 @@ impl ServerApplicationDomains { .await .map_err(|error| ApplicationError::bad_request(error.to_string()))?, } + if args.watch != Some(false) { + let _ = sqlx::query( + r#"UPDATE sessions + SET updated_at = datetime('now', 'subsec') + WHERE id = ? AND deleted_at IS NULL"#, + ) + .bind(id) + .execute(&self.pool) + .await; + } let idle_timeout_secs = agents::idle_timeout_from_env() .map(|timeout| timeout.as_secs()) .unwrap_or(0); diff --git a/crates/utils/src/tunnel.rs b/crates/utils/src/tunnel.rs index 5112a4b9f..38753d579 100644 --- a/crates/utils/src/tunnel.rs +++ b/crates/utils/src/tunnel.rs @@ -3,7 +3,7 @@ use std::net::IpAddr; pub const DEFAULT_TUNNEL_PORT: u16 = 17891; -pub const DEFAULT_OFFICIAL_RELAY_HOST: &str = ""; +pub const DEFAULT_OFFICIAL_RELAY_HOST: &str = "vibex.xforever.xin"; pub const DEFAULT_OFFICIAL_RELAY_PORT: u16 = 443; pub const RELAY_HEARTBEAT_INTERVAL_MS: u64 = 15_000; pub const RELAY_CONTROL_TIMEOUT_MS: u64 = 45_000; diff --git a/docs/companion/android-frontend.md b/docs/companion/android-frontend.md index 915a82dbe..66ce14867 100644 --- a/docs/companion/android-frontend.md +++ b/docs/companion/android-frontend.md @@ -72,8 +72,10 @@ mono 12/18。 ### 2.5 动效 -只做两处:信号条在 recovering 时缓慢呼吸;新时间线行从轨上长出 120ms。 -尊重 reduce-motion:两者都改瞬切。不要全页粒子、不要骨架屏闪烁循环。 +内容动效只做两处:信号条在 recovering 时缓慢呼吸;新时间线行从轨上长出 120ms。 +页面跳转统一走 `NavMotion`:底栏切换 160ms 交叉淡入;进入下一级从右侧滑入、返回原路滑出; +配对页自底部升起。 +尊重 reduce-motion:全部改瞬切。不要全页粒子、不要骨架屏闪烁循环。 ## 3. 信息架构(对照 CodeG) diff --git a/docs/companion/webrtc-remote-connectivity-spec.md b/docs/companion/webrtc-remote-connectivity-spec.md new file mode 100644 index 000000000..70a8c1f85 --- /dev/null +++ b/docs/companion/webrtc-remote-connectivity-spec.md @@ -0,0 +1,397 @@ +# VibeX 跨网络设备互联与 WebRTC 传输架构开发文档 + +- **文档状态**:Draft(架构设计与开发规范,暂不改动业务代码) +- **适用范围**:VibeX Desktop Host (`crates/server`, `crates/remote-protocol`, `crates/application`)、Android Companion (`mobile/android`)、iOS Companion (`mobile/ios`)、VibeX Cloud Signaling & TURN Service +- **关联文档**: + - [ADR-0033: Shared Application Core and Versioned Remote Transport](../adr/0033-shared-application-core-and-versioned-remote-transport.md) + - [ADR-0041: Native Kotlin Compose Android Companion](../adr/0041-native-kotlin-compose-android-companion.md) + - [ADR-0054: Host Family Distribution and Client Surfaces](../adr/0054-host-family-distribution-and-client-surfaces.md) + - [ADR-0059: Host Identity and Pairing Invitation](../adr/0059-host-identity-and-pairing-invitation.md) + - [ADR-0078: Host Command Registry Single Seam](../adr/0078-host-command-registry-single-seam.md) + - [ADR-0084: Native SwiftUI iOS Companion](../adr/0084-native-swiftui-ios-companion.md) + - [Host 事件与时间线折叠规范](./host-events.md) + +--- + +## 1. 设计背景与核心目标 + +### 1.1 解决的核心问题 +现有配对与连接依赖用户理解“局域网 IP、二维码重扫、USB `adb reverse`、手动远程隧道”,在以下真实场景中摩擦极大: +1. **公共/办公/校园 Wi-Fi 开启 AP 客户端隔离**:手机与电脑虽在同一子网(如 `172.24.0.0/16`),但二层 ARP 不通,局域网直连必现超时。 +2. **电脑开启代理软件 TUN 模式(Clash / Surge / Mihomo)**:虚拟网卡(`utun*`,`198.18.0.0/15`)污染局域网地址列表并劫持默认路由。 +3. **跨网段与移动场景**:用户从办公室 Wi-Fi 走到电梯(5G 蜂窝网络)再回到家,IP 变化导致连接中断或需手动切换入口。 +4. **连接假死与状态失真**:网络切换或前后台切换后,通道未及时恢复,或将连接超时错误展示为“高延迟”。 + +### 1.2 总体设计原则(五句话纲领) +1. **账号统一设备发现**:登录同一账号即可看到名下电脑及其实时在线/休眠状态,无需手工输入 IP 或端口。 +2. **设备密钥建立信任**:账号只负责“找到电脑”,首次连接必须经电脑端显式确认并绑定设备非对称公钥;登录同一账号不等于自动获得控制权。 +3. **WebRTC 优先直连,TURN 首包并行兜底**:从连接发起第 0 毫秒起同时收集局域网、STUN 与 TURN(UDP + TCP/TLS 443)候选,Trickle ICE 边收集边协商,谁先通就用谁。 +4. **业务层负责断线恢复与幂等**:WebRTC 只做传输管道,不承担业务可靠性;命令去重、漏消息补齐、会话恢复完全复用 VibeX 现有的持久序号(`sequence`)与命令注册表。 +5. **云服务可选,局域网兜底**:不强制所有用户注册登录云账号;未登录用户仍可使用本机与局域网扫码配对。 + +--- + +## 2. 用户体验与状态机规范(UX & State Machine Spec) + +### 2.1 首次使用体验(零配置信任建立) +```mermaid +sequenceDiagram + autonumber + actor User as 用户 + participant Host as 电脑端 (VibeX Host) + participant Cloud as 云端设备目录 & 信令 + participant Phone as 手机端 (Companion App) + + User->>Host: 1. 登录账号,开启「允许远程访问」 + Host->>Cloud: 注册 Host 身份 (host_id + Host Ed25519 公钥 + 在线租约) + User->>Phone: 2. 登录同一账号 + Phone->>Cloud: 拉取名下 Host 列表与在线状态 + Cloud-->>Phone: 返回电脑「MacBook Pro (在线)」 + User->>Phone: 3. 点击连接该电脑 + Phone->>Cloud: 发送绑定请求 (附手机 Ed25519 公钥 + 设备名 + 临时 ECDH 公钥) + Cloud->>Host: 推送授权请求 + Host->>User: 4. 弹出授权确认框(显示手机型号 + 4 位核对码 SAS) + User->>Host: 5. 点击「允许访问」(默认 Companion 权限集) + Host->>Host: 本地 SQLite 持久化手机公钥与权限集 + Host->>Cloud: 确认授权并直接下发 WebRTC Offer/Answer + Phone<<->>Host: 6. 建立 DTLS/SCTP DataChannel,进入会话列表 +``` + +### 2.2 日常使用与连接体验规范 +1. **零操作直连**: + - 手机冷启动后,若名下只有一台已授权电脑,直接自动发起连接并展示上次打开的项目/会话,不增加“选设备”步骤。 + - 名下有多台电脑时,默认连接上次活跃的电脑,顶部设备栏可一键切换其它电脑。 +2. **单一入口跨全网**: + - 同一 Wi-Fi、校园隔离网、5G 蜂窝网络、异地宽带全部走同一套自动寻路逻辑,**严禁在 UI 上让用户手动切换“局域网模式 / 公网模式 / 隧道模式”**。 +3. **精确区分电脑状态**: + - `Online(在线)`:绿色呼吸点,实时收发。 + - `Reconnecting(恢复中)`:手机切网或刚从后台切回,顶部细横幅无阻塞重连,允许查看已缓存内容。 + - `Host Sleeping(电脑已休眠)`:电脑合盖休眠前主动上报 `sleeping` 状态,手机明确展示“电脑已休眠”,进入离线只读模式。 + - `Host Offline(电脑已离线)`:电脑退出 VibeX 或断网超时,展示“电脑离线”,保留本地历史会话只读浏览。 +4. **指标展示规范(强制执行)**: + - **「上次连接耗时(Connect Duration)」** 与 **「实时网络往返延迟(RTT)」** 必须拆分为两个独立字段。 + - 连接失败或超时时,必须明确展示 `连接失败(原因:电脑离线 / 网络受限 / 授权已撤销)`,**严禁将 48 秒超时时间显示为 `48000ms` 延迟**。 + +--- + +## 3. 系统架构与 VibeX 接入边界 + +### 3.1 分层架构图 +```mermaid +flowchart TB + subgraph Mobile["移动端 (Android / iOS Companion)"] + UI["UI 层 (Timeline / PromptBar / ApprovalCard / TaskDock)"] + Core["纯逻辑层 (CompanionModel / EventFold / TimelineSession)"] + Api["协议客户端 (HostApi + SubscriptionClient)"] + Mux["多路传输管理器 (TransportMultiplexer)"] + LanTrans["局域网适配器 (Http + WS)"] + RtcTrans["WebRTC 适配器 (DataChannel Ch0 + Ch1)"] + UI --> Core --> Api --> Mux + Mux --> LanTrans + Mux --> RtcTrans + end + + subgraph Cloud["VibeX 云端基础设施 (仅控制面与中转)"] + OIDC["OIDC 身份认证"] + Dir["设备目录与授权元数据 (PostgreSQL)"] + Sig["信令与在线状态服务 (Rust/Axum + Redis)"] + Turn["TURN 中继集群 (coturn UDP + TCP/TLS 443)"] + end + + subgraph Desktop["桌面端 (VibeX Host 进程 - 独立于窗口)"] + HostRtc["Host WebRTC 适配器 (RtcPeerEngine)"] + HostHttp["本地 Axum HTTP / WS 服务 (:17891)"] + Dispatcher["统一分发层 (CommandRegistry + SubscriptionHub)"] + Auth["设备鉴权与幂等账本 (SqliteServerAuth + IdempotencyLedger)"] + Repo["会话与工作区核心 (ConversationRepository + ACP Agents)"] + HostRtc --> Dispatcher + HostHttp --> Dispatcher + Dispatcher --> Auth --> Repo + end + + RtcTrans <-->|"1. HTTPS/WSS 信令交换"| Sig + HostRtc <-->|"1. HTTPS/WSS 信令长连接"| Sig + RtcTrans <-->|"2a. P2P 直连 (LAN / STUN SRFLX)"| HostRtc + RtcTrans <-->|"2b. 自动兜底中转 (TURN UDP / TLS 443)"| Turn + Turn <--> HostRtc + LanTrans <-->|"局域网 Happy Eyeballs / 离线直连"| HostHttp +``` + +### 3.2 VibeX 现有模块复用与改造边界 + +| 现有能力 | 代码位置 | 处理方式 | 规范要求 | +| :--- | :--- | :--- | :--- | +| **Host 身份 (`host_id`)** | `crates/utils/src/assets.rs` (`load_or_create_host_id`)
`/host-identity.json` | **直接复用** | 云端设备目录直接关联现有 `host_id`,在同一身份文件中补充或关联 Host 的 Ed25519 公钥。 | +| **网卡枚举与代理过滤** | `crates/utils/src/net.rs` (`host_interface_addresses`, `is_advertisable_ipv4`) | **扩展增强** | 复用已有 `198.18.0.0/15` / loopback / link-local 过滤,新增虚拟隧道网卡名黑名单(非 Tailscale 的 `utun*`/`tun*` 等)与物理网卡绑定。 | +| **设备权限体系** | `crates/remote-protocol/src/device_auth.rs` (`DevicePermissionPreset`)
`mobile/ios/Sources/CompanionCore/CompanionScopes.swift` | **直接复用** | 保持 `companion` 预设权限边界(可读会话、可发消息、可审批、禁止越权写插件/任意宿主机命令)。 | +| **设备鉴权与存储** | `crates/server/src/auth.rs` (`SqliteServerAuth`)
`crates/db/migrations/` | **扩展字段** | 在 `server_device_credentials` 表扩展 `public_key_ed25519` 字段与 `companion_idempotency_ledger` 幂等去重账本表;同一 `DeviceId` 同时支持 Bearer `token_hash`(局域网 HTTP/WS)与 Ed25519 公钥(WebRTC DTLS 绑定),一次配对双通道通用。 | +| **业务命令分发** | `crates/application/src/command.rs` (`CommandRegistry::execute_name`)
`crates/server/src/runtime.rs` (`/api/v1/call/{command}`) | **100% 复用** | WebRTC 控制通道收到的 RPC 请求直接路由至 `CommandRegistry::execute_name` 及只读端点(`capabilities` / `offline` / `notification_summary`),复用 `CommandRequest.operation_id`,不写第二套业务逻辑。 | +| **会话事件与增量补齐** | `crates/server/src/ws.rs`
`crates/remote-protocol/src/subscription.rs` | **100% 复用** | WebRTC 事件流直接复用 `SubscriptionClientMessage`(`attach` / `detach` / `ping`)与 `SubscriptionServerMessage`(`ready` / `snapshot` / `event` / `live` / `detached` / `pong` / `error`)及 `after_sequence` 机制。 | +| **局域网 HTTP / WS** | `crates/server/src/runtime.rs`
`mobile/ios/Sources/CompanionCore/HostClient.swift` | **完整保留** | 作为未登录云账号时的离线入口,以及同局域网下的 Happy Eyeballs 加速通道。 | +| **宿主进程生命周期** | `src-tauri/` + `crates/server` | **强制约束** | **WebRTC 引擎必须运行在 Rust Host 后台服务侧**,绝不能运行在前端 Tauri WebView 窗口中。 | + +--- + +## 4. 连接策略与穿透工程规范(WebRTC + ICE + TURN) + +### 4.1 Happy Eyeballs 并发寻路策略 +手机端发起连接时,由 `TransportMultiplexer` 自动执行以下流水线(用户无感知): +1. **第 0ms 同时启动**: + - **WebRTC Trickle ICE 全量通道**:向信令服务发送连接请求,同时向本机网卡、STUN、TURN(UDP 与 TCP/TLS 443)发起候选收集(**严禁等直连超时后再申请 TURN 候选**)。 + - **局域网快速探针(仅当设备目录含局域网地址或本地已缓存时)**:并发对局域网地址发起 250ms 超时的健康/鉴权探测。 +2. **路径选定与防抖(Anti-Flapping)**: + - ICE 按标准优先级自动优选可用的直连路径(`host` > `srflx` > `prflx` > `relay`)。 + - **关键稳定性红线**:一旦通过 `relay`(TURN 中转)成功建立连接并正在进行会话交互,**严禁为了追求“必须 P2P”而主动断开或频繁重协商打断当前正在进行的生成/审批操作**。仅在下一次空闲心跳周期或网络接口发生变化时才尝试平滑迁移。 + +### 4.2 本机代理虚拟网卡(TUN)与 AP 隔离防御规范 +针对桌面端开启 Clash / Surge / Mihomo / VPN 等工具的场景,Rust Host 端必须满足以下硬性规范: +1. **虚拟接口与保留网段黑名单**: + - 在枚举 Host Candidate 时,必须过滤: + - 基准测试与 Fake-IP 网段:`198.18.0.0/15`(`198.18.0.0` ~ `198.19.255.255`) + - 链路本地与环回:`127.0.0.0/8`、`169.254.0.0/16`、`fe80::/10` + - 代理虚拟隧道网卡:非 Tailscale(`100.64.0.0/10`)的 `utun*`、`tun*`、`tap*`、`veth*`、`docker*` +2. **物理出口网卡绑定(Socket Interface Binding)**: + - Host 侧发起 STUN / TURN 连接时,应探测系统真实物理默认网关网卡(如 macOS `en0`),通过 `IP_BOUND_IF`(macOS)或 `SO_BINDTODEVICE`(Linux)绑定物理网卡,防止 TURN UDP 流量被本机 TUN 代理规则吞噬。 + +### 4.3 TURN 生产服务配置规范(`coturn`) +1. **多协议入口**: + - `UDP 3478`:常规低延迟穿透与中转路径。 + - `TCP / TLS 443`:针对禁用 UDP 的企业网/校园网/严格防火墙。**注意:TURN 443 端口必须直连 `coturn` 进程或四层负载均衡(NLB/HAProxy TCP),严禁套在 Nginx/Cloudflare 普通七层 HTTP 反向代理后面**。 + - **明确支持边界**:对于强制要求所有 443 流量通过企业 HTTP CONNECT 代理并实施 SSL 解密审查的极端内网,文档与错误提示需明确告知不支持,不做“100% 穿透一切网络”的虚假承诺。 +2. **短期动态凭据(REST API Ephemeral Credentials)**: + - 严禁在客户端硬编码静态 TURN 账号密码。 + - 采用 `coturn` 标准 `use-auth-secret`(HMAC-SHA1 动态令牌):信令服务在验证设备授权关系后,动态签发有效期为 **600 秒(10 分钟)** 的临时凭据(`username = ":"`)。 +3. **配额与带宽保护**: + - 单设备最大并发 Allocation 数:`<= 4`。 + - 单会话带宽上限(`bps-capacity`):`2,097,152 bps`(约 2MB/s,足以支撑实时流式对话、代码浏览与 Diff 传输,同时防止恶意跑满云带宽)。 + - 安全禁止项:必须在 `coturn` 中开启 `no-loopback-peers`、`no-multicast-peers` 并屏蔽云内网元数据网段(`10.0.0.0/8`、`169.254.169.254` 等),防止 SSRF 攻击。 + +--- + +## 5. 信任机制、密钥绑定与撤销闭环规范 + +### 5.1 端到端设备密钥体系 +1. **密钥算法**:统一采用标准 **Ed25519**(签名/验签)与 **X25519**(密钥协商),使用经过安全审计的标准密码库(Rust 端使用 `ed25519-dalek` / `ring`;Android 使用 `AndroidKeyStore` / `Tink`;iOS 使用 `CryptoKit` + `Keychain`)。**严禁自创加密算法或手写密码学原语**。 +2. **密钥生命周期**: + - 每台客户端与每台 Host 在首次初始化时生成独立的设备身份密钥对。 + - 私钥永久保存在操作系统安全存储中,不可导出;云端设备目录仅存储设备公钥与基础元数据(设备名、系统类型、创建时间)。 + +### 5.2 信令与 DTLS 信道绑定(Channel Binding) +为防止信令服务器被攻破或重放攻击,采用 **SDP DTLS 指纹签名绑定**: +1. 手机与 Host 在生成 WebRTC SDP `offer` / `answer` 时,提取 SDP 中的本端 DTLS 证书指纹(`a=fingerprint:sha-256 `)。 +2. 发送方构造签名原文: + ```text + vibex-webrtc-v1||||| + ``` +3. 使用本端 **Ed25519 私钥** 对上述原文签名,随信令包一同发送。 +4. 接收方收到信令后: + - 第一步:检查 `recipient_device_id`、`unix_timestamp`(允许 ±60s 偏差)及 `session_nonce` 是否重放。 + - 第二步:使用本地已信任的对方 **Ed25519 公钥** 验证签名。 + - 第三步:验签通过后,强制校验后续 DTLS 握手对端证书哈希与签名中的 `` 完全一致。 +5. **效果**:无需在 DataChannel 内再套一层 TLS,直接把 WebRTC 原生 DTLS 信道死死绑定在双方的硬件级设备密钥上。 + +### 5.3 首次授权与防弹窗冒充(SAS 核对码) +1. 新设备首次请求连接某台 Host 时,Host 绝不自动放行。 +2. Host 与手机基于双方公钥与 `session_nonce` 计算 HKDF,取前 2 字节生成 **4 位十进制核对码(SAS,如 `8392`)**。 +3. 手机屏幕显示“正在等待电脑确认(核对码:`8392`)”,电脑弹窗显示“手机 `Honor DIO-AN00` 请求访问(核对码:`8392`)”。 +4. 用户在电脑端点击「允许」后,Host 将 `{ device_id, public_key_ed25519, scopes, trusted_at }` 写入本地 SQLite `server_device_credentials` 表,并同步授权关系摘要至云端。 + +### 5.4 设备撤销三级闭环(Revocation Closure) +当用户在电脑端或账号中心撤销某台手机时,必须同时完成以下三步: +1. **云端即时拒签**:云端设备目录将该授权标记为 `revoked`,立即停止向该手机签发新的 TURN 凭据,并拒绝转发其发往该 Host 的任何信令。 +2. **在线 Host 秒级断连**:云端通过信令长连接向在线 Host 推送 `device_revoked` 事件;Host 立即更新本地 SQLite,并主动销毁(`close()`)该设备当前活跃的所有 WebRTC PeerConnection 与本地 WebSocket 会话。 +3. **离线 Host 启动同步**:若撤销发生时 Host 处于休眠/离线状态,Host 下次启动连接云端时,**必须先完成撤销列表同步并更新本地 SQLite,然后才开始处理任何入站连接请求**。 + +--- + +## 6. 双 DataChannel 协议与业务恢复规范 + +### 6.1 双 DataChannel 职责与流控规范 + +在同一 `RTCPeerConnection` 下固定创建两条 DataChannel: + +| 通道名称 | Label | 配置属性 | 承载内容 | 限流与背压规范 | +| :--- | :--- | :--- | :--- | :--- | +| **控制与事件通道** | `vibex.control.v1` | `ordered = true`
`maxRetransmits = null` (可靠) | 1. RPC 请求与响应(发送消息、审批、回答问题、模式切换)
2. 会话订阅 (`attach`) 与实时增量事件 (`event`)
3. 应用层心跳 (`ping`/`pong`) | 单帧最大 `64KB`;高优先级立即入队。 | +| **批量数据通道** | `vibex.bulk.v1` | `ordered = true`
`maxRetransmits = null` (可靠) | 1. 工作区文件树与文件内容读取
2. 大体积 Git Unified Diff
3. 图片/附件分块上传与下载 | **强制分片**:每片 `16KB ~ 32KB`。
**水位线背压**:设置 `bufferedAmountLowThreshold = 64KB`;当 `bufferedAmount > 128KB` 时立即暂停写入,等待 `onBufferedAmountLow` 触发,严禁填满底层 SCTP 拥塞窗口阻塞控制通道。 | + +### 6.2 控制通道与批量通道帧协议(JSON Envelope) +为实现与现有 `CommandRegistry`([ADR-0078](../adr/0078-host-command-registry-single-seam.md))、`HostClient` 和 `ws.rs` 零成本对接,消除双套信封或双套幂等键: +- 命令调用直接复用 `CommandRequest` 的 `operation_id` 作为唯一请求 ID 与幂等去重键(与 [host-events.md](./host-events.md) 第 3 节「所有写都带客户端生成的 `operation_id`,重试同一 id 不得产生第二条输入」保持严格一致)。 +- 订阅控制与推送帧直接内嵌 `crates/remote-protocol/src/subscription.rs` 中的 `SubscriptionClientMessage` 与 `SubscriptionServerMessage` 序列化结构,不做二次字段重命名。 + +```json +// 1. 命令调用请求帧 (对应 POST /api/v1/call/{command} 的 CommandRequest) +{ + "frame": "rpc_request", + "operation_id": "01930c8a-7b12-7000-8000-000000000001", + "command": "conversation_input_submit", + "args": { + "request": { + "conversationId": "c8b6d31f-0000-4000-8000-000000000000", + "payload": { + "agentId": "claude_code", + "workspaceId": "w1", + "text": "帮我检查一下单元测试" + } + } + } +} + +// 2. 命令调用成功响应帧 (对应 CommandResponse) +{ + "frame": "rpc_response", + "operation_id": "01930c8a-7b12-7000-8000-000000000001", + "status": 200, + "data": { "inputId": "f1e2d3c4-0000-4000-8000-000000000000", "status": "submitted" } +} + +// 3. 命令调用错误响应帧 (对应 ErrorEnvelope) +{ + "frame": "rpc_error", + "operation_id": "01930c8a-7b12-7000-8000-000000000001", + "status": 409, + "error": { + "code": "conflict", + "message": "turn has already completed", + "retryable": false, + "operation_id": "01930c8a-7b12-7000-8000-000000000001" + } +} + +// 4. 订阅控制帧 (100% 复用 SubscriptionClientMessage) +{ + "frame": "sub_client", + "payload": { + "type": "attach", + "request": { + "subscription_id": "01930c8a-7b12-7000-8000-000000000010", + "resource": "conversation", + "conversation_id": "c8b6d31f-0000-4000-8000-000000000000", + "after_sequence": 142 + } + } +} + +// 5. 订阅服务端推送帧 (100% 复用 SubscriptionServerMessage) +{ + "frame": "sub_server", + "payload": { + "type": "event", + "subscription_id": "01930c8a-7b12-7000-8000-000000000010", + "event": { + "sequence": 143, + "kind": "assistant_text_delta", + "payload": { "message_id": "m1", "delta": "好的,我来检查..." } + } + } +} +``` + +对于大体积只读命令(如 `conversation_workspace_diff`、`conversation_workspace_file`、`conversation_timeline_image`、`conversation_timeline_page`),请求经 `vibex.bulk.v1` 发出或当响应序列化体积超过 `32KB` 时自动在 `vibex.bulk.v1` 按分片帧(`bulk_start` → `bulk_chunk` × N → `bulk_end`,支持客户端发送 `bulk_cancel` 中途终止)传输。 + +### 6.3 六大异常场景恢复规范 + +| 异常场景 | 客户端行为规范 | Host 端行为规范 | +| :--- | :--- | :--- | +| **1. 手机断线,电脑仍在生成回复** | 保持本地已收到的 `lastSequence`(持久化在 `OfflineStore`);重连成功后立即发送 `attach(after_sequence = lastSequence)`。 | Agent 执行与本地 SQLite 事件落盘完全不受客户端断线影响;收到重连 `attach` 后从 `lastSequence + 1` 补发全部增量事件。 | +| **2. 命令发出后断网,不知是否成功** | 为每条写操作(发消息、审批、回答问题)生成唯一 `operation_id`(UUIDv7);断线重连后对未收到确认的命令使用**原 `operation_id`** 重试。 | 维护 SQLite 幂等账本 `companion_idempotency_ledger`(保留 24 小时):若同一 `(device_id, operation_id)` 已执行,直接回放上次 `CommandResponse`,**严禁重复执行**。 | +| **3. Wi-Fi 切换蜂窝网络** | 监听系统网络变更回调:先触发 `ICE Restart`(耗时通常 300~800ms);若 3 秒内未恢复,立即销毁旧 PeerConnection 重建新连接并自动重发 `after_sequence` 订阅。 | 支持对同一设备会话无缝切换底层 PeerConnection,自动接管订阅游标。 | +| **4. 手机切后台与回到前台** | **切后台 > 15s**:若无大文件传输,主动发送 `suspend` 并关闭 PeerConnection 省电。
**回前台**:在重连信令 `Offer` 中捎带 `{ conversation_id, after_sequence }`;收到信令 `Answer` 时优先渲染捎带的增量事件,同时等待 DataChannel 连通。 | 收到带游标的 `Offer` 时,若增量事件总大小 `<= 32KB`,直接将增量事件列表打包进信令 `Answer` 返回(**Signaling Piggyback**),实现“回前台秒级刷出新消息”。 | +| **5. 电脑进程重启** | 重连后通过 `capabilities` 与会话快照校准 `inFlightTurnId` 与真实运行状态,清理过期悬空的本地 Loading 态。 | 启动时根据持久化的会话状态恢复真实状态,**绝不因为客户端重连而自动重复启动已中断的任务**。 | +| **6. 大文件/大 Diff 传输中聊天与审批** | 批量通道拉取大 Diff 时按 16KB~32KB 分片接收,支持中途取消(`bulk_cancel`)。 | 严格执行批量通道 `128KB` 缓冲区上限背压,确保控制通道的审批与聊天指令 0 排队优先发出。 | + +--- + +## 7. 组件选型、分阶段开发路线与编码规范 + +### 7.1 核心组件技术选型 + +| 模块 | 选型方案 | 选型理由与约束 | +| :--- | :--- | :--- | +| **信令与设备目录服务** | **Rust + Axum + Tokio** | 与 VibeX 桌面后端技术栈 100% 一致,可共享 `crates/remote-protocol` 中的数据结构定义。 | +| **账号身份认证** | **标准 OIDC 服务** | 复用成熟 OIDC 身份提供商,不自建密码哈希与找回体系。 | +| **持久化元数据存储** | **PostgreSQL** | 存储用户账号、Host 注册信息、设备公钥及授权关系权威数据。 | +| **在线状态与信令路由** | **Redis** | 仅存储 Host 在线心跳租约(TTL 45s)与跨信令实例的 WebSocket 路由,**绝不作为设备授权的权威数据源**。 | +| **TURN 中继服务** | **coturn** | 工业级标准,支持 UDP / TCP / TLS 443 与 HMAC 动态短期凭据。 | +| **Android / iOS WebRTC** | **原生 `libwebrtc` 预编译包** | 移动端社区成熟度最高,硬件网络切换适配最完善。 | +| **Rust Host WebRTC** | **定义 `RtcPeerEngine` Trait,原型期对比验证 `libdatachannel` 绑定与 `str0m`** | VibeX 仅需 DataChannel(ICE + DTLS + SCTP),无需 100MB+ 的音视频编解码管线;必须在 macOS / Windows / Linux 三端完成与移动端 `libwebrtc` 的跨平台压测后再锁定最终实现。 | +| **离线推送通知** | **APNs (iOS) + FCM / 系统推送 (Android)** | 仅在任务完成、出错或需要审批/提问且设备处于后台离线时触发;**推送 Payload 仅含会话 ID 与状态类型,严禁包含任何敏感代码或对话正文**。 | + +### 7.2 四阶段研发路线图(Phased Roadmap) + +#### Phase 0:独立验证原型(PoC,不改动现有主干业务代码) +- **目标**:独立 CLI / Demo 验证“真实手机外网连接、TURN 443 兜底、切网恢复、Ed25519 密钥授权”四件事。 +- **交付物**: + 1. 最小信令服务 + `coturn` 部署脚本。 + 2. Rust Host CLI 原型与移动端测试页,跑通 `vibex.control.v1` 与 `vibex.bulk.v1` 双通道收发。 + 3. 输出实测报告:覆盖电脑开 Clash TUN、手机 5G 蜂窝网、Wi-Fi 切蜂窝、UDP 封禁走 TLS 443 四类场景的连通率与耗时。 + +#### Phase 1:Host 端幂等账本、设备密钥绑定与传输抽象层 +- **目标**:在 `crates/server` 与 `crates/remote-protocol` 中完成传输层解耦与安全加固。 +- **交付物**: + 1. `server_device_credentials` 扩展 Ed25519 公钥存储与撤销同步接口。 + 2. 新增 `companion_idempotency_ledger` 表与基于 `CommandRequest.operation_id` 的写命令去重机制。 + 3. 抽离 `TransportSession` 统一接口,使本地 HTTP/WS 与 WebRTC DataChannel 共用同一套 `CommandRegistry` 与订阅分发逻辑。 + +#### Phase 2:移动端 `TransportMultiplexer` 与无感连接体验接入 +- **目标**:Android (`companion-core` + `app`) 与 iOS (`mobile/ios`) 接入设备目录与 WebRTC 适配器。 +- **交付物**: + 1. 实现 `WebRtcTransport`(承载 `HostApi` 与 `EventSocket` 契约)及 `Happy Eyeballs` 局域网/WebRTC 并发选择器。 + 2. 实现前后台生命周期管理(15s 后台挂起 + 回前台信令 Piggyback 增量恢复)。 + 3. 改造连接状态 UI:展示设备列表、在线/休眠状态,拆分“连接用时”与“实时延迟”。 + +#### Phase 3:混沌测试、可观测性埋点与生产灰度 +- **目标**:按第 8 节上线标准完成全场景验收与指标监控。 + +### 7.3 开发规范(Coding & Engineering Standards) + +1. **模块深模块原则(Deep Modules)**: + - 上层业务(`TimelineScreen`、`CompanionModel`、`EventFold`)**严禁感知 WebRTC、ICE Candidate、SDP 或 TURN 的存在**。 + - 传输层对上只暴露: + - `ConnectionState`(`Offline` / `Connecting` / `Online` / `Recovering` / `HostSleeping` / `AuthRequired`) + - `executeRpc(request): Response` + - `subscribeEvents(conversationId, afterSequence): Flow` +2. **所有超时与魔法数字必须配置化并有明确语义**: + - 信令握手超时:`5,000 ms` + - Happy Eyeballs 局域网优先窗口:`200 ms` + - 全路径 ICE 建连总超时:`12,000 ms` + - DataChannel 心跳间隔:`15,000 ms`(3 秒未收到 `pong` 立即触发通道探测/ICE Restart) +3. **安全红线(Security Redlines)**: + - 严禁在日志、崩溃上报或信令服务器落盘日志中打印 `access_token`、私钥、SDP 明文聊天内容或 TURN 长期密钥。 + - 严禁信任客户端上报的权限声明;所有 RPC 命令在 Host 端必须通过 `AuthenticatedCredential::allows(scope)` 强制鉴权。 + - 严禁在云端 Redis/PostgreSQL 中存储用户的会话正文、代码片段或 Git Diff。 + +--- + +## 8. 上线验收标准与观测指标(Production Acceptance Matrix) + +在未完成以下矩阵实测并获得真实数据前,不得对外承诺连接成功率或连接耗时指标。 + +### 8.1 必测网络与故障场景矩阵 + +| 编号 | 测试场景 | 预期行为与通过标准 | +| :--- | :--- | :--- | +| **S1** | 家庭宽带(NAT3/NAT4)与手机 5G 蜂窝网络互连 | Trickle ICE 自动完成 STUN 直连或 TURN UDP 中转,无需任何手动配置。 | +| **S2** | 运营商 CGNAT / 双重对称型 NAT(Symmetric NAT) | 首包并发收集的 TURN 候选在直连无法打通时无缝接管,总建连时间不因等待直连超时而劣化。 | +| **S3** | 电脑开启 Clash / Surge / Mihomo TUN 模式 + 校园网 AP 隔离 | Host 自动过滤 `198.18.0.0/15` 虚拟网卡并绑定物理网卡连通信令/TURN;手机跨过隔离的局域网直接通过 WebRTC 连通。 | +| **S4** | 防火墙完全禁用 UDP(仅开放 TCP 80/443) | 自动回落至 `coturn` 的 `TURNS (TLS over TCP 443)` 候选并建立 DataChannel。 | +| **S5** | IPv4 / IPv6 纯栈与双栈混合环境 | 双栈候选正常收集与配对,不因 IPv6 ULA (`fd00::/8`) 不可达而卡死。 | +| **S6** | AI 正在流式输出时,手机关闭 Wi-Fi 切换至 5G | 触发 ICE Restart 或自动重连,通过 `after_sequence` 补齐断网期间生成的 token,最终文本无缺失、无乱序。 | +| **S7** | 点击「发送消息」或「允许权限」瞬间断网,3 秒后恢复 | 重连后携带同一 `operation_id` 重试,Host 幂等账本拦截重复执行并回放原响应,会话中只出现一条消息。 | +| **S8** | 手机切后台 60 秒后切回前台 | 后台自动释放连接;回前台通过信令捎带(Piggyback)在 1 秒内刷新出断线期间的新消息并恢复实时流。 | +| **S9** | 正在加载 2MB Git Diff 时点击「批准权限」 | 批量通道严格受 `128KB` 背压限制,控制通道的审批请求在 `< 200ms` 内得到响应,无队头阻塞。 | +| **S10** | 电脑端点击「撤销该手机设备」 | 在线手机在 `< 2s` 内被强制断开并跳转至未授权页;重放旧信令或旧请求全部被拒绝。 | + +### 8.2 必须采集的 5 项核心遥测指标 +1. **连接成功率与失败归因分布**(区分:`host_offline` / `auth_revoked` / `signaling_timeout` / `ice_all_failed` / `dtls_handshake_failed`)。 +2. **耗时分位数(P50 / P90 / P99)**: + - `cold_connect_ms`(冷启动首次建连耗时) + - `foreground_resume_ms`(从后台切回前台恢复可用耗时) +3. **路径分布比例**: + - `lan_direct_ratio`(局域网直连占比) + - `webrtc_p2p_ratio`(STUN P2P 直连占比) + - `webrtc_turn_udp_ratio`(TURN UDP 中转占比) + - `webrtc_turn_tls443_ratio`(TURN TLS 443 中转占比)及单设备日均 TURN 流量消耗。 +4. **通道健康度**:连接建立后的真实 DataChannel `ping/pong` 往返延迟(RTT ms)。 +5. **业务恢复准确度**:每次重连补齐的增量事件数(`replayed_events_count`)与幂等账本命中次数(`idempotency_hit_count`)。 diff --git a/mobile/android b/mobile/android index 95e0c7dbd..c40b5fa1b 160000 --- a/mobile/android +++ b/mobile/android @@ -1 +1 @@ -Subproject commit 95e0c7dbd67d50a19e652859c7b6a784d4771e7d +Subproject commit c40b5fa1bdae1f8b09e4554e9652027eb09ceb7a diff --git a/mobile/ios b/mobile/ios index 9d19c236f..ea86542df 160000 --- a/mobile/ios +++ b/mobile/ios @@ -1 +1 @@ -Subproject commit 9d19c236fb5cf501b06972e5f4e6fb4f85cedd77 +Subproject commit ea86542df60933975a9c3eb07aa5427b0aef9173 diff --git a/scripts/deploy-relay-server.sh b/scripts/deploy-relay-server.sh new file mode 100644 index 000000000..cacce7b6e --- /dev/null +++ b/scripts/deploy-relay-server.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +set -euo pipefail + +LISTEN_PORT="${VIBEX_RELAY_PORT:-17890}" +INSTALL_BIN="/usr/local/bin/vibex-relay-server" +STATE_DIR="/var/lib/vibex-relay" +SERVICE_FILE="/etc/systemd/system/vibex-relay.service" + +echo "==> [1/4] Preparing directories and kernel limits..." +sudo mkdir -p "${STATE_DIR}" + +if [ -f "Cargo.toml" ] && [ -d "crates/relay-server" ]; then + echo "==> [2/4] Building vibex-relay-server (release)..." + cargo build --release -p relay-server --bin vibex-relay-server + sudo install -m 0755 target/release/vibex-relay-server "${INSTALL_BIN}" +elif [ -f "./vibex-relay-server" ]; then + echo "==> [2/4] Installing prebuilt vibex-relay-server..." + sudo install -m 0755 ./vibex-relay-server "${INSTALL_BIN}" +else + echo "Error: Neither Cargo workspace nor ./vibex-relay-server binary found in current directory." >&2 + exit 1 +fi + +echo "==> [3/4] Writing systemd unit ${SERVICE_FILE}..." +sudo tee "${SERVICE_FILE}" >/dev/null < [4/4] Starting and enabling vibex-relay.service..." +sudo systemctl daemon-reload +sudo systemctl enable --now vibex-relay.service +sleep 1 +sudo systemctl --no-pager --full status vibex-relay.service + +echo "" +echo "✅ VibeX Relay Server is live on 0.0.0.0:${LISTEN_PORT}" +echo " Health check: curl -s http://127.0.0.1:${LISTEN_PORT}/health" diff --git a/src-tauri/src/commands/host_tunnel.rs b/src-tauri/src/commands/host_tunnel.rs index 1b115f898..7912d2d28 100644 --- a/src-tauri/src/commands/host_tunnel.rs +++ b/src-tauri/src/commands/host_tunnel.rs @@ -196,14 +196,17 @@ fn default_official_quick_origin() -> Option { } fn all_published_origin_strings(store: &HostTunnelStore) -> Vec { - if !store.enabled { - return Vec::new(); - } let mut origins = Vec::new(); - if let Some(custom) = active_published_origin(store) { - origins.push(custom); - } - if let Some(quick) = default_official_quick_origin() + if store.enabled { + if let Some(custom) = active_published_origin(store) { + origins.push(custom); + } + if let Some(quick) = default_official_quick_origin() + && !origins.contains(&quick) + { + origins.push(quick); + } + } else if let Some(quick) = quick_tunnel_origin() && !origins.contains(&quick) { origins.push(quick); @@ -582,19 +585,50 @@ fn sha256_hex(input: &str) -> String { out } -const SHARED_CLOUD_DISCOVERY_TOPIC: &str = "vbx-cloud-hosts-v1"; - async fn publish_domestic_beacon(relay_host: &str, relay_port: u16, host_id: &str, origin: &str) { - let host_name = utils::net::local_hostname().unwrap_or_else(|| "VibeX Desktop".to_string()); let payload = serde_json::json!({ "v": 2, "host_id": host_id, - "name": host_name, "origin": origin, "ts": Utc::now().timestamp(), }); let host_hash = &sha256_hex(&format!("vibex-host-v1:{host_id}"))[..32]; let topic = format!("vbx-h-{host_hash}"); + post_relay_beacon_topic(relay_host, relay_port, &topic, &payload).await; +} + +pub async fn publish_pairing_code_beacon(connection_code: &str, host_id: &str) { + let clean_code: String = connection_code + .trim() + .chars() + .filter(|c| !c.is_whitespace() && *c != '-') + .collect::() + .to_ascii_uppercase(); + if clean_code.is_empty() || host_id.trim().is_empty() { + return; + } + let Some(endpoint) = utils::tunnel::official_relay_endpoint(None) else { + return; + }; + let origin = quick_tunnel_origin() + .unwrap_or_else(|| utils::tunnel::format_tenant_origin("https", &endpoint, host_id)); + let payload = serde_json::json!({ + "v": 2, + "host_id": host_id, + "origin": origin, + "ts": Utc::now().timestamp(), + }); + let code_hash = &sha256_hex(&format!("vibex-pair-code-v1:{clean_code}"))[..32]; + let topic = format!("vbx-p-{code_hash}"); + post_relay_beacon_topic(&endpoint.host, endpoint.port, &topic, &payload).await; +} + +async fn post_relay_beacon_topic( + relay_host: &str, + relay_port: u16, + topic: &str, + payload: &serde_json::Value, +) { let is_domain = relay_host.parse::().is_err() && !relay_host.eq_ignore_ascii_case("localhost"); let (base_url, target_port) = if is_domain && (relay_port == 80 || relay_port == 443) { @@ -623,12 +657,7 @@ async fn publish_domestic_beacon(relay_host: &str, relay_port: u16, host_id: &st if let Ok(client) = builder.build() { let _ = client .post(format!("{base_url}/{topic}")) - .json(&payload) - .send() - .await; - let _ = client - .post(format!("{base_url}/{SHARED_CLOUD_DISCOVERY_TOPIC}")) - .json(&payload) + .json(payload) .send() .await; } @@ -702,17 +731,13 @@ async fn maintain_control( .ok() .flatten() .unwrap_or_else(|| "default".to_string()); - let host_name = utils::net::local_hostname().unwrap_or_else(|| "VibeX Desktop".to_string()); - let lan_origins: Vec = utils::net::advertised_http_origins(local_port, true) - .into_iter() - .filter(|origin| !remote_protocol::is_loopback_origin(origin)) - .collect(); let stream = connect_to_relay_host(host, port).await?; let (reader, mut writer) = stream.into_split(); - let name_b64 = BASE64.encode(host_name.as_bytes()); - let lan_b64 = BASE64.encode(serde_json::to_vec(&lan_origins).unwrap_or_default()); + // Never transmit local hostname or internal LAN IPs to the public relay control plane. + let name_b64 = BASE64.encode(b"VibeX Desktop"); + let lan_b64 = BASE64.encode(b"[]"); writer .write_all(format!("VIBEX-CTRL v2 {host_id} {token} {name_b64} {lan_b64}\n").as_bytes()) .await diff --git a/src-tauri/src/commands/web_service.rs b/src-tauri/src/commands/web_service.rs index 9d1c8f2b9..f8d29804c 100644 --- a/src-tauri/src/commands/web_service.rs +++ b/src-tauri/src/commands/web_service.rs @@ -620,9 +620,17 @@ pub async fn create_host_device_pairing( &challenge, reachability, ); - Ok(remote_protocol::IssuedPairingInvitation::from_payload( - challenge, payload, - )) + let issued = remote_protocol::IssuedPairingInvitation::from_payload(challenge, payload); + let code_for_beacon = issued.connection_code.clone(); + let host_id_for_beacon = issued.host_id.clone(); + tokio::spawn(async move { + crate::commands::host_tunnel::publish_pairing_code_beacon( + &code_for_beacon, + &host_id_for_beacon, + ) + .await; + }); + Ok(issued) } #[tauri::command] From cd1f01b37e8dcbc234d7412213939d3b59f06f14 Mon Sep 17 00:00:00 2001 From: DorJay Date: Wed, 11 Nov 2026 21:45:46 +0800 Subject: [PATCH 02/12] fix(ci): satisfy arch-check ratchet in server/host/conversation and clippy in relay-server --- crates/conversations/src/turn/binding.rs | 30 ++++++++++++++++++++---- crates/relay-server/src/lib.rs | 12 +++++----- crates/server/src/host/conversation.rs | 10 -------- 3 files changed, 32 insertions(+), 20 deletions(-) diff --git a/crates/conversations/src/turn/binding.rs b/crates/conversations/src/turn/binding.rs index fa7291172..a98369a87 100644 --- a/crates/conversations/src/turn/binding.rs +++ b/crates/conversations/src/turn/binding.rs @@ -242,11 +242,21 @@ impl ConversationSessionService { &self, conversation_id: Uuid, ) -> Result<(), ConversationServiceError> { - self.ctx + let res = self + .ctx .agent_runtime .touch_session(AgentSessionId(conversation_id)) .await - .map_err(Into::into) + .map_err(Into::into); + let _ = sqlx::query( + r#"UPDATE sessions + SET updated_at = datetime('now', 'subsec') + WHERE id = ? AND deleted_at IS NULL"#, + ) + .bind(conversation_id) + .execute(&self.ctx.deployment.db().pool) + .await; + res } /// `watch` registers the on-screen surface. The runtime repeats the bump. @@ -256,11 +266,23 @@ impl ConversationSessionService { conversation_id: Uuid, watch: bool, ) -> Result<(), ConversationServiceError> { - self.ctx + let res = self + .ctx .agent_runtime .set_session_keepalive(AgentSessionId(conversation_id), watch) .await - .map_err(Into::into) + .map_err(Into::into); + if watch { + let _ = sqlx::query( + r#"UPDATE sessions + SET updated_at = datetime('now', 'subsec') + WHERE id = ? AND deleted_at IS NULL"#, + ) + .bind(conversation_id) + .execute(&self.ctx.deployment.db().pool) + .await; + } + res } pub(super) async fn ensure_session_controls_locked( diff --git a/crates/relay-server/src/lib.rs b/crates/relay-server/src/lib.rs index e98fe9301..33caee81f 100644 --- a/crates/relay-server/src/lib.rs +++ b/crates/relay-server/src/lib.rs @@ -428,7 +428,7 @@ async fn handle_control_connection( return; }; - let parts: Vec<&str> = first_line.trim().split_whitespace().collect(); + let parts: Vec<&str> = first_line.split_whitespace().collect(); // Format: VIBEX-CTRL v2 [name_b64] [lan_origins_b64] let (host_id, token, host_name, lan_origins) = if parts.len() >= 4 && parts[1] == "v2" { let host_id = parts[2].trim().to_string(); @@ -504,10 +504,10 @@ async fn handle_control_connection( _ = ping_interval.tick() => { if let Ok(frame) = serde_json::to_string(&ControlServerFrame::Ping { ts: chrono::Utc::now().timestamp_millis(), - }) { - if ctrl_tx.send(format!("{frame}\n")).is_err() { - break; - } + }) + && ctrl_tx.send(format!("{frame}\n")).is_err() + { + break; } // Evict stale pre-warmed streams and ask Host to replenish if needed let needed = { @@ -594,7 +594,7 @@ async fn handle_data_connection(stream: TcpStream, state: Arc) if n == 0 { return; } - let parts: Vec<&str> = first_line.trim().split_whitespace().collect(); + let parts: Vec<&str> = first_line.split_whitespace().collect(); // Format: VIBEX-DATA v2 let (host_id, token, conn_id) = if parts.len() >= 5 && parts[1] == "v2" { (parts[2].trim(), parts[3].trim(), parts[4].trim()) diff --git a/crates/server/src/host/conversation.rs b/crates/server/src/host/conversation.rs index 76b84578e..c7ca73360 100644 --- a/crates/server/src/host/conversation.rs +++ b/crates/server/src/host/conversation.rs @@ -252,16 +252,6 @@ impl ServerApplicationDomains { .await .map_err(|error| ApplicationError::bad_request(error.to_string()))?, } - if args.watch != Some(false) { - let _ = sqlx::query( - r#"UPDATE sessions - SET updated_at = datetime('now', 'subsec') - WHERE id = ? AND deleted_at IS NULL"#, - ) - .bind(id) - .execute(&self.pool) - .await; - } let idle_timeout_secs = agents::idle_timeout_from_env() .map(|timeout| timeout.as_secs()) .unwrap_or(0); From 85879f866a03946f0fcf6ebde2c9bb141d691b8c Mon Sep 17 00:00:00 2001 From: DorJay Date: Thu, 12 Nov 2026 16:55:55 +0800 Subject: [PATCH 03/12] feat(conversation): surface native relay models and prefer populated agent bindings in catalog Co-Authored-By: BaoCode --- crates/application/src/conversation.rs | 166 ++++++++++++++++++++++- crates/db/src/conversation_repository.rs | 7 +- 2 files changed, 167 insertions(+), 6 deletions(-) diff --git a/crates/application/src/conversation.rs b/crates/application/src/conversation.rs index 7365e4a99..24a248b1b 100644 --- a/crates/application/src/conversation.rs +++ b/crates/application/src/conversation.rs @@ -205,6 +205,147 @@ fn parse_json_value(raw: Option<&str>) -> Option { serde_json::from_str(text).ok() } +fn enrich_catalog_agent_with_native_relay_models(agent: &mut ConversationCatalogAgent) { + let home = std::env::var_os("HOME") + .or_else(|| std::env::var_os("USERPROFILE")) + .map(std::path::PathBuf::from); + let Some(home) = home else { + return; + }; + + let mut extra_models: Vec<(String, String)> = Vec::new(); + let mut preferred_default: Option = None; + + match agent.id.as_str() { + "claude_code" => { + if let Ok(raw) = std::fs::read_to_string(home.join(".claude").join("settings.json")) + && let Ok(val) = serde_json::from_str::(&raw) + { + if let Some(model) = val + .get("model") + .and_then(serde_json::Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + { + preferred_default = Some(model.to_string()); + } + if let Some(env) = val.get("env").and_then(serde_json::Value::as_object) { + for (env_key, tag) in [ + ("ANTHROPIC_MODEL", "主模型"), + ("ANTHROPIC_DEFAULT_OPUS_MODEL", "Opus"), + ("ANTHROPIC_DEFAULT_SONNET_MODEL", "Sonnet"), + ("ANTHROPIC_DEFAULT_HAIKU_MODEL", "Haiku"), + ("ANTHROPIC_CUSTOM_MODEL_OPTION", "自定义"), + ] { + if let Some(m) = env + .get(env_key) + .and_then(serde_json::Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + { + if preferred_default.is_none() && env_key == "ANTHROPIC_MODEL" { + preferred_default = Some(m.to_string()); + } + if !extra_models.iter().any(|(v, _)| v == m) { + extra_models.push((m.to_string(), format!("{m} ({tag})"))); + } + } + } + } + } + } + "codex" => { + if let Ok(raw) = + std::fs::read_to_string(home.join(".codex").join("vibex-model-catalog.json")) + && let Ok(val) = serde_json::from_str::(&raw) + && let Some(models) = val.get("models").and_then(serde_json::Value::as_array) + { + for item in models { + if let Some(slug) = item + .get("slug") + .and_then(serde_json::Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + { + let label = item + .get("display_name") + .and_then(serde_json::Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or(slug); + if !extra_models.iter().any(|(v, _)| v == slug) { + extra_models.push((slug.to_string(), label.to_string())); + } + } + } + } + } + _ => {} + } + + if extra_models.is_empty() { + return; + } + + let mut options = agent + .session_config + .as_ref() + .and_then(serde_json::Value::as_array) + .cloned() + .unwrap_or_default(); + + let model_opt_idx = options.iter().position(|opt| { + opt.get("category").and_then(serde_json::Value::as_str) == Some("model") + || opt.get("key").and_then(serde_json::Value::as_str) == Some("model") + }); + + if let Some(idx) = model_opt_idx { + if let Some(obj) = options[idx].as_object_mut() { + let mut choices = obj + .get("choices") + .and_then(serde_json::Value::as_array) + .cloned() + .unwrap_or_default(); + for (val, label) in extra_models { + let exists = choices.iter().any(|c| { + c.get("value") + .and_then(serde_json::Value::as_str) + .is_some_and(|v| v.eq_ignore_ascii_case(&val)) + }); + if !exists { + choices.push(serde_json::json!({ + "value": val, + "label": label, + })); + } + } + obj.insert("choices".to_string(), serde_json::Value::Array(choices)); + } + } else { + let default_val = preferred_default + .or_else(|| extra_models.first().map(|(v, _)| v.clone())) + .unwrap_or_default(); + let choices: Vec = extra_models + .into_iter() + .map(|(val, label)| serde_json::json!({ "value": val, "label": label })) + .collect(); + options.insert( + 0, + serde_json::json!({ + "key": "model", + "label": "Model", + "category": "model", + "value": default_val, + "choices": choices, + }), + ); + } + + let updated = serde_json::Value::Array(options); + agent.session_config_json = serde_json::to_string(&updated).ok(); + agent.session_config = Some(updated); +} + fn builtin_catalog_tags() -> Vec { vec![ ConversationCatalogTag { @@ -1033,8 +1174,7 @@ impl ConversationRepository for SqliteConversationRepository { .modes_json .filter(|value| !value.is_empty() && value != "[]"); } - if agent.session_config.is_none() - && let Ok(Some(controls)) = self.catalog_agent_capability(&agent.id).await + if let Ok(Some(controls)) = self.catalog_agent_capability(&agent.id).await && let Ok(value) = serde_json::from_str::(&controls) { let modes = value @@ -1043,13 +1183,29 @@ impl ConversationRepository for SqliteConversationRepository { .filter(|item| item != &serde_json::json!([])); let options = value .get("config_options") + .or_else(|| value.get("configOptions")) .cloned() .filter(|item| item != &serde_json::json!([])); - if agent.session_modes.is_none() { - agent.session_modes = modes; + let current_mode = value + .get("current_mode") + .or_else(|| value.get("currentMode")) + .and_then(serde_json::Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(ToOwned::to_owned); + if agent.current_mode.is_none() { + agent.current_mode = current_mode; + } + if agent.session_modes.is_none() && let Some(modes_val) = modes { + agent.session_modes_json = serde_json::to_string(&modes_val).ok(); + agent.session_modes = Some(modes_val); + } + if agent.session_config.is_none() && let Some(options_val) = options { + agent.session_config_json = serde_json::to_string(&options_val).ok(); + agent.session_config = Some(options_val); } - agent.session_config = options; } + enrich_catalog_agent_with_native_relay_models(agent); } let mut tags = builtin_catalog_tags(); if let Ok(rows) = db::models::tag::Tag::find_all(self.pool()).await { diff --git a/crates/db/src/conversation_repository.rs b/crates/db/src/conversation_repository.rs index 565d9cda3..a7c82ca39 100644 --- a/crates/db/src/conversation_repository.rs +++ b/crates/db/src/conversation_repository.rs @@ -182,7 +182,12 @@ impl SqliteConversationRepository { r#"SELECT config_options_json, modes_json, current_mode FROM conversation_agent_bindings WHERE agent_id = ? - ORDER BY updated_at DESC + ORDER BY ( + config_options_json IS NOT NULL + AND TRIM(config_options_json) != '' + AND TRIM(config_options_json) != '[]' + ) DESC, + updated_at DESC LIMIT 1"#, ) .bind(agent_id) From e20afde9e800b1cb33dee0b63289234f02cf32a5 Mon Sep 17 00:00:00 2001 From: DorJay Date: Thu, 12 Nov 2026 18:28:00 +0800 Subject: [PATCH 04/12] feat(server,remote): authorize same-account phones through host connect requests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Connect requests may carry the phone's VibeX account token. The host resolves both the phone's token and its own signed-in owner through the VibeX site and only queues the request when they are the same account; the desktop banner tags verified requests 同账号 for one-time approval. Co-Authored-By: BaoCode --- ...20261112010000_connect_request_account.sql | 1 + crates/remote-protocol/src/device_auth.rs | 26 +- crates/server/src/account_link.rs | 276 ++++++++++++++++++ crates/server/src/auth.rs | 46 ++- crates/server/src/lib.rs | 1 + crates/server/src/runtime.rs | 46 ++- .../tests/webrtc_security_and_session.rs | 1 + .../layout/MobileDeviceConnectBanner.test.tsx | 19 ++ .../layout/MobileDeviceConnectBanner.tsx | 5 + frontend/src/lib/api/config.ts | 2 + 10 files changed, 415 insertions(+), 8 deletions(-) create mode 100644 crates/db/migrations/20261112010000_connect_request_account.sql create mode 100644 crates/server/src/account_link.rs diff --git a/crates/db/migrations/20261112010000_connect_request_account.sql b/crates/db/migrations/20261112010000_connect_request_account.sql new file mode 100644 index 000000000..57964aab7 --- /dev/null +++ b/crates/db/migrations/20261112010000_connect_request_account.sql @@ -0,0 +1 @@ +ALTER TABLE server_device_connect_requests ADD COLUMN account_display_name TEXT; diff --git a/crates/remote-protocol/src/device_auth.rs b/crates/remote-protocol/src/device_auth.rs index feb6e99a6..4e1d30c3a 100644 --- a/crates/remote-protocol/src/device_auth.rs +++ b/crates/remote-protocol/src/device_auth.rs @@ -189,7 +189,7 @@ pub struct RevokeDeviceResponse { pub revoked: bool, } -#[derive(Clone, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize, TS)] +#[derive(Clone, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize, TS)] pub struct CreateDeviceConnectRequest { pub device_name: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -200,6 +200,26 @@ pub struct CreateDeviceConnectRequest { pub session_nonce: Option, #[serde(default)] pub replace_existing_mobile: bool, + /// VibeX account token of the requesting device. When present, the host only + /// accepts the request if the token belongs to the account signed in on the host. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub account_token: Option, +} + +impl std::fmt::Debug for CreateDeviceConnectRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CreateDeviceConnectRequest") + .field("device_name", &self.device_name) + .field("client_kind", &self.client_kind) + .field("public_key_ed25519", &self.public_key_ed25519) + .field("session_nonce", &self.session_nonce) + .field("replace_existing_mobile", &self.replace_existing_mobile) + .field( + "account_token", + &self.account_token.as_ref().map(|_| ""), + ) + .finish() + } } #[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize, TS)] @@ -221,6 +241,10 @@ pub struct PendingDeviceConnectRequest { pub sas_code: String, pub created_at: String, pub expires_at: String, + /// Display name of the VibeX account the host verified for this request; absent for + /// requests made without an account token. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub account_display_name: Option, } #[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize, TS)] diff --git a/crates/server/src/account_link.rs b/crates/server/src/account_link.rs new file mode 100644 index 000000000..db4b64663 --- /dev/null +++ b/crates/server/src/account_link.rs @@ -0,0 +1,276 @@ +//! Same-account device authorization. +//! +//! A device that presents a VibeX account token may ask this host for a connection when +//! the token belongs to the account signed in on the host. The host never trusts the +//! identity a device claims: both sides are resolved through the VibeX site. The request +//! still waits for one-time approval on the desktop like any other connect request. + +use std::{path::Path, sync::OnceLock, time::Duration}; + +use async_trait::async_trait; +use serde_json::{Map, Value}; + +/// Keys the desktop frontend writes into the host's `frontend` settings section. +const HOST_ACCOUNT_TOKEN_KEY: &str = "__account_token_v1"; +const HOST_ACCOUNT_OWNER_KEY: &str = "__account_owner_v1"; + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub(crate) enum AccountLinkError { + #[error("this computer is not signed in to a VibeX account")] + HostSignedOut, + #[error("the VibeX account token is not valid")] + InvalidToken, + #[error("the VibeX account does not match the account signed in on this computer")] + Mismatch, + #[error("VibeX account verification is unavailable")] + Unavailable, +} + +impl AccountLinkError { + pub(crate) fn reason(&self) -> &'static str { + match self { + Self::HostSignedOut => "host_account_signed_out", + Self::InvalidToken => "account_token_invalid", + Self::Mismatch => "account_mismatch", + Self::Unavailable => "account_verification_unavailable", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct AccountIdentity { + pub username: String, + pub display_name: String, +} + +#[async_trait] +pub(crate) trait AccountResolver: Send + Sync { + async fn resolve(&self, token: &str) -> Result; +} + +/// Resolves account tokens through the VibeX site account API. +pub(crate) struct SiteAccountResolver { + client: reqwest::Client, + origin: String, +} + +pub(crate) fn site_resolver() -> &'static SiteAccountResolver { + static RESOLVER: OnceLock = OnceLock::new(); + RESOLVER.get_or_init(|| SiteAccountResolver { + client: reqwest::Client::builder() + .timeout(Duration::from_secs(10)) + .build() + .unwrap_or_default(), + origin: utils::site_origin(), + }) +} + +#[async_trait] +impl AccountResolver for SiteAccountResolver { + async fn resolve(&self, token: &str) -> Result { + let response = self + .client + .get(format!("{}/api/modelrouter/desktop", self.origin)) + .bearer_auth(token) + .header("user-agent", "VibeX") + .send() + .await + .map_err(|_| AccountLinkError::Unavailable)?; + if response.status() == reqwest::StatusCode::UNAUTHORIZED { + return Err(AccountLinkError::InvalidToken); + } + if !response.status().is_success() { + return Err(AccountLinkError::Unavailable); + } + let body: Value = response + .json() + .await + .map_err(|_| AccountLinkError::Unavailable)?; + identity_from_user(body.get("user")).ok_or(AccountLinkError::InvalidToken) + } +} + +fn non_empty_str<'a>(value: Option<&'a Value>, key: &str) -> Option<&'a str> { + value? + .get(key)? + .as_str() + .map(str::trim) + .filter(|s| !s.is_empty()) +} + +fn identity_from_user(user: Option<&Value>) -> Option { + let username = non_empty_str(user, "username")?.to_owned(); + let display_name = non_empty_str(user, "displayName") + .map(ToOwned::to_owned) + .unwrap_or_else(|| username.clone()); + Some(AccountIdentity { + username, + display_name, + }) +} + +struct HostAccount { + owner_username: Option, + token: Option, +} + +async fn read_host_account(settings_path: &Path) -> HostAccount { + let frontend: Map = + services::services::settings_store::read_section(settings_path, "frontend") + .await + .ok() + .flatten() + .unwrap_or_default(); + let owner_username = + non_empty_str(frontend.get(HOST_ACCOUNT_OWNER_KEY), "username").map(ToOwned::to_owned); + let token = match frontend.get(HOST_ACCOUNT_TOKEN_KEY) { + Some(Value::String(raw)) => Some(raw.trim()), + Some(object @ Value::Object(_)) => non_empty_str(Some(object), "token"), + _ => None, + } + .filter(|token| !token.is_empty()) + .map(ToOwned::to_owned); + HostAccount { + owner_username, + token, + } +} + +/// Verifies that `device_token` belongs to the account signed in on this host and returns +/// that account's identity. +pub(crate) async fn verify_same_account( + settings_path: &Path, + resolver: &dyn AccountResolver, + device_token: &str, +) -> Result { + let host = read_host_account(settings_path).await; + if host.owner_username.is_none() && host.token.is_none() { + return Err(AccountLinkError::HostSignedOut); + } + let device = resolver.resolve(device_token).await?; + let owner_username = match host.owner_username { + Some(username) => username, + None => match host.token { + Some(token) => match resolver.resolve(&token).await { + Ok(owner) => owner.username, + Err(AccountLinkError::InvalidToken) => { + return Err(AccountLinkError::HostSignedOut); + } + Err(error) => return Err(error), + }, + None => return Err(AccountLinkError::HostSignedOut), + }, + }; + if device.username.eq_ignore_ascii_case(&owner_username) { + Ok(device) + } else { + Err(AccountLinkError::Mismatch) + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use serde_json::json; + + use super::*; + + struct FakeResolver(HashMap<&'static str, &'static str>); + + #[async_trait] + impl AccountResolver for FakeResolver { + async fn resolve(&self, token: &str) -> Result { + match self.0.get(token) { + Some(username) => Ok(AccountIdentity { + username: (*username).to_owned(), + display_name: format!("{username} display"), + }), + None => Err(AccountLinkError::InvalidToken), + } + } + } + + fn resolver() -> FakeResolver { + FakeResolver(HashMap::from([ + ("tok-alice", "alice"), + ("tok-alice-2", "Alice"), + ("tok-bob", "bob"), + ])) + } + + async fn settings_with(frontend: Value) -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + tokio::fs::write( + dir.path().join("settings.json"), + serde_json::to_vec(&json!({ "frontend": frontend })).unwrap(), + ) + .await + .unwrap(); + dir + } + + #[tokio::test] + async fn accepts_device_of_the_host_owner() { + let dir = settings_with(json!({ + HOST_ACCOUNT_OWNER_KEY: { "username": "alice", "displayName": "Alice" }, + })) + .await; + let identity = verify_same_account( + &dir.path().join("settings.json"), + &resolver(), + "tok-alice-2", + ) + .await + .unwrap(); + assert_eq!(identity.username, "Alice"); + } + + #[tokio::test] + async fn resolves_owner_from_host_token_when_owner_record_is_missing() { + let dir = settings_with(json!({ HOST_ACCOUNT_TOKEN_KEY: "tok-alice" })).await; + let path = dir.path().join("settings.json"); + assert!( + verify_same_account(&path, &resolver(), "tok-alice") + .await + .is_ok() + ); + assert_eq!( + verify_same_account(&path, &resolver(), "tok-bob").await, + Err(AccountLinkError::Mismatch) + ); + } + + #[tokio::test] + async fn rejects_other_accounts_and_invalid_tokens() { + let dir = settings_with(json!({ + HOST_ACCOUNT_OWNER_KEY: { "username": "alice" }, + HOST_ACCOUNT_TOKEN_KEY: "tok-alice", + })) + .await; + let path = dir.path().join("settings.json"); + assert_eq!( + verify_same_account(&path, &resolver(), "tok-bob").await, + Err(AccountLinkError::Mismatch) + ); + assert_eq!( + verify_same_account(&path, &resolver(), "forged").await, + Err(AccountLinkError::InvalidToken) + ); + } + + #[tokio::test] + async fn rejects_when_host_is_signed_out() { + let dir = settings_with(json!({})).await; + let path = dir.path().join("settings.json"); + assert_eq!( + verify_same_account(&path, &resolver(), "tok-alice").await, + Err(AccountLinkError::HostSignedOut) + ); + let missing = dir.path().join("missing.json"); + assert_eq!( + verify_same_account(&missing, &resolver(), "tok-alice").await, + Err(AccountLinkError::HostSignedOut) + ); + } +} diff --git a/crates/server/src/auth.rs b/crates/server/src/auth.rs index 2f976284e..f1a36af75 100644 --- a/crates/server/src/auth.rs +++ b/crates/server/src/auth.rs @@ -386,6 +386,7 @@ pub trait ServerAuth: Send + Sync { _host_id: &str, _request: CreateDeviceConnectRequest, _ip_address: Option<&str>, + _account_display_name: Option<&str>, ) -> Result { Err(AuthStoreError::PairingUnavailable) } @@ -950,6 +951,7 @@ impl ServerAuth for SqliteServerAuth { host_id: &str, request: CreateDeviceConnectRequest, ip_address: Option<&str>, + account_display_name: Option<&str>, ) -> Result { let device_name = request.device_name.trim(); if device_name.is_empty() || device_name.len() > 128 { @@ -1029,12 +1031,14 @@ impl ServerAuth for SqliteServerAuth { if let Ok(request_id) = id_str.parse::() { sqlx::query( "UPDATE server_device_connect_requests - SET device_name = ?, ip_address = COALESCE(?, ip_address), expires_at_unix = ? - WHERE id = ?", + SET device_name = ?, ip_address = COALESCE(?, ip_address), expires_at_unix = ?, + account_display_name = ? + WHERE id = ?", ) .bind(device_name) .bind(ip_address) .bind(expires_at) + .bind(account_display_name) .bind(&id_str) .execute(&self.pool) .await?; @@ -1069,8 +1073,8 @@ impl ServerAuth for SqliteServerAuth { sqlx::query( "INSERT INTO server_device_connect_requests (id, device_name, client_kind, ip_address, public_key_ed25519, sas_code, - status, created_at_unix, expires_at_unix) - VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)", + status, created_at_unix, expires_at_unix, account_display_name) + VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?)", ) .bind(&request_id_str) .bind(device_name) @@ -1080,6 +1084,7 @@ impl ServerAuth for SqliteServerAuth { .bind(&sas_code) .bind(now) .bind(expires_at) + .bind(account_display_name) .execute(&self.pool) .await?; @@ -1167,8 +1172,9 @@ impl ServerAuth for SqliteServerAuth { } let now = self.now(); let rows = sqlx::query( - "SELECT id, device_name, client_kind, ip_address, sas_code, created_at_unix, expires_at_unix - FROM server_device_connect_requests + "SELECT id, device_name, client_kind, ip_address, sas_code, created_at_unix, expires_at_unix, + account_display_name + FROM server_device_connect_requests WHERE status = 'pending' AND expires_at_unix > ? ORDER BY created_at_unix DESC", ) @@ -1196,6 +1202,7 @@ impl ServerAuth for SqliteServerAuth { sas_code: row.try_get("sas_code")?, created_at: unix_timestamp(created_at_unix), expires_at: unix_timestamp(expires_at_unix), + account_display_name: row.try_get("account_display_name")?, }); } Ok(items) @@ -2013,4 +2020,31 @@ mod host_console_pairing_tests { "expected ~7d ttl, got {long_elapsed}" ); } + + #[tokio::test] + async fn connect_requests_carry_the_verified_account_to_the_host_console() { + let auth = auth().await; + let owner = AuthenticatedCredential::host_console_owner(); + let request = |name: &str| remote_protocol::CreateDeviceConnectRequest { + device_name: name.to_owned(), + client_kind: Some("mobile".to_owned()), + ..Default::default() + }; + auth.create_connect_request("host-1", request("Alice iPhone"), None, Some("Alice")) + .await + .expect("account request"); + auth.create_connect_request("host-1", request("Bob iPhone"), None, None) + .await + .expect("plain request"); + + let pending = auth.list_connect_requests(&owner).await.expect("list"); + let account_of = |name: &str| { + pending + .iter() + .find(|item| item.device_name == name) + .map(|item| item.account_display_name.clone()) + }; + assert_eq!(account_of("Alice iPhone"), Some(Some("Alice".to_owned()))); + assert_eq!(account_of("Bob iPhone"), Some(None)); + } } diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index 3b4256c46..099563a36 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -1,5 +1,6 @@ //! Headless VibeX server composition and transport adapters. +mod account_link; mod agent_install; mod artifact_sink; mod auth; diff --git a/crates/server/src/runtime.rs b/crates/server/src/runtime.rs index 1d252cbb2..a0e42ba7e 100644 --- a/crates/server/src/runtime.rs +++ b/crates/server/src/runtime.rs @@ -942,9 +942,32 @@ async fn create_connect_request( Json(request): Json, ) -> Response { let ip_address = extract_client_ip(&headers, state.config.listen_addr); + let account_display_name = match request + .account_token + .as_deref() + .map(str::trim) + .filter(|token| !token.is_empty()) + { + Some(token) => match crate::account_link::verify_same_account( + &utils::assets::settings_path(), + crate::account_link::site_resolver(), + token, + ) + .await + { + Ok(identity) => Some(identity.display_name), + Err(error) => return account_link_error_response(&error), + }, + None => None, + }; match state .auth - .create_connect_request(&state.config.host_id, request, ip_address.as_deref()) + .create_connect_request( + &state.config.host_id, + request, + ip_address.as_deref(), + account_display_name.as_deref(), + ) .await { Ok(response) => (StatusCode::CREATED, Json(response)).into_response(), @@ -1158,6 +1181,27 @@ fn status_for_error_code(code: ErrorCode) -> StatusCode { } } +fn account_link_error_response(error: &crate::account_link::AccountLinkError) -> Response { + use crate::account_link::AccountLinkError; + let (status, code) = match error { + AccountLinkError::Mismatch => (StatusCode::FORBIDDEN, ErrorCode::Forbidden), + AccountLinkError::InvalidToken => (StatusCode::UNAUTHORIZED, ErrorCode::Unauthorized), + AccountLinkError::HostSignedOut => (StatusCode::CONFLICT, ErrorCode::Conflict), + AccountLinkError::Unavailable => ( + StatusCode::SERVICE_UNAVAILABLE, + ErrorCode::CapabilityUnavailable, + ), + }; + let envelope = ErrorEnvelope::new( + code, + error.to_string(), + matches!(error, AccountLinkError::Unavailable), + OperationId::new(), + ) + .with_details(json!({ "reason": error.reason() })); + (status, Json(envelope)).into_response() +} + fn auth_error_response(error: AuthStoreError) -> Response { let mut existing_mobile_device: Option<(String, String)> = None; let reason = match &error { diff --git a/crates/server/tests/webrtc_security_and_session.rs b/crates/server/tests/webrtc_security_and_session.rs index 8f54d65ec..462f74ea4 100644 --- a/crates/server/tests/webrtc_security_and_session.rs +++ b/crates/server/tests/webrtc_security_and_session.rs @@ -566,6 +566,7 @@ async fn mobile_zero_config_connect_request_triggers_host_prompt_and_approves_wi public_key_ed25519: Some(pubkey_b64.clone()), session_nonce: Some("first-connect-nonce".to_owned()), replace_existing_mobile: false, + account_token: None, }) .expect("serialize"), )) diff --git a/frontend/src/components/layout/MobileDeviceConnectBanner.test.tsx b/frontend/src/components/layout/MobileDeviceConnectBanner.test.tsx index 1b09b1892..d79cc5776 100644 --- a/frontend/src/components/layout/MobileDeviceConnectBanner.test.tsx +++ b/frontend/src/components/layout/MobileDeviceConnectBanner.test.tsx @@ -70,4 +70,23 @@ describe('MobileDeviceConnectBanner', () => { await screen.findByText(/已连接移动设备「Pixel 9 Pro」/) ).toBeInTheDocument(); }); + + it('marks requests the host verified as coming from its own account', async () => { + listConnectRequestsMock.mockResolvedValue([ + { + request_id: 'req-acct', + device_name: 'iPhone 16 Pro', + client_kind: 'mobile', + sas_code: '1204', + created_at: '2026-11-12T05:00:00Z', + expires_at: '2026-11-12T05:03:00Z', + account_display_name: 'Alice', + }, + ]); + + render(); + + expect(await screen.findByText('同账号 · Alice')).toBeInTheDocument(); + expect(screen.getByText('核对码 1204')).toBeInTheDocument(); + }); }); diff --git a/frontend/src/components/layout/MobileDeviceConnectBanner.tsx b/frontend/src/components/layout/MobileDeviceConnectBanner.tsx index d3fedf5ca..bbc168a10 100644 --- a/frontend/src/components/layout/MobileDeviceConnectBanner.tsx +++ b/frontend/src/components/layout/MobileDeviceConnectBanner.tsx @@ -232,6 +232,11 @@ export function MobileDeviceConnectBanner() { 发现可用移动设备「{active.device_name}」 + {active.account_display_name ? ( + + 同账号 · {active.account_display_name} + + ) : null} Date: Thu, 12 Nov 2026 19:10:59 +0800 Subject: [PATCH 05/12] chore(mobile): bump ios/android to account-first onboarding and same-account connect Co-Authored-By: BaoCode --- mobile/android | 2 +- mobile/ios | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/mobile/android b/mobile/android index c40b5fa1b..e012cff74 160000 --- a/mobile/android +++ b/mobile/android @@ -1 +1 @@ -Subproject commit c40b5fa1bdae1f8b09e4554e9652027eb09ceb7a +Subproject commit e012cff7480f4bd5273aca2d421187a34207f2eb diff --git a/mobile/ios b/mobile/ios index ea86542df..d5dcc6f0c 160000 --- a/mobile/ios +++ b/mobile/ios @@ -1 +1 @@ -Subproject commit ea86542df60933975a9c3eb07aa5427b0aef9173 +Subproject commit d5dcc6f0cdfb2b4089c271ad1e1b15226fd55194 From 6a5a1d9aba17c0974c90f670f7e3b5c61e34380c Mon Sep 17 00:00:00 2001 From: DorJay Date: Thu, 12 Nov 2026 22:35:35 +0800 Subject: [PATCH 06/12] chore(mobile): bump ios/android for offline desktop error message Co-Authored-By: BaoCode --- mobile/android | 2 +- mobile/ios | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/mobile/android b/mobile/android index e012cff74..4aca29ce8 160000 --- a/mobile/android +++ b/mobile/android @@ -1 +1 @@ -Subproject commit e012cff7480f4bd5273aca2d421187a34207f2eb +Subproject commit 4aca29ce896797603f075fc32a249b59f72324ed diff --git a/mobile/ios b/mobile/ios index d5dcc6f0c..b75739e34 160000 --- a/mobile/ios +++ b/mobile/ios @@ -1 +1 @@ -Subproject commit d5dcc6f0cdfb2b4089c271ad1e1b15226fd55194 +Subproject commit b75739e34880ce9a78852d898242adf1ee4c1cce From 95c470507be22b7e37589a174f519bb69e7eef7a Mon Sep 17 00:00:00 2001 From: DorJay Date: Thu, 12 Nov 2026 23:03:34 +0800 Subject: [PATCH 07/12] chore(mobile): bump ios/android for in-app account login Co-Authored-By: BaoCode --- mobile/android | 2 +- mobile/ios | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/mobile/android b/mobile/android index 4aca29ce8..ee4eff2f1 160000 --- a/mobile/android +++ b/mobile/android @@ -1 +1 @@ -Subproject commit 4aca29ce896797603f075fc32a249b59f72324ed +Subproject commit ee4eff2f107a72483767004006bc4105f621bfb4 diff --git a/mobile/ios b/mobile/ios index b75739e34..898be1a04 160000 --- a/mobile/ios +++ b/mobile/ios @@ -1 +1 @@ -Subproject commit b75739e34880ce9a78852d898242adf1ee4c1cce +Subproject commit 898be1a0494bc2c4d90a934a10ee98a16dd81af0 From f11e09e716b93df15ab9e3bc6e57800fce968371 Mon Sep 17 00:00:00 2001 From: DorJay Date: Thu, 12 Nov 2026 23:43:36 +0800 Subject: [PATCH 08/12] chore(mobile): bump ios/android to skip device-login placeholders Co-Authored-By: BaoCode --- mobile/android | 2 +- mobile/ios | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/mobile/android b/mobile/android index ee4eff2f1..686387155 160000 --- a/mobile/android +++ b/mobile/android @@ -1 +1 @@ -Subproject commit ee4eff2f107a72483767004006bc4105f621bfb4 +Subproject commit 686387155dde400fbdba7671d6e2929f16fb2162 diff --git a/mobile/ios b/mobile/ios index 898be1a04..b18554001 160000 --- a/mobile/ios +++ b/mobile/ios @@ -1 +1 @@ -Subproject commit 898be1a0494bc2c4d90a934a10ee98a16dd81af0 +Subproject commit b18554001afe187fd4d6cfa439de9ce487087299 From becb166dbae59c6ce4c869715fc074ccf8cd4a33 Mon Sep 17 00:00:00 2001 From: DorJay Date: Fri, 13 Nov 2026 02:17:15 +0800 Subject: [PATCH 09/12] chore(mobile): bump ios/android for sidebar navigation Co-Authored-By: BaoCode --- mobile/android | 2 +- mobile/ios | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/mobile/android b/mobile/android index 686387155..930bee205 160000 --- a/mobile/android +++ b/mobile/android @@ -1 +1 @@ -Subproject commit 686387155dde400fbdba7671d6e2929f16fb2162 +Subproject commit 930bee2050b1a6c22f9e830caca3bbe63e69cc7a diff --git a/mobile/ios b/mobile/ios index b18554001..a51c9a0aa 160000 --- a/mobile/ios +++ b/mobile/ios @@ -1 +1 @@ -Subproject commit b18554001afe187fd4d6cfa439de9ce487087299 +Subproject commit a51c9a0aa425a58b53f40ad61ac4520f26c34d2e From 6a6921b3c8292fed238593ba2fca0fc713ac2f31 Mon Sep 17 00:00:00 2001 From: DorJay Date: Sat, 14 Nov 2026 23:37:44 +0800 Subject: [PATCH 10/12] feat(server,remote): zero-click same-account auto-approval with 4-digit SAS notice --- ...15010000_connect_request_auto_approval.sql | 1 + crates/remote-protocol/src/device_auth.rs | 7 + crates/server/src/account_link.rs | 56 +++- crates/server/src/auth.rs | 276 +++++++++++++++++- crates/server/src/runtime.rs | 7 +- .../layout/MobileDeviceConnectBanner.test.tsx | 28 +- .../layout/MobileDeviceConnectBanner.tsx | 151 ++++++++-- frontend/src/lib/api/config.ts | 2 + .../src/pages/settings/DevicePairingPanel.tsx | 8 +- .../src/pages/settings/WebServiceSettings.tsx | 5 +- mobile/ios | 2 +- src-tauri/src/bin/generate_types.rs | 1 + 12 files changed, 481 insertions(+), 63 deletions(-) create mode 100644 crates/db/migrations/20261115010000_connect_request_auto_approval.sql diff --git a/crates/db/migrations/20261115010000_connect_request_auto_approval.sql b/crates/db/migrations/20261115010000_connect_request_auto_approval.sql new file mode 100644 index 000000000..1d506ba5e --- /dev/null +++ b/crates/db/migrations/20261115010000_connect_request_auto_approval.sql @@ -0,0 +1 @@ +ALTER TABLE server_device_connect_requests ADD COLUMN issued_device_id TEXT; diff --git a/crates/remote-protocol/src/device_auth.rs b/crates/remote-protocol/src/device_auth.rs index 4e1d30c3a..378428288 100644 --- a/crates/remote-protocol/src/device_auth.rs +++ b/crates/remote-protocol/src/device_auth.rs @@ -245,6 +245,13 @@ pub struct PendingDeviceConnectRequest { /// requests made without an account token. #[serde(default, skip_serializing_if = "Option::is_none")] pub account_display_name: Option, + /// `pending` while awaiting desktop confirmation; `approved` for recently auto-approved + /// same-account connections surfaced briefly so the desktop can show the SAS code & revoke action. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub status: Option, + /// Issued device credential ID when `status == Some(Approved)`, allowing instant one-click revocation. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub issued_device_id: Option, } #[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize, TS)] diff --git a/crates/server/src/account_link.rs b/crates/server/src/account_link.rs index db4b64663..fbe26dfdf 100644 --- a/crates/server/src/account_link.rs +++ b/crates/server/src/account_link.rs @@ -1,9 +1,10 @@ //! Same-account device authorization. //! -//! A device that presents a VibeX account token may ask this host for a connection when -//! the token belongs to the account signed in on the host. The host never trusts the -//! identity a device claims: both sides are resolved through the VibeX site. The request -//! still waits for one-time approval on the desktop like any other connect request. +//! A device that presents a VibeX account token may connect directly when the token belongs +//! to the account signed in on the host. The host never trusts the identity a device claims: +//! both sides are resolved through the VibeX site. When same-account auto-connect is enabled +//! (the default), the host issues a Companion credential immediately and surfaces the 4-digit +//! SAS connection code on both screens for non-blocking visual verification. use std::{path::Path, sync::OnceLock, time::Duration}; @@ -13,6 +14,7 @@ use serde_json::{Map, Value}; /// Keys the desktop frontend writes into the host's `frontend` settings section. const HOST_ACCOUNT_TOKEN_KEY: &str = "__account_token_v1"; const HOST_ACCOUNT_OWNER_KEY: &str = "__account_owner_v1"; +const HOST_SAME_ACCOUNT_AUTO_CONNECT_KEY: &str = "__same_account_auto_connect_v1"; #[derive(Debug, thiserror::Error, PartialEq, Eq)] pub(crate) enum AccountLinkError { @@ -43,6 +45,13 @@ pub(crate) struct AccountIdentity { pub display_name: String, } +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct VerifiedSameAccount { + pub identity: AccountIdentity, + /// Defaults to `true` unless the user explicitly turned off same-account auto-connect in Settings. + pub auto_approve: bool, +} + #[async_trait] pub(crate) trait AccountResolver: Send + Sync { async fn resolve(&self, token: &str) -> Result; @@ -112,6 +121,7 @@ fn identity_from_user(user: Option<&Value>) -> Option { struct HostAccount { owner_username: Option, token: Option, + auto_approve: bool, } async fn read_host_account(settings_path: &Path) -> HostAccount { @@ -130,19 +140,25 @@ async fn read_host_account(settings_path: &Path) -> HostAccount { } .filter(|token| !token.is_empty()) .map(ToOwned::to_owned); + let auto_approve = match frontend.get(HOST_SAME_ACCOUNT_AUTO_CONNECT_KEY) { + Some(Value::Bool(flag)) => *flag, + Some(Value::String(raw)) => !raw.trim().eq_ignore_ascii_case("false"), + _ => true, + }; HostAccount { owner_username, token, + auto_approve, } } /// Verifies that `device_token` belongs to the account signed in on this host and returns -/// that account's identity. +/// that account's identity along with the host's auto-approve preference. pub(crate) async fn verify_same_account( settings_path: &Path, resolver: &dyn AccountResolver, device_token: &str, -) -> Result { +) -> Result { let host = read_host_account(settings_path).await; if host.owner_username.is_none() && host.token.is_none() { return Err(AccountLinkError::HostSignedOut); @@ -162,7 +178,10 @@ pub(crate) async fn verify_same_account( }, }; if device.username.eq_ignore_ascii_case(&owner_username) { - Ok(device) + Ok(VerifiedSameAccount { + identity: device, + auto_approve: host.auto_approve, + }) } else { Err(AccountLinkError::Mismatch) } @@ -213,17 +232,32 @@ mod tests { #[tokio::test] async fn accepts_device_of_the_host_owner() { let dir = settings_with(json!({ - HOST_ACCOUNT_OWNER_KEY: { "username": "alice", "displayName": "Alice" }, - })) + HOST_ACCOUNT_OWNER_KEY: { "username": "alice", "displayName": "Alice" }, + })) .await; - let identity = verify_same_account( + let verified = verify_same_account( &dir.path().join("settings.json"), &resolver(), "tok-alice-2", ) .await .unwrap(); - assert_eq!(identity.username, "Alice"); + assert_eq!(verified.identity.username, "Alice"); + assert!(verified.auto_approve); + + let manual_dir = settings_with(json!({ + HOST_ACCOUNT_OWNER_KEY: { "username": "alice", "displayName": "Alice" }, + HOST_SAME_ACCOUNT_AUTO_CONNECT_KEY: false, + })) + .await; + let manual = verify_same_account( + &manual_dir.path().join("settings.json"), + &resolver(), + "tok-alice-2", + ) + .await + .unwrap(); + assert!(!manual.auto_approve); } #[tokio::test] diff --git a/crates/server/src/auth.rs b/crates/server/src/auth.rs index f1a36af75..6d31caffe 100644 --- a/crates/server/src/auth.rs +++ b/crates/server/src/auth.rs @@ -387,6 +387,7 @@ pub trait ServerAuth: Send + Sync { _request: CreateDeviceConnectRequest, _ip_address: Option<&str>, _account_display_name: Option<&str>, + _auto_approve: bool, ) -> Result { Err(AuthStoreError::PairingUnavailable) } @@ -952,6 +953,7 @@ impl ServerAuth for SqliteServerAuth { request: CreateDeviceConnectRequest, ip_address: Option<&str>, account_display_name: Option<&str>, + auto_approve: bool, ) -> Result { let device_name = request.device_name.trim(); if device_name.is_empty() || device_name.len() > 128 { @@ -985,6 +987,145 @@ impl ServerAuth for SqliteServerAuth { let host_name = utils::net::local_hostname(); let incoming_pk = parsed_pubkey.as_ref().map(|(_, pk)| pk.as_str()); + if auto_approve && account_display_name.is_some() { + let request_id = PairingId::new(); + let request_id_str = request_id.to_string(); + let host_bytes: [u8; 32] = Sha256::digest(host_id.as_bytes()).into(); + let device_bytes: [u8; 32] = match parsed_pubkey { + Some((bytes, _)) => bytes, + None => Sha256::digest(device_name.as_bytes()).into(), + }; + let nonce = request + .session_nonce + .as_deref() + .map(str::trim) + .filter(|v| !v.is_empty()) + .unwrap_or(&request_id_str); + let sas_code = compute_sas_code(&host_bytes, &device_bytes, nonce); + let canonical_pubkey = parsed_pubkey.map(|(_, pk)| pk); + + let owner = AuthenticatedCredential::host_console_owner(); + let preset = if client_kind == "mobile" { + DevicePermissionPreset::Companion + } else { + DevicePermissionPreset::Workstation + }; + let scopes = resolve_pairing_scopes( + &owner.scopes, + CreatePairingRequest { + preset: Some(preset), + requested_scopes: Vec::new(), + ttl_seconds: None, + }, + )?; + let device_id = DeviceId::new(); + let access_token = format!( + "vbx_device_{}{}", + Uuid::new_v4().simple(), + Uuid::new_v4().simple() + ); + let device_digest = TokenDigest::from_secret(&access_token); + + let mut connection = self.pool.acquire().await?; + sqlx::query("BEGIN IMMEDIATE") + .execute(&mut *connection) + .await?; + let tx_result: Result<(), AuthStoreError> = async { + if client_kind == "mobile" { + revoke_all_active_mobile_devices(&mut connection, now).await?; + } else if let Some(ref pubkey) = canonical_pubkey { + sqlx::query( + "UPDATE server_device_credentials + SET revoked_at_unix = ? + WHERE public_key_ed25519 = ? AND revoked_at_unix IS NULL", + ) + .bind(now) + .bind(pubkey) + .execute(&mut *connection) + .await?; + } + + sqlx::query( + "INSERT INTO server_device_credentials + (id, token_hash, device_name, scopes_json, created_at_unix, client_kind, + last_ip, last_connected_at_unix, public_key_ed25519) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + ) + .bind(device_id.to_string()) + .bind(device_digest.as_bytes().as_slice()) + .bind(device_name) + .bind(serde_json::to_string(&scopes).expect("scopes serialize")) + .bind(now) + .bind(&client_kind) + .bind(ip_address) + .bind(now) + .bind(&canonical_pubkey) + .execute(&mut *connection) + .await?; + + sqlx::query( + "INSERT INTO server_device_connect_requests + (id, device_name, client_kind, ip_address, public_key_ed25519, sas_code, + status, created_at_unix, expires_at_unix, responded_at_unix, + account_display_name, issued_device_id) + VALUES (?, ?, ?, ?, ?, ?, 'approved', ?, ?, ?, ?, ?)", + ) + .bind(&request_id_str) + .bind(device_name) + .bind(&client_kind) + .bind(ip_address) + .bind(&canonical_pubkey) + .bind(&sas_code) + .bind(now) + .bind(expires_at) + .bind(now) + .bind(account_display_name) + .bind(device_id.to_string()) + .execute(&mut *connection) + .await?; + + sqlx::query( + "INSERT INTO server_auth_audit_events + (id, event_kind, actor_credential_id, actor_device_id, target_id, outcome, + occurred_at_unix) + VALUES (?, 'pairing_redeemed', ?, NULL, ?, 'succeeded', ?)", + ) + .bind(Uuid::new_v4().to_string()) + .bind(&owner.credential_id) + .bind(device_id.to_string()) + .bind(now) + .execute(&mut *connection) + .await?; + + Ok(()) + } + .await; + + match tx_result { + Ok(()) => { + sqlx::query("COMMIT").execute(&mut *connection).await?; + } + Err(error) => { + let _ = sqlx::query("ROLLBACK").execute(&mut *connection).await; + return Err(error); + } + } + + return Ok(PollDeviceConnectResponse { + request_id, + host_id: host_id.to_owned(), + host_name, + sas_code, + status: DeviceConnectRequestStatus::Approved, + expires_at: unix_timestamp(expires_at), + credential: Some(DeviceCredential { + device_id, + access_token, + scopes, + }), + }); + } + if client_kind == "mobile" { let mut conn = self.pool.acquire().await?; if request.replace_existing_mobile { @@ -1171,14 +1312,26 @@ impl ServerAuth for SqliteServerAuth { return Err(AuthStoreError::Forbidden); } let now = self.now(); + let recent_auto_cutoff = now.saturating_sub(15); let rows = sqlx::query( - "SELECT id, device_name, client_kind, ip_address, sas_code, created_at_unix, expires_at_unix, - account_display_name - FROM server_device_connect_requests - WHERE status = 'pending' AND expires_at_unix > ? - ORDER BY created_at_unix DESC", + "SELECT r.id, r.device_name, r.client_kind, r.ip_address, r.sas_code, + r.status, r.created_at_unix, r.expires_at_unix, + r.account_display_name, r.issued_device_id + FROM server_device_connect_requests r + WHERE (r.status = 'pending' AND r.expires_at_unix > ?) + OR (r.status = 'approved' + AND r.account_display_name IS NOT NULL + AND r.issued_device_id IS NOT NULL + AND r.responded_at_unix >= ? + AND EXISTS ( + SELECT 1 FROM server_device_credentials d + WHERE d.id = r.issued_device_id AND d.revoked_at_unix IS NULL + )) + ORDER BY CASE WHEN r.status = 'pending' THEN 0 ELSE 1 END ASC, + r.created_at_unix DESC", ) .bind(now) + .bind(recent_auto_cutoff) .fetch_all(&self.pool) .await?; @@ -1190,6 +1343,17 @@ impl ServerAuth for SqliteServerAuth { }; let created_at_unix: i64 = row.try_get("created_at_unix")?; let expires_at_unix: i64 = row.try_get("expires_at_unix")?; + let raw_status: String = row.try_get("status")?; + let status = if raw_status == "approved" { + Some(DeviceConnectRequestStatus::Approved) + } else { + Some(DeviceConnectRequestStatus::Pending) + }; + let issued_device_id = row + .try_get::, _>("issued_device_id") + .ok() + .flatten() + .and_then(|raw| raw.parse::().ok()); items.push(PendingDeviceConnectRequest { request_id, device_name: row.try_get("device_name")?, @@ -1203,6 +1367,8 @@ impl ServerAuth for SqliteServerAuth { created_at: unix_timestamp(created_at_unix), expires_at: unix_timestamp(expires_at_unix), account_display_name: row.try_get("account_display_name")?, + status, + issued_device_id, }); } Ok(items) @@ -1331,11 +1497,13 @@ impl ServerAuth for SqliteServerAuth { let claimed = sqlx::query( "UPDATE server_device_connect_requests - SET status = 'approved', issued_credential_json = ?, responded_at_unix = ? + SET status = 'approved', issued_credential_json = ?, responded_at_unix = ?, + issued_device_id = ? WHERE id = ? AND status = 'pending'", ) .bind(credential_json) .bind(now) + .bind(device_id.to_string()) .bind(&id_str) .execute(&mut *connection) .await?; @@ -2030,10 +2198,16 @@ mod host_console_pairing_tests { client_kind: Some("mobile".to_owned()), ..Default::default() }; - auth.create_connect_request("host-1", request("Alice iPhone"), None, Some("Alice")) - .await - .expect("account request"); - auth.create_connect_request("host-1", request("Bob iPhone"), None, None) + auth.create_connect_request( + "host-1", + request("Alice iPhone"), + None, + Some("Alice"), + false, + ) + .await + .expect("account request"); + auth.create_connect_request("host-1", request("Bob iPhone"), None, None, false) .await .expect("plain request"); @@ -2047,4 +2221,86 @@ mod host_console_pairing_tests { assert_eq!(account_of("Alice iPhone"), Some(Some("Alice".to_owned()))); assert_eq!(account_of("Bob iPhone"), Some(None)); } + + #[tokio::test] + async fn same_account_auto_approve_issues_credential_immediately_and_replaces_mobile() { + use remote_protocol::DeviceConnectRequestStatus; + let auth = auth().await; + let owner = AuthenticatedCredential::host_console_owner(); + let request = |name: &str| remote_protocol::CreateDeviceConnectRequest { + device_name: name.to_owned(), + client_kind: Some("mobile".to_owned()), + ..Default::default() + }; + + let first = auth + .create_connect_request( + "host-1", + request("Alice iPhone 15"), + None, + Some("Alice"), + true, + ) + .await + .expect("first same-account connect"); + assert_eq!(first.status, DeviceConnectRequestStatus::Approved); + assert_eq!(first.sas_code.len(), 4); + let first_cred = first.credential.expect("immediate credential"); + assert!( + auth.authenticate(&first_cred.access_token) + .await + .unwrap() + .is_some() + ); + + // A second same-account phone smoothly replaces the first without MobileDeviceConflict + let second = auth + .create_connect_request( + "host-1", + request("Alice iPhone 16"), + None, + Some("Alice"), + true, + ) + .await + .expect("second same-account connect"); + assert_eq!(second.status, DeviceConnectRequestStatus::Approved); + let second_cred = second.credential.expect("second credential"); + assert!( + auth.authenticate(&first_cred.access_token) + .await + .unwrap() + .is_none() + ); + assert!( + auth.authenticate(&second_cred.access_token) + .await + .unwrap() + .is_some() + ); + + // Host console sees the active auto-approved entry with SAS code and device ID + let listed = auth.list_connect_requests(&owner).await.expect("list"); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].device_name, "Alice iPhone 16"); + assert_eq!(listed[0].status, Some(DeviceConnectRequestStatus::Approved)); + assert_eq!(listed[0].issued_device_id, Some(second_cred.device_id)); + assert_eq!(listed[0].sas_code, second.sas_code); + + // One-click disconnect from the desktop banner revokes the credential and hides the notice + auth.revoke_device(&owner, second_cred.device_id) + .await + .expect("revoke"); + assert!( + auth.authenticate(&second_cred.access_token) + .await + .unwrap() + .is_none() + ); + let after_revoke = auth + .list_connect_requests(&owner) + .await + .expect("list after revoke"); + assert!(after_revoke.is_empty()); + } } diff --git a/crates/server/src/runtime.rs b/crates/server/src/runtime.rs index a0e42ba7e..0b2e1162d 100644 --- a/crates/server/src/runtime.rs +++ b/crates/server/src/runtime.rs @@ -942,7 +942,7 @@ async fn create_connect_request( Json(request): Json, ) -> Response { let ip_address = extract_client_ip(&headers, state.config.listen_addr); - let account_display_name = match request + let (account_display_name, auto_approve) = match request .account_token .as_deref() .map(str::trim) @@ -955,10 +955,10 @@ async fn create_connect_request( ) .await { - Ok(identity) => Some(identity.display_name), + Ok(verified) => (Some(verified.identity.display_name), verified.auto_approve), Err(error) => return account_link_error_response(&error), }, - None => None, + None => (None, false), }; match state .auth @@ -967,6 +967,7 @@ async fn create_connect_request( request, ip_address.as_deref(), account_display_name.as_deref(), + auto_approve, ) .await { diff --git a/frontend/src/components/layout/MobileDeviceConnectBanner.test.tsx b/frontend/src/components/layout/MobileDeviceConnectBanner.test.tsx index d79cc5776..3fa774303 100644 --- a/frontend/src/components/layout/MobileDeviceConnectBanner.test.tsx +++ b/frontend/src/components/layout/MobileDeviceConnectBanner.test.tsx @@ -6,11 +6,16 @@ import { MobileDeviceConnectBanner } from './MobileDeviceConnectBanner'; const listConnectRequestsMock = vi.fn(); const respondConnectRequestMock = vi.fn(); const listDevicesMock = vi.fn(); +const revokeDeviceMock = vi.fn(); vi.mock('@/lib/desktopShell', () => ({ isLocalDesktopHost: () => true, })); +vi.mock('@/lib/frontendPreferences', () => ({ + writeDesktopSharedPreferenceSection: vi.fn(), +})); + vi.mock('@/lib/api/config', () => ({ webServiceApi: { listConnectRequests: (...args: unknown[]) => @@ -18,6 +23,7 @@ vi.mock('@/lib/api/config', () => ({ respondConnectRequest: (...args: unknown[]) => respondConnectRequestMock(...args), listDevices: (...args: unknown[]) => listDevicesMock(...args), + revokeDevice: (...args: unknown[]) => revokeDeviceMock(...args), }, })); @@ -26,6 +32,7 @@ describe('MobileDeviceConnectBanner', () => { listConnectRequestsMock.mockReset(); respondConnectRequestMock.mockReset(); listDevicesMock.mockReset(); + revokeDeviceMock.mockReset(); listDevicesMock.mockResolvedValue([]); }); @@ -50,6 +57,7 @@ describe('MobileDeviceConnectBanner', () => { sas_code: '8392', created_at: '2026-11-09T05:00:00Z', expires_at: '2026-11-09T05:03:00Z', + status: 'pending', }, ]); respondConnectRequestMock.mockResolvedValue(undefined); @@ -59,7 +67,7 @@ describe('MobileDeviceConnectBanner', () => { expect( await screen.findByText(/发现可用移动设备「Pixel 9 Pro」/) ).toBeInTheDocument(); - expect(screen.getByText('核对码 8392')).toBeInTheDocument(); + expect(screen.getByText('连接码 8392')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: '连接' })); @@ -71,7 +79,7 @@ describe('MobileDeviceConnectBanner', () => { ).toBeInTheDocument(); }); - it('marks requests the host verified as coming from its own account', async () => { + it('displays non-blocking connected notice with connection code and disconnect button for auto-approved same-account devices', async () => { listConnectRequestsMock.mockResolvedValue([ { request_id: 'req-acct', @@ -81,12 +89,24 @@ describe('MobileDeviceConnectBanner', () => { created_at: '2026-11-12T05:00:00Z', expires_at: '2026-11-12T05:03:00Z', account_display_name: 'Alice', + status: 'approved', + issued_device_id: 'dev-123', }, ]); + revokeDeviceMock.mockResolvedValue(undefined); render(); - expect(await screen.findByText('同账号 · Alice')).toBeInTheDocument(); - expect(screen.getByText('核对码 1204')).toBeInTheDocument(); + expect( + await screen.findByText(/已连接移动设备「iPhone 16 Pro」/) + ).toBeInTheDocument(); + expect(screen.getByText('同账号 · Alice')).toBeInTheDocument(); + expect(screen.getByText('连接码 1204')).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: '断开' })); + + await waitFor(() => { + expect(revokeDeviceMock).toHaveBeenCalledWith('dev-123'); + }); }); }); diff --git a/frontend/src/components/layout/MobileDeviceConnectBanner.tsx b/frontend/src/components/layout/MobileDeviceConnectBanner.tsx index bbc168a10..a9927a14a 100644 --- a/frontend/src/components/layout/MobileDeviceConnectBanner.tsx +++ b/frontend/src/components/layout/MobileDeviceConnectBanner.tsx @@ -8,17 +8,21 @@ import { webServiceApi, } from '@/lib/api/config'; import { isLocalDesktopHost } from '@/lib/desktopShell'; +import { writeDesktopSharedPreferenceSection } from '@/lib/frontendPreferences'; -const POLL_INTERVAL_MS = 2500; +const POLL_INTERVAL_MS = 1800; +const AUTO_CONNECT_BANNER_MS = 5000; export const CONNECT_REQUESTS_CHANGED_EVENT = 'vibex:connect-requests-changed'; export const REMOTE_AUTO_CONNECT_KEY = 'vibex:remote-auto-connect'; +export const HOST_SAME_ACCOUNT_AUTO_CONNECT_KEY = + '__same_account_auto_connect_v1'; export function getRemoteAutoConnect(): boolean { - if (typeof window === 'undefined') return false; + if (typeof window === 'undefined') return true; try { - return window.localStorage.getItem(REMOTE_AUTO_CONNECT_KEY) === 'true'; + return window.localStorage.getItem(REMOTE_AUTO_CONNECT_KEY) !== 'false'; } catch { - return false; + return true; } } @@ -29,6 +33,10 @@ export function setRemoteAutoConnect(enabled: boolean): void { REMOTE_AUTO_CONNECT_KEY, enabled ? 'true' : 'false' ); + void writeDesktopSharedPreferenceSection( + HOST_SAME_ACCOUNT_AUTO_CONNECT_KEY, + enabled + ); notifyConnectRequestsChanged(); } catch { // Ignore storage errors @@ -71,19 +79,42 @@ function isActivelyConnectedRecently( return ts >= sessionStartMs || Date.now() - ts < 90_000; } +interface ConnectedMobileNotice { + deviceName: string; + sasCode?: string | null; + accountDisplayName?: string | null; + issuedDeviceId?: string | null; +} + export function MobileDeviceConnectBanner() { const [requests, setRequests] = useState([]); const [pairedMobileDevices, setPairedMobileDevices] = useState< HostPairedDevice[] >([]); const [busyId, setBusyId] = useState(null); - const [connectedDeviceName, setConnectedDeviceName] = useState( - null - ); + const [revokingDeviceId, setRevokingDeviceId] = useState(null); + const [connectedNotice, setConnectedNotice] = + useState(null); const [idleReminderDismissed, setIdleReminderDismissed] = useState(false); const sessionStartMsRef = useRef(Date.now()); const clearFeedbackTimerRef = useRef(null); const respondedIdsRef = useRef>(new Set()); + const seenAutoApprovedIdsRef = useRef>(new Set()); + + const showConnectedNotice = useCallback( + (notice: ConnectedMobileNotice, durationMs: number) => { + setIdleReminderDismissed(true); + setConnectedNotice(notice); + if (clearFeedbackTimerRef.current !== null) { + window.clearTimeout(clearFeedbackTimerRef.current); + } + clearFeedbackTimerRef.current = window.setTimeout(() => { + setConnectedNotice(null); + clearFeedbackTimerRef.current = null; + }, durationMs); + }, + [] + ); const handleRespond = useCallback( async (item: PendingDeviceConnectRequest, approve: boolean) => { @@ -96,15 +127,14 @@ export function MobileDeviceConnectBanner() { ); notifyConnectRequestsChanged(); if (approve) { - setIdleReminderDismissed(true); - setConnectedDeviceName(item.device_name); - if (clearFeedbackTimerRef.current !== null) { - window.clearTimeout(clearFeedbackTimerRef.current); - } - clearFeedbackTimerRef.current = window.setTimeout(() => { - setConnectedDeviceName(null); - clearFeedbackTimerRef.current = null; - }, 2400); + showConnectedNotice( + { + deviceName: item.device_name, + sasCode: item.sas_code, + accountDisplayName: item.account_display_name ?? null, + }, + 3000 + ); } } catch (err) { console.warn('Failed to respond to mobile connect request:', err); @@ -112,9 +142,26 @@ export function MobileDeviceConnectBanner() { setBusyId(null); } }, - [] + [showConnectedNotice] ); + const handleDisconnectIssued = useCallback(async (deviceId: string) => { + setRevokingDeviceId(deviceId); + try { + await webServiceApi.revokeDevice(deviceId); + if (clearFeedbackTimerRef.current !== null) { + window.clearTimeout(clearFeedbackTimerRef.current); + clearFeedbackTimerRef.current = null; + } + setConnectedNotice(null); + notifyConnectRequestsChanged(); + } catch (err) { + console.warn('Failed to revoke auto-connected mobile device:', err); + } finally { + setRevokingDeviceId(null); + } + }, []); + const refreshRequests = useCallback(async () => { if (!isLocalDesktopHost()) { return; @@ -129,11 +176,30 @@ export function MobileDeviceConnectBanner() { : []; setPairedMobileDevices(mobileDevices); - const filtered = Array.isArray(nextRequests) - ? nextRequests.filter( - (entry) => !respondedIdsRef.current.has(entry.request_id) - ) - : []; + const allItems = Array.isArray(nextRequests) ? nextRequests : []; + const freshAutoApproved = allItems.find( + (entry) => + entry.status === 'approved' && + !seenAutoApprovedIdsRef.current.has(entry.request_id) + ); + if (freshAutoApproved) { + seenAutoApprovedIdsRef.current.add(freshAutoApproved.request_id); + showConnectedNotice( + { + deviceName: freshAutoApproved.device_name, + sasCode: freshAutoApproved.sas_code, + accountDisplayName: freshAutoApproved.account_display_name ?? null, + issuedDeviceId: freshAutoApproved.issued_device_id ?? null, + }, + AUTO_CONNECT_BANNER_MS + ); + } + + const filtered = allItems.filter( + (entry) => + entry.status !== 'approved' && + !respondedIdsRef.current.has(entry.request_id) + ); // If auto-connect is enabled and an already-paired mobile device is requesting connection, auto-approve if ( @@ -159,7 +225,7 @@ export function MobileDeviceConnectBanner() { } catch { // Ignore in non-host windows or before backend is ready } - }, [handleRespond]); + }, [handleRespond, showConnectedNotice]); useEffect(() => { void refreshRequests(); @@ -184,7 +250,7 @@ export function MobileDeviceConnectBanner() { // active 1-click connection approval request arrives. const active = requests[0] ?? null; const hasPairedMobile = pairedMobileDevices.length > 0; - if (!active && !hasPairedMobile && !connectedDeviceName) { + if (!active && !hasPairedMobile && !connectedNotice) { return null; } @@ -197,7 +263,7 @@ export function MobileDeviceConnectBanner() { ) && !idleReminderDismissed; - if (!active && !connectedDeviceName && !isPairedMobileIdle) { + if (!active && !connectedNotice && !isPairedMobileIdle) { return null; } @@ -211,14 +277,39 @@ export function MobileDeviceConnectBanner() { aria-label="可用移动设备连接请求" className="pointer-events-auto inline-flex min-h-11 max-w-full items-center gap-3 rounded-full border border-border bg-secondary/95 px-4 py-2 text-sm text-foreground shadow-lg backdrop-blur-md transition-all duration-150" > - {connectedDeviceName && !active ? ( + {connectedNotice && !active ? ( <> - + - 已连接移动设备「{connectedDeviceName}」 + 已连接移动设备「{connectedNotice.deviceName}」 + {connectedNotice.accountDisplayName ? ( + + 同账号 · {connectedNotice.accountDisplayName} + + ) : null} + {connectedNotice.sasCode ? ( + + 连接码 {connectedNotice.sasCode} + + ) : null} + {connectedNotice.issuedDeviceId ? ( + + ) : null} ) : active ? ( <> @@ -239,9 +330,9 @@ export function MobileDeviceConnectBanner() { ) : null} - 核对码 {active.sas_code} + 连接码 {active.sas_code} {requests.length > 1 ? ( diff --git a/frontend/src/lib/api/config.ts b/frontend/src/lib/api/config.ts index 97da117e9..aa78f8a83 100644 --- a/frontend/src/lib/api/config.ts +++ b/frontend/src/lib/api/config.ts @@ -468,6 +468,8 @@ export interface PendingDeviceConnectRequest { expires_at: string; /** Present when the host verified the request comes from its own VibeX account. */ account_display_name?: string | null; + status?: 'pending' | 'approved' | 'rejected' | 'expired'; + issued_device_id?: string | null; } export interface PortProbeResult { diff --git a/frontend/src/pages/settings/DevicePairingPanel.tsx b/frontend/src/pages/settings/DevicePairingPanel.tsx index 8306f6e78..ce3272b1e 100644 --- a/frontend/src/pages/settings/DevicePairingPanel.tsx +++ b/frontend/src/pages/settings/DevicePairingPanel.tsx @@ -176,7 +176,11 @@ export function DevicePairingPanel({ } try { const requests = await webServiceApi.listConnectRequests(); - setPendingRequests(Array.isArray(requests) ? requests : []); + setPendingRequests( + Array.isArray(requests) + ? requests.filter((entry) => entry.status !== 'approved') + : [] + ); } catch { setPendingRequests([]); } @@ -530,7 +534,7 @@ export function DevicePairingPanel({ {req.device_name} - 核对码 {req.sas_code} + 连接码 {req.sas_code} {req.ip_address ? ( diff --git a/frontend/src/pages/settings/WebServiceSettings.tsx b/frontend/src/pages/settings/WebServiceSettings.tsx index 0200132aa..5985401a4 100644 --- a/frontend/src/pages/settings/WebServiceSettings.tsx +++ b/frontend/src/pages/settings/WebServiceSettings.tsx @@ -537,10 +537,11 @@ export function WebServiceSettings({

- 首次连接成功后,已配对的手机再次发起连接时自动允许接入 + 两端登录同一 VibeX 账号或手机已配对时,免确认直连并显示 + 4 位连接码供对比

Date: Sat, 14 Nov 2026 23:47:46 +0800 Subject: [PATCH 11/12] chore(docs): drop stale android-frontend doc edit superseded upstream --- docs/companion/android-frontend.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/companion/android-frontend.md b/docs/companion/android-frontend.md index 66ce14867..915a82dbe 100644 --- a/docs/companion/android-frontend.md +++ b/docs/companion/android-frontend.md @@ -72,10 +72,8 @@ mono 12/18。 ### 2.5 动效 -内容动效只做两处:信号条在 recovering 时缓慢呼吸;新时间线行从轨上长出 120ms。 -页面跳转统一走 `NavMotion`:底栏切换 160ms 交叉淡入;进入下一级从右侧滑入、返回原路滑出; -配对页自底部升起。 -尊重 reduce-motion:全部改瞬切。不要全页粒子、不要骨架屏闪烁循环。 +只做两处:信号条在 recovering 时缓慢呼吸;新时间线行从轨上长出 120ms。 +尊重 reduce-motion:两者都改瞬切。不要全页粒子、不要骨架屏闪烁循环。 ## 3. 信息架构(对照 CodeG) From 396e1d6c9c79d90a7e0e8555c3c36d2be82507ae Mon Sep 17 00:00:00 2001 From: DorJay Date: Sun, 15 Nov 2026 02:33:54 +0800 Subject: [PATCH 12/12] feat(remote,companion): resilient remote lease lifecycle, sign-out device revocation, and iOS/Android parity --- crates/server/src/auth.rs | 116 +++++++++++++++++- frontend/src/features/model-router/account.ts | 16 ++- .../model-router/accountHostConfigs.ts | 43 +++++-- frontend/src/lib/api/config.ts | 4 + mobile/android | 2 +- mobile/ios | 2 +- shared/hostCommands.ts | 1 + src-tauri/src/bin/generate_types.rs | 1 + src-tauri/src/commands/host_tunnel.rs | 71 ++++++++++- src-tauri/src/commands/web_service.rs | 14 ++- src-tauri/src/lib.rs | 1 + 11 files changed, 250 insertions(+), 21 deletions(-) diff --git a/crates/server/src/auth.rs b/crates/server/src/auth.rs index 6d31caffe..867ec4ebe 100644 --- a/crates/server/src/auth.rs +++ b/crates/server/src/auth.rs @@ -1543,6 +1543,54 @@ impl ServerAuth for SqliteServerAuth { } impl SqliteServerAuth { + /// Revokes every device admitted because it shares the VibeX account signed in on this + /// Host. Called when the Host signs out, since that account no longer vouches for them. + /// Live WebSockets of the revoked devices close on their next revocation check. + pub async fn revoke_account_linked_devices( + &self, + actor: &AuthenticatedCredential, + ) -> Result { + if !actor.allows("device.revoke") { + return Err(AuthStoreError::Forbidden); + } + let now = self.now(); + let mut transaction = self.pool.begin().await?; + let device_ids: Vec = sqlx::query_scalar( + "SELECT DISTINCT d.id + FROM server_device_credentials d + JOIN server_device_connect_requests r ON r.issued_device_id = d.id + WHERE d.revoked_at_unix IS NULL AND r.account_display_name IS NOT NULL", + ) + .fetch_all(&mut *transaction) + .await?; + for device_id in &device_ids { + sqlx::query( + "UPDATE server_device_credentials + SET revoked_at_unix = ? + WHERE id = ? AND revoked_at_unix IS NULL", + ) + .bind(now) + .bind(device_id) + .execute(&mut *transaction) + .await?; + sqlx::query( + "INSERT INTO server_auth_audit_events + (id, event_kind, actor_credential_id, actor_device_id, target_id, outcome, + occurred_at_unix) + VALUES (?, 'device_revoked', ?, ?, ?, 'succeeded', ?)", + ) + .bind(Uuid::new_v4().to_string()) + .bind(&actor.credential_id) + .bind(actor.device_id.map(|id| id.to_string())) + .bind(device_id) + .bind(now) + .execute(&mut *transaction) + .await?; + } + transaction.commit().await?; + Ok(device_ids.len() as u64) + } + /// Persists a WebRTC device after the user approves the SAS prompt on the Host. pub async fn trust_webrtc_device( &self, @@ -1986,12 +2034,14 @@ pub(crate) fn infer_preset(scopes: &[String]) -> Option mod host_console_pairing_tests { use std::str::FromStr; + use base64::Engine as _; use chrono::{DateTime, Utc}; use remote_protocol::{CreatePairingRequest, DevicePermissionPreset, RedeemPairingRequest}; use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions}; use super::{ - AuthStoreError, AuthenticatedCredential, CredentialKind, ServerAuth, SqliteServerAuth, + AuthStoreError, AuthenticatedCredential, BASE64, CredentialKind, DeviceId, ServerAuth, + SqliteServerAuth, TrustWebRtcDeviceRequest, }; async fn auth() -> SqliteServerAuth { @@ -2303,4 +2353,68 @@ mod host_console_pairing_tests { .expect("list after revoke"); assert!(after_revoke.is_empty()); } + + #[tokio::test] + async fn host_sign_out_revokes_only_account_linked_devices() { + let auth = auth().await; + let owner = AuthenticatedCredential::host_console_owner(); + let phone = auth + .create_connect_request( + "host-1", + remote_protocol::CreateDeviceConnectRequest { + device_name: "Alice Pixel".to_owned(), + client_kind: Some("mobile".to_owned()), + ..Default::default() + }, + None, + Some("Alice"), + true, + ) + .await + .expect("same-account phone") + .credential + .expect("phone credential"); + let workstation = auth + .trust_webrtc_device( + &owner, + TrustWebRtcDeviceRequest { + device_id: DeviceId::new(), + device_name: "Studio Mac".to_owned(), + public_key_ed25519: BASE64.encode([7u8; 32]), + preset: DevicePermissionPreset::Workstation, + }, + ) + .await + .expect("paired workstation"); + + assert_eq!( + auth.revoke_account_linked_devices(&owner) + .await + .expect("revoke"), + 1 + ); + assert!( + auth.authenticate(&phone.access_token) + .await + .unwrap() + .is_none() + ); + let remaining = auth.list_devices(&owner).await.expect("list"); + assert!( + remaining + .iter() + .any(|device| device.device_id == workstation.device_id) + ); + assert!( + remaining + .iter() + .all(|device| device.device_id != phone.device_id) + ); + assert_eq!( + auth.revoke_account_linked_devices(&owner) + .await + .expect("second revoke"), + 0 + ); + } } diff --git a/frontend/src/features/model-router/account.ts b/frontend/src/features/model-router/account.ts index 1a1a2f699..e12b932e3 100644 --- a/frontend/src/features/model-router/account.ts +++ b/frontend/src/features/model-router/account.ts @@ -2,6 +2,7 @@ import { getSiteUrl } from '@/lib/branding'; import { hostClientApi, hostTunnelApi, + webServiceApi, type SyncableHostProfile, } from '@/lib/api'; import { isTauriClient } from '@/lib/desktopShell'; @@ -173,10 +174,12 @@ export class AccountError extends Error { export const ACCOUNT_TOKEN_EVENT = 'vibex:account-token-changed'; export const DESKTOP_SHARED_ACCOUNT_TOKEN_KEY = '__account_token_v1'; export const DESKTOP_SHARED_ACCOUNT_OWNER_KEY = '__account_owner_v1'; -export const HOST_BOUND_ACCOUNTS_STORAGE_KEY = 'vibex.account.hostBoundAccounts.v1'; +export const HOST_BOUND_ACCOUNTS_STORAGE_KEY = + 'vibex.account.hostBoundAccounts.v1'; export const HOST_BOUND_ACCOUNTS_EVENT = 'vibex:host-bound-accounts-changed'; let sharedTokenHydrationStarted = false; -const EMPTY_HOST_BOUND_ACCOUNTS: Record = Object.freeze({}); +const EMPTY_HOST_BOUND_ACCOUNTS: Record = + Object.freeze({}); let cachedHostBoundAccountsRaw: string | null = null; let cachedHostBoundAccountsSnapshot: Record = EMPTY_HOST_BOUND_ACCOUNTS; @@ -203,7 +206,8 @@ export function readHostBoundAccounts(): Record { for (const [key, value] of Object.entries(parsed)) { if (!value || typeof value !== 'object') continue; const obj = value as Record; - const username = typeof obj.username === 'string' ? obj.username.trim() : ''; + const username = + typeof obj.username === 'string' ? obj.username.trim() : ''; if (!username) continue; const displayName = typeof obj.displayName === 'string' && obj.displayName.trim() @@ -467,6 +471,8 @@ export const accountApi = { void hostTunnelApi.setAccountLease(null).catch(() => null); if (isTauriClient()) { void hostClientApi.setSyncAccount(null).catch(() => null); + // Phones were admitted because they share this account; signing out ends that trust. + void webServiceApi.revokeAccountLinkedDevices().catch(() => null); } if (typeof window !== 'undefined') { window.dispatchEvent(new Event('vibex:host-tunnel-updated')); @@ -557,7 +563,9 @@ export const accountApi = { savedHosts?: SyncableHostProfile[]; }> => authed('/api/account/desktop/saved-hosts', 'PUT', { profiles }), - deleteSavedHost: (selector: SavedHostDeleteSelector): Promise<{ + deleteSavedHost: ( + selector: SavedHostDeleteSelector + ): Promise<{ ok?: boolean; deleted?: number; savedHosts?: SyncableHostProfile[]; diff --git a/frontend/src/features/model-router/accountHostConfigs.ts b/frontend/src/features/model-router/accountHostConfigs.ts index c53798078..4303ba43b 100644 --- a/frontend/src/features/model-router/accountHostConfigs.ts +++ b/frontend/src/features/model-router/accountHostConfigs.ts @@ -52,6 +52,15 @@ export const ACCOUNT_HOST_CONFIGS_STORAGE_KEY = 'vibex.account.hostConfigs.v1'; export const DESKTOP_SHARED_HOST_CONFIGS_KEY = '__account_host_configs_v1'; const ACCOUNT_HOST_CONFIGS_EVENT = 'vibex:account-host-configs-changed'; const AUTO_SYNC_DEBOUNCE_MS = 800; +/** Leases last 30 days; renewing on a timer keeps the relay up without relying on window focus. */ +const RELAY_LEASE_RENEW_INTERVAL_MS = 6 * 60 * 60 * 1000; +/** Lease errors that mean the account or host can no longer use the relay; others are transient. */ +const RELAY_LEASE_TERMINAL_ERRORS = new Set([ + 'signed_out', + 'account_disabled', + 'host_id_conflict', + 'invalid_host_id', +]); export type AccountHostKind = 'local' | 'ssh' | 'remote' | 'web'; @@ -819,7 +828,9 @@ export async function reconcileRemoteHostAccount( rawHostId || null, rawHostId ? `host:${rawHostId}` : null, profile?.origin?.trim().replace(/\/+$/, '') || null, - profile?.origin ? `origin:${profile.origin.trim().replace(/\/+$/, '')}` : null, + profile?.origin + ? `origin:${profile.origin.trim().replace(/\/+$/, '')}` + : null, ]; const remoteTokenRaw = remotePrefs?.[DESKTOP_SHARED_ACCOUNT_TOKEN_KEY]; @@ -929,8 +940,14 @@ async function issueAndApplyLocalRelayLease(input: { window.dispatchEvent(new Event('vibex:host-tunnel-updated')); } return true; - } catch { - await hostTunnelApi.setAccountLease(null).catch(() => undefined); + } catch (cause) { + // A network blip must not tear down a working relay; the stored lease stays valid. + if ( + cause instanceof AccountError && + RELAY_LEASE_TERMINAL_ERRORS.has(cause.code) + ) { + await hostTunnelApi.setAccountLease(null).catch(() => undefined); + } return false; } } @@ -1487,20 +1504,28 @@ export function AccountHostConfigSyncBridge(): null { // Immediate sync upon login / account identity resolution, and debounced sync when Config changes. const hasInitialSyncForAccountRef = useRef(null); useEffect(() => { - if (!accountKey || !user || loading || !config) { - if (!accountKey) { - hasInitialSyncForAccountRef.current = null; - resetStoreOnSignOut(); - } + if (!isSignedIn) { + hasInitialSyncForAccountRef.current = null; + resetStoreOnSignOut(); return; } + // While the account profile is still loading the relay lease stays in place. + if (!accountKey || !user || loading || !config) return; if (hasInitialSyncForAccountRef.current !== accountKey) { hasInitialSyncForAccountRef.current = accountKey; void syncAccountHostConfigs(user); return; } scheduleAutoSync(); - }, [accountKey, config, loading, scheduleAutoSync, user]); + }, [accountKey, config, isSignedIn, loading, scheduleAutoSync, user]); + + useEffect(() => { + if (!accountKey) return; + const timer = window.setInterval(() => { + void syncCurrentHostRelayLease(); + }, RELAY_LEASE_RENEW_INTERVAL_MS); + return () => window.clearInterval(timer); + }, [accountKey]); // Listen for frontend preference changes & Agent enablement/reorder events on the current Host. useEffect(() => { diff --git a/frontend/src/lib/api/config.ts b/frontend/src/lib/api/config.ts index aa78f8a83..38907b402 100644 --- a/frontend/src/lib/api/config.ts +++ b/frontend/src/lib/api/config.ts @@ -782,6 +782,10 @@ export const webServiceApi = { request: { device_id: deviceId }, }); }, + /** Revokes every phone that connected through the account signed in on this computer. */ + revokeAccountLinkedDevices: async (): Promise => { + return desktopShellCall('revoke_account_linked_devices'); + }, }; export interface ChatChannelStatus { diff --git a/mobile/android b/mobile/android index 930bee205..2e06ca014 160000 --- a/mobile/android +++ b/mobile/android @@ -1 +1 @@ -Subproject commit 930bee2050b1a6c22f9e830caca3bbe63e69cc7a +Subproject commit 2e06ca014d3f74e709c1c3cb62882bdae924def5 diff --git a/mobile/ios b/mobile/ios index a3dc62aa9..8a1bc113e 160000 --- a/mobile/ios +++ b/mobile/ios @@ -1 +1 @@ -Subproject commit a3dc62aa9a9de43b437738044f463da29dff345d +Subproject commit 8a1bc113e4175e7d6369b75c1ab573b5962925da diff --git a/shared/hostCommands.ts b/shared/hostCommands.ts index dd7a4df16..fe163c8be 100644 --- a/shared/hostCommands.ts +++ b/shared/hostCommands.ts @@ -560,6 +560,7 @@ export const DESKTOP_SHELL_COMMANDS = [ 'update_tray_badge', 'host_client_delete', 'revoke_host_device', + 'revoke_account_linked_devices', 'fixture_delegate', 'fixture_reset', 'allow_preview_asset_scope', diff --git a/src-tauri/src/bin/generate_types.rs b/src-tauri/src/bin/generate_types.rs index 80f71c8b0..5feb08928 100644 --- a/src-tauri/src/bin/generate_types.rs +++ b/src-tauri/src/bin/generate_types.rs @@ -342,6 +342,7 @@ const DESKTOP_SHELL_COMMANDS: &[&str] = &[ "update_tray_badge", "host_client_delete", "revoke_host_device", + "revoke_account_linked_devices", "fixture_delegate", "fixture_reset", // The asset protocol lives in the local webview, so the Host — which may be diff --git a/src-tauri/src/commands/host_tunnel.rs b/src-tauri/src/commands/host_tunnel.rs index a408eec0b..c89a8f864 100644 --- a/src-tauri/src/commands/host_tunnel.rs +++ b/src-tauri/src/commands/host_tunnel.rs @@ -234,7 +234,11 @@ fn default_official_quick_origin(store: &HostTunnelStore) -> Option { } else { load_or_create_host_id_sync().unwrap_or_else(|| "default".to_string()) }; - let scheme = if endpoint.port == 443 { "https" } else { "http" }; + let scheme = if endpoint.port == 443 { + "https" + } else { + "http" + }; Some(utils::tunnel::format_tenant_origin( scheme, &endpoint, &host_id, )) @@ -601,7 +605,13 @@ async fn run_quick_tunnel_supervisor(local_port: u16) { let token = lease.lease_token.trim().to_string(); let state = Arc::new(Mutex::new(RelayState::default())); let key = format!("{}:{}:official", host, port); - let _ = maintain_control(&host, port, &token, local_port, &key, &state).await; + if let Err(error) = + maintain_control(&host, port, &token, local_port, &key, &state).await + && let Some(reason) = terminal_lease_rejection(&error) + { + tracing::warn!(reason, "official relay rejected the account lease"); + drop_rejected_account_lease(&token).await; + } } else { set_quick_tunnel_origin(None); } @@ -609,6 +619,42 @@ async fn run_quick_tunnel_supervisor(local_port: u16) { } } +const RELAY_REJECTION_PREFIX: &str = "relay rejected control session: "; + +/// Relay rejections that the same lease can never recover from (the computer was removed +/// from the account, or the lease is no longer valid). Retrying them only loads the relay. +fn terminal_lease_rejection(error: &str) -> Option<&str> { + let reason = error.strip_prefix(RELAY_REJECTION_PREFIX)?.trim(); + matches!( + reason, + "host_revoked" | "lease_expired" | "invalid_lease_signature" | "lease_host_mismatch" + ) + .then_some(reason) +} + +/// Forgets a lease the relay rejected, unless the frontend already stored a newer one; the +/// next lease renewal reconnects the relay. +async fn drop_rejected_account_lease(rejected_token: &str) { + let Ok(mut store) = load_store().await else { + return; + }; + let still_current = store + .account_lease + .as_ref() + .is_some_and(|lease| lease.lease_token.trim() == rejected_token); + if !still_current { + return; + } + store.account_lease = None; + set_quick_tunnel_origin(None); + if store.active_id.as_deref() == Some("auto-quick-tunnel") { + store.active_id = store.saved.first().map(|item| item.id.clone()); + } + if let Err(error) = save_store(&store).await { + tracing::warn!(%error, "failed to forget the rejected relay lease"); + } +} + fn sha256_hex(input: &str) -> String { use sha2::{Digest, Sha256}; let mut hasher = Sha256::new(); @@ -824,7 +870,7 @@ async fn maintain_control( } if let Some(err_reason) = trimmed.strip_prefix("ERR ") { writer_task.abort(); - return Err(format!("relay rejected control session: {err_reason}")); + return Err(format!("{RELAY_REJECTION_PREFIX}{err_reason}")); } // Backwards compatibility with v1 single-host relay script if let Some(id) = trimmed.strip_prefix("OPEN ") { @@ -1532,6 +1578,25 @@ mod tests { ); } + #[test] + fn only_unrecoverable_relay_rejections_drop_the_lease() { + assert_eq!( + super::terminal_lease_rejection("relay rejected control session: host_revoked"), + Some("host_revoked") + ); + assert_eq!( + super::terminal_lease_rejection("relay rejected control session: lease_expired"), + Some("lease_expired") + ); + assert_eq!( + super::terminal_lease_rejection( + "relay rejected control session: relay_lease_unconfigured" + ), + None + ); + assert_eq!(super::terminal_lease_rejection("connection reset"), None); + } + #[test] fn removed_relay_keeps_token_for_reconnect() { let mut store = HostTunnelStore { diff --git a/src-tauri/src/commands/web_service.rs b/src-tauri/src/commands/web_service.rs index 7bbb03015..849683302 100644 --- a/src-tauri/src/commands/web_service.rs +++ b/src-tauri/src/commands/web_service.rs @@ -785,6 +785,16 @@ pub async fn revoke_host_device( .map_err(|error| AppError::Internal(error.to_string())) } +/// Revokes the phones and computers admitted through the VibeX account of this Host, so +/// signing out disconnects them on every path (LAN and relay). +#[tauri::command] +pub async fn revoke_account_linked_devices(app: tauri::AppHandle) -> Result { + let auth = server::SqliteServerAuth::new(app.state::().deployment.db().pool.clone()); + auth.revoke_account_linked_devices(&server::AuthenticatedCredential::host_console_owner()) + .await + .map_err(|error| AppError::Internal(error.to_string())) +} + pub(crate) async fn listening_port() -> Option { WEB_SERVICE_RUNTIME .lock() @@ -938,7 +948,8 @@ mod tests { .local_addr() .expect("first occupied listener should expose address") .port(); - let _occupied_second = StdTcpListener::bind(("127.0.0.1", base_port.saturating_add(1))).ok(); + let _occupied_second = + StdTcpListener::bind(("127.0.0.1", base_port.saturating_add(1))).ok(); let config = WebServiceConfig { port: base_port, @@ -964,4 +975,3 @@ mod tests { ); } } - diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 8630d6f32..67dbd1f84 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -763,6 +763,7 @@ pub fn run() { commands::web_service::list_host_connect_requests, commands::web_service::respond_host_connect_request, commands::web_service::revoke_host_device, + commands::web_service::revoke_account_linked_devices, commands::host_tunnel::get_host_tunnel, commands::host_tunnel::set_host_tunnel_enabled, commands::host_tunnel::check_existing_host_tunnel,