diff --git a/crates/db/migrations/20261118000000_connect_request_account.sql b/crates/db/migrations/20261118000000_connect_request_account.sql new file mode 100644 index 000000000..57964aab7 --- /dev/null +++ b/crates/db/migrations/20261118000000_connect_request_account.sql @@ -0,0 +1 @@ +ALTER TABLE server_device_connect_requests ADD COLUMN account_display_name TEXT; diff --git a/crates/db/migrations/20261118010000_connect_request_auto_approval.sql b/crates/db/migrations/20261118010000_connect_request_auto_approval.sql new file mode 100644 index 000000000..1d506ba5e --- /dev/null +++ b/crates/db/migrations/20261118010000_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 b6b67c488..644d683ae 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, + /// Dimo 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)] @@ -223,6 +243,17 @@ pub struct PendingDeviceConnectRequest { pub sas_code: String, pub created_at: String, pub expires_at: String, + /// Display name of the Dimo 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, + /// `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 new file mode 100644 index 000000000..a496b3668 --- /dev/null +++ b/crates/server/src/account_link.rs @@ -0,0 +1,371 @@ +//! Same-account device authorization. +//! +//! A device that presents a Dimo account token may connect directly when the token belongs +//! to the account currently signed in on the host. The host never trusts the identity a device +//! claims or a stale cached owner record: both tokens are verified live through the Dimo site +//! account API and matched by immutable account ID (falling back to username only when absent). +//! 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}; + +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_SAME_ACCOUNT_AUTO_CONNECT_KEY: &str = "__same_account_auto_connect_v1"; + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub(crate) enum AccountLinkError { + #[error("this computer is not signed in to a Dimo account")] + HostSignedOut, + #[error("the Dimo account token is not valid")] + InvalidToken, + #[error("the Dimo account does not match the account signed in on this computer")] + Mismatch, + #[error("Dimo 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 user_id: Option, + pub username: String, + 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; +} + +/// Resolves account tokens through the Dimo site account API. +pub(crate) struct SiteAccountResolver { + client: reqwest::Client, +} + +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(), + }) +} + +#[async_trait] +impl AccountResolver for SiteAccountResolver { + async fn resolve(&self, token: &str) -> Result { + let origin = utils::site_origin(); + let response = self + .client + .get(format!("{origin}/api/modelrouter/desktop")) + .bearer_auth(token) + .header("user-agent", "Dimo") + .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 non_empty_id(value: Option<&Value>, key: &str) -> Option { + match value?.get(key)? { + Value::String(raw) => { + let trimmed = raw.trim(); + (!trimmed.is_empty()).then(|| trimmed.to_owned()) + } + Value::Number(num) => Some(num.to_string()), + _ => None, + } +} + +fn identity_from_user(user: Option<&Value>) -> Option { + let username = non_empty_str(user, "username")?.to_owned(); + let user_id = non_empty_id(user, "id"); + let display_name = non_empty_str(user, "displayName") + .map(ToOwned::to_owned) + .unwrap_or_else(|| username.clone()); + Some(AccountIdentity { + user_id, + username, + display_name, + }) +} + +struct HostAccount { + token: Option, + auto_approve: bool, +} + +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 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); + 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 { + token, + auto_approve, + } +} + +fn identities_match(device: &AccountIdentity, owner: &AccountIdentity) -> bool { + match (&device.user_id, &owner.user_id) { + (Some(device_id), Some(owner_id)) => device_id == owner_id, + _ => device.username.eq_ignore_ascii_case(&owner.username), + } +} + +/// Verifies that `device_token` belongs to the account currently signed in on this host and +/// returns 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 { + let host = read_host_account(settings_path).await; + let Some(host_token) = host.token else { + return Err(AccountLinkError::HostSignedOut); + }; + let trimmed_device_token = device_token.trim(); + if trimmed_device_token.is_empty() { + return Err(AccountLinkError::InvalidToken); + } + if trimmed_device_token == host_token { + let identity = resolver.resolve(trimmed_device_token).await?; + return Ok(VerifiedSameAccount { + identity, + auto_approve: host.auto_approve, + }); + } + let (device_res, owner_res) = tokio::join!( + resolver.resolve(trimmed_device_token), + resolver.resolve(&host_token), + ); + let owner = match owner_res { + Ok(owner) => owner, + Err(AccountLinkError::InvalidToken) => return Err(AccountLinkError::HostSignedOut), + Err(error) => return Err(error), + }; + let device = device_res?; + if identities_match(&device, &owner) { + Ok(VerifiedSameAccount { + identity: device, + auto_approve: host.auto_approve, + }) + } 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, &'static str)>); + + #[async_trait] + impl AccountResolver for FakeResolver { + async fn resolve(&self, token: &str) -> Result { + match self.0.get(token) { + Some((user_id, username)) => Ok(AccountIdentity { + user_id: (!user_id.is_empty()).then(|| (*user_id).to_owned()), + username: (*username).to_owned(), + display_name: format!("{username} display"), + }), + None => Err(AccountLinkError::InvalidToken), + } + } + } + + fn resolver() -> FakeResolver { + FakeResolver(HashMap::from([ + ("tok-alice", ("uid-alice", "alice")), + ("tok-alice-2", ("uid-alice", "Alice")), + ("tok-recycled-alice", ("uid-impersonator", "alice")), + ("tok-bob", ("uid-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!({ + "__account_owner_v1": { "username": "alice", "displayName": "Alice" }, + HOST_ACCOUNT_TOKEN_KEY: "tok-alice", + })) + .await; + let verified = verify_same_account( + &dir.path().join("settings.json"), + &resolver(), + "tok-alice-2", + ) + .await + .unwrap(); + assert_eq!(verified.identity.user_id.as_deref(), Some("uid-alice")); + assert_eq!(verified.identity.username, "Alice"); + assert!(verified.auto_approve); + + let manual_dir = settings_with(json!({ + HOST_ACCOUNT_TOKEN_KEY: "tok-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] + async fn rejects_stale_owner_cache_when_host_token_is_missing_or_revoked() { + let missing_token_dir = settings_with(json!({ + "__account_owner_v1": { "username": "alice", "displayName": "Alice" }, + })) + .await; + assert_eq!( + verify_same_account( + &missing_token_dir.path().join("settings.json"), + &resolver(), + "tok-alice-2", + ) + .await, + Err(AccountLinkError::HostSignedOut) + ); + + let revoked_token_dir = settings_with(json!({ + "__account_owner_v1": { "username": "alice", "displayName": "Alice" }, + HOST_ACCOUNT_TOKEN_KEY: "tok-revoked-host", + })) + .await; + assert_eq!( + verify_same_account( + &revoked_token_dir.path().join("settings.json"), + &resolver(), + "tok-alice-2", + ) + .await, + Err(AccountLinkError::HostSignedOut) + ); + } + + #[tokio::test] + async fn rejects_recycled_username_when_immutable_user_id_differs() { + let dir = settings_with(json!({ + HOST_ACCOUNT_TOKEN_KEY: "tok-alice", + })) + .await; + assert_eq!( + verify_same_account( + &dir.path().join("settings.json"), + &resolver(), + "tok-recycled-alice", + ) + .await, + Err(AccountLinkError::Mismatch) + ); + } + + #[tokio::test] + async fn rejects_other_accounts_and_invalid_tokens() { + let dir = settings_with(json!({ + 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 7f528a1f8..8401b66b8 100644 --- a/crates/server/src/auth.rs +++ b/crates/server/src/auth.rs @@ -386,6 +386,8 @@ pub trait ServerAuth: Send + Sync { _host_id: &str, _request: CreateDeviceConnectRequest, _ip_address: Option<&str>, + _account_display_name: Option<&str>, + _auto_approve: bool, ) -> Result { Err(AuthStoreError::PairingUnavailable) } @@ -950,6 +952,8 @@ impl ServerAuth for SqliteServerAuth { host_id: &str, 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 { @@ -982,6 +986,145 @@ impl ServerAuth for SqliteServerAuth { let expires_at = now.saturating_add(180); let host_name = utils::net::local_hostname(); + 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, + }), + }); + } + let existing_pending = if let Some((_, ref canonical_pk)) = parsed_pubkey { sqlx::query( "SELECT id, sas_code @@ -1014,12 +1157,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?; @@ -1054,8 +1199,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) @@ -1065,6 +1210,7 @@ impl ServerAuth for SqliteServerAuth { .bind(&sas_code) .bind(now) .bind(expires_at) + .bind(account_display_name) .execute(&self.pool) .await?; @@ -1151,13 +1297,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, public_key_ed25519, sas_code, created_at_unix, expires_at_unix - 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.public_key_ed25519, + 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?; @@ -1169,6 +1328,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")?, @@ -1186,6 +1356,9 @@ 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")?, + status, + issued_device_id, }); } Ok(items) @@ -1314,11 +1487,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?; @@ -1358,6 +1533,54 @@ impl ServerAuth for SqliteServerAuth { } impl SqliteServerAuth { + /// Revokes every device admitted because it shares the Dimo 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, @@ -1801,12 +2024,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 { @@ -2003,4 +2228,183 @@ 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"), + false, + ) + .await + .expect("account request"); + auth.create_connect_request("host-1", request("Bob iPhone"), None, None, false) + .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)); + } + + #[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()); + } + + #[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/crates/server/src/lib.rs b/crates/server/src/lib.rs index 83f90f48d..5414db826 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -1,5 +1,6 @@ //! Headless Dimo 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 0653d3e45..61093875b 100644 --- a/crates/server/src/runtime.rs +++ b/crates/server/src/runtime.rs @@ -946,9 +946,33 @@ async fn create_connect_request( Json(request): Json, ) -> Response { let ip_address = extract_client_ip(&headers, state.config.listen_addr); + let (account_display_name, auto_approve) = 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(verified) => (Some(verified.identity.display_name), verified.auto_approve), + Err(error) => return account_link_error_response(&error), + }, + None => (None, false), + }; 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(), + auto_approve, + ) .await { Ok(response) => (StatusCode::CREATED, Json(response)).into_response(), @@ -1162,6 +1186,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 62f60903a..2d8d18d9f 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"), )) @@ -728,6 +729,7 @@ async fn unauthenticated_connect_request_cannot_revoke_mobile_or_probe_device_na public_key_ed25519: Some(atk_pub_b64.clone()), session_nonce: Some("atk-nonce".to_owned()), replace_existing_mobile: true, + account_token: None, }) .expect("serialize"), )) diff --git a/frontend/src/components/layout/MobileDeviceConnectBanner.test.tsx b/frontend/src/components/layout/MobileDeviceConnectBanner.test.tsx index 3fc307836..f9b0385d7 100644 --- a/frontend/src/components/layout/MobileDeviceConnectBanner.test.tsx +++ b/frontend/src/components/layout/MobileDeviceConnectBanner.test.tsx @@ -27,11 +27,16 @@ vi.mock('@/lib/api/settingsWindow', () => ({ 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[]) => @@ -39,6 +44,7 @@ vi.mock('@/lib/api/config', () => ({ respondConnectRequest: (...args: unknown[]) => respondConnectRequestMock(...args), listDevices: (...args: unknown[]) => listDevicesMock(...args), + revokeDevice: (...args: unknown[]) => revokeDeviceMock(...args), }, })); @@ -57,6 +63,7 @@ describe('MobileDeviceConnectBanner', () => { listConnectRequestsMock.mockReset(); respondConnectRequestMock.mockReset(); listDevicesMock.mockReset(); + revokeDeviceMock.mockReset(); listDevicesMock.mockResolvedValue([]); openSettingsMock.mockClear(); localStorage.clear(); @@ -88,6 +95,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); @@ -97,7 +105,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: '连接' })); @@ -109,6 +117,37 @@ describe('MobileDeviceConnectBanner', () => { ).toBeInTheDocument(); }); + 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', + 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', + status: 'approved', + issued_device_id: 'dev-123', + }, + ]); + revokeDeviceMock.mockResolvedValue(undefined); + + render(); + + 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'); + }); + }); + it('shows an offline paired phone once, then stays quiet for the cooldown', async () => { vi.useFakeTimers(); vi.setSystemTime(new Date('2026-11-18T12:00:00Z')); diff --git a/frontend/src/components/layout/MobileDeviceConnectBanner.tsx b/frontend/src/components/layout/MobileDeviceConnectBanner.tsx index 2c6b89cc7..e4eb43aac 100644 --- a/frontend/src/components/layout/MobileDeviceConnectBanner.tsx +++ b/frontend/src/components/layout/MobileDeviceConnectBanner.tsx @@ -1,19 +1,23 @@ import { Check, Smartphone, X } from 'lucide-react'; import { useCallback, useEffect, useRef, useState } from 'react'; -import { settingsWindowApi } from '@/lib/api/settingsWindow'; import { type HostPairedDevice, type PendingDeviceConnectRequest, webServiceApi, } from '@/lib/api/config'; +import { settingsWindowApi } from '@/lib/api/settingsWindow'; import { isLocalDesktopHost } from '@/lib/desktopShell'; +import { writeDesktopSharedPreferenceSection } from '@/lib/frontendPreferences'; import { readLocalStorage, writeLocalStorage } from '@/lib/safeStorage'; -const POLL_INTERVAL_MS = 2500; -const CONNECTED_FEEDBACK_MS = 2400; +const POLL_INTERVAL_MS = 1800; +const CONNECTED_FEEDBACK_MS = 3000; +const AUTO_CONNECT_BANNER_MS = 5000; export const CONNECT_REQUESTS_CHANGED_EVENT = 'dimo:connect-requests-changed'; export const REMOTE_AUTO_CONNECT_KEY = 'dimo:remote-auto-connect'; +export const HOST_SAME_ACCOUNT_AUTO_CONNECT_KEY = + '__same_account_auto_connect_v1'; export const MOBILE_IDLE_REMINDER_KEY = 'dimo:mobile-idle-reminder'; /** How long a shown or dismissed offline reminder stays quiet for that device. */ export const MOBILE_IDLE_REMINDER_COOLDOWN_MS = 24 * 60 * 60 * 1000; @@ -25,11 +29,11 @@ export const MOBILE_IDLE_REMINDER_COOLDOWN_MS = 24 * 60 * 60 * 1000; export const MOBILE_IDLE_REMINDER_ARM_MS = 1000; 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; } } @@ -40,6 +44,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 @@ -142,17 +150,25 @@ function selectIdleReminderDevice( ); } +interface ConnectedMobileNotice { + deviceName: string; + sasCode?: string | null; + accountDisplayName?: string | null; + issuedDeviceId?: string | null; +} + export function MobileDeviceConnectBanner() { const [requests, setRequests] = useState([]); const [busyId, setBusyId] = useState(null); - const [connectedDeviceName, setConnectedDeviceName] = useState( - null - ); + const [revokingDeviceId, setRevokingDeviceId] = useState(null); + const [connectedNotice, setConnectedNotice] = + useState(null); const [idleDevice, setIdleDevice] = useState(null); const sessionStartMsRef = useRef(Date.now()); const shownIdleDeviceIdRef = useRef(null); const clearFeedbackTimerRef = useRef(null); const respondedIdsRef = useRef>(new Set()); + const seenAutoApprovedIdsRef = useRef>(new Set()); const dismissIdleReminder = useCallback(() => { const deviceId = shownIdleDeviceIdRef.current; @@ -163,6 +179,21 @@ export function MobileDeviceConnectBanner() { setIdleDevice(null); }, []); + const showConnectedNotice = useCallback( + (notice: ConnectedMobileNotice, durationMs: number) => { + dismissIdleReminder(); + setConnectedNotice(notice); + if (clearFeedbackTimerRef.current !== null) { + window.clearTimeout(clearFeedbackTimerRef.current); + } + clearFeedbackTimerRef.current = window.setTimeout(() => { + setConnectedNotice(null); + clearFeedbackTimerRef.current = null; + }, durationMs); + }, + [dismissIdleReminder] + ); + const handleRespond = useCallback( async (item: PendingDeviceConnectRequest, approve: boolean) => { setBusyId(item.request_id); @@ -174,15 +205,14 @@ export function MobileDeviceConnectBanner() { ); notifyConnectRequestsChanged(); if (approve) { - dismissIdleReminder(); - setConnectedDeviceName(item.device_name); - if (clearFeedbackTimerRef.current !== null) { - window.clearTimeout(clearFeedbackTimerRef.current); - } - clearFeedbackTimerRef.current = window.setTimeout(() => { - setConnectedDeviceName(null); - clearFeedbackTimerRef.current = null; - }, CONNECTED_FEEDBACK_MS); + showConnectedNotice( + { + deviceName: item.device_name, + sasCode: item.sas_code, + accountDisplayName: item.account_display_name ?? null, + }, + CONNECTED_FEEDBACK_MS + ); } } catch (err) { console.warn('Failed to respond to mobile connect request:', err); @@ -190,9 +220,26 @@ export function MobileDeviceConnectBanner() { setBusyId(null); } }, - [dismissIdleReminder] + [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; @@ -215,11 +262,30 @@ export function MobileDeviceConnectBanner() { current?.device_id === nextIdle?.device_id ? current : nextIdle ); - 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 with a matching Ed25519 public key is requesting connection, auto-approve. // Never auto-approve based on device_name alone or for non-mobile client_kind (which grants Workstation scopes). @@ -251,7 +317,7 @@ export function MobileDeviceConnectBanner() { } catch { // Ignore in non-host windows or before backend is ready } - }, [handleRespond]); + }, [handleRespond, showConnectedNotice]); useEffect(() => { void refreshRequests(); @@ -284,7 +350,7 @@ export function MobileDeviceConnectBanner() { // it has been on screen briefly, or the user dismisses it, that device stays // silent until the cooldown ends. const active = requests[0] ?? null; - if (!active && !connectedDeviceName && !idleDevice) { + if (!active && !connectedNotice && !idleDevice) { return null; } @@ -298,14 +364,41 @@ 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 ? ( <> @@ -319,11 +412,16 @@ export function MobileDeviceConnectBanner() { 发现可用移动设备「{active.device_name}」 + {active.account_display_name ? ( + + 同账号 · {active.account_display_name} + + ) : null} - 核对码 {active.sas_code} + 连接码 {active.sas_code} {requests.length > 1 ? ( diff --git a/frontend/src/features/model-router/account.ts b/frontend/src/features/model-router/account.ts index 3aaef7e7e..81ab0276c 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'; @@ -481,6 +482,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('dimo:host-tunnel-updated')); diff --git a/frontend/src/lib/api/config.ts b/frontend/src/lib/api/config.ts index a9f25af70..7685eebae 100644 --- a/frontend/src/lib/api/config.ts +++ b/frontend/src/lib/api/config.ts @@ -468,6 +468,10 @@ export interface PendingDeviceConnectRequest { sas_code: string; created_at: string; expires_at: string; + /** Present when the host verified the request comes from its own Dimo account. */ + account_display_name?: string | null; + status?: 'pending' | 'approved' | 'rejected' | 'expired'; + issued_device_id?: string | null; } export interface PortProbeResult { @@ -780,6 +784,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/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 a38b6ad65..8a11e294b 100644 --- a/frontend/src/pages/settings/WebServiceSettings.tsx +++ b/frontend/src/pages/settings/WebServiceSettings.tsx @@ -563,10 +563,11 @@ export function WebServiceSettings({

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

RelaySyncMode { RelaySyncMode::Idle } +fn sha256_hex(input: &str) -> String { + use sha2::{Digest, Sha256}; + let mut hasher = Sha256::new(); + hasher.update(input.as_bytes()); + let digest = hasher.finalize(); + let mut out = String::with_capacity(64); + for byte in digest { + use std::fmt::Write; + let _ = write!(&mut out, "{byte:02x}"); + } + out +} + +async fn post_relay_beacon_topics( + relay_host: &str, + relay_port: u16, + topics: &[&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) { + (format!("https://{relay_host}/v1/beacon"), 443u16) + } else { + ( + format!("http://{relay_host}:{relay_port}/v1/beacon"), + relay_port, + ) + }; + + let host_owned = relay_host.to_string(); + let resolved = tokio::task::spawn_blocking(move || { + utils::net::resolve_host_ipv4_direct(&host_owned, target_port) + }) + .await + .ok() + .flatten(); + + let mut builder = reqwest::Client::builder() + .timeout(Duration::from_secs(4)) + .no_proxy(); + if let Some(addr) = resolved { + builder = builder.resolve(relay_host, addr); + } + if let Ok(client) = builder.build() { + for topic in topics { + let _ = client + .post(format!("{base_url}/{topic}")) + .json(payload) + .send() + .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 Ok(store) = load_store().await else { + return; + }; + let Some((relay_host, relay_port, origin)) = (match decide_relay_sync_mode(&store) { + RelaySyncMode::OfficialQuickTunnel => valid_account_lease(&store) + .zip(default_official_quick_origin(&store)) + .map(|(lease, origin)| { + ( + lease.relay_host.trim().to_string(), + lease.relay_port, + origin, + ) + }), + RelaySyncMode::SavedCustomRelay { host, port, .. } => store + .saved + .iter() + .find(|item| { + Some(item.id.as_str()) == store.active_id.as_deref() && item.kind == "relay" + }) + .map(|custom| (host.trim().to_string(), port, custom.origin.clone())), + RelaySyncMode::PendingCustom { .. } | RelaySyncMode::Idle => None, + }) else { + return; + }; + 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_topics(&relay_host, relay_port, &[topic.as_str()], &payload).await; +} + pub async fn sync_relay() { let store = load_store().await.unwrap_or_default(); publish_browser_origins(&store); diff --git a/src-tauri/src/commands/web_service.rs b/src-tauri/src/commands/web_service.rs index 99f72134e..874f9ff3f 100644 --- a/src-tauri/src/commands/web_service.rs +++ b/src-tauri/src/commands/web_service.rs @@ -700,9 +700,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] @@ -777,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 Dimo 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() diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 411902112..f834c0f81 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -805,6 +805,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,