// Websites: read a public page, open a link in the person's browser, and read the tab they have // open there (where they're already logged in: Threads, Instagram, Gmail…). The original reaches // sites through its own browser; its old "copy logins from Chrome" import is retired (SAND-E0801.. // E0812 all say "removed"), so nothing is copied here either. AnyBot's own browser (botbrowser.rs) // is used when a Chrome-family browser is installed; AppleScript on the person's browser otherwise. use serde_json::{json, Value}; use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; pub const NAMES: [&str; 4] = ["web_fetch", "browser_open", "browser_read", "browser_profiles"]; /// Longest page text handed to the model (estimated). pub const MAX_PAGE_CHARS: usize = 20_000; /// Largest download read for web_fetch (estimated). const MAX_FETCH_BYTES: u64 = 3_000_000; /// AppleScript can wait on macOS's "allow AnyBot to control Chrome?" prompt; give the person time. const SCRIPT_TIMEOUT_SECS: u64 = 90; /// Time for a page to load after opening it (estimated). const OPEN_SETTLE_SECS: u64 = 4; /// Browsers in the order they're tried (Chromium-style ones share the same AppleScript). const BROWSERS: [(&str, bool); 6] = [("Google Chrome", true), ("Arc", true), ("Microsoft Edge", true), ("Brave Browser", true), ("Chromium", true), ("Safari", false)]; pub fn is_web_tool(name: &str) -> bool { NAMES.contains(&name) || crate::browser::is_tool(name) } pub fn label(name: &str) -> &'static str { match name { "web_fetch" => "讀取網頁", "browser_open" => "在瀏覽器打開", "browser_read" => "讀取瀏覽器分頁", "browser_profiles" => "瀏覽器設定檔", n if crate::browser::is_tool(n) => crate::browser::label(n), _ => "網頁", } } /// Does this call use the person's own browser ("你的瀏覽器", or the fallback when no /// Chrome-family browser is installed)? pub fn uses_person_browser(args: &str) -> bool { // The box has one browser, the bot's own; the person's browser is never in there. if crate::botbrowser::using_box() { return false; } if !crate::botbrowser::available() { return true; } let v: Value = serde_json::from_str(if args.trim().is_empty() { "{}" } else { args }).unwrap_or(Value::Null); crate::botbrowser::resolve(Some(arg(&v, "profile").as_str())).map(|p| p == crate::botbrowser::PERSON_PROFILE).unwrap_or(false) } /// browser_open / browser_read on the person's own browser run on this Mac. pub fn uses_this_computer(name: &str, args: &str) -> bool { // AnyBot's own browser is the bot's, like the reference assistant's; only the person's own browser counts // as working on their computer. Profiles are the bot's browser's, never the person's. (name == "browser_open" || name == "browser_read") && uses_person_browser(args) } /// Reading a tab asks first only when it's the person's own browser. pub fn read_needs_permission(args: &str) -> bool { uses_person_browser(args) } /// The browser tools. `browsers`: the computers with an AnyBot browser this bot can use (its own, /// this one, the account's other computers), by name; each has its own logins. pub fn specs_for(browsers: &[String], default: &str) -> Vec { let mut v = specs_inner(!browsers.is_empty()); if !browsers.is_empty() { let desc = format!("Which computer's AnyBot browser to use, by the computer's name. Each computer's browser has its own logins (a site logged in on one isn't on another). Default: {default}. Use another only when the person names it."); for t in v.iter_mut().filter(|t| t["name"].as_str().map(|n| n == "browser" || n.starts_with("browser_")).unwrap_or(false)) { t["parameters"]["properties"]["computer"] = json!({"type": "string", "enum": browsers, "description": desc}); } } v } fn specs_inner(browser: bool) -> Vec { let (names, current) = if crate::botbrowser::available() { (crate::botbrowser::choices().join(", "), crate::botbrowser::current()) } else { (crate::botbrowser::DEFAULT_PROFILE.to_string(), crate::botbrowser::DEFAULT_PROFILE.to_string()) }; let profile = json!({"type": "string", "description": format!("Which AnyBot browser profile (設定檔) to use; each has its own logins (e.g. a different account). Profiles now: {names}. Names ending in {} are the person's own Firefox profiles (their logins; AnyBot opens them in a window it can operate — if the person has that profile open the everyday way, ask them to close that window first). \"{}\" is the person's own everyday browser (read through accessibility), in whichever Chrome profile they have open there. Leave out to use the current one ({current}).", crate::botbrowser::FIREFOX_MARK, crate::botbrowser::PERSON_PROFILE)}); let _ = browser; let v = vec![ json!({"name": "web_fetch", "description": "Download a public web page and return its text (no login). For pages that need the person's login, or that only show text after scripts run, use browser_open.", "parameters": {"type": "object", "properties": {"url": {"type": "string"}}, "required": ["url"]}}), crate::browser::tool(&profile), ]; v } fn arg(v: &Value, k: &str) -> String { v.get(k).and_then(Value::as_str).unwrap_or("").trim().to_string() } pub fn describe(name: &str, args: &str) -> String { let v: Value = serde_json::from_str(args).unwrap_or(Value::Null); match name { "browser_read" => match arg(&v, "profile") { p if p.is_empty() => "目前的分頁".into(), p => format!("目前的分頁(設定檔「{p}」)"), }, "browser_profiles" => match (arg(&v, "action").as_str(), arg(&v, "name")) { ("add" | "create", n) => format!("新增「{n}」"), ("use" | "switch", n) => format!("切換到「{n}」"), // The model's call: a name alone switches to it (adding it when it is new). ("", n) if !n.is_empty() => format!("切換到「{n}」"), _ => "列出設定檔".into(), }, n if crate::browser::is_tool(n) => crate::browser::describe(n, args), _ => arg(&v, "url"), } } /// Run a web tool, with a picture when it took one (browser_screenshot). pub fn run_full(name: &str, args: &str, cancel: &AtomicBool) -> (String, bool, Option) { if crate::browser::is_tool(name) { if !crate::botbrowser::available() { return ("這些瀏覽器工具需要 AnyBot 自己的瀏覽器(Chrome、Brave、Edge、Chromium 或 Firefox)。".into(), false, None); } if uses_person_browser(args) { return ("點擊、輸入和其他操作只能在 AnyBot 自己的瀏覽器裡做。請用 browser_open 在 AnyBot 瀏覽器打開網頁(第一次要請使用者在那個視窗登入)。".into(), false, None); } let v: Value = serde_json::from_str(if args.trim().is_empty() { "{}" } else { args }).unwrap_or(Value::Null); return crate::botbrowser::as_job(&arg(&v, "_job"), || { // A click or a key can open a tab (a link to a new window): it is this job's. let watch = matches!(name, "browser_click" | "browser_press"); let profile = Some(arg(&v, "profile")).filter(|p| !p.is_empty()); let before = if watch { crate::botbrowser::tab_ids(profile.as_deref()) } else { vec![] }; let r = match crate::browser::run(name, &v) { Ok((t, img)) => (t, true, img), Err(e) => (e, false, None), }; if watch { crate::botbrowser::adopt_new(profile.as_deref(), &before); } r }); } // browser_open / browser_read on the bot's browser: the job's own tabs too. let v: Value = serde_json::from_str(if args.trim().is_empty() { "{}" } else { args }).unwrap_or(Value::Null); let (t, ok) = crate::botbrowser::as_job(&arg(&v, "_job"), || run(name, args, cancel)); (t, ok, None) } /// Run a web tool. Returns (text, ok). pub fn run(name: &str, args: &str, cancel: &AtomicBool) -> (String, bool) { let v: Value = serde_json::from_str(if args.trim().is_empty() { "{}" } else { args }).unwrap_or(Value::Null); let r = match name { "web_fetch" => fetch(&arg(&v, "url")), "browser_open" if crate::botbrowser::available() && uses_person_browser(args) => browser_open(&arg(&v, "url"), cancel), "browser_read" if crate::botbrowser::available() && uses_person_browser(args) => browser_read(v.get("max_chars").and_then(Value::as_u64).map(|n| n as usize).unwrap_or(MAX_PAGE_CHARS).min(MAX_PAGE_CHARS * 2), cancel), "browser_open" if crate::botbrowser::available() => normalize_url(&arg(&v, "url")).and_then(|u| crate::botbrowser::open(&u, Some(arg(&v, "profile").as_str()), v["_this_step_only"] == true)), "browser_read" if crate::botbrowser::available() => crate::botbrowser::read(v.get("max_chars").and_then(Value::as_u64).map(|n| n as usize).unwrap_or(MAX_PAGE_CHARS).min(MAX_PAGE_CHARS * 2), Some(arg(&v, "profile").as_str())), "browser_profiles" if crate::botbrowser::available() => crate::botbrowser::profiles_tool(&arg(&v, "action"), &arg(&v, "name")), "browser_profiles" => Err("設定檔要 AnyBot 自己的瀏覽器(需要 Chrome、Brave、Edge、Chromium 或 Firefox)。現在用的是你自己的 Safari。".into()), "browser_open" => browser_open(&arg(&v, "url"), cancel), "browser_read" => browser_read(v.get("max_chars").and_then(Value::as_u64).map(|n| n as usize).unwrap_or(MAX_PAGE_CHARS).min(MAX_PAGE_CHARS * 2), cancel), other => Err(format!("沒有「{other}」這個工具")), }; match r { Ok(s) => (s, true), Err(e) => (e, false), } } /// A web address as a browser reads it (WHATWG URL, the `url` crate): `\` is `/`, `user@` is not /// the host, the host lowercased and in punycode, an IP in any spelling made plain. Everything that /// checks an address (the private-network card, the rules, web_fetch's own check) reads it this /// way, and the browser is handed the address as parsed — what is checked is what opens. (Taking /// the host apart by hand let `http://127.0.0.1\@a.com/` past the private-network card.) pub fn parse_url(u: &str) -> Result { let u = u.trim(); if u.is_empty() { return Err("請給網址".into()); } let bad = || format!("「{u}」看起來不是網址"); let has_scheme = ["http://", "https://"].iter().any(|p| u.get(..p.len()).is_some_and(|h| h.eq_ignore_ascii_case(p))); let full = if has_scheme { u.to_string() } else { format!("https://{u}") }; if full.contains(char::is_whitespace) { return Err(bad()); } let parsed = url::Url::parse(&full).map_err(|_| bad())?; match parsed.host() { Some(url::Host::Domain(d)) if d.trim_end_matches('.').contains('.') || d.trim_end_matches('.') == "localhost" => Ok(parsed), Some(url::Host::Ipv4(_) | url::Host::Ipv6(_)) => Ok(parsed), _ => Err(bad()), } } /// [`parse_url`], written out (the form handed to the browser). pub fn normalize_url(u: &str) -> Result { parse_url(u).map(|p| p.to_string()) } /// The host a browser would open for this address: lowercased, punycode, no trailing dot, an IP /// plain (an IPv6 one without brackets). None when it isn't a web address. pub fn host_of(u: &str) -> Option { parse_url(u).ok().and_then(|p| host_text(&p)) } fn host_text(p: &url::Url) -> Option { Some(match p.host()? { url::Host::Domain(d) => d.trim_end_matches('.').to_ascii_lowercase(), url::Host::Ipv4(a) => a.to_string(), url::Host::Ipv6(a) => a.to_string(), }) } // ---------- web_fetch ---------- /// An address web_fetch (and the box's egress proxy) may reach: out on the internet. Not this /// computer, not the network it sits on (the router, the NAS, another service's port), not a /// cloud machine's metadata. pub fn public_addr(ip: std::net::IpAddr) -> bool { match ip { std::net::IpAddr::V4(a) => { let o = a.octets(); // (100.64/10: carrier NAT and Tailscale; 198.18/15: benchmark / OrbStack VM subnets; 192.0.0/24 and 240/4: reserved.) !(a.is_loopback() || a.is_private() || a.is_link_local() || a.is_unspecified() || a.is_broadcast() || a.is_multicast() || o[0] == 0 || (o[0] == 100 && o[1] & 0xc0 == 64) || (o[0] == 192 && o[1] == 0 && o[2] == 0) || (o[0] == 198 && (o[1] == 18 || o[1] == 19)) || o[0] >= 240) } std::net::IpAddr::V6(a) => match a.to_ipv4_mapped() { Some(v4) => public_addr(std::net::IpAddr::V4(v4)), // (fc00::/7 is private, fe80::/10 link-local, ::/96 IPv4-compatible, 2002::/16 6to4, 2001::/32 Teredo, 64:ff9b::/96 NAT64.) None => { let s = a.segments(); let ipv4_compat = s[..6] == [0, 0, 0, 0, 0, 0]; let six_to_four = s[0] == 0x2002; let teredo = s[0] == 0x2001 && s[1] == 0; let nat64 = s[0] == 0x64 && s[1] == 0xff9b; !(a.is_loopback() || a.is_unspecified() || a.is_multicast() || ipv4_compat || six_to_four || teredo || nat64 || s[0] & 0xfe00 == 0xfc00 || s[0] & 0xffc0 == 0xfe80) } }, } } /// True when `url` is an always-forbidden cloud metadata or Docker daemon API endpoint. pub fn is_forbidden_browser_url(url: &str) -> bool { let Some((host, port)) = host_port(url) else { return false }; let h = host.trim_end_matches('.').to_ascii_lowercase(); if h == "docker-socket-proxy" || port == 2375 || port == 2376 { return true; } if let Ok(ip) = h.parse::() { return match ip { std::net::IpAddr::V4(v) => v.is_link_local(), std::net::IpAddr::V6(v) => v.is_unicast_link_local() || v.to_ipv4_mapped().is_some_and(|v4| v4.is_link_local()), }; } false } /// True when `url` points to localhost or a private/internal network (so opening it in a browser /// should ask the person first instead of running silently on prompt injection). pub fn is_private_browser_url(url: &str) -> bool { let Ok(full) = normalize_url(url) else { return false }; public_only(&full).is_err() } /// The host and port of a web address as a browser reads it ([`parse_url`]; an IPv6 host without /// brackets). fn host_port(url: &str) -> Option<(String, u16)> { let p = parse_url(url).ok()?; Some((host_text(&p)?, p.port_or_known_default()?)) } /// web_fetch runs with nothing asked, so it reads the public web only: a page (or a redirect) /// that names this computer or the network around it is refused. It used to reach them all. fn public_only(url: &str) -> Result<(), String> { use std::net::ToSocketAddrs; let (host, port) = host_port(url).ok_or_else(|| format!("「{url}」看起來不是網址"))?; let h = host.trim_end_matches('.').to_lowercase(); let addrs: Vec = match h.parse::() { Ok(ip) => vec![ip], // (A name that can't be looked up here is left to the request, which fails the same // way, or to the person's proxy, which looks it up itself.) Err(_) => (h.as_str(), port).to_socket_addrs().map(|a| a.map(|s| s.ip()).collect()).unwrap_or_default(), }; if h == "localhost" || h.ends_with(".localhost") || h.ends_with(".local") || h.ends_with(".internal") || (!h.contains('.') && !h.contains(':')) || addrs.iter().any(|a| !public_addr(*a)) { return Err(format!("web_fetch 只讀公開的網頁,「{host}」是這台電腦或內部網路的位址。要看本機或區網上的服務,用 shell(例如 curl)或 browser_open。")); } Ok(()) } /// Looks names up like the default resolver, and hands back only public addresses: the check /// that holds at the moment of connecting (a name can answer differently the second time). #[derive(Debug)] struct PublicResolver(ureq::unversioned::resolver::DefaultResolver); impl ureq::unversioned::resolver::Resolver for PublicResolver { fn resolve(&self, uri: &ureq::http::Uri, config: &ureq::config::Config, timeout: ureq::unversioned::transport::NextTimeout) -> Result { let addrs = self.0.resolve(uri, config, timeout)?; // The proxy the person set up is theirs to reach, wherever it is. let proxy = config.proxy().is_some_and(|p| p.uri() == uri); if !proxy && addrs.iter().any(|a| !public_addr(a.ip())) { return Err(ureq::Error::Io(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "內部網路的位址"))); } Ok(addrs) } } /// Where a redirect leads, from the page it came from. fn follow(base: &str, location: &str) -> String { let location = location.trim(); let scheme = base.split_once("://").map(|(s, _)| s).unwrap_or("https"); let origin_end = base.find("://").map(|i| i + 3).and_then(|i| base[i..].find(['/', '?', '#']).map(|j| i + j)).unwrap_or(base.len()); if location.starts_with("http://") || location.starts_with("https://") { location.to_string() } else if location.starts_with("//") { format!("{scheme}:{location}") } else if location.starts_with('/') { format!("{}{location}", &base[..origin_end]) } else { let path = base[origin_end..].split(['?', '#']).next().unwrap_or(""); let dir = path.rfind('/').map(|i| &path[..=i]).unwrap_or("/"); format!("{}{dir}{location}", &base[..origin_end]) } } /// Redirects web_fetch follows before it gives up (ureq's own default). const MAX_REDIRECTS: usize = 10; /// A page off the public web, as text in its own encoding: where it ended up after redirects, /// the status, and the text. Every stop on the way is checked (`public_only`), so nothing on /// this computer or its network is read. (skill_install fetches through here too: it took any /// address, the router's and a cloud machine's metadata included.) pub fn get_public_bytes(url: &str, limit: u64) -> Result<(String, u16, String, Vec), String> { let mut url = normalize_url(url)?; // Redirects are followed here, one at a time, so each stop is checked like the first. let config = crate::net::config() .http_status_as_error(false) .max_redirects(0) .timeout_global(Some(Duration::from_secs(20))) .timeout_connect(Some(Duration::from_secs(5))) .user_agent("Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15") .build(); let agent = ureq::Agent::with_parts(config, ureq::unversioned::transport::DefaultConnector::new(), PublicResolver(Default::default())); let mut hops = 0; let resp = loop { public_only(&url)?; let resp = agent.get(&url).call().map_err(|e| format!("連不上 {url}:{e}"))?; let next = resp.headers().get("location").and_then(|l| l.to_str().ok()).filter(|_| matches!(resp.status().as_u16(), 301 | 302 | 303 | 307 | 308)).map(|l| follow(&url, l)); match next { Some(_) if hops >= MAX_REDIRECTS => return Err(format!("{url} 一直轉址,讀不到內容。")), Some(to) => { hops += 1; // (As parsed: the stop that is checked is the one asked for.) url = normalize_url(&to)?; } None => break resp, } }; let status = resp.status().as_u16(); let said = resp.headers().get("content-type").and_then(|c| c.to_str().ok()).unwrap_or("").to_string(); let raw = resp.into_body().with_config().limit(limit).read_to_vec().map_err(|e| format!("讀取失敗:{e}"))?; Ok((url, status, said, raw)) } pub fn get_public(url: &str, limit: u64) -> Result<(String, u16, String), String> { let (url, status, said, raw) = get_public_bytes(url, limit)?; Ok((url, status, page_text(&raw, &said))) } fn fetch(url: &str) -> Result { let (url, status, body) = get_public(url, MAX_FETCH_BYTES)?; if status >= 400 { return Err(format!("網站回應 {status}。如果這個頁面要登入,請改用 browser_open。")); } let title = between(&body, "").map(|t| t.split_once('>').map(|x| x.1).unwrap_or(t).trim().to_string()).unwrap_or_default(); let text = html_to_text(&body); let thin = text.chars().count() < 200; let mut out = format!("網址:{url}\n標題:{}\n\n{}", decode_entities(&title), clip(&text, MAX_PAGE_CHARS)); if thin { out.push_str("\n\n(頁面幾乎沒有文字,可能要登入或靠程式載入。可以改用 browser_open 打開,它會等頁面載入再回傳內容。)"); } Ok(out) } /// The name after `charset=` (a Content-Type header, or the start of a page with its /// `` / ``). fn charset_named(s: &str) -> Option { let l = s.to_ascii_lowercase(); let at = l.find("charset=")? + "charset=".len(); let name: String = l[at..].trim_start_matches(['"', '\'', ' ']).chars().take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_')).collect(); (!name.is_empty()).then_some(name) } /// A page's bytes as text, in the encoding the answer's header names, else the one the page /// itself names, else UTF-8 (bytes that are no text in it become �). Pages in Big5, GBK or /// Shift_JIS — many older Taiwanese sites — were refused whole as 「讀取失敗」: they were read /// as UTF-8 or not at all. fn page_text(bytes: &[u8], content_type: &str) -> String { let named = charset_named(content_type).or_else(|| charset_named(&String::from_utf8_lossy(&bytes[..bytes.len().min(4096)]))); let encoding = named.and_then(|n| encoding_rs::Encoding::for_label(n.as_bytes())).unwrap_or(encoding_rs::UTF_8); encoding.decode(bytes).0.into_owned() } fn between<'a>(s: &'a str, a: &str, b: &str) -> Option<&'a str> { let lower = s.to_ascii_lowercase(); let i = lower.find(a)?; let j = lower[i..].find(b)? + i; s.get(i + a.len()..j) } fn clip(s: &str, n: usize) -> String { let mut t: String = s.chars().take(n).collect(); if s.chars().count() > n { t.push_str("\n…(後面還有,已截斷)"); } t } pub fn decode_entities(s: &str) -> String { let mut out = s.replace(" ", " ").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("'", "'"); // Numeric entities like 中 while let Some(i) = out.find("&#") { let Some(j) = out[i..].find(';').map(|j| j + i) else { break }; let code = &out[i + 2..j]; let ch = if let Some(h) = code.strip_prefix('x').or_else(|| code.strip_prefix('X')) { u32::from_str_radix(h, 16).ok() } else { code.parse().ok() }; match ch.and_then(char::from_u32) { Some(c) => out.replace_range(i..=j, &c.to_string()), None => break, } } out.replace("&", "&") } /// Where `` and ``, never `
` (taking /// `
` for `` cut every page with a header off there — articles came back as their /// menus). fn open_tag(lower: &str, tag: &str) -> Option { let pat = format!("<{tag}"); let mut from = 0; while let Some(i) = lower[from..].find(&pat).map(|i| i + from) { match lower[i + pat.len()..].chars().next() { Some(c) if c == '>' || c == '/' || c.is_whitespace() => return Some(i), None => return Some(i), _ => from = i + pat.len(), } } None } /// Visible text of an HTML page: drop scripts, styles and tags, keep line breaks for blocks. pub fn html_to_text(html: &str) -> String { let mut s = html.to_string(); for tag in ["script", "style", "noscript", "svg", "head"] { loop { let lower = s.to_ascii_lowercase(); let Some(a) = open_tag(&lower, tag) else { break }; let end_tag = format!(""); match lower[a..].find(&end_tag) { Some(b) => s.replace_range(a..a + b + end_tag.len(), " "), None => { s.truncate(a); break; } } } } let mut out = String::new(); let mut in_tag = false; let mut tag = String::new(); for c in s.chars() { match c { '<' => { in_tag = true; tag.clear(); } '>' if in_tag => { in_tag = false; let t = tag.trim_start_matches('/').split(|c: char| c.is_whitespace()).next().unwrap_or("").to_ascii_lowercase(); if ["p", "div", "br", "li", "h1", "h2", "h3", "h4", "h5", "h6", "tr", "section", "article", "header", "footer", "main", "nav", "aside", "ul", "ol", "table", "blockquote", "pre", "dt", "dd", "figcaption"].contains(&t.as_str()) { out.push('\n'); } else if t == "td" || t == "th" { out.push(' '); } } _ if in_tag => tag.push(c), _ => out.push(c), } } let text = decode_entities(&out); let lines: Vec = text.lines().map(|l| l.split_whitespace().collect::>().join(" ")).filter(|l| !l.is_empty()).collect(); lines.join("\n") } // ---------- the person's browser ---------- fn applescript_string(s: &str) -> String { format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) } /// Run AppleScript and wait (macOS may first ask the person to allow AnyBot to control the browser). fn osascript(script: &str, cancel: &AtomicBool) -> Result { if !cfg!(target_os = "macos") { return Err("在 Linux 上讀不到你自己瀏覽器裡的分頁。請改用 AnyBot 的瀏覽器(profile 用「預設」或其他設定檔)打開那個網址再讀;要登入的網站,請先在 AnyBot 的瀏覽器登入一次。".into()); } let child = Command::new("osascript").arg("-e").arg(script).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().map_err(|e| e.to_string())?; match wait_piped(child, cancel, Duration::from_secs(SCRIPT_TIMEOUT_SECS)) { Waited::Done(true, so, _) => Ok(so.trim_end().to_string()), Waited::Done(false, _, se) => Err(se.trim().to_string()), Waited::Stopped => Err("已停止".into()), Waited::TooLong => Err("等瀏覽器回應太久了(macOS 可能在問你要不要允許,請看看螢幕)".into()), } } /// How waiting for a command ended: it finished (went well?, what it printed, what it /// complained of), the turn was stopped, or it took too long (then it is killed). enum Waited { Done(bool, String, String), Stopped, TooLong, } /// Wait for a command whose output comes through pipes, reading the pipes while waiting. A /// pipe holds 64 KB: a command that prints more (a long page's text) stood still at that /// point, was waited on until the time ran out, and the page was called unreachable. fn wait_piped(mut child: std::process::Child, cancel: &AtomicBool, limit: Duration) -> Waited { fn read_all(pipe: Option) -> std::thread::JoinHandle> { std::thread::spawn(move || { let mut all = vec![]; if let Some(mut p) = pipe { let _ = std::io::Read::read_to_end(&mut p, &mut all); } all }) } let (out, err) = (read_all(child.stdout.take()), read_all(child.stderr.take())); let start = Instant::now(); loop { if let Ok(Some(st)) = child.try_wait() { let text = |h: std::thread::JoinHandle>| String::from_utf8_lossy(&h.join().unwrap_or_default()).into_owned(); return Waited::Done(st.success(), text(out), text(err)); } let stopped = cancel.load(Ordering::Relaxed); if stopped || start.elapsed() > limit { let _ = child.kill(); let _ = child.wait(); return if stopped { Waited::Stopped } else { Waited::TooLong }; } std::thread::sleep(Duration::from_millis(if start.elapsed() < Duration::from_millis(500) { 10 } else { 100 })); } } fn is_running(app: &str, cancel: &AtomicBool) -> bool { osascript(&format!("application {} is running", applescript_string(app)), cancel).map(|s| s == "true").unwrap_or(false) } /// On-screen windows, front to back, the way the original's `listWindows` ( /// 0x52c0) reads them: `CGWindowListCopyWindowInfo(0x11 = on-screen only | exclude desktop, 0)`. const WINDOW_LIST_JXA: &str = "ObjC.import('CoreGraphics');var a=ObjC.deepUnwrap(ObjC.castRefToObject($.CGWindowListCopyWindowInfo(0x11,0)))||[];JSON.stringify(a.map(function(w){var b=w.kCGWindowBounds||{};return {owner:w.kCGWindowOwnerName||'',layer:w.kCGWindowLayer||0,alpha:(w.kCGWindowAlpha===undefined?1:w.kCGWindowAlpha),w:b.Width||0,h:b.Height||0};}));"; /// App names of the windows that can be seen, front first. Same filter as `listWindows`: skip /// fully transparent windows and ones with no width or height; plus only normal app windows /// (layer 0), so menu-bar items and overlays don't count. pub fn visible_window_owners(json: &str) -> Vec { let v: Value = serde_json::from_str(json).unwrap_or(Value::Null); v.as_array() .map(|a| { a.iter() .filter(|w| w["alpha"].as_f64().unwrap_or(1.0) > 0.0 && w["w"].as_f64().unwrap_or(0.0) > 0.0 && w["h"].as_f64().unwrap_or(0.0) > 0.0 && w["layer"].as_i64().unwrap_or(0) == 0) .filter_map(|w| w["owner"].as_str().map(str::to_string)) .collect() }) .unwrap_or_default() } fn front_window_owners(cancel: &AtomicBool) -> Vec { if !cfg!(target_os = "macos") { return vec![]; } let Ok(child) = Command::new("osascript").args(["-l", "JavaScript", "-e", WINDOW_LIST_JXA]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn() else { return vec![] }; match wait_piped(child, cancel, Duration::from_secs(10)) { Waited::Done(_, out, _) => visible_window_owners(&out), _ => vec![], } } /// The browser whose window is closest to the front: the one the person is looking at. pub fn frontmost_browser(owners: &[String]) -> Option<(&'static str, bool)> { owners.iter().find_map(|o| BROWSERS.iter().find(|(name, _)| name == o).copied()) } /// The browser to use: the front-most browser window, else the first one that's open, else /// Chrome if installed, else Safari. fn pick_browser(cancel: &AtomicBool) -> (&'static str, bool) { if let Some(b) = frontmost_browser(&front_window_owners(cancel)) { return b; } for (name, chromium) in BROWSERS { if is_running(name, cancel) { return (name, chromium); } } if std::path::Path::new("/Applications/Google Chrome.app").exists() { return ("Google Chrome", true); } ("Safari", false) } /// macOS refused to let AnyBot control the browser (-1743): open the Automation settings pane /// right away so the switch is in front of the person, and say what to turn on. fn explain(err: &str, browser: &str) -> String { let lower = err.to_lowercase(); if err.contains("-1743") || lower.contains("not authorized") || lower.contains("不允許") { let _ = crate::computer::spawn_reaped(Command::new("open").arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Automation")); format!("macOS 擋下了 AnyBot 控制 {browser}。我已經幫你打開「系統設定 → 隱私權與安全性 → 自動化」:在 AnyBot(或「終端機」)底下打開「{browser}」,然後再叫我試一次。") } else if lower.contains("javascript") { if browser == "Safari" { "Safari 還沒允許讀取網頁內容:請在 Safari 選單「開發 → 允許來自 Apple 事件的 JavaScript」打開(沒有「開發」選單的話,先到 Safari 設定 → 進階 → 勾選「顯示網頁開發者功能」),然後再叫我試一次。".to_string() } else { format!("{browser} 還沒允許讀取網頁內容:請在 {browser} 選單「檢視 → 開發人員 → 允許來自 Apple 事件的 JavaScript」打開,然後再叫我試一次。") } } else { format!("{browser} 沒有回應:{err}") } } fn browser_open(url: &str, cancel: &AtomicBool) -> Result { let url = normalize_url(url)?; if !cfg!(target_os = "macos") { // Linux: the person's default browser. crate::preview::system_open(&url).status().map_err(|e| format!("打不開瀏覽器:{e}"))?; return Ok(format!("已在你的預設瀏覽器打開 {url}。")); } let (browser, chromium) = pick_browser(cancel); // A Chromium browser started without a folder hands the link to the person's own running // window (their normal profile), never to AnyBot's own window, which `open -a` might pick. let exe = app_exe(browser); let handed = chromium && std::path::Path::new(&exe).exists() && { let mut c = Command::new(&exe); c.arg(&url).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); #[cfg(unix)] { use std::os::unix::process::CommandExt; c.process_group(0); } crate::computer::spawn_reaped(&mut c).is_ok() }; if !handed { let st = Command::new("open").arg("-a").arg(browser).arg(&url).status().map_err(|e| e.to_string())?; if !st.success() { Command::new("open").arg(&url).status().map_err(|e| e.to_string())?; } } let until = Instant::now() + Duration::from_secs(OPEN_SETTLE_SECS); while Instant::now() < until { if cancel.load(Ordering::Relaxed) { return Err("已停止".into()); } std::thread::sleep(Duration::from_millis(100)); } Ok(format!("已在 {browser} 打開 {url}。接著可以用 browser_read 讀這個分頁。")) } /// The main executable of a browser app in /Applications. pub fn app_exe(browser: &str) -> String { format!("/Applications/{browser}.app/Contents/MacOS/{browser}") } fn browser_read(max_chars: usize, cancel: &AtomicBool) -> Result { let (browser, chromium) = pick_browser(cancel); // First through accessibility, like the reference assistant's Computer Use helper: no browser setting, and // it reads whichever profile's window the person has in front. match crate::axread::read_person_browser(&app_exe(browser), max_chars) { Ok(page) if !page.text.trim().is_empty() => { return Ok(format!("瀏覽器:{browser}(你的瀏覽器)\n標題:{}\n網址:{}\n\n{}", page.title, page.url, clip(&page.text, max_chars))); } Err(e) if e.contains("輔助使用") => return Err(e), _ => {} } let app = applescript_string(browser); let (title_s, url_s, text_s) = if chromium { ( format!("tell application {app} to get title of active tab of front window"), format!("tell application {app} to get URL of active tab of front window"), format!("tell application {app} to execute active tab of front window javascript \"document.body ? document.body.innerText : ''\""), ) } else { ( format!("tell application {app} to get name of current tab of front window"), format!("tell application {app} to get URL of current tab of front window"), format!("tell application {app} to do JavaScript \"document.body ? document.body.innerText : ''\" in current tab of front window"), ) }; let title = osascript(&title_s, cancel).map_err(|e| explain(&e, browser))?; let url = osascript(&url_s, cancel).unwrap_or_default(); match osascript(&text_s, cancel) { Ok(text) => { let text: String = text.lines().map(str::trim).filter(|l| !l.is_empty()).collect::>().join("\n"); Ok(format!("瀏覽器:{browser}\n標題:{title}\n網址:{url}\n\n{}", clip(&text, max_chars))) } // Title and address still help; say how to allow the page text. Err(e) => Ok(format!("瀏覽器:{browser}\n標題:{title}\n網址:{url}\n\n(讀不到頁面文字){}", explain(&e, browser))), } } #[cfg(test)] mod tests { use super::*; #[test] fn a_page_with_a_header_keeps_its_article() { // Taking
for cut pages off at their header (WordPress sites, news sites). let html = "T

預售策略

先賣再錄

方案價格
©
"; let t = html_to_text(html); assert!(t.contains("首頁 課程") && t.contains("預售策略") && t.contains("先賣再錄") && t.contains("©"), "{t}"); assert!(t.contains("方案 價格"), "{t}"); // A page with no at all, only a
. assert!(html_to_text("
選單

內文

").contains("內文")); // is still the head. assert!(!html_to_text("不要

要

").contains("不要")); } /// A command that prints more than a pipe holds is read to its end, not waited on until /// the time runs out. #[cfg(unix)] #[test] fn long_output_is_read_while_waiting() { let run = |script: &str| Command::new("sh").args(["-c", script]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); let start = Instant::now(); match wait_piped(run("head -c 300000 /dev/zero | tr '\\0' a; echo oops >&2; exit 3"), &AtomicBool::new(false), Duration::from_secs(20)) { Waited::Done(ok, out, err) => assert_eq!((ok, out.len(), err.trim()), (false, 300_000, "oops")), _ => panic!("it should have finished"), } assert!(start.elapsed() < Duration::from_secs(10), "{:?}", start.elapsed()); assert!(matches!(wait_piped(run("sleep 30"), &AtomicBool::new(false), Duration::from_millis(200)), Waited::TooLong)); assert!(matches!(wait_piped(run("sleep 30"), &AtomicBool::new(true), Duration::from_secs(20)), Waited::Stopped)); } /// A page is read in the encoding it says it is in. #[test] fn a_page_is_read_in_its_own_encoding() { let (big5, _, _) = encoding_rs::BIG5.encode("臺南市政府公告事項"); assert!(std::str::from_utf8(&big5).is_err(), "not UTF-8 to begin with"); assert!(page_text(&big5, "text/html").contains("臺南市政府"), "named by the page"); let (gbk, _, _) = encoding_rs::GBK.encode("中文网页"); assert!(page_text(&gbk, "text/html; charset=GB2312").contains("中文网页"), "named by the header"); let (old, _, _) = encoding_rs::BIG5.encode("舊網站"); assert!(page_text(&old, "").contains("舊網站")); assert_eq!(page_text("純 UTF-8".as_bytes(), "text/html; charset=utf-8"), "純 UTF-8"); assert_eq!(page_text("沒說編碼".as_bytes(), ""), "沒說編碼"); assert!(page_text(&[b'a', 0xff, b'b'], "text/html").starts_with('a'), "bad bytes don't lose the page"); assert_eq!(charset_named("text/html; charset=\"x-unknown\"").as_deref(), Some("x-unknown")); assert_eq!(page_text("未知編碼照 UTF-8".as_bytes(), "text/html; charset=x-unknown"), "未知編碼照 UTF-8"); } /// web_fetch asks nothing, so it reaches the public web only. #[test] fn a_fetch_stays_on_the_public_web() { for inside in [ "http://127.0.0.1:8080/admin", "http://localhost:3000/", "http://api.localhost/", "http://192.168.1.1/", "http://10.0.0.5:9200/_cat/indices", "http://172.16.4.4/", "http://169.254.169.254/latest/meta-data/", "http://100.100.100.100/", "http://0.0.0.0:8000/", "http://[::1]:8080/", "http://[fd00::1]/", "http://[fe80::1]/", "http://[::ffff:127.0.0.1]/", // Other spellings of 127.0.0.1 the system reads as an address. "http://2130706433/", "http://0x7f.1/", "http://user:pw@127.0.0.1/", "http://example.com@127.0.0.1/", ] { assert!(public_only(inside).is_err(), "{inside} was let through"); // (Refused before any connection: by this check, or as not an address at all.) assert!(fetch(inside).is_err_and(|e| e.contains("只讀公開的網頁") || e.contains("不是網址")), "{inside}"); } for outside in ["https://93.184.215.14/", "http://8.8.8.8:8080/x", "https://[2606:4700:4700::1111]/", "http://127.0.0.1.nip.invalid/"] { assert!(public_only(outside).is_ok(), "{outside}"); } assert_eq!(host_port("https://example.com/a?b=http://127.0.0.1/"), Some(("example.com".to_string(), 443))); assert_eq!(host_port("http://[::1]:81/x"), Some(("::1".to_string(), 81))); assert_eq!(host_port("http://example.com:8080"), Some(("example.com".to_string(), 8080))); assert_eq!(host_port("http://example.com?x=1"), Some(("example.com".to_string(), 80))); // A redirect is read from the page it came from, then checked like any address. assert_eq!(follow("https://a.example/x/y?q=1", "http://127.0.0.1/"), "http://127.0.0.1/"); assert_eq!(follow("https://a.example/x/y?q=1", "//b.example/z"), "https://b.example/z"); assert_eq!(follow("https://a.example/x/y?q=1", "/z"), "https://a.example/z"); assert_eq!(follow("https://a.example/x/y?q=1", "z"), "https://a.example/x/z"); assert_eq!(follow("https://a.example", "z"), "https://a.example/z"); } #[test] fn html_becomes_readable_text() { let html = "T

標題

第一段 文字 & 更多

中文
"; assert_eq!(html_to_text(html), "標題\n第一段 文字 & 更多\n中文"); } #[test] fn urls_are_checked() { assert_eq!(normalize_url("threads.net/@me").unwrap(), "https://threads.net/@me"); assert!(normalize_url("not a url").is_err()); assert!(normalize_url("").is_err()); } /// Addresses are read the way a browser reads them (WHATWG): a backslash is a slash, `user@` /// isn't the host, case, a trailing dot, punycode and an IP in any spelling don't change which /// host it is — so the private-network card and the person's rules see the host that opens, /// and the browser is handed that same address. (By hand, `http://127.0.0.1\@a.com/` and /// `http://192.168.1.1\.example.com/` passed as public; `me@example.com` as host `me@example.com`.) #[test] fn addresses_are_read_as_a_browser_reads_them() { for private in ["http://127.0.0.1\\@a.com/", "http://192.168.1.1\\.example.com/", "http://me@127.0.0.1/", "http://localhost./", "http://2130706433/", "http://0x7f.1/", "http://[::1]:8080/", "http://[::ffff:127.0.0.1]/", "HTTP://192.168.1.5/"] { assert!(is_private_browser_url(private), "{private}"); } assert!(is_forbidden_browser_url(&normalize_url("http://169.254.169.254\\@a.com/latest").unwrap())); assert!(is_forbidden_browser_url(&normalize_url("http://2852039166/").unwrap()), "169.254.169.254 written as one number"); for (given, host) in [ ("https://me@example.com/cart", "example.com"), ("https://shop.EXAMPLE.com./cart", "shop.example.com"), ("https://example.com\\cart", "example.com"), ("https://bücher.example/", "xn--bcher-kva.example"), ("example.com:8443/x", "example.com"), ("http://[::1]:8080/", "::1"), ("http://2130706433/", "127.0.0.1"), ] { assert_eq!(host_of(given).as_deref(), Some(host), "{given}"); } assert_eq!(normalize_url("http://127.0.0.1\\@a.com/").unwrap(), "http://127.0.0.1/@a.com/", "what is checked is what opens"); assert_eq!(normalize_url("https://me@example.com\\cart").unwrap(), "https://me@example.com/cart"); assert!(normalize_url("ftp://example.com/").is_err() && normalize_url("javascript:alert(1)").is_err() && normalize_url("intranet").is_err()); } #[test] fn front_browser_follows_window_order() { let json = r#"[{"owner":"Window Server","layer":24,"alpha":1,"w":1920,"h":30}, {"owner":"Ghost","layer":0,"alpha":0,"w":800,"h":600}, {"owner":"Safari","layer":0,"alpha":1,"w":0,"h":600}, {"owner":"Finder","layer":0,"alpha":1,"w":800,"h":600}, {"owner":"Google Chrome","layer":0,"alpha":1,"w":1200,"h":800}, {"owner":"Safari","layer":0,"alpha":1,"w":1200,"h":800}]"#; let owners = visible_window_owners(json); assert_eq!(owners, vec!["Finder", "Google Chrome", "Safari"]); assert_eq!(frontmost_browser(&owners), Some(("Google Chrome", true))); assert_eq!(frontmost_browser(&["Finder".to_string()]), None); } #[test] fn automation_refusal_is_explained() { assert!(explain("execution error: Not authorized to send Apple events to Google Chrome. (-1743)", "Google Chrome").contains("自動化")); assert!(explain("Executing JavaScript through AppleScript is turned off.", "Google Chrome").contains("允許來自 Apple 事件的 JavaScript")); } }