Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools
Rust ai-agentautomationclaudeclaude-codedockeriosiphonelinuxmcpmcp-servermodel-context-protocolrustwebdriveragent
feat(viewer): require a login for the page and /mcp (#79)
Qinghe Li8a6ee57f9c99
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b03ec5f..091ec3f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ All notable changes to this project are documented here. The format is based on### Added+- The viewer and its `/mcp` need a login, from this machine too (the viewer can't tell a local browser from a visit forwarded by frp, cloudflared or another reverse proxy). The token is made on the first start and kept in `viewer-token` in the data directory (0600); `iphone-control viewer token` shows it with links that log in here and on the local network and the command to connect to the HTTP MCP, and `--new` replaces it. A browser stays logged in for 30 days; programs and MCP clients send `Authorization: Bearer <token>`. After too many wrong tokens (20 in a minute) tokens aren't checked for a minute. The CLI, `iphone-control mcp` (stdio) and `task run` use the local Unix socket and are unaffected.- MCP over HTTP: `/mcp` (Streamable HTTP) on the viewer's port serves the same tools as `iphone-control mcp`, for clients that only take a URL and for agents on another computer on the local network (`--lan`, over HTTPS), e.g. `claude mcp add --transport http iphone http://127.0.0.1:8200/mcp`. A task's agent sends the task's token in the `Iphone-Control-Task-Token` header. No login, as for the viewer; `--mcp off` (`IPHONE_CONTROL_VIEWER_MCP=off`) turns it off.- The viewer opened to the local network (`--lan`) now speaks HTTPS, on the same port: opened from another machine the picture can be H.264 or the phone's own HEVC instead of MJPEG, and traffic is encrypted. It uses a self-signed certificate made on this machine (kept in `viewer-tls/` in the data directory and reused); the browser warns the first time, so check the SHA-256 fingerprint shown at startup or by `service status` and go on. `--tls-cert`/`--tls-key` (`IPHONE_CONTROL_VIEWER_TLS_CERT`/`_KEY`) use a certificate of your own. `http://` from the network is redirected to `https://`; `http://127.0.0.1` on this machine works as before. `--tls off` (`IPHONE_CONTROL_VIEWER_TLS=off`) goes back to HTTP. It isn't a login: anyone on the network who can reach the page can still control the phone.- `iphone-control service viewer install` runs the viewer as a background service of its own that starts at login (`uninstall`, `start`, `stop`, `restart` too). It reads its port and whether it is open to the local network from the settings file (`IPHONE_CONTROL_VIEWER_PORT`, new; `IPHONE_CONTROL_VIEWER_LAN`; `IPHONE_CONTROL_VIEWER_LAN_HOSTS`, new) and keeps the installing shell's `PATH` to find `claude` and `codex`. Updates stop it and start it again; an automatic update waits while an AI task runs.diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex 2229384..ca13fb8 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -8,6 +8,7 @@### 新增+- 控制台和它的 `/mcp` 要登录了,本机也一样(控制台分不清本机的浏览器和经 frp、cloudflared 等反向代理转发进来的访问)。令牌第一次启动时生成,存在数据目录的 `viewer-token`(0600);`iphone-control viewer token` 显示令牌、本机和局域网的登录链接以及接入 HTTP MCP 的命令,`--new` 换一个新令牌。浏览器登录一次后记住 30 天;程序和 MCP 客户端用 `Authorization: Bearer <令牌>`。输错太多次(一分钟 20 次)会暂停校验一分钟。命令行、`iphone-control mcp`(stdio)和 `task run` 走本机的 Unix socket,不受影响。- MCP over HTTP:控制台同一个端口上的 `/mcp`(Streamable HTTP)提供和 `iphone-control mcp` 一样的工具,只能填 URL 的客户端、局域网里另一台电脑上的 agent(`--lan`,走 HTTPS)都能接入,例如 `claude mcp add --transport http iphone http://127.0.0.1:8200/mcp`。任务里的 agent 在请求头 `Iphone-Control-Task-Token` 里带上任务口令。和控制台一样没有登录,`--mcp off`(`IPHONE_CONTROL_VIEWER_MCP=off`)关掉。- 控制台对局域网开放(`--lan`)时改用 HTTPS,还是同一个端口:局域网里打开时画面也能用 H.264 或手机自己的 HEVC,不再退回 MJPEG,传输也加了密。默认用本机生成的自签证书(存在数据目录的 `viewer-tls/`,一直沿用),浏览器第一次打开会提示不受信任,核对启动时或 `service status` 显示的 SHA-256 指纹后继续;也可以用 `--tls-cert`/`--tls-key`(`IPHONE_CONTROL_VIEWER_TLS_CERT`/`_KEY`)换成自己的证书。局域网来的 `http://` 跳转到 `https://`,本机的 `http://127.0.0.1` 照旧。`--tls off`(`IPHONE_CONTROL_VIEWER_TLS=off`)恢复成 HTTP。这不是登录:局域网里能连上的人照样能操作手机。- `iphone-control service viewer install` 把控制台装成登录后自动启动的后台服务(还有 `uninstall`、`start`、`stop`、`restart`)。端口和是否对局域网开放读设置文件(新增 `IPHONE_CONTROL_VIEWER_PORT`;`IPHONE_CONTROL_VIEWER_LAN`;新增 `IPHONE_CONTROL_VIEWER_LAN_HOSTS`),并记下安装时终端的 `PATH` 以找到 `claude` 和 `codex`。升级时先停下它、升级完再启动;有 AI 任务在跑时自动升级会推迟。diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rsindex 8eb1061..ae77d46 100644--- a/apps/iphone-control/src/main.rs+++ b/apps/iphone-control/src/main.rs@@ -112,7 +112,7 @@ enum Command {#[arg(long, env = "IPHONE_CONTROL_VIEWER_PORT", default_value_t = 8200)]port: u16,// from the settings file as 1/0, yes/no, on/off or true/false (a plain flag's parser only takes true/false)- #[arg(long, env = "IPHONE_CONTROL_VIEWER_LAN", value_parser = clap::builder::BoolishValueParser::new(), help = ictl_l10n::tr!("也对局域网开放(同一个端口,局域网里用 HTTPS;还没有登录:局域网里任何人都能操作手机),只接受局域网地址来的连接", "Also open to the local network (same port, HTTPS there; no login yet: anyone on the network can control the phone); only connections from local-network addresses"))]+ #[arg(long, env = "IPHONE_CONTROL_VIEWER_LAN", value_parser = clap::builder::BoolishValueParser::new(), help = ictl_l10n::tr!("也对局域网开放(同一个端口,局域网里用 HTTPS,要令牌登录:iphone-control viewer token),只接受局域网地址来的连接", "Also open to the local network (same port, HTTPS there, login with the token: iphone-control viewer token); only connections from local-network addresses"))]lan: bool,#[arg(long = "lan-host", value_name = "HOST", env = "IPHONE_CONTROL_VIEWER_LAN_HOSTS", value_delimiter = ',', help = ictl_l10n::tr!("--lan 时还认可的主机名(可写多次);本机主机名、<主机名>.local 和各网卡 IP 已自动认可", "With --lan, another host name the page answers to (repeatable); this machine's name, <name>.local and its addresses are already accepted"))]lan_hosts: Vec<String>,@@ -124,6 +124,8 @@ enum Command {tls_key: Option<PathBuf>,#[arg(long, env = "IPHONE_CONTROL_VIEWER_MCP", value_name = "on|off", default_value = "on", action = clap::ArgAction::Set, value_parser = clap::builder::BoolishValueParser::new(), help = ictl_l10n::tr!("同一个端口上的 MCP(HTTP):/mcp,本机和(--lan 时)局域网的客户端用 URL 接入;off 关掉", "MCP over HTTP on the same port: /mcp, for clients on this machine and (with --lan) the local network that connect by URL; off turns it off"))]mcp: bool,+ #[command(subcommand)]+ action: Option<ViewerAction>,},#[command(about = ictl_l10n::tr!("AI 任务:在任务里运行外部 agent(task run),查看、暂停、接管、停止、确认任务", "AI tasks: run an external agent in a task (task run); list, pause, take over, stop and confirm tasks"))]Task {@@ -183,6 +185,15 @@ enum ServiceAction {},}+#[derive(Subcommand)]+enum ViewerAction {+ #[command(about = ictl_l10n::tr!("显示控制台的登录令牌、点开就能登录的链接和 HTTP MCP 的接入方式;--new 换一个新令牌(所有已登录的浏览器都要重新登录)", "Show the viewer's login token, links that log in and how to connect to its HTTP MCP; --new replaces the token (every browser has to log in again)"))]+ Token {+ #[arg(long)]+ new: bool,+ },+}+#[derive(Subcommand)]enum ViewerServiceAction {#[command(about = ictl_l10n::tr!("装成登录后自动启动的服务并启动;会记下当前终端的 PATH(找 claude、codex 用),PATH 变了再装一次", "Set up the service that starts at login and start it; it keeps this shell's PATH (to find claude and codex), so install again if that changes"))]@@ -313,9 +324,12 @@ async fn run() -> anyhow::Result<()> {Command::Devices => print_text(&cli.socket, Request::ListDevices).await,Command::Select { device } => print_text(&cli.socket, Request::SelectDevice { device }).await,Command::WdaBridge { port } => wda_bridge(&cli.socket, port).await,- Command::Viewer { port, lan, lan_hosts, tls, tls_cert, tls_key, mcp } => {+ Command::Viewer { port, lan, lan_hosts, tls, tls_cert, tls_key, mcp, action } => {let tls = viewer::tls::Setting { mode: tls, cert: tls_cert, key: tls_key };- viewer::run(&cli.socket, &cli.data_dir, port, lan, &lan_hosts, &tls, mcp).await+ match action {+ Some(ViewerAction::Token { new }) => viewer_token(&cli.data_dir, port, lan, &lan_hosts, &tls, mcp, new),+ None => viewer::run(&cli.socket, &cli.data_dir, port, lan, &lan_hosts, &tls, mcp).await,+ }}Command::Task { action } => task::run(&cli.socket, action).await,#[cfg(feature = "debug-cmds")]@@ -491,6 +505,68 @@ async fn service_cmd(socket: &Path, data_dir: &Path, action: ServiceAction) -> aOk(())}+/// `viewer token`: the login token, links that log in (with the viewer's own settings) and the HTTP MCP setup+fn viewer_token(+ data_dir: &Path,+ port: u16,+ lan: bool,+ lan_hosts: &[String],+ tls: &viewer::tls::Setting,+ mcp: bool,+ new: bool,+) -> anyhow::Result<()> {+ let token = if new { viewer::auth::replace(data_dir)? } else { viewer::auth::load_or_create(data_dir)? };+ let file = viewer::auth::token_file(data_dir);+ println!("{}", ictl_l10n::trf!("令牌 {token}(存在 {})", "Token {token} (kept in {})", file.display()));+ println!(+ "{}",+ ictl_l10n::trf!(+ "本机 http://127.0.0.1:{port}/?token={token}",+ "Here http://127.0.0.1:{port}/?token={token}"+ )+ );+ let scheme = if tls.enabled(lan) { "https" } else { "http" };+ if lan {+ for a in viewer::lan_addresses(lan_hosts) {+ println!(+ "{}",+ ictl_l10n::trf!(+ "局域网 {scheme}://{a}:{port}/?token={token}",+ "Network {scheme}://{a}:{port}/?token={token}"+ )+ );+ }+ }+ if mcp {+ println!(+ "{}",+ ictl_l10n::trf!(+ "MCP claude mcp add --transport http iphone http://127.0.0.1:{port}/mcp --header \"Authorization: Bearer {token}\"",+ "MCP claude mcp add --transport http iphone http://127.0.0.1:{port}/mcp --header \"Authorization: Bearer {token}\""+ )+ );+ }+ println!(+ "{}",+ ictl_l10n::tr!(+ "链接里带着令牌:别发到聊天或公开的地方。打开一次后浏览器会记住登录(30 天),地址栏里的令牌会被去掉。",+ "The links carry the token: don't paste them into chats or anywhere public. Opened once, the browser stays logged in (30 days) and the token leaves the address bar."+ )+ );+ if new {+ println!(+ "{}",+ ictl_l10n::tr!(+ "已换成新令牌,之前登录的浏览器和 MCP 客户端都要用新令牌。控制台服务在运行就会重启;手动运行的 viewer 要自己重启。",+ "The token was replaced: browsers and MCP clients logged in before need the new one. A running viewer service is restarted; restart a viewer you started by hand yourself."+ )+ );+ // a running viewer reads the token when it starts+ service::restart_viewer_if_running();+ }+ Ok(())+}+fn viewer_service_cmd(action: ViewerServiceAction) -> anyhow::Result<()> {let none = || {anyhow::anyhow!(@@ -513,8 +589,8 @@ fn viewer_service_cmd(action: ViewerServiceAction) -> anyhow::Result<()> {"{}",if lan {ictl_l10n::tr!(- "已对局域网开放(IPHONE_CONTROL_VIEWER_LAN),还没有登录:只在可信的网络里开。",- "Open to the local network (IPHONE_CONTROL_VIEWER_LAN), with no login yet: only on a trusted network."+ "已对局域网开放(IPHONE_CONTROL_VIEWER_LAN)。登录用的令牌:iphone-control viewer token。",+ "Open to the local network (IPHONE_CONTROL_VIEWER_LAN). The login token: iphone-control viewer token.")} else {ictl_l10n::tr!(@@ -1268,7 +1344,7 @@ mod tests {std::env::set_var("IPHONE_CONTROL_VIEWER_LAN_HOSTS", "nas.example,nas2");}match super::Cli::try_parse_from(["iphone-control", "viewer"]).map(|c| c.command) {- Ok(Some(super::Command::Viewer { port, lan, lan_hosts, .. })) => (port, lan, lan_hosts),+ Ok(Some(super::Command::Viewer { port, lan, lan_hosts, action: None, .. })) => (port, lan, lan_hosts),other => panic!("{lan:?}: {:?}", other.err()),}};diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.htmlindex 512e84f..3c6785c 100644--- a/apps/iphone-control/src/viewer.html+++ b/apps/iphone-control/src/viewer.html@@ -1115,7 +1115,7 @@ const LANG = (() => {return v === 'en' || v === 'zh' ? v : document.documentElement.dataset.lang === 'en' ? 'en' : 'zh';})();document.documentElement.lang = LANG === 'en' ? 'en' : 'zh-CN';-const EN = {"任务范围":"Task scope","所有 App":"All apps","任务只在这些 App 里操作":"The task only works in these apps","到了别的 App,每一步都先等你确认。不选就不限制。":"In any other app, each step waits for you first. Pick none for no limit.","任务只在这些 App 里操作:":"The task only works in: ","任务可以操作所有 App;点这里限定范围":"The task may use any app; click to limit it","已选":"Picked","不限制":"No limit","读不到 App 列表:":"Can't read the app list: ","正在读取 App…":"Reading apps…","只在":"Only in","AI 任务进行中:要自己点,先接管。":"An AI task is running: take over to tap it yourself.","实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮":"The live picture doesn't show this system alert; a button here taps it on the phone"," · 演示数据":" · demo data"," 等":" and more","<div class=\"ph-kb\" data-type=\"Keyboard\">键盘</div>":"<div class=\"ph-kb\" data-type=\"Keyboard\">Keyboard</div>","<li class=\"empty-note\">打开这一页时会读取已安装的 App。</li>":"<li class=\"empty-note\">The installed apps are read when this tab opens.</li>","<li class=\"sr-only\">正在读取 App 列表…</li>":"<li class=\"sr-only\">Reading the app list…</li>","<li class=\"sr-only\">正在读取元素…</li>":"<li class=\"sr-only\">Reading elements…</li>","<option>没有可用的 AI</option>":"<option>No AI available</option>","<p class=\"empty-note\">正在连接 iphone-control 服务…</p>":"<p class=\"empty-note\">Connecting to the iphone-control service…</p>","<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>演示模式</span></span>":"<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>Demo</span></span>","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 在等你确认一步操作,确认前画面保持锁定。":"The AI is waiting for you to confirm a step; the screen stays locked until you do.","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认前画面保持锁定。":"The screen stays locked until you confirm.","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 <code>iphone-control sign</code>,用免费 Apple ID 签名并安装。":"Run <code>iphone-control sign</code> to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 <code>iphone-control setup --reconfigure</code> 选「手机」,在设备上点「信任」。":"Run <code>iphone-control setup --reconfigure</code>, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA","只清除任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","接上了一个正在进行的 AI 任务":"Picked up an AI task in progress","外部任务":"External task","外部任务正在操作这台设备":"An external task is operating this device","手动操作已锁定,避免和它同时点击。":"Manual control is locked so you and the task don't tap at once.","外部任务已暂停":"External task paused","画面仍为这个任务保留,要自己操作先接管。":"The screen stays reserved for the task; take over to act yourself.","外部任务在等你确认一步操作":"The external task is waiting for you to confirm a step","发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。":"The program that started this task is stopped. What it already did on the device isn't undone.","接上了一个正在进行的外部任务":"Picked up an external task in progress"};+const EN = {"登录已过期":"Login expired","任务范围":"Task scope","所有 App":"All apps","任务只在这些 App 里操作":"The task only works in these apps","到了别的 App,每一步都先等你确认。不选就不限制。":"In any other app, each step waits for you first. Pick none for no limit.","任务只在这些 App 里操作:":"The task only works in: ","任务可以操作所有 App;点这里限定范围":"The task may use any app; click to limit it","已选":"Picked","不限制":"No limit","读不到 App 列表:":"Can't read the app list: ","正在读取 App…":"Reading apps…","只在":"Only in","AI 任务进行中:要自己点,先接管。":"An AI task is running: take over to tap it yourself.","实时画面里看不到这个系统弹窗,点这里就是点手机上的按钮":"The live picture doesn't show this system alert; a button here taps it on the phone"," · 演示数据":" · demo data"," 等":" and more","<div class=\"ph-kb\" data-type=\"Keyboard\">键盘</div>":"<div class=\"ph-kb\" data-type=\"Keyboard\">Keyboard</div>","<li class=\"empty-note\">打开这一页时会读取已安装的 App。</li>":"<li class=\"empty-note\">The installed apps are read when this tab opens.</li>","<li class=\"sr-only\">正在读取 App 列表…</li>":"<li class=\"sr-only\">Reading the app list…</li>","<li class=\"sr-only\">正在读取元素…</li>":"<li class=\"sr-only\">Reading elements…</li>","<option>没有可用的 AI</option>":"<option>No AI available</option>","<p class=\"empty-note\">正在连接 iphone-control 服务…</p>":"<p class=\"empty-note\">Connecting to the iphone-control service…</p>","<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>演示模式</span></span>":"<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>Demo</span></span>","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 在等你确认一步操作,确认前画面保持锁定。":"The AI is waiting for you to confirm a step; the screen stays locked until you do.","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认前画面保持锁定。":"The screen stays locked until you confirm.","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 <code>iphone-control sign</code>,用免费 Apple ID 签名并安装。":"Run <code>iphone-control sign</code> to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 <code>iphone-control setup --reconfigure</code> 选「手机」,在设备上点「信任」。":"Run <code>iphone-control setup --reconfigure</code>, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA","只清除任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","接上了一个正在进行的 AI 任务":"Picked up an AI task in progress","外部任务":"External task","外部任务正在操作这台设备":"An external task is operating this device","手动操作已锁定,避免和它同时点击。":"Manual control is locked so you and the task don't tap at once.","外部任务已暂停":"External task paused","画面仍为这个任务保留,要自己操作先接管。":"The screen stays reserved for the task; take over to act yourself.","外部任务在等你确认一步操作":"The external task is waiting for you to confirm a step","发起这个任务的程序会被停止。已经在设备上做完的操作不会撤销。":"The program that started this task is stopped. What it already did on the device isn't undone.","接上了一个正在进行的外部任务":"Picked up an external task in progress"};Object.assign(EN, {'未连接设备':'No device connected', '用数据线连接 iPhone 或 iPad。':'Connect an iPhone or iPad with a USB cable.', '等待设备连接':'Waiting for a device','外观':'Appearance', '界面字号':'Text size', '标准':'Standard', '大':'Large', '特大':'Extra large',@@ -1720,12 +1720,19 @@ function highlight(el) {/* ================================================================* 请求* ================================================================ */+/* 登录过期或令牌换了(viewer token --new):刷新,服务端回登录页。只在真的接上了 viewer 时(演示模式没有登录) */+function loggedOut(r) {+ if (r.status !== 401 || !document.documentElement.hasAttribute('data-viewer')) return false;+ if (!loggedOut.done) { loggedOut.done = true; location.reload(); }+ return true;+}async function api(path, body, device = S.udid) {const opt = body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) };opt.headers = { ...(opt.headers || {}), 'X-Ictl-Lang': LANG };// 操作只发给本页显示的那台;守护进程已换到别的设备时会被拒绝,不会点到用户没在看的手机上if (device && !path.startsWith('/api/updates')) opt.headers['X-Ictl-Device'] = device;const r = await fetch(path, opt);+ if (loggedOut(r)) throw new Error(tr('登录已过期'));if (!r.ok) {let msg = '';try { msg = (await r.json()).message || ''; } catch { /* 不是 JSON */ }@@ -2208,7 +2215,7 @@ async function loadInfo() {const seq = ++infoSequence, epoch = feedEpoch;try {const r = await fetch('/api/info?feed=' + encodeURIComponent(feedId), { headers: { 'X-Ictl-Lang': LANG }, signal: AbortSignal.timeout(4800) });- if (!r.ok) throw new Error('offline');+ if (loggedOut(r) || !r.ok) throw new Error('offline');const v = await r.json();if (seq === infoSequence && epoch === feedEpoch) applyInfo(v);} catch {@@ -2343,6 +2350,7 @@ async function startVideo(q, dev) {};try {const r = await fetch(`/video?${q}${dev ? '&src=device' : ''}`, { signal: ctrl.signal, headers: { 'X-Ictl-Lang': LANG } });+ if (loggedOut(r)) return;if (!r.ok || !r.body) return ended(r.status === 404);const rd = r.body.getReader();let buf = new Uint8Array(0);@@ -3371,6 +3379,7 @@ async function detect() {try {const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), 1500);const r = await fetch('/api/info', { signal: ctrl.signal, headers: { 'X-Ictl-Lang': LANG } }); clearTimeout(timer);+ if (loggedOut(r)) return;if (!r.ok) throw new Error('no service');const v = await r.json();if (!v || typeof v !== 'object' || !('width' in v || 'warning' in v)) throw new Error('no service');diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rsindex 1fed527..90cbf7c 100644--- a/apps/iphone-control/src/viewer.rs+++ b/apps/iphone-control/src/viewer.rs@@ -15,10 +15,9 @@//! Protections, same model as `wda-bridge`: it binds to the loopback address only, every request needs a//! loopback `Host` (against DNS rebinding), every action also needs an `Origin` of this very page and a JSON//! content type (against other web pages posting to it), and a read whose `Sec-Fetch-Site` says another site-//! sent it is refused (reading elements unlocks the phone). Other local users can still reach the port, which the-//! command says when it starts. With `--lan` the same port is open to the local network, still without a login-//! (see [`lan`]): only local-network addresses may connect, and `Host` and `Origin` may also be this machine's-//! own network names.+//! sent it is refused (reading elements unlocks the phone). Every request needs the login ([`auth`]), from this+//! machine too. With `--lan` the same port is open to the local network (see [`lan`]): only local-network addresses+//! may connect, and `Host` and `Origin` may also be this machine's own network names.//!//! The viewer follows one device, the one controlled when it starts or the one picked on the page: the picture//! always comes from it, and every action carries its UDID ([`ictl_daemon::protocol::EXPECT_UDID`]), so the daemon@@ -26,6 +25,7 @@//! instead of tapping a phone the user isn't looking at. The device handle is looked up again for each stream, so a//! replug (new usbmuxd id) doesn't break the picture.+pub mod auth;mod lan;mod mcp;mod peer;@@ -80,6 +80,8 @@ struct Ctx {tls: Option<Arc<tls::Tls>>,/// MCP over HTTP at `/mcp` (`--mcp`, on by default)mcp: Option<ictl_mcp::HttpService>,+ /// The login every HTTP request needs ([`auth`]); `None` only in tests+ auth: Option<auth::Auth>,}/// A picture handler can be cancelled at any await, including while opening its source.@@ -144,6 +146,8 @@ pub async fn run(false => None,};let agents = Agents::new(socket)?;+ let token =+ auth::load_or_create(data_dir).map_err(|e| anyhow::anyhow!("{}: {e}", auth::token_file(data_dir).display()))?;println!("{}",ictl_l10n::trf!(@@ -194,6 +198,13 @@ pub async fn run(});let scheme = if tls.is_some() { "https" } else { "http" };+ println!(+ "{}",+ ictl_l10n::tr!(+ "登录:浏览器和 /mcp 都要先登录(本机也一样)。iphone-control viewer token 显示令牌和点开就能登录的链接",+ "Login: browsers and /mcp need the token (on this machine too). iphone-control viewer token shows it, with a link that logs in"+ )+ );if let Some(t) = &tls {if t.made {println!(@@ -233,29 +244,26 @@ pub async fn run(println!("{}", ictl_l10n::trf!(" MCP:{scheme}://{a}:{port}/mcp", " MCP: {scheme}://{a}:{port}/mcp"));}}- if tls.is_some() {- println!(- "{}",+ println!(+ "{}",+ if tls.is_some() {ictl_l10n::tr!(- "注意:已对局域网开放,传输经 HTTPS 加密,但还没有登录:局域网里任何能连上这台机器的人都能看到屏幕、操作手机、用本机的 Claude Code / Codex 执行任务。只在可信的网络里开,用完就停掉。",- "Note: open to the local network, encrypted with HTTPS but with no login yet: anyone on the network who can reach this machine can watch and control the phone and run tasks with this machine's Claude Code / Codex. Only on a trusted network, and stop it when you are done."+ "注意:已对局域网开放,传输经 HTTPS 加密。有令牌的人都能看到屏幕、操作手机、用本机的 Claude Code / Codex 执行任务:令牌别外传。",+ "Note: open to the local network, encrypted with HTTPS. Whoever has the token can watch and control the phone and run tasks with this machine's Claude Code / Codex: keep it to yourself.")- );- } else {- println!(- "{}",+ } else {ictl_l10n::tr!(- "注意:已对局域网开放,还没有登录:局域网里任何能连上这台机器的人都能看到屏幕、操作手机、用本机的 Claude Code / Codex 执行任务。只在可信的网络里开,用完就停掉。从局域网地址打开时浏览器不提供 WebCodecs,画面是 MJPEG。",- "Note: open to the local network, with no login yet: anyone on the network who can reach this machine can watch and control the phone and run tasks with this machine's Claude Code / Codex. Only on a trusted network, and stop it when you are done. Opened at a network address, browsers don't offer WebCodecs, so the picture is MJPEG."+ "注意:已对局域网开放,但没有 HTTPS(--tls off):令牌和画面都以明文经过局域网。从局域网地址打开时浏览器不提供 WebCodecs,画面是 MJPEG。",+ "Note: open to the local network without HTTPS (--tls off): the token and the picture cross the network in the clear. Opened at a network address, browsers don't offer WebCodecs, so the picture is MJPEG.")- );- }+ }+ );} else {println!("{}",ictl_l10n::tr!(- "注意:本机所有用户都能经这个端口看到屏幕、操作手机、让 AI 执行任务,用完就停掉。",- "Note: every user on this machine can watch and control the phone and start AI tasks through this port; stop it when you are done."+ "注意:只在本机。经反向代理或隧道(frp、cloudflared 等)转发出去的访问在这里也像本机,同样要令牌:令牌别外传。",+ "Note: this machine only. Visits forwarded by a reverse proxy or tunnel (frp, cloudflared…) also look local here and need the token as well: keep it to yourself."));}@@ -276,6 +284,7 @@ pub async fn run(acks: Arc::default(),tls,mcp: mcp.then(|| ictl_mcp::http_service(socket.to_path_buf())),+ auth: Some(auth::Auth::new(token, port)),});let slots = Arc::new(tokio::sync::Semaphore::new(crate::MAX_CONNECTIONS));loop {@@ -310,6 +319,11 @@ pub async fn run(}}+/// This machine's network addresses `--lan` serves on (for `viewer token`)+pub fn lan_addresses(lan_hosts: &[String]) -> Vec<std::net::Ipv4Addr> {+ lan::Access::lan(lan_hosts).addresses().to_vec()+}+/// The page with `data-lang` set for English, which the page reads as its default languagefn page_in(lang: ictl_l10n::Lang) -> String {let html = match lang {@@ -344,6 +358,9 @@ async fn handle(mut client: Conn, ctx: &Ctx, head: Vec<u8>, req: Head, mut body:};return redirect(&mut client, &to).await;}+ if !login_gate(&mut client, ctx, &head, &req, &mut body).await? {+ return Ok(());+ }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,@@ -673,20 +690,28 @@ async fn json_reply(client: &mut Conn, status: u16, v: &Value) -> anyhow::Result}async fn reply(client: &mut Conn, status: u16, kind: &str, body: &[u8]) -> anyhow::Result<()> {+ reply_with(client, status, kind, body, "").await+}++/// [`reply`] with more header lines (`extra`: each ending with `\r\n`)+async fn reply_with(client: &mut Conn, status: u16, kind: &str, body: &[u8], extra: &str) -> anyhow::Result<()> {let reason = match status {200 => "OK",202 => "Accepted",+ 303 => "See Other",400 => "Bad Request",+ 401 => "Unauthorized",403 => "Forbidden",404 => "Not Found",409 => "Conflict",411 => "Length Required",413 => "Payload Too Large",+ 429 => "Too Many Requests",_ => "Bad Gateway",};let head = format!("HTTP/1.1 {status} {reason}\r\nContent-Type: {kind}\r\nContent-Length: {}\r\nCache-Control: no-store\r\n\- X-Content-Type-Options: nosniff\r\nX-Frame-Options: DENY\r\nConnection: close\r\n\r\n",+ X-Content-Type-Options: nosniff\r\nX-Frame-Options: DENY\r\n{extra}Connection: close\r\n\r\n",body.len());client.write_all(head.as_bytes()).await?;@@ -696,6 +721,77 @@ async fn reply(client: &mut Conn, status: u16, kind: &str, body: &[u8]) -> anyhoOk(())}+/// The login ([`auth`]) before anything else: `true` when the request may go on, otherwise it was answered (the+/// login page, a login, or 401 / 429)+async fn login_gate(client: &mut Conn, ctx: &Ctx, head: &[u8], req: &Head, body: &mut Vec<u8>) -> anyhow::Result<bool> {+ use auth::Verdict;+ let Some(a) = &ctx.auth else { return Ok(true) };+ let secure = client.is_tls();+ // the link `iphone-control viewer token` shows+ if req.method == "GET"+ && req.path == "/"+ && let Some(t) = req.query("token")+ {+ match a.try_token(&t) {+ Verdict::Ok => logged_in(client, a, secure).await?,+ v => login_page(client, v).await?,+ }+ return Ok(false);+ }+ // the login page's form+ if req.method == "POST" && req.path == "/login" {+ if req.origin.as_deref().is_some_and(|o| !ctx.access.origin_allowed(o, ctx.port)) {+ reply(client, 403, "text/plain", b"forbidden").await?;+ return Ok(false);+ }+ let len = req.content_length.unwrap_or(0);+ if len > 4096 {+ reply(client, 413, "text/plain", b"too large").await?;+ return Ok(false);+ }+ read_body(client, body, len).await?;+ match auth::form_token(body).filter(|t| !t.trim().is_empty()).map(|t| a.try_token(&t)) {+ Some(Verdict::Ok) => logged_in(client, a, secure).await?,+ Some(v) => login_page(client, v).await?,+ None => login_page(client, Verdict::Missing).await?,+ }+ return Ok(false);+ }+ let v = a.check(head);+ if v == Verdict::Ok {+ return Ok(true);+ }+ let status = if v == Verdict::Limited { 429 } else { 401 };+ match (req.method.as_str(), req.path.as_str()) {+ ("GET", "/") => login_page(client, v).await?,+ // MCP clients: send the token as a bearer token (RFC 6750)+ (_, "/mcp") => {+ let extra = "WWW-Authenticate: Bearer realm=\"iphone-control\"\r\n";+ reply_with(client, status, "text/plain", b"log in: Authorization: Bearer <token>", extra).await?+ }+ _ => reply(client, status, "text/plain", b"log in first").await?,+ }+ Ok(false)+}++/// Logged in: a session cookie, and the page without the token in its address (and history)+async fn logged_in(client: &mut Conn, a: &auth::Auth, secure: bool) -> anyhow::Result<()> {+ let extra = format!("Location: /\r\nSet-Cookie: {}\r\n", a.set_cookie(secure));+ reply_with(client, 303, "text/plain", b"", &extra).await+}++/// The login page, saying why the last try failed+async fn login_page(client: &mut Conn, v: auth::Verdict) -> anyhow::Result<()> {+ let (status, why) = match v {+ auth::Verdict::Wrong => (401, Some(ictl_l10n::tr!("令牌不对", "That isn't the token"))),+ auth::Verdict::Limited => {+ (429, Some(ictl_l10n::tr!("错误次数太多,一分钟后再试", "Too many wrong tokens; try again in a minute")))+ }+ _ => (401, None),+ };+ reply(client, status, "text/html; charset=utf-8", auth::login_page(why).as_bytes()).await+}+/// Where a plain HTTP request from the network goes: the same page over HTTPS, at the name it asked for (one of/// this machine's: [`lan::Access::host_allowed`] already checked it)fn https_location(head: &[u8], req: &Head, port: u16) -> Option<String> {@@ -1148,9 +1244,73 @@ mod tests {feeds: Mutex::default(),tls: None,mcp: None,+ auth: None,}}+ /// One request through [`serve`] on a real connection; the whole answer+ async fn exchange(ctx: &Ctx, raw: String) -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let client = tokio::spawn(async move {+ let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();+ s.write_all(raw.as_bytes()).await.unwrap();+ let mut out = String::new();+ s.read_to_string(&mut out).await.unwrap();+ out+ });+ let (tcp, _) = listener.accept().await.unwrap();+ serve(Conn::Plain(tcp), ctx).await.unwrap();+ client.await.unwrap()+ }++ /// Every request needs the login, from 127.0.0.1 too (a reverse proxy here looks just like it)+ #[tokio::test]+ async fn every_request_needs_the_login() {+ let temp = tempfile::tempdir_in("/tmp").unwrap();+ let mut ctx = test_ctx(temp.path(), &temp.path().join("none.sock"));+ let token = "t".repeat(64);+ ctx.auth = Some(auth::Auth::new(token.clone(), 8202));+ let get = |path: &str, extra: &str| format!("GET {path} HTTP/1.1\r\nHost: 127.0.0.1:8202\r\n{extra}\r\n");+ let status = |r: &str| r.split(' ').nth(1).unwrap_or_default().to_owned();++ let r = exchange(&ctx, get("/api/agent/backends", "")).await;+ assert_eq!(status(&r), "401", "{r}");+ let r = exchange(&ctx, get("/", "")).await;+ assert!(status(&r) == "401" && r.contains("action=\"/login\""), "the login page: {r}");+ let r = exchange(&ctx, get("/?token=nope", "")).await;+ assert!(status(&r) == "401" && r.contains("class=\"err\""), "{r}");++ // the link: a cookie, and the page without the token+ let r = exchange(&ctx, get(&format!("/?token={token}"), "")).await;+ assert_eq!(status(&r), "303", "{r}");+ assert!(r.contains("\r\nLocation: /\r\n"));+ let cookie = r.lines().find_map(|l| l.strip_prefix("Set-Cookie: ")).unwrap().split(';').next().unwrap();+ assert!(cookie.starts_with("ictl_viewer_8202=") && !cookie.contains(&token));+ let r = exchange(&ctx, get("/api/agent/backends", &format!("Cookie: {cookie}\r\n"))).await;+ assert_eq!(status(&r), "200", "{r}");+ let r = exchange(&ctx, get("/api/agent/backends", &format!("Authorization: Bearer {token}\r\n"))).await;+ assert_eq!(status(&r), "200", "a program: {r}");++ // the login page's form; not from another site+ let form = |origin: &str| {+ let body = format!("token={token}");+ format!(+ "POST /login HTTP/1.1\r\nHost: 127.0.0.1:8202\r\nContent-Type: application/x-www-form-urlencoded\r\n\+ Origin: {origin}\r\nContent-Length: {}\r\n\r\n{body}",+ body.len()+ )+ };+ let r = exchange(&ctx, form("http://127.0.0.1:0")).await;+ assert!(status(&r) == "303" && r.contains("Set-Cookie: ictl_viewer_8202="), "{r}");+ let r = exchange(&ctx, form("https://evil.example")).await;+ assert_eq!(status(&r), "403", "{r}");++ // MCP clients are told to send a bearer token+ let r = exchange(&ctx, "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1:8202\r\nContent-Length: 0\r\n\r\n".into()).await;+ assert!(status(&r) == "401" && r.contains("WWW-Authenticate: Bearer"), "{r}");+ }+#[test]fn plain_http_from_the_network_goes_to_the_same_page_over_https() {let at = |raw: &[u8]| https_location(raw, &Head::parse(raw).unwrap(), 8202);diff --git a/apps/iphone-control/src/viewer/auth.rs b/apps/iphone-control/src/viewer/auth.rsnew file mode 100644index 0000000..ed6aa0a--- /dev/null+++ b/apps/iphone-control/src/viewer/auth.rs@@ -0,0 +1,311 @@+//! Login for the control page and `/mcp` (docs/task-control.md 7.5).+//!+//! Every HTTP request needs it, from this machine too: a reverse proxy or tunnel on this machine (frp, nginx,+//! cloudflared, `tailscale serve`) makes every visitor's connection come from `127.0.0.1`, so the page can't tell+//! the user at their own browser from someone on the internet. The Unix socket (the CLI, `iphone-control mcp` over+//! stdio, `task run`) isn't HTTP and doesn't need it.+//!+//! One token, made on the first start and kept in `<data dir>/viewer-token` (0600); `iphone-control viewer token`+//! shows it with a link that logs in, `--new` replaces it (and every session with it). A browser logs in once (the+//! login page, or the link with `?token=`) and gets a session cookie: `HttpOnly`, `SameSite=Lax`, `Secure` over+//! HTTPS, 30 days. Its value is an HMAC of the token, so it shows nothing of the token and ends when the token is+//! replaced. 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. The token is 256 random bits, so+//! this only makes guessing slower still; a session that is already logged in isn't affected.++use std::collections::VecDeque;+use std::io;+use std::path::{Path, PathBuf};+use std::sync::Mutex;+use std::time::{Duration, Instant};++/// Under the data directory+pub const TOKEN_FILE: &str = "viewer-token";+/// Wrong tokens in [`WINDOW`] before tokens are refused until it is over+const MAX_FAILURES: usize = 20;+const WINDOW: Duration = Duration::from_secs(60);+/// How long a browser stays logged in+const SESSION_DAYS: u64 = 30;++pub fn token_file(data_dir: &Path) -> PathBuf {+ data_dir.join(TOKEN_FILE)+}++/// The token, made now if there is none+pub fn load_or_create(data_dir: &Path) -> io::Result<String> {+ match std::fs::read_to_string(token_file(data_dir)) {+ Ok(t) if valid_token(t.trim()) => Ok(t.trim().to_owned()),+ Ok(_) => replace(data_dir),+ Err(e) if e.kind() == io::ErrorKind::NotFound => replace(data_dir),+ Err(e) => Err(e),+ }+}++/// A new token in place of the old one; every browser has to log in again+pub fn replace(data_dir: &Path) -> io::Result<String> {+ let token = new_token()?;+ write_private(&token_file(data_dir), token.as_bytes())?;+ Ok(token)+}++fn valid_token(t: &str) -> bool {+ t.len() >= 32 && t.bytes().all(|b| b.is_ascii_alphanumeric())+}++fn new_token() -> io::Result<String> {+ use ring::rand::SecureRandom;+ let mut b = [0u8; 32];+ ring::rand::SystemRandom::new().fill(&mut b).map_err(|_| io::Error::other("no random numbers"))?;+ Ok(b.iter().map(|x| format!("{x:02x}")).collect())+}++/// Only this user may read it; written whole or not at all+fn write_private(file: &Path, data: &[u8]) -> io::Result<()> {+ use std::io::Write;+ use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};+ if let Some(dir) = file.parent() {+ std::fs::create_dir_all(dir)?;+ }+ let tmp = file.with_extension("tmp");+ let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&tmp)?;+ f.set_permissions(std::fs::Permissions::from_mode(0o600))?;+ f.write_all(data)?;+ f.sync_all()?;+ std::fs::rename(&tmp, file)+}++/// What a request shows of the login+#[derive(Debug, PartialEq, Eq)]+pub enum Verdict {+ /// A valid session cookie or `Authorization: Bearer` token+ Ok,+ /// Nothing (or only a stale cookie): log in+ Missing,+ /// A wrong token+ Wrong,+ /// Too many wrong tokens just now: not checked+ Limited,+}++pub struct Auth {+ token: String,+ /// The session cookie's value: HMAC-SHA256 of a fixed text under the token+ session: String,+ /// One per port: cookies aren't separated by port, and another viewer on this machine has another token+ cookie: String,+ failures: Mutex<VecDeque<Instant>>,+}++impl Auth {+ pub fn new(token: String, port: u16) -> Self {+ let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, token.as_bytes());+ let tag = ring::hmac::sign(&key, b"iphone-control viewer session v1");+ let session = tag.as_ref().iter().map(|x| format!("{x:02x}")).collect();+ Self { token, session, cookie: format!("ictl_viewer_{port}"), failures: Mutex::default() }+ }++ /// The request's session cookie or `Authorization: Bearer` token+ pub fn check(&self, head: &[u8]) -> Verdict {+ let text = String::from_utf8_lossy(head);+ let mut bearer = None;+ for line in text.split("\r\n").skip(1) {+ let Some((k, v)) = line.split_once(':') else { continue };+ let k = k.trim();+ if k.eq_ignore_ascii_case("cookie") {+ let ours = v.split(';').filter_map(|c| c.trim().split_once('=')).find(|(n, _)| *n == self.cookie);+ if ours.is_some_and(|(_, v)| same(v.trim(), &self.session)) {+ return Verdict::Ok;+ }+ } else if k.eq_ignore_ascii_case("authorization") {+ let v = v.trim();+ if v.len() > 7 && v[..7].eq_ignore_ascii_case("bearer ") {+ bearer = Some(v[7..].trim().to_owned());+ }+ }+ }+ match bearer {+ Some(t) => self.try_token(&t),+ None => Verdict::Missing,+ }+ }++ /// A token someone typed or sent: right, wrong (counted), or not checked now+ pub fn try_token(&self, presented: &str) -> Verdict {+ let mut f = self.failures.lock().unwrap_or_else(|p| p.into_inner());+ let now = Instant::now();+ while f.front().is_some_and(|t| now.duration_since(*t) > WINDOW) {+ f.pop_front();+ }+ if f.len() >= MAX_FAILURES {+ return Verdict::Limited;+ }+ if same(presented.trim(), &self.token) {+ Verdict::Ok+ } else {+ f.push_back(now);+ Verdict::Wrong+ }+ }++ /// `Set-Cookie` for a browser that logged in; `secure` over HTTPS (the browser then only sends it there)+ pub fn set_cookie(&self, secure: bool) -> String {+ format!(+ "{}={}; Path=/; Max-Age={}; HttpOnly; SameSite=Lax{}",+ self.cookie,+ self.session,+ SESSION_DAYS * 24 * 60 * 60,+ if secure { "; Secure" } else { "" }+ )+ }+}++/// Equal, in a time that doesn't depend on where they differ+fn same(a: &str, b: &str) -> bool {+ let (a, b) = (a.as_bytes(), b.as_bytes());+ a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0+}++/// The login page, in the viewer's language. `error`: why the last try didn't work+pub fn login_page(error: Option<&str>) -> String {+ let (lang, title, lead, label, button, hint) = match ictl_l10n::lang() {+ ictl_l10n::Lang::En => (+ "en",+ "Log in · iphone-control",+ "This control page needs its token.",+ "Token",+ "Log in",+ "Run <code>iphone-control viewer token</code> on the machine the phone is connected to: it shows the token and a link that logs in.",+ ),+ ictl_l10n::Lang::Zh => (+ "zh-CN",+ "登录 · iphone-control",+ "打开控制台要先输入令牌。",+ "令牌",+ "登录",+ "在接着手机的那台机器上运行 <code>iphone-control viewer token</code>,会显示令牌和一个点开就能登录的链接。",+ ),+ };+ let error = error.map(|e| format!("<p class=\"err\" role=\"alert\">{}</p>", html_escape(e))).unwrap_or_default();+ format!(+ r#"<!doctype html>+<html lang="{lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">+<title>{title}</title>+<style>+:root {{ color-scheme: light dark; font-family: system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif; }}+body {{ margin: 0; min-height: 100vh; display: grid; place-items: center; background: Canvas; color: CanvasText; }}+main {{ width: min(360px, calc(100vw - 48px)); }}+h1 {{ font-size: 20px; margin: 0 0 6px; }}+p {{ margin: 0 0 18px; opacity: .75; line-height: 1.5; font-size: 14px; }}+label {{ display: block; font-size: 13px; margin-bottom: 6px; }}+input {{ box-sizing: border-box; width: 100%; padding: 10px 12px; font: inherit; font-family: ui-monospace, monospace; border: 1px solid color-mix(in srgb, CanvasText 25%, transparent); border-radius: 8px; background: Field; color: FieldText; }}+button {{ margin-top: 14px; width: 100%; padding: 10px; font: inherit; font-weight: 600; border: 0; border-radius: 8px; background: #2563eb; color: #fff; cursor: pointer; }}+.err {{ color: #dc2626; opacity: 1; }}+.hint {{ margin-top: 18px; font-size: 13px; }}+code {{ font-size: 12px; padding: 1px 4px; border-radius: 4px; background: color-mix(in srgb, CanvasText 10%, transparent); }}+</style></head>+<body><main>+<h1>iphone-control</h1>+<p>{lead}</p>+{error}<form method="post" action="/login">+<label for="token">{label}</label>+<input id="token" name="token" type="password" autocomplete="current-password" autofocus required>+<button type="submit">{button}</button>+</form>+<p class="hint">{hint}</p>+</main></body></html>+"#+ )+}++fn html_escape(s: &str) -> String {+ s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)+}++/// `token=…` from a login form (`application/x-www-form-urlencoded`)+pub fn form_token(body: &[u8]) -> Option<String> {+ let text = std::str::from_utf8(body).ok()?;+ text.split('&').find_map(|kv| {+ let (k, v) = kv.split_once('=')?;+ (k == "token").then(|| super::percent_decode(&v.replace('+', " ")))+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn head(lines: &[&str]) -> Vec<u8> {+ let mut h = String::from("GET /api/info HTTP/1.1\r\nHost: 127.0.0.1:8202\r\n");+ for l in lines {+ h.push_str(l);+ h.push_str("\r\n");+ }+ h.push_str("\r\n");+ h.into_bytes()+ }++ #[test]+ fn the_token_is_made_once_kept_private_and_replaced_on_demand() {+ use std::os::unix::fs::PermissionsExt;+ let tmp = tempfile::tempdir().unwrap();+ let a = load_or_create(tmp.path()).unwrap();+ assert_eq!(a.len(), 64);+ assert!(valid_token(&a));+ assert_eq!(load_or_create(tmp.path()).unwrap(), a, "kept");+ let mode = std::fs::metadata(token_file(tmp.path())).unwrap().permissions().mode();+ assert_eq!(mode & 0o777, 0o600);+ let b = replace(tmp.path()).unwrap();+ assert_ne!(a, b);+ assert_eq!(load_or_create(tmp.path()).unwrap(), b);+ std::fs::write(token_file(tmp.path()), "short").unwrap();+ assert_ne!(load_or_create(tmp.path()).unwrap(), "short", "a broken file is replaced");+ }++ #[test]+ fn a_session_cookie_or_a_bearer_token_lets_a_request_in() {+ let auth = Auth::new("a".repeat(64), 8202);+ let cookie = auth.set_cookie(false);+ let pair = cookie.split(';').next().unwrap();+ assert!(cookie.contains("HttpOnly") && cookie.contains("SameSite=Lax") && !cookie.contains("Secure"));+ assert!(auth.set_cookie(true).ends_with("; Secure"));+ assert!(!pair.contains(&"a".repeat(64)), "the cookie doesn't carry the token");++ assert_eq!(auth.check(&head(&[])), Verdict::Missing);+ assert_eq!(auth.check(&head(&[&format!("Cookie: theme=dark; {pair}")])), Verdict::Ok);+ assert_eq!(auth.check(&head(&["Cookie: ictl_viewer_8202=deadbeef"])), Verdict::Missing, "stale: log in");+ assert_eq!(auth.check(&head(&[&format!("Cookie: {}", pair.replace("8202", "8203"))])), Verdict::Missing);+ assert_eq!(auth.check(&head(&[&format!("Authorization: Bearer {}", "a".repeat(64))])), Verdict::Ok);+ assert_eq!(auth.check(&head(&[&format!("authorization: bearer {}", "a".repeat(64))])), Verdict::Ok);+ assert_eq!(auth.check(&head(&["Authorization: Bearer nope"])), Verdict::Wrong);+ assert_eq!(auth.check(&head(&["Authorization: Basic Zm9vOmJhcg=="])), Verdict::Missing);+ // a new token ends the old sessions+ let other = Auth::new("b".repeat(64), 8202);+ assert_eq!(other.check(&head(&[pair])), Verdict::Missing);+ assert_eq!(other.check(&head(&[&format!("Cookie: {pair}")])), Verdict::Missing);+ }++ #[test]+ fn wrong_tokens_are_limited_for_everyone() {+ let auth = Auth::new("a".repeat(64), 8202);+ let session = auth.set_cookie(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");+ assert_eq!(auth.check(&head(&[&format!("Cookie: {session}")])), Verdict::Ok, "logged-in browsers go on");+ // the minute is over+ auth.failures.lock().unwrap().iter_mut().for_each(|t| *t -= WINDOW + Duration::from_secs(1));+ assert_eq!(auth.try_token(&"a".repeat(64)), Verdict::Ok);+ }++ #[test]+ fn the_login_form_and_page() {+ assert_eq!(form_token(b"token=abc%2Bd+e&x=1").as_deref(), Some("abc+d e"));+ assert_eq!(form_token(b"x=1"), None);+ let page = login_page(Some("<b>wrong</b>"));+ assert!(page.contains("<b>wrong</b>") && page.contains("action=\"/login\""));+ }+}diff --git a/apps/iphone-control/src/viewer/lan.rs b/apps/iphone-control/src/viewer/lan.rsindex 763b6dd..909b750 100644--- a/apps/iphone-control/src/viewer/lan.rs+++ b/apps/iphone-control/src/viewer/lan.rs@@ -1,8 +1,8 @@//! Who may reach the control page (docs/task-control.md 7.2, D3).//!//! By default the page is on `127.0.0.1` only, as before. With `viewer --lan` (`IPHONE_CONTROL_VIEWER_LAN=1`) the-//! same port, **without a login** (that comes later), listens on every IPv4 interface, so the page can be opened-//! from another machine on the local network; it speaks HTTPS there (`super::tls`). What still protects it:+//! same port listens on every IPv4 interface, so the page can be opened from another machine on the local network;+//! it speaks HTTPS there (`super::tls`) and needs the login like everywhere (`super::auth`). Besides the login://!//! - connections only from loopback, private (10/8, 172.16/12, 192.168/16), link-local (169.254/16) and CGNAT//! (100.64/10, which Tailscale uses) addresses: a machine reachable from the internet isn't operated from there;diff --git a/apps/iphone-control/src/viewer/mcp.rs b/apps/iphone-control/src/viewer/mcp.rsindex 1e13c51..3517b10 100644--- a/apps/iphone-control/src/viewer/mcp.rs+++ b/apps/iphone-control/src/viewer/mcp.rs@@ -7,7 +7,7 @@//!//! Who may call it is who may open the page: the viewer checks the peer address, `Host` and `Sec-Fetch-Site` first,//! and here a request that carries an `Origin` (a browser) must come from the page itself. Clients that aren't-//! browsers send none. No login yet, as for the page.+//! browsers send none. The login is the page's (`super::auth`): clients send `Authorization: Bearer <token>`.//!//! A task's agent sends the task's token in `Iphone-Control-Task-Token` ([`ictl_daemon::protocol::TASK_TOKEN_HEADER`]),//! as `IPHONE_CONTROL_TASK_TOKEN` does on stdio.diff --git a/apps/iphone-control/tests/update_viewer.rs b/apps/iphone-control/tests/update_viewer.rsindex ee1ea18..9105da5 100644--- a/apps/iphone-control/tests/update_viewer.rs+++ b/apps/iphone-control/tests/update_viewer.rs@@ -30,13 +30,27 @@ async fn viewer_and_cli_share_the_unbound_report() -> Result<()> {assert_eq!(report["availability"], "development");assert!(report["publisher"].is_null() && report["daemon_version"].is_null());+ // every HTTP request needs the viewer's login: its token, from `viewer token`+ let shown = cli().args(["viewer", "token"]).output().await?;+ assert!(shown.status.success());+ let shown = String::from_utf8_lossy(&shown.stdout);+ let token = shown+ .split(|c: char| !c.is_ascii_hexdigit())+ .find(|w| w.len() == 64)+ .context("a token in `viewer token`")?+ .to_owned();let mut viewer = cli().args(["viewer", "--port", "0"]).stdout(Stdio::piped()).stderr(Stdio::null()).spawn()?;let mut messages = BufReader::new(viewer.stdout.take().unwrap()).lines();let line = tokio::time::timeout(Duration::from_secs(10), messages.next_line()).await??.context("viewer exited")?;let from = line.find("http://127.0.0.1:").context("viewer URL")?;let origin = line[from..].split_once("/ ").context("viewer port")?.0;let _ = rustls::crypto::ring::default_provider().install_default();- let client = reqwest::Client::builder().no_proxy().timeout(Duration::from_secs(5)).build()?;+ let unauthenticated = reqwest::Client::builder().no_proxy().timeout(Duration::from_secs(5)).build()?;+ assert_eq!(unauthenticated.get(format!("{origin}/api/updates")).send().await?.status(), 401);+ let mut headers = reqwest::header::HeaderMap::new();+ headers.insert(reqwest::header::AUTHORIZATION, format!("Bearer {token}").parse()?);+ let client =+ reqwest::Client::builder().no_proxy().timeout(Duration::from_secs(5)).default_headers(headers).build()?;let response = client.get(format!("{origin}/api/updates")).send().await?.error_for_status()?;let shown: Value = serde_json::from_slice(&response.bytes().await?)?;for (field, value) in report.as_object().unwrap() {diff --git a/docs/task-control.md b/docs/task-control.mdindex 10cc375..c31b208 100644--- a/docs/task-control.md+++ b/docs/task-control.md@@ -134,7 +134,8 @@ Running → Waiting(等确认)→ Running| 三 | 执行方不能控制自己的任务(2.5 的落地版,见 5.6) | 已完成(2026-11-13) || 四 | 局域网访问控制台(7.2)、控制台后台服务、HTTPS(7.3) | 已完成(2026-11-13) || 四 | HTTP MCP(7.4) | 已完成(2026-11-13) |-| 四 | 登录、跨主机开任务(HTTP 控制面)、多设备租约 | 等需要时 |+| 四 | 登录(7.5,一个令牌) | 已完成(2026-11-13) |+| 四 | 只读/可操作两种令牌、跨主机开任务(HTTP 控制面)、多设备租约 | 等需要时 |## 5. 阶段一的具体设计@@ -283,4 +284,17 @@ Running → Waiting(等确认)→ Running- **任务**:stdio 靠进程的环境变量 `IPHONE_CONTROL_TASK_TOKEN` 加入任务;HTTP 是一个进程服务许多客户端,所以口令放在每个请求的头 `Iphone-Control-Task-Token` 里,`McpServer` 按请求读取,用 `as_task` 让这次调用发出的所有请求都带上它。「是否在任务里」也改成按请求判断(`protocol::in_task`)。带了口令就列出 `iphone_confirm`、每次调用报告步骤,和 stdio 一样。- **访问**:和控制台页面一样,对端地址、`Host`、`Sec-Fetch-Site` 先查;带 `Origin` 的请求(浏览器)必须来自控制台自己,命令行客户端不带 `Origin`。rmcp 自己的 Host 白名单设为不检查,免得两套名单不一致。`--lan` 时局域网的明文请求 307 到 HTTPS。- **开关**:`--mcp on|off`(`IPHONE_CONTROL_VIEWER_MCP`),默认开:它能做的事控制台的接口本来就能做,没有多开口子。-- **还没有的**:登录(和控制台一起做);从别的机器**开**任务(任务的租约还是本机 socket 上的连接,外部平台目前在本机用 `task run` 开任务、把口令交给远端的 agent)。+- **还没有的**:从别的机器**开**任务(任务的租约还是本机 socket 上的连接,外部平台目前在本机用 `task run` 开任务、把口令交给远端的 agent)。+++### 7.5 登录(2026-11-13)++7.1 第 2 条的落地,按用户的决定做了一个令牌(只读和可操作分开留到以后)。和 7.1 不同的一点:**本机也要登录**。frp、nginx、cloudflared、`tailscale serve` 这类反向代理或隧道跑在本机时,公网上每个访问者的连接都来自 `127.0.0.1`,控制台分不清是用户本人还是别人,所以不能「本机免登录」。++- **范围**:经 HTTP 的一切(页面、接口、画面、任务事件、`/mcp`)。Unix socket 上的命令行、stdio 的 `iphone-control mcp`、`task run` 不受影响(socket 是 0600,本来就只有这个用户能连)。+- **令牌**:第一次启动时用系统随机数生成 256 位,十六进制存在 `<数据目录>/viewer-token`(0600,先写临时文件再改名)。`iphone-control viewer token` 显示令牌、本机和局域网的登录链接(`/?token=…`)、`claude mcp add … --header "Authorization: Bearer …"`;`--new` 换新令牌,控制台服务在运行就重启它。令牌不写进启动输出和日志(journal 可能有别人能读)。+- **浏览器**:没登录时 `/` 返回登录页(401);登录页的表单 `POST /login`(带 `Origin` 时必须是控制台自己),或者点开 `/?token=…` 的链接,成功后 303 回 `/`,地址栏里不留令牌。会话 cookie `ictl_viewer_<端口>`:值是令牌对固定文本的 HMAC-SHA256,看不出令牌,换令牌后自动失效;`HttpOnly`、`SameSite=Lax`(从别处点链接进来也认得,CSRF 靠原有的 `Origin` 和 `Sec-Fetch-Site` 检查)、HTTPS 时加 `Secure`、30 天。页面上的请求遇到 401 就刷新,回到登录页。+- **程序**:`Authorization: Bearer <令牌>`。`/mcp` 的 401 带 `WWW-Authenticate: Bearer`(RFC 6750)。+- **限速**:按全局算,不按地址(经反向代理时地址都是 `127.0.0.1`)。一分钟里错 20 次后,这一分钟内不再校验令牌,一律 429;已经登录的会话不受影响。令牌是 256 位随机数,限速只是多一层保险。+- **比较**:令牌和 cookie 都用与内容无关的时间比较。+- **还没有的**:只读和可操作两种令牌、事件里记下是哪个人(现在 `by` 只到 `viewer` / `viewer <IP>` / `cli`)、页面上的退出登录。diff --git a/packaging/env.example b/packaging/env.exampleindex c440529..fb02df9 100644--- a/packaging/env.example+++ b/packaging/env.example@@ -25,8 +25,8 @@ IPHONE_CONTROL_VIEWER_CODEC=# H.264 的画质:1~51,越小越清晰、流量越大。默认 20,正常使用看不出和原画的差别;24 约省三分之一流量,快速滚动时小字略糊# H.264 quality, 1 to 51: lower is sharper and larger. Default 20 looks like the source; 24 saves about a third, small text blurs a little while scrolling fast.IPHONE_CONTROL_VIEWER_QP=-# 设为 1:控制台也对局域网开放(同一个端口,局域网里用 HTTPS;还没有登录:局域网里任何能连上这台机器的人都能操作手机),只接受局域网地址来的连接-# Set to 1: the viewer is also open to the local network (same port, HTTPS there; no login yet: anyone on the network can control the phone); only local-network addresses may connect.+# 设为 1:控制台也对局域网开放(同一个端口,局域网里用 HTTPS,要令牌登录:iphone-control viewer token),只接受局域网地址来的连接+# Set to 1: the viewer is also open to the local network (same port, HTTPS there, login with the token: iphone-control viewer token); only local-network addresses may connect.IPHONE_CONTROL_VIEWER_LAN=# 控制台的端口(默认 8200)和 --lan 时还认可的主机名(逗号分隔);控制台服务(iphone-control service viewer install)也读它们# The viewer's port (default 8200) and, with --lan, more host names it answers to (comma-separated); the viewer service reads them too.diff --git a/tests/device/mcp_http.py b/tests/device/mcp_http.pyindex 4fc819c..8364794 100644--- a/tests/device/mcp_http.py+++ b/tests/device/mcp_http.py@@ -1,7 +1,8 @@"""MCP over HTTP for the device scripts: with MCP_URL set (the viewer's `/mcp`, e.g. `http://127.0.0.1:8202/mcp`),run.py and tasks.py connect there instead of starting `iphone-control mcp` on stdio. A task's token goes in the`Iphone-Control-Task-Token` header. MCP_CA: a certificate to trust for an `https://` URL (the viewer's self-signed-one, `<data dir>/viewer-tls/cert.pem`)."""+one, `<data dir>/viewer-tls/cert.pem`). ICTL_VIEWER_TOKEN: the viewer's login token (`iphone-control viewer token`),+sent as `Authorization: Bearer`."""import osimport ssl@@ -16,7 +17,9 @@ TOKEN_HEADER = "Iphone-Control-Task-Token"async def streams(stack: AsyncExitStack, token: str | None):"""(read, write) streams of an MCP session at MCP_URL, as the task with `token` (None: no task)"""- headers = {TOKEN_HEADER: token} if token else None+ headers = {TOKEN_HEADER: token} if token else {}+ if os.environ.get("ICTL_VIEWER_TOKEN"):+ headers["Authorization"] = "Bearer " + os.environ["ICTL_VIEWER_TOKEN"]ca = os.environ.get("MCP_CA")verify = ssl.create_default_context(cafile=ca) if ca else True# the SDK's default timeouts (create_mcp_http_client), plus the certificate; never through a proxy from thediff --git a/tests/device/tasks.py b/tests/device/tasks.pyindex 6b01e99..b7390af 100644--- a/tests/device/tasks.py+++ b/tests/device/tasks.py@@ -17,7 +17,7 @@ to open (one of them a scheme no app handles). Nothing is sent, bought, deletedEnvironment: ICTL_BIN (default `iphone-control`; your branch's build for a pull request), MCP_CMD (default`$ICTL_BIN mcp`; or MCP_URL for MCP over HTTP, see mcp_http.py), ICTL_SOCKET (default `$XDG_RUNTIME_DIR/iphone-control/ctl.sock`), ICTL_VIEWER (the control page ofthe same build, such as `http://127.0.0.1:8202`; the `self` scenario then also tries the page's API from inside a-task).+task), ICTL_VIEWER_TOKEN (its login token, `iphone-control viewer token`; also sent to MCP_URL)."""import argparse@@ -49,8 +49,10 @@ VIEWER = os.environ.get("ICTL_VIEWER", "").rstrip("/")PAGE_PAUSE = """import json, os, sys, urllib.error, urllib.requestv, task = sys.argv[1], os.environ["IPHONE_CONTROL_TASK_ID"]-req = urllib.request.Request(f"{v}/api/agent/tasks/{task}/pause", data=b"{}", method="POST",- headers={"Content-Type": "application/json", "Origin": v})+headers = {"Content-Type": "application/json", "Origin": v}+if os.environ.get("ICTL_VIEWER_TOKEN"):+ headers["Authorization"] = "Bearer " + os.environ["ICTL_VIEWER_TOKEN"]+req = urllib.request.Request(f"{v}/api/agent/tasks/{task}/pause", data=b"{}", method="POST", headers=headers)try:r = urllib.request.urlopen(req, timeout=15)print(r.status, r.read().decode())diff --git a/website/en/guide/cli.md b/website/en/guide/cli.mdindex 4e1faaa..7f25623 100644--- a/website/en/guide/cli.md+++ b/website/en/guide/cli.md@@ -130,7 +130,8 @@ See [Auto-unlock](./auto-unlock). `--device` takes a UDID or name, and the devic|---|---|| `notify-test [event]` | Send test notifications: one per event type, or one type (`resign`, `session`, `pin`, `pin-recovered`, `unlock`, `offline`, `online`) || `wda-bridge [--port <port>]` | Expose WDA on `127.0.0.1` (default port 8100) for other tools. WDA has no authentication and every local user can reach it, so stop it when done |-| `viewer [--port <port>] [--lan] [--lan-host <name>…] [--tls auto\|on\|off] [--tls-cert <PEM> --tls-key <PEM>] [--mcp on\|off]` | Control page in the browser (and MCP over HTTP at `/mcp` on the same port, see [Connect an AI Client](./mcp-clients#connect-by-url-http); `--mcp off` turns it off) at `http://127.0.0.1:8200/` (default port); with `--lan` also at `https://<this machine's address>:8200/` on the local network (same port; `http://` from the network is sent to `https://`). There is no login yet, so anyone on the network can control the phone. The certificate is a self-signed one made on this machine (kept in `viewer-tls/` in the data directory and reused), so the first time the browser warns that it isn't trusted: check that the SHA-256 fingerprint matches the one printed at startup or by `service status`, then go on. With a certificate of your own (`--tls-cert`/`--tls-key`: mkcert, `tailscale cert`…) there is no warning. With `--tls off` the network gets plain HTTP and the picture falls back to MJPEG (browsers only offer WebCodecs on localhost or HTTPS), in English or Chinese (follows `IPHONE_CONTROL_LANG`, switchable on the page). **Screen:** the live picture works like a touchscreen: click to tap, drag to swipe, hold to long-press, scroll with the mouse wheel or trackpad, plus a text field and the hardware buttons. On iOS 27 and later the finger follows the pointer as it moves (over CoreDevice HID, which keeps the phone awake until 30 seconds after the last touch); older versions get the whole gesture on release. Everything goes through the daemon like an MCP call, so it queues with the agent and unlocks the phone first. On iOS 27 and later the picture is the phone's own video; otherwise it comes from WDA (none until WDA is ready), as H.264 or MJPEG; see [Picture](#viewer-picture) below. Touch is available when the frame matches the measured size and orientation. After rotating or switching devices, start a new gesture on the updated picture. Settings at the bottom of the sidebar controls the theme and text size. The picture has its own zoom controls, the − and + above it (pinching doesn't zoom, so a drag can't turn into one). **Device panel:** state and readiness checks, installed apps, on-screen elements. The page follows the device the daemon controls: switch on the page or anywhere else, and the picture and panels move over; see [Several Devices](./multi-device#control-page). **AI tasks:** type a task and a local agent carries it out (Claude Code or Codex, whichever is on `PATH`; picked on the page). Before it starts you can limit it to some apps with the App button next to the agent; in any other app each step waits for you. You can pause, take over and hand back, or stop it, and it asks on the page before paying, deleting or sending messages. Every local user can reach the port, so stop it when done |+| `viewer [--port <port>] [--lan] [--lan-host <name>…] [--tls auto\|on\|off] [--tls-cert <PEM> --tls-key <PEM>] [--mcp on\|off]` | Control page in the browser, **behind a login**: every HTTP visit (from this machine too; one forwarded by frp or another reverse proxy looks just like it) needs the token, and `viewer token` shows it with links that log in; a browser stays logged in for 30 days, programs and MCP clients send `Authorization: Bearer <token>`. (and MCP over HTTP at `/mcp` on the same port, see [Connect an AI Client](./mcp-clients#connect-by-url-http); `--mcp off` turns it off) at `http://127.0.0.1:8200/` (default port); with `--lan` also at `https://<this machine's address>:8200/` on the local network (same port; `http://` from the network is sent to `https://`). The certificate is a self-signed one made on this machine (kept in `viewer-tls/` in the data directory and reused), so the first time the browser warns that it isn't trusted: check that the SHA-256 fingerprint matches the one printed at startup or by `service status`, then go on. With a certificate of your own (`--tls-cert`/`--tls-key`: mkcert, `tailscale cert`…) there is no warning. With `--tls off` the network gets plain HTTP and the picture falls back to MJPEG (browsers only offer WebCodecs on localhost or HTTPS), in English or Chinese (follows `IPHONE_CONTROL_LANG`, switchable on the page). **Screen:** the live picture works like a touchscreen: click to tap, drag to swipe, hold to long-press, scroll with the mouse wheel or trackpad, plus a text field and the hardware buttons. On iOS 27 and later the finger follows the pointer as it moves (over CoreDevice HID, which keeps the phone awake until 30 seconds after the last touch); older versions get the whole gesture on release. Everything goes through the daemon like an MCP call, so it queues with the agent and unlocks the phone first. On iOS 27 and later the picture is the phone's own video; otherwise it comes from WDA (none until WDA is ready), as H.264 or MJPEG; see [Picture](#viewer-picture) below. Touch is available when the frame matches the measured size and orientation. After rotating or switching devices, start a new gesture on the updated picture. Settings at the bottom of the sidebar controls the theme and text size. The picture has its own zoom controls, the − and + above it (pinching doesn't zoom, so a drag can't turn into one). **Device panel:** state and readiness checks, installed apps, on-screen elements. The page follows the device the daemon controls: switch on the page or anywhere else, and the picture and panels move over; see [Several Devices](./multi-device#control-page). **AI tasks:** type a task and a local agent carries it out (Claude Code or Codex, whichever is on `PATH`; picked on the page). Before it starts you can limit it to some apps with the App button next to the agent; in any other app each step waits for you. You can pause, take over and hand back, or stop it, and it asks on the page before paying, deleting or sending messages. The token is the key: keep it to yourself |+| `viewer token [--new]` | Show the viewer's login token (kept in `viewer-token` in the data directory, 0600), links that log in on this machine and the local network, and the command to connect to its HTTP MCP; `--new` replaces it: browsers and MCP clients logged in before need the new one, and a running viewer service is restarted || `task run [--title <title>] [--app <app>…] -- <command>` | AI tasks for other agent platforms: opens a task on the controlled device and runs the command in it. An `iphone-control mcp` the command starts takes part (through `IPHONE_CONTROL_TASK_TOKEN`): the control page shows every step and can pause, take over and stop it, and it waits for you before paying or sending a message. The task ends when the command does; when the task is stopped elsewhere, so is the command; Ctrl-C stops the task. While a task runs, other clients can look but not act on the phone. `--app` (repeatable, name or bundle ID) limits the task to those apps: in any other app, or to open a link that isn't a web page, each step waits for you first || `task list` / `task events <id>` | Recent tasks (`--json` for programs); follow a task's events, one JSON per line || `task pause\|resume\|takeover\|handback\|stop <id>`, `task approve\|reject <id>` | Control a task from the command line, like the buttons on the control page. Only for a person: from inside the task (the agent's environment or a process it started) they are refused, except `stop` |diff --git a/website/en/guide/configuration.md b/website/en/guide/configuration.mdindex 4e14062..620645f 100644--- a/website/en/guide/configuration.md+++ b/website/en/guide/configuration.md@@ -29,7 +29,7 @@ iphone-control service restart| `IPHONE_CONTROL_VIEWER_QP` | `20` | H.264 quality, 1 to 51: lower is sharper and larger. `20` looks like the source in normal use; `24` saves about a third of the traffic, small text blurs a little while scrolling fast || `IPHONE_CONTROL_VIEWER_PORT` | `8200` | The viewer's port, like `viewer --port` (the viewer service reads it too) || `IPHONE_CONTROL_VIEWER_LAN_HOSTS` | empty | With `--lan`, more host names the page answers to, comma-separated, like `--lan-host` |-| `IPHONE_CONTROL_VIEWER_LAN` | off | Set to `1` to open the viewer to the local network too, like `viewer --lan`, over HTTPS there. There is no login yet: anyone on the network who can reach this machine can control the phone and start AI tasks, so only on a trusted network |+| `IPHONE_CONTROL_VIEWER_LAN` | off | Set to `1` to open the viewer to the local network too, like `viewer --lan`, over HTTPS there. As on this machine, it needs the login token (`iphone-control viewer token`) || `IPHONE_CONTROL_VIEWER_TLS` | `auto` | The viewer's HTTPS, like `--tls`: `auto` turns it on when open to the network or given a certificate; `on`, `off`. `http://127.0.0.1` on this machine always works || `IPHONE_CONTROL_VIEWER_TLS_CERT`, `IPHONE_CONTROL_VIEWER_TLS_KEY` | empty | The viewer's own certificate and key (PEM), like `--tls-cert`, `--tls-key`; without them a self-signed one made on this machine || `IPHONE_CONTROL_VIEWER_MCP` | `on` | MCP over HTTP on the viewer's port (`/mcp`), like `--mcp`; `off` turns it off |diff --git a/website/en/guide/mcp-clients.md b/website/en/guide/mcp-clients.mdindex af4ce4f..ff3f149 100644--- a/website/en/guide/mcp-clients.md+++ b/website/en/guide/mcp-clients.md@@ -44,13 +44,14 @@ The MCP server reaches the daemon through a local Unix socket. If the client runThe viewer (`iphone-control viewer`, or the service from `service viewer install`) also serves MCP over HTTP (Streamable HTTP) on its port, at `/mcp`, with the same tools as stdio above. For clients that only take a URL, and agents on another computer.-- **This machine**: `http://127.0.0.1:8200/mcp` (the viewer's port). Claude Code: `claude mcp add --transport http iphone http://127.0.0.1:8200/mcp`; in a configuration file `{"type": "http", "url": "http://127.0.0.1:8200/mcp"}`.+- **Login**: like the page, it needs the token, as `Authorization: Bearer <token>`. `iphone-control viewer token` shows it and the command below.+- **This machine**: `http://127.0.0.1:8200/mcp` (the viewer's port). Claude Code: `claude mcp add --transport http iphone http://127.0.0.1:8200/mcp --header "Authorization: Bearer <token>"`; in a configuration file `{"type": "http", "url": "http://127.0.0.1:8200/mcp", "headers": {"Authorization": "Bearer <token>"}}`.- **Another computer on the local network**: the viewer needs `--lan` (`IPHONE_CONTROL_VIEWER_LAN=1`); the address is `https://<this machine's address>:8200/mcp`. With the self-signed certificate made there, the client has to trust it: copy `~/.local/share/iphone-control/viewer-tls/cert.pem` from that machine and start Node-based clients (Claude Code and others) with `NODE_EXTRA_CA_CERTS=cert.pem`; or give the viewer a certificate of your own (`--tls-cert`/`--tls-key`). If the client uses a proxy, add the machine's address to `NO_PROXY`.- **In a task**: when an agent platform opens a task with `task run`, have the agent's MCP requests carry the header `Iphone-Control-Task-Token: <the value of IPHONE_CONTROL_TASK_TOKEN>`; it does what that variable does on stdio (each step shows on the page, calls wait while paused, `iphone_confirm` is listed).- **Off**: `viewer --mcp off` (`IPHONE_CONTROL_VIEWER_MCP=off`).-::: warning No login yet-Whoever can open the viewer can use `/mcp`: every user on this machine, and with `--lan` anyone on the network who can reach it. As for the page, only local-network addresses may connect and `Host` is checked; other web pages in a browser can't use it (a request with an `Origin` must come from the page itself).+::: warning The token is the key+Whoever has it can control the phone: keep it out of configuration that gets shared, and replace it with `iphone-control viewer token --new` if it leaks. As for the page, only local-network addresses may connect and `Host` is checked; other web pages in a browser can't use it (a request with an `Origin` must come from the page itself).:::## Tips for the agentdiff --git a/website/en/guide/security.md b/website/en/guide/security.mdindex d2e92d7..2669907 100644--- a/website/en/guide/security.md+++ b/website/en/guide/security.md@@ -12,7 +12,7 @@ This page has the essentials. What is stored, who can reach it and the details o## Built-in protections-- **No network ports.** WDA is reached through usbmuxd. `wda-bridge` and the live `viewer` are explicit opt-ins that bind 127.0.0.1 only, and other web pages in your browser can't act through them. They have no login, though: every local user can use them, including starting AI tasks from the viewer, so stop them when done. `viewer --lan` opens the viewer to the local network too, still without a login: anyone on the network who can reach this machine can control the phone. It only accepts connections from local-network addresses; use it only on a trusted network. The same goes for MCP on the viewer's port (`/mcp`); `--mcp off` turns it off.+- **No network ports.** WDA is reached through usbmuxd. `wda-bridge` and the live `viewer` are explicit opt-ins that bind 127.0.0.1 only, and other web pages in your browser can't act through them. `wda-bridge` has no login: every local user can use it, so stop it when done. The `viewer` and the MCP on its port (`/mcp`) need the login token, from this machine too, since the viewer can't tell a local browser from a visit forwarded by frp, cloudflared or another reverse proxy. The token is kept in the data directory (0600); `viewer token` shows it and `viewer token --new` replaces it. `viewer --lan` opens the viewer to the local network, only to local-network addresses and over HTTPS there.- **No root.** The daemon runs as your regular user, as a per-user service; the install script refuses to run as root.- **Auto-unlock is off by default** and disables itself after one wrong attempt.- **Developer tools are off by default.**diff --git a/website/guide/cli.md b/website/guide/cli.mdindex d87f26e..54c335a 100644--- a/website/guide/cli.md+++ b/website/guide/cli.md@@ -130,7 +130,8 @@ Viewer 只监听本机回环地址。同机其他用户也能查看安装信息|---|---|| `notify-test [事件]` | 发测试通知:每类事件各一条,或只发一类(`resign`、`session`、`pin`、`pin-recovered`、`unlock`、`offline`、`online`) || `wda-bridge [--port <端口>]` | 把 WDA 桥接到 `127.0.0.1`,端口默认 8100,给别的工具用。WDA 没有认证,本机任何用户都能连上,用完就停 |-| `viewer [--port <端口>] [--lan] [--lan-host <名字>…] [--tls auto\|on\|off] [--tls-cert <PEM> --tls-key <PEM>] [--mcp on\|off]` | 浏览器里的控制台,同一个端口的 `/mcp` 还提供 MCP over HTTP(见[接入 AI 客户端](./mcp-clients#通过-url-接入-http),`--mcp off` 关掉),地址 `http://127.0.0.1:8200/`(默认端口);加 `--lan` 时局域网里也能用 `https://<这台机器的 IP>:8200/` 打开(同一个端口;局域网来的 `http://` 会跳到 `https://`)。还没有登录,局域网里任何人都能操作手机。证书默认是本机生成的自签证书(存在数据目录的 `viewer-tls/`,一直沿用),浏览器第一次打开会提示不受信任:核对启动时或 `service status` 显示的 SHA-256 指纹一致后继续。用 `--tls-cert`/`--tls-key` 换成自己的证书(mkcert、`tailscale cert` 等)就没有这个提示。`--tls off` 时局域网里是 HTTP,画面退回 MJPEG(浏览器只在 localhost 或 HTTPS 上提供 WebCodecs)。中英文(默认跟着 `IPHONE_CONTROL_LANG`,页面上可切换)。**画面:** 实时画面像触摸屏一样用:点一下是点击,拖动是滑动,按住是长按,滚动鼠标滚轮或触控板也能滚动页面,另有输入框和硬件键。iOS 27 起手指跟着鼠标实时移动(经 CoreDevice HID,最后一次触摸后 30 秒内手机保持亮屏);更低的版本在松开后发整段手势。操作都和 MCP 调用一样经守护进程,和 agent 的操作排队,并先自动解锁。iOS 27 及以上画面直接用手机自己的视频;其余来自 WDA(WDA 没就绪时没有画面),是 H.264 或 MJPEG,见下面的[画面编码](#viewer-picture)。画面与设备实测的尺寸、方向一致时可以点按。转屏或换机后,请在新画面上重新操作。侧栏底部的「设置」可调整主题和字号,画面缩放用画面上方的加减号调整(双指捏合不缩放,免得拖动时误触)。**设备面板:** 状态和就绪检查、已安装的 App、屏幕上的元素。页面跟着守护进程控制的设备走,在页面上或别处切换设备,画面和面板都会跟过去,见[多台设备](./multi-device#control-page)。**AI 任务:** 写下任务,交给本机的 agent 执行(PATH 里有的 Claude Code 或 Codex,在页面上选)。开任务前可以用 Agent 旁边的 App 按钮限定范围,到了别的 App 每一步都先等你确认。可以暂停、接管后交还、停止;付款、删除、发消息之前它会在页面上请你确认。本机任何用户都能连上这个端口,用完就停 |+| `viewer [--port <端口>] [--lan] [--lan-host <名字>…] [--tls auto\|on\|off] [--tls-cert <PEM> --tls-key <PEM>] [--mcp on\|off]` | 浏览器里的控制台,**要先登录**:所有经 HTTP 的访问(本机也一样,经 frp 等反向代理转发进来的访问看起来就是本机)都要令牌,`viewer token` 显示令牌和点开就能登录的链接;浏览器登录一次后记住 30 天,程序和 MCP 客户端用 `Authorization: Bearer <令牌>`。同一个端口的 `/mcp` 还提供 MCP over HTTP(见[接入 AI 客户端](./mcp-clients#通过-url-接入-http),`--mcp off` 关掉),地址 `http://127.0.0.1:8200/`(默认端口);加 `--lan` 时局域网里也能用 `https://<这台机器的 IP>:8200/` 打开(同一个端口;局域网来的 `http://` 会跳到 `https://`)。证书默认是本机生成的自签证书(存在数据目录的 `viewer-tls/`,一直沿用),浏览器第一次打开会提示不受信任:核对启动时或 `service status` 显示的 SHA-256 指纹一致后继续。用 `--tls-cert`/`--tls-key` 换成自己的证书(mkcert、`tailscale cert` 等)就没有这个提示。`--tls off` 时局域网里是 HTTP,画面退回 MJPEG(浏览器只在 localhost 或 HTTPS 上提供 WebCodecs)。中英文(默认跟着 `IPHONE_CONTROL_LANG`,页面上可切换)。**画面:** 实时画面像触摸屏一样用:点一下是点击,拖动是滑动,按住是长按,滚动鼠标滚轮或触控板也能滚动页面,另有输入框和硬件键。iOS 27 起手指跟着鼠标实时移动(经 CoreDevice HID,最后一次触摸后 30 秒内手机保持亮屏);更低的版本在松开后发整段手势。操作都和 MCP 调用一样经守护进程,和 agent 的操作排队,并先自动解锁。iOS 27 及以上画面直接用手机自己的视频;其余来自 WDA(WDA 没就绪时没有画面),是 H.264 或 MJPEG,见下面的[画面编码](#viewer-picture)。画面与设备实测的尺寸、方向一致时可以点按。转屏或换机后,请在新画面上重新操作。侧栏底部的「设置」可调整主题和字号,画面缩放用画面上方的加减号调整(双指捏合不缩放,免得拖动时误触)。**设备面板:** 状态和就绪检查、已安装的 App、屏幕上的元素。页面跟着守护进程控制的设备走,在页面上或别处切换设备,画面和面板都会跟过去,见[多台设备](./multi-device#control-page)。**AI 任务:** 写下任务,交给本机的 agent 执行(PATH 里有的 Claude Code 或 Codex,在页面上选)。开任务前可以用 Agent 旁边的 App 按钮限定范围,到了别的 App 每一步都先等你确认。可以暂停、接管后交还、停止;付款、删除、发消息之前它会在页面上请你确认。令牌就是钥匙,别外传 |+| `viewer token [--new]` | 显示控制台的登录令牌(存在数据目录的 `viewer-token`,0600)、本机和局域网的登录链接,以及接入 HTTP MCP 的命令;`--new` 换一个新令牌,之前登录的浏览器和 MCP 客户端都要用新令牌,控制台服务在运行就随之重启 || `task run [--title <标题>] [--app <App>…] -- <命令>` | 给别的 agent 平台用的 AI 任务:在当前控制的设备上开一个任务,再运行这条命令。命令启动的 `iphone-control mcp` 自动加入任务(经环境变量 `IPHONE_CONTROL_TASK_TOKEN`),控制台上能看到每一步,可以暂停、接管、停止,付款、发消息之前会等你确认。命令结束,任务就结束;任务在别处被停止,命令也会被停止;按 Ctrl-C 等于停止任务。任务进行中,其他客户端只能看,不能操作手机。`--app`(可写多次,App 名或 Bundle ID)把任务限定在这些 App 里:到了别的 App、或者要打开网页以外的链接,每一步都先等你确认 || `task list` / `task events <id>` | 最近的任务(`--json` 给程序读);跟着一个任务的事件,每行一个 JSON || `task pause\|resume\|takeover\|handback\|stop <id>`、`task approve\|reject <id>` | 在命令行里控制任务,和控制台上的按钮一样。只能由人来做:在任务里面(Agent 的环境或它启动的进程)执行会被拒绝,`stop` 除外 |diff --git a/website/guide/configuration.md b/website/guide/configuration.mdindex aa748e8..196408e 100644--- a/website/guide/configuration.md+++ b/website/guide/configuration.md@@ -29,7 +29,7 @@ iphone-control service restart| `IPHONE_CONTROL_VIEWER_QP` | `20` | H.264 的画质,1~51,越小越清晰、流量越大。`20` 正常使用看不出和原画的差别;`24` 约省三分之一流量,快速滚动时小字略糊 || `IPHONE_CONTROL_VIEWER_PORT` | `8200` | 控制台的端口,同 `viewer --port`(控制台服务也读它) || `IPHONE_CONTROL_VIEWER_LAN_HOSTS` | 空 | `--lan` 时还认可的主机名,逗号分隔,同 `--lan-host` |-| `IPHONE_CONTROL_VIEWER_LAN` | 关 | 设为 `1` 时控制台也对局域网开放,同 `viewer --lan`,局域网里用 HTTPS。还没有登录:局域网里任何能连上这台机器的人都能操作手机、开 AI 任务,只在可信的网络里开 |+| `IPHONE_CONTROL_VIEWER_LAN` | 关 | 设为 `1` 时控制台也对局域网开放,同 `viewer --lan`,局域网里用 HTTPS。和本机一样要令牌登录(`iphone-control viewer token`) || `IPHONE_CONTROL_VIEWER_TLS` | `auto` | 控制台的 HTTPS,同 `--tls`:`auto` 在对局域网开放或给了证书时开启,`on`、`off`。本机的 `http://127.0.0.1` 一直能用 || `IPHONE_CONTROL_VIEWER_TLS_CERT`、`IPHONE_CONTROL_VIEWER_TLS_KEY` | 空 | 控制台用自己的证书和私钥(PEM),同 `--tls-cert`、`--tls-key`;不设就用本机生成的自签证书 || `IPHONE_CONTROL_VIEWER_MCP` | `on` | 控制台同一个端口上的 MCP over HTTP(`/mcp`),同 `--mcp`;`off` 关掉 |diff --git a/website/guide/mcp-clients.md b/website/guide/mcp-clients.mdindex b27168d..6c73294 100644--- a/website/guide/mcp-clients.md+++ b/website/guide/mcp-clients.md@@ -44,13 +44,14 @@ MCP 服务经本机的 Unix socket 找守护进程。客户端在另一台电脑控制台(`iphone-control viewer`,或装成服务的 `service viewer install`)在同一个端口上还提供 MCP over HTTP(Streamable HTTP),路径是 `/mcp`,工具和上面的 stdio 方式完全一样。适合只能填 URL 的客户端,以及另一台电脑上的 agent。-- **本机**:`http://127.0.0.1:8200/mcp`(端口跟着控制台)。Claude Code:`claude mcp add --transport http iphone http://127.0.0.1:8200/mcp`;配置文件里写 `{"type": "http", "url": "http://127.0.0.1:8200/mcp"}`。+- **登录**:和控制台一样要令牌,请求头 `Authorization: Bearer <令牌>`。`iphone-control viewer token` 显示令牌和下面这条命令。+- **本机**:`http://127.0.0.1:8200/mcp`(端口跟着控制台)。Claude Code:`claude mcp add --transport http iphone http://127.0.0.1:8200/mcp --header "Authorization: Bearer <令牌>"`;配置文件里写 `{"type": "http", "url": "http://127.0.0.1:8200/mcp", "headers": {"Authorization": "Bearer <令牌>"}}`。- **局域网里另一台电脑**:控制台要开 `--lan`(`IPHONE_CONTROL_VIEWER_LAN=1`),地址是 `https://<这台机器的 IP>:8200/mcp`。证书是本机生成的自签证书时,客户端要信任它:把那台机器上的 `~/.local/share/iphone-control/viewer-tls/cert.pem` 拷过来,Node 写的客户端(Claude Code 等)用 `NODE_EXTRA_CA_CERTS=cert.pem` 启动;也可以用 `--tls-cert`/`--tls-key` 换成自己的证书。客户端配了代理时,把这台机器的 IP 加进 `NO_PROXY`。- **在任务里**:agent 平台用 `task run` 开任务时,让 agent 的 MCP 请求带上请求头 `Iphone-Control-Task-Token: <IPHONE_CONTROL_TASK_TOKEN 的值>`,作用和 stdio 方式下的环境变量一样(每一步显示在控制台上,暂停时等待,多出 `iphone_confirm`)。- **关掉**:`viewer --mcp off`(`IPHONE_CONTROL_VIEWER_MCP=off`)。-::: warning 还没有登录-能打开控制台的人就能用 `/mcp`:本机是本机所有用户,开了 `--lan` 就是局域网里所有能连上这台机器的人。和控制台一样只接受局域网地址来的连接、检查 `Host`;浏览器里别的网页借不了它(带 `Origin` 的请求必须来自控制台自己)。+::: warning 令牌就是钥匙+有令牌就能操作手机:别写进会公开的配置。泄露了用 `iphone-control viewer token --new` 换掉。和控制台一样只接受局域网地址来的连接、检查 `Host`;浏览器里别的网页借不了它(带 `Origin` 的请求必须来自控制台自己)。:::## 给 agent 的建议diff --git a/website/guide/security.md b/website/guide/security.mdindex ff5a265..26184c5 100644--- a/website/guide/security.md+++ b/website/guide/security.md@@ -12,7 +12,7 @@ iphone-control 本质上是一个手机遥控器:能访问它的人,就能## 默认的保护-- **不开网络端口。** WDA 经 usbmuxd 直连手机。`wda-bridge` 和实时画面 `viewer` 都要显式开启,只绑 127.0.0.1,浏览器里的其他网页借不了它们操作手机。但它们没有登录,本机任何用户都能用(包括在 viewer 上发起 AI 任务),用完就停。`viewer --lan` 会把控制台也开放给局域网,仍然没有登录,局域网里任何能连上这台机器的人都能操作手机;只接受局域网地址来的连接,只在可信的网络里开。控制台同一个端口上的 MCP(`/mcp`)也一样,`--mcp off` 关掉。+- **不开网络端口。** WDA 经 usbmuxd 直连手机。`wda-bridge` 和实时画面 `viewer` 都要显式开启,只绑 127.0.0.1,浏览器里的其他网页借不了它们操作手机。`wda-bridge` 没有登录,本机任何用户都能用,用完就停。`viewer` 和它同一个端口上的 MCP(`/mcp`)要令牌登录,本机也一样:控制台分不清本机的浏览器和经 frp、cloudflared 等反向代理转发进来的访问。令牌存在数据目录(0600),`viewer token` 显示,`viewer token --new` 换掉。`viewer --lan` 会把控制台开放给局域网,只接受局域网地址来的连接,局域网里走 HTTPS。- **不用 root。** 守护进程以你的普通用户身份作为用户服务运行,安装脚本拒绝以 root 运行。- **自动解锁默认关闭**,输错一次即停用。- **开发者工具默认关闭**。