diff --git a/FEATURES.md b/FEATURES.md index f4ebcaa..a4bfb1b 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1488,7 +1488,9 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 密碼跟金鑰一樣:螢幕只看得到「已設定」,不會拿到內容;在螢幕上改指令或網址時,大腦會把密碼清掉(不然會被送到新的位址)。 - **螢幕上的開關就是大腦上的開關**:看大腦時,連接器的開關關掉,大腦就停掉那個伺服器、Bot 沒有它的工具;再打開,大腦用它自己留著的金鑰和密碼重新接上。狀態那一行顯示的是大腦上的結果(接不上會說原因)。 - 權限:每個連接器第一次被用時問「使用連接器「X」的工具:…」,可以一律允許;直接操作模式下不問。 -- 工具回傳的文字、圖片都會交給 Bot;一次最多等 120 秒(估計值)。 +- 工具回傳的文字、圖片都會交給 Bot;一次最多等 120 秒(估計值)。按停止時,本機連接器的呼叫馬上結束(以前要等到它回或 120 秒);用網址連的照樣等。 +- 連接器關掉、移除、重新連線或連不上時,連同它帶起來的所有程式一起關(npx/uvx/sh 底下真正的伺服器以前會一直留著)。 +- **憑證**:AnyBot 所有的 HTTP 連線(連接器、模型服務、Webhook、語音、下載)都信任同一份憑證:公開的加上這台電腦自己信任的。以前只有連帳號伺服器的那條會看這台電腦信任的,公司自己簽憑證的連接器或模型服務在別處會失敗。`clippy.toml` 擋下在 net.rs 以外自己建 HTTP 用戶端。 - **在聊天裡請 Bot 加**(設定畫面能做的,聊天也能做):有「管理 App」能力的 Bot 用 `manage_connectors` 列出、新增、修改(含開關)、重新連線、移除連接器。改的就是大腦上「設定 › 整合 › 連接器」那一份(Bot 的這一輪本來就在大腦上跑),所以每台螢幕電腦和手機都看得到,不會寫到手腳電腦(例如 nobledesktop 上的 ~/.local/share/AnyBot)那邊的檔案。新增、修改、移除先跳「允許…管理連接器嗎?」卡片,列出要執行的指令或網址、環境變數和標頭;名字像金鑰的(TOKEN、KEY、SECRET、PASS、AUTH…)和密碼顯示成「••••(已填)」。加好後等它連上(最多 90 秒)再回報「已連上,N 個工具」或連不上的原因;連上的工具同一輪的下一步就能用(例如「加上 GitLab,然後列出我的 MR」一次做完)。名稱重複、command 和 url 都給、網址不是 http(s)、還有「{…}」沒填、要改卻沒東西可改,都在問你之前就回給 Bot 說原因。 ### 紀錄檔、當掉報告、秘密遮罩 diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 0000000..7d90e06 --- /dev/null +++ b/clippy.toml @@ -0,0 +1,6 @@ +# AnyBot's own lint rules (cargo clippy reads this). Engineering plan E5/E6. +disallowed-methods = [ + # One TLS policy for every HTTP client: the public certificates plus the ones this computer + # trusts (net.rs). A client built elsewhere used to fail on a company's own certificate. + { path = "ureq::Agent::config_builder", reason = "use crate::net::config() or crate::net::agent(): one set of trusted certificates" }, +] diff --git a/docs/feature-map/connectors.md b/docs/feature-map/connectors.md index 8e37c0c..653155d 100644 --- a/docs/feature-map/connectors.md +++ b/docs/feature-map/connectors.md @@ -11,7 +11,9 @@ - 「連接器市集」:8 個常用的(files、memory、thinking、fetch、git、time、playwright、github),按「加入」就能用;要金鑰的(github)會把「新增連接器」表單填好,補上 Token 再按「新增」。 - 「公用市集(官方 MCP Registry)」:搜尋用網址連的連接器,按「加入」會填好表單;還有「{…}」沒換成你的值時,按不下「新增」。 - 給 Bot 的方式:所有連接器加起來 20 個工具以內,每個工具直接給,名字是 `mcp__連接器__工具`;超過 20 個,只給 `find_connector_tool` 和 `use_connector_tool`。 -- 工具回的文字和圖片都交給 Bot;一次最多等 120 秒。 +- 工具回的文字和圖片都交給 Bot;一次最多等 120 秒。按停止,本機連接器的呼叫馬上結束(不用等它回);用網址連的照樣等它回或到 120 秒。 +- 關掉、移除、重新連線或連不上時,連接器連同它帶起來的程式一起關(npx、uvx、sh 底下真正的伺服器以前會留著)。 +- 用網址連的連接器信任這台電腦信任的憑證(公司自己簽的、這台電腦裝過的也可以),和帳號伺服器、瀏覽器一樣。 - 在聊天裡請 Bot 加:Bot 用 `manage_connectors` 列出、新增、修改(含開關)、重新連線、移除連接器,跟設定畫面是同一份清單(大腦的),不會寫到別台電腦的檔案。新增、修改、移除先跳卡片給你看(指令在大腦上執行;金鑰、Token、密碼顯示成「••••(已填)」);加好會等它連上(最多 90 秒)再回報幾個工具,同一輪就能用。 ## 使用者怎麼到 diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index 2850b89..a4e645e 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -29,7 +29,7 @@ - 做法:`secrets.rs`:GitLab `glpat-`、GitHub `ghp_/gho_/github_pat_`、OpenAI/Anthropic/xAI `sk-`/`xai-`、AWS `AKIA…`、Slack `xox…`、Google `AIza…`、PEM 私鑰、`Bearer …`、JWT、`TOKEN=…/KEY=…/SECRET=…/PASSWORD=…` 的值 → `••••`。用在:紀錄檔、當掉報告、手機上的步驟細節和結果。工作紀錄(oplog)不遮:當掉後重做那一步要原本的參數。 - 做完:每一種格式都有測試;手機看到的步驟結果不含 Token。 -### E5. 一個 HTTP 用戶端、子行程成群管理、lint 規則 ⬜ +### E5. 一個 HTTP 用戶端、子行程成群管理、lint 規則 ✅(用網址連的連接器按停止還是等逾時:ureq 的請求停不下來,留給 M7) - 做法:`net::agent(timeout)` 統一建 `ureq` 用戶端(信任的憑證、逾時、User-Agent);`clippy.toml` 用 `disallowed-methods` 擋其他地方自己建。連接器的伺服器和 shell 指令開在自己的 process group,停掉時整群一起停(npx/uvx 帶起來的子行程不再留著)。`mcp::call` 收停止訊號(按停止不用等 120 秒)。 - 做完:`cargo clippy` 對新的違規報錯;停掉連接器後 `pgrep` 找不到它的子行程;按停止一秒內連接器呼叫就結束。 diff --git a/src/agent.rs b/src/agent.rs index 9a52fc4..dbf572c 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -2981,7 +2981,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< } let (output, status, img) = if allowed { started(); - let (o, ok, img) = crate::mcp::call(&mcp_name, &mcp_args); + let (o, ok, img) = crate::mcp::call_until(&mcp_name, &mcp_args, &cancel); (o, if ok { ToolStatus::Done } else { ToolStatus::Failed }, img) } else { ("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。".to_string(), ToolStatus::Denied, None) diff --git a/src/botbrowser.rs b/src/botbrowser.rs index d5e9501..e1a20b0 100644 --- a/src/botbrowser.rs +++ b/src/botbrowser.rs @@ -418,7 +418,7 @@ pub fn remove(name: &str) -> Result<(), String> { } pub(crate) fn local() -> ureq::Agent { - ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(5))).http_status_as_error(false).build().into() + crate::net::config().timeout_global(Some(Duration::from_secs(5))).http_status_as_error(false).build().into() } /// The fixed port of 「預設」 (`ANYBOT_BROWSER_PORT` overrides it, for testing). diff --git a/src/channels.rs b/src/channels.rs index c409a13..599ac4e 100644 --- a/src/channels.rs +++ b/src/channels.rs @@ -140,7 +140,7 @@ fn set_status(id: u64, ok: bool, note: &str, got: u64) { } fn agent(timeout: u64) -> ureq::Agent { - ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(timeout))).http_status_as_error(false).build().into() + crate::net::config().timeout_global(Some(Duration::from_secs(timeout))).http_status_as_error(false).build().into() } /// Seconds to wait after a 429 ("rate:N" from get_json), bounded so a bogus value can't park diff --git a/src/embed.rs b/src/embed.rs index f2feb86..bf8f789 100644 --- a/src/embed.rs +++ b/src/embed.rs @@ -96,7 +96,7 @@ fn engine_id(e: &Engine) -> String { } fn agent(secs: u64) -> ureq::Agent { - ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(secs))).build().into() + crate::net::config().timeout_global(Some(Duration::from_secs(secs))).build().into() } /// An installed embedding model in Ollama, by the names people use (bge-m3, nomic-embed-text…). @@ -208,7 +208,7 @@ fn fetch_local() -> Result<(), String> { std::fs::create_dir_all(&dir).map_err(|e| format!("建不了資料夾:{e}"))?; let url = |f: &str| format!("{}/{LOCAL_MODEL}/resolve/main/{f}", hub()); // No limit on the whole download (512 MB on a slow line takes a while): only on silence. - let net: ureq::Agent = ureq::Agent::config_builder().timeout_connect(Some(Duration::from_secs(30))).timeout_recv_response(Some(Duration::from_secs(60))).timeout_per_read(Some(Duration::from_secs(60))).build().into(); + let net: ureq::Agent = crate::net::config().timeout_connect(Some(Duration::from_secs(30))).timeout_recv_response(Some(Duration::from_secs(60))).timeout_per_read(Some(Duration::from_secs(60))).build().into(); let why = |e: ureq::Error| format!("連不到 Hugging Face:{e}"); let mut r = net.get(&url("tokenizer.json")).call().map_err(why)?; let tok = r.body_mut().with_config().limit(64 << 20).read_to_vec().map_err(|e| format!("字表沒下載完:{e}"))?; diff --git a/src/main.rs b/src/main.rs index 9ae7944..5fbad54 100644 --- a/src/main.rs +++ b/src/main.rs @@ -74,6 +74,7 @@ mod plan; mod always; mod secrets; mod logfile; +mod net; mod store; mod docindex; mod drops; diff --git a/src/mcp.rs b/src/mcp.rs index 64055d3..554be82 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -190,15 +190,32 @@ pub fn is_list_changed(v: &Value) -> bool { v.get("method").and_then(|m| m.as_str()) == Some("notifications/tools/list_changed") } -/// Read the answer with this id (skipping notifications and requests from the server). -fn wait_id(rx: &Receiver, id: u64, secs: u64) -> Result { +/// A stdio server's process and everything it started (`npx`/`uvx` run the real server as a child +/// of their own: killing only the direct child used to leave that one running). +fn end(child: &mut Child) { + crate::tools::kill_tree(child.id()); + let _ = child.kill(); + let _ = child.wait(); +} + +/// What a connector call says when the person pressed 停止. +pub const STOPPED: &str = "已停止:使用者按了停止,沒有等連接器的回答。"; + +/// Read the answer with this id (skipping notifications and requests from the server). A stop +/// (`cancel`) ends the wait within a fifth of a second; the server's late answer is skipped by +/// the next wait. +fn wait_id(rx: &Receiver, id: u64, secs: u64, cancel: Option<&std::sync::atomic::AtomicBool>) -> Result { let deadline = std::time::Instant::now() + Duration::from_secs(secs); loop { let left = deadline.saturating_duration_since(std::time::Instant::now()); if left.is_zero() { return Err("MCP 伺服器沒有回應".into()); } - match rx.recv_timeout(left) { + if cancel.is_some_and(|c| c.load(std::sync::atomic::Ordering::Relaxed)) { + return Err(STOPPED.into()); + } + match rx.recv_timeout(left.min(Duration::from_millis(200))) { + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue, Ok(v) if v["id"].as_u64() == Some(id) && v.get("method").is_none() => { if let Some(e) = v.get("error") { return Err(format!("MCP 錯誤:{}", e["message"].as_str().unwrap_or(&e.to_string()))); @@ -249,16 +266,21 @@ pub fn parse_http_answer(body: &str, id: u64) -> Result { impl Live { fn request(&mut self, method: &str, params: Value) -> Result { + self.request_until(method, params, None) + } + + /// A request a stop can end (a stdio server's; an HTTP one waits its timeout out). + fn request_until(&mut self, method: &str, params: Value, cancel: Option<&std::sync::atomic::AtomicBool>) -> Result { let id = self.next_id; self.next_id += 1; let msg = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}); match &mut self.link { Link::Stdio { stdin, rx, .. } => { send_stdio(stdin, &msg)?; - wait_id(rx, id, CALL_TIMEOUT_SECS) + wait_id(rx, id, CALL_TIMEOUT_SECS, cancel) } Link::Http { url, headers, session } => { - let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(CALL_TIMEOUT_SECS))).http_status_as_error(false).build().into(); + let agent: ureq::Agent = crate::net::config().timeout_global(Some(Duration::from_secs(CALL_TIMEOUT_SECS))).http_status_as_error(false).build().into(); let mut r = agent.post(url.as_str()).header("Content-Type", "application/json").header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", PROTOCOL); for (k, v) in headers.iter() { r = r.header(k.as_str(), v.as_str()); @@ -291,7 +313,7 @@ impl Live { let _ = send_stdio(stdin, &msg); } Link::Http { url, headers, session } => { - let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(10))).http_status_as_error(false).build().into(); + let agent: ureq::Agent = crate::net::config().timeout_global(Some(Duration::from_secs(10))).http_status_as_error(false).build().into(); let mut r = agent.post(url.as_str()).header("Content-Type", "application/json").header("Accept", "application/json, text/event-stream"); for (k, v) in headers.iter() { r = r.header(k.as_str(), v.as_str()); @@ -432,8 +454,7 @@ fn connect(config: &Server) -> Result { // A server that didn't come up is ended (it is tried again each half minute, and // used to be left running each time), and what it said on stderr goes with the error. if let Link::Stdio { child, .. } = &mut live.link { - let _ = child.kill(); - let _ = child.wait(); + end(child); } std::thread::sleep(Duration::from_millis(100)); let said: Vec = errlog.map(|l| l.lock().unwrap().iter().cloned().collect()).unwrap_or_default(); @@ -486,7 +507,7 @@ pub fn refresh_tools(name: &str) { /// stream to offer, and the thread ends — reconnecting the connector is the manual way. fn spawn_http_listener(url: String, headers: BTreeMap, session: String, name: String) { std::thread::spawn(move || { - let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(600))).http_status_as_error(false).build().into(); + let agent: ureq::Agent = crate::net::config().timeout_global(Some(Duration::from_secs(600))).http_status_as_error(false).build().into(); loop { // This thread is for one session of one connector: gone, or connected anew under // the same name (a new session, with a listener of its own), it ends. (An old one @@ -561,8 +582,7 @@ pub fn sync(servers: &[Server]) -> Vec<(String, String)> { std::thread::spawn(move || { for c in gone { if let Link::Stdio { child, .. } = &mut c.live.lock().unwrap().link { - let _ = child.kill(); - let _ = child.wait(); + end(child); } } }); @@ -592,8 +612,7 @@ pub fn forget(name: &str) { if let Some(c) = gone { std::thread::spawn(move || { if let Link::Stdio { child, .. } = &mut c.live.lock().unwrap().link { - let _ = child.kill(); - let _ = child.wait(); + end(child); } }); } @@ -728,8 +747,14 @@ pub fn resolve(name: &str) -> Option<(String, String)> { tools().into_iter().find(|t| tool_name(&t.server, &t.name) == name).map(|t| (t.server, t.name)) } -/// Call a tool. Returns (text, ok, first picture as base64). +/// Call a tool. Returns (text, ok, first picture as base64). (A turn uses `call_until`.) +#[cfg(test)] pub fn call(name: &str, args: &str) -> (String, bool, Option) { + call_until(name, args, &std::sync::atomic::AtomicBool::new(false)) +} + +/// Call a tool; the person's 停止 (`cancel`) ends the wait. +pub fn call_until(name: &str, args: &str, cancel: &std::sync::atomic::AtomicBool) -> (String, bool, Option) { let Some((server, tool)) = resolve(name) else { return (format!("沒有「{name}」這個 MCP 工具(伺服器可能已關閉)"), false, None) }; let arguments: Value = serde_json::from_str(if args.trim().is_empty() { "{}" } else { args }).unwrap_or(json!({})); // Copy the server's own handle out of the table, then lock its link alone: a two-minute @@ -740,7 +765,7 @@ pub fn call(name: &str, args: &str) -> (String, bool, Option) { // way round, and a link lock must never be held while taking the table's. let (result, dead) = { let mut live = conn.live.lock().unwrap(); - let r = live.request("tools/call", json!({"name": tool, "arguments": arguments})); + let r = live.request_until("tools/call", json!({"name": tool, "arguments": arguments}), Some(cancel)); let dead = r.is_err() && live.dead(); (r, dead) }; @@ -783,8 +808,7 @@ pub fn call(name: &str, args: &str) -> (String, bool, Option) { pub fn shutdown() { for c in conns().lock().unwrap().values() { if let Link::Stdio { child, .. } = &mut c.live.lock().unwrap().link { - let _ = child.kill(); - let _ = child.wait(); + end(child); } } } @@ -813,7 +837,7 @@ const REGISTRY_LIMIT: usize = 40; /// Search the registry: servers reached by address, as [`registry_entries`] gives them. pub fn registry_search(q: &str) -> Result, String> { let url = format!("{REGISTRY}?version=latest&limit={REGISTRY_LIMIT}&search={}", crate::httpd::url_encode(q.trim())); - let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(20))).http_status_as_error(false).build().into(); + let agent: ureq::Agent = crate::net::config().timeout_global(Some(Duration::from_secs(20))).http_status_as_error(false).build().into(); let mut resp = agent.get(&url).header("Accept", "application/json").call().map_err(|e| format!("連不到公用市集:{e}"))?; let st = resp.status().as_u16(); let body = resp.body_mut().read_to_string().unwrap_or_default(); @@ -1212,9 +1236,13 @@ for line in sys.stdin: if m["method"] == "initialize": r = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}, "serverInfo": {"name": "fake"}} elif m["method"] == "tools/list": - r = {"tools": [{"name": "tool_%02d" % i, "description": "Unrelated thing number %d" % i, "inputSchema": {"type": "object"}} for i in range(MANY)] + [{"name": "add", "description": "Add two numbers", "inputSchema": {"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}}}, {"name": "quit", "description": "End the server", "inputSchema": {"type": "object"}}]} + r = {"tools": [{"name": "tool_%02d" % i, "description": "Unrelated thing number %d" % i, "inputSchema": {"type": "object"}} for i in range(MANY)] + [{"name": "add", "description": "Add two numbers", "inputSchema": {"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}}}, {"name": "quit", "description": "End the server", "inputSchema": {"type": "object"}}] + ([{"name": "slow", "description": "Take three seconds", "inputSchema": {"type": "object"}}] if os.environ.get("FAKE_SLOW") else [])} elif m["method"] == "tools/call" and m["params"]["name"] == "quit": sys.exit(0) + elif m["method"] == "tools/call" and m["params"]["name"] == "slow": + import time + time.sleep(3) + r = {"content": [{"type": "text", "text": "slow done"}]} elif m["method"] == "tools/call": a = m["params"]["arguments"] r = {"content": [{"type": "text", "text": "sum=%d" % (a["a"] + a["b"])}]} @@ -1531,11 +1559,11 @@ for line in sys.stdin: .replace("@", extra) }; let post = |path: &str| { - let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(5))).http_status_as_error(false).build().into(); + let agent: ureq::Agent = crate::net::config().timeout_global(Some(Duration::from_secs(5))).http_status_as_error(false).build().into(); agent.post(&format!("{MANAGE}{path}")).send(()).ok().and_then(|mut r| r.body_mut().read_to_string().ok()) }; let health_tools = || -> Option { - let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(5))).http_status_as_error(false).build().into(); + let agent: ureq::Agent = crate::net::config().timeout_global(Some(Duration::from_secs(5))).http_status_as_error(false).build().into(); let b = agent.get(&format!("{MANAGE}/healthz")).call().ok()?.body_mut().read_to_string().ok()?; Some(serde_json::from_str::(&b).ok()?.get("tools")?.as_u64()? as usize) }; @@ -1783,3 +1811,55 @@ mod manage_tests { assert!(connected_text("nope", &status, &[]).is_none()); } } + +#[cfg(test)] +mod stop_tests { + use super::*; + + /// E5: 停止 ends a connector call at once (it used to wait up to two minutes for the server). + #[test] + fn a_stop_ends_a_connector_call_at_once() { + let _l = test_lock(); + sync(&[]); + let mut slow = fake_server("slowpoke", 0); + slow.env.insert("FAKE_SLOW".into(), "1".into()); + assert!(sync(&[slow]).is_empty()); + let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let c2 = cancel.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(300)); + c2.store(true, std::sync::atomic::Ordering::Relaxed); + }); + let t0 = std::time::Instant::now(); + let (text, ok, _) = call_until(&tool_name("slowpoke", "slow"), "{}", &cancel); + assert!(!ok && text == STOPPED, "{text}"); + assert!(t0.elapsed() < Duration::from_secs(2), "{:?}", t0.elapsed()); + // The server is still there for the next call (its late answer is skipped). + assert_eq!(call(&tool_name("slowpoke", "add"), r#"{"a": 1, "b": 2}"#).0.trim(), "sum=3"); + sync(&[]); + } + + /// E5: a connector started through a launcher (npx, uvx, sh) is ended with everything it + /// started — the real server under the launcher used to stay running. + #[cfg(unix)] + #[test] + fn a_connector_ends_with_what_it_started() { + let _l = test_lock(); + sync(&[]); + let mut s = fake_server("launched", 0); + let marker = format!("sleep {}", 4000 + std::process::id() % 1000); + let inner = std::iter::once(s.command.clone()).chain(s.args.iter().cloned()).collect::>().join(" "); + s.command = "sh".into(); + s.args = vec!["-c".into(), format!("{marker} & exec {inner}")]; + assert!(sync(&[s]).is_empty()); + let running = || std::process::Command::new("pgrep").args(["-f", &marker]).output().map(|o| !o.stdout.is_empty()).unwrap_or(false); + assert!(running(), "the launcher's child runs while connected"); + forget("launched"); + let t0 = std::time::Instant::now(); + while running() && t0.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(100)); + } + assert!(!running(), "still running after the connector was ended: {marker}"); + sync(&[]); + } +} diff --git a/src/net.rs b/src/net.rs new file mode 100644 index 0000000..1cb5523 --- /dev/null +++ b/src/net.rs @@ -0,0 +1,50 @@ +//! 一個 HTTP 用戶端: every HTTP client AnyBot makes starts here, so they all trust the same +//! certificates — the public ones every browser knows plus the ones this computer trusts itself +//! (tunnel::trusted_roots). Before, only the account server's client did: a connector, a model +//! service or a webhook on the local network with a certificate its company signs (trusted by +//! the computer, as in the browser) failed with "unknown issuer" everywhere else. +//! +//! Each caller still sets its own timeouts, redirects and user agent on top. `clippy.toml` refuses +//! `ureq::Agent::config_builder` anywhere but here (grok-build does the same for its HTTP clients). + +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; + +/// The certificates an AnyBot HTTP client accepts (made once: the system's list takes a moment). +fn tls() -> ureq::tls::TlsConfig { + static T: OnceLock = OnceLock::new(); + T.get_or_init(|| { + let roots: Vec<_> = crate::tunnel::trusted_roots().iter().map(|c| ureq::tls::Certificate::from_der(c.as_ref()).to_owned()).collect(); + ureq::tls::TlsConfig::builder().root_certs(ureq::tls::RootCerts::new_with_certs(&roots)).build() + }) + .clone() +} + +/// An HTTP client's settings, with AnyBot's certificates already in: add timeouts and the rest, +/// then `.build().into()`. +#[allow(clippy::disallowed_methods)] +pub fn config() -> ureq::config::ConfigBuilder { + ureq::Agent::config_builder().tls_config(tls()) +} + +/// The common client: `secs` for the whole request, an HTTP error status is an answer (not an +/// Err). One per timeout, kept (its connections are reused). +pub fn agent(secs: u64) -> ureq::Agent { + static AGENTS: OnceLock>> = OnceLock::new(); + AGENTS.get_or_init(Mutex::default).lock().unwrap_or_else(|e| e.into_inner()).entry(secs).or_insert_with(|| config().timeout_global(Some(Duration::from_secs(secs))).http_status_as_error(false).build().into()).clone() +} + +#[cfg(test)] +mod tests { + #[test] + fn every_client_trusts_the_same_certificates() { + // The public list at least, and the system's on top. + assert!(crate::tunnel::trusted_roots().len() >= webpki_root_certs::TLS_SERVER_ROOT_CERTS.len()); + let a = super::agent(7); + let b = super::agent(7); + // (The same client for the same timeout: its connections are reused.) + assert_eq!(format!("{:?}", a.config().timeouts().global), format!("{:?}", b.config().timeouts().global)); + assert!(!a.config().http_status_as_error()); + } +} diff --git a/src/phone.rs b/src/phone.rs index 7f4f7e3..a158fdf 100644 --- a/src/phone.rs +++ b/src/phone.rs @@ -25,7 +25,7 @@ fn x_api() -> String { } fn agent() -> ureq::Agent { - ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(30))).http_status_as_error(false).build().into() + crate::net::config().timeout_global(Some(Duration::from_secs(30))).http_status_as_error(false).build().into() } /// "AccountSID:AuthToken" → (sid, Basic header). diff --git a/src/providers.rs b/src/providers.rs index c689a73..1cf1525 100644 --- a/src/providers.rs +++ b/src/providers.rs @@ -342,7 +342,7 @@ pub fn backoff_delay_ms(retry: u32) -> u64 { } fn agent() -> ureq::Agent { - let config = ureq::Agent::config_builder() + let config = crate::net::config() .http_status_as_error(false) // Never follow HTTP redirects on model API calls: `x-api-key` is a custom header that // `ureq` would forward unchanged to an untrusted redirect target, and 301/302 turns POST into GET. diff --git a/src/remote.rs b/src/remote.rs index 354f662..593087e 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -1676,18 +1676,7 @@ static RELAY_GEN: AtomicU64 = AtomicU64::new(0); /// handshake each time). It accepts the same certificates as the long connection /// (`tunnel::trusted_roots`: the public ones and the ones this computer trusts). fn agent(secs: u64) -> ureq::Agent { - static AGENTS: OnceLock>> = OnceLock::new(); - AGENTS - .get_or_init(Mutex::default) - .lock() - .unwrap() - .entry(secs) - .or_insert_with(|| { - let roots: Vec<_> = crate::tunnel::trusted_roots().iter().map(|c| ureq::tls::Certificate::from_der(c.as_ref()).to_owned()).collect(); - let tls = ureq::tls::TlsConfig::builder().root_certs(ureq::tls::RootCerts::new_with_certs(&roots)).build(); - ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(secs))).http_status_as_error(false).tls_config(tls).build().into() - }) - .clone() + crate::net::agent(secs) } /// Why a request never got an answer, in plain words (never an error code). diff --git a/src/speech.rs b/src/speech.rs index 47485f5..fc91b83 100644 --- a/src/speech.rs +++ b/src/speech.rs @@ -187,7 +187,7 @@ fn openai_listen(e: &Engine, audio: &[u8], name: &str, lang: &str) -> Result Result<(), String> { let url = format!("{}/models/{}", base.trim_end_matches('/'), model); - let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(60 * 60))).http_status_as_error(false).build().into(); + let agent: ureq::Agent = crate::net::config().timeout_global(Some(Duration::from_secs(60 * 60))).http_status_as_error(false).build().into(); let mut last = String::new(); for _ in 0..30 { match agent.post(&url).send(&[][..]) { @@ -365,7 +365,7 @@ fn bearer(key: &str) -> Vec<(&'static str, String)> { } fn agent() -> ureq::Agent { - ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(120))).http_status_as_error(false).build().into() + crate::net::config().timeout_global(Some(Duration::from_secs(120))).http_status_as_error(false).build().into() } /// The recording's media type, from its name. diff --git a/src/teams.rs b/src/teams.rs index c6db07d..aa60b68 100644 --- a/src/teams.rs +++ b/src/teams.rs @@ -20,7 +20,7 @@ fn graph_base() -> String { } fn agent() -> ureq::Agent { - ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(30))).http_status_as_error(false).build().into() + crate::net::config().timeout_global(Some(Duration::from_secs(30))).http_status_as_error(false).build().into() } fn form(url: &str, fields: &[(&str, &str)]) -> Result { diff --git a/src/triggers.rs b/src/triggers.rs index 57dfe39..7054007 100644 --- a/src/triggers.rs +++ b/src/triggers.rs @@ -404,7 +404,7 @@ fn webhooks() -> &'static Mutex> { } fn agent(secs: u64) -> ureq::Agent { - ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(secs))).http_status_as_error(false).build().into() + crate::net::config().timeout_global(Some(Duration::from_secs(secs))).http_status_as_error(false).build().into() } fn get(url: &str, headers: &[(&str, String)]) -> Result { diff --git a/src/web.rs b/src/web.rs index 97b8f67..85688e5 100644 --- a/src/web.rs +++ b/src/web.rs @@ -328,7 +328,7 @@ const MAX_REDIRECTS: usize = 10; 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 = ureq::Agent::config_builder() + let config = crate::net::config() .http_status_as_error(false) .max_redirects(0) .timeout_global(Some(Duration::from_secs(20)))