From 208d37b7d89ad4bdc710f6dffd0584135c764b4c Mon Sep 17 00:00:00 2001 From: tongtongstudio Date: Sat, 14 Nov 2026 04:06:01 +0800 Subject: [PATCH] Add opt-in physical USB device enrollment and remembered choices in 0.2.7 --- AGENTS.md | 2 +- Cargo.lock | 13 +- Cargo.toml | 2 +- README.md | 4 +- agent/Cargo.toml | 1 + agent/src/main.rs | 1 + agent/src/managed.rs | 99 ++++++++- agent/src/usb_discovery.rs | 194 ++++++++++++++++++ crates/ads-management/src/lib.rs | 25 ++- ctl/src/main.rs | 33 +++ desktop/Ads.Desktop/Ads.Desktop.csproj | 2 +- desktop/Ads.Desktop/AgentManagementView.axaml | 2 +- .../Ads.Desktop/AgentManagementViewModel.cs | 16 ++ docs/agent-management.md | 26 ++- docs/verification.md | 10 + flutter_manager/lib/ui/agent_model.dart | 34 +++ flutter_manager/lib/ui/agent_view.dart | 15 ++ flutter_manager/pubspec.yaml | 2 +- flutter_manager/test/agent_test.dart | 35 +++- tests/agent_adb_presence.py | 17 ++ 20 files changed, 515 insertions(+), 18 deletions(-) create mode 100644 agent/src/usb_discovery.rs diff --git a/AGENTS.md b/AGENTS.md index 158c0c0..4f37224 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ | 目录 | 作用 | 主要语言/格式 | | --- | --- | --- | | `android_agent/` | 手机直接联网的 Android 设备端,Kotlin 传统 View、前台服务与 Rust JNI 网关;不申请运行时权限 | Kotlin、Rust、Gradle Kotlin DSL、XML、TOML | -| `agent/` | 无界面多手机守护程序 ads-agent、独立监督进程、私有 IPC 和远程管理;兼容单设备参数;源码在 `src/` | Rust、TOML | +| `agent/` | 无界面多手机守护程序 ads-agent、独立监督进程、私有 IPC、远程管理与可选真实 USB 自动注册;兼容单设备参数;源码在 `src/` | Rust、TOML | | `ctl/` | adsctl 命令行管理端,本机/远程设备、配置、日志、重启及系统启动托管;源码在 `src/` | Rust、TOML | | `usb/` | 可选 ads-usb 本机虚拟 ADB USB 设备,提供回环 USB/IP、描述符和 ADB 帧适配;Windows 使用已签名 USBip 虚拟控制器,Linux 使用内核 vhci_hcd(CLI) | Rust、TOML | | `client/` | 本地守护程序 ads-client,维护设备租约、监听本地端口并自动调用 adb connect;源码在 `src/` | Rust、TOML | diff --git a/Cargo.lock b/Cargo.lock index 35ba504..281bfe9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,7 +4,7 @@ version = 4 [[package]] name = "ads-agent" -version = "0.2.6" +version = "0.2.7" dependencies = [ "ads-core", "ads-management", @@ -13,6 +13,7 @@ dependencies = [ "libc", "serde", "serde_json", + "sha2", "tokio", "tracing", "tracing-subscriber", @@ -21,7 +22,7 @@ dependencies = [ [[package]] name = "ads-client" -version = "0.2.6" +version = "0.2.7" dependencies = [ "ads-core", "anyhow", @@ -32,7 +33,7 @@ dependencies = [ [[package]] name = "ads-core" -version = "0.2.6" +version = "0.2.7" dependencies = [ "anyhow", "bytes", @@ -51,7 +52,7 @@ dependencies = [ [[package]] name = "ads-management" -version = "0.2.6" +version = "0.2.7" dependencies = [ "ads-core", "anyhow", @@ -67,7 +68,7 @@ dependencies = [ [[package]] name = "ads-usb" -version = "0.2.6" +version = "0.2.7" dependencies = [ "anyhow", "clap", @@ -78,7 +79,7 @@ dependencies = [ [[package]] name = "adsctl" -version = "0.2.6" +version = "0.2.7" dependencies = [ "ads-core", "ads-management", diff --git a/Cargo.toml b/Cargo.toml index 9cbbe5b..3359cbc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ members = ["crates/ads-core", "agent", "client", "usb", "crates/ads-management", resolver = "2" [workspace.package] -version = "0.2.6" +version = "0.2.7" edition = "2021" license = "MIT" diff --git a/README.md b/README.md index af82dc2..9b392f3 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Windows 现支持可选的 [USB ADB 模拟](docs/windows-usb.md),默认网络 | 目录 | 作用 | 主要语言/格式 | | --- | --- | --- | | `android_agent/` | 手机直接联网的 Android 设备端,Kotlin 传统 View、前台服务与 Rust JNI 网关;不申请运行时权限 | Kotlin、Rust、Gradle Kotlin DSL、XML、TOML | -| `agent/` | 无界面多手机守护程序 ads-agent、独立监督进程、私有 IPC 和远程管理;兼容单设备参数;源码在 `src/` | Rust、TOML | +| `agent/` | 无界面多手机守护程序 ads-agent、独立监督进程、私有 IPC、远程管理与可选真实 USB 自动注册;兼容单设备参数;源码在 `src/` | Rust、TOML | | `ctl/` | adsctl 命令行管理端,本机/远程设备、配置、日志、重启及系统启动托管;源码在 `src/` | Rust、TOML | | `usb/` | 可选 ads-usb 本机虚拟 ADB USB 设备,提供回环 USB/IP、描述符和 ADB 帧适配;Windows 使用已签名 USBip 虚拟控制器,Linux 使用内核 vhci_hcd(CLI) | Rust、TOML | | `client/` | 本地守护程序 ads-client,维护设备租约、监听本地端口并自动调用 adb connect;源码在 `src/` | Rust、TOML | @@ -251,4 +251,4 @@ Android APK 交付目录固定为 `bin/apk/`(APK 格式,无业务源码, Linux 桌面 deb 安装后自动通过 update-alternatives 注册 `/usr/bin/adsctl`、`ads-agent`、`ads-client`、`ads-usb`,支持多包共存及卸载回退;无需手动创建链接,详见 [Linux 打包](docs/linux-packaging.md)。 -已配置的 Agent ADB 设备会持续检测上下线,离线撤销注册、恢复沿用原 ID;同一 ADB server 共享查询,未配置的新手机仍需手动添加。详见 [Agent 管理与设备监听](docs/agent-management.md#持续监听设备上下线026)。 +已配置的 Agent ADB 设备会持续检测上下线,离线撤销注册、恢复沿用原 ID;同一 ADB server 共享查询,默认未配置的新手机仍需手动添加;0.2.7 可按 Agent 开启真实 USB 自动注册。详见 [Agent 管理与设备监听](docs/agent-management.md#持续监听设备上下线026)。 diff --git a/agent/Cargo.toml b/agent/Cargo.toml index 88b78f8..668b360 100644 --- a/agent/Cargo.toml +++ b/agent/Cargo.toml @@ -13,6 +13,7 @@ tracing.workspace = true ads-management = { path = "../crates/ads-management" } serde.workspace = true serde_json.workspace = true +sha2 = "0.10" tracing-subscriber.workspace = true [target.'cfg(windows)'.dependencies] diff --git a/agent/src/main.rs b/agent/src/main.rs index 64a7dcd..59cd4aa 100644 --- a/agent/src/main.rs +++ b/agent/src/main.rs @@ -2,6 +2,7 @@ mod adb_monitor; mod gateway; mod managed; mod supervisor; +mod usb_discovery; use ads_core::{valid_device_id, validate_token, NetworkArgs}; use ads_management::{credential, AgentConfig}; use anyhow::{bail, Context, Result}; diff --git a/agent/src/managed.rs b/agent/src/managed.rs index 1c8b1e6..494c811 100644 --- a/agent/src/managed.rs +++ b/agent/src/managed.rs @@ -89,6 +89,7 @@ struct Runtime { restart: watch::Sender, supervised: bool, instance: String, + ready: std::sync::atomic::AtomicBool, } impl Runtime { fn reconcile(&self, state: &mut State) { @@ -105,6 +106,7 @@ impl Runtime { .clone() .unwrap_or_else(|| adb_server.clone()) }) + .chain(state.config.auto_register_usb.then(|| adb_server.clone())) .collect(); state.monitors.retain(|server, _| servers.contains(server)); for server in servers { @@ -242,6 +244,9 @@ impl Runtime { if config.devices.iter().any(|d| d.id == device.id) { bail!("device ID already exists") }; + if let Some(serial) = &device.adb_serial { + config.ignored_usb_serials.retain(|s| s != serial); + } config.devices.push(device); } Request::DeviceRemove { id } => { @@ -259,7 +264,16 @@ impl Runtime { .context("device not found")? .enabled = enabled; } - Request::ConfigSet { config: new } => { + Request::ConfigSet { + config: new, + expected_config, + } => { + if expected_config + .as_ref() + .is_some_and(|expected| expected != &state.config) + { + bail!("Agent 配置已变化,请刷新后重试,避免覆盖自动发现或其他管理操作") + } if new.id != config.id { bail!("agent ID is immutable; initialize a separate agent to change identity") }; @@ -267,6 +281,16 @@ impl Runtime { } _ => bail!("unsupported operation"), } + // Deleting an ADB entry means "do not add it again" even after a restart. + for old in &state.config.devices { + if !config.devices.iter().any(|d| d.id == old.id) { + if let Some(serial) = &old.adb_serial { + if !config.ignored_usb_serials.contains(serial) { + config.ignored_usb_serials.push(serial.clone()); + } + } + } + } config.validate()?; let changed_network = config.server != state.config.server || config.connect_address != state.config.connect_address @@ -286,6 +310,63 @@ impl Runtime { } } } + async fn discover_usb(&self) -> Result<()> { + if !self.ready.load(std::sync::atomic::Ordering::Acquire) { + return Ok(()); + } + { + let state = self.state.lock().await; + if !state.config.auto_register_usb + || !crate::usb_discovery::local_server(&state.config.adb_server) + { + return Ok(()); + } + // Native PnP enumeration is only needed for new eligible ADB serials. + // Previewing candidates does not authorize or persist any device. + let online = match state + .monitors + .get(&state.config.adb_server) + .map(|m| m.receiver.borrow().clone()) + { + Some(crate::adb_monitor::Snapshot::Devices(devices)) => devices + .into_iter() + .filter(|(_, s)| s == "device") + .map(|(serial, _)| serial) + .collect(), + _ => return Ok(()), + }; + let mut preview = state.config.clone(); + if crate::usb_discovery::add_online(&mut preview, &online, &online) == 0 { + return Ok(()); + } + } + let physical = crate::usb_discovery::physical_serials().await?; + let mut state = self.state.lock().await; + let online = match state + .monitors + .get(&state.config.adb_server) + .map(|m| m.receiver.borrow().clone()) + { + Some(crate::adb_monitor::Snapshot::Devices(devices)) => devices + .into_iter() + .filter(|(_, s)| s == "device") + .map(|(s, _)| s) + .collect(), + _ => return Ok(()), + }; + let mut config = state.config.clone(); + let count = crate::usb_discovery::add_online(&mut config, &online, &physical); + if count == 0 { + return Ok(()); + } + config.validate()?; + ads_management::save_private(&self.path, &serde_json::to_vec_pretty(&config)?)?; + state.config = config; + state.revision += 1; + self.reconcile(&mut state); + tracing::info!(count, "physical USB devices automatically added"); + Ok(()) + } async fn handle(&self, request: Request) -> Response { match self.execute(request).await { Ok(value) => value, @@ -375,6 +456,7 @@ pub async fn run(path: PathBuf, config: AgentConfig, token: String) -> Result Result Result{result?;false},_=&mut networking=>false,result=restarting.changed()=>{result?;sleep(Duration::from_millis(400)).await;true},result=crate::supervisor::shutdown()=>{result?;false}}; + let discovery = async { + let mut ticks = interval(Duration::from_secs(5)); + loop { + ticks.tick().await; + if let Err(error) = runtime.discover_usb().await { + tracing::warn!(%error,"USB auto-registration scan failed"); + } + } + }; + tokio::pin!(discovery); + let restart = tokio::select! {_=&mut discovery=>false,result=&mut ipc=>{result?;false},_=&mut networking=>false,result=restarting.changed()=>{result?;sleep(Duration::from_millis(400)).await;true},result=crate::supervisor::shutdown()=>{result?;false}}; let mut state = runtime.state.lock().await; state.workers.clear(); state.monitors.clear(); diff --git a/agent/src/usb_discovery.rs b/agent/src/usb_discovery.rs new file mode 100644 index 0000000..1385bf6 --- /dev/null +++ b/agent/src/usb_discovery.rs @@ -0,0 +1,194 @@ +//! Fail closed: only native USB devices on a physical host controller are eligible. +use ads_management::{AgentConfig, DeviceConfig}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeSet; + +pub fn local_server(server: &str) -> bool { + server + .rsplit_once(':') + .is_some_and(|(host, _)| matches!(host, "127.0.0.1" | "localhost" | "[::1]")) +} +fn allowed_serial(serial: &str) -> bool { + !serial.is_empty() + && serial.len() <= 256 + && !serial.chars().any(char::is_control) + && !serial.to_ascii_lowercase().starts_with("ads-") + && !serial.starts_with("emulator-") + && !serial.contains(':') +} +pub fn add_online( + config: &mut AgentConfig, + online: &BTreeSet, + physical: &BTreeSet, +) -> usize { + if !config.auto_register_usb || !local_server(&config.adb_server) { + return 0; + } + let mut added = 0; + for serial in online.intersection(physical) { + if !allowed_serial(serial) + || config.ignored_usb_serials.contains(serial) + || config + .devices + .iter() + .any(|d| d.adb_serial.as_ref() == Some(serial)) + || config.devices.len() >= 128 + { + continue; + } + let id = config + .usb_device_ids + .get(serial) + .cloned() + .unwrap_or_else(|| { + let hash = Sha256::digest(format!("{}:{serial}", config.id).as_bytes()); + format!("usb-{:x}", hash)[..36].to_owned() + }); + if config.devices.iter().any(|d| d.id == id) + || (!config.usb_device_ids.contains_key(serial) && config.usb_device_ids.len() >= 512) + { + continue; + } + config.usb_device_ids.insert(serial.clone(), id.clone()); + config.devices.push(DeviceConfig { + id, + target: None, + adb_serial: Some(serial.clone()), + adb_server: None, + device_port: 5555, + enabled: true, + }); + added += 1; + } + added +} + +#[cfg(target_os = "linux")] +pub async fn physical_serials() -> anyhow::Result> { + tokio::task::spawn_blocking(|| { + let mut serials = BTreeSet::new(); + for entry in std::fs::read_dir("/sys/bus/usb/devices")? { + let Ok(path) = std::fs::canonicalize(entry?.path()) else { + continue; + }; + let name = path.to_string_lossy().to_ascii_lowercase(); + if name.contains("vhci") || !name.contains("/pci") { + continue; + } + let product = std::fs::read_to_string(path.join("product")).unwrap_or_default(); + if product.to_ascii_lowercase().contains("ads virtual") { + continue; + } + if let Ok(serial) = std::fs::read_to_string(path.join("serial")) { + let serial = serial.trim(); + if allowed_serial(serial) { + serials.insert(serial.to_owned()); + } + } + } + Ok(serials) + }) + .await? +} +#[cfg(windows)] +pub async fn physical_serials() -> anyhow::Result> { + // No interpolated serials or credentials; bounded child is killed on timeout/cancellation. + let script = r#" +$ErrorActionPreference='Stop' +[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false) +$devices=Get-PnpDevice -PresentOnly | Where-Object { $_.InstanceId -like 'USB\VID_*' -and $_.InstanceId -notlike '*&MI_*' } +foreach($d in $devices) { + if($d.FriendlyName -like '*ADS Virtual*') {continue} + $serial=($d.InstanceId -split '\\')[-1] + if($serial.Contains('&')) {continue} + $parent=$d.InstanceId;$physical=$false + for($i=0;$i -lt 16;$i++) { + if($parent -match '(?i)USBIP|VHCI|UDE|^ROOT\\') {break} + if($parent.StartsWith('PCI\',[StringComparison]::OrdinalIgnoreCase)) {$physical=$true;break} + $parent=(Get-PnpDeviceProperty -InstanceId $parent -KeyName 'DEVPKEY_Device_Parent' -ErrorAction SilentlyContinue).Data + if(!$parent) {break} + } + if($physical) {[Console]::WriteLine($serial)} +} +"#; + let exe = std::env::var_os("SystemRoot") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| r"C:\Windows".into()) + .join("System32/WindowsPowerShell/v1.0/powershell.exe"); + let mut command = tokio::process::Command::new(exe); + command + .args(["-NoProfile", "-NonInteractive", "-Command", script]) + .kill_on_drop(true); + command.creation_flags(0x08000000); + let output = + tokio::time::timeout(std::time::Duration::from_secs(15), command.output()).await??; + anyhow::ensure!(output.status.success(), "native USB inventory failed"); + Ok(String::from_utf8(output.stdout)? + .lines() + .map(str::trim) + .filter(|s| allowed_serial(s)) + .map(str::to_owned) + .collect()) +} +#[cfg(not(any(windows, target_os = "linux")))] +pub async fn physical_serials() -> anyhow::Result> { + anyhow::bail!("USB auto-registration requires Windows or Linux physical USB inventory") +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn registration_is_opt_in_and_preserves_user_choices() { + let mut c: AgentConfig = serde_json::from_value( + serde_json::json!({"id":"pc","name":"pc","server":"wss://example.com","devices":[]}), + ) + .unwrap(); + let online = [ + "real", + "ignored", + "ADS-test", + "emulator-5554", + "192.168.1.2:5555", + "unauthorized", + ] + .map(str::to_owned) + .into_iter() + .collect(); + let physical = [ + "real", + "ignored", + "ADS-test", + "emulator-5554", + "192.168.1.2:5555", + ] + .map(str::to_owned) + .into_iter() + .collect(); + assert_eq!(add_online(&mut c, &online, &physical), 0); + c.auto_register_usb = true; + c.ignored_usb_serials.push("ignored".into()); + assert_eq!(add_online(&mut c, &online, &physical), 1); + let id = c.devices[0].id.clone(); + c = serde_json::from_slice(&serde_json::to_vec(&c).unwrap()).unwrap(); + c.devices[0].enabled = false; + c.devices[0].adb_server = Some("localhost:5037".into()); + assert_eq!(add_online(&mut c, &online, &physical), 0); + assert!(!c.devices[0].enabled); + c.devices.clear(); + assert_eq!(add_online(&mut c, &online, &physical), 1); + assert_eq!(c.devices[0].id, id); + c.adb_server = "192.168.1.5:5037".into(); + c.devices.clear(); + assert_eq!(add_online(&mut c, &online, &physical), 0); + } +} + +#[cfg(all(test, windows))] +mod native_tests { + #[tokio::test] + async fn native_inventory_runs_without_a_visible_console() { + super::physical_serials() + .await + .expect("Windows PnP inventory"); + } +} diff --git a/crates/ads-management/src/lib.rs b/crates/ads-management/src/lib.rs index 7fe98b0..6c8d5f9 100644 --- a/crates/ads-management/src/lib.rs +++ b/crates/ads-management/src/lib.rs @@ -45,7 +45,7 @@ pub struct DeviceConfig { #[serde(default = "yes")] pub enabled: bool, } -#[derive(Clone, Serialize, Deserialize, Debug)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub struct AgentConfig { #[serde(default = "version")] @@ -61,6 +61,12 @@ pub struct AgentConfig { pub adb_server: String, #[serde(default)] pub devices: Vec, + #[serde(default)] + pub auto_register_usb: bool, + #[serde(default)] + pub ignored_usb_serials: Vec, + #[serde(default)] + pub usb_device_ids: std::collections::BTreeMap, } impl AgentConfig { pub fn network(&self) -> NetworkArgs { @@ -90,6 +96,21 @@ impl AgentConfig { if self.devices.len() > 128 { bail!("at most 128 devices per agent") } + if self.ignored_usb_serials.len() > 512 || self.usb_device_ids.len() > 512 { + bail!("at most 512 remembered USB devices") + } + for serial in self + .ignored_usb_serials + .iter() + .chain(self.usb_device_ids.keys()) + { + if serial.is_empty() || serial.len() > 256 || serial.chars().any(char::is_control) { + bail!("invalid remembered USB serial") + } + } + if self.usb_device_ids.values().any(|id| !valid_device_id(id)) { + bail!("invalid remembered USB ID") + } let mut ids = HashSet::new(); for device in &self.devices { if !valid_device_id(&device.id) || !ids.insert(&device.id) || device.device_port == 0 { @@ -156,6 +177,8 @@ pub enum Request { ConfigGet, ConfigSet { config: AgentConfig, + #[serde(default)] + expected_config: Option, }, Logs { #[serde(default)] diff --git a/ctl/src/main.rs b/ctl/src/main.rs index b4bffdb..ad72736 100644 --- a/ctl/src/main.rs +++ b/ctl/src/main.rs @@ -67,6 +67,15 @@ enum Agents { enum Devices { /// Discover devices already known to the Agent host ADB server Discover, + /// Enable or disable automatic registration of authorized physical USB phones + AutoUsb { + #[arg(value_parser=["on","off"])] + mode: String, + }, + /// Allow a previously removed USB phone to be registered again + Unignore { + serial: String, + }, List, Add { #[arg(long)] @@ -190,6 +199,9 @@ async fn main() -> Result<()> { allow_insecure: args.network.allow_insecure, adb_server: "127.0.0.1:5037".into(), devices: vec![], + auto_register_usb: false, + ignored_usb_serials: vec![], + usb_device_ids: Default::default(), }; cfg.validate()?; let source = args @@ -327,6 +339,26 @@ async fn main() -> Result<()> { enabled: true, }, }, + Devices::AutoUsb { mode } => { + let mut config: AgentConfig = + serde_json::from_value(invoke(&args, &Request::ConfigGet).await?.value()?)?; + let expected_config = Some(config.clone()); + config.auto_register_usb = mode == "on"; + Request::ConfigSet { + config, + expected_config, + } + } + Devices::Unignore { serial } => { + let mut config: AgentConfig = + serde_json::from_value(invoke(&args, &Request::ConfigGet).await?.value()?)?; + let expected_config = Some(config.clone()); + config.ignored_usb_serials.retain(|s| s != &serial); + Request::ConfigSet { + config, + expected_config, + } + } Devices::Remove { id } => Request::DeviceRemove { id }, Devices::Enable { id } => Request::DeviceEnable { id, enabled: true }, Devices::Disable { id } => Request::DeviceEnable { id, enabled: false }, @@ -338,6 +370,7 @@ async fn main() -> Result<()> { command: Config::Set { ref file }, } => Request::ConfigSet { config: AgentConfig::load(file)?, + expected_config: None, }, _ => unreachable!(), }; diff --git a/desktop/Ads.Desktop/Ads.Desktop.csproj b/desktop/Ads.Desktop/Ads.Desktop.csproj index f88fb93..8f7dccd 100644 --- a/desktop/Ads.Desktop/Ads.Desktop.csproj +++ b/desktop/Ads.Desktop/Ads.Desktop.csproj @@ -1,4 +1,4 @@ - 0.2.6WinExenet8.0enableenable + 0.2.7WinExenet8.0enableenable diff --git a/desktop/Ads.Desktop/AgentManagementView.axaml b/desktop/Ads.Desktop/AgentManagementView.axaml index 9ba0258..4bfa110 100644 --- a/desktop/Ads.Desktop/AgentManagementView.axaml +++ b/desktop/Ads.Desktop/AgentManagementView.axaml @@ -8,7 +8,7 @@ -