From 9c4375c9002707fd242430412af9ca774334c434 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:03:26 +0800 Subject: [PATCH 1/2] fix: viewer and host configuration (review P1-3) - pages carry a Content-Security-Policy naming their own inline scripts by hash; every answer sends Referrer-Policy: no-referrer; answers and event stream writes time out (30 s) - Origin is checked against the scheme served (HTTPS on: http only from this machine; off: no https) - the viewer's certificate, key and names.json are written atomically, names last, so a stop halfway makes a new pair instead of a mismatched one - the tokens file is watched by (time, length, inode); token commands hold a flock while they read, change and write - the env file: a key's last value wins; saves use a temporary file of their own; `mcp --task-token-file` skips IPHONE_CONTROL_URL/CA from it - services: paths with spaces are quoted, `$`, backquotes and `%` refused; a paused viewer service is started again without enabling it; a failed update job setup removes what it wrote - stale task token files are cleared when the viewer starts - a read-only page sends no touches from the picture Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++ CHANGELOG.zh-CN.md | 8 ++ apps/iphone-control/src/agent.rs | 19 ++- apps/iphone-control/src/envfile.rs | 48 +++++-- apps/iphone-control/src/main.rs | 9 +- apps/iphone-control/src/schedule.rs | 5 + apps/iphone-control/src/service.rs | 71 ++++++---- apps/iphone-control/src/viewer.rs | 182 +++++++++++++++++++------ apps/iphone-control/src/viewer/auth.rs | 113 ++++++++++++++- apps/iphone-control/src/viewer/lan.rs | 53 ++++--- apps/iphone-control/src/viewer/tls.rs | 62 +++++++-- apps/iphone-control/web/js/screen.js | 15 +- docs/dev/regression-cases.md | 8 ++ tests/viewer/actions.test.mjs | 23 ++++ 14 files changed, 511 insertions(+), 113 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b50f895..58cf0fb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,14 @@ What changed in each release, one line per change. Versions follow [Semantic Ver - The H.264 copy of the phone's own video counts a crashed ffmpeg as a failure and moves on to the next encoder, instead of restarting it for ever (#201). - `task run --url` stops within 10 seconds of Ctrl-C even if the viewer doesn't answer, and gives up an event stream that goes silent or sends an endless event (#201). - Only one daemon runs per socket, even when two start at once, and the socket is private from the moment it is created; a lock that can't be taken at all is reported as such instead of as another daemon (#201). +- The control page and the login page only run their own scripts (a Content-Security-Policy with their hashes) and send no referrer; a client that stops reading no longer holds a connection for good (#202). +- With HTTPS on, the viewer takes actions only from a page served the way it serves it (HTTPS, or plain HTTP from this machine) (#202). +- A viewer stopped while it made its certificate makes a new one on the next start, instead of failing to load a key that doesn't match (#202). +- A token removed with `viewer token remove` is refused at once also within the same second, and `viewer token` commands run at the same time no longer lose each other's changes (#202). +- A setting written twice in `~/.config/iphone-control/env` takes its last value, as the services read it (#202). +- Services install from a program path with spaces, and refuse one with characters systemd or the shell would read as their own; an update that paused the viewer's service starts it again without turning on its start at login (#202). +- An AI task from the control page works when `IPHONE_CONTROL_URL` is set in the settings file (#202). +- A read-only login no longer sends touches from the picture (each answered with an error) and shows no pointer on it (#202). - When pressing Home finds a system alert in the way, the daemon's answer now also marks it in its structured result (`alert_reported`), as launching an app or opening a link does; programs reading the result rather than its text missed it (#200). - A long press falls back to HID like a tap when WebDriverAgent can't be reached (#200). - Requests that can't run (a tap count of 0, an empty tap sequence, an unknown button, a point that isn't a number) are refused at once, before waiting for the phone and without dropping the cached screen (#200). diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 6ccdee03..8ccb0bb3 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -24,6 +24,14 @@ - 手机原生视频转成 H.264 时,ffmpeg 崩溃算作失败,换下一个编码器,不再无休止地重启(#201)。 - `task run --url` 在控制台不应答时,按 Ctrl-C 后 10 秒内也能停下;事件流长时间没动静或发来没有结尾的事件时会放弃(#201)。 - 一个 socket 只会有一个守护进程在跑,两个同时启动也一样;socket 从创建那一刻起就只有自己能访问;根本拿不到锁时如实报错,不再说成已有守护进程(#201)。 +- 控制台和登录页只运行它们自己的脚本(带脚本哈希的 Content-Security-Policy),也不再发送 Referer;客户端不读数据时不会一直占着连接(#202)。 +- 开着 HTTPS 时,控制台只接受以它实际提供的方式打开的页面发来的操作(HTTPS,或本机的明文 HTTP)(#202)。 +- 控制台在生成证书的中途被停掉,下次启动会重新生成,不再因为私钥和证书对不上而起不来(#202)。 +- 用 `viewer token remove` 删掉的令牌,即使在同一秒内也会立刻失效;同时运行的几个 `viewer token` 命令不会再互相覆盖改动(#202)。 +- `~/.config/iphone-control/env` 里同一个设置写了两次时,以最后一次为准,和后台服务的读法一致(#202)。 +- 程序路径里有空格也能装服务;带有 systemd 或 shell 会特殊处理的字符时拒绝安装;升级时暂停过的控制台服务恢复时,不再把它的开机自启打开(#202)。 +- 设置文件里写了 `IPHONE_CONTROL_URL` 时,控制台上的 AI 任务也能正常工作(#202)。 +- 只读登录时,在画面上按下不再把触摸发给手机(之前每次都会弹一个错误),也不显示指针(#202)。 - 按 Home 时发现有系统弹窗挡着,守护进程的应答现在也会在结构化结果里标出(`alert_reported`),和启动 App、打开链接一样;之前只读结果字段、不看文字的程序会漏掉(#200)。 - 长按和点击一样,连不上 WebDriverAgent 时改用 HID(#200)。 - 执行不了的请求(点击次数为 0、空的点击序列、不认识的按键、坐标不是有效数字)立刻拒绝,不再先排队等手机,也不会清掉缓存的界面(#200)。 diff --git a/apps/iphone-control/src/agent.rs b/apps/iphone-control/src/agent.rs index b7257285..d30378c6 100644 --- a/apps/iphone-control/src/agent.rs +++ b/apps/iphone-control/src/agent.rs @@ -191,16 +191,29 @@ fn sub_dir(private: &Path, name: &str) -> std::io::Result { Ok(dir) } +/// Token files left by an earlier viewer (killed before it could remove them): its agents were stopped with it, and +/// one of them could share a name with a new file once a process number comes round again +fn clear_stale_tokens(dir: &Path) { + for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let p = e.path(); + if p.extension().is_some_and(|x| x == "token") && e.file_type().is_ok_and(|t| t.is_file()) { + let _ = std::fs::remove_file(p); + } + } +} + impl Agents { pub fn new(socket: &Path) -> anyhow::Result> { let base = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|p| p.is_absolute()); let private = private_dir(&base.unwrap_or_else(std::env::temp_dir))?; // the agent works in `work`; the tasks' tokens are kept beside it, not in what it works on + let tokens = sub_dir(&private, "tokens")?; + clear_stale_tokens(&tokens); Ok(Arc::new(Self { exe: std::env::current_exe()?, socket: socket.to_path_buf(), workdir: sub_dir(&private, "work")?, - tokens: sub_dir(&private, "tokens")?, + tokens, running: Default::default(), })) } @@ -635,6 +648,10 @@ mod tests { assert_ne!(a.0, b.0); drop((a, b)); std::fs::remove_dir_all(dir).unwrap(); + // a file left by an earlier viewer is cleared when the next one starts + std::fs::write(agents.tokens.join("task-1-0.token"), "old").unwrap(); + let again = Agents::new(Path::new("/nonexistent/ctl.sock")).unwrap(); + assert!(!again.tokens.join("task-1-0.token").exists()); // kept beside the agent's working directory, not in what it works on; both its own assert!(!agents.tokens.starts_with(&agents.workdir) && !agents.workdir.starts_with(&agents.tokens)); for d in [&agents.tokens, &agents.workdir] { diff --git a/apps/iphone-control/src/envfile.rs b/apps/iphone-control/src/envfile.rs index b130c0e0..2556cbc7 100644 --- a/apps/iphone-control/src/envfile.rs +++ b/apps/iphone-control/src/envfile.rs @@ -82,13 +82,21 @@ impl EnvFile { if let Some(dir) = self.path.parent() { std::fs::create_dir_all(dir)?; } - let tmp = self.path.with_extension("tmp"); - let mut f = std::fs::OpenOptions::new().create(true).write(true).truncate(true).mode(0o600).open(&tmp)?; - f.set_permissions(std::fs::Permissions::from_mode(0o600))?; - f.write_all(self.text.as_bytes())?; - f.sync_all()?; - std::fs::rename(&tmp, &self.path)?; - Ok(()) + // a name of its own: two commands saving at once must not write into the same temporary file + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = self.path.with_extension(format!("{}.{n}.tmp", std::process::id())); + let written = (|| { + let mut f = std::fs::OpenOptions::new().create_new(true).write(true).mode(0o600).open(&tmp)?; + f.set_permissions(std::fs::Permissions::from_mode(0o600))?; + f.write_all(self.text.as_bytes())?; + f.sync_all()?; + std::fs::rename(&tmp, &self.path) + })(); + if written.is_err() { + let _ = std::fs::remove_file(&tmp); + } + Ok(written?) } } @@ -138,11 +146,12 @@ fn quote(v: &str) -> anyhow::Result { } /// Puts the file's settings into this process's environment, without overriding what is already set (a variable on -/// the command line wins). Called once at start-up, before any thread is started -pub fn load_into_process() { +/// the command line wins), except the keys in `skip`. A key set twice takes its last value, as the shell and systemd +/// read the file. Called once at start-up, before any thread is started +pub fn load_into_process(skip: &[&str]) { let Ok(text) = std::fs::read_to_string(path()) else { return }; - for (k, v) in parse(&text) { - if v.is_empty() || std::env::var_os(&k).is_some() { + for (k, v) in last_values(parse(&text)) { + if v.is_empty() || skip.contains(&k.as_str()) || std::env::var_os(&k).is_some() { continue; } // SAFETY: single-threaded: main() calls this before building the async runtime @@ -150,10 +159,27 @@ pub fn load_into_process() { } } +/// Each key once, with its last value (an empty last one too: it unsets the key, as in the shell) +fn last_values(pairs: Vec<(String, String)>) -> Vec<(String, String)> { + let mut out: Vec<(String, String)> = Vec::new(); + for (k, v) in pairs { + out.retain(|(o, _)| *o != k); + out.push((k, v)); + } + out +} + #[cfg(test)] mod tests { use super::*; + /// A key set twice takes its last value, as the shell and systemd read the file; a last empty one unsets it + #[test] + fn the_last_value_of_a_key_wins() { + let v = last_values(parse("A=1\nB=x\nA=2\nexport B=\nC='3'\n")); + assert_eq!(v, vec![("A".into(), "2".into()), ("B".into(), String::new()), ("C".into(), "3".into())]); + } + #[test] fn set_replaces_in_place_and_keeps_comments() { let dir = std::env::temp_dir().join(format!("ictl-env-{}", std::process::id())); diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs index f4ebe0a5..ebc94b5c 100644 --- a/apps/iphone-control/src/main.rs +++ b/apps/iphone-control/src/main.rs @@ -272,8 +272,13 @@ fn main() -> anyhow::Result<()> { return completions::write(shell, &mut std::io::stdout().lock()); } } - // 设置文件先读进环境(命令行上已设的优先),要在启动任何线程之前:语言、代理、通知等对所有命令都生效 - envfile::load_into_process(); + // 设置文件先读进环境(命令行上已设的优先),要在启动任何线程之前:语言、代理、通知等对所有命令都生效。 + // 控制台给它的 agent 起的 MCP 服务(`mcp --task-token-file`)只连本机:设置文件里给自己的命令连别处用的地址不读, + // 读了会和这个参数冲突、服务起不来 + let local_only = std::env::args().any(|a| a == "--task-token-file"); + let skip: &[&str] = + if local_only { &[ictl_daemon::protocol::env::URL, ictl_daemon::protocol::env::CA] } else { &[] }; + envfile::load_into_process(skip); tokio::runtime::Runtime::new()?.block_on(run()) } diff --git a/apps/iphone-control/src/schedule.rs b/apps/iphone-control/src/schedule.rs index 505cf88a..7a4f2a73 100644 --- a/apps/iphone-control/src/schedule.rs +++ b/apps/iphone-control/src/schedule.rs @@ -20,6 +20,11 @@ pub fn set_policy(socket: &Path, policy: update::Policy) -> Result<()> { if let Err(e) = configure_job(socket, policy) { // A partial timer install must not later run with unintended permission to replace files. update::set_policy(update::Policy::Manual)?; + // and what was written of it goes (only ours: the same owner check as any change; a job already running is + // left to finish), or a launcher and a unit half set up stay behind + if let Err(cleanup) = configure_job(socket, update::Policy::Manual) { + tracing::debug!("removing a partial update job: {cleanup:#}"); + } bail!( "{}", ictl_l10n::trf!( diff --git a/apps/iphone-control/src/service.rs b/apps/iphone-control/src/service.rs index 92ef2555..6770c47e 100644 --- a/apps/iphone-control/src/service.rs +++ b/apps/iphone-control/src/service.rs @@ -336,15 +336,7 @@ pub fn install() -> anyhow::Result { } let exe = stable_exe()?; let exe = exe.to_string_lossy(); - if exe.contains(['"', '\'', '\\', '&', '<', '>']) { - bail!( - "{}", - ictl_l10n::trf!( - "程序路径里有特殊字符,装不了服务:{exe}", - "The program path has special characters, can't set up a service: {exe}" - ) - ); - } + check_exe(&exe)?; if cfg!(target_os = "macos") { let logs = home().join("Library/Logs/iphone-control"); std::fs::create_dir_all(&logs)?; @@ -394,8 +386,9 @@ pub fn install() -> anyhow::Result { format!( "# Written by iphone-control. Settings: ~/.config/iphone-control/env\n[Unit]\n\ Description=iphone-control daemon (iPhone over USB, MCP)\nAfter=network-online.target\n\n[Service]\n\ - ExecStart={exe} daemon\nEnvironmentFile=-%h/.config/iphone-control/env\nEnvironment=MALLOC_ARENA_MAX=2\n\ - Restart=on-failure\nRestartSec=10\nTimeoutStopSec=30\n\n[Install]\nWantedBy=default.target\n" + ExecStart={} daemon\nEnvironmentFile=-%h/.config/iphone-control/env\nEnvironment=MALLOC_ARENA_MAX=2\n\ + Restart=on-failure\nRestartSec=10\nTimeoutStopSec=30\n\n[Install]\nWantedBy=default.target\n", + exec_path(&exe) ), )?; systemctl(&["daemon-reload"]); @@ -489,11 +482,34 @@ fn viewer_unit_text(exe: &str, path: &str) -> anyhow::Result { Ok(format!( "# Written by iphone-control. Settings: ~/.config/iphone-control/env (IPHONE_CONTROL_VIEWER_*)\n[Unit]\n\ Description=iphone-control viewer (control page)\nAfter=iphone-control.service\n\n[Service]\n\ - ExecStart={exe} viewer\nEnvironmentFile=-%h/.config/iphone-control/env\nEnvironment=\"PATH={path}\"\n\ - Restart=on-failure\nRestartSec=10\n\n[Install]\nWantedBy=default.target\n" + ExecStart={} viewer\nEnvironmentFile=-%h/.config/iphone-control/env\nEnvironment=\"PATH={path}\"\n\ + Restart=on-failure\nRestartSec=10\n\n[Install]\nWantedBy=default.target\n", + exec_path(exe) )) } +/// A program path a service can run: none of the characters that systemd (`%` specifiers, `$` variables, quotes, +/// backslashes), the shell line launchd runs (`$`, backquotes, quotes inside `"…"`) or the plist's XML would read +/// as their own. Spaces are fine ([`exec_path`]) +fn check_exe(exe: &str) -> anyhow::Result<()> { + if exe.chars().any(|c| c.is_control() || "\"'\\&<>$`%".contains(c)) { + bail!( + "{}", + ictl_l10n::trf!( + "程序路径里有特殊字符,装不了服务:{exe}", + "The program path has special characters, can't set up a service: {exe}" + ) + ); + } + Ok(()) +} + +/// The path as `ExecStart=` takes it: quoted when it has spaces (a home directory with one), bare otherwise as it +/// always was ([`managed`] knows both) +fn exec_path(exe: &str) -> String { + if exe.contains(char::is_whitespace) { format!("\"{exe}\"") } else { exe.to_owned() } +} + fn xml(s: &str) -> String { s.replace('&', "&").replace('<', "<").replace('>', ">") } @@ -532,15 +548,7 @@ fn viewer_plist_text(exe: &str, path: &str, log: &Path) -> anyhow::Result anyhow::Result { let exe = stable_exe()?; let exe = exe.to_string_lossy(); - if exe.contains(['"', '\'', '\\', '&', '<', '>']) { - bail!( - "{}", - ictl_l10n::trf!( - "程序路径里有特殊字符,装不了服务:{exe}", - "The program path has special characters, can't set up a service: {exe}" - ) - ); - } + check_exe(&exe)?; let path = std::env::var("PATH").unwrap_or_default(); if let Some(s) = viewer_find() { // rewritten below with the current PATH and program; stop the old one first @@ -606,14 +614,15 @@ pub fn pause_viewer() -> anyhow::Result> { } std::thread::sleep(std::time::Duration::from_millis(200)); } - let _ = start(&s); + let _ = start_managed(&s); bail!("{}", ictl_l10n::tr!("正忙:控制台服务没有停下", "busy: the viewer service didn't stop")) } /// Starts the control page's service again after [`pause_viewer`]; a failure is only reported pub fn resume_viewer(paused: Option) { + // started as it was, not enabled: a service the user keeps from starting at login stays that way if let Some(s) = paused - && let Err(e) = start(&s) + && let Err(e) = start_managed(&s) { eprintln!("{e:#}"); } @@ -652,6 +661,20 @@ mod tests { assert!(launchd_pid(&print("running", Some(1)), Path::new("/elsewhere.plist"), false).is_err()); } + /// A path with a space runs (quoted for systemd); one with characters systemd or the shell would read is refused + #[test] + fn service_program_paths() { + assert!(check_exe("/home/u/.local/bin/iphone-control").is_ok()); + assert!(check_exe("/Users/Jo Smith/.local/bin/iphone-control").is_ok()); + for bad in ["/opt/$HOME/x", "/opt/`id`/x", "/opt/50%/x", "/opt/a\"b/x", "/opt/a\nb/x", "/opt/a&b/x"] { + assert!(check_exe(bad).is_err(), "{bad:?}"); + } + assert_eq!(exec_path("/usr/bin/x"), "/usr/bin/x"); + assert_eq!(exec_path("/Users/Jo Smith/x"), "\"/Users/Jo Smith/x\""); + let unit = viewer_unit_text("/Users/Jo Smith/x", "/usr/bin").unwrap(); + assert!(unit.contains("ExecStart=\"/Users/Jo Smith/x\" viewer\n"), "{unit}"); + } + #[test] fn the_viewer_service_runs_the_viewer_with_this_path() { let path = "/home/u/.local/bin:/home/u/.npm-global/bin:/usr/bin"; diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs index 5e398db6..6d623da8 100644 --- a/apps/iphone-control/src/viewer.rs +++ b/apps/iphone-control/src/viewer.rs @@ -62,6 +62,8 @@ struct Ctx { data_dir: PathBuf, /// The page, marked with the viewer's language (the page's default; it can switch) page: String, + /// The page's `Content-Security-Policy` ([`csp_for`]) + page_csp: String, socket: PathBuf, port: u16, /// The device the page shows and acts on @@ -282,6 +284,7 @@ pub async fn run( checking: Arc::default(), check_error: Arc::default(), names: tokio::sync::Mutex::default(), + page_csp: csp_for(&page_in(ictl_l10n::lang())), page: page_in(ictl_l10n::lang()), device_video_allowed, video, @@ -460,6 +463,42 @@ fn page_in(lang: ictl_l10n::Lang) -> String { PAGE.replacen("", html, 1) } +/// A page's `Content-Security-Policy`: its own inline scripts only (by their SHA-256, so nothing injected into the page +/// runs), inline styles (the page sets `style` attributes), and nothing from other sites: requests, pictures and the +/// picture stream go to this server; no frames, plugins or `` +fn csp_for(html: &str) -> String { + use sha2::{Digest, Sha256}; + let scripts: Vec = html + .split("").map(|(body, _)| body)) + .map(|body| format!("'sha256-{}'", base64(&Sha256::digest(body.as_bytes())))) + .collect(); + format!( + "default-src 'none'; script-src {}; style-src 'unsafe-inline'; img-src 'self' data: blob:; \ + connect-src 'self'; media-src 'self' blob:; base-uri 'none'; form-action 'self'; frame-ancestors 'none'", + if scripts.is_empty() { "'none'".to_owned() } else { scripts.join(" ") } + ) +} + +/// Standard base64 with padding, for [`csp_for`]'s hashes +fn base64(bytes: &[u8]) -> String { + const ABC: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for c in bytes.chunks(3) { + let n = + (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0)); + for i in 0..4 { + if i <= c.len() { + out.push(ABC[(n >> (18 - 6 * i) & 63) as usize] as char); + } else { + out.push('='); + } + } + } + out +} + /// How long a connection kept open waits for the page's next request (short in tests, which wait it out) const KEEP_IDLE: Duration = if cfg!(test) { Duration::from_millis(300) } else { Duration::from_secs(15) }; @@ -635,7 +674,10 @@ async fn route( let Some(client) = slot.as_mut() else { return Ok(()) }; let path = req.path.as_str(); match (req.method.as_str(), path) { - ("GET", "/") => reply(client, 200, "text/html; charset=utf-8", ctx.page.as_bytes()).await, + ("GET", "/") => { + let csp = format!("Content-Security-Policy: {}\r\n", ctx.page_csp); + reply_with(client, 200, "text/html; charset=utf-8", ctx.page.as_bytes(), &csp).await + } ("GET", "/stream" | "/video") => { let _feed = if let Some(id) = req.query("feed").filter(|id| !id.is_empty() && id.len() <= 80) { let Some(guard) = FeedGuard::register(&ctx.feeds, id) else { @@ -718,7 +760,7 @@ async fn route( } ("GET" | "POST" | "DELETE", "/mcp") if ctx.mcp.is_some() => { // a browser says where it comes from: only the page itself. Other clients send no Origin - if req.origin.as_deref().is_some_and(|o| !ctx.access.origin_allowed(o, ctx.port)) { + if req.origin.as_deref().is_some_and(|o| !ctx.access.origin_allowed(o, ctx.port, ctx.tls.is_some())) { return reply(client, 403, "text/plain", b"forbidden").await; } // a length or chunked, not both (a request read two ways is how requests are smuggled past proxies), @@ -763,7 +805,7 @@ async fn route( 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"; + X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\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(()) @@ -992,19 +1034,17 @@ 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 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?; + write_timed( + client, + 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\nReferrer-Policy: no-referrer\r\nConnection: close\r\n\r\n", + ) + .await?; loop { tokio::select! { e = stream.next() => match e { Some(e) => { - client.write_all(sse(&e).as_bytes()).await?; - client.flush().await?; + write_timed(client, sse(&e).as_bytes()).await?; if e.event == "done" { return Ok(()); } @@ -1014,8 +1054,7 @@ async fn events(client: &mut Conn, mut stream: protocol::TaskStream) -> anyhow:: }, // 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?; - client.flush().await?; + write_timed(client, b": ping\n\n").await?; } } } @@ -1042,11 +1081,10 @@ async fn open_task(client: &mut Conn, ctx: &Ctx, b: &Value, by: &str) -> anyhow: let (mut rd, mut wr) = tokio::io::split(client); let head = format!( "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\nevent: opened\ndata: {}\n\n", + X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nConnection: close\r\n\r\nevent: opened\ndata: {}\n\n", json!({"id": opened.id, "token": opened.token}) ); - wr.write_all(head.as_bytes()).await?; - wr.flush().await?; + write_timed(&mut wr, head.as_bytes()).await?; let gone = async { let mut buf = [0u8; 64]; while matches!(rd.read(&mut buf).await, Ok(n) if n > 0) {} @@ -1056,8 +1094,7 @@ async fn open_task(client: &mut Conn, ctx: &Ctx, b: &Value, by: &str) -> anyhow: tokio::select! { e = lease.next() => match e { Some(e) => { - wr.write_all(sse(&e).as_bytes()).await?; - wr.flush().await?; + write_timed(&mut wr, sse(&e).as_bytes()).await?; if e.event == "done" { return Ok(()); } @@ -1069,8 +1106,7 @@ async fn open_task(client: &mut Conn, ctx: &Ctx, b: &Value, by: &str) -> anyhow: () = &mut gone => return Ok(()), // a comment now and then keeps proxies from closing a quiet connection _ = tokio::time::sleep(Duration::from_secs(15)) => { - wr.write_all(b": ping\n\n").await?; - wr.flush().await?; + write_timed(&mut wr, b": ping\n\n").await?; } } } @@ -1089,7 +1125,7 @@ async fn action_body( pass: &Pass, body: &mut Vec, ) -> anyhow::Result> { - if !action_allowed(req, &ctx.access, ctx.port, pass.program()) { + if !action_allowed(req, &ctx.access, ctx.port, ctx.tls.is_some(), pass.program()) { reply(client, 403, "text/plain", b"forbidden").await?; return Ok(None); } @@ -1196,13 +1232,13 @@ async fn reply_with(client: &mut Conn, status: u16, kind: &str, body: &[u8], ext let connection = if keep { "Connection: keep-alive\r\n" } else { "Connection: close\r\n" }; let head = format!( "HTTP/1.1 {status} {reason}\r\nContent-Type: {kind}\r\nContent-Length: {}\r\nCache-Control: no-store\r\n\ - X-Content-Type-Options: nosniff\r\nX-Frame-Options: DENY\r\n{extra}{connection}\r\n", + X-Content-Type-Options: nosniff\r\nX-Frame-Options: DENY\r\nReferrer-Policy: no-referrer\r\n\ + {extra}{connection}\r\n", body.len() ); - client.write_all(head.as_bytes()).await?; - client.write_all(body).await?; - // over TLS the last record may still be buffered - client.flush().await?; + write_timed(client, head.as_bytes()).await?; + // flushed: over TLS the last record may still be buffered + write_timed(client, body).await?; if keep { let _ = KEEP_ALIVE.try_with(|k| k.set(Keep::Kept)); } else { @@ -1211,6 +1247,21 @@ async fn reply_with(client: &mut Conn, status: u16, kind: &str, body: &[u8], ext Ok(()) } +/// Writing one answer, or one event of a stream, at most this long: a client that reads nothing would hold its +/// connection's place for good (there are [`MAX_CONNECTIONS`]) +const WRITE_TIMEOUT: Duration = if cfg!(test) { Duration::from_millis(300) } else { Duration::from_secs(30) }; + +/// Writes and flushes `bytes` within [`WRITE_TIMEOUT`] +async fn write_timed(w: &mut W, bytes: &[u8]) -> anyhow::Result<()> { + tokio::time::timeout(WRITE_TIMEOUT, async { + w.write_all(bytes).await?; + w.flush().await + }) + .await + .map_err(|_| anyhow::anyhow!("the client stopped reading"))??; + Ok(()) +} + /// Closes after an answer without losing it: a socket closed with request data it never read (a body refused before /// it was read: 401, 403, 413) sends a reset, and the client may then never see the answer. So: end our side, then /// read what the client still sends until it closes too, for a second and 1 MB at most @@ -1289,7 +1340,7 @@ async fn login_gate( } // the login page's form if req.method == "POST" && req.path == "/login" { - if req.origin.as_deref().is_some_and(|o| !ctx.access.origin_allowed(o, ctx.port)) { + if req.origin.as_deref().is_some_and(|o| !ctx.access.origin_allowed(o, ctx.port, ctx.tls.is_some())) { reply(client, 403, "text/plain", b"forbidden").await?; return Ok(None); } @@ -1352,7 +1403,9 @@ async fn login_page(client: &mut Conn, v: auth::Verdict) -> anyhow::Result<()> { auth::Verdict::Limited => (429, Some(auth::LoginError::Limited)), _ => (401, None), }; - reply(client, status, "text/html; charset=utf-8", auth::login_page(why).as_bytes()).await + let page = auth::login_page(why); + let csp = format!("Content-Security-Policy: {}\r\n", csp_for(&page)); + reply_with(client, status, "text/html; charset=utf-8", page.as_bytes(), &csp).await } /// Where a plain HTTP request from the network goes: the same page over HTTPS, at the name it asked for (one of @@ -1367,7 +1420,7 @@ fn https_location(head: &[u8], req: &Head, port: u16) -> Option { 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" + Referrer-Policy: no-referrer\r\nConnection: close\r\n\r\n" ); client.write_all(head.as_bytes()).await?; client.flush().await?; @@ -1536,10 +1589,10 @@ fn percent_decode(s: &str) -> String { /// answers /// `bearer`: logged in with `Authorization: Bearer` (a program). A browser always sends `Origin` with a POST, and a /// web page can't make it send that header, so without `Origin` only a program's request is taken -fn action_allowed(req: &Head, access: &lan::Access, port: u16, bearer: bool) -> bool { +fn action_allowed(req: &Head, access: &lan::Access, port: u16, tls: bool, bearer: bool) -> bool { let json = req.content_type.as_deref().is_some_and(|c| c.split(';').next() == Some("application/json")); json && match req.origin.as_deref() { - Some(o) => access.origin_allowed(o, port), + Some(o) => access.origin_allowed(o, port, tls), None => bearer, } } @@ -1631,6 +1684,7 @@ mod tests { data_dir: dir.into(), port: 0, page: String::new(), + page_csp: String::new(), checking: Arc::default(), check_error: Arc::default(), names: Default::default(), @@ -2092,6 +2146,41 @@ mod tests { /// The redirect's `Location` is built from the request target: only a path is a target, so it can't send a /// browser to another host (`@evil.example/` would make `https://host:port@evil.example/`) nor add a header line + /// An answer to a client that reads nothing gives up after [`WRITE_TIMEOUT`] instead of holding the connection + #[tokio::test] + async fn a_client_that_reads_nothing_is_let_go() { + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let (client, accepted) = + tokio::join!(tokio::net::TcpStream::connect(listener.local_addr().unwrap()), listener.accept()); + let _never_reads = client.unwrap(); + let mut conn = Conn::Plain(accepted.unwrap().0); + let big = vec![b'x'; 32 << 20]; + let t0 = std::time::Instant::now(); + let r = tokio::time::timeout(Duration::from_secs(10), reply(&mut conn, 200, "text/plain", &big)).await; + assert!(matches!(r, Ok(Err(_))), "gave up with an error"); + assert!(t0.elapsed() < Duration::from_secs(5), "{:?}", t0.elapsed()); + } + + /// The pages run their own inline scripts only: the policy names each by its hash, and a script changed or added + /// by someone else matches none + #[test] + fn pages_allow_only_their_own_scripts() { + use sha2::{Digest, Sha256}; + for (input, want) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foobar", "Zm9vYmFy")] { + assert_eq!(base64(input.as_bytes()), want); + } + let page = page_in(ictl_l10n::Lang::En); + let csp = csp_for(&page); + let script = page.split("").next().unwrap(); + let hash = format!("'sha256-{}'", base64(&Sha256::digest(script.as_bytes()))); + assert!(csp.contains(&format!("script-src {hash};")), "{csp}"); + assert!(csp.starts_with("default-src 'none';") && csp.contains("frame-ancestors 'none'"), "{csp}"); + let login = auth::login_page(None); + assert_eq!(csp_for(&login).matches("'sha256-").count(), 2, "the login page's two scripts"); + assert!(!csp_for(&page.replace("'use strict';", "'use strict';alert(1);")).contains(&hash)); + assert!(csp_for("

no script

").contains("script-src 'none'")); + } + #[test] fn only_a_plain_request_head_is_taken() { let ok = |s: &str| Head::parse(s.as_bytes()).is_some(); @@ -2348,11 +2437,12 @@ mod tests { 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), &local, 8200, false)); + assert!(action_allowed(&head(ok), &local, 8200, false, false)); assert!(action_allowed( &head(&ok.replace("http://127.0.0.1:8200", "http://localhost:8200")), &local, 8200, + false, false )); // another page, another port, no origin, a form post @@ -2360,34 +2450,50 @@ mod tests { &head(&ok.replace("http://127.0.0.1:8200", "http://evil.example")), &local, 8200, + false, false )); assert!(!action_allowed( &head(&ok.replace("http://127.0.0.1:8200", "http://127.0.0.1:3000")), &local, 8200, + false, + false + )); + assert!(!action_allowed( + &head(&ok.replace("Origin: http://127.0.0.1:8200\r\n", "")), + &local, + 8200, + false, false )); - assert!(!action_allowed(&head(&ok.replace("Origin: http://127.0.0.1:8200\r\n", "")), &local, 8200, false)); // a program logged in with Authorization: Bearer sends no Origin; a cookie (a browser) needs it - assert!(action_allowed(&head(&ok.replace("Origin: http://127.0.0.1:8200\r\n", "")), &local, 8200, true)); + assert!(action_allowed(&head(&ok.replace("Origin: http://127.0.0.1:8200\r\n", "")), &local, 8200, false, true)); assert!(!action_allowed( &head(&ok.replace("http://127.0.0.1:8200", "http://evil.example")), &local, 8200, + false, true )); - assert!(!action_allowed(&head(&ok.replace("application/json", "text/plain")), &local, 8200, false)); + assert!(!action_allowed(&head(&ok.replace("application/json", "text/plain")), &local, 8200, false, false)); assert!(!action_allowed( &head(&ok.replace("Origin: http://127.0.0.1:8200", "Origin: null")), &local, 8200, + false, false )); // 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, false)); - assert!(action_allowed(&head(&on_lan), &lan::Access::with_hosts(["192.168.10.100".into()]), 8200, false)); + assert!(!action_allowed(&head(&on_lan), &local, 8200, false, false)); + assert!(action_allowed( + &head(&on_lan), + &lan::Access::with_hosts(["192.168.10.100".into()]), + 8200, + false, + false + )); } #[test] diff --git a/apps/iphone-control/src/viewer/auth.rs b/apps/iphone-control/src/viewer/auth.rs index b638f940..ff48fc42 100644 --- a/apps/iphone-control/src/viewer/auth.rs +++ b/apps/iphone-control/src/viewer/auth.rs @@ -75,8 +75,36 @@ pub fn tokens_file(data_dir: &Path) -> PathBuf { data_dir.join(TOKENS_FILE) } +/// Runs `f` holding the lock beside the tokens file: commands changing tokens at once (and the first start making +/// them) read and write one after the other instead of one losing the other's change +fn locked(data_dir: &Path, f: impl FnOnce() -> anyhow::Result) -> anyhow::Result { + use std::os::fd::AsRawFd; + use std::os::unix::fs::OpenOptionsExt; + std::fs::create_dir_all(data_dir)?; + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(tokens_file(data_dir).with_extension("lock"))?; + if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX) } != 0 { + return Err(io::Error::last_os_error().into()); + } + f() +} + /// The tokens; the first start makes [`OWNER`] (from the earlier single token if there is one) pub fn load(data_dir: &Path) -> anyhow::Result> { + if let Some(v) = read(data_dir)? { + return Ok(v); + } + locked(data_dir, || load_unlocked(data_dir)) +} + +/// [`load`] with the lock held +fn load_unlocked(data_dir: &Path) -> anyhow::Result> { if let Some(v) = read(data_dir)? { return Ok(v); } @@ -124,7 +152,11 @@ pub fn add(data_dir: &Path, name: &str, role: Role) -> anyhow::Result { "A name takes letters, digits and - _ . only, 40 at most: {name}" )); } - let mut v = load(data_dir)?; + locked(data_dir, || add_unlocked(data_dir, name, role)) +} + +fn add_unlocked(data_dir: &Path, name: &str, role: Role) -> anyhow::Result { + let mut v = load_unlocked(data_dir)?; if v.iter().any(|e| e.name == name) { bail!(ictl_l10n::trf!( "已经有叫 {name} 的令牌了;要换新的用 viewer token show {name} --new", @@ -144,7 +176,11 @@ pub fn get(data_dir: &Path, name: &str) -> anyhow::Result { /// A new token in place of `name`'s; its browsers have to log in again pub fn renew(data_dir: &Path, name: &str) -> anyhow::Result { - let mut v = load(data_dir)?; + locked(data_dir, || renew_unlocked(data_dir, name)) +} + +fn renew_unlocked(data_dir: &Path, name: &str) -> anyhow::Result { + let mut v = load_unlocked(data_dir)?; let e = v.iter_mut().find(|e| e.name == name).ok_or_else(|| no_such(name))?; e.token = new_token()?; e.created = now(); @@ -155,7 +191,11 @@ pub fn renew(data_dir: &Path, name: &str) -> anyhow::Result { /// Removes `name`; the last token that may operate stays (nobody could act otherwise) pub fn remove(data_dir: &Path, name: &str) -> anyhow::Result<()> { - let mut v = load(data_dir)?; + locked(data_dir, || remove_unlocked(data_dir, name)) +} + +fn remove_unlocked(data_dir: &Path, name: &str) -> anyhow::Result<()> { + let mut v = load_unlocked(data_dir)?; let Some(i) = v.iter().position(|e| e.name == name) else { return Err(no_such(name)) }; if v[i].role == Role::Operate && v.iter().filter(|e| e.role == Role::Operate).count() == 1 { bail!(ictl_l10n::trf!( @@ -269,7 +309,23 @@ impl Known { /// The tokens, read again when the file changes (`viewer token …` while the viewer runs) struct Tokens { known: Vec, - modified: Option, + modified: Option, +} + +/// What tells that the tokens file changed: its time alone misses a change within the same second on file systems +/// that keep whole seconds (a token removed right after another change would stay valid). Each save is a new file +/// renamed into place, so its inode changes every time +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Stamp { + modified: SystemTime, + len: u64, + ino: u64, +} + +fn stamp(data_dir: &Path) -> Option { + use std::os::unix::fs::MetadataExt; + let m = std::fs::metadata(tokens_file(data_dir)).ok()?; + Some(Stamp { modified: m.modified().ok()?, len: m.len(), ino: m.ino() }) } pub struct Auth { @@ -285,8 +341,7 @@ impl Auth { /// The tokens in `data_dir` ([`load`]) pub fn load(data_dir: &Path, port: u16) -> anyhow::Result { let known = load(data_dir)?.into_iter().map(Known::of).collect(); - let modified = std::fs::metadata(tokens_file(data_dir)).and_then(|m| m.modified()).ok(); - Ok(Self::with(Some(data_dir.to_owned()), Tokens { known, modified }, port)) + Ok(Self::with(Some(data_dir.to_owned()), Tokens { known, modified: stamp(data_dir) }, port)) } /// These tokens and no file @@ -303,7 +358,7 @@ impl Auth { fn tokens(&self) -> std::sync::MutexGuard<'_, Tokens> { let mut t = self.tokens.lock().unwrap_or_else(|p| p.into_inner()); if let Some(dir) = &self.data_dir { - let modified = std::fs::metadata(tokens_file(dir)).and_then(|m| m.modified()).ok(); + let modified = stamp(dir); if modified != t.modified && let Ok(Some(v)) = read(dir) { @@ -527,6 +582,50 @@ mod tests { assert!(t.len() == 64 && valid_token(t)); } + /// Commands adding tokens at once each keep theirs: the read-change-write is done one after the other + #[test] + fn tokens_added_at_once_are_all_kept() { + let tmp = tempfile::tempdir().unwrap(); + load(tmp.path()).unwrap(); + let dir = tmp.path().to_owned(); + let threads: Vec<_> = (0..8) + .map(|i| { + let dir = dir.clone(); + std::thread::spawn(move || add(&dir, &format!("t{i}"), Role::View).unwrap()) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + let names: Vec = load(&dir).unwrap().into_iter().map(|e| e.name).collect(); + for i in 0..8 { + assert!(names.contains(&format!("t{i}")), "{names:?}"); + } + } + + /// A token removed is let go of at once, also when the file's time reads the same (a file system keeping whole + /// seconds, a change within the same one) + #[test] + fn a_removed_token_is_noticed_within_the_same_second() { + let tmp = tempfile::tempdir().unwrap(); + load(tmp.path()).unwrap(); + let tv = add(tmp.path(), "tv", Role::View).unwrap(); + let auth = Auth::load(tmp.path(), 8200).unwrap(); + let Verdict::Ok(who) = auth.try_token(&tv.token) else { panic!("logs in") }; + assert!(auth.knows(&who)); + let file = tokens_file(tmp.path()); + let before = std::fs::metadata(&file).unwrap().modified().unwrap(); + remove(tmp.path(), "tv").unwrap(); + std::fs::File::options() + .write(true) + .open(&file) + .unwrap() + .set_times(std::fs::FileTimes::new().set_modified(before)) + .unwrap(); + assert_eq!(std::fs::metadata(&file).unwrap().modified().unwrap(), before, "the same time"); + assert!(!auth.knows(&who), "noticed all the same"); + } + #[test] fn tokens_are_added_renewed_and_removed_by_name() { let tmp = tempfile::tempdir().unwrap(); diff --git a/apps/iphone-control/src/viewer/lan.rs b/apps/iphone-control/src/viewer/lan.rs index fdc26c76..9197d65c 100644 --- a/apps/iphone-control/src/viewer/lan.rs +++ b/apps/iphone-control/src/viewer/lan.rs @@ -89,10 +89,14 @@ impl Access { host_header(head).is_some_and(|h| self.knows(&h)) } - /// An action's `Origin` is this page: `http://` or `https://:` - pub fn origin_allowed(&self, origin: &str, port: u16) -> bool { - let Some(rest) = origin.strip_prefix("http://").or_else(|| origin.strip_prefix("https://")) else { - return false; + /// An action's `Origin` is this page: `http://` or `https://:`, as this server serves it. + /// `tls`: HTTPS is on, and plain HTTP is served to this machine only (the network is sent to HTTPS); off, this + /// server speaks plain HTTP only, and no page of it is `https://` + pub fn origin_allowed(&self, origin: &str, port: u16, tls: bool) -> bool { + let (rest, https) = match (origin.strip_prefix("http://"), origin.strip_prefix("https://")) { + (Some(r), _) => (r, false), + (_, Some(r)) => (r, true), + _ => return false, }; let rest = rest.to_ascii_lowercase(); // a browser leaves the scheme's default port out @@ -102,7 +106,13 @@ impl Access { Some(np) => np, None => (rest.as_str(), default), }; - p == port && self.knows(name) + let scheme_served = match (tls, https) { + (true, true) | (false, false) => true, + // plain HTTP with HTTPS on: from this machine only + (true, false) => LOOPBACK.contains(&name), + (false, true) => false, + }; + p == port && scheme_served && self.knows(name) } } @@ -213,8 +223,8 @@ mod tests { } 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)); + assert!(a.origin_allowed("http://127.0.0.1:8202", 8202, false)); + assert!(!a.origin_allowed("http://192.168.10.100:8202", 8202, false)); } #[test] @@ -229,17 +239,26 @@ mod tests { 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), "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)); + assert!(a.origin_allowed("http://192.168.10.100:8202", 8202, false)); + assert!(a.origin_allowed("http://NAS.local:8202", 8202, false)); + assert!(a.origin_allowed("https://192.168.10.100:8202", 8202, true), "the page over HTTPS"); + assert!(!a.origin_allowed("https://evil.example:8202", 8202, true)); + assert!(!a.origin_allowed("ftp://192.168.10.100:8202", 8202, false)); + assert!(!a.origin_allowed("http://192.168.10.100:3000", 8202, false), "another port"); + assert!(!a.origin_allowed("http://evil.example:8202", 8202, false)); + assert!(!a.origin_allowed("null", 8202, false)); // the scheme's default port, which a browser leaves out - assert!(a.origin_allowed("https://nas.local", 443) && a.origin_allowed("http://nas.local", 80)); - assert!(!a.origin_allowed("https://nas.local", 8202) && !a.origin_allowed("http://nas.local", 443)); + assert!(a.origin_allowed("https://nas.local", 443, true) && a.origin_allowed("http://nas.local", 80, false)); + assert!( + !a.origin_allowed("https://nas.local", 8202, true) && !a.origin_allowed("http://nas.local", 443, false) + ); + // the scheme this server serves: with HTTPS on, plain HTTP only for this machine; off, no HTTPS page at all + assert!(!a.origin_allowed("http://nas.local:8202", 8202, true), "the network gets HTTPS"); + assert!( + a.origin_allowed("http://127.0.0.1:8202", 8202, true) + && a.origin_allowed("http://localhost:8202", 8202, true) + ); + assert!(!a.origin_allowed("https://192.168.10.100:8202", 8202, false), "no HTTPS here"); // 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"); diff --git a/apps/iphone-control/src/viewer/tls.rs b/apps/iphone-control/src/viewer/tls.rs index 698accf5..c970ac9b 100644 --- a/apps/iphone-control/src/viewer/tls.rs +++ b/apps/iphone-control/src/viewer/tls.rs @@ -190,20 +190,44 @@ fn ensure_made(dir: &Path, names: &[String], now: u64) -> anyhow::Result<(Vec return Err(e.into()), + _ => {} + } + write_atomic(&key_f, &k, 0o600)?; + write_atomic(&cert_f, &c, 0o644)?; + write_atomic(&meta_f, &serde_json::to_vec_pretty(&Made { names: all, not_after })?, 0o644)?; Ok((c, k)) } -/// The key: only for this user -fn write_private(dir: &Path, file: &Path, data: &[u8]) -> io::Result<()> { +/// Writes `data` to a temporary file beside `file` (with `mode` from the start: the key is only ever this user's), +/// syncs it and renames it into place: `file` is the old content or all of the new +fn write_atomic(file: &Path, data: &[u8], mode: u32) -> 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) + use std::os::unix::fs::OpenOptionsExt; + let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let tmp = file.with_file_name(format!(".{name}.{}.tmp", std::process::id())); + let r = std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .mode(mode) + .open(&tmp) + .and_then(|mut f| { + f.write_all(data)?; + f.sync_all() + }) + .and_then(|()| std::fs::rename(&tmp, file)); + if r.is_err() { + let _ = std::fs::remove_file(&tmp); + } + r } /// Year, month, day of a Unix time (UTC) @@ -295,6 +319,24 @@ mod tests { assert_ne!(fingerprint(&CertificateDer::pem_slice_iter(&cert).next().unwrap().unwrap()), c.fingerprint); } + /// A stop while a new pair was written (a new key beside the old certificate, names.json gone) makes a pair again + /// on the next start, instead of a viewer that can't load its certificate; nothing temporary is left + #[test] + fn a_pair_written_halfway_is_made_again() { + let tmp = tempfile::tempdir().unwrap(); + let a = Tls::made(tmp.path(), &names(&["localhost"])).unwrap(); + let dir = tmp.path().join(DIR); + // as left by a stop after the key: names.json removed, the key another one + std::fs::remove_file(dir.join("names.json")).unwrap(); + let other = rcgen::KeyPair::generate().unwrap().serialize_pem(); + std::fs::write(dir.join("key.pem"), other).unwrap(); + let b = Tls::made(tmp.path(), &names(&["localhost"])).expect("made again, and loads"); + assert_ne!(a.fingerprint, b.fingerprint); + let left: Vec = + std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + assert!(left.iter().all(|n| !n.ends_with(".tmp")), "{left:?}"); + } + #[test] fn the_user_s_files() { let tmp = tempfile::tempdir().unwrap(); diff --git a/apps/iphone-control/web/js/screen.js b/apps/iphone-control/web/js/screen.js index b950ec91..1e1c5501 100644 --- a/apps/iphone-control/web/js/screen.js +++ b/apps/iphone-control/web/js/screen.js @@ -168,8 +168,15 @@ async function touchPump() { } T.busy = false; } +/* 只读登录:画面上的手指、滚轮都不发给手机(服务端也会拒绝,但每次都弹一个错误),只提示一下,三秒内不重复 */ +let viewOnlyShown = 0; +function viewOnly() { + if (!S.readOnly) return false; + if (Date.now() - viewOnlyShown > 3000) { viewOnlyShown = Date.now(); show(tr('只读登录:只能看,不能操作'), 'warn'); } + return true; +} function touchWarm() { - if (!S.liveTouch || S.mode !== 'live' || !dims() || guarded() || Date.now() - T.warm < 20000) return; + if (S.readOnly || !S.liveTouch || S.mode !== 'live' || !dims() || guarded() || Date.now() - T.warm < 20000) return; T.warm = Date.now(); touchSend('prepare', null); } function fingerDown(p) { @@ -187,6 +194,7 @@ for (const t of ['pointerdown', 'pointermove', 'pointerup', 'pointercancel', 'wh stage.addEventListener('pointerdown', ev => { if (ev.button !== 0 || S.mode === 'detecting' || ev.target.closest('button, a, code')) return; + if (viewOnly()) return; if (guarded()) { nudgeGuard(); return; } const p = toPoints(ev.clientX, ev.clientY); if (!p || down) return; @@ -199,7 +207,7 @@ stage.addEventListener('pointerdown', ev => { /* 鼠标悬停时跟随光标的小圆点,标出将要点到的位置;触屏、画面外、AI 操作时不显示 */ let hoverDot = null; function moveHoverDot(p, ev) { - if (!p || ev.pointerType === 'touch' || guarded()) { hideHoverDot(); return; } + if (!p || ev.pointerType === 'touch' || guarded() || S.readOnly) { hideHoverDot(); return; } if (!hoverDot) { hoverDot = svgEl('g', { class: 'hover-dot' }); const scale = svgEl('g', { class: 'dot-scale' }); @@ -248,7 +256,8 @@ const W = { on: false, start: null, cur: null, pend: { x: 0, y: 0 }, idle: 0, ra const EDGE = 90; function wheelSafe(p) { const d = dims(); return { x: Math.min(d.W - 30, Math.max(30, p.x)), y: Math.min(d.H - EDGE, Math.max(EDGE, p.y)) }; } stage.addEventListener('wheel', ev => { - if (S.mode !== 'live' || ev.ctrlKey || ev.metaKey || down) return; + // read-only: the page scrolls as any page, nothing goes to the phone + if (S.mode !== 'live' || S.readOnly || ev.ctrlKey || ev.metaKey || down) return; const p = toPoints(ev.clientX, ev.clientY); if (!p) return; ev.preventDefault(); diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index b0eb7566..c51dc302 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -219,3 +219,11 @@ | 213 | 原生 HEVC 转 H.264:ffmpeg 崩了导致输入通道关闭(`try_send` 的 `Closed`)被当成「跟不上」,不计失败、无限重启;连续失败也不换编码器 | `Closed` 记一次失败;连续 3 次没出帧就像 MJPEG 一样 `give_up` 换下一个编码器(只有 ffmpeg 替内置编码器跑时不换,那不是它的问题) | 代码审查(单测需要真编码器;真机上没有能让 ffmpeg 崩的条件) | | 214 | `task run --url`:Ctrl-C 时 `stop()` 没有超时,控制台不应答就一直等;SSE 读取没有静默超时,缓冲没有上限 | `stop()` 限时 10 秒;60 秒什么都没收到(控制台每 15 秒发 ping)就当断开;一个事件超过 1 MB 还没结束就放弃 | 单测 `an_event_without_end_ends_the_stream` | | 215 | 守护进程只靠「连不上 socket」判断没有别的实例:两个同时启动都连不上,先后 bind,后一个把前一个的 socket 抢走;bind 和 chmod 0600 之间 socket 是 umask 的权限 | socket 旁边的 `ctl.lock` 加 `flock`,守护进程一直拿着(等前一个最多 15 秒,有人在服务就立即退出;`flock` 报的不是「被占用」或「被打断」就直接报错,不白等);bind 时 umask 077;自己新建的 socket 目录是 0700 | 单测 `only_one_daemon_holds_a_socket` + 真机 | +| 216 | 控制台和登录页没有 CSP、没有 `Referrer-Policy`;回答和事件流的写入没有超时,不读数据的客户端会一直占着一个连接名额 | 页面带 CSP:只放行它自己内联脚本的 sha256,`default-src 'none'`,图片、请求、媒体只到本服务,禁止被嵌入;所有回答带 `Referrer-Policy: no-referrer`;每次写回答或事件限 30 秒 | 单测 `pages_allow_only_their_own_scripts`、`a_client_that_reads_nothing_is_let_go` + 真机(iPhone Safari 打开控制台,画面、操作、任务都正常,控制台没有 CSP 报错) | +| 217 | `origin_allowed` 不看 scheme:开着 HTTPS 时 `http://<局域网名字>` 的 Origin 也收(这种页面本服务根本不提供),没开 HTTPS 时 `https://` 也收 | 开着 HTTPS:`https://` 都行,`http://` 只限本机名字;没开:只收 `http://` | 单测 `on_the_lan_its_own_names_but_no_others` | +| 218 | 证书、私钥、`names.json` 直接写:写到一半被停掉,新私钥配旧证书,`names.json` 还在,于是照常复用,启动时报「证书和私钥对不上」,以后都起不来 | 先删 `names.json`,再依次原子写(临时文件 + fsync + rename)私钥(一开始就是 0600)、证书,最后写 `names.json`;中途停掉,下次就重新生成 | 单测 `a_pair_written_halfway_is_made_again` | +| 219 | 令牌文件只按修改时间判断有没有变:秒级精度的文件系统上,同一秒内删掉的令牌照样能用;`viewer token add/renew/remove` 读改写不加锁,同时运行会丢改动 | 比较 (修改时间, 长度, inode)(每次保存都是新文件 rename,inode 必变);读改写放在 `viewer-tokens.lock` 的 `flock` 里 | 单测 `a_removed_token_is_noticed_within_the_same_second`、`tokens_added_at_once_are_all_kept` | +| 220 | `env` 设置文件里同一个键写两次:服务(systemd、launchd 的 shell)取最后一个,命令行程序取第一个;保存用固定的 `env.tmp`,两个命令同时保存会写进同一个临时文件 | `load_into_process` 取最后一个(最后为空就不设);临时文件名带进程号和序号,`create_new` | 单测 `the_last_value_of_a_key_wins` | +| 221 | 装服务:路径里的空格让 systemd 的 `ExecStart` 失败,`$`、反引号、`%` 会被 systemd 或 launchd 的 shell 当成自己的语法;升级暂停 viewer 服务后用 `enable --now` 恢复,用户关掉的开机自启又被打开;自动更新任务配置失败时写了一半的 unit、launcher 留着 | 允许空格(`ExecStart` 加引号),拒绝 `$`、反引号、`%`、引号、反斜杠、控制字符;恢复用 `start_managed`(只 start);配置失败后按 Manual 再走一遍,删掉自己的那些文件 | 单测 `service_program_paths`、原有的 `the_viewer_service_runs_the_viewer_with_this_path` | +| 222 | 设置文件里有 `IPHONE_CONTROL_URL` 时,控制台给 agent 起的 `mcp --task-token-file` 读进这个变量,和参数冲突,MCP 服务起不来;`tokens/` 里上次留下的令牌文件可能和新文件撞名 | 命令行带 `--task-token-file` 时,载入设置文件跳过 `IPHONE_CONTROL_URL`、`IPHONE_CONTROL_CA`;控制台启动时清掉 `tokens/` 里残留的令牌文件 | 单测 `a_prompt_is_never_an_option_and_the_token_never_on_the_command_line`(残留清理)+ 真机(设置文件写了 URL,控制台的任务照常完成) | +| 223 | 只读登录:画面上按下照样发 `/api/touch`(服务端拒绝,每次弹错误),悬停圆点照常显示,滚轮也会去滑手机 | 只读时手指、预热、滚轮都不发,提示「只读登录」(3 秒内不重复),不显示悬停圆点 | 页面测试 `a read-only page sends no finger and says so once in a while` | diff --git a/tests/viewer/actions.test.mjs b/tests/viewer/actions.test.mjs index b266b633..bc7023fc 100644 --- a/tests/viewer/actions.test.mjs +++ b/tests/viewer/actions.test.mjs @@ -126,3 +126,26 @@ test('hovering keeps the HID session warm at most every 20 seconds', () => { context.S.liveTouch = false; now += 20000; touchWarm(); assert.equal(sent.length, 2, 'no warm-up without live touch'); }); + +// Read-only login: the picture takes no finger (the server refuses anyway, with an error each time); a note, not a flood +test('a read-only page sends no finger and says so once in a while', () => { + const shown = [], sent = []; + const S = { readOnly: true, liveTouch: true, mode: 'live' }; + const context = { S, tr: String, show: (m, k) => shown.push([m, k]), Date: { now: () => context.now }, now: 10000, + T: { warm: 0 }, dims: () => ({ W: 1, H: 1 }), guarded: () => false, touchSend: (...a) => sent.push(a) }; + const fns = ['viewOnly', 'touchWarm'].map(n => html.match(new RegExp(`^function ${n}\\([^]*?^}`, 'm'))[0]).join('\n'); + const { viewOnly, touchWarm } = runInNewContext('let viewOnlyShown = 0;\n' + fns + '\n({ viewOnly, touchWarm })', context); + assert.equal(viewOnly(), true); + assert.equal(viewOnly(), true); + assert.equal(shown.length, 1, 'once, not on every touch'); + context.now += 4000; + viewOnly(); + assert.equal(shown.length, 2); + touchWarm(); + assert.equal(sent.length, 0, 'not even the HID session warmed'); + S.readOnly = false; + assert.equal(viewOnly(), false); + context.now += 20000; // past its once-in-20-s + touchWarm(); + assert.equal(sent.length, 1); +}); From 4c34761065b6428fa77e2d0ad94aecbe004005b2 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:01:42 +0800 Subject: [PATCH 2/2] fix: review of P1-3 (update job rollback, shared token directory, --task-token-file, /mcp writes) - Turning the update job off unloads it as far as it can: when systemctl or launchctl fails (often why setting it up just failed) the unit, timer, plist and launcher written here still go, and the error comes after. - `clear_stale_tokens` only removes token files of this process or of one that is gone: the directory is shared by every viewer of the user. - `mcp --task-token-file` (or `=FILE`) is found after the root options, for `mcp` only, from the raw arguments (non-UTF-8 ones don't panic). - `/mcp` writes its answer and each event within the write limit, and sends Referrer-Policy like every other answer; so do the redirect and the MJPEG stream; `linger` bounds its shutdown (TLS close_notify) by its second. - `write_atomic` makes a new temporary file each time and sets its mode; the token lock retries on EINTR; the page is built once; `https` reused. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- CHANGELOG.zh-CN.md | 2 +- apps/iphone-control/src/agent.rs | 48 ++++++++++++--- apps/iphone-control/src/completions.rs | 20 ++++--- apps/iphone-control/src/main.rs | 45 +++++++++++++- apps/iphone-control/src/schedule.rs | 81 ++++++++++++++++++++++++-- apps/iphone-control/src/video/mod.rs | 2 +- apps/iphone-control/src/viewer.rs | 19 +++--- apps/iphone-control/src/viewer/auth.rs | 8 ++- apps/iphone-control/src/viewer/lan.rs | 2 +- apps/iphone-control/src/viewer/mcp.rs | 39 +++++++------ apps/iphone-control/src/viewer/tls.rs | 46 ++++++++++----- docs/dev/regression-cases.md | 8 +-- 13 files changed, 249 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 58cf0fb7..dc2bf215 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,7 @@ What changed in each release, one line per change. Versions follow [Semantic Ver - A viewer stopped while it made its certificate makes a new one on the next start, instead of failing to load a key that doesn't match (#202). - A token removed with `viewer token remove` is refused at once also within the same second, and `viewer token` commands run at the same time no longer lose each other's changes (#202). - A setting written twice in `~/.config/iphone-control/env` takes its last value, as the services read it (#202). -- Services install from a program path with spaces, and refuse one with characters systemd or the shell would read as their own; an update that paused the viewer's service starts it again without turning on its start at login (#202). +- Services install from a program path with spaces, and refuse one with characters systemd or the shell would read as their own; an update that paused the viewer's service starts it again without turning on its start at login; setting up the automatic update job and failing leaves none of its files behind, even when the service manager can't be reached (#202). - An AI task from the control page works when `IPHONE_CONTROL_URL` is set in the settings file (#202). - A read-only login no longer sends touches from the picture (each answered with an error) and shows no pointer on it (#202). - When pressing Home finds a system alert in the way, the daemon's answer now also marks it in its structured result (`alert_reported`), as launching an app or opening a link does; programs reading the result rather than its text missed it (#200). diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 8ccb0bb3..0f9e8390 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -29,7 +29,7 @@ - 控制台在生成证书的中途被停掉,下次启动会重新生成,不再因为私钥和证书对不上而起不来(#202)。 - 用 `viewer token remove` 删掉的令牌,即使在同一秒内也会立刻失效;同时运行的几个 `viewer token` 命令不会再互相覆盖改动(#202)。 - `~/.config/iphone-control/env` 里同一个设置写了两次时,以最后一次为准,和后台服务的读法一致(#202)。 -- 程序路径里有空格也能装服务;带有 systemd 或 shell 会特殊处理的字符时拒绝安装;升级时暂停过的控制台服务恢复时,不再把它的开机自启打开(#202)。 +- 程序路径里有空格也能装服务;带有 systemd 或 shell 会特殊处理的字符时拒绝安装;升级时暂停过的控制台服务恢复时,不再把它的开机自启打开;配置自动更新任务失败时,连不上服务管理器也不会留下它的文件(#202)。 - 设置文件里写了 `IPHONE_CONTROL_URL` 时,控制台上的 AI 任务也能正常工作(#202)。 - 只读登录时,在画面上按下不再把触摸发给手机(之前每次都会弹一个错误),也不显示指针(#202)。 - 按 Home 时发现有系统弹窗挡着,守护进程的应答现在也会在结构化结果里标出(`alert_reported`),和启动 App、打开链接一样;之前只读结果字段、不看文字的程序会漏掉(#200)。 diff --git a/apps/iphone-control/src/agent.rs b/apps/iphone-control/src/agent.rs index d30378c6..437c7d03 100644 --- a/apps/iphone-control/src/agent.rs +++ b/apps/iphone-control/src/agent.rs @@ -192,16 +192,34 @@ fn sub_dir(private: &Path, name: &str) -> std::io::Result { } /// Token files left by an earlier viewer (killed before it could remove them): its agents were stopped with it, and -/// one of them could share a name with a new file once a process number comes round again +/// one of them could share a name with a new file once a process number comes round again. The directory is this +/// user's, shared by every viewer they run (another port, a test): a file is only removed when the process named in it +/// (`task--.token`) is this one (nothing of its own is made yet) or gone fn clear_stale_tokens(dir: &Path) { + let own = std::process::id(); for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { - let p = e.path(); - if p.extension().is_some_and(|x| x == "token") && e.file_type().is_ok_and(|t| t.is_file()) { - let _ = std::fs::remove_file(p); + let name = e.file_name(); + let Some(pid) = name + .to_str() + .and_then(|n| n.strip_prefix("task-")?.strip_suffix(".token")?.split_once('-')) + .and_then(|(pid, _)| pid.parse::().ok()) + else { + continue; + }; + if e.file_type().is_ok_and(|t| t.is_file()) && (pid == own || gone(pid)) { + let _ = std::fs::remove_file(e.path()); } } } +/// No process has this number (one of another user's still counts as there) +fn gone(pid: u32) -> bool { + let Ok(pid) = libc::pid_t::try_from(pid) else { return false }; + pid > 0 + && unsafe { libc::kill(pid, 0) } == -1 + && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) +} + impl Agents { pub fn new(socket: &Path) -> anyhow::Result> { let base = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|p| p.is_absolute()); @@ -648,10 +666,6 @@ mod tests { assert_ne!(a.0, b.0); drop((a, b)); std::fs::remove_dir_all(dir).unwrap(); - // a file left by an earlier viewer is cleared when the next one starts - std::fs::write(agents.tokens.join("task-1-0.token"), "old").unwrap(); - let again = Agents::new(Path::new("/nonexistent/ctl.sock")).unwrap(); - assert!(!again.tokens.join("task-1-0.token").exists()); // kept beside the agent's working directory, not in what it works on; both its own assert!(!agents.tokens.starts_with(&agents.workdir) && !agents.workdir.starts_with(&agents.tokens)); for d in [&agents.tokens, &agents.workdir] { @@ -659,6 +673,24 @@ mod tests { } } + /// What an earlier viewer left (its process is gone, or its number is this process's now) is cleared when the next + /// one starts; what another viewer still running uses is not + #[test] + fn only_tokens_of_viewers_that_are_gone_are_cleared() { + let dir = tempfile::tempdir().unwrap(); + let mut dead = std::process::Command::new("true").spawn().unwrap(); + let dead_pid = dead.id(); + dead.wait().unwrap(); + let name = |pid: u32| format!("task-{pid}-0.token"); + let files = [name(std::process::id()), name(dead_pid), name(1), "notes.token".into(), "task-x-0.token".into()]; + for f in &files { + std::fs::write(dir.path().join(f), "t").unwrap(); + } + clear_stale_tokens(dir.path()); + let left: Vec = files.iter().map(|f| dir.path().join(f).exists()).collect(); + assert_eq!(left, [false, false, true, true, true], "this process's and a gone one's go; a live one's stays"); + } + #[test] fn the_agent_works_in_a_directory_of_its_own() { use std::os::unix::fs::{MetadataExt, PermissionsExt}; diff --git a/apps/iphone-control/src/completions.rs b/apps/iphone-control/src/completions.rs index 9f23ce65..60fcdc46 100644 --- a/apps/iphone-control/src/completions.rs +++ b/apps/iphone-control/src/completions.rs @@ -19,21 +19,27 @@ pub enum Shell { /// 根选项的值可以恰好是 `completions`,所以不能只搜索这个单词。 pub fn requested(args: impl IntoIterator) -> bool { let mut args = args.into_iter(); + match command(&mut args) { + Some(arg) if arg == "help" => args.next().is_some_and(|arg| arg == "completions"), + Some(arg) => arg == "completions", + None => false, + } +} + +/// The first argument after the root options (`--data-dir`, `--socket` and their values), which names the command; +/// `args` is left at the command's own arguments. None when there is none +pub fn command(args: &mut impl Iterator) -> Option { while let Some(arg) = args.next() { if arg == "--data-dir" || arg == "--socket" { - if args.next().is_none() { - return false; - } + args.next()?; } else if arg.as_encoded_bytes().starts_with(b"--data-dir=") || arg.as_encoded_bytes().starts_with(b"--socket=") { continue; - } else if arg == "help" { - return args.next().is_some_and(|arg| arg == "completions"); } else { - return arg == "completions"; + return Some(arg); } } - false + None } pub fn write(shell: Shell, output: &mut dyn Write) -> anyhow::Result<()> { diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs index ebc94b5c..9fdd38dc 100644 --- a/apps/iphone-control/src/main.rs +++ b/apps/iphone-control/src/main.rs @@ -275,13 +275,36 @@ fn main() -> anyhow::Result<()> { // 设置文件先读进环境(命令行上已设的优先),要在启动任何线程之前:语言、代理、通知等对所有命令都生效。 // 控制台给它的 agent 起的 MCP 服务(`mcp --task-token-file`)只连本机:设置文件里给自己的命令连别处用的地址不读, // 读了会和这个参数冲突、服务起不来 - let local_only = std::env::args().any(|a| a == "--task-token-file"); + let local_only = mcp_with_token_file(std::env::args_os().skip(1)); let skip: &[&str] = if local_only { &[ictl_daemon::protocol::env::URL, ictl_daemon::protocol::env::CA] } else { &[] }; envfile::load_into_process(skip); tokio::runtime::Runtime::new()?.block_on(run()) } +/// `mcp --task-token-file FILE` (or `=FILE`): read off the raw arguments, before clap (which caches the language, +/// known only once the settings are loaded). Not taken for an argument of another command that happens to read the +/// same (a prompt of `task run`), and arguments that aren't UTF-8 are read too +fn mcp_with_token_file(args: impl IntoIterator) -> bool { + let mut args = args.into_iter(); + if completions::command(&mut args).is_none_or(|c| c != "mcp") { + return false; + } + while let Some(arg) = args.next() { + if arg == "--task-token-file" || arg.as_encoded_bytes().starts_with(b"--task-token-file=") { + return true; + } + if arg == "--" { + return false; + } + // an option's value isn't an option (`--ca --task-token-file` is a certificate of that name) + if arg == "--url" || arg == "--ca" { + args.next(); + } + } + false +} + /// Commands that ask once, print the result and end; see [`restore_sigpipe`] fn prints_and_exits(command: Option<&Command>) -> bool { matches!( @@ -1614,4 +1637,24 @@ mod tests { assert!(!host_is_loopback(b"GET / HTTP/1.1\r\nHost: localhost.evil.example\r\n\r\n")); assert!(!host_is_loopback(b"GET / HTTP/1.1\r\n\r\n")); } + + /// Only `mcp`'s own option, in either form, after any root options; not a prompt that reads the same, and an + /// argument that isn't UTF-8 doesn't stop it + #[test] + fn the_token_file_option_is_found_only_for_mcp() { + use super::mcp_with_token_file; + use std::ffi::OsString; + use std::os::unix::ffi::OsStringExt; + let found = |args: &[&str]| mcp_with_token_file(args.iter().map(OsString::from)); + assert!(found(&["mcp", "--task-token-file", "/t"])); + assert!(found(&["mcp", "--task-token-file=/t"])); + assert!(found(&["--socket", "/s.sock", "--data-dir=/d", "mcp", "--task-token-file", "/t"])); + assert!(!found(&["mcp"])); + assert!(!found(&["task", "run", "--", "echo", "--task-token-file"]), "another command's argument"); + assert!(!found(&["--socket", "mcp", "status", "--task-token-file"]), "a root option's value isn't the command"); + assert!(!found(&["mcp", "--ca", "--task-token-file"]), "an option's value"); + let odd = + vec![OsString::from("mcp"), OsString::from_vec(vec![0xff, 0xfe]), OsString::from("--task-token-file=/t")]; + assert!(mcp_with_token_file(odd)); + } } diff --git a/apps/iphone-control/src/schedule.rs b/apps/iphone-control/src/schedule.rs index 7a4f2a73..6a4baeb7 100644 --- a/apps/iphone-control/src/schedule.rs +++ b/apps/iphone-control/src/schedule.rs @@ -158,6 +158,10 @@ fn configure_job(socket: &Path, policy: update::Policy) -> Result<()> { if enabled { write_file(&launcher_file, launcher(&service::stable_exe()?, socket, &config)?.as_bytes())?; } + // Unloading the job when turning it off is tried, not required: when the service manager can't be reached (no + // user session: often why setting the job up just failed) the files written here still go, and the error is + // reported after that + let mut unload: Result<()> = Ok(()); if mac { let domain = format!("gui/{}", unsafe { libc::geteuid() }); let id = format!("{domain}/{LABEL}"); @@ -192,7 +196,7 @@ fn configure_job(socket: &Path, policy: update::Policy) -> Result<()> { write_file(&job, &xml)?; run("launchctl", &["bootstrap", &domain, path_str(&job)?])?; } else if loaded { - run("launchctl", &["bootout", &id])?; + unload = run("launchctl", &["bootout", &id]); } } else if enabled { let unit = format!( @@ -205,7 +209,7 @@ fn configure_job(socket: &Path, policy: update::Policy) -> Result<()> { run("systemctl", &["--user", "enable", "--now", TIMER])?; } else if timer.try_exists()? { // Do not stop an already-running replacement. Manual prevents the next one. - run("systemctl", &["--user", "disable", "--now", TIMER])?; + unload = run("systemctl", &["--user", "disable", "--now", TIMER]); } if !enabled { let mut files = vec![job, launcher_file]; @@ -218,10 +222,11 @@ fn configure_job(socket: &Path, policy: update::Policy) -> Result<()> { } } if !mac { - run("systemctl", &["--user", "daemon-reload"])?; + let reload = run("systemctl", &["--user", "daemon-reload"]); + unload = unload.and(reload); } } - Ok(()) + unload } #[cfg(test)] @@ -287,6 +292,74 @@ esac assert!(status.success()); } + /// Run with a service manager that fails: setting the job up fails, and so does unloading it again in the + /// rollback [`set_policy`] does, yet nothing written for the job is left (a development build can't set a policy + /// other than manual, so the two steps are taken here) + #[test] + fn failed_configuration_worker() { + let Some(test_home) = std::env::var_os("ICTL_TEST_SCHEDULE_FAILING_HOME") else { return }; + let home = Path::new(&test_home); + assert_eq!(envfile::home(), home); + let socket = home.join("daemon.sock"); + assert!(configure_job(&socket, update::Policy::Notify).is_err()); + assert!(configure_job(&socket, update::Policy::Manual).is_err(), "unloading failed too, and says so"); + let calls = fs::read_to_string(home.join("manager.log")).unwrap(); + let config = envfile::config_dir(); + let mut left = vec![config.join("update-job.sh")]; + if cfg!(target_os = "macos") { + assert!(calls.contains("bootout"), "{calls}"); + left.push(home.join("Library/LaunchAgents").join(format!("{LABEL}.plist"))); + } else { + assert!(calls.contains("disable"), "{calls}"); + let jobs = config.parent().unwrap().join("systemd/user"); + left.extend([jobs.join(UNIT), jobs.join(TIMER)]); + } + for f in left { + assert!(!f.exists(), "{} left behind ({calls})", f.display()); + } + } + + #[test] + fn a_failed_job_setup_leaves_nothing_behind() { + if ictl_daemon::protocol::running_as_root() { + return; + } + let temp = tempfile::tempdir().unwrap(); + let home = temp.path(); + // the job is written and loaded, then the manager fails: starting it, and unloading it again + let (name, script) = if cfg!(target_os = "macos") { + ( + "launchctl", + r#"#!/bin/sh +echo "$1" >> "$HOME/manager.log" +case "$1" in +print) [ -f "$HOME/loaded" ] || exit 1 + printf '\tpath = %s\n' "$HOME/Library/LaunchAgents/io.github.iphone-control.updates.plist" ;; +bootstrap) : > "$HOME/loaded"; exit 1;; +*) exit 1;; +esac +"#, + ) + } else { + ( + "systemctl", + "#!/bin/sh\necho \"$*\" >> \"$HOME/manager.log\"\ncase \"$2\" in enable|disable) exit 1;; esac\n", + ) + }; + let manager = home.join(name); + fs::write(&manager, script).unwrap(); + fs::set_permissions(&manager, fs::Permissions::from_mode(0o700)).unwrap(); + let status = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "schedule::tests::failed_configuration_worker"]) + .env("HOME", home) + .env("ICTL_TEST_SCHEDULE_FAILING_HOME", home) + .env("XDG_CONFIG_HOME", home.join("config")) + .env("PATH", home) + .status() + .unwrap(); + assert!(status.success()); + } + #[test] fn launcher_can_recover_without_starting_a_broken_installed_binary() { let temp = tempfile::tempdir().unwrap(); diff --git a/apps/iphone-control/src/video/mod.rs b/apps/iphone-control/src/video/mod.rs index 51fe1ed3..d0685ee4 100644 --- a/apps/iphone-control/src/video/mod.rs +++ b/apps/iphone-control/src/video/mod.rs @@ -390,7 +390,7 @@ async fn write_mjpeg( const NEXT: &[u8] = b"\r\n--ictl\r\nContent-Type: image/jpeg\r\n\r\n"; let head = b"HTTP/1.1 200 OK\r\nContent-Type: multipart/x-mixed-replace; boundary=ictl\r\nCache-Control: no-store\r\n\ - X-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\n"; + X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nConnection: close\r\n\r\n"; // the first part's boundary and headers, without the line break that ends a part let header = [head.as_slice(), &NEXT[2..]].concat(); if !write_with_progress(&mut client, &header, idle).await { diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs index 6d623da8..3296a23b 100644 --- a/apps/iphone-control/src/viewer.rs +++ b/apps/iphone-control/src/viewer.rs @@ -273,6 +273,7 @@ pub async fn run( ) ); } + let page = page_in(ictl_l10n::lang()); let ctx = Arc::new(Ctx { access, socket: socket.to_path_buf(), @@ -284,8 +285,8 @@ pub async fn run( checking: Arc::default(), check_error: Arc::default(), names: tokio::sync::Mutex::default(), - page_csp: csp_for(&page_in(ictl_l10n::lang())), - page: page_in(ictl_l10n::lang()), + page_csp: csp_for(&page), + page, device_video_allowed, video, acks: Arc::default(), @@ -1252,7 +1253,7 @@ async fn reply_with(client: &mut Conn, status: u16, kind: &str, body: &[u8], ext const WRITE_TIMEOUT: Duration = if cfg!(test) { Duration::from_millis(300) } else { Duration::from_secs(30) }; /// Writes and flushes `bytes` within [`WRITE_TIMEOUT`] -async fn write_timed(w: &mut W, bytes: &[u8]) -> anyhow::Result<()> { +pub(crate) async fn write_timed(w: &mut W, bytes: &[u8]) -> anyhow::Result<()> { tokio::time::timeout(WRITE_TIMEOUT, async { w.write_all(bytes).await?; w.flush().await @@ -1266,8 +1267,10 @@ async fn write_timed(w: &mut W, bytes: &[u8]) /// it was read: 401, 403, 413) sends a reset, and the client may then never see the answer. So: end our side, then /// read what the client still sends until it closes too, for a second and 1 MB at most async fn linger(client: &mut Conn) { - let _ = client.shutdown().await; let deadline = tokio::time::Instant::now() + Duration::from_secs(1); + // within the same second: over TLS ending our side writes (close_notify), which a client that stopped reading + // with its buffers full would hold up for good + let _ = tokio::time::timeout_at(deadline, client.shutdown()).await; let (mut buf, mut left) = ([0u8; 8192], 1usize << 20); while left > 0 { match tokio::time::timeout_at(deadline, client.read(&mut buf)).await { @@ -1422,9 +1425,7 @@ async fn redirect(client: &mut Conn, to: &str) -> anyhow::Result<()> { "HTTP/1.1 307 Temporary Redirect\r\nLocation: {to}\r\nContent-Length: 0\r\nCache-Control: no-store\r\n\ Referrer-Policy: no-referrer\r\nConnection: close\r\n\r\n" ); - client.write_all(head.as_bytes()).await?; - client.flush().await?; - Ok(()) + write_timed(client, head.as_bytes()).await } struct Head { @@ -2144,8 +2145,6 @@ mod tests { assert_eq!(at(b"GET / HTTP/1.1\r\n\r\n"), None); } - /// The redirect's `Location` is built from the request target: only a path is a target, so it can't send a - /// browser to another host (`@evil.example/` would make `https://host:port@evil.example/`) nor add a header line /// An answer to a client that reads nothing gives up after [`WRITE_TIMEOUT`] instead of holding the connection #[tokio::test] async fn a_client_that_reads_nothing_is_let_go() { @@ -2181,6 +2180,8 @@ mod tests { assert!(csp_for("

no script

").contains("script-src 'none'")); } + /// The redirect's `Location` is built from the request target: only a path is a target, so it can't send a + /// browser to another host (`@evil.example/` would make `https://host:port@evil.example/`) nor add a header line #[test] fn only_a_plain_request_head_is_taken() { let ok = |s: &str| Head::parse(s.as_bytes()).is_some(); diff --git a/apps/iphone-control/src/viewer/auth.rs b/apps/iphone-control/src/viewer/auth.rs index ff48fc42..70cc3db2 100644 --- a/apps/iphone-control/src/viewer/auth.rs +++ b/apps/iphone-control/src/viewer/auth.rs @@ -89,8 +89,12 @@ fn locked(data_dir: &Path, f: impl FnOnce() -> anyhow::Result) -> anyhow:: .mode(0o600) .custom_flags(libc::O_NOFOLLOW) .open(tokens_file(data_dir).with_extension("lock"))?; - if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX) } != 0 { - return Err(io::Error::last_os_error().into()); + while unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX) } != 0 { + let e = io::Error::last_os_error(); + // a signal while waiting: wait again + if e.kind() != io::ErrorKind::Interrupted { + return Err(e.into()); + } } f() } diff --git a/apps/iphone-control/src/viewer/lan.rs b/apps/iphone-control/src/viewer/lan.rs index 9197d65c..483d0c2f 100644 --- a/apps/iphone-control/src/viewer/lan.rs +++ b/apps/iphone-control/src/viewer/lan.rs @@ -100,7 +100,7 @@ impl Access { }; let rest = rest.to_ascii_lowercase(); // a browser leaves the scheme's default port out - let default = if origin.starts_with("https://") { 443 } else { 80 }; + let default = if https { 443 } else { 80 }; // `[::1]` has colons but no port: what follows the last one isn't a number there let (name, p) = match rest.rsplit_once(':').and_then(|(n, p)| Some((n, p.parse::().ok()?))) { Some(np) => np, diff --git a/apps/iphone-control/src/viewer/mcp.rs b/apps/iphone-control/src/viewer/mcp.rs index fdb535a5..bbe99b09 100644 --- a/apps/iphone-control/src/viewer/mcp.rs +++ b/apps/iphone-control/src/viewer/mcp.rs @@ -13,11 +13,10 @@ //! A task's agent sends the task's token in `Iphone-Control-Task-Token` ([`ictl_daemon::protocol::TASK_TOKEN_HEADER`]), //! as `IPHONE_CONTROL_TASK_TOKEN` does on stdio. +use super::tls::Conn; +use super::write_timed; use bytes::Bytes; use http_body_util::{BodyExt, Full}; -use tokio::io::AsyncWriteExt; - -use super::tls::Conn; /// A request body bigger than this is refused (a tool call is a few KB) pub const MAX_BODY: usize = 1024 * 1024; @@ -26,14 +25,14 @@ pub const MAX_BODY: usize = 1024 * 1024; /// or the client goes away pub async fn serve(svc: &ictl_mcp::HttpService, client: &mut Conn, head: &[u8], body: Vec) -> anyhow::Result<()> { let Some(req) = request(head, body) else { - client.write_all(b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await?; - client.flush().await?; - return Ok(()); + let bad = b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nReferrer-Policy: no-referrer\r\nConnection: close\r\n\r\n"; + return write_timed(client, bad).await; }; let (parts, mut body) = svc.handle(req).await.into_parts(); let chunked = sent_chunked(&parts); - client.write_all(response_head(&parts, chunked).as_bytes()).await?; - client.flush().await?; + // each write within the viewer's time limit, as its own answers: a client that stops reading doesn't hold its + // connection's place for good. Waiting for the next event of a stream has none + write_timed(client, response_head(&parts, chunked).as_bytes()).await?; while let Some(frame) = body.frame().await { let frame = match frame { Ok(f) => f, @@ -42,20 +41,19 @@ pub async fn serve(svc: &ictl_mcp::HttpService, client: &mut Conn, head: &[u8], if let Some(data) = frame.data_ref() && !data.is_empty() { + // each event goes out now, flushed (TLS holds the last record back otherwise) if chunked { - client.write_all(format!("{:x}\r\n", data.len()).as_bytes()).await?; - client.write_all(data).await?; - client.write_all(b"\r\n").await?; + let mut piece = format!("{:x}\r\n", data.len()).into_bytes(); + piece.extend_from_slice(data); + piece.extend_from_slice(b"\r\n"); + write_timed(client, &piece).await?; } else { - client.write_all(data).await?; + write_timed(client, data).await?; } - // each event goes out now (TLS holds the last record back otherwise) - client.flush().await?; } } if chunked { - client.write_all(b"0\r\n\r\n").await?; - client.flush().await?; + write_timed(client, b"0\r\n\r\n").await?; } Ok(()) } @@ -147,7 +145,7 @@ fn response_head(parts: &http::response::Parts, chunked: bool) -> String { let mut out = format!("HTTP/1.1 {} {}\r\n", parts.status.as_u16(), parts.status.canonical_reason().unwrap_or("Unknown")); for (k, v) in &parts.headers { - if k == http::header::CONNECTION || k == http::header::TRANSFER_ENCODING { + if k == http::header::CONNECTION || k == http::header::TRANSFER_ENCODING || k == http::header::REFERRER_POLICY { continue; } out.push_str(&format!("{}: {}\r\n", k.as_str(), String::from_utf8_lossy(v.as_bytes()))); @@ -155,14 +153,15 @@ fn response_head(parts: &http::response::Parts, chunked: bool) -> String { if chunked { out.push_str("Transfer-Encoding: chunked\r\n"); } - out.push_str("Connection: close\r\n\r\n"); + // as every answer of the viewer's + out.push_str("Referrer-Policy: no-referrer\r\nConnection: close\r\n\r\n"); out } #[cfg(test)] mod tests { use super::*; - use tokio::io::AsyncReadExt; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; /// One HTTP request through [`serve`], as a client sees it: (head, body) async fn exchange(svc: &ictl_mcp::HttpService, raw: String) -> (String, String) { @@ -231,6 +230,7 @@ mod tests { let done = r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#; let (head, _) = exchange(&svc, post(done, &sid)).await; assert!(head.starts_with("HTTP/1.1 202"), "{head}"); + assert_eq!(header(&head, "referrer-policy"), Some("no-referrer"), "as every answer of the viewer's"); let list = r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#; let (_, body) = exchange(&svc, post(list, &sid)).await; @@ -259,6 +259,7 @@ mod tests { http::Response::builder().header("content-type", "text/event-stream").body(()).unwrap().into_parts(); let head = response_head(&stream, true); assert!(head.contains("Transfer-Encoding: chunked\r\n") && head.ends_with("Connection: close\r\n\r\n")); + assert_eq!(head.matches("Referrer-Policy: no-referrer\r\n").count(), 1); let (json, _) = http::Response::builder().header("content-length", "2").body(()).unwrap().into_parts(); let head = response_head(&json, false); assert!(head.contains("content-length: 2\r\n") && !head.contains("Transfer-Encoding")); diff --git a/apps/iphone-control/src/viewer/tls.rs b/apps/iphone-control/src/viewer/tls.rs index c970ac9b..6086ed06 100644 --- a/apps/iphone-control/src/viewer/tls.rs +++ b/apps/iphone-control/src/viewer/tls.rs @@ -206,24 +206,25 @@ fn ensure_made(dir: &Path, names: &[String], now: u64) -> anyhow::Result<(Vec io::Result<()> { use std::io::Write; - use std::os::unix::fs::OpenOptionsExt; + use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - let tmp = file.with_file_name(format!(".{name}.{}.tmp", std::process::id())); - let r = std::fs::OpenOptions::new() - .write(true) - .create(true) - .truncate(true) - .mode(mode) - .open(&tmp) - .and_then(|mut f| { - f.write_all(data)?; - f.sync_all() - }) - .and_then(|()| std::fs::rename(&tmp, file)); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = file.with_file_name(format!(".{name}.{}-{n}.tmp", std::process::id())); + let f = std::fs::OpenOptions::new().write(true).create_new(true).mode(mode).open(&tmp)?; + let r = (|| { + let mut f = f; + // the umask may have taken bits off + f.set_permissions(std::fs::Permissions::from_mode(mode))?; + f.write_all(data)?; + f.sync_all()?; + std::fs::rename(&tmp, file) + })(); if r.is_err() { let _ = std::fs::remove_file(&tmp); } @@ -297,6 +298,21 @@ mod tests { n.iter().map(|s| (*s).to_owned()).collect() } + /// A key written over an old one is all new and only this user's, whatever the umask, and nothing is left beside it + #[test] + fn a_key_replaces_the_old_one_whole_and_private() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let key = dir.path().join("key.pem"); + std::fs::write(&key, "old").unwrap(); + std::fs::set_permissions(&key, std::fs::Permissions::from_mode(0o644)).unwrap(); + write_atomic(&key, b"new", 0o600).unwrap(); + assert_eq!(std::fs::read_to_string(&key).unwrap(), "new"); + assert_eq!(std::fs::metadata(&key).unwrap().permissions().mode() & 0o777, 0o600); + let names: Vec<_> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(names, ["key.pem"]); + } + #[test] fn the_made_certificate_is_kept_and_grows_with_new_names() { let tmp = tempfile::tempdir().unwrap(); diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index c51dc302..c4a0a871 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -219,11 +219,11 @@ | 213 | 原生 HEVC 转 H.264:ffmpeg 崩了导致输入通道关闭(`try_send` 的 `Closed`)被当成「跟不上」,不计失败、无限重启;连续失败也不换编码器 | `Closed` 记一次失败;连续 3 次没出帧就像 MJPEG 一样 `give_up` 换下一个编码器(只有 ffmpeg 替内置编码器跑时不换,那不是它的问题) | 代码审查(单测需要真编码器;真机上没有能让 ffmpeg 崩的条件) | | 214 | `task run --url`:Ctrl-C 时 `stop()` 没有超时,控制台不应答就一直等;SSE 读取没有静默超时,缓冲没有上限 | `stop()` 限时 10 秒;60 秒什么都没收到(控制台每 15 秒发 ping)就当断开;一个事件超过 1 MB 还没结束就放弃 | 单测 `an_event_without_end_ends_the_stream` | | 215 | 守护进程只靠「连不上 socket」判断没有别的实例:两个同时启动都连不上,先后 bind,后一个把前一个的 socket 抢走;bind 和 chmod 0600 之间 socket 是 umask 的权限 | socket 旁边的 `ctl.lock` 加 `flock`,守护进程一直拿着(等前一个最多 15 秒,有人在服务就立即退出;`flock` 报的不是「被占用」或「被打断」就直接报错,不白等);bind 时 umask 077;自己新建的 socket 目录是 0700 | 单测 `only_one_daemon_holds_a_socket` + 真机 | -| 216 | 控制台和登录页没有 CSP、没有 `Referrer-Policy`;回答和事件流的写入没有超时,不读数据的客户端会一直占着一个连接名额 | 页面带 CSP:只放行它自己内联脚本的 sha256,`default-src 'none'`,图片、请求、媒体只到本服务,禁止被嵌入;所有回答带 `Referrer-Policy: no-referrer`;每次写回答或事件限 30 秒 | 单测 `pages_allow_only_their_own_scripts`、`a_client_that_reads_nothing_is_let_go` + 真机(iPhone Safari 打开控制台,画面、操作、任务都正常,控制台没有 CSP 报错) | +| 216 | 控制台和登录页没有 CSP、没有 `Referrer-Policy`;回答和事件流的写入没有超时,不读数据的客户端会一直占着一个连接名额 | 页面带 CSP:只放行它自己内联脚本的 sha256,`default-src 'none'`,图片、请求、媒体只到本服务,禁止被嵌入;所有回答(含 `/mcp`、重定向、MJPEG)带 `Referrer-Policy: no-referrer`;每次写回答或事件(含 `/mcp` 的 SSE 和重定向)限 30 秒;回答后的 `shutdown`(TLS 要写 close_notify)也限在逗留的 1 秒内 | 单测 `pages_allow_only_their_own_scripts`、`a_client_that_reads_nothing_is_let_go`、`an_mcp_session_over_http`、`streams_are_chunked` + 无头 Chromium 打开部署的控制台和登录页(中英文),控制台没有 CSP 报错(手机连不到这台机器的局域网地址,Safari 测不了) | | 217 | `origin_allowed` 不看 scheme:开着 HTTPS 时 `http://<局域网名字>` 的 Origin 也收(这种页面本服务根本不提供),没开 HTTPS 时 `https://` 也收 | 开着 HTTPS:`https://` 都行,`http://` 只限本机名字;没开:只收 `http://` | 单测 `on_the_lan_its_own_names_but_no_others` | -| 218 | 证书、私钥、`names.json` 直接写:写到一半被停掉,新私钥配旧证书,`names.json` 还在,于是照常复用,启动时报「证书和私钥对不上」,以后都起不来 | 先删 `names.json`,再依次原子写(临时文件 + fsync + rename)私钥(一开始就是 0600)、证书,最后写 `names.json`;中途停掉,下次就重新生成 | 单测 `a_pair_written_halfway_is_made_again` | +| 218 | 证书、私钥、`names.json` 直接写:写到一半被停掉,新私钥配旧证书,`names.json` 还在,于是照常复用,启动时报「证书和私钥对不上」,以后都起不来 | 先删 `names.json`,再依次原子写(临时文件 + fsync + rename)私钥(一开始就是 0600)、证书,最后写 `names.json`;中途停掉,下次就重新生成 | 单测 `a_pair_written_halfway_is_made_again`、`a_key_replaces_the_old_one_whole_and_private`(临时文件每次新建、显式设权限) | | 219 | 令牌文件只按修改时间判断有没有变:秒级精度的文件系统上,同一秒内删掉的令牌照样能用;`viewer token add/renew/remove` 读改写不加锁,同时运行会丢改动 | 比较 (修改时间, 长度, inode)(每次保存都是新文件 rename,inode 必变);读改写放在 `viewer-tokens.lock` 的 `flock` 里 | 单测 `a_removed_token_is_noticed_within_the_same_second`、`tokens_added_at_once_are_all_kept` | | 220 | `env` 设置文件里同一个键写两次:服务(systemd、launchd 的 shell)取最后一个,命令行程序取第一个;保存用固定的 `env.tmp`,两个命令同时保存会写进同一个临时文件 | `load_into_process` 取最后一个(最后为空就不设);临时文件名带进程号和序号,`create_new` | 单测 `the_last_value_of_a_key_wins` | -| 221 | 装服务:路径里的空格让 systemd 的 `ExecStart` 失败,`$`、反引号、`%` 会被 systemd 或 launchd 的 shell 当成自己的语法;升级暂停 viewer 服务后用 `enable --now` 恢复,用户关掉的开机自启又被打开;自动更新任务配置失败时写了一半的 unit、launcher 留着 | 允许空格(`ExecStart` 加引号),拒绝 `$`、反引号、`%`、引号、反斜杠、控制字符;恢复用 `start_managed`(只 start);配置失败后按 Manual 再走一遍,删掉自己的那些文件 | 单测 `service_program_paths`、原有的 `the_viewer_service_runs_the_viewer_with_this_path` | -| 222 | 设置文件里有 `IPHONE_CONTROL_URL` 时,控制台给 agent 起的 `mcp --task-token-file` 读进这个变量,和参数冲突,MCP 服务起不来;`tokens/` 里上次留下的令牌文件可能和新文件撞名 | 命令行带 `--task-token-file` 时,载入设置文件跳过 `IPHONE_CONTROL_URL`、`IPHONE_CONTROL_CA`;控制台启动时清掉 `tokens/` 里残留的令牌文件 | 单测 `a_prompt_is_never_an_option_and_the_token_never_on_the_command_line`(残留清理)+ 真机(设置文件写了 URL,控制台的任务照常完成) | +| 221 | 装服务:路径里的空格让 systemd 的 `ExecStart` 失败,`$`、反引号、`%` 会被 systemd 或 launchd 的 shell 当成自己的语法;升级暂停 viewer 服务后用 `enable --now` 恢复,用户关掉的开机自启又被打开;自动更新任务配置失败时写了一半的 unit、launcher 留着 | 允许空格(`ExecStart` 加引号),拒绝 `$`、反引号、`%`、引号、反斜杠、控制字符;恢复用 `start_managed`(只 start);配置失败后按 Manual 再走一遍,删掉自己的那些文件:卸载任务(`systemctl disable --now`、`launchctl bootout`)失败也照样删,最后再报错 | 单测 `service_program_paths`、`a_failed_job_setup_leaves_nothing_behind`(假的 systemctl/launchctl 启用和卸载都失败;改回旧代码会失败)、原有的 `the_viewer_service_runs_the_viewer_with_this_path` | +| 222 | 设置文件里有 `IPHONE_CONTROL_URL` 时,控制台给 agent 起的 `mcp --task-token-file` 读进这个变量,和参数冲突,MCP 服务起不来;`tokens/` 里上次留下的令牌文件可能和新文件撞名 | `mcp` 子命令带 `--task-token-file`(或 `--task-token-file=`)时,载入设置文件跳过 `IPHONE_CONTROL_URL`、`IPHONE_CONTROL_CA`(从原始参数里认,跳过根选项,不要求 UTF-8,别的命令里的同名文字不算);控制台启动时清掉 `tokens/` 里残留的令牌文件,只清进程号是自己或已不存在的(同一用户别的 viewer 正在用的留着) | 单测 `the_token_file_option_is_found_only_for_mcp`、`only_tokens_of_viewers_that_are_gone_are_cleared` + 真机(设置文件写了 URL,控制台的任务照常完成) | | 223 | 只读登录:画面上按下照样发 `/api/touch`(服务端拒绝,每次弹错误),悬停圆点照常显示,滚轮也会去滑手机 | 只读时手指、预热、滚轮都不发,提示「只读登录」(3 秒内不重复),不显示悬停圆点 | 页面测试 `a read-only page sends no finger and says so once in a while` |