Skip to content

Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools

fix(viewer): read-only tokens don't unlock; wrong tokens can't lock out right ones; tokens stay off plain http (#89)

Qinghe Li075befbc8785
diff --git a/apps/iphone-control/src/agent.rs b/apps/iphone-control/src/agent.rs
index cfa9c99..334a56b 100644
--- a/apps/iphone-control/src/agent.rs
+++ b/apps/iphone-control/src/agent.rs
@@ -78,10 +78,44 @@ pub struct Agents {
workdir: PathBuf,
}
+/// The agent's working directory under `base`: this user's own (0700, not a link). The agent reads what is there
+/// (`CLAUDE.md`, `AGENTS.md`, `.claude/`), so in a shared directory such as `/tmp` a name made by someone else first
+/// isn't used: then one made just now, which nobody else can have
+fn private_dir(base: &Path) -> std::io::Result<PathBuf> {
+ use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
+ let uid = unsafe { libc::getuid() };
+ let make = |dir: &Path| std::fs::DirBuilder::new().mode(0o700).create(dir);
+ let dir = base.join(format!("iphone-control-agent-{uid}"));
+ match make(&dir) {
+ Ok(()) => return Ok(dir),
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
+ Err(e) => return Err(e),
+ }
+ let m = std::fs::symlink_metadata(&dir)?;
+ if m.file_type().is_dir() && m.uid() == uid {
+ // made by an earlier version, with the default permissions
+ if m.mode() & 0o077 != 0 {
+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700))?;
+ }
+ return Ok(dir);
+ }
+ tracing::warn!("{} isn't this user's own directory: the agent works in a new one", dir.display());
+ for i in 0.. {
+ let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.subsec_nanos());
+ let fresh = base.join(format!("iphone-control-agent-{uid}-{}-{nanos}-{i}", std::process::id()));
+ match make(&fresh) {
+ Ok(()) => return Ok(fresh),
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && i < 100 => {}
+ Err(e) => return Err(e),
+ }
+ }
+ unreachable!("returns from the loop")
+}
+
impl Agents {
pub fn new(socket: &Path) -> anyhow::Result<Arc<Self>> {
- let workdir = std::env::temp_dir().join(format!("iphone-control-agent-{}", unsafe { libc::getuid() }));
- std::fs::create_dir_all(&workdir)?;
+ let base = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|p| p.is_absolute());
+ let workdir = private_dir(&base.unwrap_or_else(std::env::temp_dir))?;
Ok(Arc::new(Self { exe: std::env::current_exe()?, socket: socket.to_path_buf(), workdir }))
}
@@ -461,6 +495,29 @@ mod tests {
}
}
+ #[test]
+ fn the_agent_works_in_a_directory_of_its_own() {
+ use std::os::unix::fs::{MetadataExt, PermissionsExt};
+ let base = std::env::temp_dir().join(format!("ictl-agent-dir-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&base);
+ std::fs::create_dir_all(&base).unwrap();
+ let mine = private_dir(&base).unwrap();
+ assert_eq!(std::fs::metadata(&mine).unwrap().mode() & 0o777, 0o700);
+ // an earlier version's, with the default permissions
+ std::fs::set_permissions(&mine, std::fs::Permissions::from_mode(0o755)).unwrap();
+ assert_eq!(private_dir(&base).unwrap(), mine);
+ assert_eq!(std::fs::metadata(&mine).unwrap().mode() & 0o777, 0o700);
+ // the name taken by something that isn't a directory of ours (here: a link to one)
+ std::fs::remove_dir(&mine).unwrap();
+ let elsewhere = base.join("elsewhere");
+ std::fs::create_dir(&elsewhere).unwrap();
+ std::os::unix::fs::symlink(&elsewhere, &mine).unwrap();
+ let fresh = private_dir(&base).unwrap();
+ assert!(fresh != mine && fresh.starts_with(&base) && !fresh.starts_with(&elsewhere));
+ assert!(std::fs::symlink_metadata(&fresh).unwrap().is_dir());
+ std::fs::remove_dir_all(base).unwrap();
+ }
+
#[test]
fn claude_lines() {
let a = json!({"type": "assistant", "message": {"content": [{"type": "text", "text": "先看屏幕"}, {"type": "tool_use", "name": "x"}]}});
diff --git a/apps/iphone-control/src/remote.rs b/apps/iphone-control/src/remote.rs
index 34e2186..ec4b417 100644
--- a/apps/iphone-control/src/remote.rs
+++ b/apps/iphone-control/src/remote.rs
@@ -37,16 +37,28 @@ impl Remote {
/// `url`: the viewer's address; `ca`: a certificate to trust besides the system's (the viewer's self-signed one)
pub fn new(url: &str, ca: Option<&Path>, login: Option<String>) -> anyhow::Result<Self> {
let base = url.trim().trim_end_matches('/').trim_end_matches("/mcp").to_owned();
- if !base.starts_with("http://") && !base.starts_with("https://") {
+ let parsed = reqwest::Url::parse(&base).ok().filter(|u| matches!(u.scheme(), "http" | "https") && u.has_host());
+ let Some(parsed) = parsed else {
bail!(ictl_l10n::trf!(
"--url 要是控制台的地址,比如 https://192.168.1.5:8200:{url}",
"--url takes the viewer's address, such as https://192.168.1.5:8200: {url}"
));
+ };
+ // the login token and the task's token go with every request: in the clear only to this machine
+ if parsed.scheme() == "http" && !loopback(&parsed) {
+ bail!(ictl_l10n::trf!(
+ "另一台机器的控制台要用 https://(令牌不能明文发出去):{url}",
+ "Another machine's viewer takes https:// (tokens aren't sent in the clear): {url}"
+ ));
}
// reqwest is built without a crypto provider of its own (main installs ring; so does this, for tests)
let _ = rustls::crypto::ring::default_provider().install_default();
- // the viewer is on this network: never through a proxy from the environment
- let mut b = reqwest::Client::builder().no_proxy().connect_timeout(Duration::from_secs(10));
+ // the viewer is on this network: never through a proxy from the environment. Redirects aren't followed: the
+ // tokens would go along to wherever it points
+ let mut b = reqwest::Client::builder()
+ .no_proxy()
+ .redirect(reqwest::redirect::Policy::none())
+ .connect_timeout(Duration::from_secs(10));
if let Some(ca) = ca {
let pem = std::fs::read(ca).with_context(|| ca.display().to_string())?;
let cert = reqwest::Certificate::from_pem(&pem).with_context(|| ca.display().to_string())?;
@@ -169,9 +181,22 @@ impl Remote {
}
}
+/// `localhost`, `127.0.0.0/8` or `[::1]`
+fn loopback(url: &reqwest::Url) -> bool {
+ let host = url.host_str().unwrap_or_default().trim_start_matches('[').trim_end_matches(']');
+ host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|a| a.is_loopback())
+}
+
/// What the viewer said when it refused
pub async fn failure(r: reqwest::Response) -> String {
let status = r.status();
+ if status.is_redirection() {
+ let to = r.headers().get(reqwest::header::LOCATION).and_then(|v| v.to_str().ok()).unwrap_or_default();
+ return ictl_l10n::trf!(
+ "控制台要求换个地址(HTTP {status} → {to}):把 --url 改成这个地址再试",
+ "The viewer points elsewhere (HTTP {status} → {to}): use that address as --url and try again"
+ );
+ }
let text = r.text().await.unwrap_or_default();
let message = serde_json::from_str::<Value>(&text).ok().and_then(|v| v["message"].as_str().map(str::to_owned));
let why = message.unwrap_or_else(|| text.trim().chars().take(200).collect());
@@ -283,5 +308,11 @@ mod tests {
let env = r.env();
assert!(env.contains(&(MCP_URL_ENV, "https://nas.local:8202/mcp".into())));
assert!(Remote::new("nas.local:8202", None, None).is_err());
+ // tokens in the clear only to this machine
+ assert!(Remote::new("http://192.168.1.5:8202", None, None).is_err());
+ assert!(Remote::new("http://nas.local:8202", None, None).is_err());
+ for local in ["http://127.0.0.1:8202", "http://localhost:8202", "http://[::1]:8202"] {
+ assert!(Remote::new(local, None, None).is_ok(), "{local}");
+ }
}
}
diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs
index 1df68ce..d010cce 100644
--- a/apps/iphone-control/src/viewer.rs
+++ b/apps/iphone-control/src/viewer.rs
@@ -426,6 +426,42 @@ async fn handle(mut client: Conn, ctx: &Ctx, head: Vec<u8>, req: Head, mut body:
);
return json_reply(&mut client, 403, &json!({"ok": false, "message": m})).await;
}
+ let routed = route(client, ctx, head, req, body, &pass);
+ match (&ctx.auth, &pass.who) {
+ // a stream (the picture, a task's events, `/mcp`, a task's lease) ends when its token is removed or replaced
+ (Some(a), Some(who)) => tokio::select! {
+ r = routed => r,
+ () = revoked(a, who) => {
+ tracing::info!("viewer: the token “{}” is gone, so its connection was closed", who.name);
+ Ok(())
+ }
+ },
+ _ => routed.await,
+ }
+}
+
+/// How often an open connection's token is looked for ([`revoked`])
+const TOKEN_RECHECK: Duration = Duration::from_secs(5);
+
+/// Returns once `who`'s token is no longer there
+async fn revoked(a: &auth::Auth, who: &auth::Who) {
+ loop {
+ tokio::time::sleep(TOKEN_RECHECK).await;
+ if !a.knows(who) {
+ return;
+ }
+ }
+}
+
+/// A logged-in request, by its method and path
+async fn route(
+ mut client: Conn,
+ ctx: &Ctx,
+ head: Vec<u8>,
+ req: Head,
+ mut body: Vec<u8>,
+ pass: &Pass,
+) -> anyhow::Result<()> {
let path = req.path.as_str();
match (req.method.as_str(), path) {
("GET", "/") => reply(&mut client, 200, "text/html; charset=utf-8", ctx.page.as_bytes()).await,
@@ -467,8 +503,8 @@ async fn handle(mut client: Conn, ctx: &Ctx, head: Vec<u8>, req: Head, mut body:
"status" => status(ctx).await,
"devices" => devices(ctx).await,
"apps" => apps(ctx, req.query("system").is_some_and(|v| v == "1")).await,
- "elements" => elements(ctx, &req.query("filter").unwrap_or_default()).await,
- "alert" => alert(ctx).await,
+ "elements" => elements(ctx, &req.query("filter").unwrap_or_default(), pass.watches()).await,
+ "alert" => alert(ctx, pass.watches()).await,
"agent/backends" => Ok(json!({"backends": agent::backends()})),
// every task the daemon knows, also those started elsewhere (`iphone-control task run`)
"agent/tasks" => protocol::task_list(&ctx.socket).await.map(|t| json!({"tasks": t})),
@@ -936,6 +972,11 @@ impl Pass {
/// A read-only token may look (any `GET` but `/mcp`, and report how much of a video it read); an agent only works
/// for its task
+ /// A read-only token: may look, but nothing is done on the phone for it (not even unlocking it)
+ fn watches(&self) -> bool {
+ self.who.as_ref().is_some_and(|w| w.role == auth::Role::View)
+ }
+
fn may(&self, req: &Head) -> bool {
match &self.who {
Some(w) if w.role == auth::Role::View => {
@@ -994,18 +1035,16 @@ async fn login_gate(
v => v,
};
// an agent on another machine: its task's token instead of a login, only for that task (docs/task-control.md 7.6)
- if v != Verdict::Limited
- && TASK_PATHS.contains(&req.path.as_str())
+ // (checked even after too many wrong tokens: a running task isn't cut off by someone sending wrong ones)
+ if TASK_PATHS.contains(&req.path.as_str())
&& let Some(t) = &req.task_token
{
- if a.limited() {
- v = Verdict::Limited;
- } else if protocol::task_check(&ctx.socket, t).await.is_ok() {
+ if protocol::task_check(&ctx.socket, t).await.is_ok() {
return Ok(Some(Pass { who: None, agent: true }));
- } else {
- // a wrong task token counts like a wrong login
- a.failed();
- v = Verdict::Wrong;
+ }
+ // a wrong task token counts like a wrong login (once, when no login token was sent with it)
+ if v == Verdict::Missing {
+ v = a.failed();
}
}
let status = if v == Verdict::Limited { 429 } else { 401 };
@@ -1396,8 +1435,9 @@ async fn apps(ctx: &Ctx, system: bool) -> Result<Value, String> {
}
/// `{ elements: [{ type, label, x, y, width, height }] }`, `x`/`y` the top-left corner in points
-async fn elements(ctx: &Ctx, filter: &str) -> Result<Value, String> {
- let req = Request::ListElements { filter: filter.to_owned(), limit: ELEMENT_LIMIT, max_age_ms: 0 };
+/// `keep_locked`: a read-only visitor, for whom a locked phone isn't unlocked
+async fn elements(ctx: &Ctx, filter: &str, keep_locked: bool) -> Result<Value, String> {
+ let req = Request::ListElements { filter: filter.to_owned(), limit: ELEMENT_LIMIT, max_age_ms: 0, keep_locked };
let text = text_of(&ctx.socket, req, true).await?;
Ok(json!({"elements": text.lines().filter_map(parse_element).collect::<Vec<_>>()}))
}
@@ -1409,10 +1449,10 @@ async fn elements(ctx: &Ctx, filter: &str) -> Result<Value, String> {
/// while WDA's screenshot had it. The page asks while it shows that video and puts the alert next to the picture.
/// `AlertCheck` is two quick WDA calls (the foreground app; the alert's text only when SpringBoard is in front); the
/// element tree is only read when there is an alert
-async fn alert(ctx: &Ctx) -> Result<Value, String> {
+async fn alert(ctx: &Ctx, keep_locked: bool) -> Result<Value, String> {
let check = text_of(&ctx.socket, Request::AlertCheck, true).await?;
let Some(text) = alert_text(&check) else { return Ok(json!({"alert": null})) };
- let req = Request::ListElements { filter: String::new(), limit: ELEMENT_LIMIT, max_age_ms: 0 };
+ let req = Request::ListElements { filter: String::new(), limit: ELEMENT_LIMIT, max_age_ms: 0, keep_locked };
// without its buttons the page still says there is an alert
let els: Vec<Value> = text_of(&ctx.socket, req, true)
.await
diff --git a/apps/iphone-control/src/viewer/auth.rs b/apps/iphone-control/src/viewer/auth.rs
index fe94ac0..e02731a 100644
--- a/apps/iphone-control/src/viewer/auth.rs
+++ b/apps/iphone-control/src/viewer/auth.rs
@@ -16,8 +16,9 @@
//! and ends when the token is replaced or removed. Programs send `Authorization: Bearer <token>`.
//!
//! Wrong tokens are counted for the whole page, not per address (behind a proxy every address is `127.0.0.1`): after
-//! [`MAX_FAILURES`] in a minute, tokens aren't checked until the minute is over. A token is 256 random bits, so
-//! this only makes guessing slower still; a session that is already logged in isn't affected.
+//! [`MAX_FAILURES`] in a minute, a wrong one is answered with 429 until the minute is over. A right token always gets
+//! in: a token is 256 random bits, so nobody guesses one, and refusing right tokens too would let anyone who can reach
+//! the page lock out every program (`mcp --url`, remote tasks) by sending wrong ones.
use std::collections::VecDeque;
use std::io;
@@ -34,7 +35,7 @@ pub const TOKENS_FILE: &str = "viewer-tokens.json";
const OLD_TOKEN_FILE: &str = "viewer-token";
/// The first token's name
pub const OWNER: &str = "owner";
-/// Wrong tokens in [`WINDOW`] before tokens are refused until it is over
+/// Wrong tokens in [`WINDOW`] before wrong ones are answered with 429 until it is over
const MAX_FAILURES: usize = 20;
const WINDOW: Duration = Duration::from_secs(60);
/// How long a browser stays logged in
@@ -204,15 +205,25 @@ fn write_private(file: &Path, data: &[u8]) -> io::Result<()> {
}
/// Who a request is logged in as
-#[derive(Debug, Clone, PartialEq, Eq)]
+#[derive(Debug, Clone)]
pub struct Who {
pub name: String,
pub role: Role,
/// With `Authorization: Bearer` (a program), not a session cookie (a browser): no `Origin` needed, since a web
/// page can't make a browser send it
pub bearer: bool,
+ /// The token's session value: tells whether this very token is still there ([`Auth::knows`])
+ session: String,
+}
+
+impl PartialEq for Who {
+ fn eq(&self, other: &Self) -> bool {
+ (&self.name, self.role, self.bearer) == (&other.name, other.role, other.bearer)
+ }
}
+impl Eq for Who {}
+
/// What a request shows of the login
#[derive(Debug, PartialEq, Eq)]
pub enum Verdict {
@@ -244,7 +255,7 @@ impl Known {
}
fn who(&self, bearer: bool) -> Who {
- Who { name: self.name.clone(), role: self.role, bearer }
+ Who { name: self.name.clone(), role: self.role, bearer, session: self.session.clone() }
}
}
@@ -295,6 +306,12 @@ impl Auth {
t
}
+ /// Whether the token `who` logged in with is still there (not removed or replaced since): a stream it opened
+ /// ends when it isn't
+ pub fn knows(&self, who: &Who) -> bool {
+ self.tokens().known.iter().any(|k| same(&who.session, &k.session))
+ }
+
/// The request's session cookie or `Authorization: Bearer` token
pub fn check(&self, head: &[u8]) -> Verdict {
let text = String::from_utf8_lossy(head);
@@ -322,21 +339,15 @@ impl Auth {
}
}
- /// A token someone typed or sent: right, wrong (counted), or not checked now
+ /// A token someone typed or sent: right, or wrong (counted; [`Verdict::Limited`] after too many)
pub fn try_token(&self, presented: &str) -> Verdict {
- if self.limited() {
- return Verdict::Limited;
- }
// every token is compared, so the time doesn't tell how many there are before the right one
let tokens = self.tokens();
let found =
tokens.known.iter().fold(None, |found, k| if same(presented.trim(), &k.token) { Some(k) } else { found });
match found {
Some(k) => Verdict::Ok(k.who(true)),
- None => {
- self.failed();
- Verdict::Wrong
- }
+ None => self.failed(),
}
}
@@ -350,9 +361,16 @@ impl Auth {
f.len() >= MAX_FAILURES
}
- /// A wrong token (or task token, see `viewer::login_gate`) was sent
- pub fn failed(&self) {
- self.failures.lock().unwrap_or_else(|p| p.into_inner()).push_back(Instant::now());
+ /// A wrong token (or task token, see `viewer::login_gate`) was sent: [`Verdict::Wrong`], or
+ /// [`Verdict::Limited`] once there were too many
+ pub fn failed(&self) -> Verdict {
+ let limited = self.limited();
+ let mut f = self.failures.lock().unwrap_or_else(|p| p.into_inner());
+ // counted up to the limit only: a flood doesn't keep it going after the minute
+ if !limited {
+ f.push_back(Instant::now());
+ }
+ if limited { Verdict::Limited } else { Verdict::Wrong }
}
/// `Set-Cookie` for a browser that logged in with the token named `name`; `secure` over HTTPS (the browser then
@@ -460,7 +478,7 @@ mod tests {
}
fn who(name: &str, role: Role, bearer: bool) -> Verdict {
- Verdict::Ok(Who { name: name.into(), role, bearer })
+ Verdict::Ok(Who { name: name.into(), role, bearer, session: String::new() })
}
#[test]
@@ -533,34 +551,46 @@ mod tests {
let auth = Auth::load(tmp.path(), 8202).unwrap();
let owner = get(tmp.path(), OWNER).unwrap();
let session = auth.set_cookie(OWNER, false).split(';').next().unwrap().to_owned();
- assert!(matches!(auth.try_token(&owner.token), Verdict::Ok(_)));
+ let Verdict::Ok(was) = auth.try_token(&owner.token) else { panic!("the owner's token") };
+ assert!(auth.knows(&was));
// a file's time is often only accurate to the second
std::thread::sleep(Duration::from_millis(1100));
let tv = add(tmp.path(), "tv", Role::View).unwrap();
- assert_eq!(auth.try_token(&tv.token), who("tv", Role::View, true));
+ let Verdict::Ok(watching) = auth.try_token(&tv.token) else { panic!("tv's token") };
+ assert_eq!(watching, Who { name: "tv".into(), role: Role::View, bearer: true, session: String::new() });
std::thread::sleep(Duration::from_millis(1100));
let renewed = renew(tmp.path(), OWNER).unwrap();
assert_eq!(auth.try_token(&owner.token), Verdict::Wrong, "the old token");
assert_eq!(auth.check(&head(&[&format!("Cookie: {session}")])), Verdict::Missing, "and its sessions");
- assert!(matches!(auth.try_token(&renewed.token), Verdict::Ok(_)));
+ assert!(!auth.knows(&was), "what it opened ends: the token was replaced");
+ let Verdict::Ok(now) = auth.try_token(&renewed.token) else { panic!("the new token") };
+ assert!(auth.knows(&now) && auth.knows(&watching));
+ std::thread::sleep(Duration::from_millis(1100));
+ remove(tmp.path(), "tv").unwrap();
+ assert!(!auth.knows(&watching), "and when it was removed");
}
#[test]
- fn wrong_tokens_are_limited_for_everyone() {
+ fn wrong_tokens_are_limited_but_right_ones_get_in() {
let auth = Auth::fixed(vec![entry(OWNER, Role::Operate, 'a')], 8202);
let session = auth.set_cookie(OWNER, false).split(';').next().unwrap().to_owned();
for _ in 0..MAX_FAILURES {
assert_eq!(auth.try_token("guess"), Verdict::Wrong);
}
assert_eq!(auth.try_token("guess"), Verdict::Limited);
- assert_eq!(auth.try_token(&"a".repeat(64)), Verdict::Limited, "not even checked for a minute");
+ // sending wrong tokens doesn't lock out those who have the right one
+ assert!(matches!(auth.try_token(&"a".repeat(64)), Verdict::Ok(_)), "a right token gets in");
assert!(
matches!(auth.check(&head(&[&format!("Cookie: {session}")])), Verdict::Ok(_)),
"logged-in browsers go on"
);
+ for _ in 0..100 {
+ auth.try_token("guess");
+ }
+ assert_eq!(auth.failures.lock().unwrap().len(), MAX_FAILURES, "a flood isn't counted past the limit");
// the minute is over
auth.failures.lock().unwrap().iter_mut().for_each(|t| *t -= WINDOW + Duration::from_secs(1));
- assert!(matches!(auth.try_token(&"a".repeat(64)), Verdict::Ok(_)));
+ assert_eq!(auth.try_token("guess"), Verdict::Wrong);
}
#[test]
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index 0648270..8c4fcdc 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -966,8 +966,8 @@ impl Daemon {
Request::Screenshot { region } => {
return self.screenshot(g, region).await.unwrap_or_else(Response::error);
}
- Request::ListElements { filter, limit, max_age_ms } => {
- self.list_elements(g, &filter, limit, Duration::from_millis(max_age_ms)).await
+ Request::ListElements { filter, limit, max_age_ms, keep_locked } => {
+ self.list_elements(g, &filter, limit, Duration::from_millis(max_age_ms), keep_locked).await
}
Request::Tap { x, y } => self.tap(g, x, y, view).await,
Request::TapElement { text, index, max_age_ms } => {
diff --git a/crates/ictl-daemon/src/tasks.rs b/crates/ictl-daemon/src/tasks.rs
index edcc2cc..4ae8ea8 100644
--- a/crates/ictl-daemon/src/tasks.rs
+++ b/crates/ictl-daemon/src/tasks.rs
@@ -1317,7 +1317,7 @@ mod tests {
assert!(message(admit(&ts, &tap(), Some(&t.token)).await).contains("重新看"));
assert!(admit(&ts, &tap(), Some(&t.token)).await.is_err(), "until it has looked, not just once");
assert!(admit(&ts, &Request::Status, Some(&t.token)).await.is_ok(), "status isn't acting");
- let look = Request::ListElements { filter: String::new(), limit: 10, max_age_ms: 0 };
+ let look = Request::ListElements { filter: String::new(), limit: 10, max_age_ms: 0, keep_locked: false };
assert!(admit(&ts, &look, Some(&t.token)).await.is_ok());
assert!(admit(&ts, &tap(), Some(&t.token)).await.is_err(), "a look let through isn't a look that worked");
t.observed();
diff --git a/crates/ictl-daemon/src/tools.rs b/crates/ictl-daemon/src/tools.rs
index 6122879..d3b011a 100644
--- a/crates/ictl-daemon/src/tools.rs
+++ b/crates/ictl-daemon/src/tools.rs
@@ -298,8 +298,22 @@ impl Daemon {
filter: &str,
limit: usize,
max_age: Duration,
+ keep_locked: bool,
) -> Result<String, String> {
- self.ensure_unlocked(g).await?;
+ if keep_locked {
+ // only looking (a read-only viewer): the passcode isn't typed for it
+ if let Some(w) = self.wda(g)
+ && w.locked().await.map_err(|e| e.to_string())?
+ {
+ return Err(ictl_l10n::tr!(
+ "手机锁着:只看不操作时不会替你解锁",
+ "The phone is locked: it isn't unlocked for someone who only watches"
+ )
+ .into());
+ }
+ } else {
+ self.ensure_unlocked(g).await?;
+ }
let els = self.tree(g, max_age).await?.elements;
let shown: Vec<&elements::Element> =
if filter.is_empty() { els.iter().collect() } else { elements::filter(&els, filter) };
diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs
index 89c16b9..a2f5354 100644
--- a/crates/ictl-mcp/src/lib.rs
+++ b/crates/ictl-mcp/src/lib.rs
@@ -635,9 +635,12 @@ pub fn to_request(name: &str, args: &Map<String, Value>) -> Result<Request, Stri
};
Request::Screenshot { region }
}
- "iphone_list_elements" => {
- Request::ListElements { filter: a.s_or("filter", "")?, limit: a.u_or("limit", 150)?, max_age_ms: 0 }
- }
+ "iphone_list_elements" => Request::ListElements {
+ filter: a.s_or("filter", "")?,
+ limit: a.u_or("limit", 150)?,
+ max_age_ms: 0,
+ keep_locked: false,
+ },
"iphone_tap" => Request::Tap { x: a.f("x")?, y: a.f("y")? },
"iphone_tap_element" => Request::TapElement { text: a.s("text")?, index: a.u_or("index", 0)?, max_age_ms: 0 },
"iphone_long_press" => Request::LongPress { x: a.f("x")?, y: a.f("y")?, seconds: a.f_or("seconds", 1.0)? },
@@ -1066,7 +1069,14 @@ impl McpServer {
match then {
Then::Elements(filter) => {
// Settle 刚读过元素树,直接用它
- match self.call(&Request::ListElements { filter, limit: THEN_LIMIT, max_age_ms: THEN_SETTLE_MS }).await
+ match self
+ .call(&Request::ListElements {
+ filter,
+ limit: THEN_LIMIT,
+ max_age_ms: THEN_SETTLE_MS,
+ keep_locked: false,
+ })
+ .await
{
Response::Text { text: t, .. } => {
text +=
@@ -1261,7 +1271,7 @@ mod tests {
fn defaults_match_toolkit() {
assert_eq!(
to_request("iphone_list_elements", &Map::new()).unwrap(),
- Request::ListElements { filter: String::new(), limit: 150, max_age_ms: 0 }
+ Request::ListElements { filter: String::new(), limit: 150, max_age_ms: 0, keep_locked: false }
);
assert_eq!(
to_request("iphone_swipe", &args(json!({"from_x": 1, "from_y": 2, "to_x": 3, "to_y": 4}))).unwrap(),
@@ -1401,7 +1411,7 @@ mod tests {
);
assert_eq!(
to_request("iphone_list_elements", &args(json!({"limit": null}))).unwrap(),
- Request::ListElements { filter: String::new(), limit: 150, max_age_ms: 0 }
+ Request::ListElements { filter: String::new(), limit: 150, max_age_ms: 0, keep_locked: false }
);
}
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index 86e0e97..15e4834 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -71,6 +71,9 @@ pub enum Request {
/// 用于「等界面稳定」之后紧接着列元素:Settle 刚读过
#[serde(default)]
max_age_ms: u64,
+ /// 手机锁着时不自动解锁,直接报错(控制台的只读令牌:只能看,不能让守护进程输入锁屏密码)
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ keep_locked: bool,
},
Tap {
x: f64,