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): speak HTTPS to the local network on the same port (#76)
Qinghe Lie957466017de
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c60ab81..403ffe2 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 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.- An AI task's agent can no longer pause, resume, take over, hand back or confirm its own task, so only a person answers out-of-scope steps and `iphone_confirm`. Control requests carrying the task's token (`IPHONE_CONTROL_TASK_TOKEN`) are refused, and so are those from an agent the control page or `task run` started, or any process it starts, even without the token or through the page's API. On macOS, calls through the page's API can't be traced to a process yet. Stopping a task is always allowed. The task's log records who controlled it (the page, the command line, the task's opener).- Navigate setup menus with arrow keys, confirm with Enter, or cancel with Esc. Number selection remains available, and basic terminals keep the line-by-line prompts.diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex 022fdfc..f4a902d 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -8,6 +8,7 @@### 新增+- 控制台对局域网开放(`--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 任务在跑时自动升级会推迟。- AI 任务的 Agent 不能再自己暂停、继续、接管、交还或确认,越界确认和 `iphone_confirm` 只能由人回答。带任务口令(`IPHONE_CONTROL_TASK_TOKEN`)的控制请求会被拒绝;控制台和 `task run` 启动的 Agent,连同它再启动的进程,也会被拒绝,即使去掉了口令,或者调用控制台的接口。在 macOS 上,调用控制台接口的这条路还查不出是哪个进程。停止任务不受限制。任务记录里会写下谁做了控制(控制台、命令行、任务的发起方)。- 设置菜单支持方向键选择、Enter 确认和 Esc 取消,保留数字选择;基础终端继续使用逐行提示。diff --git a/Cargo.lock b/Cargo.lockindex df5440c..095ba5d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2297,6 +2297,7 @@ dependencies = ["ictl-wda","libc","plist",+ "rcgen","reqwest 0.13.5","ring","rustls",@@ -2308,6 +2309,7 @@ dependencies = ["tempfile","termion","tokio",+ "tokio-rustls","tracing","tracing-subscriber","uuid",diff --git a/Cargo.toml b/Cargo.tomlindex 7159523..69501e8 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -55,6 +55,9 @@ tokio = { version = "=1.54.1", features = ["full"] }# rustls-no-provider:不编进 aws-lc-rs(C 代码,编译慢、体积大);idevice/plume_core 用 ring,入口处显式装 ring 为默认 providerreqwest = { version = "=0.13.5", default-features = false, features = ["form", "rustls-no-provider"] }rustls = { version = "=0.23.46", default-features = false, features = ["ring"] }+# 控制台的 HTTPS(viewer --lan):两者已经在依赖树里(idevice、reqwest、plume_core),同样只用 ring+tokio-rustls = { version = "=0.26.6", default-features = false, features = ["ring"] }+rcgen = "=0.12.1"quick-xml = "=0.42.0"image = { version = "=0.25.10", default-features = false, features = ["png", "jpeg"] }clap = { version = "=4.6.7", features = ["derive", "env"] }diff --git a/apps/iphone-control/Cargo.toml b/apps/iphone-control/Cargo.tomlindex bf0fbdb..97ddd54 100644--- a/apps/iphone-control/Cargo.toml+++ b/apps/iphone-control/Cargo.toml@@ -23,6 +23,8 @@ termion.workspace = truetokio.workspace = trueanyhow.workspace = truerustls.workspace = true+tokio-rustls.workspace = true+rcgen.workspace = truereqwest.workspace = trueserde.workspace = trueserde_json.workspace = truediff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rsindex e58c6a3..a506db6 100644--- a/apps/iphone-control/src/main.rs+++ b/apps/iphone-control/src/main.rs@@ -112,10 +112,16 @@ 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!("也对局域网开放(同一个端口、HTTP、还没有登录:局域网里任何人都能操作手机),只接受局域网地址来的连接", "Also open to the local network (same port, HTTP, 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;还没有登录:局域网里任何人都能操作手机),只接受局域网地址来的连接", "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"))]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>,+ #[arg(long, value_enum, env = "IPHONE_CONTROL_VIEWER_TLS", default_value = "auto", help = ictl_l10n::tr!("HTTPS(同一个端口,本机仍可用 http://127.0.0.1):auto 在 --lan 或给了证书时开启;on、off", "HTTPS (same port; http://127.0.0.1 still works on this machine): auto turns it on with --lan or a certificate; on, off"))]+ tls: viewer::tls::Mode,+ #[arg(long = "tls-cert", value_name = "PEM", env = "IPHONE_CONTROL_VIEWER_TLS_CERT", requires = "tls_key", help = ictl_l10n::tr!("自己的证书(PEM,可带证书链),比如 mkcert 或 tailscale cert 生成的;不给就用本机生成的自签证书", "Your own certificate (PEM, chain allowed), such as one from mkcert or tailscale cert; without it a self-signed one made on this machine"))]+ tls_cert: Option<PathBuf>,+ #[arg(long = "tls-key", value_name = "PEM", env = "IPHONE_CONTROL_VIEWER_TLS_KEY", requires = "tls_cert", help = ictl_l10n::tr!("--tls-cert 的私钥(PEM)", "The private key of --tls-cert (PEM)"))]+ tls_key: Option<PathBuf>,},#[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 {@@ -296,7 +302,7 @@ async fn run() -> anyhow::Result<()> {Command::Status => status(&cli.socket).await,Command::Doctor => print_text(&cli.socket, Request::Doctor).await,Command::Setup { reconfigure } => guide::setup(&cli, reconfigure).await,- Command::Service { action } => service_cmd(&cli.socket, action).await,+ Command::Service { action } => service_cmd(&cli.socket, &cli.data_dir, action).await,Command::Login { email } => login(&cli.data_dir, email).await,Command::Sign => print_text(&cli.socket, Request::Resign { force: true }).await,Command::Resign { force } => print_text(&cli.socket, Request::Resign { force }).await,@@ -305,8 +311,9 @@ 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 } => {- viewer::run(&cli.socket, &cli.data_dir, port, lan, &lan_hosts).await+ Command::Viewer { port, lan, lan_hosts, tls, tls_cert, tls_key } => {+ 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).await}Command::Task { action } => task::run(&cli.socket, action).await,#[cfg(feature = "debug-cmds")]@@ -410,7 +417,7 @@ fn mcp_config(socket: &Path) -> anyhow::Result<String> {Ok(mcp_command(&service::stable_exe()?, socket))}-async fn service_cmd(socket: &Path, action: ServiceAction) -> anyhow::Result<()> {+async fn service_cmd(socket: &Path, data_dir: &Path, action: ServiceAction) -> anyhow::Result<()> {let none = || {anyhow::anyhow!("{}",@@ -458,6 +465,16 @@ async fn service_cmd(socket: &Path, action: ServiceAction) -> anyhow::Result<()>)),}+ // to check against the browser's warning when the page is opened from another machine+ if let Some(fp) = viewer::tls::made_fingerprint(data_dir) {+ println!(+ "{}",+ ictl_l10n::trf!(+ " 本机生成的 HTTPS 证书 SHA-256 {fp}",+ " HTTPS certificate made here, SHA-256 {fp}"+ )+ );+ }let up = snapshot(socket).await.is_ok();println!("{}",@@ -1193,7 +1210,7 @@ const MAX_HEAD: usize = 16 * 1024;const READ_TIMEOUT: Duration = Duration::from_secs(10);/// 读到请求头结束;返回头部和跟着一起到的那部分请求体-async fn read_head(client: &mut tokio::net::TcpStream) -> anyhow::Result<(Vec<u8>, Vec<u8>)> {+async fn read_head(client: &mut (impl tokio::io::AsyncRead + Unpin)) -> anyhow::Result<(Vec<u8>, Vec<u8>)> {use tokio::io::AsyncReadExt;let mut data = Vec::new();let mut buf = [0u8; 4096];@@ -1249,7 +1266,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, .. })) => (port, lan, lan_hosts),other => panic!("{lan:?}: {:?}", other.err()),}};diff --git a/apps/iphone-control/src/video/device.rs b/apps/iphone-control/src/video/device.rsindex 6568877..4f23b7e 100644--- a/apps/iphone-control/src/video/device.rs+++ b/apps/iphone-control/src/video/device.rs@@ -18,7 +18,6 @@ use std::time::{Duration, Instant};use ictl_daemon::protocol::{SCREEN_KEYFRAME, ScreenMsg};use tokio::io::{AsyncReadExt, AsyncWriteExt};-use tokio::net::TcpStream;use tokio::sync::mpsc;use super::{AbortOnDrop, Acks, Flow, QUEUE, STREAM_IDLE, message, send_video};@@ -45,7 +44,7 @@ pub async fn serve(mut src: tokio::io::BufReader<tokio::net::unix::OwnedReadHalf>,mut daemon_w: tokio::net::unix::OwnedWriteHalf,acks: Arc<Acks>,- client: TcpStream,+ client: impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,) {let (ack_guard, mut acked) = acks.register();let mut flow = Flow::default();diff --git a/apps/iphone-control/src/video/mod.rs b/apps/iphone-control/src/video/mod.rsindex 7e84579..315143c 100644--- a/apps/iphone-control/src/video/mod.rs+++ b/apps/iphone-control/src/video/mod.rs@@ -38,7 +38,6 @@ use std::time::{Duration, Instant};use serde_json::json;use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};-use tokio::net::TcpStream;use tokio::sync::{mpsc, watch};pub use ffmpeg::Encoders;@@ -205,7 +204,7 @@ pub async fn serve(enc: Arc<Encoders>,acks: Arc<Acks>,src: impl AsyncRead + Unpin + Send + 'static,- client: TcpStream,+ client: impl AsyncRead + AsyncWrite + Unpin + Send + 'static,) {let (ack_guard, mut acked) = acks.register();let mut flow = Flow::default();@@ -441,7 +440,8 @@ async fn write_with_progress(writer: &mut (impl AsyncWrite + Unpin), mut data: &_ => return false,}}- true+ // over TLS the last record may still be buffered: each message (a frame) goes out now+ matches!(tokio::time::timeout(idle, writer.flush()).await, Ok(Ok(())))}async fn send_video(@@ -624,7 +624,7 @@ mod tests {// the page, over a real TCP connection, reporting what it read every 100 ms like viewer.htmllet l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();- let mut page = TcpStream::connect(l.local_addr().unwrap()).await.unwrap();+ let mut page = tokio::net::TcpStream::connect(l.local_addr().unwrap()).await.unwrap();let (server_side, _) = l.accept().await.unwrap();let acks = Arc::new(Acks::default());let _server = AbortOnDrop(tokio::spawn(serve(enc, acks.clone(), src, server_side)));diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rsindex ecf801a..c2a3d9f 100644--- a/apps/iphone-control/src/viewer.rs+++ b/apps/iphone-control/src/viewer.rs@@ -28,6 +28,7 @@mod lan;mod peer;+pub mod tls;use std::collections::{HashMap, HashSet};use std::path::{Path, PathBuf};@@ -38,8 +39,8 @@ use anyhow::bail;use ictl_daemon::machine::DeviceState;use ictl_daemon::protocol::{self, Request, Response, TouchPhase};use serde_json::{Value, json};+use tls::Conn;use tokio::io::{AsyncReadExt, AsyncWriteExt};-use tokio::net::TcpStream;use crate::agent::{self, Agents};@@ -74,6 +75,8 @@ struct Ctx {video: Option<Arc<crate::video::Encoders>>,/// How much of each H.264 stream its page has readacks: Arc<crate::video::Acks>,+ /// HTTPS on the same port (`--lan`); plain HTTP from the network is then sent there+ tls: Option<Arc<tls::Tls>>,}/// A picture handler can be cancelled at any await, including while opening its source.@@ -103,8 +106,16 @@ impl Ctx {}}-/// `lan`: also open the page to the local network (`--lan`); `lan_hosts`: more names it answers to there-pub async fn run(socket: &Path, data_dir: &Path, port: u16, lan: bool, lan_hosts: &[String]) -> anyhow::Result<()> {+/// `lan`: also open the page to the local network (`--lan`); `lan_hosts`: more names it answers to there; `tls`:+/// whether and with which certificate it speaks HTTPS+pub async fn run(+ socket: &Path,+ data_dir: &Path,+ port: u16,+ lan: bool,+ lan_hosts: &[String],+ tls: &tls::Setting,+) -> anyhow::Result<()> {// only a first guess: the page follows whichever device the daemon controls (see `info`). Not knowing yet is// fine: the daemon may still be starting (started together with this at login), and with several devices// connected it is the one that picks@@ -124,6 +135,10 @@ pub async fn run(socket: &Path, data_dir: &Path, port: u16, lan: bool, lan_hostslet access = if lan { lan::Access::lan(lan_hosts) } else { lan::Access::local() };let listener = tokio::net::TcpListener::bind((access.bind_ip(), port)).await?;let port = listener.local_addr()?.port();+ let tls = match tls.enabled(access.is_lan()) {+ true => Some(Arc::new(tls.load(data_dir, &access.names())?)),+ false => None,+ };let agents = Agents::new(socket)?;println!("{}",@@ -174,17 +189,51 @@ pub async fn run(socket: &Path, data_dir: &Path, port: u16, lan: bool, lan_hostsictl_l10n::trf!("AI 任务可用:{}", "AI tasks available with: {}", found.join(", "))});+ let scheme = if tls.is_some() { "https" } else { "http" };+ if let Some(t) = &tls {+ if t.made {+ println!(+ "{}",+ ictl_l10n::trf!(+ "HTTPS:证书是本机生成的({}),SHA-256 指纹 {}。浏览器第一次打开会提示证书不受信任:核对指纹一致后继续访问。想免掉这一步,用 --tls-cert/--tls-key 换成自己的证书",+ "HTTPS: a certificate made on this machine ({}), SHA-256 fingerprint {}. The first time, the browser warns that it isn't trusted: check that the fingerprint matches, then go on. To skip that, use a certificate of your own (--tls-cert/--tls-key)",+ t.cert.display(),+ t.fingerprint+ )+ );+ } else {+ println!(+ "{}",+ ictl_l10n::trf!(+ "HTTPS:证书 {}(SHA-256 {})",+ "HTTPS: certificate {} (SHA-256 {})",+ t.cert.display(),+ t.fingerprint+ )+ );+ }+ }if access.is_lan() {for a in access.addresses() {- println!("{}", ictl_l10n::trf!("局域网:http://{a}:{port}/", "On the network: http://{a}:{port}/"));+ println!("{}", ictl_l10n::trf!("局域网:{scheme}://{a}:{port}/", "On the network: {scheme}://{a}:{port}/"));+ }+ if tls.is_some() {+ println!(+ "{}",+ 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."+ )+ );+ } else {+ println!(+ "{}",+ 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."+ )+ );}- println!(- "{}",- 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."- )- );} else {println!("{}",@@ -209,6 +258,7 @@ pub async fn run(socket: &Path, data_dir: &Path, port: u16, lan: bool, lan_hostsdevice_video_allowed,video,acks: Arc::default(),+ tls,});let slots = Arc::new(tokio::sync::Semaphore::new(crate::MAX_CONNECTIONS));loop {@@ -223,6 +273,18 @@ pub async fn run(socket: &Path, data_dir: &Path, port: u16, lan: bool, lan_hostslet Ok(slot) = slots.clone().try_acquire_owned() else { continue };let ctx = ctx.clone();tokio::spawn(async move {+ let client = match &ctx.tls {+ // the handshake in the connection's own task: a slow client doesn't hold up the others+ Some(t) => match t.accept(client).await {+ Ok(c) => c,+ Err(e) => {+ tracing::debug!("viewer TLS: {e}");+ drop(slot);+ return;+ }+ },+ None => Conn::Plain(client),+ };if let Err(e) = serve(client, &ctx).await {tracing::debug!("viewer connection: {e}");}@@ -242,7 +304,7 @@ fn page_in(lang: ictl_l10n::Lang) -> String {/// One request per connection (`Connection: close`), which keeps the parser small. It is handled in the page's/// language (`X-Ictl-Lang`), so the daemon's messages match the page-async fn serve(mut client: TcpStream, ctx: &Ctx) -> anyhow::Result<()> {+async fn serve(mut client: Conn, ctx: &Ctx) -> anyhow::Result<()> {let (head, body) = crate::read_head(&mut client).await?;let Some(req) = Head::parse(&head) else {return reply(&mut client, 400, "text/plain", b"bad request").await;@@ -253,10 +315,18 @@ async fn serve(mut client: TcpStream, ctx: &Ctx) -> anyhow::Result<()> {}}-async fn handle(mut client: TcpStream, ctx: &Ctx, head: Vec<u8>, req: Head, mut body: Vec<u8>) -> anyhow::Result<()> {+async fn handle(mut client: Conn, ctx: &Ctx, head: Vec<u8>, req: Head, mut body: Vec<u8>) -> anyhow::Result<()> {if !ctx.access.host_allowed(&head) || (req.path != "/" && !fetch_site_ok(&req)) {return reply(&mut client, 403, "text/plain", b"forbidden").await;}+ // HTTPS is on: from the network only HTTPS (plain HTTP stays for this machine)+ let local = client.tcp().peer_addr().is_ok_and(|a| a.ip().to_canonical().is_loopback());+ if ctx.tls.is_some() && !client.is_tls() && !local {+ let Some(to) = https_location(&head, &req, ctx.port) else {+ return reply(&mut client, 400, "text/plain", b"bad request").await;+ };+ return redirect(&mut client, &to).await;+ }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,@@ -335,14 +405,15 @@ async fn handle(mut client: TcpStream, ctx: &Ctx, head: Vec<u8>, req: Head, mut}}-async fn video_head(client: &mut TcpStream) -> anyhow::Result<()> {+async fn video_head(client: &mut Conn) -> anyhow::Result<()> {let head = b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nCache-Control: no-store\r\n\X-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\n";tokio::time::timeout(crate::video::STREAM_IDLE, client.write_all(head)).await??;+ tokio::time::timeout(crate::video::STREAM_IDLE, client.flush()).await??;Ok(())}-async fn picture(mut client: TcpStream, ctx: &Ctx, req: &Head) -> anyhow::Result<()> {+async fn picture(mut client: Conn, ctx: &Ctx, req: &Head) -> anyhow::Result<()> {// the device the page shows (`?udid=`), so a page that hasn't noticed a switch keeps its own picture// instead of silently showing another phone. Looked up again each time: after a replug usbmuxd gives the// device a new id@@ -416,8 +487,10 @@ struct Caller {}impl Caller {- async fn of(client: &TcpStream) -> Self {- let (Ok(peer), Ok(local)) = (client.peer_addr(), client.local_addr()) else { return Self::default() };+ async fn of(client: &Conn) -> Self {+ let (Ok(peer), Ok(local)) = (client.tcp().peer_addr(), client.tcp().local_addr()) else {+ return Self::default();+ };// reads every process's open files: not on the runtime's threadslet pid = tokio::task::spawn_blocking(move || peer::local_client(peer, local)).await.ok().flatten();let by = if peer.ip().to_canonical().is_loopback() { "viewer".into() } else { format!("viewer {}", peer.ip()) };@@ -522,18 +595,20 @@ async fn post(ctx: &Ctx, name: &str, b: &Value, device: Option<&str>, caller: Ca}/// The task's events so far, then new ones as they come (from the daemon), as server-sent events, until it is done-async fn events(client: &mut TcpStream, mut stream: protocol::TaskStream) -> anyhow::Result<()> {+async fn events(client: &mut Conn, mut stream: protocol::TaskStream) -> anyhow::Result<()> {client.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\n\X-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\n",).await?;+ client.flush().await?;loop {tokio::select! {e = stream.next() => match e {Some(e) => {client.write_all(sse(&e).as_bytes()).await?;+ client.flush().await?;if e.event == "done" {return Ok(());}@@ -542,7 +617,10 @@ async fn events(client: &mut TcpStream, mut stream: protocol::TaskStream) -> anyNone => return Ok(()),},// a comment now and then finds a page that went away- _ = tokio::time::sleep(Duration::from_secs(15)) => client.write_all(b": ping\n\n").await?,+ _ = tokio::time::sleep(Duration::from_secs(15)) => {+ client.write_all(b": ping\n\n").await?;+ client.flush().await?;+ }}}}@@ -551,11 +629,11 @@ fn sse(e: &protocol::TaskEvent) -> String {format!("event: {}\ndata: {}\n\n", e.event, e.data)}-async fn json_reply(client: &mut TcpStream, status: u16, v: &Value) -> anyhow::Result<()> {+async fn json_reply(client: &mut Conn, status: u16, v: &Value) -> anyhow::Result<()> {reply(client, status, "application/json", v.to_string().as_bytes()).await}-async fn reply(client: &mut TcpStream, status: u16, kind: &str, body: &[u8]) -> anyhow::Result<()> {+async fn reply(client: &mut Conn, status: u16, kind: &str, body: &[u8]) -> anyhow::Result<()> {let reason = match status {200 => "OK",202 => "Accepted",@@ -573,6 +651,27 @@ async fn reply(client: &mut TcpStream, status: u16, kind: &str, body: &[u8]) ->);client.write_all(head.as_bytes()).await?;client.write_all(body).await?;+ // over TLS the last record may still be buffered+ client.flush().await?;+ Ok(())+}++/// 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> {+ let host = lan::host_header(head).filter(|h| !h.is_empty())?;+ let query = if req.query.is_empty() { String::new() } else { format!("?{}", req.query) };+ Some(format!("https://{host}:{port}{}{query}", req.path))+}++/// Temporary (307): with `--tls off` later, browsers mustn't remember it+async fn redirect(client: &mut Conn, to: &str) -> anyhow::Result<()> {+ let head = format!(+ "HTTP/1.1 307 Temporary Redirect\r\nLocation: {to}\r\nContent-Length: 0\r\nCache-Control: no-store\r\n\+ Connection: close\r\n\r\n"+ );+ client.write_all(head.as_bytes()).await?;+ client.flush().await?;Ok(())}@@ -1007,9 +1106,22 @@ mod tests {video: None,acks: Arc::default(),feeds: Mutex::default(),+ tls: None,}}+ #[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);+ assert_eq!(at(b"GET / HTTP/1.1\r\nHost: 192.168.10.100:8202\r\n\r\n").unwrap(), "https://192.168.10.100:8202/");+ assert_eq!(+ at(b"GET /stream?feed=a&udid=b HTTP/1.1\r\nHost: NAS.local:8202\r\n\r\n").unwrap(),+ "https://nas.local:8202/stream?feed=a&udid=b"+ );+ assert_eq!(at(b"GET / HTTP/1.1\r\nHost: [fd00::5]:8202\r\n\r\n").unwrap(), "https://[fd00::5]:8202/");+ assert_eq!(at(b"GET / HTTP/1.1\r\n\r\n"), None);+ }+#[tokio::test]async fn cancelled_picture_unregisters_its_feed() {let temp = tempfile::tempdir_in("/tmp").unwrap();@@ -1017,11 +1129,12 @@ mod tests {let daemon = tokio::net::UnixListener::bind(&socket).unwrap();let ctx = test_ctx(temp.path(), &socket);let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();- let (tab, accepted) = tokio::join!(TcpStream::connect(listener.local_addr().unwrap()), listener.accept());+ let (tab, accepted) =+ tokio::join!(tokio::net::TcpStream::connect(listener.local_addr().unwrap()), listener.accept());let _tab = tab.unwrap();let raw = b"GET /video?src=device&udid=TEST&feed=tab HTTP/1.1\r\nHost: localhost\r\n\r\n";let (client, _) = accepted.unwrap();- let mut request = Box::pin(handle(client, &ctx, raw.to_vec(), Head::parse(raw).unwrap(), vec![]));+ let mut request = Box::pin(handle(Conn::Plain(client), &ctx, raw.to_vec(), Head::parse(raw).unwrap(), vec![]));// The simulated daemon has accepted the request but has not supplied a stream.tokio::select! {result = &mut request => panic!("picture ended before cancellation: {result:?}"),diff --git a/apps/iphone-control/src/viewer/lan.rs b/apps/iphone-control/src/viewer/lan.rsindex b5a3cfa..763b6dd 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, still plain HTTP and **without a login** (that comes later), listens on every IPv4 interface, so the-//! page can be opened from another machine on the local network. What still protects it:+//! 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://!//! - 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;@@ -77,14 +77,23 @@ impl Access {LOOPBACK.contains(&name) || (self.lan && self.hosts.iter().any(|h| h == name))}+ /// The names the page answers to, for its certificate: the loopback ones too, IPv6 without brackets+ pub fn names(&self) -> Vec<String> {+ let mut v: Vec<String> = vec!["localhost".into(), "127.0.0.1".into(), "::1".into()];+ v.extend(self.hosts.iter().map(|h| h.trim_start_matches('[').trim_end_matches(']').to_owned()));+ v+ }+/// The request's `Host` names this machinepub fn host_allowed(&self, head: &[u8]) -> bool {host_header(head).is_some_and(|h| self.knows(&h))}- /// An action's `Origin` is this page: `http://<a known name>:<port>`+ /// An action's `Origin` is this page: `http://` or `https://<a known name>:<port>`pub fn origin_allowed(&self, origin: &str, port: u16) -> bool {- let Some(rest) = origin.strip_prefix("http://") else { return false };+ let Some(rest) = origin.strip_prefix("http://").or_else(|| origin.strip_prefix("https://")) else {+ return false;+ };let rest = rest.to_ascii_lowercase();let Some((name, p)) = rest.rsplit_once(':') else { return false };p.parse::<u16>().ok() == Some(port) && self.knows(name)@@ -109,7 +118,8 @@ pub fn peer_allowed(ip: IpAddr) -> bool {}/// The `Host` header's name without the port, lowercase; an IPv6 address in brackets-fn host_header(head: &[u8]) -> Option<String> {+/// The `Host` header's name, lowercase, without the port; IPv6 in brackets+pub fn host_header(head: &[u8]) -> Option<String> {let text = String::from_utf8_lossy(head);let host = text.split("\r\n").skip(1).find_map(|l| {let (k, v) = l.split_once(':')?;@@ -215,10 +225,15 @@ mod tests {}assert!(a.origin_allowed("http://192.168.10.100:8202", 8202));assert!(a.origin_allowed("http://NAS.local:8202", 8202));- assert!(!a.origin_allowed("https://192.168.10.100:8202", 8202), "only what is served");+ assert!(a.origin_allowed("https://192.168.10.100:8202", 8202), "the page over HTTPS");+ assert!(!a.origin_allowed("https://evil.example:8202", 8202));+ assert!(!a.origin_allowed("ftp://192.168.10.100:8202", 8202));assert!(!a.origin_allowed("http://192.168.10.100:3000", 8202), "another port");assert!(!a.origin_allowed("http://evil.example:8202", 8202));assert!(!a.origin_allowed("null", 8202));+ // what its certificate covers+ assert_eq!(a.names(), ["localhost", "127.0.0.1", "::1", "192.168.10.100", "nas.local", "nas"]);+ assert_eq!(Access::with_hosts(["[fd00::5]".into()]).names()[3], "fd00::5");}#[test]diff --git a/apps/iphone-control/src/viewer/tls.rs b/apps/iphone-control/src/viewer/tls.rsnew file mode 100644index 0000000..1047360--- /dev/null+++ b/apps/iphone-control/src/viewer/tls.rs@@ -0,0 +1,371 @@+//! HTTPS for the control page opened from the local network (docs/task-control.md 7.1, item 4).+//!+//! Browsers only offer WebCodecs (and some other APIs) in a secure context: HTTPS, or `localhost`. Opened at+//! `http://<LAN address>` the page can't decode H.264 or the phone's HEVC and falls back to MJPEG, and everything,+//! taps and typed text included, crosses the network in the clear. So with `--lan` the same port also speaks TLS:+//! the first byte of a connection tells (a TLS handshake starts with 0x16, an HTTP request with a letter). Plain+//! HTTP stays for `127.0.0.1`; from the network it is redirected to HTTPS.+//!+//! The certificate is the user's (`--tls-cert`, `--tls-key`: mkcert, `tailscale cert`, an internal CA), or one made+//! here, self-signed, kept in the data directory and reused, so the browser asks once rather than every start. Its+//! SHA-256 fingerprint is printed, to check against the browser's warning the first time. A new name or address+//! (DHCP gave the machine another one) makes a new certificate that also covers the old ones.+//!+//! Not a login: anyone who can reach the page can still use it.++use std::io;+use std::path::{Path, PathBuf};+use std::pin::Pin;+use std::sync::Arc;+use std::task::{Context, Poll};+use std::time::{Duration, SystemTime, UNIX_EPOCH};++use anyhow::{Context as _, bail};+use rustls::pki_types::pem::PemObject;+use rustls::pki_types::{CertificateDer, PrivateKeyDer};+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};+use tokio::net::TcpStream;++/// Days a made certificate is valid: under Apple's 825-day limit for TLS server certificates+const VALID_DAYS: u64 = 800;+/// A made certificate this close to its end is made again+const RENEW_DAYS: u64 = 30;+const DAY: u64 = 24 * 60 * 60;+/// A TLS record starts with its content type; 22 is a handshake (the client's hello)+const HANDSHAKE: u8 = 0x16;+/// For the first byte and for the handshake: a connection that says nothing is dropped+const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);+/// Under the data directory: the certificate made here+const DIR: &str = "viewer-tls";++/// `--tls`+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]+pub enum Mode {+ /// HTTPS with `--lan` or with a certificate of the user's+ Auto,+ On,+ Off,+}++/// `--tls`, `--tls-cert`, `--tls-key`+#[derive(Debug, Clone)]+pub struct Setting {+ pub mode: Mode,+ pub cert: Option<PathBuf>,+ pub key: Option<PathBuf>,+}++impl Setting {+ /// Whether the page speaks HTTPS+ pub fn enabled(&self, lan: bool) -> bool {+ match self.mode {+ Mode::On => true,+ Mode::Off => false,+ Mode::Auto => lan || self.cert.is_some(),+ }+ }++ /// The certificate: the user's files, or the one made here for `names`+ pub fn load(&self, data_dir: &Path, names: &[String]) -> anyhow::Result<Tls> {+ match (&self.cert, &self.key) {+ (Some(c), Some(k)) => Tls::from_files(c, k),+ (None, None) => Tls::made(data_dir, names),+ _ => bail!(ictl_l10n::tr!("--tls-cert 和 --tls-key 要一起给", "--tls-cert and --tls-key go together")),+ }+ }+}++pub struct Tls {+ acceptor: tokio_rustls::TlsAcceptor,+ /// SHA-256 of the certificate, as browsers show it (`AB:CD:…`)+ pub fingerprint: String,+ /// The certificate's file+ pub cert: PathBuf,+ /// Made here (self-signed): browsers warn the first time+ pub made: bool,+}++impl Tls {+ /// The user's certificate (PEM, may hold the chain after it) and key (PEM)+ pub fn from_files(cert: &Path, key: &Path) -> anyhow::Result<Self> {+ let c = std::fs::read(cert).with_context(|| cert.display().to_string())?;+ let k = std::fs::read(key).with_context(|| key.display().to_string())?;+ Self::new(&c, &k, cert, false)+ }++ /// The certificate made here, made (again) when there is none, it doesn't cover all of `names`, or it ends soon+ pub fn made(data_dir: &Path, names: &[String]) -> anyhow::Result<Self> {+ let dir = data_dir.join(DIR);+ let (cert, key) = ensure_made(&dir, names, now())?;+ Self::new(&cert, &key, &dir.join("cert.pem"), true)+ }++ fn new(cert_pem: &[u8], key_pem: &[u8], path: &Path, made: bool) -> anyhow::Result<Self> {+ let certs = CertificateDer::pem_slice_iter(cert_pem)+ .collect::<Result<Vec<_>, _>>()+ .map_err(|e| anyhow::anyhow!("{}: {e:?}", path.display()))?;+ let Some(first) = certs.first() else {+ bail!(ictl_l10n::trf!("{} 里没有证书", "No certificate in {}", path.display()));+ };+ let fingerprint = fingerprint(first);+ let key = PrivateKeyDer::from_pem_slice(key_pem).map_err(|e| anyhow::anyhow!("key: {e:?}"))?;+ let provider = Arc::new(rustls::crypto::ring::default_provider());+ let mut cfg = rustls::ServerConfig::builder_with_provider(provider)+ .with_safe_default_protocol_versions()?+ .with_no_client_auth()+ .with_single_cert(certs, key)+ .with_context(|| {+ ictl_l10n::trf!("证书和私钥对不上({})", "The certificate and key don't match ({})", path.display())+ })?;+ cfg.alpn_protocols = vec![b"http/1.1".to_vec()];+ Ok(Self { acceptor: tokio_rustls::TlsAcceptor::from(Arc::new(cfg)), fingerprint, cert: path.to_owned(), made })+ }++ /// The connection as it comes: TLS when it starts with a handshake, plain HTTP otherwise+ pub async fn accept(&self, tcp: TcpStream) -> io::Result<Conn> {+ let timed_out = |_| io::Error::from(io::ErrorKind::TimedOut);+ let mut first = [0u8; 1];+ let n = tokio::time::timeout(HANDSHAKE_TIMEOUT, tcp.peek(&mut first)).await.map_err(timed_out)??;+ if n == 0 || first[0] != HANDSHAKE {+ return Ok(Conn::Plain(tcp));+ }+ let s = tokio::time::timeout(HANDSHAKE_TIMEOUT, self.acceptor.accept(tcp)).await.map_err(timed_out)??;+ Ok(Conn::Tls(Box::new(s)))+ }+}++/// The fingerprint of the certificate made here, if there is one (for `service status`)+pub fn made_fingerprint(data_dir: &Path) -> Option<String> {+ let pem = std::fs::read(data_dir.join(DIR).join("cert.pem")).ok()?;+ let first = CertificateDer::pem_slice_iter(&pem).next()?.ok()?;+ Some(fingerprint(&first))+}++fn fingerprint(der: &[u8]) -> String {+ Sha256::digest(der).iter().map(|b| format!("{b:02X}")).collect::<Vec<_>>().join(":")+}++fn now() -> u64 {+ SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)+}++/// What a made certificate covers, next to it+#[derive(Serialize, Deserialize)]+struct Made {+ names: Vec<String>,+ not_after: u64,+}++/// The made certificate and key (PEM) in `dir`, made now if needed+fn ensure_made(dir: &Path, names: &[String], now: u64) -> anyhow::Result<(Vec<u8>, Vec<u8>)> {+ let (cert_f, key_f, meta_f) = (dir.join("cert.pem"), dir.join("key.pem"), dir.join("names.json"));+ let meta: Option<Made> = std::fs::read(&meta_f).ok().and_then(|b| serde_json::from_slice(&b).ok());+ if let (Some(m), Ok(c), Ok(k)) = (&meta, std::fs::read(&cert_f), std::fs::read(&key_f))+ && names.iter().all(|n| m.names.contains(n))+ && m.not_after > now + RENEW_DAYS * DAY+ {+ return Ok((c, k));+ }+ // the names it had stay: a page opened at an old address keeps working+ let mut all: Vec<String> = meta.map(|m| m.names).unwrap_or_default();+ for n in names {+ if !all.contains(n) {+ all.push(n.clone());+ }+ }+ let not_after = now + VALID_DAYS * DAY;+ let mut p = rcgen::CertificateParams::new(all.clone());+ let (y, m, d) = ymd(now.saturating_sub(DAY));+ p.not_before = rcgen::date_time_ymd(y, m, d);+ let (y, m, d) = ymd(not_after);+ p.not_after = rcgen::date_time_ymd(y, m, d);+ p.distinguished_name = rcgen::DistinguishedName::new();+ p.distinguished_name.push(rcgen::DnType::CommonName, "iphone-control viewer");+ p.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth];+ // a new certificate under the same name gets a new serial number (Firefox refuses a reused one)+ p.serial_number = Some(rcgen::SerialNumber::from(now.max(1)));+ let cert = rcgen::Certificate::from_params(p)?;+ let (c, k) = (cert.serialize_pem()?.into_bytes(), cert.serialize_private_key_pem().into_bytes());+ write_private(dir, &key_f, &k)?;+ std::fs::write(&cert_f, &c)?;+ std::fs::write(&meta_f, serde_json::to_vec_pretty(&Made { names: all, not_after })?)?;+ Ok((c, k))+}++/// The key: only for this user+fn write_private(dir: &Path, file: &Path, data: &[u8]) -> io::Result<()> {+ use std::io::Write;+ use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};+ std::fs::DirBuilder::new().recursive(true).mode(0o700).create(dir)?;+ let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(file)?;+ f.set_permissions(std::fs::Permissions::from_mode(0o600))?;+ f.write_all(data)+}++/// Year, month, day of a Unix time (UTC)+fn ymd(secs: u64) -> (i32, u8, u8) {+ use chrono::Datelike;+ let t = chrono::DateTime::from_timestamp(secs as i64, 0).unwrap_or_default();+ (t.year(), t.month() as u8, t.day() as u8)+}++/// A connection to the page: plain HTTP or HTTPS+pub enum Conn {+ Plain(TcpStream),+ Tls(Box<tokio_rustls::server::TlsStream<TcpStream>>),+}++impl Conn {+ pub fn tcp(&self) -> &TcpStream {+ match self {+ Self::Plain(s) => s,+ Self::Tls(s) => s.get_ref().0,+ }+ }++ pub fn is_tls(&self) -> bool {+ matches!(self, Self::Tls(_))+ }+}++impl AsyncRead for Conn {+ fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {+ match self.get_mut() {+ Self::Plain(s) => Pin::new(s).poll_read(cx, buf),+ Self::Tls(s) => Pin::new(s.as_mut()).poll_read(cx, buf),+ }+ }+}++impl AsyncWrite for Conn {+ fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {+ match self.get_mut() {+ Self::Plain(s) => Pin::new(s).poll_write(cx, buf),+ Self::Tls(s) => Pin::new(s.as_mut()).poll_write(cx, buf),+ }+ }++ fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {+ match self.get_mut() {+ Self::Plain(s) => Pin::new(s).poll_flush(cx),+ Self::Tls(s) => Pin::new(s.as_mut()).poll_flush(cx),+ }+ }++ fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {+ match self.get_mut() {+ Self::Plain(s) => Pin::new(s).poll_shutdown(cx),+ Self::Tls(s) => Pin::new(s.as_mut()).poll_shutdown(cx),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use tokio::io::{AsyncReadExt, AsyncWriteExt};++ fn names(n: &[&str]) -> Vec<String> {+ n.iter().map(|s| (*s).to_owned()).collect()+ }++ #[test]+ fn the_made_certificate_is_kept_and_grows_with_new_names() {+ let tmp = tempfile::tempdir().unwrap();+ let a = Tls::made(tmp.path(), &names(&["localhost", "127.0.0.1"])).unwrap();+ assert!(a.made);+ assert_eq!(a.fingerprint.len(), 32 * 3 - 1);+ let b = Tls::made(tmp.path(), &names(&["127.0.0.1"])).unwrap();+ assert_eq!(a.fingerprint, b.fingerprint, "covered: the same certificate");+ let c = Tls::made(tmp.path(), &names(&["localhost", "192.168.1.9"])).unwrap();+ assert_ne!(a.fingerprint, c.fingerprint, "a new address: a new certificate");+ let meta: Made =+ serde_json::from_slice(&std::fs::read(tmp.path().join(DIR).join("names.json")).unwrap()).unwrap();+ assert_eq!(meta.names, names(&["localhost", "127.0.0.1", "192.168.1.9"]), "keeping the old names");+ assert_eq!(made_fingerprint(tmp.path()), Some(c.fingerprint.clone()));+ use std::os::unix::fs::PermissionsExt;+ let mode = std::fs::metadata(tmp.path().join(DIR).join("key.pem")).unwrap().permissions().mode();+ assert_eq!(mode & 0o777, 0o600);+ // close to its end: made again+ let (cert, _) = ensure_made(&tmp.path().join(DIR), &names(&["localhost"]), meta.not_after - DAY).unwrap();+ assert_ne!(fingerprint(&CertificateDer::pem_slice_iter(&cert).next().unwrap().unwrap()), c.fingerprint);+ }++ #[test]+ fn the_user_s_files() {+ let tmp = tempfile::tempdir().unwrap();+ let made = Tls::made(tmp.path(), &names(&["localhost"])).unwrap();+ let dir = tmp.path().join(DIR);+ let own = Tls::from_files(&dir.join("cert.pem"), &dir.join("key.pem")).unwrap();+ assert_eq!(own.fingerprint, made.fingerprint);+ assert!(!own.made);+ std::fs::write(tmp.path().join("bad.pem"), "not a certificate").unwrap();+ assert!(Tls::from_files(&tmp.path().join("bad.pem"), &dir.join("key.pem")).is_err());+ assert!(Tls::from_files(&tmp.path().join("missing.pem"), &dir.join("key.pem")).is_err());+ // a key of another certificate+ let other = tempfile::tempdir().unwrap();+ Tls::made(other.path(), &names(&["localhost"])).unwrap();+ assert!(Tls::from_files(&dir.join("cert.pem"), &other.path().join(DIR).join("key.pem")).is_err());+ let half = Setting { mode: Mode::On, cert: Some(dir.join("cert.pem")), key: None };+ assert!(half.load(tmp.path(), &[]).is_err());+ }++ #[test]+ fn when_https_is_on() {+ let s = |mode, cert: bool| Setting { mode, cert: cert.then(|| "c.pem".into()), key: None };+ assert!(s(Mode::Auto, false).enabled(true));+ assert!(!s(Mode::Auto, false).enabled(false));+ assert!(s(Mode::Auto, true).enabled(false));+ assert!(s(Mode::On, false).enabled(false));+ assert!(!s(Mode::Off, true).enabled(true));+ }++ /// One port: a TLS client gets HTTPS, a plain one plain HTTP, and the first byte isn't lost to either+ #[tokio::test]+ async fn the_same_port_speaks_both() {+ let tmp = tempfile::tempdir().unwrap();+ let tls = Arc::new(Tls::made(tmp.path(), &names(&["localhost", "127.0.0.1"])).unwrap());+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let server = {+ let tls = tls.clone();+ tokio::spawn(async move {+ for _ in 0..2 {+ let (tcp, _) = listener.accept().await.unwrap();+ let mut conn = tls.accept(tcp).await.unwrap();+ let mut buf = [0u8; 14];+ conn.read_exact(&mut buf).await.unwrap();+ let reply = if conn.is_tls() { "secure" } else { "plain" };+ conn.write_all(format!("{}:{reply}", String::from_utf8_lossy(&buf)).as_bytes()).await.unwrap();+ conn.flush().await.unwrap();+ conn.shutdown().await.unwrap();+ }+ })+ };++ let mut plain = TcpStream::connect(addr).await.unwrap();+ plain.write_all(b"GET / HTTP/1.1").await.unwrap();+ let mut got = String::new();+ plain.read_to_string(&mut got).await.unwrap();+ assert_eq!(got, "GET / HTTP/1.1:plain");++ let mut roots = rustls::RootCertStore::empty();+ let pem = std::fs::read(&tls.cert).unwrap();+ roots.add(CertificateDer::pem_slice_iter(&pem).next().unwrap().unwrap()).unwrap();+ let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))+ .with_safe_default_protocol_versions()+ .unwrap()+ .with_root_certificates(roots)+ .with_no_client_auth();+ let connector = tokio_rustls::TlsConnector::from(Arc::new(cfg));+ let name = rustls::pki_types::ServerName::try_from("127.0.0.1").unwrap();+ let mut secure = connector.connect(name, TcpStream::connect(addr).await.unwrap()).await.unwrap();+ secure.write_all(b"GET / HTTP/1.1").await.unwrap();+ let mut got = String::new();+ secure.read_to_string(&mut got).await.unwrap();+ assert_eq!(got, "GET / HTTP/1.1:secure");+ server.await.unwrap();+ }+}diff --git a/docs/task-control.md b/docs/task-control.mdindex 6d18bae..e395130 100644--- a/docs/task-control.md+++ b/docs/task-control.md@@ -132,7 +132,8 @@ Running → Waiting(等确认)→ Running| 二 | 控制台接上正在进行的任务(刷新后、在别处开的);命令行查看事件 | 已完成(2026-11-12) || 三 | 任务范围(App 白名单)和越界确认 | 已完成(2026-11-13,见 5.5) || 三 | 执行方不能控制自己的任务(2.5 的落地版,见 5.6) | 已完成(2026-11-13) |-| 四 | 带认证的 HTTP 控制面、HTTP MCP;局域网访问控制台(第 7 节);`SO_PEERCRED`;多设备租约 | 等需要时 |+| 四 | 局域网访问控制台(7.2)、控制台后台服务、HTTPS(7.3) | 已完成(2026-11-13) |+| 四 | 登录、HTTP MCP、多设备租约 | 等需要时 |## 5. 阶段一的具体设计@@ -256,4 +257,18 @@ Running → Waiting(等确认)→ Running之后:1. 控制台做成后台服务(`iphone-control service viewer install`,开机自启,跟着设置文件里的 `IPHONE_CONTROL_VIEWER_*`):已完成(2026-11-13)。升级时先停下它(它是常驻客户端,会让升级一直 busy),升级完再启动;有 AI 任务在跑时自动升级推迟。-2. 登录:一个令牌,存在数据目录,登录后用 `HttpOnly; SameSite=Strict` 的 cookie,程序用 `Authorization: Bearer`,失败限速;局域网口子开了登录才放行。HTTPS 和 HTTP MCP 届时再定。+2. 登录:一个令牌,存在数据目录,登录后用 `HttpOnly; SameSite=Strict; Secure` 的 cookie,程序用 `Authorization: Bearer`,失败限速;局域网口子开了登录才放行。HTTP MCP 届时再定。+3. HTTPS:已完成(2026-11-13),见 7.3。++### 7.3 HTTPS(2026-11-13)++7.1 第 4 条的落地。目的是让局域网里打开的控制台和本机一样用 WebCodecs(H.264、手机自己的 HEVC),并且加密;它不是登录。++- **同一个端口**:看连接的第一个字节,`0x16`(TLS 握手)走 TLS,否则是明文 HTTP。明文从本机(回环)来照常服务;从局域网来的回 307 跳到 `https://<它请求的 Host>:<端口><路径>`(Host 已经过白名单,不会成为开放跳转;用 307 而不是 308,免得浏览器记住,之后 `--tls off` 时打不开)。握手在每个连接自己的任务里做,最多等 10 秒。+- **什么时候开**:`--tls auto`(默认)在 `--lan` 或给了证书时开;`on`、`off` 强制。设置文件:`IPHONE_CONTROL_VIEWER_TLS`、`_TLS_CERT`、`_TLS_KEY`。+- **证书**:用户给的(PEM,可带证书链;mkcert、`tailscale cert`、内部 CA),或者本机生成的自签证书:ECDSA P-256,800 天(低于 Apple 的 825 天上限),EKU serverAuth,SAN 是回环名、主机名和 `.local`、各网卡 IP、`--lan-host`。存在数据目录 `viewer-tls/`(`key.pem` 0600),旁边 `names.json` 记下覆盖的名字和到期时间。名字都覆盖、离到期还有 30 天以上就沿用;出现新名字(DHCP 换了地址)或快到期就重新生成,新证书保留旧名字,序列号取当前时间(Firefox 拒绝同一签发者重复的序列号)。+- **指纹**:SHA-256,按浏览器显示的 `AB:CD:…` 格式,在启动输出和 `service status` 里,供第一次核对浏览器的警告。+- **Origin**:操作的 Origin 接受 `http://` 和 `https://` 两种,名字和端口照旧要对。+- **写出**:TLS 会把最后一段留在缓冲里,所以每个响应、视频头、每条任务事件、每帧画面之后都 flush(明文 TCP 上 flush 什么也不做)。+- **依赖**:`tokio-rustls`、`rcgen` 原本就在依赖树里(idevice、reqwest、plume_core),只用 ring,没有新增 crate。+- **局限**:自签证书第一次要手动点「继续」;之后页面按规范是安全上下文,但各浏览器对点过警告的证书仍有限制(比如 Chrome 不注册 Service Worker),WebCodecs 能不能用以真机浏览器实测为准。diff --git a/packaging/env.example b/packaging/env.exampleindex 5056568..0e2cd1f 100644--- a/packaging/env.example+++ b/packaging/env.example@@ -25,13 +25,18 @@ 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:控制台也对局域网开放(同一个端口、HTTP、还没有登录:局域网里任何能连上这台机器的人都能操作手机),只接受局域网地址来的连接-# Set to 1: the viewer is also open to the local network (same port, HTTP, no login yet: anyone on the network can control the phone); only local-network addresses may connect.+# 设为 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.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.IPHONE_CONTROL_VIEWER_PORT=IPHONE_CONTROL_VIEWER_LAN_HOSTS=+# 控制台的 HTTPS:auto(默认,对局域网开放或给了证书时开启)、on、off;证书和私钥(PEM)不设就用本机生成的自签证书+# The viewer's HTTPS: auto (default: on when open to the network or given a certificate), on, off; without a certificate and key (PEM) a self-signed one made here.+IPHONE_CONTROL_VIEWER_TLS=+IPHONE_CONTROL_VIEWER_TLS_CERT=+IPHONE_CONTROL_VIEWER_TLS_KEY=# 固定控制哪台设备,设了就不能切换。留空为自动选:正在控制的那台一直用到它断开;# 运行中可以用 `iphone-control select` 或 iphone_select_device 工具切换diff --git a/website/en/guide/cli.md b/website/en/guide/cli.mdindex b8772ae..d014e0f 100644--- a/website/en/guide/cli.md+++ b/website/en/guide/cli.md@@ -130,7 +130,7 @@ 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>…]` | Control page in the browser at `http://127.0.0.1:8200/` (default port); with `--lan` also at `http://<this machine's address>:8200/` on the local network (no login yet, so anyone on the network can control the phone; the picture is MJPEG there, since 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>]` | Control page in the browser 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 || `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 b7108ee..07ad76a 100644--- a/website/en/guide/configuration.md+++ b/website/en/guide/configuration.md@@ -29,7 +29,9 @@ 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`. 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. 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_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_UDID` | automatic | Pin the device to control. Unset: the controlled device is kept until it disconnects, and you can switch with the `select` command or the `iphone_select_device` tool. When set, switching is refused || `RESIGN_MIN_DAYS` | `2` | Re-sign when fewer days than this remain || `RESIGN_CHECK_HOURS` | `6` | How often to check; it is also checked within a minute after the phone reconnects or you switch devices |diff --git a/website/guide/cli.md b/website/guide/cli.mdindex fce9bf0..d64c9aa 100644--- a/website/guide/cli.md+++ b/website/guide/cli.md@@ -130,7 +130,7 @@ 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 <名字>…]` | 浏览器里的控制台,地址 `http://127.0.0.1:8200/`(默认端口);加 `--lan` 时局域网里也能用 `http://<这台机器的 IP>:8200/` 打开(还没有登录,局域网里任何人都能操作手机;画面是 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>]` | 浏览器里的控制台,地址 `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 每一步都先等你确认。可以暂停、接管后交还、停止;付款、删除、发消息之前它会在页面上请你确认。本机任何用户都能连上这个端口,用完就停 || `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 4718e2a..7f20810 100644--- a/website/guide/configuration.md+++ b/website/guide/configuration.md@@ -29,7 +29,9 @@ 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`。还没有登录:局域网里任何能连上这台机器的人都能操作手机、开 AI 任务,只在可信的网络里开 |+| `IPHONE_CONTROL_VIEWER_LAN` | 关 | 设为 `1` 时控制台也对局域网开放,同 `viewer --lan`,局域网里用 HTTPS。还没有登录:局域网里任何能连上这台机器的人都能操作手机、开 AI 任务,只在可信的网络里开 |+| `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_UDID` | 自动选 | 固定控制哪台设备。不设时自动选:正在控制的那台一直用到它断开;运行中可以用 `select` 命令或 `iphone_select_device` 工具切换。设了就不能切换 || `RESIGN_MIN_DAYS` | `2` | 描述文件剩余不到几天时重签 || `RESIGN_CHECK_HOURS` | `6` | 每隔几小时检查一次;手机重新连上或切换设备后 1 分钟内也查一次 |