From 46a58fd33a97bd2fb0ad5f9f1246f5ea530cb5c0 Mon Sep 17 00:00:00 2001 From: cui Date: Fri, 4 Dec 2026 17:28:32 +0800 Subject: [PATCH 1/3] feat(client): remember privacy mode per device --- client/src-tauri/src/config.rs | 1 + client/src-tauri/src/devices.rs | 11 +++++ client/src/components/ConnectView.tsx | 32 +++++++++++-- client/src/components/SessionView.tsx | 8 ++-- client/src/lib/actions.ts | 2 + client/src/lib/api.ts | 2 + client/src/lib/devices.ts | 12 ++++- client/src/lib/messages.ts | 20 +++++++- client/src/lib/session.ts | 29 +++++++++++- client/src/locales/en.ts | 2 + client/src/locales/zh.ts | 2 + client/tests/devices.test.ts | 16 +++++++ client/tests/session.test.ts | 67 +++++++++++++++++++++++++-- docs/usage.md | 1 + docs/usage.zh-CN.md | 1 + 15 files changed, 190 insertions(+), 16 deletions(-) diff --git a/client/src-tauri/src/config.rs b/client/src-tauri/src/config.rs index 8cdc7a75..7efdf7c8 100644 --- a/client/src-tauri/src/config.rs +++ b/client/src-tauri/src/config.rs @@ -2026,6 +2026,7 @@ mod tests { quality: None, mouse: None, swap_ctrl_command: false, + auto_privacy: false, host_key: None, } } diff --git a/client/src-tauri/src/devices.rs b/client/src-tauri/src/devices.rs index 486e859c..3295148d 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` 的"端到端加密"): //! 之后只认它,对不上就警告。是公钥,不用加密。 @@ -74,6 +75,8 @@ pub struct Device { pub mouse: Option, #[serde(default)] pub swap_ctrl_command: bool, + #[serde(default)] + pub auto_privacy: bool, } /// 认识的鼠标模式(自动是默认,不记) @@ -177,6 +180,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), }) } @@ -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/components/ConnectView.tsx b/client/src/components/ConnectView.tsx index 400cff72..6b82b2df 100644 --- a/client/src/components/ConnectView.tsx +++ b/client/src/components/ConnectView.tsx @@ -2,19 +2,28 @@ // // 输入的内容放在 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, + 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(); @@ -428,6 +437,21 @@ function DeviceItem({ {!editing && ( + {api.kind === "desktop" && canAutoPrivacy(d) && ( + + )} + {!waiting && ( + + )} + + + + ); +} + /** 防窥模式现在怎么样。对方是 Mac 时不换虚拟显示器,开不了的原因也不一样 */ function privacyHint(s: RemoteSession): string { const mac = s.hostPlatform === "mac"; diff --git a/client/src/lib/devices.ts b/client/src/lib/devices.ts index 9b61c5d6..c06be4fa 100644 --- a/client/src/lib/devices.ts +++ b/client/src/lib/devices.ts @@ -46,8 +46,8 @@ export function remember( quality: seen.quality ?? old?.quality ?? null, mouse: seen.mouse ?? old?.mouse ?? null, swapCtrlCommand: seen.swapCtrlCommand ?? old?.swapCtrlCommand ?? false, - // 控制码相同、身份变了:不把自动防窥带到新的设备上 - autoPrivacy: old?.autoPrivacy === true && !!hostKey && old.hostKey === hostKey, + // 重新配对后,这条已保存设备仍使用原来的防窥偏好 + autoPrivacy: old?.autoPrivacy ?? false, // 对方的公钥:连上时确认过的(第一次连上、或者用户信任了新的身份)代替旧的 hostKey, }; diff --git a/client/src/lib/messages.ts b/client/src/lib/messages.ts index f1ed6db2..f5f150ff 100644 --- a/client/src/lib/messages.ts +++ b/client/src/lib/messages.ts @@ -31,8 +31,7 @@ export type LocalNotice = /** 对方的版本旧,不支持剪贴板里的文件 */ | { kind: "filesUnsupported" } /** 在这里的手柄上按了按钮,对方却接不了手柄(为什么见 gamepadHint) */ - | { kind: "gamepadUnavailable"; state: GamepadSupport; platform: Platform | null; detail: string | null } - | { kind: "autoPrivacyFailed"; state: PrivacyFailure; platform: Platform | null; detail: string | null }; + | { kind: "gamepadUnavailable"; state: GamepadSupport; platform: Platform | null; detail: string | null }; /** 被控端发来的"已恢复":只用来撤下之前的提示,本身不显示 */ export type RecoveredNotice = Extract; @@ -89,9 +88,6 @@ export function noticeText(n: SessionNotice): string { if (n.kind === "gamepadUnavailable") { return t("notice.gamepadUnavailable", { reason: gamepadHint(n.state, n.platform, n.detail) }); } - if (n.kind === "autoPrivacyFailed") { - return t("notice.autoPrivacyFailed", { reason: privacyFailureText(n.state, n.platform, n.detail) }); - } const { kind, ...params } = n; return t(`notice.${kind}` as const, params); } diff --git a/client/src/lib/session.ts b/client/src/lib/session.ts index 1e4b4986..467f0c89 100644 --- a/client/src/lib/session.ts +++ b/client/src/lib/session.ts @@ -48,7 +48,6 @@ import * as media from "./media"; import { AudioOutput } from "./audio"; import { MicCapture, type MicError } from "./mic"; import { ConnectionAttempt } from "./connection-attempt"; -import { canAutoPrivacy } from "./devices"; import { RemoteInput } from "./input"; import { gamepads, MAX_PADS, type GamepadTarget } from "./gamepad"; import type { AvSyncStats } from "./avsync"; @@ -102,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)。 @@ -161,6 +161,7 @@ export class RemoteSession implements GamepadTarget { zoom = 1; /** 双向同步剪贴板文本 */ clipboardSync = true; + private clipboardOn = true; /** 播放远程声音(用户开关;实际只在当前查看的会话上播放) */ audioEnabled = true; /** 音画同步开关(用户设置;实际只在播放声音时生效) */ @@ -179,8 +180,11 @@ export class RemoteSession implements GamepadTarget { privacyDetail: string | null = null; /** 要防窥模式(开关):重连时在连接选项里带上,对方就一直保持防窥。跟着对方说的状态变 */ privacyWanted = false; - /** 新连接请求了按设备保存的自动防窥,正在等被控端确认结果 */ - private autoPrivacyPending = false; + /** 要求被控端确认防窥后才允许操作 */ + private requirePrivacy = false; + private allowVisibleScreen = false; + private privacyWaitTimer?: number; + private privacyWaitOver = false; /** 对方能不能接本机的手柄(hello 之后对方会说);对方不能接(手机、版本旧)、还没说时为 null:不发手柄 */ gamepadState: GamepadSupport | null = null; /** 对方插不上虚拟手柄的原因(英文技术信息) */ @@ -362,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 }); }, @@ -410,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(); @@ -418,14 +422,57 @@ export class RemoteSession implements GamepadTarget { // ───────────────────────── 连接 ───────────────────────── - /** 主动发起连接时读设备偏好;断线自动重连沿用当前会话的开关 */ + /** 主动发起连接时读设备偏好 */ private useSavedPrivacy() { if (api.kind !== "desktop") return; const saved = store.get().devices.find((d) => d.code === this.code); - // 重新配对时不再校验保存的公钥,不能把之前的防窥设置带过去 - this.autoPrivacyPending = !this.pairing && saved?.autoPrivacy === true - && saved.hostKey === this.hostKey && canAutoPrivacy(saved); - this.privacyWanted = this.autoPrivacyPending; + this.requirePrivacy = saved?.autoPrivacy === true; + this.privacyWanted = false; + } + + 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(); } /** 建立连接。首次连接失败会抛出错误。 */ @@ -446,6 +493,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; // 手柄也是:对方说了能接才发 @@ -459,6 +509,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; @@ -472,11 +525,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 @@ -511,8 +564,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); } @@ -563,6 +619,7 @@ export class RemoteSession implements GamepadTarget { */ private scheduleRetry(reason: Problem | null) { if (this.disposed) return; + this.clearPrivacyWait(); this.sid = null; this.syncAudio(); this.syncMic(); @@ -641,6 +698,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); @@ -666,6 +724,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); @@ -713,19 +772,14 @@ export class RemoteSession implements GamepadTarget { this.syncMic(); break; case "privacy": { - // 被控端可能先报告当前处于关闭,再处理握手里的请求 - const initialOff = this.privacyState === null && ev.state === "off"; + const wasBlocked = !!this.privacyBlock; this.privacyState = ev.state; this.privacyDetail = ev.detail; - if (this.autoPrivacyPending && initialOff) break; - if (this.autoPrivacyPending && ev.state !== "starting") { - this.autoPrivacyPending = false; - if (ev.state === "unavailable" || ev.state === "notAllowed" || ev.state === "failed") { - this.notice = { kind: "autoPrivacyFailed", state: ev.state, platform: this.hostPlatform, detail: 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": { @@ -784,6 +838,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); @@ -809,6 +864,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(() => {}); } @@ -1324,7 +1380,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); @@ -1333,6 +1390,7 @@ export class RemoteSession implements GamepadTarget { /** 本机手柄的输入(GamepadHub 只在这个会话是正在操作的那个时交过来) */ gamepadInput(events: InputEvent[], urgent: boolean) { + if (this.privacyBlock) return; if (this.gamepadSendable) { this.enqueue(events, urgent); return; @@ -1361,13 +1419,16 @@ export class RemoteSession implements GamepadTarget { * 还没连上时只记下来,连上时在连接选项里告诉对方 */ setPrivacy(on: boolean) { - this.autoPrivacyPending = false; - if (this.notice?.kind === "autoPrivacyFailed") this.notice = null; + 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(); } @@ -1384,6 +1445,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; @@ -1636,10 +1698,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) ───────────────────────── /** @@ -1647,7 +1716,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" }; @@ -1750,7 +1819,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/locales/en.ts b/client/src/locales/en.ts index cc735a76..45f20728 100644 --- a/client/src/locales/en.ts +++ b/client/src/locales/en.ts @@ -333,6 +333,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)", @@ -399,7 +404,6 @@ const en: Record = { "notice.fileError": "Couldn't transfer “{name}”: {reason}", "notice.filesUnsupported": "The remote Airhand is too old to transfer files through the clipboard", "notice.gamepadUnavailable": "The gamepad isn't sent to the remote computer: {reason}", - "notice.autoPrivacyFailed": "Automatic privacy mode did not turn on. {reason}", "fileError.notFound": "it's gone (deleted or renamed)", "fileError.denied": "permission denied", "fileError.changed": "it changed after it was copied, copy it again", diff --git a/client/src/locales/zh.ts b/client/src/locales/zh.ts index 7676bea5..1b6b35ff 100644 --- a/client/src/locales/zh.ts +++ b/client/src/locales/zh.ts @@ -345,6 +345,11 @@ export default { // 防窥模式:对方的显示器黑屏、键盘鼠标不起作用,只有控制端看得到、操作得了 "privacy.toggle": "防窥模式", + "privacy.guardWaiting": "等待防窥开启,远程操作已暂停", + "privacy.guardInactive": "防窥未开启,远程操作已暂停", + "privacy.guardUnconfirmed": "被控端没有确认防窥已开启。", + "privacy.guardDisconnect": "断开连接", + "privacy.guardContinue": "继续(对方屏幕可见)", "privacy.off": "打开后,对方电脑的显示器全部黑屏、键盘鼠标不起作用,只有你看得到、操作得了(画面换成一块虚拟显示器)。断开连接后自动恢复", "privacy.starting": "正在打开:对方电脑正在换成虚拟显示器,要几秒钟", "privacy.on": "已打开:对方电脑的显示器全部黑屏、键盘鼠标不起作用。断开连接 30 秒后自动恢复(期间重连会接着保持)", @@ -418,7 +423,6 @@ export default { "notice.fileError": "“{name}”传不了:{reason}", "notice.filesUnsupported": "对方的 Airhand 版本较旧,不能通过剪贴板传文件", "notice.gamepadUnavailable": "手柄没有发给对方:{reason}", - "notice.autoPrivacyFailed": "自动防窥未开启。{reason}", "fileError.notFound": "文件不在了(被删除或改了名)", "fileError.denied": "没有权限读取", "fileError.changed": "复制之后文件变了,请重新复制", diff --git a/client/tests/devices.test.ts b/client/tests/devices.test.ts index 17323644..ce339855 100644 --- a/client/tests/devices.test.ts +++ b/client/tests/devices.test.ts @@ -58,7 +58,7 @@ test("Ctrl / Command 互换只记在选中的设备,重连保留,也能关 assert.equal(remember(list, { ...seen("482913"), swapCtrlCommand: false }, 4)[0].swapCtrlCommand, false); }); -test("自动防窥只保留给设置时的设备身份", () => { +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); @@ -67,7 +67,10 @@ test("自动防窥只保留给设置时的设备身份", () => { 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]]); - assert.equal(remember(list, { ...pc, hostKey: "ef".repeat(32) }, 4)[0].autoPrivacy, 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); diff --git a/client/tests/session.test.ts b/client/tests/session.test.ts index aab6ee74..774ba927 100644 --- a/client/tests/session.test.ts +++ b/client/tests/session.test.ts @@ -4,7 +4,6 @@ import fs from "node:fs"; import vm from "node:vm"; import { stripTypeScriptTypes } from "node:module"; import { ConnectionAttempt } from "../src/lib/connection-attempt.ts"; -import { canAutoPrivacy } from "../src/lib/devices.ts"; import { renderPlan } from "../src/lib/enhance.ts"; import { fitSize, stricter, viewMaxShort } from "../src/lib/fit.ts"; import * as media from "../src/lib/media.ts"; @@ -54,9 +53,10 @@ function sessionHarness( let resolve: (value: any) => void = () => {}; const calls: any[] = []; const timers: (() => void)[] = []; + const clipboardStarts: boolean[] = []; const storeState: any = { enhance: "off", decoders: ["h264"], devices: [] }; const sandbox: any = { console, performance, clearTimeout, setTimeout, queueMicrotask, ConnectionAttempt, - fitSize, stricter, viewMaxShort, renderPlan, media, hitTest, layoutTiles, placeDisplays, RemoteInput, canAutoPrivacy, devicePixelRatio: 1, + fitSize, stricter, viewMaxShort, renderPlan, media, hitTest, layoutTiles, placeDisplays, RemoteInput, devicePixelRatio: 1, codecUsable: () => true, bestCodec: () => "h264", store: { get: () => storeState }, // 手柄:记下交给了哪个会话、震动、要重发 @@ -70,8 +70,9 @@ function sessionHarness( toProblem: (e: any) => e, api: { kind, - connect: (c: any, o: any, _view: any, onEvent: any) => { + 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) => { @@ -79,6 +80,7 @@ function sessionHarness( 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], ); @@ -98,12 +100,12 @@ function sessionHarness( 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", () => { @@ -799,7 +801,7 @@ test("防窥模式:对方说了状态才能开;打开时先显示正在打 assert.equal(opts.privacy, false); }); -test("自动防窥通过握手请求,失败有提示,手动关闭只影响当前会话", async () => { +test("自动防窥等对方确认才放行输入,关闭后重新暂停操作", async () => { const privacyRequests: boolean[] = []; const h = sessionHarness(async (_code, _resume, opts) => { privacyRequests.push(opts.privacy); @@ -808,43 +810,87 @@ test("自动防窥通过握手请求,失败有提示,手动关闭只影响 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 }); - await s.start(); - assert.deepEqual(privacyRequests, [true, true], "初始关闭状态不会撤销尚未处理的请求"); + 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: "notAllowed", detail: null }); - assert.equal(s.notice?.kind, "autoPrivacyFailed"); - assert.equal(s.notice?.state, "notAllowed"); - await s.start(); - assert.equal(privacyRequests.at(-1), false, "断线自动重连不会重试被拒绝的请求"); - - s.sid = null; - s.state = "closed"; - s.reconnect(); - await new Promise((resolve) => setImmediate(resolve)); - assert.equal(privacyRequests.at(-1), true, "手动重新连接会读取已保存的偏好"); + 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); - await s.start(); - assert.equal(privacyRequests.at(-1), 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(privacyRequests.at(-1), true); + 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] of [ - ["desktop", "ef".repeat(32), null, true], - ["desktop", null, null, true], - ["desktop", granted.hostKey, "654321", true], - ["desktop", granted.hostKey, null, false], - ["web", granted.hostKey, null, 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.ok(!opts.privacy); + assert.equal(Boolean(opts.privacy), request); + assert.equal(opts.pairing, pairing); return granted; }, kind); h.session.code = "482913"; @@ -852,6 +898,7 @@ test("自动防窥只用于身份匹配、没有重新配对的桌面连接", as 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); } }); 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 a8c480ea..6cb864d8 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -342,7 +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 next connection to that device requests privacy mode automatically, and the shield in the toolbar shows when it is on. The toolbar switch controls the current session. If the computer's identity changes and you pair again, turn the device preference on again. +- 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 37c317f4..414943b1 100644 --- a/docs/usage.zh-CN.md +++ b/docs/usage.zh-CN.md @@ -342,7 +342,7 @@ rm -rf "${XDG_CONFIG_HOME:-$HOME/.config}/airhand" # 删除当前用户的配 让对方电脑前的人看不到你在做什么:对方所有的显示器黑屏,对方的键盘鼠标不起作用,只有你看得到、操作得了。工具栏的盾牌按钮 → **防窥模式**;手机上(Android、iPhone / iPad)是画面边上的圆钮 → **防窥模式**,开关下面写着现在的状态。 -- 在桌面控制台的**我的设备**里,把指针移到已配对的 Windows 或 Mac 上,再点旁边的盾牌,就能设置**连接时自动开启**。下次连接这台电脑时会自动请求防窥,工具栏里的盾牌显示是否已经开启。工具栏开关只控制当前会话。被控端换了身份并重新配对后,需要重新打开这台设备的自动防窥。 +- 在桌面控制台的**我的设备**里,把指针移到已配对的 Windows 或 Mac 上,再点旁边的盾牌,就能设置**连接时自动开启**。这条设备记录的设置在重新配对后仍然有效。控制台等被控端确认防窥已开启后才允许远程操作。如果防窥没有开启,可以断开,或者点**继续(对方屏幕可见)**。选择继续只影响本次会话。 - Windows 被控端要为所有用户安装、安装时装上了[虚拟显示器](#虚拟显示器)驱动;Mac 被控端要允许 Airhand 使用“辅助功能”(操作它的键盘鼠标本来就要)。不满足时开关是灰的,菜单里写着为什么。对方是 Linux、手机时没有这个按钮 - **Windows**:打开时对方启用一块虚拟显示器(分辨率和对方的主显示器一样),只留它在桌面上,把本机的显示器都撤下来(没有信号),要几秒钟;你看到、操作的就是这块虚拟显示器。开始菜单、UAC 确认框、锁屏、鼠标指针也都在它上面,对方的显示器上什么都没有。对方的键盘鼠标被挡住,但 Ctrl+Alt+Del 挡不住(Windows 的安全键):按了只是切到安全桌面,对方的显示器上也看不到 - **Mac**:马上就打开,你看到、操作的还是对方原来的显示器,画面不变;对方的显示器调成全黑(背光还亮着),每个显示器上还盖着一个黑色的窗口(只有你这边看不到它)。对方的键盘、鼠标、触控板(包括媒体键、手势)被挡住。挡不住的情况见[已知限制](limitations.zh-CN.md#macos) From c4b928854f6f2084c197a84fe862901947ee88d2 Mon Sep 17 00:00:00 2001 From: cui Date: Fri, 4 Dec 2026 18:07:52 +0800 Subject: [PATCH 3/3] fix(client): honor persisted privacy settings on startup and reconnect --- client/src-tauri/src/config.rs | 45 +++++++--- client/src-tauri/src/devices.rs | 28 +++--- client/src-tauri/src/lib.rs | 28 ++++-- client/src-tauri/src/winsvc/ipc.rs | 124 ++++++++++++++++++++++---- client/src/components/ConnectView.tsx | 52 +++++++++-- client/src/lib/actions.ts | 78 +++++++++++----- client/src/lib/session.ts | 9 +- client/src/lib/store.ts | 20 ++++- client/src/locales/en.ts | 5 ++ client/src/locales/zh.ts | 5 ++ client/tests/device-actions.test.ts | 115 ++++++++++++++++++++++++ client/tests/session.test.ts | 32 ++++++- 12 files changed, 452 insertions(+), 89 deletions(-) create mode 100644 client/tests/device-actions.test.ts diff --git a/client/src-tauri/src/config.rs b/client/src-tauri/src/config.rs index 7efdf7c8..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]) { @@ -2316,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)] @@ -2330,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( @@ -2345,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)] { @@ -2358,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 3295148d..23e32b39 100644 --- a/client/src-tauri/src/devices.rs +++ b/client/src-tauri/src/devices.rs @@ -29,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; @@ -122,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` 还没解密) @@ -226,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() 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 f8707980..b260c667 100644 --- a/client/src/components/ConnectView.tsx +++ b/client/src/components/ConnectView.tsx @@ -6,6 +6,7 @@ import { api, type SavedDevice } from "../lib/api"; import { fmtCode, forgetDevice, + loadDevices, openSession, openTerminal, renameDevice, @@ -32,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)[]>([]); // 新建连接标签总是有的时候才显示这一页;万一没有(例如状态不一致),补一个 @@ -60,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; @@ -88,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 }); }; @@ -241,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} /> ); @@ -281,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); @@ -339,6 +356,12 @@ function MyDevices({ )} + {privacySaveError && ( +
+ + {t("devices.privacySaveFailed")} +
+ )}
{shown.map((d) => ( @@ -350,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); @@ -370,6 +398,7 @@ function DeviceItem({ editing, onOpen, onTerminal, + onTogglePrivacy, onEdit, onForget, }: { @@ -380,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; @@ -442,14 +474,16 @@ function DeviceItem({ className="icon-btn subtle" aria-label={t("devices.autoPrivacy")} aria-pressed={d.autoPrivacy === true} - title={t("devices.autoPrivacy")} + aria-busy={savingPrivacy} + title={t(savingPrivacy ? "devices.privacySaving" : "devices.autoPrivacy")} + disabled={savingPrivacy} onKeyDown={(e) => e.stopPropagation()} onClick={(e) => { e.stopPropagation(); - setDeviceAutoPrivacy(d.code, !d.autoPrivacy); + onTogglePrivacy(); }} > - {d.autoPrivacy ? : } + {savingPrivacy ? : d.autoPrivacy ? : } )}