AnyBot/src/attach.rs

251 lines
12 KiB
Rust
Raw Normal View History

// Files and pictures the person gives a bot with a message (the original: 附件 — drag files in,
// paste a picture, or pick files; pictures go to the model, documents are read for it).
// Each one is copied into AnyBot's data folder, so the chat keeps working after the original moves.
use base64::Engine;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
/// Largest file accepted (estimated).
pub const MAX_FILE_BYTES: u64 = 52_428_800;
/// Text read from one file for the model (estimated; the original reads 20,000 characters of mail
/// and notes).
pub const MAX_TEXT_CHARS: usize = 20_000;
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct Attachment {
pub name: String,
/// The copy in AnyBot's data folder.
pub path: String,
#[serde(default)]
pub image: bool,
#[serde(default)]
pub bytes: u64,
/// Where it was also put on the bot's own computer (empty when not).
#[serde(default)]
pub on_box: String,
}
fn dir_for(bot_id: u64) -> PathBuf {
crate::model::State::path().parent().map(|p| p.to_path_buf()).unwrap_or_else(std::env::temp_dir).join("attachments").join(format!("bot-{bot_id}"))
}
Bug sweep: gates, relay 2FA, Windows input, snapshots, encodings Permissions and reach - a file leaving a computer passes the same questions as reading it; "looking" shell commands that do more than look ask first - a symlink out of the work/sealed folder counts as outside it (real paths, not just lexical ones); the search walk skips links - web_fetch and skill_install read the public web only: localhost, the LAN and cloud metadata are refused, at every redirect - preview shows a file without running it; browser_upload may ask - vault: logins no longer match across shared suffixes (pages.dev, com.tw, ...); registrable_domain knows public suffixes - axwrite: found elements are retained (use-after-free) Relay - replacing or turning off 2FA needs the current code (rate-limited); new recovery codes only count once enrollment is verified - a removed computer loses its socket and its `call` access - a site name taken by another account answers 409 - RELAY_TRUST_PROXY: the login lock counts the caller's address, not the proxy's (compose files and README) - httpd: half a body is not a request Desktop - sign-in, join and restore work with 2FA on (code field; --serve reads ANYBOT_ACCOUNT_CODE; the setup wizard points to a pairing code) - Windows: text was typed twice; modifiers are held through click, drag and scroll; horizontal scroll; screen control is no longer refused - a recording that hits the limit is transcribed, not thrown away - bot's computer: a new home volume restores the snapshot; a snapshot is read through before the home is wiped; a failed volume removal stops reset/restore - events of a stopped turn no longer land in the next one; each channel message gets a turn of its own - saving a bot's settings keeps what it got meanwhile (three-way merge); a save file that cannot be read is kept - pages in Big5/GBK/Shift_JIS are read in their own encoding (encoding_rs); osascript output past 64 KB no longer stalls - pick_tab keeps a job's own non-http tab; pictures larger than the texture limit are fitted; the auto-update time field takes typing - skills live in <data>/skills; memories are unnumbered in the prompt; the phone may skillify and skill_install CI - the test step fails when the tests fail (it piped into tail) Tests: anybot 268 passed, 27 ignored; relay 16 passed; clippy unchanged. Not run: Windows on a real machine (win.rs type-checked alone), the Docker paths of the bot's computer, the live accessibility writes. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 03:46:17 +00:00
/// A file the person gave this bot with a message (the copy kept here): the bot may pass it
/// on, though it sits in AnyBot's own folder, which is otherwise closed to it.
pub fn is_given(bot_id: u64, p: &Path) -> bool {
let dir = dir_for(bot_id);
let real = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
p.is_file() && real(p).starts_with(real(&dir))
}
pub fn is_image_name(name: &str) -> bool {
let n = name.to_lowercase();
[".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".heic", ".tif", ".tiff"].iter().any(|e| n.ends_with(e))
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
fn safe_attach_name(raw: &str, fallback: &str) -> String {
let last = raw.rsplit(['/', '\\']).next().unwrap_or("");
let s: String = last.chars().filter(|c| !c.is_control() && *c != ':').collect();
let s = s.trim().trim_start_matches('.').trim();
let capped: String = s.chars().take(120).collect();
if capped.is_empty() { fallback.to_string() } else { capped }
}
/// Copy a file in as an attachment.
pub fn store(bot_id: u64, src: &Path) -> Result<Attachment, String> {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let real = std::fs::canonicalize(src).map_err(|e| format!("讀不到 {}:{e}", src.display()))?;
let temp = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir());
if !real.starts_with(&temp) && crate::tools::is_ignored(&real) && !is_given(bot_id, &real) {
return Err(format!("「{}」是系統或私密金鑰檔案,不能附加。", src.display()));
}
let meta = std::fs::metadata(&real).map_err(|e| format!("讀不到 {}:{e}", src.display()))?;
if meta.is_dir() {
return Err(format!("「{}」是資料夾,請壓縮後再附加,或請 Bot 直接處理那個資料夾。", src.display()));
}
if meta.len() > MAX_FILE_BYTES {
return Err(format!("「{}」太大了(最多 50 MB)", src.display()));
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let raw_name = src.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let name = safe_attach_name(&raw_name, "附件");
let dir = dir_for(bot_id);
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
crate::httpd::ensure_private_dir(&dir);
let dst = dir.join(format!("{}-{name}", chrono::Local::now().format("%Y%m%d%H%M%S%3f")));
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
std::fs::copy(&real, &dst).map_err(|e| format!("複製失敗:{e}"))?;
crate::httpd::tighten_permissions(&dst);
Ok(Attachment { image: is_image_name(&name), name, path: dst.display().to_string(), bytes: meta.len(), on_box: String::new() })
}
/// A picture or file the bot hands over (a screen it shows, a file fetched from another computer).
pub fn store_bytes(bot_id: u64, name: &str, bytes: &[u8]) -> Result<Attachment, String> {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let safe_name = safe_attach_name(name, "檔案");
if bytes.len() as u64 > MAX_FILE_BYTES {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
return Err(format!("「{safe_name}」太大了(最多 50 MB)"));
}
let dir = dir_for(bot_id);
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
crate::httpd::ensure_private_dir(&dir);
let dst = dir.join(format!("{}-{safe_name}", chrono::Local::now().format("%Y%m%d%H%M%S%3f")));
crate::httpd::write_private(&dst, bytes).map_err(|e| format!("存不下來:{e}"))?;
Ok(Attachment { image: is_image_name(&safe_name), name: safe_name, path: dst.display().to_string(), bytes: bytes.len() as u64, on_box: String::new() })
}
Bug sweep: gates, relay 2FA, Windows input, snapshots, encodings Permissions and reach - a file leaving a computer passes the same questions as reading it; "looking" shell commands that do more than look ask first - a symlink out of the work/sealed folder counts as outside it (real paths, not just lexical ones); the search walk skips links - web_fetch and skill_install read the public web only: localhost, the LAN and cloud metadata are refused, at every redirect - preview shows a file without running it; browser_upload may ask - vault: logins no longer match across shared suffixes (pages.dev, com.tw, ...); registrable_domain knows public suffixes - axwrite: found elements are retained (use-after-free) Relay - replacing or turning off 2FA needs the current code (rate-limited); new recovery codes only count once enrollment is verified - a removed computer loses its socket and its `call` access - a site name taken by another account answers 409 - RELAY_TRUST_PROXY: the login lock counts the caller's address, not the proxy's (compose files and README) - httpd: half a body is not a request Desktop - sign-in, join and restore work with 2FA on (code field; --serve reads ANYBOT_ACCOUNT_CODE; the setup wizard points to a pairing code) - Windows: text was typed twice; modifiers are held through click, drag and scroll; horizontal scroll; screen control is no longer refused - a recording that hits the limit is transcribed, not thrown away - bot's computer: a new home volume restores the snapshot; a snapshot is read through before the home is wiped; a failed volume removal stops reset/restore - events of a stopped turn no longer land in the next one; each channel message gets a turn of its own - saving a bot's settings keeps what it got meanwhile (three-way merge); a save file that cannot be read is kept - pages in Big5/GBK/Shift_JIS are read in their own encoding (encoding_rs); osascript output past 64 KB no longer stalls - pick_tab keeps a job's own non-http tab; pictures larger than the texture limit are fitted; the auto-update time field takes typing - skills live in <data>/skills; memories are unnumbered in the prompt; the phone may skillify and skill_install CI - the test step fails when the tests fail (it piped into tail) Tests: anybot 268 passed, 27 ignored; relay 16 passed; clippy unchanged. Not run: Windows on a real machine (win.rs type-checked alone), the Docker paths of the bot's computer, the live accessibility writes. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 03:46:17 +00:00
/// The picture a paste brought (⌘V with a picture and no text on the clipboard: the window is
/// handed the pixels, straight RGBA, not a V key).
pub fn store_pasted(bot_id: u64, size: [usize; 2], rgba: Vec<u8>) -> Result<Attachment, String> {
let img = image::RgbaImage::from_raw(size[0] as u32, size[1] as u32, rgba).ok_or("貼上的圖片讀不出來")?;
let mut png = std::io::Cursor::new(Vec::new());
img.write_to(&mut png, image::ImageFormat::Png).map_err(|e| format!("貼上的圖片存不下來:{e}"))?;
store_bytes(bot_id, &format!("貼上的圖片 {}.png", chrono::Local::now().format("%H%M%S")), png.get_ref())
}
/// A picture on the clipboard (e.g. a screenshot copied with ⌃⇧⌘4) becomes an attachment.
pub fn paste_image(bot_id: u64) -> Option<Attachment> {
let dir = dir_for(bot_id);
std::fs::create_dir_all(&dir).ok()?;
let name = format!("貼上的圖片 {}.png", chrono::Local::now().format("%H%M%S"));
let dst = dir.join(format!("{}-{name}", chrono::Local::now().format("%Y%m%d%H%M%S%3f")));
if !cfg!(target_os = "macos") {
let png = crate::platform::clipboard_png_linux()?;
std::fs::write(&dst, &png).ok()?;
return Some(Attachment { name, path: dst.display().to_string(), image: true, bytes: png.len() as u64, on_box: String::new() });
}
let script = r#"ObjC.import('AppKit');
function run(argv) {
const img = $.NSImage.alloc.initWithPasteboard($.NSPasteboard.generalPasteboard);
if (img.isNil()) return 'none';
const rep = $.NSBitmapImageRep.imageRepWithData(img.TIFFRepresentation);
const png = rep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $({}));
return png.writeToFileAtomically(argv[0], true) ? 'ok' : 'fail';
}"#;
let out = std::process::Command::new("osascript").args(["-l", "JavaScript", "-e", script, "--"]).arg(&dst).output().ok()?;
if String::from_utf8_lossy(&out.stdout).trim() != "ok" {
return None;
}
let bytes = std::fs::metadata(&dst).map(|m| m.len()).unwrap_or(0);
Some(Attachment { name, path: dst.display().to_string(), image: true, bytes, on_box: String::new() })
}
/// The Finder file picker (several files at once).
pub fn pick_files() -> Vec<PathBuf> {
if !cfg!(target_os = "macos") {
return crate::platform::pick_files_linux(&crate::i18n::t("選擇要附加的檔案"));
}
let script = r#"function run() {
const app = Application.currentApplication(); app.includeStandardAdditions = true;
try { return app.chooseFile({withPrompt: '選擇要附加的檔案', multipleSelectionsAllowed: true}).map(f => f.toString()).join('\n'); } catch (e) { return ''; }
}"#;
std::process::Command::new("osascript")
.args(["-l", "JavaScript", "-e", script])
.output()
.map(|o| String::from_utf8_lossy(&o.stdout).lines().map(str::trim).filter(|l| !l.is_empty()).map(PathBuf::from).collect())
.unwrap_or_default()
}
pub fn human(b: u64) -> String {
crate::cloudbox::human(b)
}
/// A picture, sized like a screenshot, as base64 JPEG.
pub fn image_b64(path: &str) -> Option<String> {
// The viewer's decoder: every common format, SVG, and HEIC/AVIF through sips or ffmpeg.
let img = image::DynamicImage::ImageRgba8(crate::preview::decode_image(std::path::Path::new(path))?);
let img = img.to_rgb8();
let (w, h) = img.dimensions();
let (fw, fh, resize) = crate::computer::fit(w, h);
let img = if resize { image::imageops::resize(&img, fw, fh, image::imageops::FilterType::Triangle) } else { img };
crate::computer::encode_jpeg(&img).map(|j| base64::engine::general_purpose::STANDARD.encode(j))
}
fn clip(s: &str) -> String {
let n = s.chars().count();
if n <= MAX_TEXT_CHARS {
s.to_string()
} else {
format!("{}\n…(後面省略 {} 個字)", s.chars().take(MAX_TEXT_CHARS).collect::<String>(), n - MAX_TEXT_CHARS)
}
}
/// The text inside a document, when it can be read here.
pub fn read_text(path: &str, name: &str) -> Option<String> {
let n = name.to_lowercase();
let ext = n.rsplit('.').next().unwrap_or("");
// Word and web pages: read in AnyBot itself (same on every system).
if ext == "docx" {
if let Ok(md) = crate::preview::docx_markdown(std::path::Path::new(path)) {
return Some(md).filter(|t| !t.trim().is_empty());
}
}
if ext == "html" || ext == "htm" {
let bytes = std::fs::read(path).ok()?;
return Some(crate::preview::html_markdown(&String::from_utf8_lossy(&bytes))).filter(|t| !t.trim().is_empty());
}
if ["docx", "doc", "rtf", "rtfd", "odt", "webarchive", "pages"].contains(&ext) && cfg!(target_os = "macos") {
let out = std::process::Command::new("textutil").args(["-convert", "txt", "-stdout", path]).output().ok()?;
return out.status.success().then(|| String::from_utf8_lossy(&out.stdout).to_string()).filter(|t| !t.trim().is_empty());
}
if ext == "pdf" {
// pdftotext keeps the layout best; without it, read the text in AnyBot (pure Rust).
if let Some(t) = std::process::Command::new("pdftotext").env("PATH", crate::cloudbox::tool_path()).args(["-layout", path, "-"]).output().ok().filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).to_string()).filter(|t| !t.trim().is_empty()) {
return Some(t);
}
let bytes = std::fs::read(path).ok()?;
// NFKC: PDFs often carry CJK radicals ("⽂") for the ordinary characters ("文").
use unicode_normalization::UnicodeNormalization;
return std::panic::catch_unwind(|| pdf_extract::extract_text_from_mem(&bytes).ok()).ok().flatten().map(|t| t.nfkc().collect::<String>()).filter(|t| !t.trim().is_empty());
}
let bytes = std::fs::read(path).ok()?;
if bytes.len() > 2 * 1024 * 1024 || bytes.iter().take(8000).any(|b| *b == 0) {
return None;
}
String::from_utf8(bytes).ok()
}
/// What the model gets for a message's attachments: extra text and pictures.
pub fn for_model(atts: &[Attachment]) -> (String, Vec<String>) {
let mut text = String::new();
let mut images = vec![];
for a in atts {
let where_ = if a.on_box.is_empty() { format!("檔案存在 AnyBot 所在的電腦:{}", a.path) } else { format!("檔案已放進你自己的電腦:{}", a.on_box) };
if a.image {
match image_b64(&a.path) {
Some(b) => {
images.push(b);
text.push_str(&format!("\n\n[附件圖片「{}」,就是下面這張。{where_}]", a.name));
}
None => text.push_str(&format!("\n\n[附件圖片「{}」讀不出來。{where_}]", a.name)),
}
} else if let Some(t) = read_text(&a.path, &a.name) {
text.push_str(&format!("\n\n[附件「{}」({})。{where_}]\n```\n{}\n```", a.name, human(a.bytes), clip(&t)));
} else {
text.push_str(&format!("\n\n[附件「{}」({}),這裡讀不出內容,可以用工具處理。{where_}]", a.name, human(a.bytes)));
}
}
(text, images)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn text_and_images_reach_the_model() {
let dir = std::env::temp_dir().join(format!("anybot-attach-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let txt = dir.join("筆記.md");
std::fs::write(&txt, "# 標題\n內容 hello").unwrap();
let png = dir.join("圖.png");
image::RgbImage::from_pixel(2000, 1000, image::Rgb([10, 20, 30])).save(&png).unwrap();
let bin = dir.join("data.bin");
std::fs::write(&bin, [0u8, 1, 2, 0, 5]).unwrap();
let atts: Vec<Attachment> = [&txt, &png, &bin].iter().map(|p| store(99_999, p).unwrap()).collect();
assert!(atts[1].image && !atts[0].image);
let (text, images) = for_model(&atts);
assert!(text.contains("內容 hello") && text.contains("附件圖片「圖.png」") && text.contains("讀不出內容"), "{text}");
assert_eq!(images.len(), 1);
for a in &atts {
let _ = std::fs::remove_file(&a.path);
}
let _ = std::fs::remove_dir_all(&dir);
assert!(store(1, Path::new("/nonexistent/x")).is_err());
}
}