Skip to content

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

feat(viewer): open the control page to the local network with --lan (#72)

Qinghe Li20b89d3b4383
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a236c67..3942f13 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ All notable changes to this project are documented here. The format is based on
- 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.
- Generate Bash, Zsh and Fish completion scripts with `iphone-control completions <shell>`, without starting the daemon or accessing a device.
+- `iphone-control viewer --lan` (or `IPHONE_CONTROL_VIEWER_LAN=1`) also opens the control page to the local network, on the same port. There is no login yet: anyone on the network who can reach the machine can control the phone, so only use it on a trusted network. It only accepts connections from local-network addresses and only answers to this machine's own names; `--lan-host` adds another name. Opened at a network address the picture is MJPEG, since browsers only offer WebCodecs on localhost or HTTPS.
- On the control page, a task can be limited to some apps before it starts (the App button next to the agent): in any other app each step waits for you, as with `task run --app`. The task card shows the scope, and running a task again keeps it.
- AI tasks for any agent platform: `iphone-control task run -- <command>` runs a command in a task, and an `iphone-control mcp` it starts takes part (the control page shows its steps and can pause, take over, stop and confirm). `task list`, `task events`, `task pause`/`resume`/`takeover`/`handback`/`stop` and `task approve`/`reject` follow and steer tasks from the command line.
- The control page picks up a task in progress: after a reload, and for tasks started elsewhere.
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index ac5c5f8..e59f02d 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -10,6 +10,7 @@
- 设置菜单支持方向键选择、Enter 确认和 Esc 取消,保留数字选择;基础终端继续使用逐行提示。
- `iphone-control completions <shell>` 可生成 Bash、Zsh 和 Fish 补全脚本,不启动守护进程、不访问设备。
+- `iphone-control viewer --lan`(或 `IPHONE_CONTROL_VIEWER_LAN=1`)让控制台也对局域网开放,还是同一个端口。还没有登录:局域网里任何能连上这台机器的人都能操作手机,只在可信的网络里开。只接受局域网地址来的连接,只认本机自己的名字和地址;`--lan-host` 可以再加名字。从局域网地址打开时画面是 MJPEG,因为浏览器只在 localhost 或 HTTPS 上提供 WebCodecs。
- 控制台上开任务前可以限定 App 范围(Agent 旁边的 App 按钮):到了别的 App,每一步都先等你确认,和 `task run --app` 一样。任务卡片上显示范围,重新执行时沿用。
- 任何 agent 平台都能用 AI 任务:`iphone-control task run -- <命令>` 在任务里运行命令,它启动的 `iphone-control mcp` 自动加入任务(控制台能看到每一步,可以暂停、接管、停止、确认)。`task list`、`task events`、`task pause`/`resume`/`takeover`/`handback`/`stop`、`task approve`/`reject` 在命令行里查看和控制任务。
- 控制台会接上正在进行的任务:页面刷新后,以及在别处开的任务。
diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs
index da65cb5..31cf6d3 100644
--- a/apps/iphone-control/src/main.rs
+++ b/apps/iphone-control/src/main.rs
@@ -111,6 +111,10 @@ enum Command {
Viewer {
#[arg(long, default_value_t = 8200)]
port: u16,
+ #[arg(long, env = "IPHONE_CONTROL_VIEWER_LAN", 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"))]
+ lan: bool,
+ #[arg(long = "lan-host", value_name = "HOST", 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>,
},
#[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 {
@@ -284,7 +288,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 } => viewer::run(&cli.socket, &cli.data_dir, port).await,
+ Command::Viewer { port, lan, lan_hosts } => {
+ viewer::run(&cli.socket, &cli.data_dir, port, lan, &lan_hosts).await
+ }
Command::Task { action } => task::run(&cli.socket, action).await,
#[cfg(feature = "debug-cmds")]
Command::Debug(args) => debug::run(env_nonempty("IPHONE_UDID").as_deref(), args).await,
diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.html
index 40bfb9d..512e84f 100644
--- a/apps/iphone-control/src/viewer.html
+++ b/apps/iphone-control/src/viewer.html
@@ -2265,12 +2265,16 @@ function stopMjpegTurn() {
M.on = false; cancelAnimationFrame(M.raf); live.style.opacity = '';
if (!V.on) cv.hidden = true;
}
+/* 画面流的编号。不用 crypto.randomUUID:它只在安全上下文(HTTPS 或 localhost)里有,从局域网地址(viewer --lan)打开时没有 */
+function newFeedId() {
+ return Array.from(crypto.getRandomValues(new Uint8Array(16)), x => x.toString(16).padStart(2, '0')).join('');
+}
function connect() {
stopMjpegTurn();
cancelGestures(); const epoch = ++feedEpoch;
clearTimeout(firstFrameTimer); clearTimeout(retryTimer);
stopVideo(); cv.hidden = true;
- feedId = crypto.randomUUID();
+ feedId = newFeedId();
S.stream = 'connecting'; frameWidth = frameHeight = 0;
applyZoom();
stageMsg.textContent = tr('正在连接画面…'); delete stageMsg.dataset.note; stageMsg.hidden = false;
diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs
index 642369a..cc24bc0 100644
--- a/apps/iphone-control/src/viewer.rs
+++ b/apps/iphone-control/src/viewer.rs
@@ -16,7 +16,9 @@
//! 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.
+//! 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.
//!
//! 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
@@ -24,6 +26,8 @@
//! 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.
+mod lan;
+
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
@@ -48,6 +52,8 @@ const SPRINGBOARD: &str = "com.apple.springboard";
/// What every connection shares
struct Ctx {
+ /// Who may reach the page: `127.0.0.1` only, or the local network too (`--lan`)
+ access: lan::Access,
/// The data directory: whether an Apple ID is signed in (signing WDA from the page needs one)
data_dir: PathBuf,
/// The page, marked with the viewer's language (the page's default; it can switch)
@@ -96,7 +102,8 @@ impl Ctx {
}
}
-pub async fn run(socket: &Path, data_dir: &Path, port: u16) -> anyhow::Result<()> {
+/// `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<()> {
// 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
@@ -113,7 +120,8 @@ pub async fn run(socket: &Path, data_dir: &Path, port: u16) -> anyhow::Result<()
String::new()
}
};
- let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?;
+ let 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 agents = Agents::new(socket)?;
println!(
@@ -165,14 +173,28 @@ pub async fn run(socket: &Path, data_dir: &Path, port: u16) -> anyhow::Result<()
ictl_l10n::trf!("AI 任务可用:{}", "AI tasks available with: {}", found.join(", "))
}
);
- 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."
- )
- );
+ 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::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!(
+ "{}",
+ 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."
+ )
+ );
+ }
let ctx = Arc::new(Ctx {
+ access,
socket: socket.to_path_buf(),
data_dir: data_dir.to_path_buf(),
port,
@@ -189,7 +211,13 @@ pub async fn run(socket: &Path, data_dir: &Path, port: u16) -> anyhow::Result<()
});
let slots = Arc::new(tokio::sync::Semaphore::new(crate::MAX_CONNECTIONS));
loop {
- let (client, _) = listener.accept().await?;
+ let (client, peer) = listener.accept().await?;
+ // open to the network: only from the local network (a machine reachable from the internet isn't operated
+ // from there)
+ if !lan::peer_allowed(peer.ip()) {
+ tracing::warn!("viewer: refused a connection from {}", peer.ip());
+ continue;
+ }
// too many open connections (for example many tabs): drop the new one
let Ok(slot) = slots.clone().try_acquire_owned() else { continue };
let ctx = ctx.clone();
@@ -225,7 +253,7 @@ 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<()> {
- if !crate::host_is_loopback(&head) || (req.path != "/" && !fetch_site_ok(&req)) {
+ if !ctx.access.host_allowed(&head) || (req.path != "/" && !fetch_site_ok(&req)) {
return reply(&mut client, 403, "text/plain", b"forbidden").await;
}
let path = req.path.as_str();
@@ -278,7 +306,7 @@ async fn handle(mut client: TcpStream, ctx: &Ctx, head: Vec<u8>, req: Head, mut
}
}
("POST", p) if p.starts_with("/api/") => {
- if !action_allowed(&req, ctx.port) {
+ if !action_allowed(&req, &ctx.access, ctx.port) {
return reply(&mut client, 403, "text/plain", b"forbidden").await;
}
let len = req.content_length.unwrap_or(0);
@@ -610,14 +638,12 @@ fn percent_decode(s: &str) -> String {
String::from_utf8_lossy(&out).into_owned()
}
-/// An action must come from this page: `Origin` is the viewer's own address, and the body is JSON, which a
-/// cross-origin page can't send without a preflight that this server never answers
-fn action_allowed(req: &Head, port: u16) -> bool {
+/// An action must come from this page: `Origin` is the viewer's own address (one of this machine's names with
+/// `--lan`), and the body is JSON, which a cross-origin page can't send without a preflight that this server never
+/// answers
+fn action_allowed(req: &Head, access: &lan::Access, port: u16) -> bool {
let json = req.content_type.as_deref().is_some_and(|c| c.split(';').next() == Some("application/json"));
- let origin = req.origin.as_deref().is_some_and(|o| {
- ["127.0.0.1", "localhost", "[::1]"].iter().any(|h| o.eq_ignore_ascii_case(&format!("http://{h}:{port}")))
- });
- json && origin
+ json && req.origin.as_deref().is_some_and(|o| access.origin_allowed(o, port))
}
/// A read from another site (an `<img>` or `<script>` on some page) is refused: browsers say so in
@@ -947,6 +973,7 @@ mod tests {
fn test_ctx(dir: &Path, socket: &Path) -> Ctx {
Ctx {
+ access: lan::Access::local(),
agents: Agents::new(socket).unwrap(),
socket: socket.to_owned(),
data_dir: dir.into(),
@@ -1092,15 +1119,20 @@ mod tests {
#[test]
fn actions_need_own_origin_and_json() {
+ let local = lan::Access::local();
let ok = "POST /api/tap HTTP/1.1\r\nHost: 127.0.0.1:8200\r\nOrigin: http://127.0.0.1:8200\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n";
- assert!(action_allowed(&head(ok), 8200));
- assert!(action_allowed(&head(&ok.replace("http://127.0.0.1:8200", "http://localhost:8200")), 8200));
+ assert!(action_allowed(&head(ok), &local, 8200));
+ assert!(action_allowed(&head(&ok.replace("http://127.0.0.1:8200", "http://localhost:8200")), &local, 8200));
// another page, another port, no origin, a form post
- assert!(!action_allowed(&head(&ok.replace("http://127.0.0.1:8200", "http://evil.example")), 8200));
- assert!(!action_allowed(&head(&ok.replace("http://127.0.0.1:8200", "http://127.0.0.1:3000")), 8200));
- assert!(!action_allowed(&head(&ok.replace("Origin: http://127.0.0.1:8200\r\n", "")), 8200));
- assert!(!action_allowed(&head(&ok.replace("application/json", "text/plain")), 8200));
- assert!(!action_allowed(&head(&ok.replace("Origin: http://127.0.0.1:8200", "Origin: null")), 8200));
+ assert!(!action_allowed(&head(&ok.replace("http://127.0.0.1:8200", "http://evil.example")), &local, 8200));
+ assert!(!action_allowed(&head(&ok.replace("http://127.0.0.1:8200", "http://127.0.0.1:3000")), &local, 8200));
+ assert!(!action_allowed(&head(&ok.replace("Origin: http://127.0.0.1:8200\r\n", "")), &local, 8200));
+ assert!(!action_allowed(&head(&ok.replace("application/json", "text/plain")), &local, 8200));
+ assert!(!action_allowed(&head(&ok.replace("Origin: http://127.0.0.1:8200", "Origin: null")), &local, 8200));
+ // only open to the network with --lan
+ let on_lan = ok.replace("http://127.0.0.1:8200", "http://192.168.10.100:8200");
+ assert!(!action_allowed(&head(&on_lan), &local, 8200));
+ assert!(action_allowed(&head(&on_lan), &lan::Access::with_hosts(["192.168.10.100".into()]), 8200));
}
#[test]
diff --git a/apps/iphone-control/src/viewer/lan.rs b/apps/iphone-control/src/viewer/lan.rs
new file mode 100644
index 0000000..b5a3cfa
--- /dev/null
+++ b/apps/iphone-control/src/viewer/lan.rs
@@ -0,0 +1,228 @@
+//! 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:
+//!
+//! - 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;
+//! - the `Host` header must name this machine (loopback names, its host name and `<name>.local`, its interfaces'
+//! addresses, names given with `--lan-host`), against DNS rebinding;
+//! - an action's `Origin` must be this page at one of those names, against other web pages posting to it.
+
+use std::net::{IpAddr, Ipv4Addr};
+
+const LOOPBACK: [&str; 3] = ["localhost", "127.0.0.1", "[::1]"];
+
+/// The names the page answers to
+#[derive(Debug, Clone)]
+pub struct Access {
+ lan: bool,
+ /// Besides the loopback names, lowercase; IPv6 addresses in brackets
+ hosts: Vec<String>,
+ /// This machine's IPv4 addresses other than loopback, to print
+ addresses: Vec<Ipv4Addr>,
+}
+
+impl Access {
+ /// `127.0.0.1` only
+ pub fn local() -> Self {
+ Self { lan: false, hosts: Vec::new(), addresses: Vec::new() }
+ }
+
+ /// Every IPv4 interface: this machine's names and addresses, and `extra` (`--lan-host`)
+ pub fn lan(extra: &[String]) -> Self {
+ let addresses: Vec<Ipv4Addr> = interface_ipv4s().into_iter().filter(|a| !a.is_loopback()).collect();
+ let mut names: Vec<String> = Vec::new();
+ if let Some(h) = hostname() {
+ if !h.contains('.') {
+ names.push(format!("{h}.local"));
+ }
+ names.push(h);
+ }
+ names.extend(addresses.iter().map(Ipv4Addr::to_string));
+ names.extend(extra.iter().cloned());
+ let mut a = Self::with_hosts(names);
+ a.addresses = addresses;
+ a
+ }
+
+ /// Open to the network, answering to `names` (and the loopback names)
+ pub fn with_hosts(names: impl IntoIterator<Item = String>) -> Self {
+ let mut hosts: Vec<String> = Vec::new();
+ for n in names {
+ let n = n.trim().trim_end_matches('.').to_ascii_lowercase();
+ if !n.is_empty() && !LOOPBACK.contains(&n.as_str()) && !hosts.contains(&n) {
+ hosts.push(n);
+ }
+ }
+ Self { lan: true, hosts, addresses: Vec::new() }
+ }
+
+ pub fn is_lan(&self) -> bool {
+ self.lan
+ }
+
+ /// Where to listen
+ pub fn bind_ip(&self) -> Ipv4Addr {
+ if self.lan { Ipv4Addr::UNSPECIFIED } else { Ipv4Addr::LOCALHOST }
+ }
+
+ /// This machine's network addresses (for the startup message)
+ pub fn addresses(&self) -> &[Ipv4Addr] {
+ &self.addresses
+ }
+
+ fn knows(&self, name: &str) -> bool {
+ LOOPBACK.contains(&name) || (self.lan && self.hosts.iter().any(|h| h == name))
+ }
+
+ /// The request's `Host` names this machine
+ pub 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>`
+ pub fn origin_allowed(&self, origin: &str, port: u16) -> bool {
+ let Some(rest) = origin.strip_prefix("http://") 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)
+ }
+}
+
+/// A connection from this address may be served (on the local network only)
+pub fn peer_allowed(ip: IpAddr) -> bool {
+ match ip {
+ IpAddr::V4(a) => {
+ let [o0, o1, ..] = a.octets();
+ a.is_loopback() || a.is_private() || a.is_link_local() || (o0 == 100 && (o1 & 0xc0) == 64)
+ }
+ IpAddr::V6(a) => {
+ let s0 = a.segments()[0];
+ a.is_loopback()
+ || (s0 & 0xfe00) == 0xfc00
+ || (s0 & 0xffc0) == 0xfe80
+ || a.to_ipv4_mapped().is_some_and(|v4| peer_allowed(IpAddr::V4(v4)))
+ }
+ }
+}
+
+/// The `Host` header's name without the port, lowercase; an IPv6 address in brackets
+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(':')?;
+ k.trim().eq_ignore_ascii_case("host").then(|| v.trim().to_ascii_lowercase())
+ })?;
+ Some(match host.strip_prefix('[') {
+ Some(rest) => format!("[{}]", rest.split(']').next().unwrap_or_default()),
+ None => host.split(':').next().unwrap_or_default().trim_end_matches('.').to_owned(),
+ })
+}
+
+fn hostname() -> Option<String> {
+ let mut buf = [0u8; 256];
+ // SAFETY: the buffer is valid for its length; gethostname writes at most that many bytes
+ if unsafe { libc::gethostname(buf.as_mut_ptr().cast(), buf.len()) } != 0 {
+ return None;
+ }
+ let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
+ let name = std::str::from_utf8(&buf[..end]).ok()?.trim().to_ascii_lowercase();
+ (!name.is_empty()).then_some(name)
+}
+
+/// The IPv4 addresses of this machine's interfaces
+fn interface_ipv4s() -> Vec<Ipv4Addr> {
+ let mut out = Vec::new();
+ let mut list: *mut libc::ifaddrs = std::ptr::null_mut();
+ // SAFETY: getifaddrs fills `list`, which is walked read-only and freed once
+ unsafe {
+ if libc::getifaddrs(&mut list) != 0 {
+ return out;
+ }
+ let mut p = list;
+ while !p.is_null() {
+ let a = (*p).ifa_addr;
+ if !a.is_null() && i32::from((*a).sa_family) == libc::AF_INET {
+ let sin = &*(a as *const libc::sockaddr_in);
+ let ip = Ipv4Addr::from(u32::from_be(sin.sin_addr.s_addr));
+ if !out.contains(&ip) {
+ out.push(ip);
+ }
+ }
+ p = (*p).ifa_next;
+ }
+ libc::freeifaddrs(list);
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn head(host: &str) -> Vec<u8> {
+ format!("GET /api/status HTTP/1.1\r\nHost: {host}\r\n\r\n").into_bytes()
+ }
+
+ #[test]
+ fn only_the_local_network_may_connect() {
+ for ok in [
+ "127.0.0.1",
+ "10.1.2.3",
+ "172.20.0.5",
+ "192.168.10.15",
+ "169.254.1.1",
+ "100.100.1.1",
+ "::1",
+ "fd7a:115c::1",
+ "fe80::1",
+ "::ffff:192.168.1.2",
+ ] {
+ assert!(peer_allowed(ok.parse().unwrap()), "{ok}");
+ }
+ for no in ["8.8.8.8", "172.32.0.1", "100.128.0.1", "1.1.1.1", "2001:db8::1", "::ffff:8.8.8.8"] {
+ assert!(!peer_allowed(no.parse().unwrap()), "{no}");
+ }
+ }
+
+ #[test]
+ fn without_lan_only_loopback_names() {
+ let a = Access::local();
+ assert!(!a.is_lan());
+ assert_eq!(a.bind_ip(), Ipv4Addr::LOCALHOST);
+ for h in ["127.0.0.1:8202", "localhost:8202", "[::1]:8202", "LOCALHOST"] {
+ assert!(a.host_allowed(&head(h)), "{h}");
+ }
+ assert!(!a.host_allowed(&head("192.168.10.100:8202")), "the network's name for it doesn't count");
+ assert!(!a.host_allowed(b"GET / HTTP/1.1\r\n\r\n"), "no Host");
+ assert!(a.origin_allowed("http://127.0.0.1:8202", 8202));
+ assert!(!a.origin_allowed("http://192.168.10.100:8202", 8202));
+ }
+
+ #[test]
+ fn on_the_lan_its_own_names_but_no_others() {
+ let a = Access::with_hosts(["192.168.10.100".into(), "NAS.local.".into(), "nas".into(), "localhost".into()]);
+ assert!(a.is_lan());
+ assert_eq!(a.bind_ip(), Ipv4Addr::UNSPECIFIED);
+ for h in ["192.168.10.100:8202", "nas.local", "NAS:8202", "127.0.0.1:8202"] {
+ assert!(a.host_allowed(&head(h)), "{h}");
+ }
+ // DNS rebinding: a name that resolves to this machine but isn't one of its own
+ for h in ["evil.example:8202", "192.168.10.101:8202", "nas.evil.example"] {
+ assert!(!a.host_allowed(&head(h)), "{h}");
+ }
+ 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("http://192.168.10.100:3000", 8202), "another port");
+ assert!(!a.origin_allowed("http://evil.example:8202", 8202));
+ assert!(!a.origin_allowed("null", 8202));
+ }
+
+ #[test]
+ fn this_machine_has_addresses() {
+ assert!(interface_ipv4s().contains(&Ipv4Addr::LOCALHOST));
+ }
+}
diff --git a/docs/decisions.md b/docs/decisions.md
index 1a36053..09e9a9c 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -20,6 +20,7 @@
- **决定**:用 idevice 的 provider 直连设备端口访问 WDA;外部工具需要时显式开 bridge,只绑 127.0.0.1。
- **理由**:WDA 没有认证;toolkit 早期用 `ios forward` 监听了所有网卡,局域网内任何人都能控制手机。
- **补充**:`iphone-control viewer` 用同样的保护模型(显式开启、只绑 127.0.0.1、检查 `Host`),另加操作的 `Origin` 和 JSON 内容类型检查、读接口的 `Sec-Fetch-Site` 检查,并只作用于页面跟着的那台设备。它的 AI 任务不开新端口:agent 的 MCP 服务经控制接口旁边的 Unix socket(0600,每个任务一个口令)回报 viewer。
+- **补充(2026-11-13)**:`viewer --lan` 让控制台也对局域网开放:同一个端口,仍是 HTTP,**还没有登录**(用户决定先这样,登录以后再加,见 task-control.md 7.2)。没有登录时能做的防护都做了:显式开启、只接受回环和局域网地址(私有网段、链路本地、100.64/10)来的连接、`Host` 只认本机的名字和地址、操作的 `Origin` 必须是页面自己。代价是局域网里能连上这台机器的人都能操作手机、用本机的 Claude Code / Codex 开任务;从局域网地址打开时浏览器不提供 WebCodecs,画面退回 MJPEG。默认仍只绑 127.0.0.1。
## D4:WDA 仍然是 Objective-C,在 macOS CI 上编译
diff --git a/docs/task-control.md b/docs/task-control.md
index cd0ff8a..3d4f388 100644
--- a/docs/task-control.md
+++ b/docs/task-control.md
@@ -225,3 +225,20 @@ Running → Waiting(等确认)→ Running
- 局域网另一台电脑:用令牌登录后能看画面(H.264 或 HEVC,不退回 MJPEG)、操作、开 AI 任务、暂停、确认。
- 没有令牌、令牌错误、`Host` 不在名单里、来自别的网页的 `Origin`:一律拒绝。
- 只读令牌:能看画面和状态,操作、开任务、确认都被拒绝。
+
+### 7.2 局域网访问:第一版(2026-11-13)
+
+和 7.1 不同,第一版按用户的决定**先不做登录**,登录(一个令牌)放到以后。所以它只能是显式开启的,默认和现在完全一样。
+
+- **开启**:`iphone-control viewer --lan`(设置文件里 `IPHONE_CONTROL_VIEWER_LAN=1`)。还是同一个端口、同样是 HTTP,只是从 `127.0.0.1` 改成监听所有 IPv4 网卡。不加 `--lan` 时只绑 `127.0.0.1`,和以前一样。
+- **只接受局域网来的连接**:对端地址必须是回环、私有网段(10/8、172.16/12、192.168/16)、链路本地(169.254/16)或 CGNAT(100.64/10,Tailscale 用它)。别的一律直接断开,机器万一暴露在公网也不会被外网操作。
+- **Host 检查保留**(防 DNS rebinding):认可的是回环名、本机主机名和 `<主机名>.local`、启动时各网卡的 IPv4 地址,以及 `--lan-host` 额外写的名字(可写多次,给 DNS 名用)。
+- **Origin 检查保留**(防别的网页借浏览器操作):操作的 Origin 必须是 `http://<认可的 Host>:<端口>`。`Sec-Fetch-Site` 检查照旧。
+- **启动时提醒**:打印每个局域网地址,并说明「局域网里任何人都能打开它操作手机、让 AI 执行任务,没有登录,只在可信的网络里开」。
+- **画面**:浏览器只在 HTTPS 或 `localhost` 上提供 WebCodecs,从局域网 IP 打开时,页面自动退回 MJPEG(每秒 4~10 MB)。手机自己的 HEVC 画面也用不了,所以系统弹窗直接在 MJPEG 画面里看得到。
+- **代价**:局域网里能连上这台机器的人都能操作手机、用本机登录的 Claude Code / Codex 开任务。这是有意的权衡,等加了登录再收紧。决策记录见 D3 的补充。
+
+之后:
+
+1. 控制台做成后台服务(`iphone-control service` 管,开机自启,跟着设置文件里的 `--lan` 开关)。
+2. 登录:一个令牌,存在数据目录,登录后用 `HttpOnly; SameSite=Strict` 的 cookie,程序用 `Authorization: Bearer`,失败限速;局域网口子开了登录才放行。HTTPS 和 HTTP MCP 届时再定。
diff --git a/packaging/env.example b/packaging/env.example
index 57f545a..359db16 100644
--- a/packaging/env.example
+++ b/packaging/env.example
@@ -25,6 +25,9 @@ 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.
+IPHONE_CONTROL_VIEWER_LAN=
# 固定控制哪台设备,设了就不能切换。留空为自动选:正在控制的那台一直用到它断开;
# 运行中可以用 `iphone-control select` 或 iphone_select_device 工具切换
diff --git a/tests/viewer/lan.test.mjs b/tests/viewer/lan.test.mjs
new file mode 100644
index 0000000..3f7b113
--- /dev/null
+++ b/tests/viewer/lan.test.mjs
@@ -0,0 +1,26 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { test } from 'node:test';
+import { runInNewContext } from 'node:vm';
+
+const html = readFileSync(new URL('../../apps/iphone-control/src/viewer.html', import.meta.url), 'utf8');
+const code = html.slice(html.indexOf('<script>'), html.lastIndexOf('</script>'));
+
+// Opened at a network address (`viewer --lan`, plain HTTP) the page isn't a secure context: browsers leave out
+// crypto.randomUUID, WebCodecs, the clipboard API. The page must connect without them
+test('the picture connects without APIs that need a secure context', () => {
+ assert.doesNotMatch(code.replace(/\/\*[^]*?\*\//g, ''), /crypto\.randomUUID\(/, 'crypto.randomUUID is missing on http://<address>');
+ const fn = html.match(/^function newFeedId\([^]*?^}/m)[0];
+ const { newFeedId } = runInNewContext(fn + '\n({ newFeedId })', { crypto: { getRandomValues: a => { for (let i = 0; i < a.length; i++) a[i] = i * 17; return a; } } });
+ assert.match(newFeedId(), /^[0-9a-f]{32}$/);
+ assert.ok(newFeedId().length <= 80, 'the viewer accepts feed ids up to 80 characters');
+});
+
+test('WebCodecs and the clipboard are only used where they may be missing', () => {
+ for (const m of code.matchAll(/new VideoDecoder\(|VideoDecoder\.isConfigSupported/g)) {
+ const before = code.slice(Math.max(0, m.index - 6000), m.index);
+ assert.match(before, /'VideoDecoder' in window/, 'checked before use');
+ }
+ const clip = code.indexOf('navigator.clipboard.writeText');
+ assert.match(code.slice(clip - 40, clip), /try \{/, 'a failure falls back to selecting the text');
+});
diff --git a/website/en/guide/cli.md b/website/en/guide/cli.md
index 49b2fa2..a279090 100644
--- a/website/en/guide/cli.md
+++ b/website/en/guide/cli.md
@@ -128,7 +128,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>]` | Control page in the browser at `http://127.0.0.1:8200/` (default port), 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>…]` | 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 |
| `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 |
diff --git a/website/en/guide/configuration.md b/website/en/guide/configuration.md
index fa1f642..3eb0983 100644
--- a/website/en/guide/configuration.md
+++ b/website/en/guide/configuration.md
@@ -27,6 +27,7 @@ iphone-control service restart
| `IPHONE_CONTROL_DEV_TOOLS` | off | `1` adds the [developer tools](./tools#developer-tools-opt-in) to the MCP server: logs, crash reports, installing and removing apps, and Web Inspector (JavaScript in web pages and WebViews). See [Security](./security) for the risks. See the note below the table |
| `IPHONE_CONTROL_VIEWER_CODEC` | `auto` | The control page's picture: `auto` uses the phone's own video (HEVC) on iOS 27 and later, else H.264 (on macOS with VideoToolbox directly, on Linux when ffmpeg is installed), GPU encoding first; `device` only the phone's own video, MJPEG where it can't be used; `mjpeg` only MJPEG; or name one of `nvenc`, `vaapi`, `qsv`, `v4l2m2m`, `videotoolbox`, `x264`. `iphone-control viewer` says which one it uses when it starts, see [CLI](./cli#viewer-picture) |
| `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_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_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/en/guide/security.md b/website/en/guide/security.md
index e25a3b1..12e2adf 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.
+- **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.
- **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.md
index 367d55b..e89d67c 100644
--- a/website/guide/cli.md
+++ b/website/guide/cli.md
@@ -128,7 +128,7 @@ Viewer 只监听本机回环地址。同机其他用户也能查看安装信息
|---|---|
| `notify-test [事件]` | 发测试通知:每类事件各一条,或只发一类(`resign`、`session`、`pin`、`pin-recovered`、`unlock`、`offline`、`online`) |
| `wda-bridge [--port <端口>]` | 把 WDA 桥接到 `127.0.0.1`,端口默认 8100,给别的工具用。WDA 没有认证,本机任何用户都能连上,用完就停 |
-| `viewer [--port <端口>]` | 浏览器里的控制台,地址 `http://127.0.0.1:8200/`(默认端口),中英文(默认跟着 `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 <名字>…]` | 浏览器里的控制台,地址 `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 每一步都先等你确认。可以暂停、接管后交还、停止;付款、删除、发消息之前它会在页面上请你确认。本机任何用户都能连上这个端口,用完就停 |
| `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>` | 在命令行里控制任务,和控制台上的按钮一样 |
diff --git a/website/guide/configuration.md b/website/guide/configuration.md
index 09e5000..4821a8e 100644
--- a/website/guide/configuration.md
+++ b/website/guide/configuration.md
@@ -27,6 +27,7 @@ iphone-control service restart
| `IPHONE_CONTROL_DEV_TOOLS` | 关 | 设为 `1` 时 MCP 服务多出[开发者工具](./tools#开发者工具-显式开启):日志、崩溃报告、安装和卸载 App、Web Inspector(在网页和 WebView 里执行 JavaScript)。风险见[安全与隐私](./security)。见表下说明 |
| `IPHONE_CONTROL_VIEWER_CODEC` | `auto` | 控制台画面的编码:`auto` 在 iOS 27 及以上用手机自己的视频(HEVC),其余用 H.264(macOS 上直接用 VideoToolbox;Linux 上要装 ffmpeg),先试显卡编码;`device` 只用手机自己的视频,用不了时是 MJPEG;`mjpeg` 只用 MJPEG;也可以指定 `nvenc`、`vaapi`、`qsv`、`v4l2m2m`、`videotoolbox`、`x264`。`iphone-control viewer` 启动时会显示用的是哪个,见[命令行](./cli#viewer-picture) |
| `IPHONE_CONTROL_VIEWER_QP` | `20` | H.264 的画质,1~51,越小越清晰、流量越大。`20` 正常使用看不出和原画的差别;`24` 约省三分之一流量,快速滚动时小字略糊 |
+| `IPHONE_CONTROL_VIEWER_LAN` | 关 | 设为 `1` 时控制台也对局域网开放,同 `viewer --lan`。还没有登录:局域网里任何能连上这台机器的人都能操作手机、开 AI 任务,只在可信的网络里开 |
| `IPHONE_UDID` | 自动选 | 固定控制哪台设备。不设时自动选:正在控制的那台一直用到它断开;运行中可以用 `select` 命令或 `iphone_select_device` 工具切换。设了就不能切换 |
| `RESIGN_MIN_DAYS` | `2` | 描述文件剩余不到几天时重签 |
| `RESIGN_CHECK_HOURS` | `6` | 每隔几小时检查一次;手机重新连上或切换设备后 1 分钟内也查一次 |
diff --git a/website/guide/security.md b/website/guide/security.md
index 8a0cb91..e2d1db9 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 任务),用完就停。
+- **不开网络端口。** WDA 经 usbmuxd 直连手机。`wda-bridge` 和实时画面 `viewer` 都要显式开启,只绑 127.0.0.1,浏览器里的其他网页借不了它们操作手机。但它们没有登录,本机任何用户都能用(包括在 viewer 上发起 AI 任务),用完就停。`viewer --lan` 会把控制台也开放给局域网,仍然没有登录,局域网里任何能连上这台机器的人都能操作手机;只接受局域网地址来的连接,只在可信的网络里开。
- **不用 root。** 守护进程以你的普通用户身份作为用户服务运行,安装脚本拒绝以 root 运行。
- **自动解锁默认关闭**,输错一次即停用。
- **开发者工具默认关闭**。