diff --git a/client/src-tauri/src/config.rs b/client/src-tauri/src/config.rs index 8cdc7a75..3f641d02 100644 --- a/client/src-tauri/src/config.rs +++ b/client/src-tauri/src/config.rs @@ -35,7 +35,7 @@ use airhand_link::LinkConfig; use airhand_link::net::{MemoryTrust, Trust, TrustStore, format_fingerprint, parse_fingerprint}; use airhand_link::secure::Identity; use airhand_proto::signal::Reclaim; -use anyhow::{Result, bail}; +use anyhow::{Context, Result, bail}; use serde::{Deserialize, Serialize}; use tokio::sync::watch; use toml_edit::{DocumentMut, Item}; @@ -900,9 +900,14 @@ fn edit(f: impl FnOnce(&mut DocumentMut) -> Result<()>) -> Result<()> { } fn edit_at(path: &Path, f: impl FnOnce(&mut DocumentMut) -> Result<()>) -> Result<()> { + edit_if_writable(path, f).map(|_| ()) +} + +/// 检查配置写入是否已暂停,并返回是否真的写入了。 +fn edit_if_writable(path: &Path, f: impl FnOnce(&mut DocumentMut) -> Result<()>) -> Result { let mut last = last(); if FROZEN.load(std::sync::atomic::Ordering::Acquire) { - return Ok(()); + return Ok(false); } let mut doc = match std::fs::read_to_string(path) { // 用户写坏了的文件不覆盖:这次就不保存了 @@ -916,7 +921,7 @@ fn edit_at(path: &Path, f: impl FnOnce(&mut DocumentMut) -> Result<()>) -> Resul let text = doc.to_string(); write(path, &text)?; *last = Some(text); - Ok(()) + Ok(true) } /// 先写临时文件再改名:写到一半断电也不会把配置文件弄坏。目录不存在时创建(macOS / Linux 第一次运行、 @@ -1367,10 +1372,15 @@ fn autostart_note() -> String { /// 保存控制台的"我的设备":整个列表换成 `list`([`crate::devices::for_file`] 整理过的,`code` 已经加密) pub fn save_devices(list: &[crate::devices::Device]) -> Result<()> { - edit(|doc| { - put_devices(doc, list); - Ok(()) - }) + let path = path().context("the configuration file path is unavailable")?; + anyhow::ensure!( + edit_if_writable(&path, |doc| { + put_devices(doc, list); + Ok(()) + })?, + "configuration writes are paused" + ); + Ok(()) } fn put_devices(doc: &mut DocumentMut, list: &[crate::devices::Device]) { @@ -2026,6 +2036,7 @@ mod tests { quality: None, mouse: None, swap_ctrl_command: false, + auto_privacy: false, host_key: None, } } @@ -2315,7 +2326,7 @@ mod tests { save_code(Some(code)).unwrap(); let mut d = device("482913"); save_devices(&crate::devices::for_file(vec![d.clone()]).unwrap()).unwrap(); - assert_eq!(crate::devices::load(), vec![d.clone()]); + assert_eq!(crate::devices::load().unwrap(), vec![d.clone()]); assert_eq!(parse(&read_text().unwrap()).unwrap().code(), Some(code)); // Windows:文件里没有明文的控制码 #[cfg(windows)] @@ -2329,7 +2340,7 @@ mod tests { let text = read_text().unwrap(); assert!(text.starts_with("# Airhand")); assert_eq!(parse(&text).unwrap().code(), Some(code)); - assert_eq!(crate::devices::load(), vec![d.clone()]); + assert_eq!(crate::devices::load().unwrap(), vec![d.clone()]); // 手动给设备起了个名字,然后整个目录被删掉 let edited = text.replace( @@ -2344,7 +2355,7 @@ mod tests { }); std::fs::remove_dir_all(&dir).unwrap(); wait_for("the directory to be recreated", &|| file.exists()); - assert_eq!(crate::devices::load(), vec![d]); + assert_eq!(crate::devices::load().unwrap(), vec![d]); assert_eq!(parse(&read_text().unwrap()).unwrap().code(), Some(code)); #[cfg(unix)] { @@ -2357,6 +2368,21 @@ mod tests { std::fs::remove_dir_all(&root).unwrap(); } + #[test] + fn devices_distinguish_empty_config_from_read_failure() { + let root = tempfile::tempdir().unwrap(); + let file = root.path().join(FILE_NAME); + TEST_PATH.with(|p| *p.borrow_mut() = Some(file.clone())); + assert!(crate::devices::load().is_err()); + std::fs::write(&file, "").unwrap(); + assert!(crate::devices::load().unwrap().is_empty()); + + std::fs::write(&file, "[[").unwrap(); + assert!(crate::devices::load().is_err()); + assert!(save_devices(&[]).is_err()); + assert_eq!(std::fs::read_to_string(file).unwrap(), "[["); + } + /// 服务器地址:host:port,端口 1~65535,IPv6 写在方括号里(和控制台的 validServer、Android 的设置一样) #[test] fn server_address_rules() { diff --git a/client/src-tauri/src/devices.rs b/client/src-tauri/src/devices.rs index 486e859c..23e32b39 100644 --- a/client/src-tauri/src/devices.rs +++ b/client/src-tauri/src/devices.rs @@ -15,6 +15,7 @@ //! //! `mouse` 是上次用的鼠标模式(控制台的"桌面" / "游戏",没有就是"自动")。 //! `swap_ctrl_command = true`:操作这台 Mac 时互换 Ctrl 和 Command;默认关闭。 +//! `auto_privacy = true`:连接这台设备时请求防窥模式;默认关闭。 //! //! `host_key` 是那台电脑的端到端加密公钥(第一次连上时记下,见 `airhand_link::controller` 的"端到端加密"): //! 之后只认它,对不上就警告。是公钥,不用加密。 @@ -28,12 +29,11 @@ use airhand_proto::session::{Codec, QualitySettings}; use airhand_proto::signal::ResumeToken; -use anyhow::Result; +use anyhow::{Context, Result}; use base64::Engine; use base64::engine::general_purpose::STANDARD; use serde::{Deserialize, Serialize}; use toml_edit::{Datetime, InlineTable, Item, Table, Value}; -use tracing::warn; /// 每个账户最多保存多少台(控制台也按这个数截断) pub const MAX: usize = 50; @@ -74,6 +74,8 @@ pub struct Device { pub mouse: Option, #[serde(default)] pub swap_ctrl_command: bool, + #[serde(default)] + pub auto_privacy: bool, } /// 认识的鼠标模式(自动是默认,不记) @@ -119,17 +121,19 @@ fn host_key(s: &str) -> Option { // ───────────────────────────── 读 ───────────────────────────── -/// 配置文件里本账户的设备(文件不存在、没有设备时为空) -pub fn load() -> Vec { - let Some(text) = crate::config::read_text() else { - return Vec::new(); - }; - let Ok(doc) = text.parse::() else { - warn!("config.toml isn't valid TOML, can't read the saved devices"); - return Vec::new(); - }; +/// 配置文件里本账户的设备。启动代码会先创建配置文件;读不到时由控制台提示重试。 +pub fn load() -> Result> { + let doc = read_device_document()?; let list = entries(&doc).into_iter().filter_map(open).collect(); - normalize(list) + Ok(normalize(list)) +} + +fn read_device_document() -> Result { + let path = crate::config::path().context("the configuration file path is unavailable")?; + let text = + std::fs::read_to_string(&path).with_context(|| format!("can't read {}", path.display()))?; + text.parse() + .with_context(|| format!("{} isn't valid TOML", path.display())) } /// 文件里的所有项(`code` 还没解密) @@ -177,6 +181,7 @@ fn from_table(t: &Table) -> Option { .and_then(mouse_mode) .map(Into::into), swap_ctrl_command: t.get("swap_ctrl_command").and_then(Item::as_bool) == Some(true), + auto_privacy: t.get("auto_privacy").and_then(Item::as_bool) == Some(true), host_key: t.get("host_key").and_then(Item::as_str).and_then(host_key), }) } @@ -222,9 +227,8 @@ pub fn for_file(mine: Vec) -> Result> { } // 别的账户保存的(本账户解不开)原样保留;本账户的以控制台发来的为准(删掉的就不要了) #[cfg(windows)] - if let Some(doc) = - crate::config::read_text().and_then(|t| t.parse::().ok()) { + let doc = read_device_document()?; out.extend( entries(&doc) .into_iter() @@ -273,6 +277,9 @@ pub fn to_table(d: &Device) -> Option { if d.swap_ctrl_command { t["swap_ctrl_command"] = toml_edit::value(true); } + if d.auto_privacy { + t["auto_privacy"] = toml_edit::value(true); + } if let Some(r) = &d.resume { t["resume"] = toml_edit::value(STANDARD.encode(r)); } @@ -368,6 +375,7 @@ mod tests { }), mouse: Some("game".into()), swap_ctrl_command: true, + auto_privacy: true, host_key: Some("ab".repeat(32)), } } @@ -402,14 +410,17 @@ mod tests { quality: None, mouse: None, swap_ctrl_command: false, + auto_privacy: false, last_used: 0, host_key: None, ..d.clone() }; let bare_table = to_table(&bare).unwrap(); assert!(!bare_table.contains_key("swap_ctrl_command")); + assert!(!bare_table.contains_key("auto_privacy")); assert_eq!(from_table(&bare_table), Some(bare)); assert!(t.to_string().contains("mouse = \"game\"")); + assert!(t.to_string().contains("auto_privacy = true")); // 自动(默认)和不认识的鼠标模式不写进文件,读回来是自动 for m in ["auto", "warp"] { let other = Device { diff --git a/client/src-tauri/src/lib.rs b/client/src-tauri/src/lib.rs index 2cb68b0f..181d6805 100644 --- a/client/src-tauri/src/lib.rs +++ b/client/src-tauri/src/lib.rs @@ -620,10 +620,11 @@ fn app_info() -> AppInfo { /// 我的设备(配置文件里本账户的) #[tauri::command] -async fn devices_load() -> Vec { +async fn devices_load() -> Result, Problem> { tauri::async_runtime::spawn_blocking(devices::load) .await - .unwrap_or_default() + .map_err(Problem::failed)? + .map_err(|e| Problem::failed(format!("{e:#}"))) } /// 保存我的设备(控制台传来整个列表) @@ -640,15 +641,24 @@ async fn devices_save( // Windows 安装版:配置文件在安装目录里,由服务里的被控端维护(托盘没有写权限),经命名管道交给它写 #[cfg(windows)] if state.service_mode { - let connected = state.hub.borrow().service.is_some_and(|s| s.connected); - let sv = state.services.lock().unwrap(); - return match &sv.host { - Some(Hosting::Service(link)) if connected => { - link.send(winsvc::ipc::ToAgent::SaveDevices { devices: list }); - Ok(()) + let saved = { + let connected = state.hub.borrow().service.is_some_and(|s| s.connected); + let sv = state.services.lock().unwrap(); + match &sv.host { + Some(Hosting::Service(link)) if connected => { + link.save_devices(list).map_err(Problem::failed)? + } + _ => { + return Err(Problem::failed( + "the Airhand service isn't reachable from this session", + )); + } } + }; + return match tokio::time::timeout(Duration::from_secs(5), saved).await { + Ok(Ok(result)) => result.map_err(Problem::failed), _ => Err(Problem::failed( - "the Airhand service isn't reachable from this session", + "the Airhand service didn't confirm the device settings were saved", )), }; } diff --git a/client/src-tauri/src/winsvc/ipc.rs b/client/src-tauri/src/winsvc/ipc.rs index bc82cd9b..8446544f 100644 --- a/client/src-tauri/src/winsvc/ipc.rs +++ b/client/src-tauri/src/winsvc/ipc.rs @@ -4,9 +4,10 @@ //! 被控端还会核对连上来的进程是不是在同一个会话里; //! * 只有交互登录的用户(和 SYSTEM、管理员)能连接,而且不能另开同名管道冒充被控端(见 [`PIPE_SDDL`]); //! 托盘还会核对管道的所有者是 SYSTEM(或管理员),普通用户的程序抢先开了同名管道也骗不了托盘; -//! * 被控端 → 托盘:[`AgentStatus`],连上时发一次,之后有变化就发; +//! * 被控端 → 托盘:[`AgentStatus`](连上时、状态变了时),以及配置保存的结果; //! * 托盘 → 被控端:[`ToAgent`]。 +use std::collections::HashMap; use std::sync::Arc; use std::time::Duration; @@ -15,7 +16,7 @@ use serde::{Deserialize, Serialize}; use tauri::async_runtime::JoinHandle; use tokio::io::{AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader}; use tokio::net::windows::named_pipe::{NamedPipeClient, NamedPipeServer, ServerOptions}; -use tokio::sync::{mpsc, watch}; +use tokio::sync::{mpsc, oneshot, watch}; use tracing::{debug, info, warn}; use windows::Win32::Foundation::{CloseHandle, ERROR_PIPE_BUSY, HANDLE}; use windows::Win32::Foundation::{HLOCAL, LocalFree}; @@ -69,6 +70,18 @@ pub struct AgentStatus { pub server: Option, } +pub type DeviceSaveResult = std::result::Result<(), String>; + +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +enum FromAgent { + Status(AgentStatus), + DevicesSaved { + request: u64, + result: DeviceSaveResult, + }, +} + /// 托盘 → 被控端 #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] @@ -82,6 +95,8 @@ pub enum ToAgent { /// 已经由托盘整理好、`code` 用那个用户的 DPAPI 加密过(见 [`crate::devices::for_file`]) SaveDevices { devices: Vec, + #[serde(default)] + request: Option, }, /// 换一个配对码(暂停了的配对随之恢复) NewPairingCode, @@ -252,7 +267,11 @@ async fn serve_tray(pipe: NamedPipeServer, hub: StatusHub, agent: Agent) -> Resu line = lines.next_line() => { let Some(line) = line? else { return Ok(()) }; match serde_json::from_str::(&line) { - Ok(msg) => handle(msg, &agent, &hub).await, + Ok(msg) => { + if let Some(reply) = handle(msg, &agent, &hub).await { + send_line(&mut w, &reply).await?; + } + } Err(e) => warn!("invalid message from the tray: {e}"), } } @@ -260,7 +279,7 @@ async fn serve_tray(pipe: NamedPipeServer, hub: StatusHub, agent: Agent) -> Resu } } -async fn handle(msg: ToAgent, agent: &Agent, hub: &StatusHub) { +async fn handle(msg: ToAgent, agent: &Agent, hub: &StatusHub) -> Option { let (cmds, autostart) = (&agent.cmds, &agent.autostart); match msg { ToAgent::KickAll => { @@ -346,28 +365,41 @@ async fn handle(msg: ToAgent, agent: &Agent, hub: &StatusHub) { Err(e) => warn!("can't change autostart: {e}"), } } - ToAgent::SaveDevices { devices } => { + ToAgent::SaveDevices { devices, request } => { // 只改 [[device]],每一项写之前再检查一遍(见 devices::to_table) let n = devices.len(); let r = tokio::task::spawn_blocking(move || crate::config::save_devices(&devices)).await; - match r { - Ok(Ok(())) => debug!(n, "saved the devices"), - Ok(Err(e)) => warn!("can't save the devices: {e:#}"), + let result = match r { + Ok(result) => result.map_err(|e| format!("{e:#}")), + Err(e) => Err(e.to_string()), + }; + match &result { + Ok(()) => debug!(n, "saved the devices"), Err(e) => warn!("can't save the devices: {e}"), } + return request.map(|request| FromAgent::DevicesSaved { request, result }); } } + None } // ───────────────────────────── 托盘一侧 ───────────────────────────── /// 托盘到服务里被控端的连接:断了自动重连,状态写进 [`AppStatus`](crate::status::AppStatus) pub struct AgentLink { - tx: mpsc::UnboundedSender, + tx: mpsc::UnboundedSender, task: JoinHandle<()>, } +enum TrayCommand { + Send(ToAgent), + SaveDevices { + devices: Vec, + reply: oneshot::Sender, + }, +} + impl AgentLink { /// `on_stopped`:服务运行过、后来停止了(托盘"退出"、卸载、升级)时调用,托盘随之退出 pub fn start(hub: StatusHub, on_stopped: impl FnOnce() + Send + 'static) -> Self { @@ -378,7 +410,19 @@ impl AgentLink { /// 发给被控端(没连上时丢弃) pub fn send(&self, msg: ToAgent) { - let _ = self.tx.send(msg); + let _ = self.tx.send(TrayCommand::Send(msg)); + } + + /// 返回保存结果的通道;管道断开或命令被丢弃时,接收端也会关闭 + pub fn save_devices( + &self, + devices: Vec, + ) -> Result> { + let (tx, rx) = oneshot::channel(); + self.tx + .send(TrayCommand::SaveDevices { devices, reply: tx }) + .map_err(|_| anyhow::anyhow!("the Airhand service command queue is closed"))?; + Ok(rx) } } @@ -390,7 +434,7 @@ impl Drop for AgentLink { async fn run( hub: StatusHub, - mut rx: mpsc::UnboundedReceiver, + mut rx: mpsc::UnboundedReceiver, on_stopped: impl FnOnce() + Send + 'static, ) { let name = pipe_name(my_session()); @@ -421,8 +465,8 @@ async fn run( // 断开期间的命令作废,选的界面语言、更新的设置除外(只留最后一次) while let Ok(msg) = rx.try_recv() { match msg { - ToAgent::SetLanguage { .. } => lang = Some(msg), - ToAgent::SetUpdate { .. } => update = Some(msg), + TrayCommand::Send(msg @ ToAgent::SetLanguage { .. }) => lang = Some(msg), + TrayCommand::Send(msg @ ToAgent::SetUpdate { .. }) => update = Some(msg), _ => {} } } @@ -508,12 +552,14 @@ pub(super) fn open_pipe(name: &str, check_owner: bool) -> std::io::Result, + rx: &mut mpsc::UnboundedReceiver, seen_running: &mut bool, first: [Option; 2], ) -> Result<()> { let (r, mut w) = tokio::io::split(pipe); let mut lines = BufReader::new(r).lines(); + let mut pending: HashMap> = HashMap::new(); + let mut next_request = 0; for msg in first.into_iter().flatten() { send_line(&mut w, &msg).await?; } @@ -521,7 +567,15 @@ async fn talk( tokio::select! { line = lines.next_line() => { let Some(line) = line? else { return Ok(()) }; - let st: AgentStatus = serde_json::from_str(&line)?; + let st = match serde_json::from_str(&line)? { + FromAgent::Status(st) => st, + FromAgent::DevicesSaved { request, result } => { + if let Some(reply) = pending.remove(&request) { + let _ = reply.send(result); + } + continue; + } + }; *seen_running = true; // 控制台跟着被控端用同一个服务器(控制台里改了服务器设置时,被控端换好了才到这里) if let Some(server) = &st.server { @@ -538,8 +592,21 @@ async fn talk( }); } msg = rx.recv() => { - let Some(msg) = msg else { return Ok(()) }; - send_line(&mut w, &msg).await?; + match msg { + Some(TrayCommand::Send(msg)) => send_line(&mut w, &msg).await?, + Some(TrayCommand::SaveDevices { devices, reply }) => { + if reply.is_closed() { + continue; + } + let request = next_request; + next_request += 1; + let msg = ToAgent::SaveDevices { devices, request: Some(request) }; + send_line(&mut w, &msg).await?; + pending.retain(|_, reply| !reply.is_closed()); + pending.insert(request, reply); + } + None => return Ok(()), + } } } } @@ -629,6 +696,29 @@ mod tests { assert_eq!(changed.server, "relay.example.net:4433"); assert_eq!(changed.fingerprint, "ab".repeat(32)); assert_eq!(current(), changed); + + // 测试的服务线程没有配置文件路径:把真实的写入错误回给发出请求的托盘 + send_line( + &mut w, + &ToAgent::SaveDevices { + devices: Vec::new(), + request: Some(7), + }, + ) + .await + .unwrap(); + let line = tokio::time::timeout(Duration::from_secs(5), lines.next_line()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert!(matches!( + serde_json::from_str::(&line).unwrap(), + FromAgent::DevicesSaved { + request: 7, + result: Err(_) + } + )); crate::config::apply_server(&before); } } diff --git a/client/src/components/ConnectView.tsx b/client/src/components/ConnectView.tsx index 400cff72..b260c667 100644 --- a/client/src/components/ConnectView.tsx +++ b/client/src/components/ConnectView.tsx @@ -2,19 +2,29 @@ // // 输入的内容放在 store 里(Draft),切到别的标签再回来时还在。 import { useEffect, useRef, useState } from "react"; -import type { SavedDevice } from "../lib/api"; -import { fmtCode, forgetDevice, openSession, openTerminal, renameDevice, resetDraft, restoreDevice } from "../lib/actions"; -import { deviceTitle, matchDevice, relativeTime } from "../lib/devices"; +import { api, type SavedDevice } from "../lib/api"; +import { + fmtCode, + forgetDevice, + loadDevices, + openSession, + openTerminal, + renameDevice, + resetDraft, + restoreDevice, + setDeviceAutoPrivacy, +} from "../lib/actions"; +import { canAutoPrivacy, deviceTitle, matchDevice, relativeTime } from "../lib/devices"; import { getLang, useT } from "../lib/i18n"; import { problemText, sessionStateText } from "../lib/messages"; import { bestCodec } from "../lib/codec"; import { CODEC_LABEL, PRESETS, matchPreset, presetDesc, presetName, presetSettings } from "../lib/presets"; import type { RemoteSession } from "../lib/session"; import { isDesktop, store, useSession, useStore, type Draft } from "../lib/store"; +import { IconBolt, IconClose, IconMonitor, IconPencil, IconSearch, IconShield, IconShieldOff, IconTerminal, IconWarn } from "./Icons"; /** 这些问题要用户输入配对码(对方的身份变了也是:重新配对才认新的身份) */ const PAIRING_PROBLEMS = new Set(["pairingRequired", "pairingFailed", "pairingUnavailable", "hostKeyChanged"]); -import { IconBolt, IconClose, IconMonitor, IconPencil, IconSearch, IconTerminal, IconWarn } from "./Icons"; export function ConnectView() { const t = useT(); @@ -23,6 +33,7 @@ export function ConnectView() { const serverProblem = useStore((s) => s.serverProblem); const decoders = useStore((s) => s.decoders); const devices = useStore((s) => s.devices); + const deviceStorage = useStore((s) => s.deviceStorage); const inputs = useRef<(HTMLInputElement | null)[]>([]); // 新建连接标签总是有的时候才显示这一页;万一没有(例如状态不一致),补一个 @@ -51,6 +62,8 @@ export function ConnectView() { const code = digits.join(""); const ready = /^\d{6}$/.test(code) && code[0] !== "0"; const online = server.state === "connected"; + const devicesReady = api.kind === "web" || deviceStorage === "ready"; + const canConnect = ready && !busy && online && devicesReady; // 输入的是我的设备里的:告诉用户是哪台 const known = ready ? devices.find((d) => d.code === code) : undefined; @@ -79,13 +92,13 @@ export function ConnectView() { }; const connect = () => { - if (!ready || busy || !online) return; + if (!canConnect) return; void openSession(code, presetSettings(preset, codec), { pairing: pairingReady ? pairing : null }); }; /** 只开终端(不传画面,见 lib/terminal.ts) */ const connectTerminal = () => { - if (!ready || busy || !online) return; + if (!canConnect) return; void openTerminal(code, { pairing: pairingReady ? pairing : null }); }; @@ -232,16 +245,28 @@ export function ConnectView() { )} + {deviceStorage === "failed" && ( +
+ + {t("devices.loadFailed")} + +
+ )} + {!devicesReady && deviceStorage === "loading" && ( +

{t("devices.loading")}

+ )}
- {/* 只想跑命令行程序:不传画面,开一个终端 */}
- void openTerminal(d.code)} disabled={busy || !online} /> + void openTerminal(d.code)} disabled={busy || !online || !devicesReady} /> ); @@ -272,7 +297,8 @@ function MyDevices({ }) { const t = useT(); const devices = useStore((s) => s.devices); - const saved = useStore((s) => s.devicesSaved); + const saved = useStore((s) => s.deviceStorage === "ready"); + const privacySaveError = useStore((s) => s.devices.some((d) => s.autoPrivacyWrites.get(d.code) === "failed")); const sessions = useStore((s) => s.sessions); const [query, setQuery] = useState(""); const [editing, setEditing] = useState(null); @@ -330,6 +356,12 @@ function MyDevices({ )} + {privacySaveError && ( +
+ + {t("devices.privacySaveFailed")} +
+ )}
{shown.map((d) => ( @@ -341,6 +373,11 @@ function MyDevices({ editing={editing === d.code} onOpen={() => onOpen(d)} onTerminal={() => onTerminal(d)} + onTogglePrivacy={() => { + void setDeviceAutoPrivacy(d.code, !d.autoPrivacy).catch((e) => { + console.warn("can't save automatic privacy mode", e); + }); + }} onEdit={(on) => setEditing(on ? d.code : null)} onForget={() => { forgetDevice(d.code); @@ -361,6 +398,7 @@ function DeviceItem({ editing, onOpen, onTerminal, + onTogglePrivacy, onEdit, onForget, }: { @@ -371,11 +409,14 @@ function DeviceItem({ editing: boolean; onOpen: () => void; onTerminal: () => void; + onTogglePrivacy: () => void; onEdit: (on: boolean) => void; onForget: () => void; }) { const t = useT(); useSession(session); + const privacyWrite = useStore((s) => s.autoPrivacyWrites.get(d.code)); + const savingPrivacy = privacyWrite === "enabling" || privacyWrite === "disabling"; const title = deviceTitle(d); // 打开着的可以随时切过去;其余的要等服务器连上、没有正在进行的连接 const off = disabled && !session; @@ -428,6 +469,23 @@ function DeviceItem({ {!editing && ( + {api.kind === "desktop" && (d.autoPrivacy || canAutoPrivacy(d)) && ( + + )}
)} - {live && gamePaused &&
{t("session.clickToLock")}
} + {live && } + {live && !s.privacyBlock && gamePaused &&
{t("session.clickToLock")}
} ); } diff --git a/client/src/components/SessionView.tsx b/client/src/components/SessionView.tsx index e2a58fc2..814b01a4 100644 --- a/client/src/components/SessionView.tsx +++ b/client/src/components/SessionView.tsx @@ -13,7 +13,7 @@ import { api, MOUSE_MODES, type MouseMode, type Platform } from "../lib/api"; import { type MsgKey, t, useT } from "../lib/i18n"; import { LocalFiles } from "../lib/files"; import { gamepads } from "../lib/gamepad"; -import { errorText, gamepadHint, noticeText, problemText, sessionStateText } from "../lib/messages"; +import { errorText, gamepadHint, noticeText, privacyFailureText, problemText, sessionStateText } from "../lib/messages"; import { CODEC_LABEL } from "../lib/presets"; import { SCROLL_STYLES } from "../lib/scroll-style"; import { SCALE_MODES, ZOOM_LEVELS, type RemoteSession } from "../lib/session"; @@ -238,6 +238,7 @@ export function SessionView({ s }: { s: RemoteSession }) { const typeClipboard = async () => { try { const text = await api.localClipboardText(); + if (s.privacyBlock) return; if (!text) return setToast(t("session.noClipboard")); s.sendText(text); setToast(t("session.typed", { n: text.length })); @@ -433,6 +434,7 @@ export function SessionView({ s }: { s: RemoteSession }) { + {!waiting && ( + + )} + + + + ); +} + /** 防窥模式现在怎么样。对方是 Mac 时不换虚拟显示器,开不了的原因也不一样 */ function privacyHint(s: RemoteSession): string { const mac = s.hostPlatform === "mac"; switch (s.privacyState) { case "unavailable": - return t(mac ? "privacy.unavailableMac" : "privacy.unavailable"); case "notAllowed": - return t("privacy.notAllowed"); + case "failed": + return privacyFailureText(s.privacyState, s.hostPlatform, s.privacyDetail); case "starting": return t(mac ? "privacy.startingMac" : "privacy.starting"); case "on": return t("privacy.on"); - case "failed": - return t("privacy.failed", { detail: s.privacyDetail ?? "—" }); default: return t(mac ? "privacy.offMac" : "privacy.off"); } diff --git a/client/src/lib/actions.ts b/client/src/lib/actions.ts index ea6b84cc..99ccab93 100644 --- a/client/src/lib/actions.ts +++ b/client/src/lib/actions.ts @@ -25,6 +25,7 @@ export interface OpenOptions { */ export async function openSession(code: string, settings: QualitySettings, opts: OpenOptions = {}): Promise { const st = store.get(); + if (api.kind === "desktop" && st.deviceStorage !== "ready") return; const dup = st.sessions.filter(isDesktop).find((s) => s.code === code); if (dup) { if (st.view === "new") store.closeDraft(); @@ -70,6 +71,7 @@ export async function openSession(code: string, settings: QualitySettings, opts: */ export async function openTerminal(code: string, opts: OpenOptions = {}): Promise { const st = store.get(); + if (api.kind === "desktop" && st.deviceStorage !== "ready") return; if (!st.draft) store.newTab(); if (store.get().draft?.busy) return; store.patchDraft({ digits: code.split(""), busy: true, error: null, terminal: true }); @@ -127,17 +129,27 @@ export function reopenLast() { // ── 我的设备 ── -/** 读出保存的设备(打开控制台时) */ -export async function loadDevices() { - const list = await api.loadDevices().catch((e) => { +/** 桌面版在连接之前读取设备的身份和偏好。读取失败时可以重试 */ +let loadingDevices: Promise | null = null; + +export function loadDevices(): Promise { + if (api.kind === "web") { + store.setDeviceStorage("memory"); + return Promise.resolve(); + } + if (loadingDevices) return loadingDevices; + if (store.get().deviceStorage === "ready") return Promise.resolve(); + store.setDeviceStorage("loading"); + loadingDevices = api.loadDevices().then((list) => { + if (list === null) throw new Error("the desktop did not return the saved devices"); + store.setDevices(list.slice(0, devices.MAX_DEVICES), "ready"); + }).catch((e) => { console.warn("can't load the saved devices", e); - return null; + store.setDeviceStorage("failed"); + }).finally(() => { + loadingDevices = null; }); - // 读的时候控制台里可能已经记下了新连上的(很少见):合在一起 - const now = store.get().devices; - const merged = list ? devices.sortDevices([...now, ...list.filter((d) => !now.some((x) => x.code === d.code))]) : now; - store.setDevices(merged.slice(0, devices.MAX_DEVICES), list !== null); - if (list && now.length > 0) saveDevices(); + return loadingDevices; } /** 保存:一次只存一份,存的时候取最新的列表(连续几次变化只存最后一次,也不会旧的盖掉新的) */ @@ -146,19 +158,23 @@ let dirty = false; /** 还没存完的次数 */ let unsaved = 0; -function saveDevices() { - if (!store.get().devicesSaved) return; - dirty = true; +function queueDeviceWrite(write: () => Promise): Promise { unsaved++; - saving = saving.then(async () => { - try { - if (!dirty) return; - dirty = false; - await api.saveDevices(store.get().devices).catch((e) => console.warn("can't save the devices", e)); - } finally { - unsaved--; - } + const task = saving.then(write).finally(() => { + unsaved--; }); + saving = task.catch(() => {}); + return task; +} + +function saveDevices() { + if (store.get().deviceStorage !== "ready") return; + dirty = true; + void queueDeviceWrite(async () => { + if (!dirty) return; + dirty = false; + await api.saveDevices(store.get().devices); + }).catch((e) => console.warn("can't save the devices", e)); } function setDevices(list: SavedDevice[]) { @@ -207,6 +223,26 @@ function rememberInputSettings(s: RemoteSession) { export const renameDevice = (code: string, name: string) => setDevices(devices.renameDevice(store.get().devices, code, name)); +export async function setDeviceAutoPrivacy(code: string, on: boolean) { + const st = store.get(); + const write = st.autoPrivacyWrites.get(code); + if (st.deviceStorage !== "ready" || write === "enabling" || write === "disabling") return; + store.setAutoPrivacyWrite(code, on ? "enabling" : "disabling"); + try { + await queueDeviceWrite(async () => { + const list = store.get().devices; + const next = devices.patchDevice(list, code, { autoPrivacy: on }); + if (next === list) return; + await api.saveDevices(next); + // 写入期间的改名、画质等改动仍由同一条队列保存;这里只确认防窥偏好的变化 + store.setDevices(devices.patchDevice(store.get().devices, code, { autoPrivacy: on })); + }); + store.setAutoPrivacyWrite(code, null); + } catch (e) { + store.setAutoPrivacyWrite(code, "failed"); + throw e; + } +} export const forgetDevice = (code: string) => setDevices(devices.forgetDevice(store.get().devices, code)); export const restoreDevice = (d: SavedDevice) => setDevices(devices.restoreDevice(store.get().devices, d)); diff --git a/client/src/lib/api.ts b/client/src/lib/api.ts index f0da64ab..0f15e818 100644 --- a/client/src/lib/api.ts +++ b/client/src/lib/api.ts @@ -239,6 +239,8 @@ export interface SavedDevice { mouse?: MouseMode | null; /** 操作这台 Mac 时互换物理 Ctrl 和 Command 键,默认关闭 */ swapCtrlCommand?: boolean; + /** 连接这台设备时请求防窥模式,默认关闭 */ + autoPrivacy?: boolean; /** 对方的端到端加密公钥(64 位十六进制,第一次连上时记下):之后只认它 */ hostKey: string | null; } diff --git a/client/src/lib/devices.ts b/client/src/lib/devices.ts index 18e8c5ea..c06be4fa 100644 --- a/client/src/lib/devices.ts +++ b/client/src/lib/devices.ts @@ -14,6 +14,11 @@ export const deviceTitle = (d: SavedDevice) => d.alias?.trim() || d.name.trim() /** 最近连过的在前面 */ export const sortDevices = (list: SavedDevice[]) => [...list].sort((a, b) => b.lastUsed - a.lastUsed); +/** 已经认过身份的 Windows、macOS 被控端可以设置自动防窥 */ +export function canAutoPrivacy(d: SavedDevice): boolean { + return !!d.hostKey && (d.os.startsWith("macOS") || /\bWindows\b/.test(d.os)); +} + /** 连上了:记下(或更新)这台电脑。自己起的名字保留,对方的名字、系统、凭证、画质、鼠标模式用这次的 */ export function remember( list: SavedDevice[], @@ -30,6 +35,7 @@ export function remember( now: number, ): SavedDevice[] { const old = list.find((d) => d.code === seen.code); + const hostKey = seen.hostKey ?? old?.hostKey ?? null; const d: SavedDevice = { code: seen.code, alias: old?.alias ?? null, @@ -40,8 +46,10 @@ export function remember( quality: seen.quality ?? old?.quality ?? null, mouse: seen.mouse ?? old?.mouse ?? null, swapCtrlCommand: seen.swapCtrlCommand ?? old?.swapCtrlCommand ?? false, + // 重新配对后,这条已保存设备仍使用原来的防窥偏好 + autoPrivacy: old?.autoPrivacy ?? false, // 对方的公钥:连上时确认过的(第一次连上、或者用户信任了新的身份)代替旧的 - hostKey: seen.hostKey ?? old?.hostKey ?? null, + hostKey, }; return sortDevices([d, ...list.filter((x) => x.code !== seen.code)]).slice(0, MAX_DEVICES); } @@ -50,7 +58,7 @@ export function remember( export function patchDevice( list: SavedDevice[], code: string, - patch: Partial>, + patch: Partial>, ) { if (!list.some((d) => d.code === code)) return list; return list.map((d) => (d.code === code ? { ...d, ...patch } : d)); diff --git a/client/src/lib/messages.ts b/client/src/lib/messages.ts index 66224037..f5f150ff 100644 --- a/client/src/lib/messages.ts +++ b/client/src/lib/messages.ts @@ -7,6 +7,7 @@ import { type FileError, type GamepadSupport, type Platform, + type PrivacyState, type Problem, type RemoteNotice, type UpdateProblem, @@ -14,6 +15,8 @@ import { import { t } from "./i18n"; import type { Session } from "./store"; +type PrivacyFailure = Extract; + /** 本机产生的提示 */ export type LocalNotice = | { kind: "h264Undecodable" } @@ -69,6 +72,17 @@ export function gamepadHint(state: GamepadSupport, platform: Platform | null, de } } +export function privacyFailureText(state: PrivacyFailure, platform: Platform | null, detail: string | null): string { + switch (state) { + case "unavailable": + return t(platform === "mac" ? "privacy.unavailableMac" : "privacy.unavailable"); + case "notAllowed": + return t("privacy.notAllowed"); + case "failed": + return t("privacy.failed", { detail: detail ?? "—" }); + } +} + export function noticeText(n: SessionNotice): string { if (n.kind === "fileError") return t("notice.fileError", { name: n.name, reason: t(`fileError.${n.error}` as const) }); if (n.kind === "gamepadUnavailable") { diff --git a/client/src/lib/session.ts b/client/src/lib/session.ts index 3846247d..3b5bad13 100644 --- a/client/src/lib/session.ts +++ b/client/src/lib/session.ts @@ -101,6 +101,7 @@ const MAX_RETRIES = 30; const WAIT_CHECK_MS = 60_000; /** 没连上服务器(网页版还有控制端服务)时多久试一次;连上时马上会试(serverConnected) */ const NO_SERVER_RETRY_MS = 5_000; +const PRIVACY_WAIT_MS = 20_000; /** * 服务器的明确回答:自动重试只会被当成在猜控制码。 * kicked:重连凭证作废了(对方断开过所有控制端,或者换了控制码),连上过的会话不再自动重连(见 connect)。 @@ -160,6 +161,7 @@ export class RemoteSession implements GamepadTarget { zoom = 1; /** 双向同步剪贴板文本 */ clipboardSync = true; + private clipboardOn = true; /** 播放远程声音(用户开关;实际只在当前查看的会话上播放) */ audioEnabled = true; /** 音画同步开关(用户设置;实际只在播放声音时生效) */ @@ -178,6 +180,11 @@ export class RemoteSession implements GamepadTarget { privacyDetail: string | null = null; /** 要防窥模式(开关):重连时在连接选项里带上,对方就一直保持防窥。跟着对方说的状态变 */ privacyWanted = false; + /** 要求被控端确认防窥后才允许操作 */ + private requirePrivacy = false; + private allowVisibleScreen = false; + private privacyWaitTimer?: number; + private privacyWaitOver = false; /** 对方能不能接本机的手柄(hello 之后对方会说);对方不能接(手机、版本旧)、还没说时为 null:不发手柄 */ gamepadState: GamepadSupport | null = null; /** 对方插不上虚拟手柄的原因(英文技术信息) */ @@ -359,7 +366,7 @@ export class RemoteSession implements GamepadTarget { private newInput(screen: HTMLElement, locate: (x: number, y: number) => { x: number; y: number; stream: number }) { const input = new RemoteInput( screen, - () => this.sid !== null && !this.disposed, + () => this.sid !== null && !this.disposed && !this.privacyBlock, (events) => { if (this.sid !== null) this.command({ cmd: "input", sid: this.sid, events }); }, @@ -407,7 +414,7 @@ export class RemoteSession implements GamepadTarget { private emit() { // 弹出窗口里的画面:连着的时候就能操作(主窗口的由 CanvasHost 管,见 setInteractive) - const live = this.state === "live" && !this.disposed; + const live = this.state === "live" && !this.disposed && !this.privacyBlock; for (const d of this.popouts.values()) if (d.input.interactive !== live) d.input.interactive = live; this.version++; for (const l of this.listeners) l(); @@ -415,6 +422,62 @@ export class RemoteSession implements GamepadTarget { // ───────────────────────── 连接 ───────────────────────── + /** 主动发起连接时读设备偏好 */ + private useSavedPrivacy() { + if (api.kind !== "desktop") return; + const { devices, autoPrivacyWrites } = store.get(); + const saved = devices.find((d) => d.code === this.code); + // 写入启用请求期间,新的会话也先等防窥;关闭请求要等写入成功才生效 + const required = !!saved && (saved.autoPrivacy === true || autoPrivacyWrites.get(this.code) === "enabling"); + if (this.requirePrivacy && !required) this.privacyWanted = false; + this.requirePrivacy = required; + } + + get privacyBlock(): "waiting" | "inactive" | null { + if (!this.requirePrivacy || this.allowVisibleScreen || this.privacyState === "on") return null; + const state = this.privacyState; + if (this.privacyWaitOver || state === "unavailable" || state === "notAllowed" || state === "failed") return "inactive"; + if (this.hostPlatform && this.hostPlatform !== "windows" && this.hostPlatform !== "mac") return "inactive"; + return "waiting"; + } + + private clearPrivacyWait() { + clearTimeout(this.privacyWaitTimer); + this.privacyWaitTimer = undefined; + } + + private syncPrivacyWait() { + if (this.state !== "live" || this.privacyBlock !== "waiting") { + this.clearPrivacyWait(); + } else if (this.privacyWaitTimer === undefined) { + this.privacyWaitTimer = window.setTimeout(() => { + this.privacyWaitTimer = undefined; + this.privacyWaitOver = true; + this.emit(); + }, PRIVACY_WAIT_MS); + } + } + + private syncPrivacyControls(wasBlocked: boolean) { + if (!wasBlocked && this.privacyBlock && this.sid !== null) { + // 已经在操作时防窥被关闭:丢掉尚未发出的输入,通知对方释放按键和手柄 + for (const input of this.inputs) input.reset(); + this.command({ cmd: "input", sid: this.sid, events: [{ type: "releaseAll" }] }); + } + this.syncPrivacyWait(); + this.syncClipboard(); + this.syncGamepads(); + this.syncMic(); + } + + continueWithoutPrivacy() { + if (this.sid === null || this.privacyBlock !== "inactive") return; + this.allowVisibleScreen = true; + this.privacyWanted = false; + this.syncPrivacyControls(true); + this.emit(); + } + /** 建立连接。首次连接失败会抛出错误。 */ async start(): Promise { const gen = this.attempt.begin(); @@ -433,6 +496,9 @@ export class RemoteSession implements GamepadTarget { this.micDetail = null; this.micOn = false; // 防窥模式也一样:对方重新说。要不要在握手里就告诉它(下面的连接选项) + this.clearPrivacyWait(); + this.allowVisibleScreen = false; + this.privacyWaitOver = false; this.privacyState = null; this.privacyDetail = null; // 手柄也是:对方说了能接才发 @@ -446,6 +512,9 @@ export class RemoteSession implements GamepadTarget { // 不用先建一个默认的再重建(重连时知道对方有哪些显示器;第一次连时不知道,对方先看主显示器) const sent = this.effectiveSettings(); const audio = this.audioEnabled && this.foreground; + const clipboard = this.clipboardSync && !this.privacyBlock; + // 已保存的公钥或新的配对码都可以认证对端;被控端确认握手后才打开防窥 + const privacy = this.requirePrivacy ? Boolean(this.hostKey || this.pairing) : this.privacyWanted; const view = this.wantedView(); this.placeCanvases(view.map((v) => v.display)); this.sentView = null; @@ -459,11 +528,11 @@ export class RemoteSession implements GamepadTarget { settings: sent, audio, view, - privacy: this.privacyWanted, + privacy, }, this.view, onEvent, - this.clipboardSync, + clipboard, ); } catch (e) { // A Closed event already decided whether to retry. An old failure must @@ -498,8 +567,11 @@ export class RemoteSession implements GamepadTarget { // 对方已经按握手里说的开始(或者没有开始)发声音;连接期间变了(例如切换了标签)再告诉对方 this.audioOn = audio; if (audio) this.audio.enable(); + this.clipboardOn = clipboard; this.applySyncState(); this.syncAudio(); + if (this.requirePrivacy) this.syncPrivacyControls(true); + else this.syncClipboard(); this.emit(); this.onConnected?.(this); } @@ -527,6 +599,7 @@ export class RemoteSession implements GamepadTarget { * 所以对方不在线时不用再拿控制码试一次——那样会算一次猜错,占掉这个 IP 的额度 */ async open(): Promise { + this.useSavedPrivacy(); try { await this.connect(); } catch (e) { @@ -549,6 +622,7 @@ export class RemoteSession implements GamepadTarget { */ private scheduleRetry(reason: Problem | null) { if (this.disposed) return; + this.clearPrivacyWait(); this.sid = null; this.syncAudio(); this.syncMic(); @@ -616,6 +690,7 @@ export class RemoteSession implements GamepadTarget { /** 手动重连(关闭状态下) */ reconnect() { if (this.disposed) return; + this.useSavedPrivacy(); this.retries = 0; this.state = "reconnecting"; this.emit(); @@ -626,6 +701,7 @@ export class RemoteSession implements GamepadTarget { this.disposed = true; this.attempt.invalidate(); clearTimeout(this.retryTimer); + this.clearPrivacyWait(); this.input.dispose(); this.view.dispose(); clearTimeout(this.viewTimer); @@ -651,6 +727,7 @@ export class RemoteSession implements GamepadTarget { this.hostName = ev.hostname; this.hostOs = ev.os; this.hostPlatform = ev.platform; + this.syncPrivacyWait(); // 手机点的是触屏,没有鼠标模式(工具栏也不显示):一律按自动 if ((ev.platform === "android" || ev.platform === "ios") && this.input.mode !== "auto") { for (const input of this.inputs) input.setMode("auto", false); @@ -697,12 +774,17 @@ export class RemoteSession implements GamepadTarget { this.micDetail = ev.detail; this.syncMic(); break; - case "privacy": + case "privacy": { + const wasBlocked = !!this.privacyBlock; this.privacyState = ev.state; this.privacyDetail = ev.detail; + // 确认过已开启后,如果防窥被关闭,马上告诉用户 + if (ev.state === "on") this.privacyWaitOver = true; // 开关跟着对方说的变:别的控制端打开 / 关掉了、没能打开,都以对方的为准 this.privacyWanted = ev.state === "on" || ev.state === "starting"; + if (this.requirePrivacy) this.syncPrivacyControls(wasBlocked); break; + } case "gamepad": { const could = this.gamepadSendable; this.gamepadState = ev.state; @@ -759,6 +841,7 @@ export class RemoteSession implements GamepadTarget { if (this.disposed) return; this.attempt.invalidate(); clearTimeout(this.retryTimer); + this.clearPrivacyWait(); for (const input of this.inputs) input.reset(); if (ev.retry) { this.scheduleRetry(ev.reason); @@ -784,6 +867,7 @@ export class RemoteSession implements GamepadTarget { /** 对会话的操作(失败了也没关系:会话断了会另外收到 closed) */ private command(c: Command) { + if (c.cmd === "input" && this.privacyBlock && c.events.some((e) => e.type !== "releaseAll")) return; void api.command(c).catch(() => {}); } @@ -1299,7 +1383,8 @@ export class RemoteSession implements GamepadTarget { * 不再交给它时,GamepadHub 先让对方把按着的手柄放回原位 */ private syncGamepads() { - const want = this.foreground && this.interactive && this.sid !== null && !this.disposed && this.gamepadState !== null; + const want = this.foreground && this.interactive && this.sid !== null && !this.disposed && this.gamepadState !== null + && !this.privacyBlock; if (want === this.gamepadClaimed) return; this.gamepadClaimed = want; if (want) gamepads.claim(this); @@ -1308,6 +1393,7 @@ export class RemoteSession implements GamepadTarget { /** 本机手柄的输入(GamepadHub 只在这个会话是正在操作的那个时交过来) */ gamepadInput(events: InputEvent[], urgent: boolean) { + if (this.privacyBlock) return; if (this.gamepadSendable) { this.enqueue(events, urgent); return; @@ -1336,11 +1422,16 @@ export class RemoteSession implements GamepadTarget { * 还没连上时只记下来,连上时在连接选项里告诉对方 */ setPrivacy(on: boolean) { + const wasBlocked = !!this.privacyBlock; this.privacyWanted = on; if (this.sid !== null && this.privacyState !== null) { - this.command({ cmd: "privacy", sid: this.sid, on }); this.privacyState = on ? "starting" : "off"; this.privacyDetail = null; + if (this.requirePrivacy) { + this.privacyWaitOver = !on; + this.syncPrivacyControls(wasBlocked); + } + this.command({ cmd: "privacy", sid: this.sid, on }); } this.emit(); } @@ -1357,6 +1448,7 @@ export class RemoteSession implements GamepadTarget { private syncMic() { const want = this.micEnabled && this.foreground && this.sid !== null && !this.disposed + && !this.privacyBlock && this.micState !== null && this.micState !== "unsupported"; if (want !== this.micOn && this.sid !== null) this.command({ cmd: "mic", sid: this.sid, enabled: want }); this.micOn = want; @@ -1609,10 +1701,17 @@ export class RemoteSession implements GamepadTarget { setClipboardSync(v: boolean) { this.clipboardSync = v; - if (this.sid !== null) this.command({ cmd: "clipboardSync", sid: this.sid, enabled: v }); + this.syncClipboard(); this.emit(); } + private syncClipboard() { + const enabled = this.clipboardSync && !this.privacyBlock; + if (this.sid === null || this.clipboardOn === enabled) return; + this.clipboardOn = enabled; + this.command({ cmd: "clipboardSync", sid: this.sid, enabled }); + } + // ───────────────────────── 剪贴板里的文件(见 files.ts) ───────────────────────── /** @@ -1620,7 +1719,7 @@ export class RemoteSession implements GamepadTarget { * 返回公告了没有 */ offerFiles(files: LocalFiles): boolean { - if (this.sid === null || !this.clipboardSync) return false; + if (this.sid === null || !this.clipboardSync || this.privacyBlock) return false; api.offerFiles(this.sid, files).catch((e) => { // 对方的版本旧,不支持剪贴板里的文件 this.notice = { kind: "filesUnsupported" }; @@ -1723,7 +1822,9 @@ export class RemoteSession implements GamepadTarget { focus() { this.input.focus(); } private releaseAll() { this.input.releaseAll(); } - private enqueue(events: InputEvent[], urgent: boolean) { this.input.enqueue(events, urgent); } + private enqueue(events: InputEvent[], urgent: boolean) { + if (!this.privacyBlock) this.input.enqueue(events, urgent); + } } /** 放在单独窗口里的一个显示器(见 popout.ts) */ diff --git a/client/src/lib/store.ts b/client/src/lib/store.ts index 4b29aa2a..12244d98 100644 --- a/client/src/lib/store.ts +++ b/client/src/lib/store.ts @@ -42,6 +42,8 @@ export interface Recent { /** 等用户确认的操作:关闭控制台会断开所有会话 */ export type Confirm = null | { kind: "close"; sessions: number }; +type AutoPrivacyWrite = "enabling" | "disabling" | "failed"; + interface State { /** 顺序就是标签的顺序(桌面和终端都在里面) */ sessions: Session[]; @@ -51,8 +53,10 @@ interface State { recent: Recent[]; /** 我的设备:连接过的电脑,最近连过的在前面 */ devices: SavedDevice[]; - /** 我的设备能不能保存(桌面版:config.toml);网页版只在本页面的内存里 */ - devicesSaved: boolean; + /** 桌面版必须先读出保存的设备;网页版只在本页面的内存里 */ + deviceStorage: "loading" | "ready" | "failed" | "memory"; + /** 正在保存或保存失败的设备防窥设置;切换标签后仍能看到失败提示 */ + autoPrivacyWrites: ReadonlyMap; confirm: Confirm; server: ServerState; /** @@ -139,7 +143,8 @@ let state: State = { draft: emptyDraft(), recent: [], devices: [], - devicesSaved: false, + deviceStorage: "loading", + autoPrivacyWrites: new Map(), confirm: null, server: { state: "connecting" }, serverProblem: null, @@ -319,7 +324,14 @@ export const store = { const v = n >= 9 ? tabs[tabs.length - 1] : tabs[n - 1]; if (v) store.setView(v); }, - setDevices: (devices: SavedDevice[], saved = state.devicesSaved) => set({ devices, devicesSaved: saved }), + setDevices: (devices: SavedDevice[], deviceStorage = state.deviceStorage) => set({ devices, deviceStorage }), + setDeviceStorage: (deviceStorage: State["deviceStorage"]) => set({ deviceStorage }), + setAutoPrivacyWrite: (code: string, write: AutoPrivacyWrite | null) => { + const autoPrivacyWrites = new Map(state.autoPrivacyWrites); + if (write === null) autoPrivacyWrites.delete(code); + else autoPrivacyWrites.set(code, write); + set({ autoPrivacyWrites }); + }, setConfirm: (confirm: Confirm) => set({ confirm }), }; diff --git a/client/src/locales/en.ts b/client/src/locales/en.ts index ce5ae3bf..1c0fbf17 100644 --- a/client/src/locales/en.ts +++ b/client/src/locales/en.ts @@ -128,6 +128,12 @@ const en: Record = { "devices.search": "Search by name or code", "devices.noMatch": "No matching devices", "devices.rename": "Rename", + "devices.autoPrivacy": "Turn on privacy mode when connecting", + "devices.loading": "Loading saved devices…", + "devices.loadFailed": "Couldn't read saved device settings. Connections are paused.", + "devices.retryLoad": "Retry", + "devices.privacySaving": "Saving privacy mode preference…", + "devices.privacySaveFailed": "Couldn't confirm that the privacy preference was saved. Please try again.", "devices.forget": "Remove from My devices", "devices.removed": "Removed {name}", "devices.undo": "Undo", @@ -332,6 +338,11 @@ const en: Record = { // Privacy mode: the remote monitors go blank and its keyboard and mouse stop working, only the controller sees and controls it "privacy.toggle": "Privacy mode", + "privacy.guardWaiting": "Waiting for privacy mode. Remote input is paused.", + "privacy.guardInactive": "Privacy mode is off. Remote input is paused.", + "privacy.guardUnconfirmed": "The remote computer did not confirm that privacy mode is on.", + "privacy.guardDisconnect": "Disconnect", + "privacy.guardContinue": "Continue with remote screen visible", "privacy.off": "Blanks all of the remote computer's monitors and disables its keyboard and mouse, so only you can see and control it (the picture moves to a virtual display). Turns off by itself after you disconnect", "privacy.starting": "Turning on: the remote computer is switching to a virtual display, this takes a few seconds", "privacy.on": "On: the remote computer's monitors are blank and its keyboard and mouse don't work. Turns off 30 seconds after you disconnect (reconnecting in time keeps it on)", diff --git a/client/src/locales/zh.ts b/client/src/locales/zh.ts index 55e0ecb1..2bc7ad38 100644 --- a/client/src/locales/zh.ts +++ b/client/src/locales/zh.ts @@ -136,6 +136,12 @@ export default { "devices.search": "搜索名称或控制码", "devices.noMatch": "没有匹配的设备", "devices.rename": "重命名", + "devices.autoPrivacy": "连接时自动开启防窥模式", + "devices.loading": "正在读取已保存的设备…", + "devices.loadFailed": "无法读取已保存的设备设置,连接已暂停。", + "devices.retryLoad": "重新读取", + "devices.privacySaving": "正在保存防窥设置…", + "devices.privacySaveFailed": "未能确认防窥设置已保存,请重试。", "devices.forget": "从我的设备中移除", "devices.removed": "已移除 {name}", "devices.undo": "撤销", @@ -344,6 +350,11 @@ export default { // 防窥模式:对方的显示器黑屏、键盘鼠标不起作用,只有控制端看得到、操作得了 "privacy.toggle": "防窥模式", + "privacy.guardWaiting": "等待防窥开启,远程操作已暂停", + "privacy.guardInactive": "防窥未开启,远程操作已暂停", + "privacy.guardUnconfirmed": "被控端没有确认防窥已开启。", + "privacy.guardDisconnect": "断开连接", + "privacy.guardContinue": "继续(对方屏幕可见)", "privacy.off": "打开后,对方电脑的显示器全部黑屏、键盘鼠标不起作用,只有你看得到、操作得了(画面换成一块虚拟显示器)。断开连接后自动恢复", "privacy.starting": "正在打开:对方电脑正在换成虚拟显示器,要几秒钟", "privacy.on": "已打开:对方电脑的显示器全部黑屏、键盘鼠标不起作用。断开连接 30 秒后自动恢复(期间重连会接着保持)", diff --git a/client/tests/device-actions.test.ts b/client/tests/device-actions.test.ts new file mode 100644 index 00000000..04e84664 --- /dev/null +++ b/client/tests/device-actions.test.ts @@ -0,0 +1,115 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import { stripTypeScriptTypes } from "node:module"; +import { test } from "node:test"; +import vm from "node:vm"; +import type { SavedDevice } from "../src/lib/api.ts"; +import * as devices from "../src/lib/devices.ts"; + +const settings = { fps: 30, bitrateKbps: 4000, maxShort: 1080, adaptive: true, codec: "h264" as const }; +const saved: SavedDevice = { + code: "482913", alias: null, name: "PC", os: "Windows", resume: null, lastUsed: 1, + quality: settings, hostKey: "ab".repeat(32), autoPrivacy: true, +}; + +// 运行真正的连接入口和保存队列,模拟 Tauri 的异步读写。 +function harness() { + const state = { + deviceStorage: "loading", + devices: [] as SavedDevice[], + autoPrivacyWrites: new Map(), + sessions: [], + draft: { busy: false }, + }; + const store = { + get: () => state, + patchDraft: (patch: { busy: boolean }) => Object.assign(state.draft, patch), + add() {}, + setDevices: (list: SavedDevice[], storage = state.deviceStorage) => { + state.devices = list; + state.deviceStorage = storage; + }, + setDeviceStorage: (storage: string) => { state.deviceStorage = storage; }, + setAutoPrivacyWrite: (code: string, write: "enabling" | "disabling" | "failed" | null) => { + if (write === null) state.autoPrivacyWrites.delete(code); + else state.autoPrivacyWrites.set(code, write); + }, + }; + const connections: (SavedDevice | undefined)[] = []; + class RemoteSession { + sid = null; + private readonly saved: SavedDevice | undefined; + constructor(_code: string, _settings: unknown, saved: SavedDevice | undefined) { + this.saved = saved; + } + async open() { connections.push(this.saved); } + } + const api = { + kind: "desktop", + loadDevices: async (): Promise => [saved], + saveDevices: async (_list: SavedDevice[]): Promise => {}, + }; + const source = fs.readFileSync(new URL("../src/lib/actions.ts", import.meta.url), "utf8") + .replace(/^import[\s\S]*?from "[^"]+";\r?\n/gm, "") + .replace(/^export \{[^}]+\} from "[^"]+";\r?\n/gm, ""); + const js = stripTypeScriptTypes(source).replace(/\bexport\s+/g, ""); + const actions = vm.runInNewContext( + js + "\n({ loadDevices, openSession, openTerminal, renameDevice, setDeviceAutoPrivacy })", + { api, store, RemoteSession, devices, isDesktop: () => true, console: { warn() {} } }, + ) as Pick; + return { actions, api, connections, state }; +} + +test("桌面连接等设备偏好读完,读失败时不把它当作空列表", async () => { + const { actions, api, connections, state } = harness(); + const read = Promise.withResolvers(); + api.loadDevices = () => read.promise; + const loading = actions.loadDevices(); + assert.equal(actions.loadDevices(), loading); + await actions.openSession(saved.code, settings); + await actions.openTerminal(saved.code); + assert.equal(connections.length, 0); + assert.equal(state.draft.busy, false); + read.reject(new Error("can't read config")); + await loading; + assert.equal(state.deviceStorage, "failed"); + await actions.openSession(saved.code, settings); + assert.equal(connections.length, 0); + + api.loadDevices = async () => [saved]; + await actions.loadDevices(); + await actions.openSession(saved.code, settings); + assert.equal(state.deviceStorage, "ready"); + assert.equal(connections[0]?.autoPrivacy, true); +}); + +test("设备防窥等写入成功才确认,失败后可重试并保留期间的改名", async () => { + const { actions, api, state } = harness(); + api.loadDevices = async () => [{ ...saved, autoPrivacy: false }]; + await actions.loadDevices(); + api.saveDevices = async () => { throw new Error("can't write config"); }; + await assert.rejects(actions.setDeviceAutoPrivacy(saved.code, true), /can't write config/); + assert.equal(state.devices[0].autoPrivacy, false); + assert.equal(state.autoPrivacyWrites.get(saved.code), "failed"); + + const write = Promise.withResolvers(); + const writes: SavedDevice[][] = []; + api.saveDevices = async (list) => { + writes.push(list); + if (writes.length === 1) await write.promise; + }; + const saving = actions.setDeviceAutoPrivacy(saved.code, true); + await Promise.resolve(); + assert.equal(state.autoPrivacyWrites.get(saved.code), "enabling"); + assert.equal(state.devices[0].autoPrivacy, false); + actions.renameDevice(saved.code, "书房"); + write.resolve(); + await saving; + await new Promise(setImmediate); + assert.equal(state.autoPrivacyWrites.has(saved.code), false); + assert.equal(state.devices[0].autoPrivacy, true); + assert.equal(state.devices[0].alias, "书房"); + assert.equal(writes.at(-1)?.[0].autoPrivacy, true); + assert.equal(writes.at(-1)?.[0].alias, "书房"); +}); diff --git a/client/tests/devices.test.ts b/client/tests/devices.test.ts index b2a45e23..ce339855 100644 --- a/client/tests/devices.test.ts +++ b/client/tests/devices.test.ts @@ -4,6 +4,7 @@ import { test } from "node:test"; import type { SavedDevice } from "../src/lib/api.ts"; import { MAX_DEVICES, + canAutoPrivacy, deviceTitle, forgetDevice, matchDevice, @@ -57,6 +58,24 @@ test("Ctrl / Command 互换只记在选中的设备,重连保留,也能关 assert.equal(remember(list, { ...seen("482913"), swapCtrlCommand: false }, 4)[0].swapCtrlCommand, false); }); +test("自动防窥按设备记录保存,重新配对后保留", () => { + const pc = { ...seen("482913"), hostKey: "ab".repeat(32) }; + const mac = { ...seen("731205"), os: "macOS 26.6", hostKey: "cd".repeat(32) }; + let list = remember(remember([], pc, 1), mac, 2); + assert.ok(list.every(canAutoPrivacy)); + assert.ok(list.every((d) => !d.autoPrivacy)); + list = patchDevice(list, pc.code, { autoPrivacy: true }); + list = remember(list, pc, 3); + assert.deepEqual(list.map((d) => [d.code, d.autoPrivacy]), [[pc.code, true], [mac.code, false]]); + const newKey = "ef".repeat(32); + const repaired = remember(list, { ...pc, hostKey: newKey }, 4)[0]; + assert.equal(repaired.hostKey, newKey); + assert.equal(repaired.autoPrivacy, true); + assert.equal(patchDevice(list, pc.code, { autoPrivacy: false })[0].autoPrivacy, false); + assert.equal(canAutoPrivacy({ ...list[0], hostKey: null }), false); + assert.equal(canAutoPrivacy({ ...list[0], os: "Ubuntu 24.04" }), false); +}); + test("自己起的名字:重连后保留;改回对方的名字或清空就是不另起名字", () => { let list = remember([], seen("482913"), 1); list = renameDevice(list, "482913", " 书房 "); diff --git a/client/tests/session.test.ts b/client/tests/session.test.ts index bf287897..941cdc58 100644 --- a/client/tests/session.test.ts +++ b/client/tests/session.test.ts @@ -42,7 +42,10 @@ function fakePopout(w: number, h: number) { // Load the actual session class with browser/backend dependencies replaced by // small fakes. This tests delivery ordering without a WebView or network. -function sessionHarness(connect?: (code: string, resume: any, opts: any) => Promise) { +function sessionHarness( + connect?: (code: string, resume: any, opts: any) => Promise, + kind: "desktop" | "web" = "desktop", +) { const source = fs.readFileSync(new URL("../src/lib/session.ts", import.meta.url), "utf8") .replace(/^import[\s\S]*?from "[^"]+";\r?\n/gm, ""); const js = stripTypeScriptTypes(source).replace(/\bexport\s+/g, "") + "\nglobalThis.RemoteSession = RemoteSession;"; @@ -50,7 +53,8 @@ function sessionHarness(connect?: (code: string, resume: any, opts: any) => Prom let resolve: (value: any) => void = () => {}; const calls: any[] = []; const timers: (() => void)[] = []; - const storeState: any = { enhance: "off", decoders: ["h264"] }; + const clipboardStarts: boolean[] = []; + const storeState: any = { enhance: "off", decoders: ["h264"], devices: [], autoPrivacyWrites: new Map() }; const sandbox: any = { console, performance, clearTimeout, setTimeout, queueMicrotask, ConnectionAttempt, fitSize, stricter, viewMaxShort, renderPlan, media, hitTest, layoutTiles, placeDisplays, RemoteInput, devicePixelRatio: 1, codecUsable: () => true, bestCodec: () => "h264", @@ -65,8 +69,10 @@ function sessionHarness(connect?: (code: string, resume: any, opts: any) => Prom }, toProblem: (e: any) => e, api: { - connect: (c: any, o: any, _view: any, onEvent: any) => { + kind, + connect: (c: any, o: any, _view: any, onEvent: any, clipboard: boolean) => { sink = onEvent; + clipboardStarts.push(clipboard); return connect ? connect(c, o.resume, o) : new Promise(res => { resolve = res; }); }, command: async (c: any) => { @@ -74,6 +80,7 @@ function sessionHarness(connect?: (code: string, resume: any, opts: any) => Prom c.cmd === "settings" ? [c.cmd, c.sid, c.settings] : c.cmd === "mic" ? [c.cmd, c.sid, c.enabled] : c.cmd === "privacy" ? [c.cmd, c.sid, c.on] + : c.cmd === "clipboardSync" ? [c.cmd, c.sid, c.enabled] : c.cmd === "view" ? [c.cmd, c.sid, plain(c.streams)] : [c.cmd, c.sid], ); @@ -93,12 +100,12 @@ function sessionHarness(connect?: (code: string, resume: any, opts: any) => Prom newCanvas(home: any) { const c: any = fakeCanvas(); c.home = home; return c; }, popouts: new Map(), opening: new Map(), cursorCss: new WeakMap(), view: { setSync() {}, setAudio() {}, setLayout() {}, dispose() {}, addCanvas() {} }, frames: [{ w: 16, h: 9 }], - input: { reset() {} }, + input: { reset() {} }, clipboardSync: true, clipboardOn: true, cursorSlots: new Map(), resume: null, hostKey: null, safety: null, pairing: null, onlineAt: -1, attemptAt: 0, retries: 0, dismissedTips: new Set(), emit() {}, syncAudio() {}, syncMic() {}, applySyncState() {}, onConnected() { calls.push("connected"); }, }); - return { session, calls, timers, store: storeState, event: (ev: any) => sink(ev), resolve: () => resolve({ sid: 7, resume: [], hostName: "host", hostOs: "Android" }) }; + return { session, calls, timers, clipboardStarts, store: storeState, event: (ev: any) => sink(ev), resolve: () => resolve({ sid: 7, resume: [], hostName: "host", hostOs: "Android" }) }; } test("文字分块保留 emoji 的代理对,每块都能独立编码成 UTF-8", () => { @@ -794,6 +801,137 @@ test("防窥模式:对方说了状态才能开;打开时先显示正在打 assert.equal(opts.privacy, false); }); +test("自动防窥等对方确认才放行输入,关闭后重新暂停操作", async () => { + const privacyRequests: boolean[] = []; + const h = sessionHarness(async (_code, _resume, opts) => { + privacyRequests.push(opts.privacy); + return granted; + }); + const s = h.session; + s.code = "482913"; + s.hostKey = granted.hostKey; + s.gamepadEnabled = true; + s.foreground = true; + s.interactive = true; + s.gamepadClaimed = false; + const queued: unknown[] = []; + s.input.enqueue = (events: unknown[]) => queued.push(...events); + h.store.devices = [{ code: s.code, os: granted.hostOs, hostKey: granted.hostKey, autoPrivacy: true }]; + + await s.open(); + assert.equal(privacyRequests.at(-1), true); + assert.equal(h.clipboardStarts.at(-1), false); + h.event({ type: "privacy", state: "off", detail: null }); + assert.equal(s.privacyBlock, "waiting"); + s.continueWithoutPrivacy(); + assert.equal(s.privacyBlock, "waiting", "不能在等待确认时直接继续"); + h.event({ type: "privacy", state: "starting", detail: null }); + h.event({ type: "gamepad", state: "ready", detail: null }); + s.sendCombo(["KeyA"]); + s.sendText("private"); + s.gamepadInput([{ type: "gamepad", pad: 0, buttons: 1 }], true); + s.command({ cmd: "input", sid: 7, events: [{ type: "mouseMove", x: 0, y: 0 }] }); + assert.equal(s.offerFiles({}), false); + assert.deepEqual(queued, []); + assert.ok(!h.calls.some((call) => ["input", "clipboardSync", "claim"].includes(call[0]))); + + h.event({ type: "privacy", state: "on", detail: null }); + assert.equal(s.privacyBlock, null); + assert.deepEqual(h.calls.slice(-2), [["clipboardSync", 7, true], ["claim"]]); + s.sendCombo(["KeyA"]); + assert.equal(queued.length, 2); + h.event({ type: "privacy", state: "off", detail: null }); + assert.equal(s.privacyBlock, "inactive"); + assert.deepEqual(h.calls.slice(-3), [["input", 7], ["clipboardSync", 7, false], ["release"]]); + s.sendText("private"); + assert.equal(queued.length, 2); + h.event({ type: "privacy", state: "on", detail: null }); + s.setPrivacy(false); + assert.equal(s.privacyBlock, "inactive"); + assert.deepEqual(h.calls.slice(-4), [["input", 7], ["clipboardSync", 7, false], ["release"], ["privacy", 7, false]]); +}); + +test("防窥失败或超时需要明确继续,临时选择在下一次连接失效", async () => { + const privacyRequests: boolean[] = []; + const h = sessionHarness(async (_code, _resume, opts) => { + privacyRequests.push(opts.privacy); + return granted; + }); + const s = h.session; + s.code = "482913"; + s.hostKey = granted.hostKey; + s.state = "live"; + h.store.devices = [{ code: s.code, os: granted.hostOs, hostKey: granted.hostKey, autoPrivacy: true }]; + + await s.open(); + assert.equal(s.privacyBlock, "waiting"); + h.timers.at(-1)!(); + assert.equal(s.privacyBlock, "inactive"); + s.continueWithoutPrivacy(); + assert.equal(s.privacyBlock, null); + assert.deepEqual(h.calls.at(-1), ["clipboardSync", 7, true]); + + s.sid = null; + await s.start(); + assert.deepEqual(privacyRequests, [true, true]); + assert.equal(s.privacyBlock, "waiting"); + h.event({ type: "privacy", state: "notAllowed", detail: null }); + assert.equal(s.privacyBlock, "inactive"); + assert.equal(h.store.devices[0].autoPrivacy, true); +}); + +test("桌面自动防窥允许配对握手,也保留无认证信息时的操作限制", async () => { + for (const [kind, hostKey, pairing, autoPrivacy, request, blocked] of [ + ["desktop", granted.hostKey, null, true, true, true], + ["desktop", "ef".repeat(32), "654321", true, true, true], + ["desktop", null, null, true, false, true], + ["desktop", granted.hostKey, null, false, false, false], + ["web", granted.hostKey, null, true, false, false], + ] as const) { + const h = sessionHarness(async (_code, _resume, opts) => { + assert.equal(Boolean(opts.privacy), request); + assert.equal(opts.pairing, pairing); + return granted; + }, kind); + h.session.code = "482913"; + h.session.hostKey = hostKey; + h.session.pairing = pairing; + h.store.devices = [{ code: h.session.code, os: granted.hostOs, hostKey: granted.hostKey, autoPrivacy }]; + await h.session.open(); + assert.equal(Boolean(h.session.privacyBlock), blocked); + } +}); + +test("保存启用期间的新连接仍受防窥保护,手动重连沿用当前会话的请求", async () => { + const requests: boolean[] = []; + const h = sessionHarness(async (_code, _resume, opts) => { + requests.push(opts.privacy); + return granted; + }); + const s = h.session; + s.code = "482913"; + s.hostKey = granted.hostKey; + h.store.devices = [{ code: s.code, os: granted.hostOs, hostKey: granted.hostKey, autoPrivacy: false }]; + h.store.autoPrivacyWrites.set(s.code, "enabling"); + await s.open(); + assert.equal(s.privacyBlock, "waiting"); + + h.store.autoPrivacyWrites.clear(); + s.sid = null; + s.state = "closed"; + s.reconnect(); + await new Promise(setImmediate); + assert.equal(s.privacyBlock, null); + assert.deepEqual(requests, [true, false]); + + h.event({ type: "privacy", state: "on", detail: null }); + s.sid = null; + s.state = "closed"; + s.reconnect(); + await new Promise(setImmediate); + assert.deepEqual(requests, [true, false, true]); +}); + test("stale completion cannot finish a newer attempt", () => { const attempt = new ConnectionAttempt(); const old = attempt.begin(); diff --git a/crates/airhand-link/src/secure.rs b/crates/airhand-link/src/secure.rs index 4d948518..e0f56ca0 100644 --- a/crates/airhand-link/src/secure.rs +++ b/crates/airhand-link/src/secure.rs @@ -1239,11 +1239,18 @@ mod tests { let (c, h) = run(&gate, &me, Some(stale), None).await; assert_eq!(problem(c), Problem::HostKeyChanged); assert!(h.is_err()); - let (c, _) = run(&gate, &me, Some(stale), Some("000000")).await; + let intro = ControllerIntro { + privacy: true, + ..test_intro() + }; + let (c, h) = run_with(&gate, &me, Some(stale), Some("000000"), intro.clone()).await; assert_eq!(problem(c), Problem::PairingFailed); - let (c, h) = run(&gate, &me, Some(stale), Some("123456")).await; + assert!(h.is_err()); + let (c, h) = run_with(&gate, &me, Some(stale), Some("123456"), intro).await; assert_eq!(c.unwrap().secured.peer, *gate.me.public()); - assert_eq!(h.unwrap().admission, Admission::Paired); + let h = h.unwrap(); + assert_eq!(h.admission, Admission::Paired); + assert!(h.intro.privacy); } #[tokio::test] diff --git a/docs/usage.md b/docs/usage.md index cba25420..6cb864d8 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -342,6 +342,7 @@ Send this computer's microphone to the remote computer: programs there (meetings Keeps the people at the remote computer from seeing what you do: all of its monitors go blank and its keyboard and mouse stop working, so only you can see and control it. Toolbar shield button → **Privacy mode**; on a phone (Android, iPhone / iPad) it's the round button on the edge of the picture → **Privacy mode**, with the current state under the switch. +- To **turn on privacy mode when connecting**, hover over a paired Windows computer or Mac in the desktop console's **My devices** and click the shield. The saved device keeps this preference after pairing again. The console waits for the remote computer to confirm privacy mode before allowing remote input. If privacy mode is off, you can disconnect or choose **Continue with remote screen visible** for this session. - Windows hosts have to be installed for all users with the [virtual display](#virtual-display) driver; Mac hosts have to allow Airhand Accessibility (which controlling their keyboard and mouse needs anyway). Otherwise the switch is greyed out and the menu says why. There's no such button for Linux and phones - **Windows**: turning it on switches the remote computer to a virtual display (at the resolution of its main monitor), the only display left on its desktop, with its own monitors taken off (no signal); this takes a few seconds. You see and control that virtual display. The Start menu, UAC prompts, the lock screen and the mouse pointer are all on it too, nothing shows on the remote monitors. The remote keyboard and mouse are blocked, except Ctrl+Alt+Del (Windows' secure attention sequence): it only switches to the secure desktop, which doesn't show on the remote monitors either - **Mac**: it's on right away, and you keep seeing and controlling the Mac's own displays, unchanged; at the Mac they go fully black (the backlight stays on), with a black window over each of them as well (only your side doesn't see it). The remote keyboard, mouse and trackpad (media keys and gestures included) are blocked. For what it can't block, see [Known limitations](limitations.md#macos) diff --git a/docs/usage.zh-CN.md b/docs/usage.zh-CN.md index b0bf4373..414943b1 100644 --- a/docs/usage.zh-CN.md +++ b/docs/usage.zh-CN.md @@ -342,6 +342,7 @@ rm -rf "${XDG_CONFIG_HOME:-$HOME/.config}/airhand" # 删除当前用户的配 让对方电脑前的人看不到你在做什么:对方所有的显示器黑屏,对方的键盘鼠标不起作用,只有你看得到、操作得了。工具栏的盾牌按钮 → **防窥模式**;手机上(Android、iPhone / iPad)是画面边上的圆钮 → **防窥模式**,开关下面写着现在的状态。 +- 在桌面控制台的**我的设备**里,把指针移到已配对的 Windows 或 Mac 上,再点旁边的盾牌,就能设置**连接时自动开启**。这条设备记录的设置在重新配对后仍然有效。控制台等被控端确认防窥已开启后才允许远程操作。如果防窥没有开启,可以断开,或者点**继续(对方屏幕可见)**。选择继续只影响本次会话。 - Windows 被控端要为所有用户安装、安装时装上了[虚拟显示器](#虚拟显示器)驱动;Mac 被控端要允许 Airhand 使用“辅助功能”(操作它的键盘鼠标本来就要)。不满足时开关是灰的,菜单里写着为什么。对方是 Linux、手机时没有这个按钮 - **Windows**:打开时对方启用一块虚拟显示器(分辨率和对方的主显示器一样),只留它在桌面上,把本机的显示器都撤下来(没有信号),要几秒钟;你看到、操作的就是这块虚拟显示器。开始菜单、UAC 确认框、锁屏、鼠标指针也都在它上面,对方的显示器上什么都没有。对方的键盘鼠标被挡住,但 Ctrl+Alt+Del 挡不住(Windows 的安全键):按了只是切到安全桌面,对方的显示器上也看不到 - **Mac**:马上就打开,你看到、操作的还是对方原来的显示器,画面不变;对方的显示器调成全黑(背光还亮着),每个显示器上还盖着一个黑色的窗口(只有你这边看不到它)。对方的键盘、鼠标、触控板(包括媒体键、手势)被挡住。挡不住的情况见[已知限制](limitations.zh-CN.md#macos)